> 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-session07-dream-engine-product-integration/spec.md).

# Session Specification

**Session ID**: `phase38-session07-dream-engine-product-integration` **Phase**: 38 - Claude OS v2.8.1 Semantic Port **Status**: Not Started **Created**: 2026-06-30

***

## 1. Session Overview

This session adds durable Dream engine selection and a health-aware Dream dashboard path without replacing AI OS Dream execution. It is next because the deterministic project analysis shows Phase 38 Sessions 01 through 06 complete, no active session, and Session 07 as the first unfinished candidate.

The work ports the upstream Dream engine picker into AI OS product surfaces: setup gets a distinct engine step after Dream cadence, the home dashboard gets engine readiness and recovery copy, and dashboard generation continues through the existing `/__run_dream` path. The scheduler, setup, and dashboard must read the same selected engine from AI OS-owned config.

Upstream `scripts/run-dream.ts` remains superseded. AI OS keeps `scripts/lib/dream/**`, `scripts/scheduler-runner.ts`, and `scripts/dashboard-dream-run.ts` as the execution source while auditing upstream engine resolution for missing readiness, auto-selection, and prompt-assembly nuance.

***

## 2. Objectives

1. Add an AI OS Dream engine registry and durable config layer that can read legacy Claude OS config but writes AI OS-owned private config.
2. Expose `/__dream_engines` and `/__set_dream_engine` through guarded local middleware with schema-validated input and safe error responses.
3. Add setup and home dashboard product controls for selecting a ready Dream engine, seeing no-ready-engine recovery copy, and triggering a real Dream generation.
4. Prove scheduled runs, dashboard runs, and setup use the same selected engine through focused script, hook, component, and route tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase38-session03-aggregate-and-dream-health` - Provides Dream health metadata, `dream.healthStatus`, and `dream.fixHint` in live data.
* [x] `phase38-session04-dream-scheduling-and-setup` - Provides Dream scheduler and setup readiness behavior this session extends.
* [x] `phase38-session05-runtime-bridge-hardening` - Provides local control-plane loopback, token, Host-header, and path-safety guardrails.
* [x] `phase38-session06-policy-docs-and-catalogs` - Records current-state docs and prevents overclaiming Session 07, 08, or 09 behavior.

### Required Tools Or Knowledge

* Bun 1.3.14, Vitest, React Testing Library, Vite middleware conventions, and `rg`.
* Upstream reference files under `/home/aiwithapex/projects/claudeos/claude-os-v2.8.1/`.
* Current AI OS Dream modules, setup component system, local control-plane guards, and LiveData Dream health fields.

### Environment Requirements

* Repository root is `/home/aiwithapex/projects/aios`.
* No provider keys, bearer headers, token-shaped strings, raw local private paths, prompts, transcripts, or generated private Dream output may enter browser state, logs, docs, fixtures, or tests.
* Local writes must remain loopback and token gated, and public demo mode must remain read-only.

***

## 4. Scope

### In Scope (MVP)

* Local operators can choose a Dream engine in setup and on the home dashboard - persist the selection through AI OS private config and mirror browser draft state only for setup continuity.
* Local operators can see engine readiness and Dream health before generating - combine engine status with `dream.healthStatus` and `dream.fixHint`.
* Local operators can trigger Dream from the dashboard - keep the request on `/__run_dream`, prevent duplicate triggers while in flight, refresh live data only when output is written, and render the produced review.
* Scheduler and dashboard runs use one engine source of truth - read the selected engine inside AI OS Dream execution rather than installing a separate upstream runner.
* Session 10 can reconcile upstream `scripts/run-dream.ts` - record the audited upstream engine order, prompt handling, and superseded AI OS replacement files.

### Out Of Scope (Deferred)

* Copying upstream `scripts/run-dream.ts` or raw `claude-os.dream.engine` storage - Reason: Phase 38 policy keeps AI OS Dream runners and AI OS config paths as the source of truth.
* Implementing the OpenAI Realtime voice broker - Reason: Session 08 owns voice broker behavior, provider token minting, and `OPENAI_BASE_URL` voice policy.
* Implementing the Hermes Intelligence portal - Reason: Session 09 owns portal, visualizer, voice loop, and `/__hermes_chat` integration.
* Adding a disconnected debug route or demo-only Dream UI - Reason: this session must ship product-facing setup and dashboard controls.

***

## 5. Technical Approach

### Architecture

Create a narrow Dream engine config owner under `scripts/lib/dream/`. The module should define allowed engine ids, readiness states, safe labels, default auto-selection, AI OS private config read/write behavior, and legacy read compatibility for `~/.claude-os/config.json`. Writes should target the AI OS private root, preserve existing config fields, and reject malformed engine ids.

Keep Dream execution centralized. `executeDream()` should resolve the selected engine at run time, adapt it into the existing AI runtime provider config where supported, and preserve the current activation gates, locks, material readiness, output validation, continuity merge, fallback, timeout, and write paths. Unsupported upstream-only engines must be represented as unavailable with recovery copy instead of silently falling back to another provider.

Expose two local middleware routes in `vite.config.ts`: a safe read endpoint for engine readiness and a token-gated write endpoint for selected engine updates. The home dashboard and setup step should use small client hooks for fetch, write, loading, empty, error, offline, and public-demo states. Product surfaces must show actionable recovery copy and never surface raw env values or private config paths.

### Design Patterns

* Local control-plane guardrails: reuse loopback, Host-header, token, and safe JSON response patterns already used by `/__run_dream`.
* Config-owner module: centralize engine parsing, legacy migration, and readiness projection before touching UI components.
* Product-surface extension: extend `DreamHero`, `DreamSourcesStrip`, setup modal, and home route patterns instead of introducing a parallel Dream page.
* Browser-safe projection: expose engine ids, labels, readiness states, and recovery messages only; never expose secrets or raw private paths.

***

## 6. Deliverables

### Files To Create

| File                                                          | Purpose                                                                                                        | Est. Lines |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/dream/engine-config.ts`                          | Dream engine ids, readiness, AI OS private config read/write, legacy read compatibility, and safe projections. | \~220      |
| `scripts/lib/dream/engine-endpoints.ts`                       | Pure request/response helpers for Dream engine read/write middleware.                                          | \~120      |
| `src/lib/use-dream-engines.ts`                                | Client hook for engine readiness fetch, selection write, loading, error, offline, and public-demo behavior.    | \~160      |
| `src/components/setup/step-dream-engine.tsx`                  | Setup step after Dream cadence with engine readiness selection and recovery states.                            | \~220      |
| `src/components/home/dream-engine-control.tsx`                | Dashboard engine switcher plus health-aware Connect/Generate state.                                            | \~220      |
| `scripts/lib/__tests__/dream-engine-config.test.ts`           | Script tests for config parsing, legacy read, write safety, auto-selection, and readiness projection.          | \~180      |
| `scripts/lib/__tests__/dream-engine-endpoints.test.ts`        | Endpoint-helper tests for read payloads, token-gated writes, invalid input, and safe errors.                   | \~160      |
| `src/lib/__tests__/use-dream-engines.test.tsx`                | Hook tests for fetch, save, public demo, failed token, failed write, and offline states.                       | \~180      |
| `src/components/home/__tests__/dream-engine-control.test.tsx` | Dashboard component tests for health states, engine switching, and generate recovery copy.                     | \~180      |

