Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

simplify: lift the duplicated expand shell, universe backlog walk, and provider pick out of the burn jobs

[._.]/ Adam Eivy93ddbacebcc8
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index a8cf5d5b43..4fba431a37 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -147,18 +147,11 @@ 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.
+Locked entries are never picked, and every attempted entry is stamped into the
+shared in-flight ledger for its 6-hour TTL. Why picks are ranked by blank
+*fraction* rather than raw gap count, and why the stamp covers entries the model
+declined to fill, are argued at the code site
+(`server/services/quotaBurnJobs/universeBibleDescribe.js`).
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
diff --git a/server/lib/README.md b/server/lib/README.md
index 12931ee66f..7515b0f7e3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -88,7 +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. |
+| `universeBibleCompleteness.js` | Is a universe bible entry actually described? The shared per-kind expand-field vocabulary (`BIBLE_EXPAND_FIELDS`, `BIBLE_CORE_FIELDS`) and the `core`/`full` completeness predicates the quota-burn describe job scans with. 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/storyBible.js b/server/lib/storyBible.js
index e10966b641..9ccd6536f3 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -1130,6 +1130,31 @@ export const SANITIZERS = Object.freeze({
object: sanitizeObject,
});
+/**
+ * Run ONE proposed field value through its kind's sanitizer and return the
+ * cleaned value (or `undefined` when the kind is unknown).
+ *
+ * Every LLM-expand merge needs this before it records a field as filled: the
+ * sanitizers drop rows missing required keys (a stat without `label`, a palette
+ * swatch without `name`) and fold an unrecognized enum to null, so accepting a
+ * raw proposal reports a field as updated that the next persist silently
+ * discards.
+ *
+ * The stub carries `target`'s identity fields because the top-level sanitizers
+ * REJECT a record without one — a character/object needs `name`, a place needs
+ * `name` OR `slugline` — and a rejected stub would discard every proposal for a
+ * slugline-only place. That rule is the reason this is one helper rather than
+ * the same three-line stub written at each merge site.
+ */
+export function sanitizeBibleField(kind, target, field, value) {
+ const sanitize = SANITIZERS[kind];
+ if (!sanitize) return undefined;
+ return sanitize(
+ { name: target?.name, slugline: target?.slugline, [field]: value },
+ { preserveTimestamps: false },
+ )?.[field];
+}
+
// ---------------------------------------------------------------------------
// Reveal-gated canon / spoiler scoping (#2178)
// ---------------------------------------------------------------------------
@@ -1340,6 +1365,17 @@ const MERGE_CONFIG = Object.freeze({
},
});
+/**
+ * The fields the prose extractor's merge will fill only when blank, per kind.
+ *
+ * Exported so `universeBibleCompleteness.js` can be held to it: the extractor's
+ * no-clobber set and the expand prompts' field set are two answers to the same
+ * question ("what may an LLM fill in on an existing entry?"), and a field added
+ * to one but not the other is invisible to the completeness scan forever.
+ * `universeBibleCompleteness.test.js` asserts the two match modulo a named delta.
+ */
+export const bibleUserEditableFields = (kind) => MERGE_CONFIG[kind]?.userEditable || [];
+
function indexEntry(map, entry, keyFields) {
for (const { field, normalize } of keyFields) {
const val = entry[field];
diff --git a/server/lib/universeBibleCompleteness.js b/server/lib/universeBibleCompleteness.js
index d9d698d194..090aed37b8 100644
--- a/server/lib/universeBibleCompleteness.js
+++ b/server/lib/universeBibleCompleteness.js
@@ -24,11 +24,16 @@
* scan, so the two are deliberately one list rather than two that agree today.
*/
+import { isBlank } from './storyBible.js';
+
/** 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']);
+/**
+ * The three slider axes, all of which must be rated for `sliders` to count as
+ * filled. Exported so the character expand's merge rates the same three.
+ */
+export const SLIDER_AXES = Object.freeze(['proactivity', 'likability', 'competence']);
/**
* Every field the per-kind expand prompt may fill, grouped by how it is stored.
@@ -83,9 +88,6 @@ export const BIBLE_CORE_FIELDS = Object.freeze({
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
@@ -93,41 +95,36 @@ export const BIBLE_DESCRIBE_KINDS = Object.freeze(Object.keys(BIBLE_EXPAND_FIELD
* 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).
+ * Every field a kind's expand prompt can fill, flattened across the groups.
+ * Reads the groups generically so adding a fifth storage shape is one edit here
+ * rather than one at every flatten site.
*/
-const FIELD_VALUE = Object.freeze({
- physicalDescription: (entry) => entry?.physicalDescription || entry?.description || '',
-});
+export const expandableBibleFields = (kind) => Object.values(BIBLE_EXPAND_FIELDS[kind] || {}).flat();
+
+const requiredFields = (kind, depth) => {
+ if (!BIBLE_EXPAND_FIELDS[kind]) return [];
+ return depth === 'core' ? (BIBLE_CORE_FIELDS[kind] || []) : expandableBibleFields(kind);
+};
/**
- * 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.
+ * Whether ONE field on an entry is still unfilled — the single blank predicate
+ * the completeness scan AND the expand merges both call, so the code that
+ * decides an entry needs work can't disagree with the code that does it.
+ * `isBlank` (storyBible) carries the base string/array rule; the two exceptions
+ * below are what this wrapper adds.
*/
-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);
+ // 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.
+ if (field === 'physicalDescription') return isBlank(entry?.physicalDescription) && isBlank(entry?.description);
+ // `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.
+ if (field === 'sliders') return SLIDER_AXES.some((axis) => entry?.sliders?.[axis] == null);
+ return isBlank(entry?.[field]);
}
/** Normalize an untrusted depth param to a known depth, defaulting to `full`. */
@@ -148,17 +145,14 @@ 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).
+ * The gap list plus the size of the sheet it was measured against — what orders
+ * the describe job's picks (emptiest FRACTION first, so one kind's much longer
+ * sheet doesn't permanently outrank another's).
*/
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,
- };
+ const missing = (entry && typeof entry === 'object')
+ ? required.filter((field) => bibleFieldIsBlank(entry, field))
+ : [];
+ return { required: required.length, missing };
}
diff --git a/server/lib/universeBibleCompleteness.test.js b/server/lib/universeBibleCompleteness.test.js
index e5358d9c17..7dcad61d6b 100644
--- a/server/lib/universeBibleCompleteness.test.js
+++ b/server/lib/universeBibleCompleteness.test.js
@@ -6,9 +6,11 @@ import {
bibleEntryCompleteness,
bibleEntryIsDescribed,
bibleFieldIsBlank,
+ expandableBibleFields,
missingBibleFields,
normalizeDescribeDepth,
} from './universeBibleCompleteness.js';
+import { bibleUserEditableFields } from './storyBible.js';
const describedCharacter = () => {
const groups = BIBLE_EXPAND_FIELDS.character;
@@ -23,10 +25,7 @@ const describedCharacter = () => {
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).toHaveLength(expandableBibleFields('character').length);
expect(missing).toContain('physicalDescription');
expect(missing).toContain('colorPalette');
expect(missing).toContain('sliders');
@@ -78,13 +77,19 @@ describe('missingBibleFields', () => {
});
describe('bibleEntryCompleteness', () => {
- it('reports the gap size the describe job orders its picks by', () => {
+ it('reports the gap and the sheet size the describe job ranks on', () => {
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);
+ expect(empty.required).toBe(expandableBibleFields('place').length);
+ expect(empty.missing).toHaveLength(empty.required);
+ expect(partial.missing).toHaveLength(empty.required - 2);
+ // The ratio is what the job sorts on — a place's 7-field sheet must be
+ // comparable to a character's 31-field one.
+ expect(partial.missing.length / partial.required).toBeLessThan(1);
+ });
+
+ it('reports a blank gap list rather than throwing on a malformed entry', () => {
+ expect(bibleEntryCompleteness('place', null).missing).toEqual([]);
});
});
@@ -97,6 +102,31 @@ describe('normalizeDescribeDepth', () => {
});
});
+describe('parity with the prose extractor\'s no-clobber set', () => {
+ // `MERGE_CONFIG[kind].userEditable` (storyBible) and `BIBLE_EXPAND_FIELDS`
+ // answer the same question — what may an LLM fill in on an existing entry? A
+ // field added to one but not the other is invisible to the completeness scan
+ // forever, so the delta has to be named rather than merely tolerated.
+ const KNOWN_DELTA = {
+ // `role` is extracted from prose but is not something the expand prompts
+ // invent — a character's function in the story is the writer's call.
+ character: { extractorOnly: ['role'], expandOnly: ['sliders'] },
+ place: { extractorOnly: [], expandOnly: [] },
+ object: { extractorOnly: [], expandOnly: [] },
+ };
+
+ for (const kind of Object.keys(BIBLE_EXPAND_FIELDS)) {
+ it(`matches for ${kind} modulo the documented delta`, () => {
+ const expand = new Set(expandableBibleFields(kind));
+ const extractor = new Set(bibleUserEditableFields(kind));
+ expect([...extractor].filter((f) => !expand.has(f)).sort())
+ .toEqual([...KNOWN_DELTA[kind].extractorOnly].sort());
+ expect([...expand].filter((f) => !extractor.has(f)).sort())
+ .toEqual([...KNOWN_DELTA[kind].expandOnly].sort());
+ });
+ }
+});
+
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)) {
diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.js
index c331f099fc..5a98c530bf 100644
--- a/server/services/quotaBurnJobs/agentPrompt.js
+++ b/server/services/quotaBurnJobs/agentPrompt.js
@@ -13,68 +13,10 @@
import { addTask } from '../cosTaskStore.js';
import { getAppById } from '../apps.js';
-import { getAllProviders } from '../providers.js';
-import { commandBasename } from '../../lib/providerModels.js';
+import { noProviderReason, resolveBurnProvider } from './providerPick.js';
import { burnTaskDescription, isUnlimitedDispatchCap } from '../../lib/quotaBurnConfig.js';
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 type named by `prefer` (default `tui`).
- *
- * 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:
- * - API-type providers bill per token rather than drawing down a window.
- * - Ollama-backed wrappers run a LOCAL model, so there is no window to spend and
- * burning through one accomplishes nothing. `resolveEnabledFamilies` drops
- * 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, 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 === prefer) || inFamily[0] || null;
-}
-
-/**
- * Does this provider belong to `familyId`?
- *
- * The BINARY is what actually identifies the family — the provider id is a
- * user-facing label and does not have to contain the family name. Matching on
- * the id alone silently stranded the whole `agy` family: its providers ship as
- * `antigravity-cli` / `antigravity-tui`, neither of which contains "agy", so a
- * configured Antigravity burn plan reported "no enabled CLI/TUI provider" and
- * could never dispatch — while the quota card sat right above it showing a
- * healthy window, because `providerUsage`'s own matcher checks the command.
- *
- * The id substring stays as a fallback for a provider registered under a wrapper
- * script whose basename isn't the family name.
- */
-const matchesFamily = (provider, familyId) => {
- const needle = String(familyId || '').toLowerCase();
- if (!needle) return false;
- return commandBasename(provider.command) === needle
- || String(provider.id || '').toLowerCase().includes(needle);
-};
-
async function resolve({ params, job, family }) {
const appId = typeof params?.appId === 'string' ? params.appId.trim() : '';
const prompt = typeof params?.prompt === 'string' ? params.prompt.trim() : '';
@@ -82,12 +24,10 @@ async function resolve({ params, job, family }) {
if (!prompt) return { error: 'no work prompt configured' };
const app = await getAppById(appId);
if (!app) return { error: `managed app ${appId} no longer exists` };
- const result = await getAllProviders();
- const provider = providerForFamily(
- Array.isArray(result) ? result : result?.providers,
- { familyId: family?.id, providerId: job?.providerId || null },
- );
- if (!provider) return { error: `no enabled CLI/TUI provider in the ${family?.id} family` };
+ // Default `prefer: 'tui'` — an agent burn runs for minutes and should be
+ // watchable in Active Agents.
+ const provider = await resolveBurnProvider({ job, family });
+ if (!provider) return { error: noProviderReason(family) };
return { app, prompt, provider };
}
diff --git a/server/services/quotaBurnJobs/agentPrompt.test.js b/server/services/quotaBurnJobs/agentPrompt.test.js
index 76d50f752d..73f8705f57 100644
--- a/server/services/quotaBurnJobs/agentPrompt.test.js
+++ b/server/services/quotaBurnJobs/agentPrompt.test.js
@@ -8,7 +8,7 @@ vi.mock('../cosTaskStore.js', () => ({
vi.mock('../apps.js', () => ({ getAppById: vi.fn(async (id) => state.apps[id] || null) }));
vi.mock('../providers.js', () => ({ getAllProviders: vi.fn(async () => state.providers) }));
-const { countPending, providerForFamily, renderBurnPrompt, run } = await import('./agentPrompt.js');
+const { countPending, renderBurnPrompt, run } = await import('./agentPrompt.js');
const { quotaBurnFamilyOfDescription } = await import('../../lib/quotaBurnConfig.js');
const family = { id: 'grok', reservePercent: 10, maxDispatchesPerWindow: 3 };
@@ -24,73 +24,6 @@ beforeEach(() => {
state.addResult = null;
});
-describe('providerForFamily', () => {
- it('matches an enabled CLI/TUI provider by family name', () => {
- expect(providerForFamily(state.providers, { familyId: 'grok' })?.id).toBe('grok-cli');
- });
-
- it('honors an explicit pin and ignores API-type providers', () => {
- // The job exists to spend a SUBSCRIPTION window; an API provider bills per
- // token instead, so burning through it would cost real money.
- expect(providerForFamily(state.providers, { familyId: 'grok', providerId: 'claude-code' })?.id).toBe('claude-code');
- expect(providerForFamily([{ id: 'grok-api', type: 'api', enabled: true }], { familyId: 'grok' })).toBeNull();
- expect(providerForFamily([{ id: 'grok-cli', type: 'cli', enabled: false }], { familyId: 'grok' })).toBeNull();
- });
-
- // A burn runs unattended for minutes on the user's own subscription — the TUI
- // is the one that can be watched in Active Agents and steered mid-run. Most
- // families register both, and the CLI sorts first, so a plain `find` picked
- // the unobservable one every time.
- it('prefers the TUI provider over the CLI in the same family', () => {
- const providers = [
- { id: 'grok-cli', type: 'cli', enabled: true },
- { id: 'grok-tui', type: 'tui', enabled: true },
- ];
- expect(providerForFamily(providers, { familyId: 'grok' })?.id).toBe('grok-tui');
- // Registry order must not decide it either way.
- expect(providerForFamily([...providers].reverse(), { familyId: 'grok' })?.id).toBe('grok-tui');
- // CLI-only families still resolve — the preference is not a requirement.
- expect(providerForFamily([{ id: 'grok-cli', type: 'cli', enabled: true }], { familyId: 'grok' })?.id).toBe('grok-cli');
- // An explicit pin still outranks the preference.
- expect(providerForFamily(providers, { familyId: 'grok', providerId: 'grok-cli' })?.id).toBe('grok-cli');
- });
-
- // The whole `agy` family was unreachable: its providers ship as
- // `antigravity-cli` / `antigravity-tui`, neither of which contains "agy", so a
- // configured Antigravity plan reported "no enabled CLI/TUI provider" forever —
- // under a quota card that was showing a healthy window, because that card's
- // matcher checks the command.
- it('matches on the provider BINARY, not just the id — the agy/antigravity case', () => {
- const providers = [
- { id: 'antigravity-cli', type: 'cli', enabled: true, command: 'agy' },
- { id: 'antigravity-tui', type: 'tui', enabled: true, command: 'agy' },
- ];
- expect(providerForFamily(providers, { familyId: 'agy' })?.id).toBe('antigravity-tui');
- // An absolute path still resolves by basename.
- expect(providerForFamily([{ id: 'custom', type: 'tui', enabled: true, command: '/opt/tools/agy' }], { familyId: 'agy' })?.id).toBe('custom');
- // And the id substring still works for a wrapper whose basename differs.
- expect(providerForFamily([{ id: 'grok-tui', type: 'tui', enabled: true, command: 'grok-wrapper.sh' }], { familyId: 'grok' })?.id).toBe('grok-tui');
- // An unrelated family must not be dragged in by either signal.
- expect(providerForFamily(providers, { familyId: 'codex' })).toBeNull();
- });
-
- it('never selects an ollama-backed wrapper — a local model has no window to burn', () => {
- // `claude-ollama-tui` matches the `claude` family and IS a TUI, so the
- // preference above would reach for it. It runs a local model: nothing
- // expires, nothing is spent, and the window it was supposed to drain goes
- // unused. Same exclusion `resolveEnabledFamilies` applies to the cards.
- const providers = [
- { id: 'claude-ollama-tui', type: 'tui', enabled: true, ollamaBacked: true },
- { id: 'claude-code-tui', type: 'tui', enabled: true },
- { id: 'claude-code', type: 'cli', enabled: true },
- ];
- expect(providerForFamily(providers, { familyId: 'claude' })?.id).toBe('claude-code-tui');
- // Not even by explicit pin — it cannot do the one thing the job is for.
- expect(providerForFamily(providers, { familyId: 'claude', providerId: 'claude-ollama-tui' })).toBeNull();
- expect(providerForFamily([providers[0]], { familyId: 'claude' })).toBeNull();
- });
-});
-
describe('countPending', () => {
it('is ready only when the app, the prompt, and a provider all resolve', async () => {
await expect(countPending({ params: { appId: 'app-1', prompt: 'Do the thing' }, family }))
diff --git a/server/services/quotaBurnJobs/providerPick.js b/server/services/quotaBurnJobs/providerPick.js
new file mode 100644
index 0000000000..5989650f31
--- /dev/null
+++ b/server/services/quotaBurnJobs/providerPick.js
@@ -0,0 +1,82 @@
+/**
+ * Which provider a burn job spends — shared by every job type.
+ *
+ * Its own module rather than a sibling job's export: the registry lazy-imports
+ * job modules specifically so a status read doesn't drag in a job's heavy
+ * dependencies (`agentPrompt.js` pulls the CoS task store and the managed-app
+ * store), and importing this helper from there would have made every
+ * programmatic job's probe load exactly that.
+ */
+
+import { getAllProviders } from '../providers.js';
+import { commandBasename } from '../../lib/providerModels.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 type named by `prefer` (default `tui`).
+ *
+ * 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:
+ * - API-type providers bill per token rather than drawing down a window.
+ * - Ollama-backed wrappers run a LOCAL model, so there is no window to spend and
+ * burning through one accomplishes nothing. `resolveEnabledFamilies` drops
+ * 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, 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 === prefer) || inFamily[0] || null;
+}
+
+/**
+ * Does this provider belong to `familyId`?
+ *
+ * The BINARY is what actually identifies the family — the provider id is a
+ * user-facing label and does not have to contain the family name. Matching on
+ * the id alone silently stranded the whole `agy` family: its providers ship as
+ * `antigravity-cli` / `antigravity-tui`, neither of which contains "agy", so a
+ * configured Antigravity burn plan reported "no enabled CLI/TUI provider" and
+ * could never dispatch — while the quota card sat right above it showing a
+ * healthy window, because `providerUsage`'s own matcher checks the command.
+ *
+ * The id substring stays as a fallback for a provider registered under a wrapper
+ * script whose basename isn't the family name.
+ */
+const matchesFamily = (provider, familyId) => {
+ const needle = String(familyId || '').toLowerCase();
+ if (!needle) return false;
+ return commandBasename(provider.command) === needle
+ || String(provider.id || '').toLowerCase().includes(needle);
+};
+
+/** The reason a job reports when its family has nothing it is allowed to spend. */
+export const noProviderReason = (family) => `no enabled CLI/TUI provider in the ${family?.id} family`;
+
+/** `providerForFamily` against the live provider list. */
+export async function resolveBurnProvider({ job, family, prefer }) {
+ const result = await getAllProviders();
+ return providerForFamily(Array.isArray(result) ? result : result?.providers, {
+ familyId: family?.id,
+ providerId: job?.providerId || null,
+ prefer,
+ });
+}
diff --git a/server/services/quotaBurnJobs/providerPick.test.js b/server/services/quotaBurnJobs/providerPick.test.js
new file mode 100644
index 0000000000..78b652ae8f
--- /dev/null
+++ b/server/services/quotaBurnJobs/providerPick.test.js
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import { noProviderReason, providerForFamily } from './providerPick.js';
+
+const cliProviders = [
+ { id: 'grok-cli', type: 'cli', enabled: true },
+ { id: 'claude-code', type: 'cli', enabled: true },
+];
+
+describe('providerForFamily', () => {
+ it('matches an enabled CLI/TUI provider by family name', () => {
+ expect(providerForFamily(cliProviders, { familyId: 'grok' })?.id).toBe('grok-cli');
+ });
+
+ it('honors an explicit pin and ignores API-type providers', () => {
+ // The job exists to spend a SUBSCRIPTION window; an API provider bills per
+ // token instead, so burning through it would cost real money.
+ expect(providerForFamily(cliProviders, { familyId: 'grok', providerId: 'claude-code' })?.id).toBe('claude-code');
+ expect(providerForFamily([{ id: 'grok-api', type: 'api', enabled: true }], { familyId: 'grok' })).toBeNull();
+ expect(providerForFamily([{ id: 'grok-cli', type: 'cli', enabled: false }], { familyId: 'grok' })).toBeNull();
+ });
+
+ // A burn runs unattended for minutes on the user's own subscription — the TUI
+ // is the one that can be watched in Active Agents and steered mid-run. Most
+ // families register both, and the CLI sorts first, so a plain `find` picked
+ // the unobservable one every time.
+ it('prefers the TUI provider over the CLI in the same family', () => {
+ const providers = [
+ { id: 'grok-cli', type: 'cli', enabled: true },
+ { id: 'grok-tui', type: 'tui', enabled: true },
+ ];
+ expect(providerForFamily(providers, { familyId: 'grok' })?.id).toBe('grok-tui');
+ // Registry order must not decide it either way.
+ expect(providerForFamily([...providers].reverse(), { familyId: 'grok' })?.id).toBe('grok-tui');
+ // CLI-only families still resolve — the preference is not a requirement.
+ expect(providerForFamily([{ id: 'grok-cli', type: 'cli', enabled: true }], { familyId: 'grok' })?.id).toBe('grok-cli');
+ // An explicit pin still outranks the preference.
+ expect(providerForFamily(providers, { familyId: 'grok', providerId: 'grok-cli' })?.id).toBe('grok-cli');
+ });
+
+ // The whole `agy` family was unreachable: its providers ship as
+ // `antigravity-cli` / `antigravity-tui`, neither of which contains "agy", so a
+ // configured Antigravity plan reported "no enabled CLI/TUI provider" forever —
+ // under a quota card that was showing a healthy window, because that card's
+ // matcher checks the command.
+ it('matches on the provider BINARY, not just the id — the agy/antigravity case', () => {
+ const providers = [
+ { id: 'antigravity-cli', type: 'cli', enabled: true, command: 'agy' },
+ { id: 'antigravity-tui', type: 'tui', enabled: true, command: 'agy' },
+ ];
+ expect(providerForFamily(providers, { familyId: 'agy' })?.id).toBe('antigravity-tui');
+ // An absolute path still resolves by basename.
+ expect(providerForFamily([{ id: 'custom', type: 'tui', enabled: true, command: '/opt/tools/agy' }], { familyId: 'agy' })?.id).toBe('custom');
+ // And the id substring still works for a wrapper whose basename differs.
+ expect(providerForFamily([{ id: 'grok-tui', type: 'tui', enabled: true, command: 'grok-wrapper.sh' }], { familyId: 'grok' })?.id).toBe('grok-tui');
+ // An unrelated family must not be dragged in by either signal.
+ expect(providerForFamily(providers, { familyId: 'codex' })).toBeNull();
+ });
+
+ it('never selects an ollama-backed wrapper — a local model has no window to burn', () => {
+ // `claude-ollama-tui` matches the `claude` family and IS a TUI, so the
+ // preference above would reach for it. It runs a local model: nothing
+ // expires, nothing is spent, and the window it was supposed to drain goes
+ // unused. Same exclusion `resolveEnabledFamilies` applies to the cards.
+ const providers = [
+ { id: 'claude-ollama-tui', type: 'tui', enabled: true, ollamaBacked: true },
+ { id: 'claude-code-tui', type: 'tui', enabled: true },
+ { id: 'claude-code', type: 'cli', enabled: true },
+ ];
+ expect(providerForFamily(providers, { familyId: 'claude' })?.id).toBe('claude-code-tui');
+ // Not even by explicit pin — it cannot do the one thing the job is for.
+ expect(providerForFamily(providers, { familyId: 'claude', providerId: 'claude-ollama-tui' })).toBeNull();
+ expect(providerForFamily([providers[0]], { familyId: 'claude' })).toBeNull();
+ });
+});
+
+
+describe('the cli preference for programmatic jobs', () => {
+ it('flips the default without forking the helper', () => {
+ // A programmatic job sends one headless prompt through the stage runner:
+ // no agent session to watch or steer, so the TUI buys nothing and its
+ // interactive startup is pure overhead.
+ const providers = [
+ { id: 'codex-tui', type: 'tui', enabled: true, command: 'codex' },
+ { id: 'codex', type: 'cli', enabled: true, command: 'codex' },
+ ];
+ expect(providerForFamily(providers, { familyId: 'codex', prefer: 'cli' })?.id).toBe('codex');
+ expect(providerForFamily(providers, { familyId: 'codex' })?.id).toBe('codex-tui');
+ // The other type stays a fallback — a TUI-only family must not stop burning.
+ expect(providerForFamily([providers[0]], { familyId: 'codex', prefer: 'cli' })?.id).toBe('codex-tui');
+ });
+});
+
+describe('noProviderReason', () => {
+ it('is one string so countPending and run cannot word the same refusal differently', () => {
+ expect(noProviderReason({ id: 'claude' })).toContain('claude');
+ expect(noProviderReason(undefined)).toContain('undefined');
+ });
+});
diff --git a/server/services/quotaBurnJobs/universeBacklog.js b/server/services/quotaBurnJobs/universeBacklog.js
new file mode 100644
index 0000000000..15247769b9
--- /dev/null
+++ b/server/services/quotaBurnJobs/universeBacklog.js
@@ -0,0 +1,73 @@
+/**
+ * The universe-walking half of every universe-backed burn job.
+ *
+ * Both the describe job and the images job answer the same two questions — "how
+ * much work is outstanding across every universe" and "which single universe do
+ * I chew on this run" — and differ only in what counts as a row. Written twice,
+ * the pick rule drifted immediately: the ONE-universe-per-run rule below is a
+ * correction of an earlier version that spread the cap across universes and
+ * produced a cap the run never honored, and a second copy is a second chance to
+ * regress it.
+ */
+
+import { getUniverse, listUniverses } from '../universeBuilder.js';
+import { QUOTA_BURN_BOUNDS } from '../../lib/quotaBurnConfig.js';
+
+// 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 jobs actually run.
+const ENTRY_BOUNDS = QUOTA_BURN_BOUNDS.maxEntries;
+
+/** `params.maxEntries` clamped into the range the job form advertises. */
+export const clampMaxEntries = (params) =>
+ Math.min(ENTRY_BOUNDS.max, Math.max(ENTRY_BOUNDS.min, Number(params?.maxEntries) || ENTRY_BOUNDS.default));
+
+/**
+ * The universes a job targets: the one it names, or all of them. 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.
+ */
+export async function loadUniverses(params) {
+ const id = typeof params?.universeId === 'string' ? params.universeId.trim() : '';
+ if (!id || id === 'all') return listUniverses();
+ return getUniverse(id).then((universe) => [universe]).catch(() => []);
+}
+
+/**
+ * Walk the targeted universes, count the whole backlog, and pick the FIRST
+ * universe that has work — capped to `maxEntries`.
+ *
+ * One universe per run because each job's `run` makes a single batched call
+ * against one universe (one render collection, or one describe batch reported
+ * under one name). Spreading the budget across several produced a cap the run
+ * never honored and a status line that advertised more universes than it
+ * touched.
+ *
+ * `rowsFor(universe)` returns that universe's outstanding rows, already filtered
+ * for the cooldown. `sortRows` (optional) orders the pick — applied ONLY to the
+ * universe actually chosen, since every other universe contributes nothing but
+ * its row count and sorting those is pure waste on a path that runs for every
+ * configured job on every config-page load.
+ *
+ * Returns `{ picked, total, max }`, where `picked` carries the universe's id and
+ * name rather than the record: the probe's return value is handed to the client
+ * inside the status payload, and a universe record is a multi-megabyte blob that
+ * neither job's `run` reads more than two fields of.
+ */
+export async function collectUniverseBacklog(params, { rowsFor, sortRows } = {}) {
+ const max = clampMaxEntries(params);
+ const universes = await loadUniverses(params);
+ let picked = null;
+ let total = 0;
+ for (const universe of universes) {
+ const rows = rowsFor(universe);
+ total += rows.length;
+ if (!rows.length || picked) continue;
+ picked = {
+ universeId: universe.id,
+ universeName: universe.name,
+ rows: (sortRows ? sortRows(rows) : rows).slice(0, max),
+ };
+ }
+ return { picked, total, max };
+}
diff --git a/server/services/quotaBurnJobs/universeBibleDescribe.js b/server/services/quotaBurnJobs/universeBibleDescribe.js
index b5a5f914b1..399d1f8932 100644
--- a/server/services/quotaBurnJobs/universeBibleDescribe.js
+++ b/server/services/quotaBurnJobs/universeBibleDescribe.js
@@ -25,28 +25,27 @@
* 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 { BIBLE_FIELD, BIBLE_KEYS, BIBLE_KIND, BIBLE_KINDS } from '../../lib/storyBible.js';
import { bibleEntryCompleteness, normalizeDescribeDepth } from '../../lib/universeBibleCompleteness.js';
-import { QUOTA_BURN_BOUNDS } from '../../lib/quotaBurnConfig.js';
-import { providerForFamily } from './agentPrompt.js';
+import { collectUniverseBacklog } from './universeBacklog.js';
+import { noProviderReason, resolveBurnProvider } from './providerPick.js';
-/** Scope value → the canon kinds it selects. `all` walks the cast first. */
+/**
+ * Scope value → the canon kinds it selects, derived from `BIBLE_FIELD` rather
+ * than restated, so a future canon kind reaches this job's picker for free (the
+ * scope option list in the job catalog is the one place it still needs naming).
+ * Order matters: `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],
+ all: BIBLE_KINDS,
+ ...Object.fromEntries(BIBLE_KINDS.map((kind) => [BIBLE_FIELD[kind], [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.
-const ENTRY_BOUNDS = QUOTA_BURN_BOUNDS.maxEntries;
+// Pinned so a rename of a `BIBLE_FIELD` value can't silently orphan a stored
+// job's `scope` — the catalog's option list has to move with it.
+export const DESCRIBE_SCOPES = Object.freeze(['all', ...BIBLE_KEYS]);
/**
* One in-flight key per ENTRY (ids are unique, unlike the image job's labels),
@@ -57,16 +56,8 @@ export const describeInFlightKey = (universeId, kind, entryId) => `describe:${un
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.
+ * Every under-described entry in one universe. Unordered — `sortRows` below is
+ * what ranks the ones actually picked.
*/
export function findUnderdescribedEntries(universe, { scope = 'all', depth = 'full' } = {}) {
const kinds = SCOPE_KINDS[scope] || SCOPE_KINDS.all;
@@ -82,46 +73,42 @@ export function findUnderdescribedEntries(universe, { scope = 'all', depth = 'fu
rows.push({
kind,
id: entry.id,
- label: entryLabel(entry),
+ label: entry.name || entry.slugline || entry.id,
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));
+ return rows;
}
-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(() => []);
-}
+/**
+ * Emptiest first, by the FRACTION of the entry's own sheet that is blank rather
+ * than 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 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 const sortByEmptiest = (rows) =>
+ [...rows].sort((a, b) => b.blankRatio - a.blankRatio || b.missing - a.missing || a.id.localeCompare(b.id));
/**
* 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.
+ * "10 of 143". The universe walk + one-universe-per-run rule are shared with the
+ * image job (`universeBacklog.js`).
*/
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 };
+ const collected = await collectUniverseBacklog(params, {
+ rowsFor: (universe) => findUnderdescribedEntries(universe, { scope, depth })
+ .filter((row) => !inFlight.has(describeInFlightKey(universe.id, row.kind, row.id))),
+ sortRows: sortByEmptiest,
+ });
+ return { ...collected, depth };
}
/**
@@ -132,22 +119,14 @@ async function collect(params, inFlight = new Set()) {
* 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 const resolveDescribeProvider = ({ job, family }) =>
+ // Headless one-shot prompts, not a watchable agent session — see `providerForFamily`.
+ resolveBurnProvider({ job, family, 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);
+ if (!provider) return { count: 0, detail: noProviderReason(family) };
+ const collected = await collect(params, await getQuotaBurnInFlight());
const { picked, total, depth } = collected;
const next = picked?.rows.length || 0;
return {
@@ -156,7 +135,7 @@ export async function countPending({ params, job, family } = {}) {
// 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}"`
+ ? `${total} bible ${total === 1 ? 'entry is' : 'entries are'} under-described (${depth}) — ${next} queued next from "${picked.universeName}"`
: `every bible entry is described (${depth}) or was just attempted`,
};
}
@@ -181,7 +160,7 @@ const expandRow = (universeId, row, options) => (row.kind === BIBLE_KIND.CHARACT
*/
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` };
+ if (!provider) return { dispatched: false, reason: noProviderReason(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
@@ -194,7 +173,7 @@ export async function run({ params, job, family, context, force = false } = {})
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 }));
+ const result = await expandRow(picked.universeId, row, options).catch((err) => ({ error: err.message }));
if (result?.error) {
outcome.failed += 1;
if (failures.length < 3) failures.push(`${row.label}: ${result.error}`);
@@ -222,14 +201,14 @@ export async function run({ params, job, family, context, force = false } = {})
// 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)));
+ await recordQuotaBurnInFlight(picked.rows.map((row) => describeInFlightKey(picked.universeId, 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}`);
+ console.log(`🔥 Quota-burn describe "${picked.universeName}" 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}`,
+ 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.universeName}" via ${provider.id}`,
detail: {
- universeId: picked.universe.id,
+ universeId: picked.universeId,
providerId: provider.id,
model: job?.model || null,
depth,
diff --git a/server/services/quotaBurnJobs/universeBibleDescribe.test.js b/server/services/quotaBurnJobs/universeBibleDescribe.test.js
index edec14f8c3..8f6c32de27 100644
--- a/server/services/quotaBurnJobs/universeBibleDescribe.test.js
+++ b/server/services/quotaBurnJobs/universeBibleDescribe.test.js
@@ -25,7 +25,7 @@ vi.mock('../quotaBurnStore.js', () => ({
}));
const {
- countPending, describeInFlightKey, findUnderdescribedEntries, run,
+ countPending, describeInFlightKey, findUnderdescribedEntries, run, sortByEmptiest,
} = await import('./universeBibleDescribe.js');
const CODEX_CLI = { id: 'codex', type: 'cli', enabled: true, command: '/usr/local/bin/codex' };
@@ -61,16 +61,19 @@ beforeEach(() => {
});
describe('findUnderdescribedEntries', () => {
- it('orders the emptiest entries first and skips locked ones', () => {
- const rows = findUnderdescribedEntries(universe());
+ it('skips locked entries', () => {
+ // 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(findUnderdescribedEntries(universe()).some((row) => row.id === 'c2')).toBe(false);
+ });
+
+ it('ranks the emptiest FRACTION first, not the biggest raw gap', () => {
// 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.
+ const rows = sortByEmptiest(findUnderdescribedEntries(universe()));
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', () => {
diff --git a/server/services/quotaBurnJobs/universeBibleImages.js b/server/services/quotaBurnJobs/universeBibleImages.js
index 5356f6dff5..1740468d0c 100644
--- a/server/services/quotaBurnJobs/universeBibleImages.js
+++ b/server/services/quotaBurnJobs/universeBibleImages.js
@@ -13,21 +13,19 @@
* down the backlog instead of re-rendering the same entries.
*/
-import { getUniverse, listUniverses } from '../universeBuilder.js';
import { getWorldCategoryKeys } from '../universeBuilder/sanitize.js';
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 { BIBLE_FIELD, BIBLE_KEYS, BIBLE_KINDS } from '../../lib/storyBible.js';
import { bibleEntryIsDescribed } from '../../lib/universeBibleCompleteness.js';
+import { collectUniverseBacklog } from './universeBacklog.js';
-// 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.
-const ENTRY_BOUNDS = QUOTA_BURN_BOUNDS.maxEntries;
+// Universe array key → the canon kind `bibleEntryIsDescribed` measures. Derived
+// from `BIBLE_FIELD` rather than hand-written, so a future canon kind flows
+// through this walker the way `BIBLE_KEYS` promises.
+const CANON_TRUNK_KIND = Object.freeze(Object.fromEntries(BIBLE_KINDS.map((kind) => [BIBLE_FIELD[kind], kind])));
+const CANON_TRUNKS = BIBLE_KEYS;
const hasNoImage = (entry) => !Array.isArray(entry?.imageRefs) || entry.imageRefs.length === 0;
@@ -98,49 +96,28 @@ export function buildRenderSelection(rows) {
return { selection, canonSelection, sheetSelection };
}
-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 render next, plus the total backlog so the page can say
- * "10 of 143".
- *
- * ONE universe per run, capped to `maxEntries`: `run` makes a single
- * `renderUniverseJobs` call, which provisions one collection and one run
- * record. Spreading the budget across several universes (as an earlier version
- * did) produced a cap the run never honored and a status line that advertised
- * more universes than it touched.
+ * "10 of 143". The universe walk and the one-universe-per-run rule are shared
+ * with the describe job (`universeBacklog.js`).
*
- * `inFlight` is the set of `<universeId>:<label>` keys this job has already
- * enqueued recently. `imageRefs` only fills in when a render COMPLETES, and a
- * cloud render routinely outlives the 5–720 minute tick interval — so without
- * this the next cycle re-selects the same entries and enqueues them again,
- * spending the whole window cap re-rendering the same handful and making zero
- * progress on the backlog.
+ * `inFlight` is the set of keys this job has already enqueued recently.
+ * `imageRefs` only fills in when a render COMPLETES, and a cloud render
+ * routinely outlives the 5–720 minute tick interval — so without this the next
+ * cycle re-selects the same entries and enqueues them again, spending the whole
+ * window cap re-rendering the same handful and making zero progress.
*/
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;
- for (const universe of universes) {
+ const collected = await collectUniverseBacklog(params, {
// 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, 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, requireDescribed };
+ rowsFor: (universe) => dedupeByLabel(findMissingImageEntries(universe, { scope, requireDescribed }))
+ .filter((row) => !inFlight.has(inFlightKey(universe.id, row))),
+ });
+ return { ...collected, requireDescribed };
}
// Keyed on the same identity `dedupeByLabel` uses. Label alone would let one
@@ -196,7 +173,7 @@ export async function countPending({ params, family } = {}) {
// dispatch instead of twice — see the registry's hook contract.
context: collected,
detail: total
- ? `${total} bible ${total === 1 ? 'entry has' : 'entries have'} no image — ${next} queued next from "${picked.universe.name}"`
+ ? `${total} bible ${total === 1 ? 'entry has' : 'entries have'} no image — ${next} queued next from "${picked.universeName}"`
// 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.
@@ -225,7 +202,7 @@ export async function run({ params, job, family, context, force = false } = {})
const { selection, canonSelection, sheetSelection } = buildRenderSelection(picked.rows);
- const result = await renderUniverseJobs(picked.universe.id, {
+ const result = await renderUniverseJobs(picked.universeId, {
promptMode: 'all',
selection,
canonSelection,
@@ -239,12 +216,12 @@ export async function run({ params, job, family, context, force = false } = {})
// fills in when the render completes, so this cooldown is the only thing
// stopping the next cycle from re-selecting the same entries and spending the
// window's whole cap re-rendering them.
- await recordQuotaBurnInFlight(picked.rows.map((row) => inFlightKey(picked.universe.id, row)));
+ await recordQuotaBurnInFlight(picked.rows.map((row) => inFlightKey(picked.universeId, row)));
- console.log(`🔥 Quota-burn rendered ${result.promptCount} bible image(s) for "${picked.universe.name}" via ${result.mode}`);
+ console.log(`🔥 Quota-burn rendered ${result.promptCount} bible image(s) for "${picked.universeName}" via ${result.mode}`);
return {
dispatched: true,
- summary: `Queued ${result.promptCount} image render${result.promptCount === 1 ? '' : 's'} for "${picked.universe.name}" via ${result.mode}`,
- detail: { universeId: picked.universe.id, runId: result.runId, jobIds: result.jobIds, mode: result.mode, backlog: total, cap: max },
+ summary: `Queued ${result.promptCount} image render${result.promptCount === 1 ? '' : 's'} for "${picked.universeName}" via ${result.mode}`,
+ detail: { universeId: picked.universeId, runId: result.runId, jobIds: result.jobIds, mode: result.mode, backlog: total, cap: max },
};
}
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index e736c60062..42d79d7bc3 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -73,6 +73,13 @@ const selectJobs = (family, { jobId = null, force = false, completions = {} } =
&& (targeted || (job?.enabled !== false && !jobIsSpent(job, family.id, completions))));
};
+/**
+ * The two fields of a pending-probe the page actually renders. An allowlist
+ * rather than an omit so a job type that starts returning something new has to
+ * opt into the wire deliberately.
+ */
+const wireShape = (pending) => ({ count: pending?.count ?? 0, detail: pending?.detail ?? '' });
+
/**
* The plan, re-anchored to start just AFTER the job this family last dispatched.
*
@@ -463,7 +470,12 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {
return {
id: job.id,
ranAt,
- pending: family.enabled && !spent ? await countJobPending({ job, family }) : null,
+ // `context` is stripped: it is the probe→run hand-off (see the job
+ // registry), and it holds whatever the probe already computed —
+ // for the universe jobs a picked-universe payload. The page renders
+ // `count` and `detail` only, so shipping the rest would put probe
+ // internals on the wire and grow with every job type.
+ pending: family.enabled && !spent ? wireShape(await countJobPending({ job, family })) : null,
};
})),
};
diff --git a/server/services/universeCanonEntryExpand.js b/server/services/universeCanonEntryExpand.js
index 32ae1fe5c5..9147fb989c 100644
--- a/server/services/universeCanonEntryExpand.js
+++ b/server/services/universeCanonEntryExpand.js
@@ -18,13 +18,11 @@
* 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 { runCanonEntryExpand } from './universeCanonExpandRunner.js';
import { ServerError } from '../lib/errorHandler.js';
-import { BIBLE_FIELD, BIBLE_KIND, SANITIZERS } from '../lib/storyBible.js';
+import { 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]);
@@ -81,6 +79,12 @@ export function applyCanonEntryExpansion(kind, target, content) {
* 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.
+ *
+ * No route exposes this yet: its only caller is the quota-burn describe job.
+ * The character expand has a ✨ button because a writer iterates on the cast by
+ * hand; places and objects reached the same capability through the automation
+ * that needed it. Wiring a route + button is the obvious follow-up, and with the
+ * shared shell it is a handler and a fetch.
*/
export async function expandUniverseCanonEntry(universeId, kind, entryId, options = {}) {
if (!CANON_ENTRY_EXPAND_KINDS.includes(kind)) {
@@ -88,62 +92,22 @@ export async function expandUniverseCanonEntry(universeId, kind, entryId, option
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({
+ return runCanonEntryExpand({
+ universeId,
+ kind,
+ entryId,
templateName: 'universe-canon-entry-expand',
- variables: {
+ buildVariables: ({ universe, target, peers }) => ({
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,
+ peersJson: JSON.stringify(peers.map(peerForExpandPrompt)),
+ }),
+ applyMerge: (target, content) => applyCanonEntryExpansion(kind, target, content),
+ options,
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/universeCanonExpandRunner.js b/server/services/universeCanonExpandRunner.js
new file mode 100644
index 0000000000..b346833c0d
--- /dev/null
+++ b/server/services/universeCanonExpandRunner.js
@@ -0,0 +1,96 @@
+/**
+ * The shared shell every universe canon expand runs inside.
+ *
+ * `universeCharacterExpand.js` and `universeCanonEntryExpand.js` differ only in
+ * their prompt template, the variables it takes, and the merge that applies the
+ * response. Everything around that is the same delicate sequence, and it is the
+ * part with the contracts worth stating once:
+ *
+ * 1. Locked entries are skipped BEFORE the LLM call — a locked entry is
+ * protected from every AI rewrite path, and spending a provider round-trip
+ * to discover that is pure waste.
+ * 2. The merge is re-derived INSIDE the write queue against the freshest
+ * persisted universe, not against the copy read before the call. A user
+ * edit (or another LLM call) that lands during a multi-second round-trip
+ * would otherwise be silently overwritten.
+ * 3. The lock is re-checked in that same mutator, because it can be set during
+ * the round-trip. That case returns `locked: true` rather than "nothing to
+ * fill", so the UI shows the same Locked badge it would have shown had the
+ * lock been set a second earlier.
+ *
+ * When these lived in both services they had already drifted (one guarded the
+ * post-write read, the other dereferenced it bare). One copy, one contract.
+ */
+
+import { getUniverse, updateUniverse } from './universeBuilder.js';
+import { runPromptRefineRaw } from './pipeline/refineHelpers.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { BIBLE_FIELD } from '../lib/storyBible.js';
+import { shortId } from '../lib/fileUtils.js';
+
+/**
+ * Run one canon entry through its expand prompt and merge the result.
+ *
+ * @param {object} args
+ * @param {string} args.universeId
+ * @param {string} args.kind canon kind — picks the universe array via `BIBLE_FIELD`
+ * @param {string} args.entryId
+ * @param {string} args.templateName prompt stage to run
+ * @param {(ctx: {universe: object, target: object, peers: object[]}) => object} args.buildVariables
+ * @param {(target: object, content: object) => {merged: object, updatedFields: string[]}} args.applyMerge
+ * @param {object} [args.options] `{ providerId, model }` overrides
+ * @param {object} [args.emptyError] `{ code, message }` for an empty LLM payload
+ * @returns {Promise<{universe, entry, updatedFields, locked?, rationale?, runId?, providerId?, model?}>}
+ */
+export async function runCanonEntryExpand({
+ universeId, kind, entryId, templateName, buildVariables, applyMerge, options = {}, emptyError,
+}) {
+ 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: [] };
+ }
+
+ // logTag: null — the context-rich line is emitted AFTER the merge below, where
+ // the field count is known.
+ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({
+ templateName,
+ variables: buildVariables({ universe, target, peers: list.filter((_, i) => i !== idx) }),
+ options: { providerId: options.providerId, model: options.model },
+ source: templateName,
+ logTag: null,
+ emptyError,
+ });
+
+ 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 } = applyMerge(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;
+ const result = { universe: updated || universe, entry: latestEntry, rationale, runId, providerId, model };
+ if (lockedDuringRender) return { ...result, locked: true, updatedFields: [] };
+ if (updatedFields.length > 0) {
+ console.log(`✨ Universe ${kind} expand — universe=${shortId(universeId)} entry=${shortId(entryId)} fields=${updatedFields.length} runId=${shortId(runId)}`);
+ }
+ return { ...result, updatedFields };
+}
diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.js
index 8bd3a412de..cb9e32bdfa 100644
--- a/server/services/universeCharacterExpand.js
+++ b/server/services/universeCharacterExpand.js
@@ -11,13 +11,10 @@
* - key present with non-empty value → fill ONLY when target field is blank.
*/
-import { getUniverse, updateUniverse } from './universeBuilder.js';
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';
+import { runCanonEntryExpand } from './universeCanonExpandRunner.js';
+import { BIBLE_KIND, sanitizeBibleField } from '../lib/storyBible.js';
+import { BIBLE_EXPAND_FIELDS, bibleFieldIsBlank, SLIDER_AXES } from '../lib/universeBibleCompleteness.js';
// Adding a new extended field on `sanitizeCharacter` requires adding it to
// `BIBLE_EXPAND_FIELDS.character` too — otherwise the expand response key is
@@ -65,7 +62,7 @@ export function applyExpansion(target, content) {
if (!(field in content)) continue;
const proposed = content[field];
if (isAbsent(proposed) || typeof proposed !== 'string') continue;
- if (!isBlankString(target[field])) continue;
+ if (!bibleFieldIsBlank(target, field)) continue;
if (isBlankString(proposed)) continue;
merged[field] = proposed.trim();
updatedFields.push(field);
@@ -74,32 +71,25 @@ export function applyExpansion(target, content) {
if (!(field in content)) continue;
const proposed = content[field];
if (isAbsent(proposed) || !Array.isArray(proposed)) continue;
- if (!isBlankArray(target[field])) continue;
+ if (!bibleFieldIsBlank(target, field)) continue;
if (isBlankArray(proposed)) continue;
- // Sanitize the proposed list before recording the update. The bible
+ // Sanitize the proposed list before recording the update: the bible
// sanitizer drops rows missing required keys (stats without `label`,
- // props/expressions/gestures without `name`, palette without `name`),
- // so a raw acceptance would report `updatedFields: ['stats']` while
- // the persisted character actually saves `stats: []`. Run the proposal
- // through `sanitizeCharacter` (target's name carries the record so the
- // top-level sanitizer accepts it) and use the cleaned rows; skip the
- // field entirely when nothing survives.
- const sanitized = sanitizeCharacter(
- { name: target.name, [field]: proposed },
- { preserveTimestamps: false },
- );
- const cleaned = Array.isArray(sanitized?.[field]) ? sanitized[field] : [];
- if (cleaned.length === 0) continue;
+ // props/expressions/gestures without `name`, palette without `name`), so a
+ // raw acceptance would report `updatedFields: ['stats']` while the persisted
+ // character actually saves `stats: []`. Skip the field when nothing survives.
+ const cleaned = sanitizeBibleField('character', target, field, proposed);
+ if (!Array.isArray(cleaned) || cleaned.length === 0) continue;
merged[field] = cleaned;
updatedFields.push(field);
}
// arcType — a bare enum string, filled only when the target has no arc type.
- // Run through sanitizeCharacter so an unrecognized value (folded to null by
- // trimEnum) never records a spurious update.
- if ('arcType' in content && !isBlankString(content.arcType) && isBlankString(target.arcType)) {
- const sanitized = sanitizeCharacter({ name: target.name, arcType: content.arcType }, { preserveTimestamps: false });
- if (sanitized?.arcType) {
- merged.arcType = sanitized.arcType;
+ // Sanitized so an unrecognized value (folded to null by trimEnum) never
+ // records a spurious update.
+ if ('arcType' in content && !isBlankString(content.arcType) && bibleFieldIsBlank(target, 'arcType')) {
+ const cleaned = sanitizeBibleField('character', target, 'arcType', content.arcType);
+ if (cleaned) {
+ merged.arcType = cleaned;
updatedFields.push('arcType');
}
}
@@ -108,11 +98,11 @@ export function applyExpansion(target, content) {
// rated. Sanitize the proposal so an out-of-range value collapses to null and
// never records a bogus update.
if (content.sliders && typeof content.sliders === 'object') {
- const proposed = sanitizeCharacter({ name: target.name, sliders: content.sliders }, { preserveTimestamps: false })?.sliders || {};
+ const proposed = sanitizeBibleField('character', target, 'sliders', content.sliders) || {};
const existing = (target.sliders && typeof target.sliders === 'object') ? target.sliders : {};
const nextSliders = { ...existing };
let changed = false;
- for (const axis of ['proactivity', 'likability', 'competence']) {
+ for (const axis of SLIDER_AXES) {
if (existing[axis] == null && proposed[axis] != null) {
nextSliders[axis] = proposed[axis];
changed = true;
@@ -126,72 +116,28 @@ export function applyExpansion(target, content) {
return { merged, updatedFields };
}
+/**
+ * Fill blank fields on one canon character. The lock checks, the re-derive of
+ * the merge inside the write queue, and the return shape all live in
+ * `universeCanonExpandRunner.js` — shared with the place/object expand, which
+ * needs the same three contracts.
+ */
export async function expandUniverseCharacter(universeId, entryId, options = {}) {
- const universe = await getUniverse(universeId);
- const list = Array.isArray(universe.characters) ? universe.characters : [];
- const idx = list.findIndex((e) => e.id === entryId);
- if (idx < 0) {
- throw new ServerError(`Character ${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 peers = list.filter((_, i) => i !== idx);
-
- // logTag: null — emit a context-rich log AFTER the merge so universeId,
- // entryId, and the field count are all available.
- const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({
+ return runCanonEntryExpand({
+ universeId,
+ kind: BIBLE_KIND.CHARACTER,
+ entryId,
templateName: 'universe-character-expand',
- variables: {
+ buildVariables: ({ universe, target, peers }) => ({
styleClause: buildStyleClause(universe),
characterJson: JSON.stringify(target),
peersJson: JSON.stringify(peers.map(peerForExpandPrompt)),
- },
- options: { providerId: options.providerId, model: options.model },
- source: 'universe-character-expand',
- logTag: null,
+ }),
+ applyMerge: applyExpansion,
+ options,
emptyError: {
code: 'UNIVERSE_CHARACTER_EXPAND_EMPTY',
message: 'LLM returned an empty character expansion',
},
});
-
- // Re-derive the merge INSIDE the write queue against the freshest persisted
- // universe so a user edit (or another LLM call) that landed during the
- // expand LLM round-trip isn't silently overwritten. The mutator returns
- // null to short-circuit the write when nothing changed.
- let updatedFields = [];
- // Track WHY the write was skipped so the caller can distinguish "nothing
- // to fill" (no-op success) from "user locked the character mid-LLM-call"
- // (preserves the locked-character contract — UI shows the same "Locked"
- // badge it would for the pre-LLM-call lock check).
- let lockedDuringRender = false;
- const updated = await updateUniverse(universeId, (latest) => {
- const latestList = Array.isArray(latest.characters) ? latest.characters : [];
- const latestIdx = latestList.findIndex((e) => e.id === entryId);
- if (latestIdx < 0) return null;
- const latestTarget = latestList[latestIdx];
- // Re-check the lock — could have been set during the LLM call.
- if (latestTarget.locked === true) {
- lockedDuringRender = true;
- return null;
- }
- const { merged: next, updatedFields: fields } = applyExpansion(latestTarget, content);
- updatedFields = fields;
- if (fields.length === 0) return null;
- const nextList = latestList.map((e, i) => (i === latestIdx ? next : e));
- return { characters: nextList };
- });
- const latestEntry = (updated.characters || []).find((e) => e.id === entryId) || target;
- if (lockedDuringRender) {
- return { universe: updated, entry: latestEntry, locked: true, updatedFields: [], rationale, runId, providerId, model };
- }
- if (updatedFields.length === 0) {
- return { universe: updated, entry: latestEntry, rationale, runId, providerId, model, updatedFields };
- }
- console.log(`✨ Universe character 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/universeVisionExpand.js b/server/services/universeVisionExpand.js
index ca769b164f..e4ba138c79 100644
--- a/server/services/universeVisionExpand.js
+++ b/server/services/universeVisionExpand.js
@@ -28,13 +28,8 @@
*/
import { getUniverse } from './universeBuilder.js';
-import {
- applyExpansion,
- STRING_FIELDS,
- LIST_FIELDS,
- isBlankString,
- isBlankArray,
-} from './universeCharacterExpand.js';
+import { applyExpansion, STRING_FIELDS, LIST_FIELDS } from './universeCharacterExpand.js';
+import { bibleFieldIsBlank } from '../lib/universeBibleCompleteness.js';
import { resolveAPIProvider, parseLLMJSON } from '../lib/aiProvider.js';
import { runPromptThroughProvider, assertProvider, assertVisionRunUsedImages } from '../lib/promptRunner.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -160,10 +155,10 @@ export async function expandEntityFromImages({
return { universe, entry: target, locked: true, updatedFields: [] };
}
- const blankFields = [
- ...STRING_FIELDS.filter((f) => isBlankString(target[f])),
- ...LIST_FIELDS.filter((f) => isBlankArray(target[f])),
- ];
+ // Same blank predicate the completeness scan and the text expand use — a
+ // second implementation here is how a pre-migration character carrying only
+ // the legacy `description` alias ended up in the "still blank" ask.
+ const blankFields = [...STRING_FIELDS, ...LIST_FIELDS].filter((f) => bibleFieldIsBlank(target, f));
const provider = await resolveAPIProvider(providerId);
assertProvider(provider, {