> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase38-session02-platform-foundation/spec.md).

# Session Specification

**Session ID**: `phase38-session02-platform-foundation` **Phase**: 38 - Claude OS v2.8.1 Semantic Port **Status**: Not Started **Created**: 2026-06-29

***

## 1. Session Overview

This session establishes the shared cross-platform helper layer required by the rest of Phase 38. Session 01 is complete, and Session 02 is the first incomplete Phase 38 session; Sessions 03, 04, and 05 all depend on one trustworthy source for platform flags, path normalization, app-data locations, CLI candidates, and virtual-environment binary paths.

The implementation must stay inside AI OS architecture. Upstream introduced a root-level `scripts/platform.ts`, but AI OS keeps shared Bun script utilities under `scripts/lib/`, so the primary target is `scripts/lib/platform.ts`. Current AI OS platform logic is split across `scripts/lib/scan-helpers.ts` and `scripts/lib/tool-detection.ts`; this session centralizes the duplicated decisions without changing public aggregate or scanner behavior.

The non-negotiable quality bar is branch evidence. A constants-only helper is not sufficient; tests must exercise mocked `win32`, `darwin`, and `linux` behavior, plus Windows `.cmd`/`.exe`, app-data, path separator, and venv `Scripts` cases that later sessions will rely on.

***

## 2. Objectives

1. Create `scripts/lib/platform.ts` with injectable platform helpers for OS flags, POSIX path normalization, app-data directories, CLI candidate names/directories, and venv binary paths.
2. Refactor `scripts/lib/scan-helpers.ts` and `scripts/lib/tool-detection.ts` so shared platform decisions no longer live in two independent places.
3. Add focused platform tests proving Windows, macOS, and Linux branches with realistic environment and home-directory inputs.
4. Preserve current POSIX scanner and CLI resolution behavior while adding Windows-ready helper coverage for later Phase 38 sessions.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase38-session01-tier-0-parity-fixes` - Provides the completed Tier 0 baseline and leaves Phase 38 ready for platform helper work.

### Required Tools Or Knowledge

* Bun 1.3.14 and Vitest for script test execution.
* Existing script helper conventions in `scripts/lib/`.
* Upstream platform concept from `/home/aiwithapex/projects/claudeos/claude-os-v2.8.1/scripts/platform.ts`.

### Environment Requirements

* Repository root is `/home/aiwithapex/projects/aios`.
* No Windows host is required for planning or implementation because faithful branch tests can inject `platform`, `home`, and environment maps.

***

## 4. Scope

### In Scope (MVP)

* Operators running AI OS scripts have one shared platform helper module for Windows, macOS, and Linux path decisions - implement `scripts/lib/platform.ts` with testable dependency injection.
* Aggregate and scanner helpers continue to use AI OS script conventions - move shared home, app support, path normalization, and OS flag logic out of `scripts/lib/scan-helpers.ts`.
* CLI detection consumers get centralized command-name and candidate-directory behavior - adapt `scripts/lib/tool-detection.ts` to the new helper while preserving current PATH-first ordering.
* Later Phase 38 sessions can resolve venv binaries and Windows app-data paths consistently - include `venvBin`, `appData`, `localAppData`, `appSupportDir`, CLI executable-name helpers, and CLI candidate-directory helpers.
* Script tests prove real branch behavior - add coverage under `scripts/lib/__tests__/platform.test.ts` and update scan/tool detection tests as needed.

### Out Of Scope (Deferred)

* Windows-aware aggregate app detection and Dream health fields - Reason: owned by Session 03 and depends on this helper.
* Windows Dream Task Scheduler install mechanics - Reason: owned by Session 04.
* Request-time Hermes, Graphify, Dream, and Vite bridge hardening - Reason: owned by Session 05.
* Voice broker and Intelligence portal work - Reason: owned by Sessions 08 and 09.
* Root-level `scripts/platform.ts` compatibility re-export - Reason: current AI OS code has no root-level import need; add only if implementation discovers a real import compatibility requirement.

***

## 5. Technical Approach

### Architecture

Create `scripts/lib/platform.ts` as the sole script-layer platform helper. The module should expose stable runtime constants for current-process consumers and pure/injectable helper functions for tests and future Windows harnesses. The helper should prefer explicit input objects for platform, home, and environment values where branch behavior matters, while still offering defaults backed by `node:os` and `process.env` for normal callers.

Refactor `scripts/lib/scan-helpers.ts` to import `HOME`, `IS_MACOS`, app-support helpers, path expansion, and redaction primitives from `scripts/lib/platform.ts` where the logic is platform-owned. Refactor `scripts/lib/tool-detection.ts` so executable-name expansion, CLI candidate directories, PATH delimiter handling, and Windows app-data/npm locations come from the platform helper instead of local private functions. Current tests in `scripts/lib/__tests__/scan-helpers.test.ts` and `scripts/lib/__tests__/tool-detection.test.ts` should continue to pass, with new assertions proving the centralized helper paths.

### Design Patterns

* Dependency-injected helpers: Allows Windows, macOS, and Linux branches to be tested from any host without mutating global `process.platform`.
* Local-first script utilities: Keeps shared helpers under `scripts/lib/`, matching AI OS conventions rather than copying upstream root layout.
* PATH-first resolution: Preserves the current tool-detection contract that explicit PATH entries beat fallback manager directories.
* Additive refactor: Centralizes platform logic without changing aggregate, scanner, or runtime bridge behavior ahead of their owning sessions.

***

## 6. Deliverables

### Files To Create

| File                                     | Purpose                                                                                                    | Est. Lines |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/platform.ts`                | Shared platform helpers for OS flags, path normalization, app-data, CLI candidates, and venv binary paths. | \~170      |
| `scripts/lib/__tests__/platform.test.ts` | Direct Windows, macOS, and Linux branch tests for the new helper contract.                                 | \~180      |

