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
Merge remote-tracking branch 'origin/main' into claim/auto-sort-with-ai-llm-classify-each-kind-other
[._.]/ Adam Eivy53aa8f8e4ba6
diff --cc DONE.mdindex 6b10f6e010,170eb2b31d..2c72300766--- a/DONE.md+++ b/DONE.md@@@ -8,10 -8,9 +8,13 @@@ For active roadmap see [PLAN.md](./PLAN## 2026-05+### 2026-05-17++- **[auto-sort-with-ai-llm-classify-each-kind-other] Universe Builder — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` (server: `server/services/universeBuilderAutoSort.js`, `server/routes/universeBuilder.js`) batches every `kind: 'other'` bucket into a single LLM call that returns `{ classifications: [{ key, kind, suggestedKey? }] }`. The service applies kind reassignments atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds); `suggestedKey` renames stay opt-in — they surface as a count in the success toast but the bucket key isn't auto-renamed. Replaces the Other-tab's toast-stub `onAutoSort` handler with a real spinner-driven handler in `client/src/pages/UniverseBuilder.jsx`; new `autoSortBuckets` API helper in `client/src/services/apiUniverseBuilder.js`. Concurrent-edit safety: the service re-fetches the latest universe state immediately before the write so a variation added to a soon-to-be-classified bucket in another tab during the LLM call isn't overwritten; the client merges only the reclassified buckets into the draft to preserve user edits to other buckets. Covered by 15 unit tests in `universeBuilderAutoSort.test.js` (happy path, no-other-buckets short-circuit, hallucinated-key filter, `LLM_INVALID_JSON` (empty response + no-parse + non-array `classifications`) vs `NO_CLASSIFICATIONS` paths, `NO_PROVIDER` gate, prompt-injection defense via newline + Unicode-line-separator stripping on labels/styleNotes/logline) + 4 route tests in `universeBuilder.test.js`.+ - **[extract-a-shared-tabpills-primitive-in-client-src] Extract a shared `<TabPills>` primitive in `client/src/components/ui/`.** New `client/src/components/ui/TabPills.jsx` with two variants (`underline` default + `pills` for UniverseBuilder) and knobs for the call-site quirks: `runningKind` (StoryboardPanel's per-tab spinner), `stretch` (flex-1 equal-width tabs), `mobileDropdown` (UniverseBuilder's `<select>` fallback), `hideLabelOnMobile` (Brain/DigitalTwin/ChiefOfStaff icon-only at < sm), `controlsIdPrefix` (ChiefOfStaff's `aria-controls` wiring), `listRef`+`onScroll` (ChiefOfStaff's scroll-arrow overlay). Migrated ten call sites — two local `TabNav` components (UniverseBuilder, StoryboardPanel) plus eight inline tab-button blocks (Brain, Calendar, ChiefOfStaff, DigitalTwin, MediaGen, Messages, Settings, Wiki). Net -250+ LOC consolidated into one primitive + 7 vitest cases. Small intentional visual unification across the surface area: StoryboardPanel active text-white → text-port-accent, ChiefOfStaff/Settings gained the standard `bg-port-accent/5` active wash + `hover:bg-port-card` inactive. PipelineIssue's status-dot tab variant is captured in PLAN.md as a follow-up needing a `trailing` slot extension on the primitive.+ - **[unify-canoncard-variation-card-into-a-single] Universe Builder — unify CanonCard + variation card into shared `EntryCard` shell.** New `client/src/components/universe/EntryCard.jsx` slot-based primitive (locked accent, title row, body, action column, optional thumbnail, optional footer). `CanonCard` now renders through it and surfaces a top-left thumbnail derived from `primaryImageRef` (falling back to the first `imageRefs[0]`) so each canon entry has a visual at-a-glance. The variation `<li>` in `CategoryEditor` is extracted into a `VariationCard` helper that also renders through `EntryCard` — view mode shows label + prompt + action column (promote / render / lock / edit / remove); edit mode swaps the body for an inline form. Visual consistency between the two card families now flows from the shared shell rather than parallel Tailwind class strings.+ - **[client-component-tests-for-categoryeditor-promote] Client component tests for `CategoryEditor` + `TrunkView`.** Wired up the first vitest-based client test suite (vitest 3 + jsdom + @testing-library/react + user-event) — new `client/vitest.config.js`, `client/src/test/setup.js`, `test` + `test:watch` scripts in `client/package.json`, CI step in `.github/workflows/ci.yml`. Named-exported `CategoryEditor` and `TrunkView` from `client/src/pages/UniverseBuilder.jsx` and added `client/src/pages/UniverseBuilder.test.jsx` covering: promote button disabled when `!canPromote` (parent's `!selectedId`); promote fires directly with no targetKind for a kinded bucket; clicking promote on a `bucketKind: null` ("other") variation opens the trunk picker; clicking a picker option calls `onPromote(variation, { targetKind })` with the correct kind; `TrunkView` "Bulk-render all" button disabled at zero count and enabled with the right count from variations. Three pre-existing orphaned client tests (`cleanPlatePrompt`, `clipboard`, `normalize`) now run too.+- **CoS — explicit `init()` instead of module-level auto-init.** Dropped the `NODE_ENV !== 'test' && VITEST !== 'true'` guard from `server/services/cos.js`; `init` is now exported and called from `server/index.js` alongside the other startup `*.init()` calls. Test imports no longer spin up event listeners / timers as a side effect, and the prod boot path no longer branches on test-env vars.- **Universe Builder DRY — `resolveProviderAndModel` + `findBibleEntryByName`.** Two shared helpers landed in `server/lib/`. The first collapses four inlined `getProviderById/getActiveProvider/resolveEffectiveModel` chains across the universe-builder LLM entrypoints onto one helper; the second consolidates the "case-insensitive name OR alias" predicate at the promote duplicate-collision check. (The retired-characters bucket fold keeps its O(1) seen-set index since it folds entries into a growing array — a per-iteration linear scan would have made it O(n*m).)- **CoS / Agent lifecycle hardening.** Six backlog items flushed in one pass. (1) TUI providers now usable from the manual `/api/runs` runner panel — the client-side disable was stale once the server-side `executeTuiRun` branch landed in `routes/runs.js`. (2) Extracted two complementary helpers in `agentLifecycle.js` so the central completion sequence is shared between runner-mode `handleAgentCompletion`, the TUI `finish` path, and the direct-CLI `close` handler: `releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage })` fires lane release + tool-execution tracking EARLY (before output I/O / error analysis / state writes) so other lane tasks aren't blocked, and `finalizeAgent({ agentId, task, runId, providerId, success, exitCode, duration, outputBuffer, errorAnalysis, terminatedByUser, isTruthyMetaFn, error, completionReason })` runs the centralized state writes sequentially (persistSimplifySummaries → completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion). A future divergence in any leg is now a one-place fix. (3) Wrapped `handleAgentCompletion` in try/finally so a throw from any inner step still drops the `runnerAgents` Map entry (previously leaked forever on memory-extraction crashes, JIRA push failures, etc.). (4) Added `isTuiProvider` next to `isClaudeCliProvider` and lifted `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`. (5) Converted `spawnTuiAgent` + `spawnDirectly` from 11-positional-arg signatures to options objects. (6) Wrapped `shellService.createShellSession` for agent TUIs in a thin `createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit })` helper. Regression-pin tests in `agentLifecycle.test.js` flipped from "documents the gap" to "asserts the guard fires."diff --cc PLAN.mdindex 54fc1feba9,3793ab066c..ec2eac843f--- a/PLAN.md+++ b/PLAN.md@@@ -11,16 -11,9 +11,12 @@@ For project goals, see [GOALS.md](./GOA- **Phase B — Expand contract enrichment.** Teach `buildExpansionPrompt()` (`server/services/universeBuilderExpand.js`) to return rich canon arrays (`characters[]`/`settings[]`/`objects[]` with `physicalDescription`/`palette`/`recurringDetails`/`wardrobe`) alongside the existing `categories` (now kind-tagged) + `compositeSheets`. Update `isExpansionShape()` predicate. Client `handleExpand` in `UniverseBuilder.jsx` merges canon entries into the canon arrays parallel to the category merge (dedupe by name, respect per-entry locks). Categories the LLM emits include a `kind` so they land under the right trunk.- **Phase C — Layout rewrite.** Tabbed top-level (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state (`?tab=cast&bucket=heroes` per CLAUDE.md linkable-routes convention) — Bible is its own tab (not a sticky header). Per-trunk view = sub-bucket chip filter row + responsive card grid. Unify `CanonCard` + a new card for category variations into a single `EntryCard` component (renders thumbnail from `primaryImageRef` or most recent render). **Canon entries are first-class batch-render targets** alongside category variations and composite sheets: per-bucket actions are "Generate N more" + "Bulk-render this bucket"; per-trunk action is "Bulk-render all Cast/Places/Objects" (includes BOTH canon entries AND every variation in every sub-bucket under that trunk); the Batch Render tab itself offers per-trunk, per-bucket, and "All canon" selectors plus the existing composite-sheets mode. Composite reference images stay intact as their own render mode (no regression). Server-side: extend `compilePrompts` to accept canon entries as render sources (synthesize a prompt from `name + physicalDescription/palette/description`, layered with the universe style preset the same way variations are today). The **Other** tab only appears when un-kinded buckets exist, and shows the **Auto-sort with AI** action. Mobile: tabs collapse to a select dropdown.- **Phase D — Polish & promotion.** ~~"Promote variation to canon" action~~ shipped: `POST /api/universe-builder/:id/promote-variation` LLM-expands a `{label, prompt}` variation into a full canon entry (per-kind `physicalDescription` / `slugline`+`palette` / `description`+`significance`) and atomically writes the canon append + variation removal in one `updateUniverse` patch. CategoryEditor renders a promote button per row; Other-tab buckets open a trunk picker (since `kind: 'other'` can't be auto-resolved). Duplicate-name collisions short-circuit with a 409 before the LLM call. Deferred: client component tests; standalone design doc (not warranted — CLAUDE.md notes + this PR's prose cover the contract).- - **Phase D follow-ups (deferred from the Phase D PR):**- - [ ] [client-component-tests-for-categoryeditor-promote] **Client component tests for `CategoryEditor` promote wiring + `TrunkView` button visibility.** Assert promote button disabled when `!selectedId`, picker opens for `kind: 'other'` buckets, picker option click invokes `onPromote` with the correct `targetKind`. No client vitest infra wired for `UniverseBuilder.jsx` yet — add when the page's first spec lands.- **Phase C follow-ups (deferred from the Phase C PR):**- - [ ] [unify-canoncard-variation-card-into-a-single] **Unify `CanonCard` + variation card into a single `EntryCard`.** Phase C reuses `CanonCard` for canon and `CategoryEditor` for variations inside the same TrunkView. Visual consistency is achieved through shared Tailwind classes; an actual single-component unification (with thumbnail-from-`primaryImageRef`-or-recent-render) is the Phase D card-extraction task.- - [ ] [extract-a-shared-tabpills-primitive-in-client-src] **Extract a shared `<TabPills>` primitive in `client/src/components/ui/`.** Phase C's `TabNav` in `UniverseBuilder.jsx` duplicates the pattern in `StoryboardPanel.jsx` `TabNav` + 5 inline tab-button pages (`Calendar.jsx`, `ChiefOfStaff.jsx`, `DigitalTwin.jsx`, `Messages.jsx`, etc.). One primitive that accepts `{ tabs: [{id,label,icon,count}], activeTab, onChange }` would consolidate. Cross-cutting refactor — defer until next time we touch tab UI somewhere.- - [ ] [auto-sort-with-ai-llm-classify-each-kind-other] **Auto-sort with AI** — LLM-classify each `kind: 'other'` bucket into characters/settings/objects + suggest a meaningful name. New server route `POST /api/universe-builder/:id/auto-sort` that sends bucket keys + variation labels to the active LLM and applies the classification. Currently the Other-tab button is a stub that points users at re-running Generate From Idea (Phase B's expand emits kind tags). Land in a follow-up to keep the Phase C PR scoped.- [ ] [extract-descriptorforcanonentry-kind-entry-into] **Extract `descriptorForCanonEntry(kind, entry)` into `server/lib/canonPrompt.js` (mirror in client).** The new server-side `synthesizeCanonPrompt()` in `server/services/universeBuilder.js` duplicates the per-kind descriptor logic already present in `client/src/components/universe/UniverseCanonSection.jsx`'s `KINDS[].descFor` closures and overlaps with `server/lib/scenePrompt.js` (`settingFrags`). One helper would let canon-render synthesis, the canon UI summary, and scene-prompt framing all share the same field-precedence rules.+ - [ ] [extract-builduniversestylecontext-helper] **Extract `buildUniverseStyleContext(universe, options)` helper.** The `LOGLINE / STYLE NOTES / EMBRACE INFLUENCES` prompt prefix is duplicated verbatim in three places: `server/services/universeBuilderPromote.js#buildPromotePrompt`, `server/services/universeBuilderAutoSort.js#buildAutoSortPrompt`, and a near-twin in `server/services/universeBuilderExpand.js` (adds `premise`). A single helper in `server/services/universeBuilder.js` (next to `joinInfluenceList`) would consolidate. Pipeline callsites at `server/services/pipeline/visualStages.js` and `pipeline/seriesTitleLogo.js` hand-roll variants of the same shape — fold them in too.+ - [ ] [extract-useuniverseaction-hook] **Extract `useUniverseAction({ selectedId, mountedRef, setWorlds, setDraft })` hook.** `handlePromoteVariation`, `handleAutoSort`, and (to a lesser extent) `handleGenerateInCategory` in `client/src/pages/UniverseBuilder.jsx` share the same `*Ref` re-entrancy guard → `capturedId = selectedId` → `toast.loading` → API call → `mountedRef && capturedId === selectedId` stale-write guard → `setWorlds` + selective `setDraft` skeleton. `useAsyncAction` is too thin — it doesn't model the stale-write guard CLAUDE.md calls out. Extract when a 4th LLM-driven handler lands.+ - [ ] [universe-builder-llm-action-read-modify-write-inside-queue] **Move LLM-action read-modify-write inside `queueUniverseWrite`.** `autoSortOtherBuckets` (and `promoteVariationToCanon`) currently read the universe state, run a long LLM call, then write — the gap between the LLM call and `updateUniverse` admits a narrow race where another tab can edit the same bucket. The service-level refetch right before write narrows the window to ~ms but doesn't eliminate it (concurrent writes between refetch and `updateUniverse`'s own queued readState can still drop a variation). Real fix: extend `updateUniverse` to accept a `mutator(latest) => patch` callback so the read-modify-write runs inside the file-level queue. Cross-cutting (touches every LLM-driven mutator).+ - [ ] [universe-builder-flush-draft-before-llm-actions] **Flush dirty draft before triggering LLM-driven mutators.** `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` operate against the server-persisted universe; if the user has unsaved local edits to a bucket and clicks one of these, the server's stale copy comes back and gets merged into the draft, silently discarding the local edits. Either auto-save on click (and wait for confirmation) or gate the buttons on `!isDirty`. Decide which after looking at what `isDirty` means in this page (`draftRef` vs `worlds` snapshot).2. **Step-by-step approval/lock UX across Universe → Series → Arc → Seasons → Episodes.** Iteration 1 shipped a single arc-level lock; extend to per-season + per-field locks, lock the bulk runners, surface stage-progress strip, enforce locks server-side before LLM invocations.3. **Sharing v2 contracts** — per-peer subscription filenames (`sub-<kind>-<recordId>-<senderInstanceId>.json`), tombstone-based item removals, "🔄 live" badge on inbox subscription rows.4. **Pipeline continuity gaps** — plumb character physicalDescription/personality/background into idea-stage prompt; plumb setting `palette`/`era`/`weather`/`recurringDetails` into visual stages; add `worldEntitiesSummary` to text stages; add a dedicated `voice` / speech-pattern field to the bible schema.