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
refactor: address Copilot review findings
[._.]/ Adam Eivy2dd9ae66d25a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b34c3d398e..8651b4a771 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` (13 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` (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 — 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.mdindex 4e725fcb34..16e58c9fcf 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`. Covered by 13 unit tests in `universeBuilderAutoSort.test.js` (happy path, no-other-buckets short-circuit, hallucinated-key filter, `LLM_INVALID_JSON` 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 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`.- **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/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 2156ab0ae9..f78e27394b 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -1434,12 +1434,22 @@ export default function UniverseBuilder() {toast.dismiss(toastId);return;}- setDraft((d) => ({- ...d,- categories: updated.categories,- schemaVersion: updated.schemaVersion,- updatedAt: updated.updatedAt,- }));+ // Merge only the reclassified buckets into the draft — wholesale-+ // replacing `categories` with the server snapshot would discard any+ // user edits to OTHER buckets made while the LLM call was in flight.+ const sortedKeys = new Set((result.results || []).map((r) => r.sourceKey));+ setDraft((d) => {+ const next = { ...(d.categories || {}) };+ for (const key of sortedKeys) {+ if (updated.categories?.[key]) next[key] = updated.categories[key];+ }+ return {+ ...d,+ categories: next,+ schemaVersion: updated.schemaVersion,+ updatedAt: updated.updatedAt,+ };+ });toast.dismiss(toastId);const sortedCount = result.results?.length || 0;const renames = (result.results || []).filter((r) => r.suggestedKey);diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.jsindex 5c83814ee2..a00b31ea8d 100644--- a/server/services/universeBuilderAutoSort.js+++ b/server/services/universeBuilderAutoSort.js@@ -93,7 +93,13 @@ const extractClassifications = (raw) => {const { value, lastError, lastPreview } = extractJsonShared(raw, {shapePredicate: isClassificationsShape,});- if (value !== undefined) return value.classifications;+ // extractJson returns the first parseable block as a fallback even when+ // shapePredicate fails — so `value` could be `{ classifications: null }`+ // or `{ error: "..." }`. Re-gate on the array shape so downstream+ // iteration can't throw a generic 500.+ if (value !== undefined && Array.isArray(value?.classifications)) {+ return value.classifications;+ }throw new ServerError('LLM returned invalid JSON for bucket classification. Try a different model or rerun.',{@@ -127,15 +133,13 @@ export async function autoSortOtherBuckets(universeId, options = {}) {const universe = await getUniverse(universeId);const categories = universe.categories || {};- // Snapshot the un-classified buckets in insertion order. Retain the full- // bucket record (not just `variations`) so the patch below can spread it- // and preserve any future per-bucket fields (locked flags, customPrompt,- // etc.) added beyond the current `kind`+`variations` shape.+ // Snapshot the un-classified buckets in insertion order — used only to+ // build the prompt body. The actual write below re-fetches the latest+ // universe state so concurrent edits aren't overwritten.const otherBuckets = Object.entries(categories).filter(([, c]) => c && c.kind === 'other').map(([key, c]) => ({key,- bucket: c,variations: Array.isArray(c.variations) ? c.variations : [],}));@@ -171,11 +175,19 @@ export async function autoSortOtherBuckets(universeId, options = {}) {const classifications = extractClassifications(raw);- // Build a lookup of the buckets we actually asked about; the LLM may- // hallucinate a key not in our list and we should ignore those rather- // than blindly creating a new bucket. Keys are pre-normalized in the- // universe sanitizer so a direct equality check is safe.- const byKey = new Map(otherBuckets.map((b) => [b.key, b]));+ // Re-fetch the latest universe state immediately before the write so+ // concurrent edits made to OTHER buckets (in another tab) during the+ // LLM call aren't overwritten. We still build the patch keyed only on+ // the buckets the LLM classified, but each bucket's spread uses the+ // freshest persisted shape — so a variation added mid-LLM-call to a+ // bucket that's about to be reclassified is preserved.+ const latest = await getUniverse(universeId);+ const latestCategories = latest.categories || {};+ const byKey = new Map(+ Object.entries(latestCategories)+ .filter(([, c]) => c && c.kind === 'other')+ .map(([key, c]) => [key, c]),+ );const categoriesPatch = {};const results = [];const seenSourceKeys = new Set();@@ -192,19 +204,18 @@ export async function autoSortOtherBuckets(universeId, options = {}) {if (!SORTABLE_KINDS.includes(c.kind)) continue;const sourceKey = normalizeCategoryKey(c.key);if (!sourceKey || seenSourceKeys.has(sourceKey)) continue;- const bucket = byKey.get(sourceKey);- if (!bucket) continue;+ // Drop classifications for buckets that no longer exist or are no+ // longer kind:'other' on the latest state — a concurrent assignBucketKind+ // or removeCategory call would otherwise be silently reverted here.+ const latestBucket = byKey.get(sourceKey);+ if (!latestBucket) continue;seenSourceKeys.add(sourceKey);- // Emit the per-bucket patch keyed by sourceKey (no rename auto-applied —- // see file-level comment). updateUniverse does per-key replacement on- // categories (not per-field merge), so we spread the whole bucket- // record to avoid dropping any non-kind fields.- categoriesPatch[sourceKey] = { ...bucket.bucket, kind: c.kind };+ // updateUniverse does per-key replacement on categories (not per-field+ // merge), so spread the whole latest bucket record to preserve any+ // variations / fields added mid-flight.+ categoriesPatch[sourceKey] = { ...latestBucket, kind: c.kind };- // Surface suggestedKey only when it's a real, distinct, normalized- // suggestion — drop empties / unchanged values so the UI doesn't- // render no-op "Rename to <same thing>" suggestions.const suggested = typeof c.suggestedKey === 'string' ? normalizeCategoryKey(c.suggestedKey) : '';const suggestedKey = (suggested && suggested !== sourceKey) ? suggested : null;@@ -212,9 +223,6 @@ export async function autoSortOtherBuckets(universeId, options = {}) {}if (results.length === 0) {- // No bucket survived classification (rare — LLM returned only hallucinated- // keys or only invalid kinds). Surface this so the UI can fall back to- // "try another model" guidance rather than silently no-op'ing.throw new ServerError('LLM returned no valid classifications for any bucket. Try a different model or rerun.',{ status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' },diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.jsindex 53239e07ee..cafd7f8f59 100644--- a/server/services/universeBuilderAutoSort.test.js+++ b/server/services/universeBuilderAutoSort.test.js@@ -246,6 +246,25 @@ describe('universeBuilderAutoSort — LLM-shaped failures', () => {).rejects.toMatchObject({ status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' });});+ 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)+ // must hit the typed 502 path, not flow into the for-of loop and throw a 500.+ const w = await seedUniverseWithBuckets({+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],+ },+ });+ runPromptThroughProviderMock.mockResolvedValue({+ text: '{"classifications": null}',+ runId: 'run-bad-3',+ model: 'mock-default',+ });+ await expect(+ autoSortSvc.autoSortOtherBuckets(w.id),+ ).rejects.toMatchObject({ status: 502, code: 'LLM_INVALID_JSON' });+ });+it('rejects when no AI provider is available', async () => {const w = await seedUniverseWithBuckets({colonies: {