Skip to content

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

refactor: address Copilot review round 2

[._.]/ Adam Eivy0880b3fa673a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8651b4a771..1057c015cb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,7 +10,7 @@
### Universe Builder
-- **Other tab — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` batches every `kind: 'other'` bucket into one LLM call that classifies each into characters / settings / objects (and optionally suggests a clearer key). Reassignments land atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds so the sanitizer can't coerce them back to `other`); `suggestedKey` renames surface in the response but stay opt-in. The Other-tab button replaces its old toast stub with a real spinner + result summary. New service `server/services/universeBuilderAutoSort.js` (14 unit tests, including a prompt-injection pin that newlines in user-supplied labels/styleNotes/logline are stripped before embedding) + `server/routes/universeBuilder.test.js` (4 route tests); client helper `autoSortBuckets` in `apiUniverseBuilder.js`.
+- **Other tab — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` batches every `kind: 'other'` bucket into one LLM call that classifies each into characters / settings / objects (and optionally suggests a clearer key). Reassignments land atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds so the sanitizer can't coerce them back to `other`); `suggestedKey` renames surface in the response but stay opt-in. The Other-tab button replaces its old toast stub with a real spinner + result summary. New service `server/services/universeBuilderAutoSort.js` (15 unit tests, including a prompt-injection pin that newlines + Unicode line separators in user-supplied labels/styleNotes/logline are stripped before embedding) + `server/routes/universeBuilder.test.js` (4 route tests); client helper `autoSortBuckets` in `apiUniverseBuilder.js`.
- **Other tab — manual trunk assignment.** Each bucket on the Other tab now has an **Assign to…** menu (Cast / Places / Objects) that retags `categories[bucket].kind` so the bucket moves out of Other into the matching trunk on next render. Variations stay in place; per-variation promote-to-canon remains a separate action.
- **Render tab — Other group + dedupe.** Removed the redundant "Prompt set" dropdown from the Batch render card — scope is now always chosen via the Render targets section below. Render targets gained an **Other** group with per-bucket sub-buttons and a `Bulk-render all (N)` button. Top-level action is now **Render everything (N)**.
- **Batch render — full Image Gen surface.** Batch Render now uses the shared `ImageGenSettingsForm`, so switching the backend chip (Local / External / Codex) reveals every per-mode option: model, resolution, steps, guidance/CFG, quantize, seed, **LoRAs**, **style preset**, negative prompt, and extra style. Server-side render schema accepts these as optional per-batch overrides and threads them through prompt composition + every enqueued job (`server/routes/universeBuilder.js` + `server/services/universeBuilder.js`).
diff --git a/DONE.md b/DONE.md
index 16e58c9fcf..6b10f6e010 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,7 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 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 14 unit tests in `universeBuilderAutoSort.test.js` (happy path, no-other-buckets short-circuit, hallucinated-key filter, `LLM_INVALID_JSON` (no-parse + non-array `classifications`) vs `NO_CLASSIFICATIONS` paths, `NO_PROVIDER` gate, prompt-injection defense via newline stripping on labels/styleNotes/logline) + 4 route tests in `universeBuilder.test.js`.
+- **[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`.
- **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).)
diff --git a/PLAN.md b/PLAN.md
index af2a31eb51..54fc1feba9 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -19,6 +19,8 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [ ] [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.
diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.js
index a00b31ea8d..85ffcc7ff2 100644
--- a/server/services/universeBuilderAutoSort.js
+++ b/server/services/universeBuilderAutoSort.js
@@ -38,7 +38,7 @@ const VARIATION_SAMPLE_PER_BUCKET = 10;
// bounded even if injection lands, but stripping at the embed layer is the
// cheap defense.
const escapePromptText = (s) =>
- typeof s === 'string' ? s.replace(/[\r\n\t]+/g, ' ').trim() : '';
+ typeof s === 'string' ? s.replace(/[\r\n\t\f\v\u0085\u2028\u2029]+/g, ' ').trim() : '';
const kindUnionForPrompt = SORTABLE_KINDS.map((k) => `"${k}"`).join(' | ');
const kindListForPrompt = SORTABLE_KINDS.join(', ');
@@ -89,7 +89,15 @@ const isClassificationsShape = (o) => {
};
const extractClassifications = (raw) => {
- if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');
+ // Surface empty/non-string responses through the same typed 502 path as
+ // malformed JSON — without this, a successful run with empty `text` would
+ // throw an untyped Error that the route would normalize to a generic 500.
+ if (!raw || typeof raw !== 'string') {
+ throw new ServerError(
+ 'LLM returned an empty response for bucket classification. Try a different model or rerun.',
+ { status: 502, code: 'LLM_INVALID_JSON' },
+ );
+ }
const { value, lastError, lastPreview } = extractJsonShared(raw, {
shapePredicate: isClassificationsShape,
});
diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.js
index cafd7f8f59..24b8c714ff 100644
--- a/server/services/universeBuilderAutoSort.test.js
+++ b/server/services/universeBuilderAutoSort.test.js
@@ -246,6 +246,22 @@ describe('universeBuilderAutoSort — LLM-shaped failures', () => {
).rejects.toMatchObject({ status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' });
});
+ it('rejects with LLM_INVALID_JSON when the response is an empty string (typed error, not bare Error → 500)', async () => {
+ const w = await seedUniverseWithBuckets({
+ colonies: {
+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],
+ },
+ });
+ runPromptThroughProviderMock.mockResolvedValue({
+ text: '',
+ runId: 'run-empty-1',
+ model: 'mock-default',
+ });
+ await expect(
+ autoSortSvc.autoSortOtherBuckets(w.id),
+ ).rejects.toMatchObject({ status: 502, code: 'LLM_INVALID_JSON' });
+ });
+
it('rejects with LLM_INVALID_JSON when value.classifications is not an array (fallback path)', async () => {
// extractJson returns the first parseable block as a fallback even when
// shapePredicate fails. A malformed top-level shape (classifications: null)