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
add a quota-burn job that describes under-described universe bible entries before images are rendered
[._.]/ Adam Eivydd88ca2f8dc7
diff --git a/.changelog/next/added-agent-f1c8f4b0.md b/.changelog/next/added-agent-f1c8f4b0.mdnew file mode 100644index 0000000000..6de1b19538--- /dev/null+++ b/.changelog/next/added-agent-f1c8f4b0.md@@ -0,0 +1 @@+- Quota burn can now describe universe bible entries before rendering them: a new `universe-bible-describe` job fills blank fields on under-described entries — the full character sheet for cast, description plus world detail for places and objects — pinned to the burning provider family. The image job gained an opt-in "skip canon entries that have no description yet" so the two can be ordered describe then render.diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex 7358e8449e..6c1541bd39 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -611,6 +611,13 @@"returnsJson": true,"variables": []},+ "universe-canon-entry-expand": {+ "name": "Universe — Expand Place / Object Entry",+ "description": "Flesh out blank fields on one universe canon place or object — description, palette / era / weather / recurring details for a place, description + significance for an object. Preserves populated fields and stays distinct from peer entries of the same kind.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"importer-classify": {"name": "Importer — Content-Type Classification","description": "Classify the first chunk of a source as short-story / novel / screenplay / comic-script. Runs at `light` tier — only sees ~4K chars from the head of the source, costs are negligible compared to the canon/arc/issue extractors.",diff --git a/data.reference/prompts/stages/universe-canon-entry-expand.md b/data.reference/prompts/stages/universe-canon-entry-expand.mdnew file mode 100644index 0000000000..38cbf3e5f7--- /dev/null+++ b/data.reference/prompts/stages/universe-canon-entry-expand.md@@ -0,0 +1,65 @@+# Universe — Expand Place / Object Entry++You are fleshing out one canon entry in a story universe so a novelist and a graphic novelist both have everything they need to write and render it consistently.++This entry's kind is: **{{kind}}**++## Universe style / aesthetic++{{styleClause}}++## The entry++Current data — fields that are already populated MUST be preserved verbatim. Only fill BLANK fields. Empty string `""` or `null` means blank.++```json+{{entryJson}}+```++## Other entries of the same kind in this universe (peers — DO NOT collide)++```json+{{peersJson}}+```++## Task++For every BLANK field below that applies to this entry's kind, propose a value that:++1. **Fits the universe's aesthetic** and whatever the entry already establishes.+2. **Stays distinct from every peer.** Two taverns must not share a palette; two relics must not share a silhouette or a purpose.+3. **Reads as image-gen-ready prose** for the descriptive fields. Dense, specific, single paragraphs. No bullet points inside string values.+4. **Invents nothing that contradicts** an already-populated field.++### Field guidance — `place`++- `description` — 50–100 words of stable, concrete, image-generation identity: scale, architecture or terrain, materials, light quality, signature fixtures, state of repair, and what the space is FOR. Never substitute the location's name for visible detail.+- `palette` — the dominant colors and their sources ("sodium-orange street light on wet slate; brass fittings; oxidized copper trim").+- `era` — the period the built environment reads as ("late-industrial, retrofitted"; "pre-collapse arcology"; "timeless — no visible technology").+- `weather` — the ambient conditions the location is usually seen in ("perpetual low fog off the estuary; rain three days in four").+- `recurringDetails` — the small persistent things a reader should recognize across scenes ("the cracked third step; the noticeboard nobody clears; a radio always half a station off").+- `intExt` — exactly `INT` or `EXT`. Pick the one the location is predominantly shot in. Omit if genuinely both.+- `timeOfDay` — exactly one of `dawn`, `day`, `dusk`, `night` — the location's signature hour. Omit if it has none.++### Field guidance — `object`++- `description` — 50–100 words of stable, concrete, image-generation identity: size in the hand or in the room, materials, finish and wear, markings, mechanism, how it moves or sounds. Never substitute the object's name for visible detail.+- `significance` — what the object MEANS in the story: who wants it, what it costs to hold, and what its presence in a scene signals. 2–4 sentences.++## Output contract++Return ONLY valid JSON, no markdown fence, no commentary. Include ONLY the keys you are proposing values for — if a field is already populated, or does not apply to this entry's kind, or you have nothing meaningful to add, OMIT the key entirely. Do not echo unchanged values.++```json+{+ "description": "string",+ "palette": "string",+ "era": "string",+ "weather": "string",+ "recurringDetails": "string",+ "intExt": "INT | EXT",+ "timeOfDay": "dawn | day | dusk | night",+ "significance": "string",+ "rationale": "1-sentence summary of the direction you chose"+}+```diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex 5cf65187fb..a8cf5d5b43 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -116,8 +116,55 @@ its own type, optional model/provider pin, and type-specific params.| Job type | What it does || --- | --- || `agent-prompt` | Queues a CoS agent in a named managed app with a custom prompt. Visible in the CoS queue and Active Agents like any other task. |+| `universe-bible-describe` | **Programmatic** — no agent. Sends one headless expand prompt per under-described bible entry, pinned to the burning family's own CLI/TUI provider. || `universe-bible-images` | **Programmatic** — no agent. Enqueues renders for universe bible entries whose `imageRefs[]` is empty. Render backend defaults to the burning family's own image mode, so a codex burn spends codex's image quota. |+### Describe before you render++`universe-bible-describe` is the step that belongs **before** `universe-bible-images`+in a plan. An image rendered from a character row holding only a name is a+generic figure that has to be thrown away — and it has already spent the image+quota. Ordering the two describe→images in the family's rotation walks the+backlog into shape first, then renders from something worth rendering.++The job's `depth` param picks what "described" means, per+`server/lib/universeBibleCompleteness.js`:++- **`core`** — the entry is unusable without these: a character's+ `physicalDescription` / `personality` / `background` / `motivations` /+ `visualNotes`; a place's or object's `description`.+- **`full`** (default) — the whole sheet. For a character that is every field the+ character-sheet expand prompt fills: the visual set (silhouette, posture,+ palette, props, expressions, hand gestures, wardrobes), the novelist set+ (likes, mannerisms, relationships, skills), and the Ghost → Wound → Lie → Want+ → Need framework with its arc type and sliders. `full` is the default because+ the job exists for the sheet — a cast member with a one-line description still+ renders inconsistently from panel to panel.++Cast is the point but not the whole scope: places and objects run through+`universe-canon-entry-expand` (description, palette/era/weather/recurring details+for a place; description + significance for an object). Category variations and+composite sheets are **out of scope** — their sanitizer already requires a+prompt, so one cannot exist undescribed.++Picks are ordered by the FRACTION of an entry's own sheet that is blank, not the+raw gap count. Raw counts would rank by kind: a character sheet has ~31 fields+and an object two, so every half-written character would outrank a completely+blank object forever and a large cast would starve the rest of the bible.++Two things bound the spend. Locked entries are never picked (an expand on one+returns without an LLM call). And every **attempted** entry — including the ones+the model declined to fill — is stamped into the shared in-flight ledger for its+6-hour TTL: at `full` depth some fields are legitimately meant to stay blank (the+prompt tells the model to leave the Ghost→Need chain alone for a bit-player), so+an entry can be permanently "incomplete", and without the stamp the plan would+re-pick the same handful every tick and never reach the rest.++The image job's opt-in `requireDescribed` is the other half of the pairing: with+it on, canon entries with no `core` description are held out of the render+backlog until the describe job has been through them. It defaults **off**, so an+existing plan keeps rendering exactly the backlog it rendered yesterday.+### Repeating vs one-shot work (`runOnce`)A plan is a **rotation**: the walk resumes after the family's last dispatch@@ -285,6 +332,7 @@ folds those overrides into the single plan (each app's family prompt becomes an| File | Role || --- | --- || `server/lib/quotaBurnConfig.js` | Plan shape, job-type catalog, total normalization |+| `server/lib/universeBibleCompleteness.js` | What "described" means per kind + depth — the field vocabulary the describe job scans with || `server/lib/quotaBurnPresets.js` | Ready-made single-focus audit prompts for `agent-prompt` jobs || `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) || `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log |diff --git a/scripts/migrations/264-universe-canon-entry-expand-stage.js b/scripts/migrations/264-universe-canon-entry-expand-stage.jsnew file mode 100644index 0000000000..477541b6b5--- /dev/null+++ b/scripts/migrations/264-universe-canon-entry-expand-stage.js@@ -0,0 +1,14 @@+/**+ * Seed the `universe-canon-entry-expand` stage into existing installs.+ *+ * Boot runs migrations but NOT `setup-data.js`, so an upgrade that pulls ++ * `pm2 restart`s would otherwise leave the new place/object expand stage+ * unseeded — and the quota-burn "describe bible entries" job would throw+ * "Stage not found" the first time it picked a place or an object.+ * Custom prompts/config are preserved by the shared seed helper; only missing+ * files and config entries are added.+ */++import { makeSeedMigration } from './_seedStageHelpers.js';++export default makeSeedMigration('universe-canon-entry-expand');diff --git a/scripts/migrations/264-universe-canon-entry-expand-stage.test.js b/scripts/migrations/264-universe-canon-entry-expand-stage.test.jsnew file mode 100644index 0000000000..31d316a65e--- /dev/null+++ b/scripts/migrations/264-universe-canon-entry-expand-stage.test.js@@ -0,0 +1,12 @@+import { describe } from 'vitest';++import migration from './264-universe-canon-entry-expand-stage.js';+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';++describe('migration 264 — seed the universe canon place/object expand stage', () => {+ runSeedStageMigrationTests({+ migration,+ stages: ['universe-canon-entry-expand'],+ prefix: 'migration-264-universe-canon-entry-expand-',+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex a1a602cb6f..12931ee66f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -88,6 +88,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. || `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. || `creativeDirectorPrompts.js` | Creative Director agent prompt builders. |+| `universeBibleCompleteness.js` | "Is this bible entry actually described?" — `BIBLE_EXPAND_FIELDS` (every field the per-kind expand prompt can fill, grouped by storage shape; the SOURCE for `universeCharacterExpand`'s `STRING_FIELDS`/`LIST_FIELDS`), `BIBLE_CORE_FIELDS`, and the predicates the quota-burn describe job scans with: `missingBibleFields` / `bibleEntryIsDescribed` / `bibleEntryCompleteness` / `bibleFieldIsBlank`, at `core` or `full` depth. Pure. || `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context. || `writersRoomPresets.js` | Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS). || `writersRoomStylePresets.js` | Curated style presets for storyboards + universe. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 7d6fb2b7f3..037da6e734 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -84,6 +84,7 @@ export * from './streamLines.js';// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for// back-compat — namespace it so the canonical scenePrompt export wins flat.export * as storyBible from './storyBible.js';+export * from './universeBibleCompleteness.js';export * from './universePromptRenderers.js';export * from './writersRoomPresets.js';export * from './writersRoomStylePresets.js';diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.jsonindex afc1d416ec..ded02766f6 100644--- a/server/lib/promptStageCallSites.generated.json+++ b/server/lib/promptStageCallSites.generated.json@@ -374,6 +374,10 @@"twin-trait-extractor": ["server/services/digital-twin-analysis.js"],+ "universe-canon-entry-expand": [+ "server/services/universeCanon.js",+ "server/services/universeCanonEntryExpand.js"+ ],"universe-character-expand": ["server/services/universeCharacterExpand.js"],diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.jsindex bcfeb66b4a..162ebffb5d 100644--- a/server/lib/quotaBurnConfig.js+++ b/server/lib/quotaBurnConfig.js@@ -23,6 +23,7 @@*/import { isPlainObject, POLLUTING_KEYS } from './objects.js';+import { BIBLE_DESCRIBE_DEPTHS } from './universeBibleCompleteness.js';/** Provider quota families a burn plan may target. Mirrors `providerUsage.js`'s card ids. */export const QUOTA_BURN_FAMILIES = Object.freeze(['claude', 'codex', 'agy', 'grok']);@@ -110,6 +111,7 @@ export const isUnlimitedDispatchCap = (cap) => Number(cap) < 0;*/export const QUOTA_BURN_JOB_TYPE = Object.freeze({AGENT_PROMPT: 'agent-prompt',+ UNIVERSE_BIBLE_DESCRIBE: 'universe-bible-describe',UNIVERSE_BIBLE_IMAGES: 'universe-bible-images',});export const QUOTA_BURN_JOB_TYPES = Object.freeze(Object.values(QUOTA_BURN_JOB_TYPE));@@ -149,6 +151,21 @@ export const QUOTA_BURN_JOB_CATALOG = Object.freeze([{ key: 'discardWorktree', kind: 'boolean', label: 'Discard the worktree (nothing lands)', default: false },]),},+ {+ id: QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_DESCRIBE,+ label: 'Universe bible descriptions',+ description: 'Fill in blank fields on universe bible entries — the full character sheet for cast, description + world detail for places and objects. No agent; PortOS sends one expand prompt per entry. Order this BEFORE the image job so renders have something to work from.',+ programmatic: true,+ params: Object.freeze([+ { key: 'universeId', kind: 'universe', label: 'Universe', default: 'all', emptyLabel: 'All universes', emptyValue: 'all' },+ { key: 'scope', kind: 'enum', label: 'Entries', options: ['all', 'characters', 'places', 'objects'], default: 'all' },+ // `full` is the default because the job exists for the sheet, not the+ // one-line description: a cast member with a description and nothing else+ // still renders inconsistently from panel to panel.+ { key: 'depth', kind: 'enum', label: 'Depth', options: BIBLE_DESCRIBE_DEPTHS, default: 'full' },+ { key: 'maxEntries', kind: 'number', label: 'Max entries per run', min: BOUNDS.maxEntries.min, max: BOUNDS.maxEntries.max, default: BOUNDS.maxEntries.default },+ ]),+ },{id: QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_IMAGES,label: 'Universe bible images',@@ -159,6 +176,11 @@ export const QUOTA_BURN_JOB_CATALOG = Object.freeze([{ key: 'scope', kind: 'enum', label: 'Entries', options: ['all', 'variations', 'canon', 'sheets'], default: 'all' },{ key: 'maxEntries', kind: 'number', label: 'Max entries per run', min: BOUNDS.maxEntries.min, max: BOUNDS.maxEntries.max, default: BOUNDS.maxEntries.default },{ key: 'mode', kind: 'imageMode', label: 'Render backend', default: null, emptyLabel: 'Match the burning provider', emptyValue: '' },+ // Opt-IN, and default `false`, so an existing plan keeps rendering exactly+ // the backlog it rendered yesterday. Turning it on pairs this job with the+ // describe job above: canon entries that are still blank wait for a+ // description instead of spending image quota on a generic render.+ { key: 'requireDescribed', kind: 'boolean', label: 'Skip canon entries that have no description yet', default: false },]),},]);diff --git a/server/lib/universeBibleCompleteness.js b/server/lib/universeBibleCompleteness.jsnew file mode 100644index 0000000000..d9d698d194--- /dev/null+++ b/server/lib/universeBibleCompleteness.js@@ -0,0 +1,164 @@+/**+ * "Is this bible entry actually described?" — the one field vocabulary the+ * describe automation, the character/canon expand services, and the image jobs+ * all measure completeness against.+ *+ * A universe bible entry can be *present* without being *usable*: a character+ * row with a name and nothing else renders a generic figure, and a place with a+ * blank description renders whatever the model felt like. The quota-burn+ * describe job exists to close that gap before any image quota is spent on it,+ * which needs a definition of "described" that does not live in the job.+ *+ * Two depths, because the two questions are different:+ * - `core` — the minimum for the entry to render or be written at all.+ * - `full` — the whole sheet: everything the expand prompts can fill, which+ * for a character is the character-sheet field set a novelist ++ * graphic novelist both need.+ *+ * Pure module: shape and predicates only, no storage and no provider I/O, so the+ * burn job (which must not import the universe store to answer "how many are+ * missing"), the expand services, and the tests all agree on one list. The+ * character lists are the SOURCE for `universeCharacterExpand.js`'s+ * `STRING_FIELDS` / `LIST_FIELDS` — a field the expand prompt fills but this+ * module doesn't know about would be permanently invisible to the completeness+ * scan, so the two are deliberately one list rather than two that agree today.+ */++/** Depth vocabulary. `core` = renderable at all; `full` = the whole sheet. */+export const BIBLE_DESCRIBE_DEPTHS = Object.freeze(['core', 'full']);++/** The three slider axes, all of which must be rated for `sliders` to count as filled. */+const SLIDER_AXES = Object.freeze(['proactivity', 'likability', 'competence']);++/**+ * Every field the per-kind expand prompt may fill, grouped by how it is stored.+ * The grouping is what lets one merge helper handle all three kinds:+ * - `strings` — plain prose, blank when empty/whitespace+ * - `lists` — arrays of sanitized rows, blank when empty+ * - `enums` — a single constrained token, blank when unset (null)+ * - `objects` — structured records with their own "is it filled" rule+ */+export const BIBLE_EXPAND_FIELDS = Object.freeze({+ character: Object.freeze({+ strings: Object.freeze([+ 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern',+ 'physicalDescription', 'personality', 'background', 'visualNotes',+ 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity',+ 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',+ // Character framework (CWQE Phase 10, #2175) — the Ghost → Wound → Lie →+ // Want → Need chain. `arcType` and `sliders` are the structured half.+ 'ghost', 'wound', 'lie', 'want', 'need',+ ]),+ lists: Object.freeze([+ 'stats', 'colorPalette', 'props', 'expressions', 'handGestures',+ 'wardrobes', 'secrets',+ ]),+ enums: Object.freeze(['arcType']),+ objects: Object.freeze(['sliders']),+ }),+ place: Object.freeze({+ strings: Object.freeze(['description', 'palette', 'era', 'weather', 'recurringDetails']),+ lists: Object.freeze([]),+ enums: Object.freeze(['intExt', 'timeOfDay']),+ objects: Object.freeze([]),+ }),+ object: Object.freeze({+ strings: Object.freeze(['description', 'significance']),+ lists: Object.freeze([]),+ enums: Object.freeze([]),+ objects: Object.freeze([]),+ }),+});++/**+ * The `core` set per kind — what an entry needs before it is worth rendering.+ *+ * Deliberately short. `core` gates the image job's opt-in "skip entries nobody+ * has described yet" filter, and a long core list there would park most of a+ * young universe's backlog behind an LLM pass the user may not want.+ */+export const BIBLE_CORE_FIELDS = Object.freeze({+ character: Object.freeze(['physicalDescription', 'personality', 'background', 'motivations', 'visualNotes']),+ place: Object.freeze(['description']),+ object: Object.freeze(['description']),+});++/** Canon kinds this module knows how to measure. Mirrors `storyBible.BIBLE_KINDS`. */+export const BIBLE_DESCRIBE_KINDS = Object.freeze(Object.keys(BIBLE_EXPAND_FIELDS));++/**+ * `relationshipLinks` (characters) and `attachments` (objects) are INTENTIONALLY+ * absent from every list above: each row points at a sibling entry by id, which+ * an expand call has no way to mint. They are authored in the UI, so counting+ * them as "missing" would make every entry permanently incomplete.+ */++const requiredFields = (kind, depth) => {+ const groups = BIBLE_EXPAND_FIELDS[kind];+ if (!groups) return [];+ if (depth === 'core') return BIBLE_CORE_FIELDS[kind] || [];+ return [...groups.strings, ...groups.lists, ...groups.enums, ...groups.objects];+};++/**+ * A character's canonical description lives in `physicalDescription`; migration+ * 019 rewrites the legacy `description` alias forward but the read-side fallback+ * stays, so a pre-migration entry must not read as blank here (it would be+ * re-described on top of text it already has).+ */+const FIELD_VALUE = Object.freeze({+ physicalDescription: (entry) => entry?.physicalDescription || entry?.description || '',+});++/**+ * Per-field "is this still blank" overrides. Everything else falls through to+ * the string/array rule below: `sliders` is an always-present object whose axes+ * are individually null until rated, so plain presence would report it filled+ * the moment the sanitizer materialized it.+ */+const FIELD_IS_BLANK = Object.freeze({+ sliders: (value) => !value || typeof value !== 'object' || SLIDER_AXES.some((axis) => value[axis] == null),+});++const isBlankValue = (value) => (Array.isArray(value)+ ? value.length === 0+ : (typeof value !== 'string' || value.trim() === ''));++/** Whether ONE field on an entry is still unfilled. Exported for the expand merges. */+export function bibleFieldIsBlank(entry, field) {+ const value = FIELD_VALUE[field] ? FIELD_VALUE[field](entry) : entry?.[field];+ return (FIELD_IS_BLANK[field] || isBlankValue)(value);+}++/** Normalize an untrusted depth param to a known depth, defaulting to `full`. */+export const normalizeDescribeDepth = (depth) =>+ (BIBLE_DESCRIBE_DEPTHS.includes(depth) ? depth : 'full');++/**+ * The fields still blank on `entry`, in the canonical order the expand prompt+ * lists them. Empty array means the entry is described to that depth.+ */+export function missingBibleFields(kind, entry, { depth = 'full' } = {}) {+ if (!entry || typeof entry !== 'object') return [];+ return requiredFields(kind, normalizeDescribeDepth(depth)).filter((field) => bibleFieldIsBlank(entry, field));+}++/** Whether `entry` has every field the depth asks for. */+export const bibleEntryIsDescribed = (kind, entry, options) =>+ missingBibleFields(kind, entry, options).length === 0;++/**+ * Completeness as a ratio plus the gap list — what the describe job reports and+ * what orders its picks (the emptiest entries first, so a capped run spends its+ * budget where it buys the most).+ */+export function bibleEntryCompleteness(kind, entry, { depth = 'full' } = {}) {+ const required = requiredFields(kind, normalizeDescribeDepth(depth));+ const missing = missingBibleFields(kind, entry, { depth });+ return {+ required: required.length,+ missing,+ filled: required.length - missing.length,+ complete: missing.length === 0,+ };+}diff --git a/server/lib/universeBibleCompleteness.test.js b/server/lib/universeBibleCompleteness.test.jsnew file mode 100644index 0000000000..e5358d9c17--- /dev/null+++ b/server/lib/universeBibleCompleteness.test.js@@ -0,0 +1,110 @@+import { describe, expect, it } from 'vitest';++import {+ BIBLE_CORE_FIELDS,+ BIBLE_EXPAND_FIELDS,+ bibleEntryCompleteness,+ bibleEntryIsDescribed,+ bibleFieldIsBlank,+ missingBibleFields,+ normalizeDescribeDepth,+} from './universeBibleCompleteness.js';++const describedCharacter = () => {+ const groups = BIBLE_EXPAND_FIELDS.character;+ const entry = { id: 'c1', name: 'Alice' };+ for (const field of groups.strings) entry[field] = `${field} text`;+ for (const field of groups.lists) entry[field] = [{ name: 'x' }];+ entry.arcType = 'positive';+ entry.sliders = { proactivity: 7, likability: 6, competence: 8 };+ return entry;+};++describe('missingBibleFields', () => {+ it('reports every unfilled character-sheet field at full depth', () => {+ const missing = missingBibleFields('character', { id: 'c1', name: 'Alice' });+ const groups = BIBLE_EXPAND_FIELDS.character;+ expect(missing).toHaveLength(+ groups.strings.length + groups.lists.length + groups.enums.length + groups.objects.length,+ );+ expect(missing).toContain('physicalDescription');+ expect(missing).toContain('colorPalette');+ expect(missing).toContain('sliders');+ });++ it('reports nothing for a fully-sheeted character', () => {+ expect(missingBibleFields('character', describedCharacter())).toEqual([]);+ expect(bibleEntryIsDescribed('character', describedCharacter())).toBe(true);+ });++ it('core depth asks only for what makes an entry renderable', () => {+ const core = {+ id: 'c1',+ name: 'Alice',+ physicalDescription: 'a', personality: 'b', background: 'c', motivations: 'd', visualNotes: 'e',+ };+ expect(missingBibleFields('character', core, { depth: 'core' })).toEqual([]);+ // The same entry is still far from a finished sheet.+ expect(missingBibleFields('character', core, { depth: 'full' }).length).toBeGreaterThan(10);+ });++ it('treats a character with only the legacy `description` alias as described', () => {+ // Migration 019 rewrites `description` → `physicalDescription`, but the+ // read-side fallback stays. Without it a pre-migration entry reads as blank+ // and gets re-described on top of text it already has.+ expect(bibleFieldIsBlank({ description: 'weathered, tall' }, 'physicalDescription')).toBe(false);+ expect(missingBibleFields('place', { description: 'a foundry' }, { depth: 'core' })).toEqual([]);+ });++ it('counts a partly-rated sliders object as unfilled', () => {+ // `sliders` is always present after sanitization with null axes, so plain+ // presence would report it filled the moment the record was written.+ expect(bibleFieldIsBlank({ sliders: { proactivity: 7, likability: null, competence: 3 } }, 'sliders')).toBe(true);+ expect(bibleFieldIsBlank({ sliders: { proactivity: 7, likability: 2, competence: 3 } }, 'sliders')).toBe(false);+ });++ it('never asks for id-bearing link fields an expand call cannot mint', () => {+ const all = Object.values(BIBLE_EXPAND_FIELDS).flatMap((groups) => [+ ...groups.strings, ...groups.lists, ...groups.enums, ...groups.objects,+ ]);+ expect(all).not.toContain('relationshipLinks');+ expect(all).not.toContain('attachments');+ });++ it('reports nothing for an unknown kind or a non-object entry', () => {+ expect(missingBibleFields('sandwich', { name: 'x' })).toEqual([]);+ expect(missingBibleFields('character', null)).toEqual([]);+ });+});++describe('bibleEntryCompleteness', () => {+ it('reports the gap size the describe job orders its picks by', () => {+ const empty = bibleEntryCompleteness('place', { id: 'p1' });+ const partial = bibleEntryCompleteness('place', { id: 'p2', description: 'a foundry', era: 'late-industrial' });+ expect(empty.filled).toBe(0);+ expect(partial.filled).toBe(2);+ expect(partial.missing.length).toBeLessThan(empty.missing.length);+ expect(empty.complete).toBe(false);+ });+});++describe('normalizeDescribeDepth', () => {+ it('defaults an unknown depth to full rather than silently narrowing the ask', () => {+ expect(normalizeDescribeDepth('core')).toBe('core');+ expect(normalizeDescribeDepth('full')).toBe('full');+ expect(normalizeDescribeDepth('deep')).toBe('full');+ expect(normalizeDescribeDepth(undefined)).toBe('full');+ });+});++describe('core sets', () => {+ it('are a subset of what the expand prompts can actually fill', () => {+ for (const [kind, fields] of Object.entries(BIBLE_CORE_FIELDS)) {+ const groups = BIBLE_EXPAND_FIELDS[kind];+ const fillable = new Set([...groups.strings, ...groups.lists, ...groups.enums, ...groups.objects]);+ // A core field the expand prompt cannot fill would make the entry+ // permanently under-described and re-picked on every burn cycle.+ for (const field of fields) expect(fillable.has(field)).toBe(true);+ }+ });+});diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.jsindex 3d9fb95066..c331f099fc 100644--- a/server/services/quotaBurnJobs/agentPrompt.js+++ b/server/services/quotaBurnJobs/agentPrompt.js@@ -21,15 +21,21 @@ import { windowLabelOf } from '../../lib/quotaWindows.js';/*** An agent-capable provider in the burning family. A job's explicit* `providerId` wins; otherwise match the family id against the enabled- * providers, PREFERRING the TUI.+ * providers, PREFERRING the type named by `prefer` (default `tui`).*- * Preferring the TUI is the point: a burn runs unattended for minutes on the- * user's own subscription, and a TUI agent is watchable in Active Agents and can- * be steered mid-run, where a headless CLI run can only be read after it has- * finished. Most families have both registered (`claude-code` + `claude-code-tui`,- * `codex` + `codex-tui`, …) and the CLI sorts first, so a plain `find` silently- * picked the unobservable one every time. `pickScrapeProvider` applies the same- * preference when reading `/usage`.+ * Preferring the TUI is the point for an AGENT burn: it runs unattended for+ * minutes on the user's own subscription, and a TUI agent is watchable in Active+ * Agents and can be steered mid-run, where a headless CLI run can only be read+ * after it has finished. Most families have both registered (`claude-code` ++ * `claude-code-tui`, `codex` + `codex-tui`, …) and the CLI sorts first, so a+ * plain `find` silently picked the unobservable one every time.+ * `pickScrapeProvider` applies the same preference when reading `/usage`.+ *+ * A PROGRAMMATIC job passes `prefer: 'cli'` instead: it sends one headless+ * prompt through the stage runner, with no agent session to watch or steer, so+ * the TUI's observability buys nothing and its interactive startup is pure+ * overhead. The other type is still accepted as a fallback — a family with only+ * a TUI registered must not silently stop burning.** Two exclusions, both about what a burn is FOR — spending a subscription window* that would otherwise expire unused:@@ -39,13 +45,13 @@ import { windowLabelOf } from '../../lib/quotaWindows.js';* them from the quota cards for exactly this reason; a `claude-ollama-tui`* would otherwise be a perfectly good match for the `claude` family.*/-export function providerForFamily(providers, { familyId, providerId }) {+export function providerForFamily(providers, { familyId, providerId, prefer = 'tui' }) {const available = (providers || []).filter((provider) =>provider?.enabled && provider.ollamaBacked !== true&& (provider.type === 'cli' || provider.type === 'tui'));if (providerId) return available.find((provider) => provider.id === providerId) || null;const inFamily = available.filter((provider) => matchesFamily(provider, familyId));- return inFamily.find((provider) => provider.type === 'tui') || inFamily[0] || null;+ return inFamily.find((provider) => provider.type === prefer) || inFamily[0] || null;}/**diff --git a/server/services/quotaBurnJobs/index.js b/server/services/quotaBurnJobs/index.jsindex b7fe05bbf0..321b351838 100644--- a/server/services/quotaBurnJobs/index.js+++ b/server/services/quotaBurnJobs/index.js@@ -34,6 +34,7 @@ import { QUOTA_BURN_JOB_TYPE } from '../../lib/quotaBurnConfig.js';export const JOB_MODULES = {[QUOTA_BURN_JOB_TYPE.AGENT_PROMPT]: () => import('./agentPrompt.js'),+ [QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_DESCRIBE]: () => import('./universeBibleDescribe.js'),[QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_IMAGES]: () => import('./universeBibleImages.js'),};diff --git a/server/services/quotaBurnJobs/universeBibleDescribe.js b/server/services/quotaBurnJobs/universeBibleDescribe.jsnew file mode 100644index 0000000000..b5a5f914b1--- /dev/null+++ b/server/services/quotaBurnJobs/universeBibleDescribe.js@@ -0,0 +1,242 @@+/**+ * Burn job — fill in the blanks on universe bible entries that are named but+ * not actually described.+ *+ * PROGRAMMATIC: no agent is spawned. PortOS sends one headless expand prompt per+ * entry through the stage runner, pinned to the burning family's own CLI/TUI+ * provider, so a `codex` burn spends CODEX's subscription window.+ *+ * This is the step that belongs BEFORE `universe-bible-images` in a plan: an+ * image rendered from a character row holding only a name is a generic figure+ * that has to be thrown away, and it has already spent the image quota. Order+ * the two jobs describe→images in the family's rotation (and optionally set the+ * image job's `requireDescribed`) and the backlog gets described first, then+ * rendered from something worth rendering.+ *+ * "Not described" is `lib/universeBibleCompleteness.js`'s definition, at the+ * depth the job selects:+ * - `core` — the entry is unusable without these (a character's+ * physicalDescription / personality / background / motivations / visualNotes;+ * a place's or object's description).+ * - `full` — the whole sheet, which for a character is every field the+ * character-sheet expand prompt fills.+ *+ * Category variations and composite sheets are deliberately out of scope: their+ * sanitizer already REQUIRES a prompt, so one cannot exist undescribed.+ */++import { getUniverse, listUniverses } from '../universeBuilder.js';+import { expandUniverseCharacter } from '../universeCharacterExpand.js';+import { expandUniverseCanonEntry } from '../universeCanonEntryExpand.js';+import { getAllProviders } from '../providers.js';+import { getQuotaBurnInFlight, recordQuotaBurnInFlight } from '../quotaBurnStore.js';+import { BIBLE_FIELD, BIBLE_KIND } from '../../lib/storyBible.js';+import { bibleEntryCompleteness, normalizeDescribeDepth } from '../../lib/universeBibleCompleteness.js';+import { QUOTA_BURN_BOUNDS } from '../../lib/quotaBurnConfig.js';+import { providerForFamily } from './agentPrompt.js';++/** Scope value → the canon kinds it selects. `all` walks the cast first. */+const SCOPE_KINDS = Object.freeze({+ all: [BIBLE_KIND.CHARACTER, BIBLE_KIND.PLACE, BIBLE_KIND.OBJECT],+ characters: [BIBLE_KIND.CHARACTER],+ places: [BIBLE_KIND.PLACE],+ objects: [BIBLE_KIND.OBJECT],+});++// Bounds come from the catalog descriptor the client renders its min/max from —+// hardcoding them here would let a raised cap change the accepted range in the+// form without changing what the job actually runs.+const ENTRY_BOUNDS = QUOTA_BURN_BOUNDS.maxEntries;++/**+ * One in-flight key per ENTRY (ids are unique, unlike the image job's labels),+ * namespaced so a described entry never shadows the same entry's pending render.+ */+export const describeInFlightKey = (universeId, kind, entryId) => `describe:${universeId}:${kind}:${entryId}`;++const entryLabel = (entry) => entry?.name || entry?.slugline || entry?.id || '';++/**+ * Every under-described entry in one universe, emptiest first.+ *+ * Ordering is by the FRACTION of the entry's own sheet that is blank, not the+ * raw gap count. Raw counts would rank by kind rather than by need: a character+ * sheet has ~31 fields and an object two, so every half-written character in the+ * cast would outrank a completely blank object forever, and on a large cast the+ * places and objects would simply never be reached. The absolute gap breaks+ * ties (between two equally-empty entries the bigger one buys more per call) and+ * the id breaks those, so repeated runs walk a stable backlog rather than+ * reshuffling it.+ */+export function findUnderdescribedEntries(universe, { scope = 'all', depth = 'full' } = {}) {+ const kinds = SCOPE_KINDS[scope] || SCOPE_KINDS.all;+ const rows = [];+ for (const kind of kinds) {+ for (const entry of universe?.[BIBLE_FIELD[kind]] || []) {+ // Locked entries are protected from every AI rewrite path; picking one+ // would spend a dispatch on an expand that returns `{ locked: true }`+ // without an LLM call and changes nothing.+ if (!entry?.id || entry.locked === true) continue;+ const { missing, required } = bibleEntryCompleteness(kind, entry, { depth });+ if (missing.length === 0) continue;+ rows.push({+ kind,+ id: entry.id,+ label: entryLabel(entry),+ missing: missing.length,+ required,+ blankRatio: required ? missing.length / required : 0,+ });+ }+ }+ return rows.sort((a, b) => b.blankRatio - a.blankRatio || b.missing - a.missing || a.id.localeCompare(b.id));+}++async function loadUniverses(params) {+ const id = typeof params?.universeId === 'string' ? params.universeId.trim() : '';+ if (!id || id === 'all') return listUniverses();+ // A universe deleted since the job was configured must not wedge the family —+ // report zero pending and let the next job in the plan take the window.+ return getUniverse(id).then((universe) => [universe]).catch(() => []);+}++/**+ * Rows this job would describe next, plus the total backlog so the page can say+ * "10 of 143".+ *+ * ONE universe per run, capped to `maxEntries` — same shape as the image job, so+ * a run's summary names exactly one universe and the cap means what it says.+ */+async function collect(params, inFlight = new Set()) {+ const max = Math.min(ENTRY_BOUNDS.max, Math.max(ENTRY_BOUNDS.min, Number(params?.maxEntries) || ENTRY_BOUNDS.default));+ const scope = typeof params?.scope === 'string' ? params.scope : 'all';+ const depth = normalizeDescribeDepth(params?.depth);+ const universes = await loadUniverses(params);+ let picked = null;+ let total = 0;+ for (const universe of universes) {+ const rows = findUnderdescribedEntries(universe, { scope, depth })+ .filter((row) => !inFlight.has(describeInFlightKey(universe.id, row.kind, row.id)));+ total += rows.length;+ if (!rows.length || picked) continue;+ picked = { universe, rows: rows.slice(0, max) };+ }+ return { picked, total, max, depth };+}++/**+ * The provider this job would prompt through, or null when the family has none.+ *+ * Same rule the image job applies to render backends: a family with no usable+ * provider must NOT fall through to the install's active provider, or the expand+ * calls would spend a DIFFERENT subscription while this family's window expires+ * unused and its dispatch cap is charged for the privilege.+ */+export async function resolveDescribeProvider({ job, family }) {+ const result = await getAllProviders();+ return providerForFamily(Array.isArray(result) ? result : result?.providers, {+ familyId: family?.id,+ providerId: job?.providerId || null,+ // Headless one-shot prompts, not a watchable agent session — see+ // `providerForFamily`.+ prefer: 'cli',+ });+}++export async function countPending({ params, job, family } = {}) {+ const provider = await resolveDescribeProvider({ job, family });+ if (!provider) return { count: 0, detail: `no enabled CLI/TUI provider in the ${family?.id} family` };+ const inFlight = await getQuotaBurnInFlight();+ const collected = await collect(params, inFlight);+ const { picked, total, depth } = collected;+ const next = picked?.rows.length || 0;+ return {+ count: total,+ // Handed back to run() by the runner so the bible scan + provider lookup+ // happen once per dispatch instead of twice — see the registry's contract.+ context: { ...collected, provider },+ detail: total+ ? `${total} bible ${total === 1 ? 'entry is' : 'entries are'} under-described (${depth}) — ${next} queued next from "${picked.universe.name}"`+ : `every bible entry is described (${depth}) or was just attempted`,+ };+}++/** Route one row to the expand service that owns its kind. */+const expandRow = (universeId, row, options) => (row.kind === BIBLE_KIND.CHARACTER+ ? expandUniverseCharacter(universeId, row.id, options)+ : expandUniverseCanonEntry(universeId, row.kind, row.id, options));++/**+ * Describe the next batch, one LLM call per entry, sequentially.+ *+ * Sequential rather than fanned out on purpose: the whole point is to draw a+ * subscription window down at a steady rate, and a parallel fan-out against a+ * CLI provider mostly produces rate-limit refusals — which the denial ledger+ * then reads as "this family's short window is spent".+ *+ * A per-entry failure is absorbed, not propagated: one entry whose expand came+ * back empty must not discard the batch's earlier successes (the registry turns+ * a throw into "this job declined", which would also mean the successful writes+ * went unreported).+ */+export async function run({ params, job, family, context, force = false } = {}) {+ const provider = context?.provider ?? await resolveDescribeProvider({ job, family });+ if (!provider) return { dispatched: false, reason: `no enabled CLI/TUI provider in the ${family?.id} family` };++ // Reuse the probe's scan when the runner supplied it; the page's force path+ // calls run() with no probe, so fall back to scanning here. A forced run+ // ignores the cooldown: the user clicked ▶ on this exact job.+ const collected = context ?? await collect(params, force ? new Set() : await getQuotaBurnInFlight());+ const { picked, total, max, depth } = collected;+ if (!picked) return { dispatched: false, reason: 'every bible entry is already described' };++ const options = { providerId: provider.id, model: job?.model || undefined };+ const outcome = { described: 0, fields: 0, skipped: 0, failed: 0 };+ const failures = [];+ for (const row of picked.rows) {+ const result = await expandRow(picked.universe.id, row, options).catch((err) => ({ error: err.message }));+ if (result?.error) {+ outcome.failed += 1;+ if (failures.length < 3) failures.push(`${row.label}: ${result.error}`);+ continue;+ }+ const filled = result?.updatedFields?.length || 0;+ if (filled === 0) outcome.skipped += 1;+ else {+ outcome.described += 1;+ outcome.fields += filled;+ }+ }++ // Every entry failing is a provider problem, not progress — report it as a+ // non-dispatch so the window's cap isn't charged for a burn that did nothing,+ // and return BEFORE the cooldown stamp: a provider that was down for one tick+ // must not park this batch for the ledger's whole six-hour TTL.+ if (outcome.described === 0 && outcome.failed === picked.rows.length) {+ return { dispatched: false, reason: `every expand failed via ${provider.id} — ${failures[0] || 'unknown error'}` };+ }++ // Stamp EVERY attempted entry of a batch that got somewhere, including the+ // ones the model declined to fill. At `full` depth some fields are legitimately+ // meant to stay blank (the expand prompt tells the model to leave the Ghost→Need+ // chain alone for a bit-player), so an entry can be permanently "incomplete" —+ // without the cooldown the plan would re-pick the same handful every tick and+ // never reach the rest.+ await recordQuotaBurnInFlight(picked.rows.map((row) => describeInFlightKey(picked.universe.id, row.kind, row.id)));++ console.log(`🔥 Quota-burn describe "${picked.universe.name}" via ${provider.id} — described=${outcome.described} fields=${outcome.fields} skipped=${outcome.skipped} failed=${outcome.failed}`);+ return {+ dispatched: true,+ summary: `Described ${outcome.described} of ${picked.rows.length} bible entr${picked.rows.length === 1 ? 'y' : 'ies'} (${outcome.fields} field${outcome.fields === 1 ? '' : 's'}) in "${picked.universe.name}" via ${provider.id}`,+ detail: {+ universeId: picked.universe.id,+ providerId: provider.id,+ model: job?.model || null,+ depth,+ ...outcome,+ failures,+ backlog: total,+ cap: max,+ },+ };+}diff --git a/server/services/quotaBurnJobs/universeBibleDescribe.test.js b/server/services/quotaBurnJobs/universeBibleDescribe.test.jsnew file mode 100644index 0000000000..edec14f8c3--- /dev/null+++ b/server/services/quotaBurnJobs/universeBibleDescribe.test.js@@ -0,0 +1,172 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const listUniverses = vi.fn();+const getUniverse = vi.fn();+const expandUniverseCharacter = vi.fn();+const expandUniverseCanonEntry = vi.fn();+const getAllProviders = vi.fn();+const getQuotaBurnInFlight = vi.fn(async () => new Set());+const recordQuotaBurnInFlight = vi.fn(async () => {});++vi.mock('../universeBuilder.js', () => ({+ listUniverses: (...args) => listUniverses(...args),+ getUniverse: (...args) => getUniverse(...args),+}));+vi.mock('../universeCharacterExpand.js', () => ({+ expandUniverseCharacter: (...args) => expandUniverseCharacter(...args),+}));+vi.mock('../universeCanonEntryExpand.js', () => ({+ expandUniverseCanonEntry: (...args) => expandUniverseCanonEntry(...args),+}));+vi.mock('../providers.js', () => ({ getAllProviders: (...args) => getAllProviders(...args) }));+vi.mock('../quotaBurnStore.js', () => ({+ getQuotaBurnInFlight: (...args) => getQuotaBurnInFlight(...args),+ recordQuotaBurnInFlight: (...args) => recordQuotaBurnInFlight(...args),+}));++const {+ countPending, describeInFlightKey, findUnderdescribedEntries, run,+} = await import('./universeBibleDescribe.js');++const CODEX_CLI = { id: 'codex', type: 'cli', enabled: true, command: '/usr/local/bin/codex' };+const CODEX_TUI = { id: 'codex-tui', type: 'tui', enabled: true, command: '/usr/local/bin/codex' };++const universe = () => ({+ id: 'u1',+ name: 'Example Universe',+ characters: [+ // Blank except for a name — the case this job exists for.+ { id: 'c1', name: 'Alice' },+ // Locked: protected from every AI rewrite path.+ { id: 'c2', name: 'Bob', locked: true },+ // Core prose filled, sheet still thin — fewer gaps than Alice.+ {+ id: 'c3',+ name: 'Cass',+ physicalDescription: 'tall', personality: 'wry', background: 'exile',+ motivations: 'find the map', visualNotes: 'ochre coat',+ },+ ],+ places: [{ id: 'p1', name: 'The Foundry', description: 'a rolling mill, still hot' }],+ objects: [{ id: 'o1', name: 'The Ledger' }],+});++beforeEach(() => {+ vi.clearAllMocks();+ getQuotaBurnInFlight.mockResolvedValue(new Set());+ getAllProviders.mockResolvedValue([CODEX_CLI, CODEX_TUI]);+ listUniverses.mockResolvedValue([universe()]);+ expandUniverseCharacter.mockResolvedValue({ updatedFields: ['personality', 'background'] });+ expandUniverseCanonEntry.mockResolvedValue({ updatedFields: ['description'] });+});++describe('findUnderdescribedEntries', () => {+ it('orders the emptiest entries first and skips locked ones', () => {+ const rows = findUnderdescribedEntries(universe());+ // Fully-blank entries first (the character sheet wins the tiebreak on raw+ // gap size), then the partly-filled ones. Ranking on the raw count instead+ // would put every half-written character ahead of a totally blank object,+ // and on a real cast the objects would never be reached at all.+ expect(rows.map((row) => row.id)).toEqual(['c1', 'o1', 'p1', 'c3']);+ // Bob is locked — an expand on it returns `{ locked: true }` without an LLM+ // call, so picking it would spend a dispatch on a guaranteed no-op.+ expect(rows.some((row) => row.id === 'c2')).toBe(false);+ });++ it('reports a place described at core depth as done, and still thin at full', () => {+ expect(findUnderdescribedEntries(universe(), { scope: 'places', depth: 'core' })).toEqual([]);+ expect(findUnderdescribedEntries(universe(), { scope: 'places', depth: 'full' })).toHaveLength(1);+ });++ it('honors a narrowed scope', () => {+ expect(findUnderdescribedEntries(universe(), { scope: 'objects' }).map((r) => r.id)).toEqual(['o1']);+ expect(findUnderdescribedEntries(universe(), { scope: 'characters' }).map((r) => r.id)).toEqual(['c1', 'c3']);+ });++ it('tolerates an empty or malformed universe', () => {+ expect(findUnderdescribedEntries(null)).toEqual([]);+ expect(findUnderdescribedEntries({})).toEqual([]);+ });+});++describe('countPending', () => {+ it('refuses to fall through to another family\'s provider', async () => {+ // `claude` has no registered provider here. Falling through to the install's+ // active provider would spend a DIFFERENT subscription while claude's window+ // expires unused — and charge claude's dispatch cap for it.+ getAllProviders.mockResolvedValue([CODEX_CLI]);+ await expect(countPending({ params: {}, family: { id: 'claude' } }))+ .resolves.toMatchObject({ count: 0, detail: expect.stringContaining('no enabled CLI/TUI provider') });+ });++ it('counts the backlog and names how many go next', async () => {+ const result = await countPending({ params: { maxEntries: 2 }, family: { id: 'codex' } });+ expect(result.count).toBe(4);+ expect(result.detail).toContain('2 queued next');+ expect(result.context.picked.rows).toHaveLength(2);+ });++ it('drops entries still inside the cooldown', async () => {+ getQuotaBurnInFlight.mockResolvedValue(new Set([describeInFlightKey('u1', 'character', 'c1')]));+ const result = await countPending({ params: {}, family: { id: 'codex' } });+ expect(result.count).toBe(3);+ expect(result.context.picked.rows.some((row) => row.id === 'c1')).toBe(false);+ });+});++describe('run', () => {+ it('prefers the headless CLI provider over the TUI and pins every expand to it', async () => {+ const result = await run({ params: { maxEntries: 2 }, job: {}, family: { id: 'codex' } });+ expect(result.dispatched).toBe(true);+ expect(expandUniverseCharacter).toHaveBeenCalledWith('u1', 'c1', { providerId: 'codex', model: undefined });+ expect(expandUniverseCanonEntry).toHaveBeenCalledWith('u1', 'object', 'o1', { providerId: 'codex', model: undefined });+ expect(result.detail).toMatchObject({ described: 2, fields: 3, providerId: 'codex' });+ });++ it('stamps a cooldown on every attempted entry, including the ones nothing was filled on', async () => {+ // At `full` depth some fields are meant to stay blank (a bit-player has no+ // Ghost→Need chain), so an entry can be permanently incomplete. Without the+ // stamp the plan re-picks the same handful every tick forever.+ expandUniverseCharacter.mockResolvedValue({ updatedFields: [] });+ await run({ params: { maxEntries: 1 }, job: {}, family: { id: 'codex' } });+ expect(recordQuotaBurnInFlight).toHaveBeenCalledWith([describeInFlightKey('u1', 'character', 'c1')]);+ });++ it('absorbs a single failed expand and still reports the batch\'s successes', async () => {+ expandUniverseCharacter.mockRejectedValueOnce(new Error('empty expansion'));+ const result = await run({ params: { maxEntries: 2 }, job: {}, family: { id: 'codex' } });+ expect(result.dispatched).toBe(true);+ expect(result.detail).toMatchObject({ described: 1, failed: 1 });+ expect(result.detail.failures[0]).toContain('empty expansion');+ });++ it('declines (rather than charging the cap) when every expand failed', async () => {+ expandUniverseCharacter.mockRejectedValue(new Error('provider refused'));+ expandUniverseCanonEntry.mockRejectedValue(new Error('provider refused'));+ const result = await run({ params: { maxEntries: 2 }, job: {}, family: { id: 'codex' } });+ expect(result.dispatched).toBe(false);+ expect(result.reason).toContain('provider refused');+ // …and does NOT stamp the cooldown: a provider down for one tick must not+ // park this batch for the ledger's whole six-hour TTL.+ expect(recordQuotaBurnInFlight).not.toHaveBeenCalled();+ });++ it('declines when nothing is under-described', async () => {+ listUniverses.mockResolvedValue([{ id: 'u2', name: 'Done', characters: [], places: [], objects: [] }]);+ await expect(run({ params: {}, job: {}, family: { id: 'codex' } }))+ .resolves.toMatchObject({ dispatched: false, reason: expect.stringContaining('already described') });+ });++ it('ignores the cooldown on a forced run', async () => {+ getQuotaBurnInFlight.mockResolvedValue(new Set([describeInFlightKey('u1', 'character', 'c1')]));+ const result = await run({ params: { maxEntries: 1 }, job: {}, family: { id: 'codex' }, force: true });+ expect(expandUniverseCharacter).toHaveBeenCalledWith('u1', 'c1', expect.anything());+ expect(result.dispatched).toBe(true);+ });++ it('honors a job-level provider and model pin', async () => {+ const job = { providerId: 'codex-tui', model: 'gpt-5' };+ await run({ params: { maxEntries: 1 }, job, family: { id: 'codex' } });+ expect(expandUniverseCharacter).toHaveBeenCalledWith('u1', 'c1', { providerId: 'codex-tui', model: 'gpt-5' });+ });+});diff --git a/server/services/quotaBurnJobs/universeBibleImages.js b/server/services/quotaBurnJobs/universeBibleImages.jsindex f72f0dc07b..5356f6dff5 100644--- a/server/services/quotaBurnJobs/universeBibleImages.js+++ b/server/services/quotaBurnJobs/universeBibleImages.js@@ -19,8 +19,11 @@ import { renderUniverseJobs } from '../universeBuilderRender.js';import { CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';import { getQuotaBurnInFlight, recordQuotaBurnInFlight } from '../quotaBurnStore.js';import { QUOTA_BURN_BOUNDS } from '../../lib/quotaBurnConfig.js';+import { bibleEntryIsDescribed } from '../../lib/universeBibleCompleteness.js';-const CANON_TRUNKS = ['characters', 'places', 'objects'];+// Universe array key → the canon kind `bibleEntryIsDescribed` measures.+const CANON_TRUNK_KIND = Object.freeze({ characters: 'character', places: 'place', objects: 'object' });+const CANON_TRUNKS = Object.keys(CANON_TRUNK_KIND);// Bounds come from the catalog descriptor the client renders its min/max from —// hardcoding them here would let a raised cap change the accepted range in the// form without changing what the job actually runs.@@ -42,8 +45,14 @@ const wantsScope = (scope, kind) => scope === 'all' || !scope || scope === kind;* Every image-less entry in one universe, as `{ kind, categoryKey, label }`* rows in a stable order (variations → sheets → canon), so a capped run always* chews through the same backlog front-to-back rather than sampling randomly.+ *+ * `requireDescribed` holds back canon entries that have no description yet, so a+ * plan that also runs the `universe-bible-describe` job spends its image quota+ * on entries worth rendering rather than on a name with nothing behind it. Only+ * canon can be under-described — a variation or composite sheet cannot exist+ * without its prompt (the sanitizer drops one that has none).*/-export function findMissingImageEntries(universe, { scope = 'all' } = {}) {+export function findMissingImageEntries(universe, { scope = 'all', requireDescribed = false } = {}) {const rows = [];if (wantsScope(scope, 'variations')) {for (const categoryKey of getWorldCategoryKeys(universe?.categories)) {@@ -64,6 +73,11 @@ export function findMissingImageEntries(universe, { scope = 'all' } = {}) {for (const entry of universe?.[trunk] || []) {const label = canonLabel(trunk, entry);if (!hasNoImage(entry) || !label) continue;+ // `core` depth, not `full`: the gate is "is there anything to render+ // from", not "is the sheet finished". Holding a fully-described+ // character back because its `dislikes` is blank would park most of a+ // real universe behind a job the user may not even have configured.+ if (requireDescribed && !bibleEntryIsDescribed(CANON_TRUNK_KIND[trunk], entry, { depth: 'core' })) continue;rows.push({ kind: 'canon', categoryKey: trunk, label });}}@@ -112,6 +126,7 @@ async function loadUniverses(params) {async function collect(params, inFlight = new Set()) {const max = Math.min(ENTRY_BOUNDS.max, Math.max(ENTRY_BOUNDS.min, Number(params?.maxEntries) || ENTRY_BOUNDS.default));const scope = typeof params?.scope === 'string' ? params.scope : 'all';+ const requireDescribed = params?.requireDescribed === true;const universes = await loadUniverses(params);let picked = null;let total = 0;@@ -119,13 +134,13 @@ async function collect(params, inFlight = new Set()) {// Labels are what `compilePrompts` selects on and they are NOT unique// (nothing dedupes them on write), so a case-insensitive dedupe here keeps// one row from expanding into several renders and blowing past the cap.- const rows = dedupeByLabel(findMissingImageEntries(universe, { scope }))+ const rows = dedupeByLabel(findMissingImageEntries(universe, { scope, requireDescribed })).filter((row) => !inFlight.has(inFlightKey(universe.id, row)));total += rows.length;if (!rows.length || picked) continue;picked = { universe, rows: rows.slice(0, max) };}- return { picked, total, max };+ return { picked, total, max, requireDescribed };}// Keyed on the same identity `dedupeByLabel` uses. Label alone would let one@@ -173,7 +188,7 @@ export async function countPending({ params, family } = {}) {}const inFlight = await getQuotaBurnInFlight();const collected = await collect(params, inFlight);- const { picked, total } = collected;+ const { picked, total, requireDescribed } = collected;const next = picked?.rows.length || 0;return {count: total,@@ -182,7 +197,10 @@ export async function countPending({ params, family } = {}) {context: collected,detail: total? `${total} bible ${total === 1 ? 'entry has' : 'entries have'} no image — ${next} queued next from "${picked.universe.name}"`- : 'every bible entry already has an image or is already queued',+ // Naming the description gate matters: with it on, a universe full of+ // blank canon rows reports zero pending, and "already has an image" would+ // read as a bug rather than as the filter doing its job.+ : `every bible entry already has an image${requireDescribed ? ', has no description yet,' : ''} or is already queued`,};}diff --git a/server/services/quotaBurnJobs/universeBibleImages.test.js b/server/services/quotaBurnJobs/universeBibleImages.test.jsindex 35cef392c5..7ec0a9f2d0 100644--- a/server/services/quotaBurnJobs/universeBibleImages.test.js+++ b/server/services/quotaBurnJobs/universeBibleImages.test.js@@ -44,6 +44,29 @@ describe('findMissingImageEntries', () => {expect(findMissingImageEntries(null)).toEqual([]);expect(findMissingImageEntries({})).toEqual([]);});++ it('holds back undescribed canon when requireDescribed is on', () => {+ // Alice is a bare name; rendering her spends image quota on a generic+ // figure. The variation and the composite sheet are unaffected — their+ // sanitizer requires a prompt, so they cannot be undescribed.+ const rows = findMissingImageEntries(universe, { requireDescribed: true });+ expect(rows.map((row) => row.label)).toEqual(['Salt Flats', 'Cast Sheet']);+ });++ it('lets a canon entry through once it has a core description', () => {+ const described = {+ ...universe,+ characters: [{+ id: 'c1',+ name: 'Alice',+ imageRefs: [],+ physicalDescription: 'a', personality: 'b', background: 'c', motivations: 'd', visualNotes: 'e',+ }],+ places: [],+ };+ const rows = findMissingImageEntries(described, { scope: 'canon', requireDescribed: true });+ expect(rows.map((row) => row.label)).toEqual(['Alice']);+ });});describe('buildRenderSelection', () => {@@ -90,7 +113,11 @@ describe('label deduping', () => {};const { selection } = buildRenderSelection(findMissingImageEntries(dupes));expect(selection.vehicles).toHaveLength(2);- // The job's own collect() dedupes before selecting — pinned via the export.- expect(inFlightKey('u2', 'Skiff')).toBe(inFlightKey('u2', 'skiff'));+ // The job's own collect() dedupes before selecting — pinned via the export,+ // which takes a ROW (passing bare labels here would compare `undefined` to+ // `undefined` and pass no matter what the key did).+ const row = (label) => ({ kind: 'variation', categoryKey: 'vehicles', label });+ expect(inFlightKey('u2', row('Skiff'))).toBe(inFlightKey('u2', row('skiff')));+ expect(inFlightKey('u2', row('Skiff'))).not.toBe(inFlightKey('u2', row('Barge')));});});diff --git a/server/services/universeCanonEntryExpand.js b/server/services/universeCanonEntryExpand.jsnew file mode 100644index 0000000000..32ae1fe5c5--- /dev/null+++ b/server/services/universeCanonEntryExpand.js@@ -0,0 +1,149 @@+/**+ * Universe Place / Object — LLM expansion.+ *+ * The non-character half of `universeCharacterExpand.js`: one LLM call that+ * fleshes out blank fields on a canon place or object without clobbering+ * populated content. Characters keep their own module because their prompt+ * carries the whole character-sheet contract (stats, palette, expressions,+ * props, the Ghost→Need chain) and a peer-distinctness pass; places and objects+ * share a much smaller field set and one template.+ *+ * Same strict "fill blanks only" semantics as the character expand:+ * - key absent from LLM response → preserve existing value+ * - key present with an empty value → IGNORED (no "clear" intent exists in an+ * expand flow — an empty proposal just means the model had nothing to add)+ * - key present with a non-empty value → fill ONLY when the target is blank+ *+ * Locked entries are never touched, checked both before the call and again+ * inside the write queue (a lock can land during the LLM round-trip).+ */++import { getUniverse, updateUniverse } from './universeBuilder.js';+import { buildStyleClause } from './universeCanon.js';+import { runPromptRefineRaw } from './pipeline/refineHelpers.js';+import { ServerError } from '../lib/errorHandler.js';+import { BIBLE_FIELD, BIBLE_KIND, SANITIZERS } from '../lib/storyBible.js';+import { BIBLE_EXPAND_FIELDS, bibleFieldIsBlank } from '../lib/universeBibleCompleteness.js';+import { shortId } from '../lib/fileUtils.js';++/** Kinds this module expands. Characters route to `universeCharacterExpand.js`. */+export const CANON_ENTRY_EXPAND_KINDS = Object.freeze([BIBLE_KIND.PLACE, BIBLE_KIND.OBJECT]);++// Peers exist so the model doesn't hand three taverns the same palette. Kept+// deliberately thin — a place's own description is the only field that matters+// for collision, and sending the full records would blow the prompt up on a+// universe with a hundred locations.+const peerForExpandPrompt = (entry) => ({+ id: entry.id,+ name: entry.name || entry.slugline || '',+ description: entry.description || '',+});++/**+ * Pure no-clobber merge of an LLM payload onto a place/object. Exported so the+ * merge semantics can be exercised without an LLM round-trip.+ *+ * Every accepted value round-trips through the kind's sanitizer before it is+ * recorded: an out-of-vocabulary enum (`intExt: "INTERIOR"`) collapses to null+ * there, and accepting the raw proposal would report a field as filled that the+ * next persist silently drops.+ */+export function applyCanonEntryExpansion(kind, target, content) {+ const groups = BIBLE_EXPAND_FIELDS[kind];+ const sanitize = SANITIZERS[kind];+ if (!groups || !sanitize || !target || typeof target !== 'object' || !content || typeof content !== 'object') {+ return { merged: target, updatedFields: [] };+ }+ const merged = { ...target };+ const updatedFields = [];+ for (const field of [...groups.strings, ...groups.enums]) {+ if (!(field in content)) continue;+ const proposed = content[field];+ if (typeof proposed !== 'string' || !proposed.trim()) continue;+ if (!bibleFieldIsBlank(target, field)) continue;+ // `name`/`slugline` carry the record past the sanitizer's identity check —+ // a place needs one of them or `sanitizePlace` returns null and every+ // proposal would be discarded as unsanitizable.+ const cleaned = sanitize(+ { name: target.name, slugline: target.slugline, [field]: proposed },+ { preserveTimestamps: false },+ )?.[field];+ if (typeof cleaned !== 'string' || !cleaned.trim()) continue;+ merged[field] = cleaned;+ updatedFields.push(field);+ }+ return { merged, updatedFields };+}++/**+ * Fill blank fields on one canon place or object.+ *+ * Returns `{ universe, entry, updatedFields, locked? }` — `locked: true` with no+ * updated fields when the entry was (or became) locked, mirroring+ * `expandUniverseCharacter` so a caller can treat the two identically.+ */+export async function expandUniverseCanonEntry(universeId, kind, entryId, options = {}) {+ if (!CANON_ENTRY_EXPAND_KINDS.includes(kind)) {+ throw new ServerError(`Canon kind ${kind} is not expandable here`, {+ status: 400, code: 'UNIVERSE_CANON_KIND_UNSUPPORTED',+ });+ }+ const field = BIBLE_FIELD[kind];+ const universe = await getUniverse(universeId);+ const list = Array.isArray(universe[field]) ? universe[field] : [];+ const idx = list.findIndex((e) => e.id === entryId);+ if (idx < 0) {+ throw new ServerError(`${kind} ${entryId} not found in universe`, {+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',+ });+ }+ const target = list[idx];+ if (target.locked === true) {+ return { universe, entry: target, locked: true, updatedFields: [] };+ }++ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({+ templateName: 'universe-canon-entry-expand',+ variables: {+ kind,+ styleClause: buildStyleClause(universe),+ entryJson: JSON.stringify(target),+ peersJson: JSON.stringify(list.filter((_, i) => i !== idx).map(peerForExpandPrompt)),+ },+ options: { providerId: options.providerId, model: options.model },+ source: 'universe-canon-entry-expand',+ logTag: null,+ emptyError: {+ code: 'UNIVERSE_CANON_ENTRY_EXPAND_EMPTY',+ message: `LLM returned an empty ${kind} expansion`,+ },+ });++ // Re-derive the merge INSIDE the write queue against the freshest persisted+ // universe so a user edit that landed during the LLM round-trip isn't+ // overwritten. The mutator returns null to skip the write when nothing changed.+ let updatedFields = [];+ let lockedDuringRender = false;+ const updated = await updateUniverse(universeId, (latest) => {+ const latestList = Array.isArray(latest[field]) ? latest[field] : [];+ const latestIdx = latestList.findIndex((e) => e.id === entryId);+ if (latestIdx < 0) return null;+ if (latestList[latestIdx].locked === true) {+ lockedDuringRender = true;+ return null;+ }+ const { merged, updatedFields: fields } = applyCanonEntryExpansion(kind, latestList[latestIdx], content);+ updatedFields = fields;+ if (fields.length === 0) return null;+ return { [field]: latestList.map((e, i) => (i === latestIdx ? merged : e)) };+ });++ const latestEntry = (updated?.[field] || []).find((e) => e.id === entryId) || target;+ if (lockedDuringRender) {+ return { universe: updated, entry: latestEntry, locked: true, updatedFields: [], rationale, runId, providerId, model };+ }+ if (updatedFields.length > 0) {+ console.log(`✨ Universe ${kind} expand — universe=${shortId(universeId)} entry=${shortId(entryId)} fields=${updatedFields.length} runId=${shortId(runId)}`);+ }+ return { universe: updated, entry: latestEntry, rationale, runId, providerId, model, updatedFields };+}diff --git a/server/services/universeCanonEntryExpand.test.js b/server/services/universeCanonEntryExpand.test.jsnew file mode 100644index 0000000000..22d66481bf--- /dev/null+++ b/server/services/universeCanonEntryExpand.test.js@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest';++import { applyCanonEntryExpansion, CANON_ENTRY_EXPAND_KINDS } from './universeCanonEntryExpand.js';++const place = (overrides = {}) => ({ id: 'p1', name: 'The Foundry', ...overrides });+const object = (overrides = {}) => ({ id: 'o1', name: 'The Ledger', ...overrides });++describe('applyCanonEntryExpansion', () => {+ it('fills blank fields and reports exactly what it filled', () => {+ const { merged, updatedFields } = applyCanonEntryExpansion('place', place(), {+ description: 'A rolling mill, still hot at midnight.',+ era: 'late-industrial, retrofitted',+ });+ expect(updatedFields).toEqual(['description', 'era']);+ expect(merged.description).toBe('A rolling mill, still hot at midnight.');+ });++ it('never clobbers a populated field', () => {+ const target = place({ description: 'what the writer wrote' });+ const { merged, updatedFields } = applyCanonEntryExpansion('place', target, {+ description: 'what the model would rather have written',+ palette: 'sodium orange on wet slate',+ });+ expect(merged.description).toBe('what the writer wrote');+ expect(updatedFields).toEqual(['palette']);+ });++ it('ignores an empty proposal rather than treating it as a clear', () => {+ // An expand flow has no "clear" intent — an empty value just means the model+ // had nothing to add. (Distinct from the direct-PATCH merge convention,+ // where empty CAN mean clear.)+ const { merged, updatedFields } = applyCanonEntryExpansion('place', place({ era: 'pre-collapse' }), {+ description: ' ',+ era: '',+ });+ expect(updatedFields).toEqual([]);+ expect(merged.era).toBe('pre-collapse');+ });++ it('drops an out-of-vocabulary enum instead of reporting a field the sanitizer will discard', () => {+ // `intExt` only accepts INT/EXT. Accepting the raw proposal would report+ // the field as filled while the next persist silently drops it.+ const { merged, updatedFields } = applyCanonEntryExpansion('place', place(), {+ intExt: 'INTERIOR',+ timeOfDay: 'dusk',+ });+ expect(updatedFields).toEqual(['timeOfDay']);+ expect(merged.intExt).toBeUndefined();+ });++ it('normalizes an enum the model cased differently', () => {+ const { merged, updatedFields } = applyCanonEntryExpansion('place', place(), { intExt: 'int' });+ expect(updatedFields).toEqual(['intExt']);+ expect(merged.intExt).toBe('INT');+ });++ it('fills a place that carries only a slugline', () => {+ // `sanitizePlace` accepts name OR slugline; passing neither through would+ // make every proposal on a slugline-only place unsanitizable and dropped.+ const target = { id: 'p2', slugline: 'EXT. FOUNDRY — DAY' };+ const { updatedFields } = applyCanonEntryExpansion('place', target, { description: 'a yard of cooling slag' });+ expect(updatedFields).toEqual(['description']);+ });++ it('expands objects with their own field set', () => {+ const { merged, updatedFields } = applyCanonEntryExpansion('object', object(), {+ description: 'A hand-bound quarto, spine cracked.',+ significance: 'Everyone in the syndicate wants it burned.',+ // Not an object field — must not leak in from the place half of the prompt.+ weather: 'rain',+ });+ expect(updatedFields).toEqual(['description', 'significance']);+ expect(merged.weather).toBeUndefined();+ });++ it('returns the target untouched for an unknown kind or a malformed payload', () => {+ const target = place();+ expect(applyCanonEntryExpansion('character', target, { description: 'x' })).toEqual({ merged: target, updatedFields: [] });+ expect(applyCanonEntryExpansion('place', target, null)).toEqual({ merged: target, updatedFields: [] });+ expect(applyCanonEntryExpansion('place', null, { description: 'x' })).toEqual({ merged: null, updatedFields: [] });+ });++ it('does not claim to expand characters — they have their own module', () => {+ expect(CANON_ENTRY_EXPAND_KINDS).toEqual(['place', 'object']);+ });+});diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.jsindex 313cea5941..8bd3a412de 100644--- a/server/services/universeCharacterExpand.js+++ b/server/services/universeCharacterExpand.js@@ -16,28 +16,18 @@ import { buildStyleClause } from './universeCanon.js';import { runPromptRefineRaw } from './pipeline/refineHelpers.js';import { ServerError } from '../lib/errorHandler.js';import { sanitizeCharacter } from '../lib/storyBible.js';+import { BIBLE_EXPAND_FIELDS } from '../lib/universeBibleCompleteness.js';import { shortId } from '../lib/fileUtils.js';-// Adding a new extended field on `sanitizeCharacter` requires adding it here-// too — otherwise the expand response key is silently dropped. Exported so the-// vision-driven expand (`universeVisionExpand.js`) fills the SAME canonical set-// of fields from one source of truth rather than a drifting second copy.-export const STRING_FIELDS = Object.freeze([- 'pronouns', 'age', 'coreTheme', 'speechAccent', 'speechPattern',- 'physicalDescription', 'personality', 'background', 'visualNotes',- 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity',- 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',- // Character framework (CWQE Phase 10, #2175) — the Ghost → Wound → Lie →- // Want → Need chain. Plain prose fields; `arcType` (enum) and `sliders`- // (structured) are handled separately below.- 'ghost', 'wound', 'lie', 'want', 'need',-]);-export const LIST_FIELDS = Object.freeze([- 'stats', 'colorPalette', 'props', 'expressions', 'handGestures',- 'wardrobes',- // Character framework — secrets are a plain string list (#2175).- 'secrets',-]);+// Adding a new extended field on `sanitizeCharacter` requires adding it to+// `BIBLE_EXPAND_FIELDS.character` too — otherwise the expand response key is+// silently dropped. Sourced from there rather than restated here so the+// completeness scan that decides WHICH characters still need an expand and the+// merge that applies one can never disagree about the field set. Re-exported+// because the vision-driven expand (`universeVisionExpand.js`) fills the SAME+// canonical set.+export const STRING_FIELDS = BIBLE_EXPAND_FIELDS.character.strings;+export const LIST_FIELDS = BIBLE_EXPAND_FIELDS.character.lists;// `relationshipLinks` (#1287) is INTENTIONALLY excluded from both lists: each// link points at a sibling character by `targetCharacterId`, an id the LLM// expand call has no way to produce. The `{ ...target }` spread above