### Files To Modify

| File                                                                                            | Changes                                                                                                          | Est. Lines |
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/dream/contracts.ts`                                                                | Add Dream engine ids, readiness status, and safe projection types.                                               | \~60       |
| `scripts/lib/dream/index.ts`                                                                    | Export Dream engine config and endpoint helpers.                                                                 | \~15       |
| `scripts/lib/dream/execution.ts`                                                                | Resolve selected engine at run time and adapt supported engines into existing AI runtime execution.              | \~80       |
| `scripts/dashboard-dream-run.ts`                                                                | Preserve selected-engine behavior for dashboard-triggered runs and report safe status text.                      | \~30       |
| `scripts/scheduler-runner.ts`                                                                   | Ensure scheduled Dream runs use the same selected engine path.                                                   | \~30       |
| `vite.config.ts`                                                                                | Add guarded `/__dream_engines` and `/__set_dream_engine` middleware and keep `/__run_dream` on the AI OS runner. | \~140      |
| `src/components/setup/constants.ts`                                                             | Insert the Dream engine step after Dream cadence and update step indices.                                        | \~25       |
| `src/components/setup/setup-modal.tsx`                                                          | Render the new Dream engine step and make it skippable only when no ready engine exists.                         | \~60       |
| `src/components/setup/types.ts`                                                                 | Add optional Dream engine config fields with safe browser shape.                                                 | \~30       |
| `src/components/setup/config-helpers.ts`                                                        | Hydrate and persist setup draft/install config with Dream engine selection.                                      | \~50       |
| `src/lib/use-dream-run.ts`                                                                      | Accept selected engine context, preserve duplicate-trigger prevention, and map endpoint errors to recovery copy. | \~60       |
| `src/lib/home-transforms.ts`                                                                    | Project Dream health and engine-control props from LiveData safely.                                              | \~60       |
| `src/lib/use-home-data.ts`                                                                      | Return Dream health data needed by dashboard controls.                                                           | \~25       |
| `src/routes/index.tsx`                                                                          | Mount the Dream engine control next to the existing Dream hero and source strip.                                 | \~35       |
| `src/components/home/dream-hero.tsx`                                                            | Render health-aware empty and generated-review states without scheduler-command-only copy.                       | \~60       |
| `src/routes/__tests__/setup-modal.test.tsx`                                                     | Cover step order, engine readiness selection, persistence, and save failure.                                     | \~120      |
| `src/components/home/__tests__/dream-hero.test.tsx`                                             | Cover no-ready-engine, stale, silent-failure, and generated-review rendering.                                    | \~80       |
| `src/lib/__tests__/use-dream-run.test.tsx`                                                      | Cover selected-engine runs, duplicate-trigger prevention, and failure mapping.                                   | \~80       |
| `.spec_system/specs/phase38-session07-dream-engine-product-integration/implementation-notes.md` | Record upstream supersession audit and verification evidence.                                                    | \~160      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Setup displays a distinct Dream engine step immediately after Dream cadence.
* [ ] Setup and dashboard read real engine readiness from `/__dream_engines`.
* [ ] A selected ready engine persists through AI OS private config and is read by setup, dashboard, scheduled Dream runs, and dashboard Dream runs.
* [ ] Dashboard can trigger a real Dream generation through `/__run_dream`, refresh live data after a written output, and render the produced review.
* [ ] No-ready-engine, token/write failure, stale, silent-failure, generation failure, concurrent-run, and public-demo states show actionable product copy.
* [ ] Upstream `scripts/run-dream.ts` is recorded as superseded with AI OS replacement files named by absolute path.

### Testing Requirements

* [ ] Unit tests cover engine config parsing, legacy read compatibility, write safety, invalid inputs, and auto-selection.
* [ ] Endpoint-helper tests cover safe read payloads, token-gated writes, bad tokens, invalid engine ids, and sanitized errors.
* [ ] Hook and component tests cover loading, empty, error, offline, public-demo, selected-engine, and generated-review states.
* [ ] Setup route tests cover step order, selection persistence, save failure, and localStorage draft continuity.
* [ ] Dream execution tests prove selected engine config is used by scheduled and dashboard runs without duplicating upstream runners.

### Non-Functional Requirements

* [ ] Local writes remain loopback and token gated.
* [ ] Browser-facing payloads contain no secrets, raw private paths, prompts, transcripts, auth JSON, bearer headers, or token-shaped strings.
* [ ] Unsupported upstream-only engines are explicit unavailable states, not silent provider fallbacks.
* [ ] Setup and dashboard copy stays product-facing; diagnostics remain in tests, logs, and implementation notes.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Product surfaces contain product-facing copy only.

***

## 8. Implementation Notes

### Working Assumptions

* Dream engine selection should be an AI OS private config layer that can read legacy Claude OS config but writes AI OS-owned data. Repo evidence: Phase 38 resolved policy says browser setup persists through `ai-os-config` with legacy migrations, private Dream files use `~/.ai-os` primary with `~/.claude-os` read compatibility, and current code has no Dream-specific engine owner beyond env-backed AI runtime config. Planning can proceed because a narrow `scripts/lib/dream/engine-config.ts` owner fits the existing Dream module layout and avoids copying upstream storage.
* Session 07 should be a single-repo session. Repo evidence: the analysis script reports no monorepo detection and no active package. Planning can proceed with repo-root-relative paths.

### Key Considerations

* Keep `scripts/run-dream.ts` superseded; port only missing engine/readiness nuance into AI OS modules.
* Preserve the existing `/__run_dream` execution path so dashboard generation and scheduled generation cannot drift.
* Use public-demo read-only behavior from existing setup and Dream controls.
* Treat no ready engines as a normal empty state with recovery copy, not as an implementation stop.

### Potential Challenges

* Engine labels can imply unsupported providers: keep unavailable upstream-only engines explicit and prevent selection until an AI OS executor exists.
* Browser setup and private scheduler config can drift: make the server config owner authoritative and use browser storage only as setup draft continuity.
* Dream health and engine readiness can produce conflicting copy: define one priority order in the dashboard control and cover it in component tests.
* Endpoint failures can expose private details: sanitize all errors before JSON responses and before client copy.

### Relevant Considerations

* \[P01] **Old `claude-os-*` naming**: Preserve legacy read compatibility but write new Dream engine config through AI OS paths.
* \[P04] **Hermes bridge guardrails must stay intact**: Keep loopback, token, Host-header, body-size, and path safety protections on all local control plane changes.
* \[P11] **Scheduler state/log privacy boundary**: Expose only engine labels, readiness states, status, durations, warnings, and freshness metadata.
* \[P21] **Claude OAuth material stays script-only**: Provider credentials and bearer headers must not enter browser state, generated data, or logs.
* \[P00] **Stack conventions**: Use Bun, Vite 8, TanStack Start, React 19, Radix UI patterns, and existing component conventions.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Setup, dashboard, and scheduler read different selected engines.
* A user can trigger duplicate Dream runs while one is already in flight.
* Engine readiness or provider errors leak private paths, tokens, or raw provider details into browser-visible copy.
* Unsupported upstream-only engines silently fall back to another provider.

***

## 9. Testing Strategy

### Unit Tests

* `scripts/lib/__tests__/dream-engine-config.test.ts` for config parsing, legacy read compatibility, path containment, write preservation, auto-selection, and safe projections.
* `scripts/lib/__tests__/dream-engine-endpoints.test.ts` for safe JSON payloads, token-gated writes, invalid engine ids, and sanitized error mapping.
* `scripts/lib/__tests__/dream-execution.test.ts` for selected engine runtime resolution and no silent fallback to unsupported engines.

### Integration Tests

* `src/routes/__tests__/setup-modal.test.tsx` for setup step order, selected engine persistence, skipped/no-ready state, and save failure.
* `src/lib/__tests__/use-dream-engines.test.tsx` and `src/lib/__tests__/use-dream-run.test.tsx` for hook fetch/write/run flows.
* `src/components/home/__tests__/dream-engine-control.test.tsx` and `src/components/home/__tests__/dream-hero.test.tsx` for dashboard health, empty, error, and generated-review states.

### Runtime Verification

* Run `bun run test -- scripts/lib/__tests__/dream-engine-config.test.ts scripts/lib/__tests__/dream-engine-endpoints.test.ts scripts/lib/__tests__/dream-execution.test.ts`.
* Run `bun run test -- src/routes/__tests__/setup-modal.test.tsx src/lib/__tests__/use-dream-engines.test.tsx src/lib/__tests__/use-dream-run.test.tsx src/components/home/__tests__/dream-engine-control.test.tsx src/components/home/__tests__/dream-hero.test.tsx`.
* Run `bun run lint`, `bun run typecheck`, and `bun run typecheck:scripts`.
* Manually verify the home dashboard and setup modal in local dev when credentials are available, or record exact credential absence in implementation notes.

### Edge Cases

* Legacy config contains an unknown, malformed, or unsupported engine id.
* AI OS private config is missing, malformed, or unwritable.
* No engine is ready, or only an unavailable upstream-only engine is detected.
* Token lookup fails before `/__set_dream_engine` or `/__run_dream`.
* `/__run_dream` returns skipped, concurrent-run, timeout, provider failure, or written-output success.
* Public demo mode attempts to open setup or run Dream.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase38-session03-aggregate-and-dream-health`, `phase38-session04-dream-scheduling-and-setup`, `phase38-session05-runtime-bridge-hardening`, `phase38-session06-policy-docs-and-catalogs`.
* Depended by: `phase38-session08-voice-broker`, `phase38-session09-intelligence-portal`, `phase38-session10-hunk-reconciliation-and-release-gate`.

***

## 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-session07-dream-engine-product-integration/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.