### Files To Modify

| File                                                                               | Changes                                                                                         | Est. Lines |
| ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/scan-helpers.ts`                                                      | Import shared platform primitives and remove duplicated OS/home/path logic.                     | \~35       |
| `scripts/lib/tool-detection.ts`                                                    | Use shared CLI name and directory helpers, including Windows app-data/npm and venv-aware paths. | \~60       |
| `scripts/lib/__tests__/scan-helpers.test.ts`                                       | Adjust imports or assertions after scan helper platform logic moves.                            | \~25       |
| `scripts/lib/__tests__/tool-detection.test.ts`                                     | Add regression assertions for Windows candidate names and app-data/npm candidate directories.   | \~70       |
| `.spec_system/specs/phase38-session02-platform-foundation/implementation-notes.md` | Record implementation evidence during the next command.                                         | \~220      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `scripts/lib/platform.ts` exports testable helpers for `IS_WIN`, `IS_MACOS`, `IS_LINUX`, `toPosix`, app-data paths, app-support paths, CLI executable names, CLI candidate directories, and venv bin paths.
* [ ] `scripts/lib/scan-helpers.ts` no longer owns independent platform/home/path logic that belongs in the shared helper.
* [ ] `scripts/lib/tool-detection.ts` no longer owns independent executable-name and candidate-directory platform logic that belongs in the shared helper.
* [ ] Current POSIX CLI resolution order remains PATH entries first, then known package-manager and system fallback directories.
* [ ] Windows helper behavior includes `.cmd`/`.exe` candidates, `%APPDATA%\npm`, `%LOCALAPPDATA%\Programs`, and venv `Scripts` paths.

### Testing Requirements

* [ ] Unit tests written and passing for Windows, macOS, and Linux helper branches.
* [ ] Existing `scan-helpers` and `tool-detection` tests still pass.
* [ ] Targeted script tests run with `bun run test -- scripts/lib/__tests__/platform.test.ts scripts/lib/__tests__/scan-helpers.test.ts scripts/lib/__tests__/tool-detection.test.ts`.
* [ ] Script typecheck run with `bun run typecheck:scripts`.

### Non-Functional Requirements

* [ ] Platform helper branch behavior is deterministic under injected inputs and does not require mutating process globals in tests.
* [ ] No new dependencies or lockfile changes are introduced.
* [ ] Helper outputs are bounded deterministic arrays with duplicate candidate paths removed while preserving priority order.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] No browser-visible or product-surface changes.

***

## 8. Implementation Notes

### Working Assumptions

* Root-level `scripts/platform.ts` is not needed for this session: repository evidence shows AI OS shared Bun script utilities live under `scripts/lib/`, the Phase 38 stub names `scripts/lib/platform.ts` as the AI OS target, and no current AI OS file imports `scripts/platform.ts`; planning can proceed with `scripts/lib/platform.ts` and no compatibility re-export.
* Faithful branch tests are sufficient for Windows/macOS/Linux planning: the session stub explicitly allows tests or faithful platform harnesses, and the current code already accepts injected `platform`, `home`, and `envPath` inputs in `resolveCliPath`; planning can proceed without a Windows host.

### Conflict Resolutions

* Upstream root helper path versus AI OS script structure: upstream uses `scripts/platform.ts`, while `.spec_system/CONVENTIONS.md` and the Session 02 stub require AI OS shared script code under `scripts/lib/`; the plan chooses `scripts/lib/platform.ts` and defers root re-export unless implementation discovers a concrete importer.

### Key Considerations

* This session is foundational for Sessions 03 through 05, so a leaky helper would spread into aggregate, scheduler, and bridge behavior.
* Current `scripts/lib/tool-detection.ts` already has good POSIX coverage and PATH-first tests; preserve that behavior while extracting platform-specific decisions.
* Current `scripts/lib/scan-helpers.ts` exports many scanner helpers; refactor only platform-owned primitives to keep the blast radius tight.

### Potential Challenges

* Windows paths are hard to test on a POSIX host: use injected platform, home, env maps, and `path.win32` where necessary to assert string output rather than host filesystem semantics.
* Existing tests mock `node:fs` in `scan-helpers.test.ts`: keep platform helpers pure enough that tests do not need brittle module reloads or global process mutation.
* Tool detection currently filters by actual executable files: keep filesystem tests focused on resolver order while direct platform tests cover candidate-list construction.

### Relevant Considerations

* \[P00] **Stack conventions**: Use Bun, TypeScript, and Vitest; keep script code under `scripts/lib/`.
* \[P01] **Old `claude-os-*` naming**: Do not introduce new global `claude-os` storage prefixes while adding platform helpers; preserve compatibility paths only where existing helpers already expose them.
* \[P05] **Script-only runtime boundary**: Keep auth, transport, scanner, and path helper behavior under `scripts/lib/`, not browser state.
* \[P11] **Scheduler state/log privacy boundary**: Plan platform helpers as data-only path utilities; do not add scheduler state or log exposure.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Platform branch drift between scanner and CLI helpers after extraction.
* Windows candidate paths or separators silently diverging from later aggregate and bridge needs.
* Fallback CLI search growing unbounded or changing priority order in ways that hide user-configured PATH entries.

***

## 9. Testing Strategy

### Unit Tests

* Add `scripts/lib/__tests__/platform.test.ts` for `toPosix`, app-data paths, app-support paths, CLI executable names, CLI candidate directories, duplicate removal, and `venvBin` across `win32`, `darwin`, and `linux`.
* Extend `scripts/lib/__tests__/tool-detection.test.ts` to prove `resolveCliPath` still prefers PATH, includes current manager fallback directories, and can resolve Windows extension candidates.
* Keep `scripts/lib/__tests__/scan-helpers.test.ts` green after imports move.

### Integration Tests

* Run the targeted Vitest command for platform, scan helper, and tool detection coverage.
* Run `bun run typecheck:scripts` to prove the shared helper contract compiles across script consumers.

### Runtime Verification

* Run `bun run test -- scripts/lib/__tests__/platform.test.ts scripts/lib/__tests__/scan-helpers.test.ts scripts/lib/__tests__/tool-detection.test.ts`.
* Run `bun run typecheck:scripts`.

### Edge Cases

* Windows drive-letter and backslash paths normalized through `toPosix`.
* Missing `APPDATA`, `LOCALAPPDATA`, and `XDG_CONFIG_HOME` fall back deterministically.
* Command names with existing extensions do not receive duplicate Windows extensions.
* Duplicate PATH or fallback entries are removed without changing first-match priority.
* POSIX venv binary paths remain `<root>/bin/<name>` while Windows uses `<root>/Scripts/<name>.exe`.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase38-session01-tier-0-parity-fixes`
* Depended by: `phase38-session03-aggregate-and-dream-health`, `phase38-session04-dream-scheduling-and-setup`, `phase38-session05-runtime-bridge-hardening`

***

## Next Steps

Run the `implement` workflow step to begin implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase38-session02-platform-foundation/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
