Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
docs: replan — completed [per-panel-scene-image-progress-in-the-pipeline-ui], [legacy-series-canon-orphan-universe-leak-on-throw]; added 4 new items; flagged 1 drift
[._.]/ Adam Eivy5856ffad8820
diff --git a/PLAN.md b/PLAN.mdindex 270bd82ecd..a5a7ea257f 100644--- a/PLAN.md+++ b/PLAN.md@@ -2,55 +2,23 @@For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changelog/](./.changelog/) and `git log`.-----## Next Up-_Nothing currently parked — pick the next item from the Backlog._--## Backlog--### Code quality / dedup (from `/simplify` passes)--### Better-audit residue--### Pipeline — deferred-+- [ ] [agent-spawn-widen-try-finally-guard] **Widen the `spawningTasks` guard in `agentLifecycle.js` to cover the whole spawn path.** `server/services/agentLifecycle.js:~165` adds `task.id` to `spawningTasks` but the `try/finally` only wraps a narrow window; an uncaught throw inside `buildAgentPrompt`, `writeFile('prompt.txt')`, `createAgentRun`, or `registerAgent` (lines ~165–525) leaks the guard forever, permanently blocking re-spawns of that task id until process restart. Four `it.skip('TODO(plan.md backlog): …')` tests at `agentLifecycle.test.js:440-490` already pin the regression and flip green on fix. Single-user system means a stuck guard is silently un-recoverable.- [ ] [backport-pre-023-migrations-to-_lib] **Back-port pre-023 prompt-replace migrations onto `scripts/migrations/_lib.js`.** 003 / 004 / 005 / 006 / 010 / 013 / 019 all clone the inline `applyMigration` + per-file scan + customized-skip warning pattern that `_lib.js` now centralizes. Wrap any `OLD_SHIPPED_MD5: string` entries (003 / 004 / 006) into single-element arrays to match the `accepted[filename]: string[]` shape. Drop ~70 LOC per migration; nothing changes behaviorally so the only risk is mis-typed hashes — review each diff alongside a re-run of its test against the `_testHelpers.js` `runPromptMigrationTests`. Settled-history migrations have a higher rewrite-bar than active code, so a separate PR with focused review is appropriate. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.-- [ ] [per-panel-scene-image-progress-in-the-pipeline-ui] **Per-panel/scene image progress in the Pipeline UI.** ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview.- [ ] [pipeline-list-strip-route-contract-tests] **Lock the runHistory-strip decision at the HTTP boundary.** `server/services/pipeline/issues.js`'s `listIssues` / `listRecentIssues` take `withHistory` (default `true`); the strip choice now lives in `server/routes/pipeline.js`. Service-layer tests cover both shapes, but no route test asserts the response. Add Supertest coverage to `server/routes/pipeline.test.js`: (1) `GET /api/pipeline/series/:id/issues` (paginated + non-paginated) seeds an issue with persisted runHistory and asserts the response body's `stages.*.runHistory` is `[]`; (2) for `GET /api/pipeline/issues/recent` — whose route projection drops `stages` entirely — spy on `issuesSvc.listRecentIssues` and assert it's called with `{ withHistory: false }`. Caught by codex review iter 2 on PR #411 as LOW non-blocking; deferred to keep that PR scoped to the perf change.--### CODEX 5.5 review residue (deferred from product/engineering review, 2026-04-25)--The 2026-04-25 CODEX 5.5 review's concrete bugs (Brain Feeds nav, Time Capsule nav, `/cos/scripts` dead target, `/ask` full-height, client lint, route/nav contract tests) are all shipped. These are the strategic items left open from that review.--**Engineering / performance**--- [ ] [codex5-polling-consolidation] **[P2][PERF]** Standardize polling on `useAutoRefetch` + sockets + visibility pause. Brain, Digital Twin, CoS, Links, Processes, Browser, CyberCity, and several widgets still spin local `setInterval`s. Pick a single hook (`client/src/hooks/useAutoRefetch.js` if it exists, otherwise extract one), add `document.visibilityState === 'hidden'` short-circuit, and migrate domains that already have Socket.IO event streams to event-driven refetch.+- [ ] [codex5-polling-consolidation] **[P2][PERF]** Migrate remaining `setInterval` callers to `useAutoRefetch`. The shared hook at `client/src/hooks/useAutoRefetch.js` exists; 20+ pages/components still spin local `setInterval`s — ChiefOfStaff, Brain, DigitalTwin, Loops, Browser, CyberCity, ImageGen, Ambient, AgentsPage, calendar, meatspace, city tabs. Migrate each to `useAutoRefetch` (which already provides the `document.visibilityState === 'hidden'` short-circuit); for domains with a Socket.IO event stream, switch to event-driven refetch instead of polling.- [ ] [codex5-client-error-reporter] **[P2][OBSERVABILITY]** Funnel client errors into Review Hub. `client/src/main.jsx`'s `window.onerror` + `unhandledrejection` listeners only `console.log` today. Add `POST /api/client-errors` with redaction (drop tokens / long payloads) + rate-limit (~1/sec, drop duplicates by message+stack hash). Surface grouped client errors in the Review Hub feed; optionally raise a CoS task at a configurable threshold.--**Product UX — concrete, medium scope**--- [ ] [codex5-dashboard-intent-layouts] **[P2][DASHBOARD]** Intent-named layouts + morning default + widget suggestions. Rename built-in layouts to user-intent (`Morning Review`, `Deep Work`, `Ops`, `Health`, `Agent Watch`); update `server/services/dashboardLayouts.js` seeded built-ins. Add a "make this my morning default" toggle that activates a layout in a configured time window. Add a "widget suggestion" hint: when a layout omits a widget whose data source is populated (e.g. layout has no calendar widget but calendar is connected), surface an inline "Add Calendar?" affordance.+- [ ] [codex5-dashboard-intent-layouts] **[P2][DASHBOARD]** Finish intent-named layouts + morning default + widget suggestions. `server/services/dashboardLayouts.js` seeds `morning-review` and `ops` already; still missing `Deep Work`, `Health`, `Agent Watch`. Add the three remaining seeded layouts, a "make this my morning default" toggle that activates a layout in a configured time window, and a "widget suggestion" hint: when a layout omits a widget whose data source is populated (e.g. layout has no calendar widget but calendar is connected), surface an inline "Add Calendar?" affordance.- [ ] [codex5-onboarding-capability-map] **[P2][ONBOARDING]** Capability map of connected systems. One page showing each integration's status: Providers (per-provider configured/available/throttled), Calendar, Brain/memory embeddings, Voice (mic + TTS), Tailscale + HTTPS, Genome/health imports, Telegram/messages, App registry/PM2. Each row links to the relevant settings page. Doubles as a setup checklist and a runtime health overview.--### Deferred from better/2026-05-19--- [ ] [legacy-series-canon-orphan-universe-leak-on-throw] **[LOW][SHARING]** `server/services/pipeline/migrateSeriesCanon.js#applyLegacySeriesCanonToUniverse` — when the helper hits a transient I/O failure between `createUniverse(...)` and `updateUniverse(universeId, patch)` (or any subsequent write), the orphan universe is persisted on disk but the helper throws. On retry the manifest reprocesses, sees `s.universeId` still unset (bucket record isn't mutated), and mints a SECOND auto-migrated universe. Canon data isn't lost (the manifest stays retryable via `legacyCanonPendingFailures`), but empty `"<series-name> (auto-migrated)"` universes accumulate per retry pass. Fix needs a deterministic universe id derived from the importing series (e.g. `uni-import-<seriesHash>` or persisting the chosen id back to the bucket sidecar) so the second creation hits `ERR_DUPLICATE` and the helper reuses the existing universe. Deferred from `[med-sharing-server-services-sharing-version-js]` because the fix touches the universe identity model — out of scope for the importer-side migration salvage PR. Surfaced 2026-05-20 in codex review iter 4.--- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.--### Voice agent-+- [ ] [migrate-two-remaining-local-formatters] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.- [ ] [wire-proactive-cos-speech-to-real-triggers] **Wire proactive CoS speech to real triggers.** Plumbing landed (`POST /api/voice/speak` + `voice:speak` socket event); hook to high-severity `errorEvents`, `task:ready`, and `notificationEvents` with per-source rate-limits.- [ ] [optimize-voice-ui-index-text-payload-lazy-only-run] **Optimize `voice:ui:index` text payload.** Lazy: only run `extractVisibleText` when server requests via `voice:ui:read-request`. Keep current behavior as fallback.- [ ] [voice-agent-explicit-long-term-memory-routing-on] **Voice agent — explicit long-term memory routing.** On retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search`.--### Image / Video Gen UI-- [ ] [flux2-multi-reference-python-runner] **FLUX.2 multi-reference Python runner.** The UI + server contract for multi-reference editing shipped 2026-05-17 (slug `multi-reference-image-editing-for-flux-2-ui`); the Python runner (`scripts/flux2_macos.py`) currently ignores the `--reference-images`/`--reference-strengths` args that `local.js` now passes. Wire diffusers' multi-reference API in the runner and swap `server/lib/mediaModels.js#flux2-klein-9b` `tokenizerRepo` to `FLUX.2-klein-9B-kv` (gated repo — requires the user to accept the license on HF). Validate end-to-end with 2–4 uploaded refs.-----+- [ ] [voice-cos-tool-expansion-calendar-today-calendar] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (existing Google Calendar MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (pick API: OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js`).+- [ ] [voice-agent-vision-fallback-ui-describe-visually] **Voice agent vision fallback** — `ui_describe_visually`: screenshot tab and send to a vision-capable model so "what's on this chart?" works on CyberCity / graph views.+- [ ] [apple-health-integration-live-sync] **Apple Health integration for MeatSpace.** iOS live sync (HealthKit Shortcut → `POST /api/meatspace/apple-health` endpoint) plus a bulk historical import path for an exported `export.xml`. Wire into existing MeatSpace tabs so steps / sleep / heart rate / VO2 max / resting HR show alongside the alcohol / blood / body / epigenetic tracks already shipped. GOALS.md flags this as a documented Secondary Goal ("Apple Health integration planned") but no implementation tracking existed until this entry.## Deferred Architecture (human-led planning)@@ -95,11 +63,6 @@ Items here need a research / design pass, an explicit decision, or a preconditio- [ ] [ai-assisted-panel-scene-prompt-generation-reserve] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` for a future "turn script fragment into N image-gen prompts" button.- [ ] [whole-episode-audio-generation-strategy-stop] **Whole-episode audio generation strategy.** Stop relying on per-clip audio; drive audio gen from episode-level prose/script arc. Generator candidates: Suno (commercial, duration control), MusicGen-MLX (local, bounded ~30s), AudioLDM2. New `audioMode: 'per-clip' | 'silent' | 'generated' | 'uploaded-track'`. Treat as a new sub-brainstorm when picked up — investigation first.-### Voice / agents--- [ ] [voice-cos-tool-expansion-calendar-today-calendar] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (existing Google Calendar MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (pick API: OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js`).-- [ ] [voice-agent-vision-fallback-ui-describe-visually] **Voice agent vision fallback** — `ui_describe_visually`: screenshot tab and send to a vision-capable model so "what's on this chart?" works on CyberCity / graph views.-### Large product / UX redesigns- [ ] [writers-room-phases-4-5-phase-4-synced-prose] **Writers Room Phases 4–5.** Phase 4 synced prose/script/media review; Phase 5 realtime CD feedback. Builds on the unified bible/scene model. See [writers-room.md](./docs/features/writers-room.md).@@ -107,11 +70,13 @@ Items here need a research / design pass, an explicit decision, or a preconditio- [ ] [m50-p9-cos-automation-rules-automated-email] **M50 P9 — CoS Automation & Rules.** Automated email classification, rule-based pre-filtering, email-to-task pipeline.- [ ] [m50-p10-auto-send-with-ai-review-gate-per-account] **M50 P10 — Auto-Send with AI Review Gate.** Per-account/per-recipient trust level + dual-LLM review (drafter + reviewer). Auto-send only when both approve or trust ≥ 0.9. See [messages-security.md](./docs/features/messages-security.md).- [ ] [m34-p5-p7-digital-twin-multi-modal-capture-voice] **M34 P5-P7 — Digital Twin.** Multi-modal capture (voice/video/image identity sources), advanced testing, personas. Ties to GOALS.md "Multi-Modal Identity Capture".+- [ ] [cross-domain-insights-engine-m42-p5] **M42 P5 — Cross-Domain Insights Engine.** Connect genome ↔ health ↔ taste ↔ identity ↔ creative output into narrative insights surfaced in Brain. Needs a design pass on (a) which signal pairs are worth correlating, (b) where insights land (new Insights surface vs. Brain daily/weekly digest), (c) how the user dismisses / accepts an insight, and (d) whether the LLM gets a structured "facts table" or raw stage data. GOALS.md flags this as the next milestone for "Digital Identity Modeling" but no design has been written.- [ ] [codex5-unified-review-queue] **[P1][PRODUCT]** Cross-domain Review Queue (the "inbox zero" for PortOS). One page (`/review` or `/inbox`) that collects: Brain inbox items needing classification, Ask answers ready for promotion, CoS completed tasks pending approval, Message drafts awaiting send, Health anomalies pending acknowledgement, and failed syncs / imports / backups. Each row has accept / dismiss / drill-down. Build the surface aggregator first, then opt each producer into it.- [ ] [codex5-health-provenance-chips] **[P1][HEALTH][TRUST]** Extend Ask's source-chip pattern to MeatSpace / genome / death clock / longevity views. Each insight tags itself as `data-backed | inferred | experimental | speculative` with a "what would change this?" explainer and a clinician-export view for blood + lifestyle data. Pairs with `[codex5-decision-provenance-everywhere]`.- [ ] [codex5-autonomy-guardrails] **[P1][AUTONOMY]** Per-domain autonomy levels + dry-run + budgets + while-away briefing. Today CoS has a single global autonomy posture. Split into per-domain knobs (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) each with `off | dry-run | execute`. Add spending / time / token budgets per domain. Add a "what did agents do while I was away?" digest pulling from the existing CoS / agent run logs into a daily briefing card.- [ ] [codex5-mobile-task-flows] **[P2][MOBILE]** Five phone-native flows: (1) system health + one-tap restart of an app, (2) one-tap voice/text Brain capture, (3) "what should I do now?" Ask, (4) approve / reject a CoS result from a notification, (5) log a health/lifestyle event in ≤10 seconds. Each should be reachable in ≤2 taps from a Tailscale-launched mobile session.- [ ] [codex5-operating-loop-dashboard] **[P0][PRODUCT]** Top-level daily command center / operating loop. Replace the homepage-equivalent dashboard with 3–5 prioritized cards: Critical System Issues, Today's Calendar Commitments, Active Agent Work, Goal Next Action, Health/Recovery Signal. Each card gets one primary action + one drill-down. Add an explicit day-mode selector (`Focus | Ops | Health | Review | Autonomous`) that re-ranks the cards. Pulls signals from Digital Twin, chronotype, calendar, goals, and CoS. Treat as a multi-PR design spike — investigation + mockups first.+ > ⚠️ DRIFT: A naive "replace dashboard" execution would silently drop the **Network Exposure** widget (`bc716743` feat([codex5-network-exposure-ui])) and regress per-widget lazy-loading + stale-chunk recovery (`eaab7857` feat([codex5-bundle-lazy-routes])). Reword to "evolve the dashboard composition layer" so the widget registry + lazy infrastructure is explicitly preserved.- [ ] [codex5-sidebar-collapse-ia] **[P1][IA]** Collapse sidebar to 8–10 top-level domains + Pinned + Recent. Today the sidebar carries deep nested tabs at the same level as top-level domains; review recommends `Home, Ask, Apps, CoS, Brain, Calendar, Goals, Health, Dev Tools, Settings` only at the top level with deep tabs pushed into each page's local tab bar and Cmd+K. Add Pinned + Recent sections driven by the user's actual working set. Touch every consumer of `Layout.jsx`'s nav tree; expect alphabetical ordering convention to survive.- [ ] [codex5-visual-modes] **[P2][DESIGN]** Product-specific visual modes: `Ops` (dense terminal-like, minimal animation), `Focus` (quiet, spacious, only next actions), `Health` (warmer, less cyber, more explanation), `Review` (document-like, optimized for reading + decisions). Tied to the day-mode selector from `[codex5-operating-loop-dashboard]`. Extend the existing Tailwind token system rather than introducing a parallel theming layer.- [ ] [codex5-decision-provenance-everywhere] **[P2][DESIGN]** Decision/provenance pattern across CoS, Insights, Health, Goals, Dashboard widgets. Each AI-generated or rule-driven surface answers: "Why am I seeing this?", "What data backs this?", "What changed?", "What can I do next?" Reuse the Ask source-chip component. Pairs with `[codex5-health-provenance-chips]`.@@ -140,4 +105,5 @@ Items here need a research / design pass, an explicit decision, or a preconditio- **Inline Code Review Annotations** — one-click fix from self-improvement findings.- **Major Dependency Upgrades** — React 19, Zod 4, PM2 6, Vite 8.- **Workflow tab Phase 2** — drag-and-drop ordering of stages, custom user-defined stages, per-app workflow overrides.+- **Inspiration & Mood Board Canvas** — dedicated mood-board surface for collecting visual + textual references that feed into Universe Builder, Writers Room, and Creative Director (distinct from raw Media History). Items can be pinned from any media surface; canvas surfaces ref images when starting a new universe / scene / treatment. Documented as a Secondary Goal in GOALS.md but had no tracking.- **Generative regen path for SynthID defeat (image cleaner) — research/backlog, hardware-gated.** Current `cleanImageBuffer` (`server/lib/imageClean.js`) only strips the C2PA `caBX` chunk + runs `median(3).sharpen()` — SynthID survives by design (verified 2026-05-20 against codex output: post-clean image reads as `C2PA removed, SynthID detected` on openai.com/synthid). The detector heatmap that OpenAI's verifier renders is a one-way correlation map `∫ image · template`, not the watermark template itself — so deterministic image-processing approaches (subtracting the heatmap, overlaying a second "PortOS SynthID," frequency-band cancellation) can't work without the secret key. The only honest defeat path is to round-trip pixels through a generative model: short-step img2img (low step count + low–moderate denoise, ~0.35–0.5) on a local FLUX runner so composition holds but the per-pixel watermark signal is overwritten by fresh sampling. **Scope narrowed (2026-05-20):** post-hoc, history-only. Surface as a second button next to "Clean (aggressive)" on the image-settings/lightbox modal — never auto-applied, never wired into the active gen flow, no per-render checkbox. Each run is ~5–15s on local mflux and GPU/unified-memory heavy; wants its own queue lane. Sidecar records `regenerated: true, regenSteps: N, regenStrength: 0.4, regenModelId: 'flux-v1'` so lineage stays honest. **Hardware-gated** — defer until the 128GB unified-memory machine arrives; current dev hardware can't comfortably host the local diffusion runner alongside the rest of PortOS. Pull in only after that hardware is online and the user wants to play with it. UX caveat: this is the only honest watermark-defeat path; the existing C2PA-strip-and-denoise will always be a no-op against SynthID and should never be relabeled as a watermark stripper.