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

feat: hold the Series foundation judge to per-character integrity depth, not a uniform blank count (#6415)

[._.]/ Adam Eivy79db2a4877f3
diff --git a/data.reference/prompts/stages/pipeline-judge-foundation.md b/data.reference/prompts/stages/pipeline-judge-foundation.md
index ec6787bbfb..bff82d5a03 100644
--- a/data.reference/prompts/stages/pipeline-judge-foundation.md
+++ b/data.reference/prompts/stages/pipeline-judge-foundation.md
@@ -26,6 +26,28 @@ You are a **harsh, critical developmental editor** judging whether a story's FOU
### Characters ({{characterCount}}) — framework completeness
{{characterRoster}}
+### Cast integrity — deterministic depth rulings
+{{castIntegrity}}
+
+The block above is a model-free pass over the same cast, and its **depth ruling
+per character is binding on your `character` score**:
+
+- `explained` — the author has ruled the interior out (unknown / not-applicable)
+ and said why. That is a finished assessment, not a gap. Do not score it as one
+ and do not ask for more.
+- `light` — a declared minor role or a flat arc. Judge only the conscious
+ pursuit (motivations, want). Never demand a Ghost, a wound, a trauma, or a
+ redemption from one of these.
+- `full` — the whole framework is fair to expect.
+
+A filled field is not integrity: a `full`-depth character whose stated control
+belief does not predict its own described behavior, whose survival, connection
+and status drives are one sentiment restated three times, or whose Lie is simply
+its theory of control reworded, is a **character** gap even though nothing is
+blank. Name that in `gap` with the field it lives in. Conversely, never
+manufacture damage to fill a slot — an absence the author explained is not a
+deficiency.
+
### Structure — the series arc & volumes
~~~~~~~~~~~~~~~~
{{arc}}
diff --git a/scripts/migrations/241-foundation-judge-repair-ownership.js b/scripts/migrations/241-foundation-judge-repair-ownership.js
index 3f626b9c27..c014b3b155 100644
--- a/scripts/migrations/241-foundation-judge-repair-ownership.js
+++ b/scripts/migrations/241-foundation-judge-repair-ownership.js
@@ -20,7 +20,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410', // post-256 (series-linked cast)
+ 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25', // post-256 (series-linked cast)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/248-foundation-judge-author-intent.js b/scripts/migrations/248-foundation-judge-author-intent.js
index bc91eb999b..c236397fb8 100644
--- a/scripts/migrations/248-foundation-judge-author-intent.js
+++ b/scripts/migrations/248-foundation-judge-author-intent.js
@@ -20,7 +20,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410', // post-256 (series-linked cast)
+ 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25', // post-256 (series-linked cast)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/255-character-visual-foundation.js b/scripts/migrations/255-character-visual-foundation.js
index 96bb894537..54262c0a4b 100644
--- a/scripts/migrations/255-character-visual-foundation.js
+++ b/scripts/migrations/255-character-visual-foundation.js
@@ -25,7 +25,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4', // post-256 (series-linked cast)
- 'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410', // post-256 (series-linked cast)
+ 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25', // post-256 (series-linked cast)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/256-series-linked-character-profiles.js b/scripts/migrations/256-series-linked-character-profiles.js
index 1643e4a3c8..de2134e24b 100644
--- a/scripts/migrations/256-series-linked-character-profiles.js
+++ b/scripts/migrations/256-series-linked-character-profiles.js
@@ -17,7 +17,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4',
- 'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410',
+ 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/364-foundation-judge-cast-integrity.js b/scripts/migrations/364-foundation-judge-cast-integrity.js
new file mode 100644
index 0000000000..089d10ae42
--- /dev/null
+++ b/scripts/migrations/364-foundation-judge-cast-integrity.js
@@ -0,0 +1,34 @@
+/**
+ * Teach the foundation judge the deterministic cast-integrity block (#6415).
+ *
+ * The judge previously held every series-linked character to one field list, so
+ * a declared minor role and a character whose interior the author explicitly
+ * ruled out both scored as incomplete leads. The new `{{castIntegrity}}` section
+ * carries a model-free depth ruling per character and makes it binding, plus the
+ * converse rule the blank count could never express: a fully populated profile
+ * whose control belief does not predict its own behavior is still a character
+ * gap. Hash replacement preserves customized prompts.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-judge-foundation.md': ['e44b6c50d741bbd21fc86f481684c410'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'foundation judge cast integrity',
+ customizedHint: (filename) =>
+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
+ ` against data/prompts/stages/${filename} and adopt the {{castIntegrity}} section\n` +
+ ' with its binding explained/light/full depth rulings.',
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/364-foundation-judge-cast-integrity.test.js b/scripts/migrations/364-foundation-judge-cast-integrity.test.js
new file mode 100644
index 0000000000..503f904292
--- /dev/null
+++ b/scripts/migrations/364-foundation-judge-cast-integrity.test.js
@@ -0,0 +1,39 @@
+import { readFileSync } from 'fs';
+import { describe, expect, it } from 'vitest';
+
+import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';
+import migration, {
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ applyMigration,
+} from './364-foundation-judge-cast-integrity.js';
+
+describe('migration 364 — foundation judge cast integrity', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-364-foundation-judge-cast-integrity-',
+ });
+
+ it('makes the depth rulings binding and separates filled fields from integrity', () => {
+ const judge = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/pipeline-judge-foundation.md`,
+ 'utf8',
+ );
+ // The variable the judge context now supplies — without it the section
+ // renders as literal mustache and the rulings say nothing.
+ expect(judge).toContain('{{castIntegrity}}');
+ expect(judge).toContain('binding on your `character` score');
+ // The three depths must each be named, or the judge cannot act on a ruling
+ // it is told to obey.
+ for (const depth of ['explained', 'light', 'full']) {
+ expect(judge).toContain(`\`${depth}\``);
+ }
+ // The two halves of the issue's contract: no manufactured trauma, and
+ // all-fields-filled is not integrity.
+ expect(judge).toContain('A filled field is not integrity');
+ expect(judge).toContain('manufacture damage to fill a slot');
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index dc9319d213..7aa206e445 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -54,7 +54,7 @@ const EXPECTED_STAGE_OLD = {
'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9', 'ef0d96f6ebde43af6c4579969d31cfb7'],
'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d', '21352c21ed6d4edb7a4b7c32704eff55'],
'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c', 'cda34127b40754ddbcc8544e3d82572b', 'd6c449c06de73a0868141c899b26e52c', '04419e382f3b46ed92bfaaa1d4f39e13', 'b7d2bac347e11171606f4c6acfcd32e1'],
- 'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f'],
+ 'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9', '4c0bd349ff4d329048c9f4ac068745d4', 'edf7850d0c724c63761bc9fb667227d9', '02a8e9215ba534b333f3a29f11f3ac4f', 'e44b6c50d741bbd21fc86f481684c410'],
'pipeline-observer.md': ['f3dc51ac077050a887c2161ee7438181'],
'pipeline-self-improve.md': ['ed0b0df42e0690d515b8dd88911931e4'],
'fableloom-weave-episode.md': ['1fea11b8c4269008561ac22a30494d46', '1b27f5b0073a304c21079aa6e2c71447', '4c9454d1537c4ebb3becbfa04fae3ed8', '18a442e39b973e4074a0d595928a665d', 'e0f8d864caa8746912b56cd567f1c09d', 'b4d363db94fd8a9928fa977745c76ff9'],
@@ -100,7 +100,7 @@ const EXPECTED_STAGE_NEW = {
'cd-plan.md': '41a61590896d1327df2c6915557361de',
'pipeline-series-generate.md': '136a21435aba2b2b212883750040b986',
'pipeline-character-foundation.md': 'c606061954b23a9957c68dd068b54dc4',
- 'pipeline-judge-foundation.md': 'e44b6c50d741bbd21fc86f481684c410',
+ 'pipeline-judge-foundation.md': '75714f0e41c77ff5c8b9623cb4fb0a25',
'pipeline-observer.md': '29e0212d2252b1be3278f20e2959eb8e',
'pipeline-self-improve.md': '95b378832ff78e5976a6a63fcf328090',
'fableloom-weave-episode.md': 'abea2442af2be2039b70deee4919c00e',
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index a459200517..680987c2fc 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -65,6 +65,7 @@ import {
buildFoundationContext,
contentHash,
countFoundationCharacterBlanks,
+ countSeriesCastIntegrityFindings,
foundationInputs,
foundationInputsHash,
pickFrameworkFields,
@@ -81,6 +82,7 @@ import {
// foundationJudge.js while their implementation lives with the context builder.
export {
countFoundationCharacterBlanks,
+ countSeriesCastIntegrityFindings,
foundationInputs,
foundationInputsHash,
rankFoundationCharacters,
@@ -347,11 +349,23 @@ export function isFoundationStale(snap, currentHash) {
// ---------- context record reads ----------
/**
- * `countFoundationCharacterBlanks` against live records. Pass `charactersOverride`
- * to measure a checkpoint's cast (the pre-repair snapshot) against the same
- * series/issue roster the live count uses, so only the cast content differs.
+ * The two objective, LLM-free measures of a `character` repair's work, read off
+ * live records. Pass `charactersOverride` to measure a checkpoint's cast (the
+ * pre-repair snapshot) against the same series/issue roster the live read uses,
+ * so only the cast CONTENT differs between a before and an after.
+ *
+ * - `blanks` — named framework/profile/visual fields that are empty across the
+ * repairable roster. Holds every character to one field list.
+ * - `integrityFindings` — deterministic cast-integrity gaps (#6415), which
+ * apply a per-character depth (a declared minor role or an author-explained
+ * unknown owes less) and are the only measure that reaches the psychology
+ * profile at all.
+ *
+ * Both are facts on disk. Neither subsumes the other: a visual-identity pass
+ * moves only `blanks`, and authoring a theory of control moves only
+ * `integrityFindings`.
*/
-export async function readFoundationCharacterBlanks(seriesId, charactersOverride = null) {
+export async function readFoundationCharacterProgress(seriesId, charactersOverride = null) {
assertValidSeriesId(seriesId);
const series = await getSeries(seriesId);
const [universe, issues] = await Promise.all([
@@ -359,7 +373,10 @@ export async function readFoundationCharacterBlanks(seriesId, charactersOverride
listIssues({ seriesId }),
]);
const characters = Array.isArray(charactersOverride) ? charactersOverride : universe?.characters;
- return countFoundationCharacterBlanks(characters, series, issues);
+ return {
+ blanks: countFoundationCharacterBlanks(characters, series, issues),
+ integrityFindings: countSeriesCastIntegrityFindings(characters, series, issues),
+ };
}
// One deliberate malformed-JSON retry (see module doc). Mirrors pipelineJudge.js.
diff --git a/server/services/pipeline/foundationJudgeContext.js b/server/services/pipeline/foundationJudgeContext.js
index af78a50b78..4157a2a82c 100644
--- a/server/services/pipeline/foundationJudgeContext.js
+++ b/server/services/pipeline/foundationJudgeContext.js
@@ -11,6 +11,7 @@ import { renderCharacterArcsForPrompt } from '../../lib/seriesCharacterArc.js';
import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';
import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';
import { PSYCHOLOGY_DRIVE_AXES } from '../../lib/storyBible.js';
+import { buildCastIntegrityReport } from '../../lib/characterIntegrity.js';
// The character-framework subset the character dimension scores (Ghost → Wound →
// Lie → Want → Need chain + secrets + arc fields). Shared by the hash projection
@@ -170,6 +171,93 @@ export function countFoundationCharacterBlanks(characters, series, issues = [])
.reduce((total, { blanks }) => total + blanks, 0);
}
+// ---------- cast integrity (#6415) ----------
+
+/**
+ * Deterministic cast-integrity gaps across the cast a `character` repair may
+ * WRITE — the shared contract scoped to this series' repairable roster.
+ *
+ * `countFoundationCharacterBlanks` above answers "how many named fields are
+ * empty" and holds every character to the SAME field list. That is the wrong
+ * question for two of this cast: a declared minor role does not owe the story a
+ * Ghost, and a character whose interior the author explicitly ruled out with a
+ * note is finished, not thin. `buildCastIntegrityReport` computes that depth
+ * per character and only reports the gaps the depth actually asks for — so the
+ * judge can be told which requirements are binding instead of scoring every
+ * spear-carrier as an incomplete lead.
+ *
+ * It is also the only deterministic view that reaches the psychology profile
+ * (#6414): none of the blank-counted field sets include `psychology`, so a
+ * repair that authors a theory of control and six drive leaves currently
+ * registers as literally zero measurable progress.
+ *
+ * Zero provider calls — safe on every judge round, exactly like the blank count.
+ *
+ * It measures the same repairable roster `countFoundationCharacterBlanks` does,
+ * so the two objective signals disagree only about what they count, never who.
+ */
+export function countSeriesCastIntegrityFindings(characters, series, issues = []) {
+ return buildCastIntegrityReport(
+ repairableSeriesFoundationCharacters(characters, series, issues),
+ ).findings.length;
+}
+
+// Why a character is held to a lighter standard, in the judge's own terms. The
+// issue is explicit that these are EXPLAINED requirements, not silent excuses:
+// a depth the prompt cannot justify reads as inconsistent scoring.
+const DEPTH_NOTE = Object.freeze({
+ explained: 'interior declared unknown/not-applicable with an author note — a finished assessment, ask nothing further',
+ light: 'declared minor role or flat arc — conscious pursuit only, no origin-damage chain',
+ full: 'full framework expected',
+});
+
+/**
+ * Render the deterministic report for the judge prompt, bounded by `maxChars`.
+ *
+ * Rows carrying gaps are emitted first so a tight budget drops the clean ones —
+ * a dropped clean line costs the judge nothing, where a dropped gap line would
+ * hide the very thing the character dimension is scored on. The header always
+ * survives, so the judge can never read a truncated block as a full pass.
+ */
+export function renderCastIntegrity(report, { maxChars = Infinity } = {}) {
+ const coverage = Array.isArray(report?.coverage) ? report.coverage : [];
+ if (coverage.length === 0) return '(no series-linked cast to measure)';
+ const byCharacter = new Map();
+ for (const finding of (Array.isArray(report?.findings) ? report.findings : [])) {
+ const own = byCharacter.get(finding.characterId) || [];
+ own.push(`${finding.field} (${finding.kind})`);
+ byCharacter.set(finding.characterId, own);
+ }
+ const withGaps = coverage.filter((row) => row.findingCount > 0).length;
+ const head = [
+ `Deterministic pass (no model call) over ${coverage.length} series-linked characters — ${withGaps} carry gaps.`,
+ `Depth rulings are BINDING: ${Object.entries(DEPTH_NOTE).map(([depth, note]) => `${depth} = ${note}`).join('; ')}.`,
+ ];
+ const rows = coverage
+ .map((row) => {
+ const gaps = byCharacter.get(row.characterId) || [];
+ const detail = gaps.length
+ ? `${gaps.length} gap${gaps.length === 1 ? '' : 's'}: ${gaps.join('; ')}`
+ : `no gaps (${DEPTH_NOTE[row.depth] || DEPTH_NOTE.full})`;
+ return { hasGaps: gaps.length > 0, line: `- **${row.characterName || 'Unnamed'}** [${row.depth}] — ${detail}` };
+ })
+ .sort((a, b) => Number(b.hasGaps) - Number(a.hasGaps));
+ let remaining = maxChars - joinedLength(head);
+ const kept = [];
+ let index = 0;
+ // Stop at the first row that does not fit rather than skipping ahead to a
+ // shorter one: the sort put the gaps first, and a greedy fill would happily
+ // drop a long gap line to keep a short clean one.
+ while (index < rows.length && rows[index].line.length + 1 <= remaining) {
+ kept.push(rows[index].line);
+ remaining -= rows[index].line.length + 1;
+ index += 1;
+ }
+ const omitted = rows.length - index;
+ if (omitted > 0) kept.push(` [${omitted} clean cast-integrity ${pluralLines(omitted)} omitted to fit the judging budget]`);
+ return [...head, ...kept].join('\n');
+}
+
// ---------- input hashing (fast-pass / staleness) ----------
// The judged foundation as a stable, hashable projection: universe canon,
@@ -477,6 +565,12 @@ export function buildFoundationContext({ series, universe, canon, issues = [], c
? seriesCharacters.map((character) => renderCharacterLine(character, { core: true })).join('\n')
: '(no canon characters)';
const sectionMax = Math.max(1_000, Math.floor(contentMax / 3));
+ // The cast's third of the budget is split between the full roster render and
+ // the deterministic integrity block. The block gets the smaller share because
+ // it summarizes material the roster already shows in full — its unique
+ // contribution is the depth ruling per character, which is one short clause.
+ const integrityMax = Math.max(400, Math.floor(sectionMax / 4));
+ const rosterMax = Math.max(600, sectionMax - integrityMax);
const world = renderWorldFoundation(universe, { maxChars: sectionMax });
// Character quality lives in the choices between start and end, not merely
// the endpoints. Reuse the canonical authored-arc renderer here so the judge
@@ -484,8 +578,8 @@ export function buildFoundationContext({ series, universe, canon, issues = [], c
// repair prompt keeps the legacy compact summary because it already receives
// the full `series.characterArcs` JSON separately.
const arcText = renderArc(series, issues, { includeArcTransitions: true });
- const roster = characterRoster.length > sectionMax
- ? `${characterRoster.slice(0, sectionMax)}\n\n[character roster truncated for judging]`
+ const roster = characterRoster.length > rosterMax
+ ? `${characterRoster.slice(0, rosterMax)}\n\n[character roster truncated for judging]`
: characterRoster;
const arcContext = arcText.length > sectionMax
? `${arcText.slice(0, sectionMax)}\n\n[series plan truncated for judging]`
@@ -499,6 +593,13 @@ export function buildFoundationContext({ series, universe, canon, issues = [], c
},
worldEntitiesSummary: world,
characterRoster: roster,
+ // Deterministic, model-free, and measured off the SAME roster the render
+ // above walks — so the depth rulings the judge is told are binding always
+ // name characters it can actually see.
+ castIntegrity: renderCastIntegrity(
+ buildCastIntegrityReport(seriesCharacters),
+ { maxChars: integrityMax },
+ ),
characterCount: seriesCharacters.length,
arc: arcContext,
};
diff --git a/server/services/pipeline/foundationJudgeContext.test.js b/server/services/pipeline/foundationJudgeContext.test.js
index 6f096db0c9..de5da5aa74 100644
--- a/server/services/pipeline/foundationJudgeContext.test.js
+++ b/server/services/pipeline/foundationJudgeContext.test.js
@@ -1,8 +1,13 @@
import { describe, it, expect } from 'vitest';
+import { buildCastIntegrityReport } from '../../lib/characterIntegrity.js';
import {
+ buildFoundationContext,
+ countFoundationCharacterBlanks,
+ countSeriesCastIntegrityFindings,
foundationInputsHash,
pickFrameworkFields,
+ renderCastIntegrity,
renderCharacterLine,
} from './foundationJudgeContext.js';
@@ -63,3 +68,88 @@ describe('foundationJudgeContext — optional psychology profile (#6414)', () =>
expect(line).toMatch(/theory: —/);
});
});
+
+// The Series surface of the shared cast-integrity contract (#6415). The judge
+// used to hold every series-linked character to one field list, so a declared
+// minor role and an author-explained unknown both scored as incomplete leads,
+// and the foundation loop's only objective progress measure could not see the
+// psychology profile at all.
+describe('foundationJudgeContext — cast integrity (#6415)', () => {
+ const series = { id: 'ser-2', name: 'Example Series', premise: 'A salvage crew.' };
+ // Fully populated framework + psychology, and mutually contradictory: the
+ // control belief promises retreat while the want is a public confrontation.
+ // Nothing is blank, so no blank count can report it.
+ const filledButIncoherent = {
+ id: 'chr-lead', name: 'Ada Vance', role: 'protagonist',
+ motivations: 'Keep the crew solvent.', ghost: 'Lost the Kesh run.',
+ wound: 'Blamed for a wreck she did not cause.', lie: 'I only matter if I win.',
+ want: 'To face the board in open session.', need: 'To be kept without winning.',
+ psychology: {
+ theoryOfControl: 'If nobody looks at me, nothing can be taken.',
+ strategy: 'Withdraws before any hearing.',
+ protectiveBenefit: 'Never tests whether she would be believed.',
+ presentCost: 'A claim that lapses every cycle.',
+ drives: {
+ survival: { desire: 'a berth', fear: 'the dock' },
+ connection: { desire: 'to be kept', fear: 'replacement' },
+ status: { desire: 'to be counted on', fear: 'surplus' },
+ },
+ },
+ };
+ const minor = { id: 'chr-minor', name: 'Dock Clerk', role: 'minor', motivations: 'Close out the shift.', want: 'A quiet gate.' };
+ const explained = {
+ id: 'chr-oracle',
+ name: 'The Oracle',
+ role: 'antagonist',
+ psychology: { assessment: 'unknown', assessmentNote: 'Read only through its effects; never given an interior.' },
+ };
+ const cast = [filledButIncoherent, minor, explained];
+ const universe = { id: 'uni-2', name: 'Example Universe', characters: cast };
+ const context = () => buildFoundationContext({
+ series, universe, canon: { characters: cast }, issues: [], contentMax: 60_000,
+ });
+
+ it('reports zero deterministic gaps for a lighter role and an explained unknown', () => {
+ // Neither owes the story an origin-damage chain, so neither may be counted
+ // as work a character repair still has to do.
+ expect(countSeriesCastIntegrityFindings([minor, explained], series)).toBe(0);
+ // The same roster held to the old uniform standard is nowhere near clean —
+ // that gap is exactly what the depth ruling exists to explain.
+ expect(countFoundationCharacterBlanks([minor, explained], series)).toBeGreaterThan(0);
+ });
+
+ it('counts the psychology profile no blank-field set reaches', () => {
+ const unassessedLead = { ...filledButIncoherent, psychology: undefined };
+ // Blank-counting sees no difference: `psychology` is in none of the
+ // framework/profile/visual field lists.
+ expect(countFoundationCharacterBlanks([unassessedLead], series))
+ .toBe(countFoundationCharacterBlanks([filledButIncoherent], series));
+ // The integrity count does, which is what lets the foundation loop accept a
+ // repair that authored a control belief and its drives.
+ expect(countSeriesCastIntegrityFindings([unassessedLead], series))
+ .toBeGreaterThan(countSeriesCastIntegrityFindings([filledButIncoherent], series));
+ });
+
+ it('hands the judge a binding depth ruling for every series character', () => {
+ const { castIntegrity } = context();
+ expect(castIntegrity).toContain('Ada Vance');
+ expect(castIntegrity).toContain('[full]');
+ expect(castIntegrity).toContain('Dock Clerk');
+ expect(castIntegrity).toContain('[light]');
+ expect(castIntegrity).toContain('The Oracle');
+ expect(castIntegrity).toContain('[explained]');
+ // A populated-but-incoherent lead has nothing blank, so the deterministic
+ // pass must NOT invent a gap for it — the semantic judgement is the judge's
+ // job, and the prompt asks for it.
+ expect(castIntegrity).toContain('**Ada Vance** [full] — no gaps');
+ });
+
+ it('never lets a truncated block read as a clean cast', () => {
+ // The header survives any budget; dropped rows are named rather than
+ // silently absent, so "no gaps listed" can never mean "nothing was checked".
+ const report = buildCastIntegrityReport(cast);
+ const tight = renderCastIntegrity(report, { maxChars: 200 });
+ expect(tight).toContain('Deterministic pass (no model call) over 3 series-linked characters');
+ expect(tight).toMatch(/\[\d+ clean cast-integrity lines? omitted/);
+ });
+});
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 8a56259ff5..c0336c1a0c 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -191,10 +191,10 @@ const judgeFoundation = vi.fn(async () => ({
const applyFoundationFix = vi.fn(async (_sId, dimension) => ({ dimension, applied: foundationFixApplied }));
const snapshotFoundationState = vi.fn(async (seriesId) => ({ seriesId, marker: 'foundation-checkpoint' }));
const restoreFoundationState = vi.fn(async () => ({ restored: true, episodesRestored: 0 }));
-// Objective blank-field count behind the character arm's tie-breaker. Default:
-// an unchanged cast (the checkpoint read and the post-repair read agree), so a
-// tie stays a tie unless a test says the repair actually filled fields.
-const readFoundationCharacterBlanks = vi.fn(async () => 0);
+// The two objective, LLM-free measures behind the character arm's tie-breaker.
+// Default: an unchanged cast (the checkpoint read and the post-repair read
+// agree), so a tie stays a tie unless a test says the repair moved one of them.
+const readFoundationCharacterProgress = vi.fn(async () => ({ blanks: 0, integrityFindings: 0 }));
vi.mock('./foundationJudge.js', async (importOriginal) => {
const actual = await importOriginal();
return {
@@ -204,7 +204,7 @@ vi.mock('./foundationJudge.js', async (importOriginal) => {
establishCharacterFoundation: (...args) => establishCharacterFoundation(...args),
snapshotFoundationState: (...args) => snapshotFoundationState(...args),
restoreFoundationState: (...args) => restoreFoundationState(...args),
- readFoundationCharacterBlanks: (...args) => readFoundationCharacterBlanks(...args),
+ readFoundationCharacterProgress: (...args) => readFoundationCharacterProgress(...args),
};
});
@@ -2329,7 +2329,9 @@ describe('autopilot conductor', () => {
},
}));
// 25 blank fields across the repairable cast before the repair, none after.
- readFoundationCharacterBlanks.mockResolvedValueOnce(25).mockResolvedValueOnce(0);
+ readFoundationCharacterProgress
+ .mockResolvedValueOnce({ blanks: 25, integrityFindings: 4 })
+ .mockResolvedValueOnce({ blanks: 0, integrityFindings: 4 });
const { seriesId } = await seedComplete();
await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 3 });
@@ -2340,6 +2342,46 @@ describe('autopilot conductor', () => {
expect(applyFoundationFix.mock.calls.map(([, dimension]) => dimension)).toEqual(['character', 'character']);
});
+ it('foundation gate: keeps a tied character repair that only closed cast-integrity gaps (#6415)', async () => {
+ // The psychology profile (#6414) is in none of the blank-counted field sets,
+ // so a repair that authored a lead's theory of control and its six drives
+ // used to register as literally zero objective progress and get rewound on a
+ // tied score. The deterministic cast-integrity count is the measure that
+ // sees it.
+ const snapshot = (weightedScore, worldbuilding) => ({
+ seriesId: 'ser-example', status: 'complete', weightedScore,
+ dimensions: {
+ worldbuilding: { score: worldbuilding, gap: 'External societies read as negotiation venues.', fix: 'Add daily practices.' },
+ character: { score: 5, gap: 'The lead states no theory of control.', fix: 'Author the control belief and drives.' },
+ structure: { score: 5, gap: 'The climax occurs in two places.', fix: 'Reconcile issue 11 and 12.' },
+ craft: { score: 8, gap: 'The exemplars are all one culture.', fix: 'Add an external-culture exemplar.' },
+ },
+ });
+ judgeFoundation
+ .mockImplementationOnce(async () => snapshot(6.5, 8))
+ .mockImplementationOnce(async () => snapshot(6.1, 7))
+ .mockImplementationOnce(async () => ({
+ seriesId: 'ser-example', status: 'complete', weightedScore: 8,
+ dimensions: {
+ worldbuilding: { score: 8, gap: 'g', fix: 'f' },
+ character: { score: 8, gap: 'g', fix: 'f' },
+ structure: { score: 8, gap: 'g', fix: 'f' },
+ craft: { score: 8, gap: 'g', fix: 'f' },
+ },
+ }));
+ // Blanks are UNCHANGED — only the integrity gaps closed.
+ readFoundationCharacterProgress
+ .mockResolvedValueOnce({ blanks: 12, integrityFindings: 7 })
+ .mockResolvedValueOnce({ blanks: 12, integrityFindings: 0 });
+
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxFoundationRounds: 3 });
+ await waitFor(runFinished(seriesId));
+
+ expect(restoreFoundationState).not.toHaveBeenCalled();
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
it('foundation gate: pauses only after repeated rejected repairs exhaust the same target', async () => {
const stalled = {
seriesId: 'ser-example', status: 'complete', weightedScore: 7,
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index a09a313867..734c7ae49b 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -15,7 +15,7 @@ import {
} from '../arcPlanner.js';
import {
judgeFoundation, applyFoundationFix, establishCharacterFoundation, foundationGateStatus, foundationFixTarget,
- residualFindings, snapshotFoundationState, restoreFoundationState, readFoundationCharacterBlanks,
+ residualFindings, snapshotFoundationState, restoreFoundationState, readFoundationCharacterProgress,
DEFAULT_FOUNDATION_THRESHOLD,
} from '../foundationJudge.js';
import * as volumeBeatsRunner from '../volumeBeatsRunner.js';
@@ -929,16 +929,24 @@ async function runFoundationRounds(seriesId, record, { bank }) {
{ location: dimension, problem: afterDimension.gap || '' },
);
// A character repair's work is objectively measurable without asking an
- // LLM: count the blank framework/visual fields across the repairable cast
- // before and after. A judge that renders or reads the cast wrongly can
- // report a tied score over a foundation it can no longer see — that cost
- // a complete five-sheet character design pass on 2026-08-11, discarded
- // because the judge prompt showed each authored field as the bare word
- // `ready`. Filled fields are a fact on disk, so they outrank a tie.
- const blanksAfter = pendingRepair.characterBlanksBefore === null
+ // LLM. A judge that renders or reads the cast wrongly can report a tied
+ // score over a foundation it can no longer see — that cost a complete
+ // five-sheet character design pass on 2026-08-11, discarded because the
+ // judge prompt showed each authored field as the bare word `ready`.
+ //
+ // Two independent facts on disk outrank that tie, and EITHER one earns
+ // the repair, because neither covers the other's ground: blank named
+ // fields (framework/profile/visual) miss the psychology profile entirely,
+ // and cast-integrity gaps (#6415) miss the visual sheets. A repair that
+ // authored a lead's theory of control and its six drives moved only the
+ // second; the 2026-08-11 design pass moved only the first.
+ const progressAfter = pendingRepair.characterProgressBefore === null
? null
- : await readFoundationCharacterBlanks(seriesId).catch(() => null);
- const objectivelyFilled = blanksAfter !== null && blanksAfter < pendingRepair.characterBlanksBefore;
+ : await readFoundationCharacterProgress(seriesId).catch(() => null);
+ const progressBefore = pendingRepair.characterProgressBefore;
+ const objectivelyFilled = progressAfter !== null
+ && (progressAfter.blanks < progressBefore.blanks
+ || progressAfter.integrityFindings < progressBefore.integrityFindings);
// A tie can represent a deeper newly exposed layer, but only when the
// aggregate did not regress. A strictly improved target is accepted even
// if it makes another latent dimension judgeable.
@@ -1092,8 +1100,8 @@ async function runFoundationRounds(seriesId, record, { bank }) {
// Measured off the checkpoint's own cast so the before/after pair differs
// only in character content — null for every other dimension, which is what
// switches the objective check off.
- const characterBlanksBefore = weak.dimension === 'character'
- ? await readFoundationCharacterBlanks(seriesId, repairSnapshot?.universe?.characters).catch(() => null)
+ const characterProgressBefore = weak.dimension === 'character'
+ ? await readFoundationCharacterProgress(seriesId, repairSnapshot?.universe?.characters).catch(() => null)
: null;
let fix;
const repairRunIds = [];
@@ -1192,7 +1200,7 @@ async function runFoundationRounds(seriesId, record, { bank }) {
judge: snap,
snapshot: repairSnapshot,
runIds: retainedRepairRunIds,
- characterBlanksBefore,
+ characterProgressBefore,
};
changed = true;
}