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
feat([auto-sort-with-ai-llm-classify-each-kind-other]): bulk-classify Other-tab buckets via one LLM call
[._.]/ Adam Eivyf81cd84cea39
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 86f92b88c9..ef12f8801a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +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` + 16 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 a1327f5ded..a3f9165fff 100644--- a/DONE.md+++ b/DONE.md@@ -8,6 +8,10 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./## 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 surface on the response but stay opt-in (the UI shows a hint, doesn't auto-apply). Replaces the toast-stub at `client/src/pages/UniverseBuilder.jsx:1739` with a real handler + spinner state; new `autoSortBuckets` API helper in `client/src/services/apiUniverseBuilder.js`. Covered by 12 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) + 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).)- **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 --git a/PLAN.md b/PLAN.mdindex 1127ac2d7f..af2a31eb51 100644--- a/PLAN.md+++ b/PLAN.md@@ -14,10 +14,11 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- **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):**- - [ ] [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.- [ ] [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.- [ ] [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.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/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 52d202e5b2..60da92d67a 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -18,7 +18,7 @@ import {import toast from '../components/ui/Toast';import {listUniverses, getUniverse, createUniverse, updateUniverse, deleteUniverse, expandUniverse,- generateCategoryVariations, promoteVariationToCanon,+ generateCategoryVariations, promoteVariationToCanon, autoSortBuckets,renderWorld, listWorldRuns, getProviders, refineWorldPrompts, WORLD_CATEGORIES,WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,@@ -566,6 +566,8 @@ export default function UniverseBuilder() {// first's canon append.const [promoting, setPromoting] = useState(false);const promotingRef = useRef(false);+ const [autoSorting, setAutoSorting] = useState(false);+ const autoSortingRef = useRef(false);const [newCategoryName, setNewCategoryName] = useState('');// True when handleExpand merged new canon entries into the draft that the// server doesn't yet know about (auto-save failed or hasn't run). On the@@ -1387,6 +1389,60 @@ export default function UniverseBuilder() {toast.success(`Moved "${humanizeCategory(bucket)}" to ${trunk.label}`);}};+ // Auto-sort with AI — one LLM call classifies every Other-tab bucket into+ // characters/settings/objects. Each bucket's `kind` is reassigned via a+ // single atomic patch server-side so the universe ends up consistent or+ // unchanged. Renames the LLM suggests are surfaced in the toast but not+ // auto-applied (the user can rename manually if they want it).+ const handleAutoSort = async () => {+ if (!selectedId) {+ toast.error('Save the universe first — auto-sort needs the persisted record');+ return;+ }+ if (autoSortingRef.current) return;+ autoSortingRef.current = true;+ setAutoSorting(true);+ const capturedId = selectedId;+ const toastId = toast.loading('Auto-sorting buckets with AI…');+ const result = await autoSortBuckets(selectedId, {+ providerId: draft.llm?.provider || undefined,+ model: draft.llm?.model || undefined,+ }, { silent: true }).catch((e) => {+ toast.dismiss(toastId);+ toast.error(`Auto-sort failed: ${e.message}`);+ return null;+ });+ if (mountedRef.current) {+ autoSortingRef.current = false;+ setAutoSorting(false);+ }+ if (!result?.universe) return;+ const updated = result.universe;+ setWorlds((prev) => {+ const without = prev.filter((w) => w.id !== updated.id);+ return [updated, ...without];+ });+ if (!mountedRef.current || capturedId !== selectedId) return;+ // Only the categories changed server-side — preserve other in-progress+ // draft edits the user might have made while the LLM call was in flight.+ setDraft((d) => ({+ ...d,+ categories: updated.categories,+ schemaVersion: updated.schemaVersion,+ updatedAt: updated.updatedAt,+ }));+ toast.dismiss(toastId);+ const sortedCount = result.results?.length || 0;+ const renames = (result.results || []).filter((r) => r.suggestedKey);+ const summary = sortedCount+ ? `Sorted ${sortedCount} bucket${sortedCount === 1 ? '' : 's'} into canon trunks`+ : 'No buckets were classified';+ const renameHint = renames.length+ ? ` — ${renames.length} rename suggestion${renames.length === 1 ? '' : 's'} available`+ : '';+ toast.success(`${summary}${renameHint}`);+ };+const handleGenerateInCategory = async (cat, count) => {const current = draft.categories?.[cat]?.variations || [];const existingLabels = current.map((v) => v.label).filter(Boolean);@@ -1735,9 +1791,8 @@ export default function UniverseBuilder() {onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}onAssignBucketKind={assignBucketKind}- onAutoSort={() => {- toast('Auto-sort with AI is wired in a follow-up. Re-run "Generate From Idea" — Phase B\'s expand call now classifies buckets into the right trunk.', { icon: 'ℹ️' });- }}+ onAutoSort={handleAutoSort}+ autoSorting={autoSorting}/>)}@@ -3011,6 +3066,7 @@ function OtherTab({draft, buckets, activeBucket, setBucket, canRender, canPromote,onUpdateBucket, onRemoveBucket, onGenerateInBucket, onPromoteVariation,onBulkRenderBucket, onRenderVariation, onAssignBucketKind, onAutoSort,+ autoSorting = false,}) {return (<>@@ -3024,16 +3080,18 @@ function OtherTab({<buttontype="button"onClick={onAutoSort}- className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 text-port-accent rounded flex items-center gap-1 min-h-[32px]"- title="Auto-sort with AI — shows guidance until the dedicated endpoint lands (tracked in PLAN.md)"+ disabled={autoSorting}+ className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-50 text-port-accent rounded flex items-center gap-1 min-h-[32px]"+ title="Auto-sort with AI — sends every Other-tab bucket to the active LLM and assigns each to characters / settings / objects">- <Wand2 size={12} /> Auto-sort with AI+ {autoSorting ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}+ {autoSorting ? 'Sorting…' : 'Auto-sort with AI'}</button></div><p className="text-[11px] text-gray-500">These buckets aren't tagged as Cast / Places / Objects yet — they wereeither added manually or imported from a pre-Phase-A universe. Auto-sort- will classify each bucket into the right trunk with a meaningful name.+ asks the active LLM to classify every bucket into the right trunk.</p></section>diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex ca01956cdf..e095305935 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -208,3 +208,13 @@ export const promoteVariationToCanon = (universeId, {body: JSON.stringify({ category, label, targetKind, providerId, model }),...options,});++// Bulk-classify every `kind: 'other'` bucket on a universe. Server returns+// `{ universe, results: [{ sourceKey, kind, suggestedKey? }], llm, runId }`.+// Pass `{ silent: true }` when the caller owns its own error toast.+export const autoSortBuckets = (universeId, { providerId, model } = {}, options = {}) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/auto-sort`, {+ method: 'POST',+ body: JSON.stringify({ providerId, model }),+ ...options,+ });diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex ec7eb24b10..9ea6954d7f 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -23,6 +23,7 @@ import { getUniverseCanonUsage } from '../services/canonUsage.js';import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';import { refineWorldPrompts } from '../services/universeBuilderRefine.js';import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../services/universeBuilderPromote.js';+import { autoSortOtherBuckets } from '../services/universeBuilderAutoSort.js';import { enqueueJob } from '../services/mediaJobQueue/index.js';import { getSettings } from '../services/settings.js';import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';@@ -198,6 +199,14 @@ const promoteVariationSchema = z.object({model: z.string().trim().max(200).optional(),});+// Auto-sort takes no bucket selection — the service scans for every+// `kind: 'other'` bucket on the universe. Provider/model are optional;+// the service falls back to the active provider when omitted.+const autoSortSchema = z.object({+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+const generateVariationsSchema = z.object({category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),count: z.number().int().min(1).max(svc.VARIATIONS_PER_CATEGORY_MAX),@@ -561,6 +570,17 @@ router.post('/:id/promote-variation', asyncHandler(async (req, res) => {res.json(result);}));+// Bulk-classify every `kind: 'other'` bucket via one LLM call. Each bucket's+// `kind` is updated atomically in one `updateUniverse` patch; renames the+// LLM suggests are surfaced in the response but not auto-applied (the UI+// can present them as opt-in suggestions).+router.post('/:id/auto-sort', asyncHandler(async (req, res) => {+ const body = validateRequest(autoSortSchema, req.body ?? {});+ const result = await autoSortOtherBuckets(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+const refineCharSchema = z.object({providerId: z.string().trim().max(64).optional(),model: z.string().trim().max(128).optional(),diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.jsindex 313a0f0410..d4cf63e41d 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder.test.js@@ -40,6 +40,19 @@ vi.mock('../services/universeBuilderPromote.js', async () => {};});+// Stub the auto-sort service — same shape as promote, just returns a mock+// classification batch so the route's Zod schema + error mapping are+// exercised without shelling out to a real LLM.+const autoSortOtherBucketsMock = vi.fn(async (universeId, body = {}) => ({+ universe: { id: universeId, categories: {} },+ results: [{ sourceKey: 'colonies', kind: 'settings', suggestedKey: null }],+ llm: { provider: 'mock', model: body.model || null },+ runId: 'mock-autosort-run',+}));+vi.mock('../services/universeBuilderAutoSort.js', () => ({+ autoSortOtherBuckets: (...args) => autoSortOtherBucketsMock(...args),+}));+// Stub the LLM expander so the route test doesn't shell out to a real provider.vi.mock('../services/universeBuilderExpand.js', () => ({expandWorldTemplate: vi.fn(async ({ starterPrompt }) => ({@@ -593,4 +606,57 @@ describe('universe-builder routes', () => {expect(res.body.code).toBe('UNIVERSE_PROMOTE_NO_CATEGORY');});});++ describe('POST /:id/auto-sort', () => {+ beforeEach(() => {+ autoSortOtherBucketsMock.mockClear();+ });++ it('forwards the body to the service and returns the result', async () => {+ const app = buildApp();+ const res = await request(app)+ .post('/api/universe-builder/some-id/auto-sort')+ .send({ providerId: 'p1', model: 'm1' });+ expect(res.status).toBe(200);+ expect(autoSortOtherBucketsMock).toHaveBeenCalledWith('some-id', expect.objectContaining({+ providerId: 'p1',+ model: 'm1',+ }));+ expect(res.body.results[0].kind).toBe('settings');+ expect(res.body.runId).toBe('mock-autosort-run');+ });++ it('accepts an empty body (providerId + model are optional)', async () => {+ const app = buildApp();+ const res = await request(app)+ .post('/api/universe-builder/some-id/auto-sort')+ .send({});+ expect(res.status).toBe(200);+ expect(autoSortOtherBucketsMock).toHaveBeenCalled();+ });++ it('400s when providerId exceeds the schema cap (Zod schema)', async () => {+ const app = buildApp();+ const res = await request(app)+ .post('/api/universe-builder/some-id/auto-sort')+ .send({ providerId: 'a'.repeat(100) });+ expect(res.status).toBe(400);+ expect(autoSortOtherBucketsMock).not.toHaveBeenCalled();+ });++ it('maps service ServerError status onto the HTTP response', async () => {+ autoSortOtherBucketsMock.mockRejectedValueOnce(+ Object.assign(new Error('No provider'), {+ status: 503,+ code: 'UNIVERSE_AUTOSORT_NO_PROVIDER',+ }),+ );+ const app = buildApp();+ const res = await request(app)+ .post('/api/universe-builder/some-id/auto-sort')+ .send({});+ expect(res.status).toBe(503);+ expect(res.body.code).toBe('UNIVERSE_AUTOSORT_NO_PROVIDER');+ });+ });});diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.jsnew file mode 100644index 0000000000..79591c5ece--- /dev/null+++ b/server/services/universeBuilderAutoSort.js@@ -0,0 +1,230 @@+/**+ * Universe Builder — Auto-sort with AI.+ *+ * Bulk-classifies every `kind: 'other'` bucket on a universe into one of the+ * three canon trunks (characters / settings / objects) via a single LLM call.+ * Optionally surfaces a `suggestedKey` rename per bucket the UI can present+ * to the user — only the `kind` change is auto-applied here so a stray+ * rename can't silently break an in-flight reference or collide with an+ * existing bucket. (Renames stay an explicit, opt-in follow-up.)+ *+ * Atomic write: one `updateUniverse` patch carries every reclassified bucket+ * so a partial failure either commits the full classification or leaves the+ * universe untouched.+ */++import {+ getUniverse,+ updateUniverse,+ normalizeCategoryKey,+ joinInfluenceList,+} from './universeBuilder.js';+import { VALID_TARGET_KINDS } from './universeBuilderPromote.js';+import { ServerError } from '../lib/errorHandler.js';+import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';+import { resolveProviderAndModel, runPromptThroughProvider } from '../lib/promptRunner.js';++// The 3 real trunks — derived from BIBLE_FIELD via universeBuilderPromote so+// adding a new canon kind reaches this resolver automatically.+const SORTABLE_KINDS = VALID_TARGET_KINDS;++const VARIATION_SAMPLE_PER_BUCKET = 10;++const buildAutoSortPrompt = ({ buckets, universe }) => {+ const embraceTokens = joinInfluenceList(universe.influences?.embrace);+ const styleContext = [+ universe.logline ? `LOGLINE: ${universe.logline}` : null,+ universe.styleNotes ? `STYLE NOTES: ${universe.styleNotes}` : null,+ embraceTokens ? `EMBRACE INFLUENCES: ${embraceTokens}` : null,+ ].filter(Boolean).join('\n\n');+ const styleSection = styleContext+ ? `\n# Universe context\n${styleContext}\n`+ : '';++ const bucketBlock = buckets.map(({ key, variations }) => {+ const sample = variations+ .slice(0, VARIATION_SAMPLE_PER_BUCKET)+ .map((v) => ` - ${v.label}`)+ .join('\n');+ const body = sample || ' (no variations yet)';+ return `## ${key}\n${body}`;+ }).join('\n\n');++ return `You are organizing a story-bible template. The user has these custom buckets that aren't yet tagged to a canon trunk. For each bucket, decide whether it represents CHARACTERS (people, beings, factions of people), SETTINGS (places, environments, locations, regions), or OBJECTS (props, vehicles, weapons, artifacts, technology). Optionally suggest a clearer snake_case bucket key when the original is ambiguous.+${styleSection}+# Buckets to classify+${bucketBlock}++# Output contract+Return a JSON object: { "classifications": [{ "key": "<original bucket key, unchanged>", "kind": "characters" | "settings" | "objects", "suggestedKey": "<optional snake_case alternative>" }] }++# Rules+- "kind" MUST be one of: characters, settings, objects. Never "other".+- "key" MUST exactly match an input bucket key from the list above.+- "suggestedKey" is OPTIONAL — include only when the original is ambiguous or unclear. lowercase snake_case, max 64 chars, no spaces. Omit when the original is fine.+- Output ONLY the JSON object. No commentary, no markdown, no code fences.`;+};++const isClassificationsShape = (o) => {+ if (!o || typeof o !== 'object') return false;+ if (!Array.isArray(o.classifications)) return false;+ return o.classifications.every(+ (c) => c && typeof c === 'object'+ && typeof c.key === 'string'+ && SORTABLE_KINDS.includes(c.kind),+ );+};++const extractClassifications = (raw) => {+ if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');+ const { value, lastError, lastPreview } = extractJsonShared(raw, {+ shapePredicate: isClassificationsShape,+ });+ if (value !== undefined) return value.classifications;+ throw new ServerError(+ 'LLM returned invalid JSON for bucket classification. Try a different model or rerun.',+ {+ status: 502,+ code: 'LLM_INVALID_JSON',+ context: {+ details: {+ reason: lastError?.message || 'no matching JSON found',+ preview: lastPreview || '',+ },+ },+ },+ );+};++/**+ * Auto-sort every `kind: 'other'` bucket on a universe.+ *+ * Returns `{ universe, results, llm, runId }`. `results` is one entry per+ * bucket the LLM classified: `{ sourceKey, kind, suggestedKey? }`.+ * Buckets the LLM omitted, or returned with an unknown key/kind, are+ * dropped silently (no partial-failure for the rest of the batch).+ *+ * @param {string} universeId+ * @param {object} [options]+ * @param {string} [options.providerId]+ * @param {string} [options.model]+ */+export async function autoSortOtherBuckets(universeId, options = {}) {+ const { providerId, model } = 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.+ const otherBuckets = Object.entries(categories)+ .filter(([, c]) => c && c.kind === 'other')+ .map(([key, c]) => ({+ key,+ bucket: c,+ variations: Array.isArray(c.variations) ? c.variations : [],+ }));++ if (otherBuckets.length === 0) {+ return {+ universe,+ results: [],+ llm: { provider: null, model: null },+ runId: null,+ };+ }++ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });+ if (!provider) {+ throw new ServerError('No AI provider available for auto-sort', {+ status: 503,+ code: 'UNIVERSE_AUTOSORT_NO_PROVIDER',+ });+ }++ const prompt = buildAutoSortPrompt({ buckets: otherBuckets, universe });+ console.log(+ `🪄 Universe Builder auto-sort — universe=${universeId.slice(0, 8)} buckets=${otherBuckets.length} via ${provider.name}/${selectedModel || 'default'}`,+ );++ const { text: raw, runId } = await runPromptThroughProvider({+ provider,+ model: selectedModel,+ prompt,+ source: 'universe-builder-auto-sort',+ });+ console.log(`🪄 Universe Builder auto-sort raw — runId=${runId} length=${raw?.length || 0}`);++ 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]));+ const categoriesPatch = {};+ const results = [];+ const seenSourceKeys = new Set();++ for (const c of classifications) {+ // Defensive per-entry kind gate. The shape predicate above only filters+ // which parsed block extractJson returns — when only one block parses,+ // it's returned as a fallback even if its entries fail the predicate.+ // Without this guard a hallucinated `kind: "magic"` would flow into the+ // categories patch and the universe sanitizer would silently coerce it+ // to 'other', undoing the auto-sort the user just ran.+ if (!c || typeof c !== 'object') continue;+ if (typeof c.key !== 'string') continue;+ 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;+ 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 };++ // 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;++ results.push({ sourceKey, kind: c.kind, suggestedKey });+ }++ 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' },+ );+ }++ const updated = await updateUniverse(universeId, { categories: categoriesPatch });++ console.log(+ `🪄 Universe Builder auto-sort complete — universe=${universeId.slice(0, 8)} classified=${results.length} runId=${runId.slice(0, 8)}`,+ );++ return {+ universe: updated,+ results,+ llm: { provider: provider.id, model: selectedModel || null },+ runId,+ };+}++// Test seam.+export const __testing = {+ buildAutoSortPrompt,+ extractClassifications,+ isClassificationsShape,+};diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.jsnew file mode 100644index 0000000000..9dbc07392a--- /dev/null+++ b/server/services/universeBuilderAutoSort.test.js@@ -0,0 +1,289 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// In-memory file store mirrors universeBuilderPromote.test.js so a single+// readState/writeState path roundtrips through the same code the real+// service uses (no live file I/O).+const fileStore = new Map();++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+}));++let uuidCounter = 0;+vi.mock('crypto', async () => {+ const actual = await vi.importActual('crypto');+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+});++const resolveProviderAndModelMock = vi.fn();+const runPromptThroughProviderMock = vi.fn();+vi.mock('../lib/promptRunner.js', () => ({+ runPromptThroughProvider: (...a) => runPromptThroughProviderMock(...a),+ resolveProviderAndModel: (...a) => resolveProviderAndModelMock(...a),+}));++const svc = await import('./universeBuilder.js');+const autoSortSvc = await import('./universeBuilderAutoSort.js');++const seedUniverseWithBuckets = async (categories) => {+ const w = await svc.createUniverse({+ name: 'Test Universe',+ starterPrompt: 'test seed',+ influences: { embrace: ['cel-shading'], avoid: ['lowres'] },+ });+ return svc.updateUniverse(w.id, { categories });+};++const mockLlmClassifications = (classifications) => {+ runPromptThroughProviderMock.mockResolvedValue({+ text: JSON.stringify({ classifications }),+ runId: 'run-autosort-1',+ model: 'mock-default',+ });+};++beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ resolveProviderAndModelMock.mockReset();+ runPromptThroughProviderMock.mockReset();+ resolveProviderAndModelMock.mockResolvedValue({+ provider: { id: 'provider-mock', name: 'Mock', type: 'api', defaultModel: 'mock-default' },+ selectedModel: 'mock-default',+ });+});++describe('universeBuilderAutoSort — happy path', () => {+ it('classifies every other-kinded bucket and applies kinds via one patch', async () => {+ const w = await seedUniverseWithBuckets({+ colonies: {+ // sanitizer defaults to 'other' when kind absent + key not in defaults map.+ variations: [{ label: 'Foundry Prime', prompt: 'industrial colony' }],+ },+ factions: {+ variations: [{ label: 'The Bone Harvesters', prompt: 'desert raider clan' }],+ },+ relics: {+ variations: [{ label: 'Sun Crown', prompt: 'glass crown' }],+ },+ });+ // Sanity: all three start as 'other'+ expect(w.categories.colonies.kind).toBe('other');+ expect(w.categories.factions.kind).toBe('other');+ expect(w.categories.relics.kind).toBe('other');++ mockLlmClassifications([+ { key: 'colonies', kind: 'settings' },+ { key: 'factions', kind: 'characters' },+ { key: 'relics', kind: 'objects' },+ ]);++ const result = await autoSortSvc.autoSortOtherBuckets(w.id, {+ providerId: 'p-explicit',+ model: 'm-explicit',+ });++ expect(resolveProviderAndModelMock).toHaveBeenCalledWith({ providerId: 'p-explicit', model: 'm-explicit' });+ expect(result.results).toEqual([+ { sourceKey: 'colonies', kind: 'settings', suggestedKey: null },+ { sourceKey: 'factions', kind: 'characters', suggestedKey: null },+ { sourceKey: 'relics', kind: 'objects', suggestedKey: null },+ ]);+ expect(result.universe.categories.colonies.kind).toBe('settings');+ expect(result.universe.categories.factions.kind).toBe('characters');+ expect(result.universe.categories.relics.kind).toBe('objects');+ // Variations are preserved through the patch — the bucket itself moves+ // trunks but its contents stay.+ expect(result.universe.categories.colonies.variations).toHaveLength(1);+ expect(result.universe.categories.factions.variations[0].label).toBe('The Bone Harvesters');+ expect(result.runId).toBe('run-autosort-1');+ expect(result.llm.provider).toBe('provider-mock');+ });++ it('short-circuits with no LLM call when no other-kinded buckets exist', async () => {+ const w = await seedUniverseWithBuckets({+ landscapes: {+ kind: 'settings',+ variations: [{ label: 'Crystalline canyon', prompt: 'salt flats' }],+ },+ });+ const result = await autoSortSvc.autoSortOtherBuckets(w.id);+ expect(result.results).toEqual([]);+ expect(result.runId).toBeNull();+ expect(runPromptThroughProviderMock).not.toHaveBeenCalled();+ expect(resolveProviderAndModelMock).not.toHaveBeenCalled();+ });++ it('leaves non-other buckets untouched in the patch', async () => {+ const w = await seedUniverseWithBuckets({+ landscapes: {+ kind: 'settings',+ variations: [{ label: 'Crystalline canyon', prompt: 'salt flats' }],+ },+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'industrial colony' }],+ },+ });+ mockLlmClassifications([+ { key: 'colonies', kind: 'settings' },+ ]);++ const result = await autoSortSvc.autoSortOtherBuckets(w.id);++ // The settings-kinded `landscapes` bucket is preserved exactly.+ expect(result.universe.categories.landscapes.kind).toBe('settings');+ expect(result.universe.categories.landscapes.variations[0].label).toBe('Crystalline canyon');+ expect(result.universe.categories.colonies.kind).toBe('settings');+ });+});++describe('universeBuilderAutoSort — suggested rename surfacing', () => {+ it('returns suggestedKey on the result without auto-applying it', async () => {+ const w = await seedUniverseWithBuckets({+ stuff: {+ variations: [{ label: 'Plasma Lance', prompt: 'energy weapon' }],+ },+ });+ mockLlmClassifications([+ { key: 'stuff', kind: 'objects', suggestedKey: 'weapons' },+ ]);++ const result = await autoSortSvc.autoSortOtherBuckets(w.id);++ expect(result.results).toEqual([+ { sourceKey: 'stuff', kind: 'objects', suggestedKey: 'weapons' },+ ]);+ // Bucket is still `stuff` — rename not auto-applied.+ expect(result.universe.categories.stuff).toBeDefined();+ expect(result.universe.categories.stuff.kind).toBe('objects');+ expect(result.universe.categories.weapons).toBeUndefined();+ });++ it('drops suggestedKey when normalized form matches the source', async () => {+ const w = await seedUniverseWithBuckets({+ vehicles_extra: {+ variations: [{ label: 'Salvage Mech', prompt: 'mech' }],+ },+ });+ mockLlmClassifications([+ // LLM returns a "rename" that just re-cases the original — should drop.+ { key: 'vehicles_extra', kind: 'objects', suggestedKey: 'Vehicles Extra' },+ ]);++ const result = await autoSortSvc.autoSortOtherBuckets(w.id);+ expect(result.results[0].suggestedKey).toBeNull();+ });+});++describe('universeBuilderAutoSort — LLM-shaped failures', () => {+ it('drops classifications for keys not in the input list', async () => {+ const w = await seedUniverseWithBuckets({+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],+ },+ });+ mockLlmClassifications([+ { key: 'colonies', kind: 'settings' },+ { key: 'hallucinated_bucket', kind: 'characters' },+ ]);++ const result = await autoSortSvc.autoSortOtherBuckets(w.id);+ expect(result.results.map((r) => r.sourceKey)).toEqual(['colonies']);+ expect(result.universe.categories.hallucinated_bucket).toBeUndefined();+ });++ it('throws UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS when no input bucket was classified', async () => {+ const w = await seedUniverseWithBuckets({+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],+ },+ });+ mockLlmClassifications([+ { key: 'hallucinated_only', kind: 'settings' },+ ]);+ await expect(+ autoSortSvc.autoSortOtherBuckets(w.id),+ ).rejects.toMatchObject({ status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' });+ });++ it('rejects with LLM_INVALID_JSON when the response has no parseable JSON', async () => {+ const w = await seedUniverseWithBuckets({+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],+ },+ });+ runPromptThroughProviderMock.mockResolvedValue({+ text: 'i could not classify anything',+ runId: 'run-bad-1',+ model: 'mock-default',+ });+ await expect(+ autoSortSvc.autoSortOtherBuckets(w.id),+ ).rejects.toMatchObject({ status: 502, code: 'LLM_INVALID_JSON' });+ });++ it('treats invalid kinds as no-classifications (shape-predicate fallback drops them)', async () => {+ // extractJson returns the first parseable block as a fallback even when+ // shapePredicate fails; the service then filters per-entry kinds and+ // throws NO_CLASSIFICATIONS when nothing valid survives. Pin this so a+ // future change to the extractor fallback doesn't silently start+ // accepting `kind: 'magic'` into the patch.+ const w = await seedUniverseWithBuckets({+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],+ },+ });+ runPromptThroughProviderMock.mockResolvedValue({+ text: '{"classifications": [{"key": "colonies", "kind": "magic"}]}',+ runId: 'run-bad-2',+ model: 'mock-default',+ });+ await expect(+ autoSortSvc.autoSortOtherBuckets(w.id),+ ).rejects.toMatchObject({ status: 502, code: 'UNIVERSE_AUTOSORT_NO_CLASSIFICATIONS' });+ });++ it('rejects when no AI provider is available', async () => {+ const w = await seedUniverseWithBuckets({+ colonies: {+ variations: [{ label: 'Foundry Prime', prompt: 'colony' }],+ },+ });+ resolveProviderAndModelMock.mockResolvedValue({ provider: null, selectedModel: null });++ await expect(+ autoSortSvc.autoSortOtherBuckets(w.id),+ ).rejects.toMatchObject({ status: 503, code: 'UNIVERSE_AUTOSORT_NO_PROVIDER' });+ expect(runPromptThroughProviderMock).not.toHaveBeenCalled();+ });+});++describe('universeBuilderAutoSort — prompt + shape helpers', () => {+ it('isClassificationsShape only accepts arrays of valid records', () => {+ const { isClassificationsShape } = autoSortSvc.__testing;+ expect(isClassificationsShape({ classifications: [{ key: 'a', kind: 'characters' }] })).toBe(true);+ expect(isClassificationsShape({ classifications: [{ key: 'a', kind: 'other' }] })).toBe(false);+ expect(isClassificationsShape({ classifications: 'nope' })).toBe(false);+ expect(isClassificationsShape({})).toBe(false);+ expect(isClassificationsShape(null)).toBe(false);+ });++ it('buildAutoSortPrompt includes bucket keys and the first N variation labels', () => {+ const { buildAutoSortPrompt } = autoSortSvc.__testing;+ const variations = Array.from({ length: 15 }, (_, i) => ({ label: `Variation ${i}`, prompt: `p${i}` }));+ const prompt = buildAutoSortPrompt({+ buckets: [{ key: 'colonies', variations }],+ universe: { logline: 'A frontier civilization', influences: { embrace: ['retro'] } },+ });+ expect(prompt).toContain('## colonies');+ expect(prompt).toContain('Variation 0');+ expect(prompt).toContain('Variation 9');+ // Sample cap is 10 — variation 10+ shouldn't appear.+ expect(prompt).not.toContain('Variation 10');+ expect(prompt).toContain('LOGLINE: A frontier civilization');+ expect(prompt).toContain('EMBRACE INFLUENCES: retro');+ });+});