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

fix: finish full series character foundations

[._.]/ Adam Eivyc1cbef495da2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 537df4ca69..90a1c5aaea 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -111,6 +111,8 @@
## Series Pipeline
+- **Character-first planning now finishes the whole story cast instead of repeatedly polishing six people.** The foundation repair selector had a hard top-six cutoff, so a larger ensemble could spend every bounded repair round revisiting the same principals while later story-referenced characters remained blank. It now derives the series roster from authored arcs and issue synopses, processes every referenced character in sequential six-character work batches, and gives each batch the full ensemble map so voices, values and relationships stay differentiated. The foundation judge and its cache use that same series-scoped roster, so undeveloped characters belonging to other stories in a shared universe no longer make this series fail its character gate; before an arc exists, the small fallback remains and the architect may add only genuinely missing core roles.
+
- **A paused Series Autopilot run now resumes with its visual and gap-filing choices intact.** Those two controls were run-local, but the pause marker remembered only the current step and error. Reloading the page or restarting PortOS therefore made the Options form look like a brand-new run: visuals returned to their default and "File CoS tasks" silently turned off, so a later unresolved gap could disappear instead of being tracked. Active and paused markers now carry only those two safe continuation choices, the resume form restores them, and a completed run or different series still gets clean defaults. The one-shot "Unlock everything" consent is deliberately not re-armed: its pass already leaves the records unlocked, and repeating a spent mutation is not part of resuming.
- **Series autopilot now secures the foundation before it grows a manuscript.** The foundation judge now reads the actual volume and episode synopses, authored character arcs, and series voice/exemplars — and its cache invalidates when any of them change. A weighted average can no longer hide a critically weak dimension: every world/character/structure/craft score must also clear a floor. Character findings repair the referenced core cast as an ensemble and write whole-series character arcs instead of expanding whichever unrelated record has the most blanks; craft findings repair the series voice and add concrete tuning-fork examples instead of rewriting the universe's visual style; world findings carry the judge's specific directive into the world-bible pass. Foundation and structural verification now form one bounded planning loop: either one's repairs invalidate the other's verdict, every volume gets its own synopsis-level verification alongside the cross-volume pass, and autopilot refuses to start beat sheets until the two gates jointly converge.
diff --git a/data.reference/prompts/stages/pipeline-character-foundation.md b/data.reference/prompts/stages/pipeline-character-foundation.md
index 3281d8938e..cb4966cf4a 100644
--- a/data.reference/prompts/stages/pipeline-character-foundation.md
+++ b/data.reference/prompts/stages/pipeline-character-foundation.md
@@ -27,20 +27,24 @@ You are the senior character architect for a long-form series. Build the human e
{{outline}}
~~~~~~~~~~~~~~~~
-## Candidate core cast
+## Series cast workset
```json
{{charactersJson}}
```
+- `targetCharacters` is the exhaustive batch you must author in this response.
+- `fullSeriesRoster` is the complete story-referenced ensemble. Use it to keep values, voices, secrets, and relationship pressures distinct, but do not return a non-target existing character.
+
## Character doctrine
- Preserve the `id`, name, physical identity, and established history of every supplied character. Existing canon is a constraint, not raw material to replace.
- Make Ghost → Wound → Lie → Want → Need causal and specific. The Want must create external action; the Need must demand a costly contradiction of the Lie.
-- Give each core character distinct values, contradictions, motivation, speech rhythm, secrets, and relationships that exert pressure in both directions.
+- Give each target character distinct values, contradictions, motivation, speech rhythm, secrets, and relationships that exert pressure in both directions.
+- Return every supplied target whose framework is incomplete or whose existing engine needs the requested editorial repair. Never silently omit a target merely because the batch is large; later batches handle the rest of the roster.
- A provisional character arc describes choices and state changes, not moods. Place transitions at concrete issue numbers within the series target when one is known.
- `newCharacters` is additive and capped at three. Use it only for a missing protagonist/foil/intimate/mentor role before the arc, or a named story function the current arc truly requires afterward. Never return a replacement or near-duplicate of an existing character.
-- Return only existing characters whose framework materially improves. Never delete a character or character arc.
+- Return only target existing characters whose framework materially improves. Never delete a character or character arc.
- Character arc types: `positive|negative|flat`. Transition kinds: `decision|realization|point-of-no-return|relapse|sacrifice`.
## Output contract
diff --git a/scripts/migrations/240-character-foundation-exhaustive-cast.js b/scripts/migrations/240-character-foundation-exhaustive-cast.js
new file mode 100644
index 0000000000..8e62f0c119
--- /dev/null
+++ b/scripts/migrations/240-character-foundation-exhaustive-cast.js
@@ -0,0 +1,32 @@
+/**
+ * Upgrade the character-foundation prompt from a single implicit core-cast
+ * array to an explicit target batch plus the full series ensemble map.
+ *
+ * The server now processes every story-referenced character in sequential
+ * batches. Existing installs need this prompt wording so the model authors the
+ * whole target batch while using the full roster for differentiation. The
+ * hash-driven replacement preserves customized prompts and is idempotent.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-character-foundation.md': 'cda34127b40754ddbcc8544e3d82572b',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'exhaustive series-cast character foundation',
+ customizedHint: (filename) =>
+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
+ ` against data/prompts/stages/${filename} and adopt the targetCharacters\n` +
+ ' plus fullSeriesRoster workset contract.',
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/240-character-foundation-exhaustive-cast.test.js b/scripts/migrations/240-character-foundation-exhaustive-cast.test.js
new file mode 100644
index 0000000000..46daa853e9
--- /dev/null
+++ b/scripts/migrations/240-character-foundation-exhaustive-cast.test.js
@@ -0,0 +1,31 @@
+import { readFileSync } from 'fs';
+import { describe, it, expect } from 'vitest';
+
+import { runPromptMigrationTests, repoRoot } from './_testHelpers.js';
+import migration, {
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+} from './240-character-foundation-exhaustive-cast.js';
+
+const FILENAME = 'pipeline-character-foundation.md';
+
+describe('migration 240 — exhaustive series-cast character foundation', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-240-character-foundation-',
+ });
+
+ it('ships the target-batch and full-roster contract', () => {
+ const body = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/${FILENAME}`,
+ 'utf8',
+ );
+ expect(body).toContain('`targetCharacters` is the exhaustive batch');
+ expect(body).toContain('`fullSeriesRoster` is the complete story-referenced ensemble');
+ expect(body).toContain('Return every supplied target');
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index d131778bbb..2ebf1833a1 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -50,6 +50,7 @@ const EXPECTED_STAGE_OLD = {
'cd-treatment.md': ['2ffa482e7bfb6fe8b7224505fedbf712', '16d0ef6a7fd2533719a846019122ebee', '95b7685690ecfee4f682b0293b790277'],
'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9'],
'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d'],
+ 'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c'],
};
const EXPECTED_STAGE_NEW = {
'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f',
@@ -78,6 +79,7 @@ const EXPECTED_STAGE_NEW = {
'cd-treatment.md': 'd940eadfb406ce584f0e244032f33382',
'cd-plan.md': 'ef0d96f6ebde43af6c4579969d31cfb7',
'pipeline-series-generate.md': '21352c21ed6d4edb7a4b7c32704eff55',
+ 'pipeline-character-foundation.md': 'cda34127b40754ddbcc8544e3d82572b',
};
const EXPECTED_PARTIAL_OLD = {
'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index 37172cf785..567a6660b5 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -117,6 +117,7 @@ const snapshotPath = (seriesId) => join(foundationDir(), `${seriesId}.json`);
// render slot) doesn't needlessly invalidate the score.
export function foundationInputs(series, universe, issues = []) {
const characters = Array.isArray(universe?.characters) ? universe.characters : [];
+ const seriesCharacters = seriesFoundationCharacters(characters, series, issues);
const episodeInputs = [...(Array.isArray(issues) ? issues : [])]
.sort((a, b) => String(a?.seasonId || '').localeCompare(String(b?.seasonId || ''))
|| (a?.number ?? 9999) - (b?.number ?? 9999)
@@ -143,7 +144,11 @@ export function foundationInputs(series, universe, issues = []) {
objects: Array.isArray(universe.objects) ? universe.objects : [],
}
: null,
- characters: characters.map((c) => ({
+ // A linked universe can contain characters belonging to other stories. Only
+ // the cast referenced by THIS series is judged and hashed; otherwise an
+ // unrelated blank universe asset can keep an otherwise-ready series trapped
+ // in the character repair loop forever.
+ characters: seriesCharacters.map((c) => ({
id: c.id,
name: c.name,
role: c.role || '',
@@ -364,7 +369,7 @@ function countOccurrences(text, value) {
return count;
}
-export function rankFoundationCharacters(characters, series, issues = []) {
+export function rankFoundationCharacters(characters, series, issues = [], { includeLocked = false } = {}) {
const list = Array.isArray(characters) ? characters : [];
const storyText = JSON.stringify({
logline: series?.logline || '',
@@ -384,7 +389,7 @@ export function rankFoundationCharacters(characters, series, issues = []) {
])
.filter(Boolean));
return list
- .filter((character) => character && character.locked !== true)
+ .filter((character) => character && (includeLocked || character.locked !== true))
.map((character, index) => {
const blanks = FRAMEWORK_STRING_FIELDS.filter((field) => isBlankString(character[field])).length
+ (isBlankArray(character.secrets) ? 1 : 0);
@@ -401,12 +406,27 @@ export function rankFoundationCharacters(characters, series, issues = []) {
|| a.index - b.index);
}
-function coreFoundationCharacters(characters, series, issues = []) {
- const ranked = rankFoundationCharacters(characters, series, issues);
+/**
+ * Resolve the cast that belongs to this series from actual story references.
+ * Once a plot exists, every named/arc-linked character is retained: there is no
+ * arbitrary top-N cap. Before a plot exists, a small ranked fallback gives the
+ * character architect enough principals to start from without drafting every
+ * unrelated person in a shared universe.
+ *
+ * Locked referenced characters remain in this returned roster because the
+ * judge still has to see constraints it cannot repair. Repair callers filter
+ * them separately.
+ */
+export function seriesFoundationCharacters(characters, series, issues = []) {
+ const ranked = rankFoundationCharacters(characters, series, issues, { includeLocked: true });
const referenced = ranked.filter(({ authoredArc, mentions }) => authoredArc || mentions > 0);
- return (referenced.length > 0 ? referenced : ranked)
- .slice(0, 6)
- .map(({ character }) => character);
+ const selected = referenced.length > 0 ? referenced : ranked.slice(0, 6);
+ return selected.map(({ character }) => character);
+}
+
+function repairableSeriesFoundationCharacters(characters, series, issues = []) {
+ return seriesFoundationCharacters(characters, series, issues)
+ .filter((character) => character?.locked !== true);
}
const joinedLength = (lines) => lines.reduce((total, line) => total + line.length + 1, 0);
@@ -512,11 +532,10 @@ function renderWorldFoundation(universe) {
// overflowing; a big-context judge gets the whole foundation).
function buildFoundationContext({ series, universe, canon, issues = [], contentMax }) {
const characters = Array.isArray(canon?.characters) ? canon.characters : [];
- const coreIds = new Set(coreFoundationCharacters(characters, series, issues).map((character) => character.id));
+ const seriesCharacters = seriesFoundationCharacters(characters, series, issues);
const worldEntitiesSummary = renderWorldFoundation(universe);
- const orderedCharacters = [...characters].sort((a, b) => Number(coreIds.has(b.id)) - Number(coreIds.has(a.id)));
- const characterRoster = orderedCharacters.length
- ? orderedCharacters.map((character) => renderCharacterLine(character, { core: coreIds.has(character.id) })).join('\n')
+ const characterRoster = seriesCharacters.length
+ ? seriesCharacters.map((character) => renderCharacterLine(character, { core: true })).join('\n')
: '(no canon characters)';
const arcText = renderArc(series, issues);
const sectionMax = Math.max(1_000, Math.floor(contentMax / 3));
@@ -538,7 +557,7 @@ function buildFoundationContext({ series, universe, canon, issues = [], contentM
},
worldEntitiesSummary: world,
characterRoster: roster,
- characterCount: characters.length,
+ characterCount: seriesCharacters.length,
arc: arcContext,
};
}
@@ -686,6 +705,11 @@ const REPAIRABLE_CHARACTER_FIELDS = Object.freeze([
]);
const MAX_FOUNDATION_NEW_CHARACTERS = 3;
+// Exhaustive, not restrictive: large casts are split across as many sequential
+// calls as necessary so every story-referenced character gets authored without
+// asking one response to carry an unbounded amount of JSON. Each batch sees the
+// full ensemble map for differentiation and relationship continuity.
+const CHARACTER_FOUNDATION_BATCH_SIZE = 6;
// How much of the synopsis-level plan a repair prompt may carry. The judge
// prompt this mirrors has always been budgeted (`buildFoundationContext` caps
@@ -704,6 +728,21 @@ const REPAIR_OUTLINE_MAX_CHARS = 12_000;
async function runFoundationRepair(series, issues, dimension, finding, characters, options) {
const stage = dimension === 'character' ? CHARACTER_FOUNDATION_STAGE : REPAIR_STAGE;
+ const renderPromptCharacter = (character) => ({
+ id: character.id,
+ name: character.name,
+ role: character.role,
+ personality: character.personality,
+ background: character.background,
+ relationships: character.relationships,
+ ...pickFrameworkFields(character),
+ });
+ const charactersPayload = dimension === 'character'
+ ? {
+ targetCharacters: characters.map(renderPromptCharacter),
+ fullSeriesRoster: (options.ensembleCharacters || characters).map(renderPromptCharacter),
+ }
+ : characters.map(renderPromptCharacter);
const result = await runStagedLLM(stage, {
dimension,
phase: options.phase || (dimension === 'character' ? 'post-arc reconciliation' : 'foundation repair'),
@@ -719,15 +758,7 @@ async function runFoundationRepair(series, issues, dimension, finding, character
characterArcs: series.characterArcs,
}, null, 2),
outline: renderArc(series, issues, { maxChars: REPAIR_OUTLINE_MAX_CHARS }),
- charactersJson: JSON.stringify(characters.map((character) => ({
- id: character.id,
- name: character.name,
- role: character.role,
- personality: character.personality,
- background: character.background,
- relationships: character.relationships,
- ...pickFrameworkFields(character),
- })), null, 2),
+ charactersJson: JSON.stringify(charactersPayload, null, 2),
}, {
returnsJson: true,
providerDefault: options.providerId,
@@ -739,9 +770,51 @@ async function runFoundationRepair(series, issues, dimension, finding, character
}
async function repairCharacters(series, issues, universe, finding, options) {
- const targets = coreFoundationCharacters(universe?.characters, series, issues);
- const proposal = await runFoundationRepair(series, issues, 'character', finding, targets, options);
- const proposedCharacters = Array.isArray(proposal.characters) ? proposal.characters : [];
+ const seriesRoster = seriesFoundationCharacters(universe?.characters, series, issues);
+ const targets = seriesRoster.filter((character) => character?.locked !== true);
+ const targetBatches = targets.length > 0
+ ? Array.from({ length: Math.ceil(targets.length / CHARACTER_FOUNDATION_BATCH_SIZE) }, (_, index) => (
+ targets.slice(index * CHARACTER_FOUNDATION_BATCH_SIZE, (index + 1) * CHARACTER_FOUNDATION_BATCH_SIZE)
+ ))
+ : [[]];
+ const proposals = [];
+ let workingRoster = [...seriesRoster];
+ const workingNewCharacters = [];
+ for (const originalBatch of targetBatches) {
+ const batchIds = new Set(originalBatch.map((character) => character.id));
+ const targetBatch = workingRoster.filter((character) => batchIds.has(character.id));
+ const proposal = await runFoundationRepair(series, issues, 'character', finding, targetBatch, {
+ ...options,
+ // Locked cast members are immutable constraints, but the model still
+ // needs to see them when differentiating relationships and voices.
+ // Later batches also see the accepted shape of earlier proposals, so two
+ // batches cannot independently invent the same voice or relationship.
+ ensembleCharacters: [...workingRoster, ...workingNewCharacters],
+ });
+ proposals.push(proposal);
+
+ const proposedById = new Map((Array.isArray(proposal.characters) ? proposal.characters : [])
+ .filter((character) => typeof character?.id === 'string')
+ .map((character) => [character.id, character]));
+ workingRoster = workingRoster.map((character) => {
+ const raw = proposedById.get(character.id);
+ if (!raw) return character;
+ return sanitizeCharacter({ ...character, ...raw, id: character.id, name: character.name }) || character;
+ });
+ const knownNames = new Set([...workingRoster, ...workingNewCharacters]
+ .map((character) => String(character?.name || '').trim().toLowerCase())
+ .filter(Boolean));
+ for (const raw of Array.isArray(proposal.newCharacters) ? proposal.newCharacters : []) {
+ if (workingNewCharacters.length >= MAX_FOUNDATION_NEW_CHARACTERS) break;
+ const nameKey = String(raw?.name || '').trim().toLowerCase();
+ if (!nameKey || knownNames.has(nameKey)) continue;
+ workingNewCharacters.push(raw);
+ knownNames.add(nameKey);
+ }
+ }
+ const proposedCharacters = proposals.flatMap((proposal) => (
+ Array.isArray(proposal.characters) ? proposal.characters : []
+ ));
const proposalById = new Map(proposedCharacters
.filter((character) => typeof character?.id === 'string')
.map((character) => [character.id, character]));
@@ -772,9 +845,9 @@ async function repairCharacters(series, issues, universe, finding, options) {
const knownNames = new Set(characters
.map((character) => String(character?.name || '').trim().toLowerCase())
.filter(Boolean));
- const proposedNewCharacters = Array.isArray(proposal.newCharacters)
- ? proposal.newCharacters.slice(0, MAX_FOUNDATION_NEW_CHARACTERS)
- : [];
+ const proposedNewCharacters = proposals
+ .flatMap((proposal) => (Array.isArray(proposal.newCharacters) ? proposal.newCharacters : []))
+ .slice(0, MAX_FOUNDATION_NEW_CHARACTERS);
for (const raw of proposedNewCharacters) {
const nameKey = String(raw?.name || '').trim().toLowerCase();
if (!nameKey || knownNames.has(nameKey)) continue;
@@ -800,7 +873,8 @@ async function repairCharacters(series, issues, universe, finding, options) {
...(Array.isArray(universe?.characters) ? universe.characters : []),
...addedCharacters,
].map((character) => [String(character?.name || '').trim().toLowerCase(), character?.id]));
- const proposedArcs = sanitizeCharacterArcList((Array.isArray(proposal.characterArcs) ? proposal.characterArcs : [])
+ const proposedArcs = sanitizeCharacterArcList(proposals
+ .flatMap((proposal) => (Array.isArray(proposal.characterArcs) ? proposal.characterArcs : []))
.map((arc) => ({
...arc,
characterId: characterIdByName.get(String(arc?.characterName || '').trim().toLowerCase()) || arc?.characterId,
@@ -866,7 +940,7 @@ export async function establishCharacterFoundation(seriesId, {
if (!universe) {
return { applied: false, skipped: true, ran: false, reason: 'linked universe not found' };
}
- const targets = coreFoundationCharacters(universe.characters, series, []);
+ const targets = repairableSeriesFoundationCharacters(universe.characters, series, []);
const authoredArcs = Array.isArray(series.characterArcs) ? series.characterArcs : [];
const arcKeys = new Set(authoredArcs.flatMap((arc) => [
arc?.characterId || '',
@@ -1062,5 +1136,6 @@ export const __testing = {
renderArc,
renderCharacterLine,
REPAIR_OUTLINE_MAX_CHARS,
+ CHARACTER_FOUNDATION_BATCH_SIZE,
FRAMEWORK_STRING_FIELDS,
};
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index 20eefe8414..37fa9e459c 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -66,6 +66,7 @@ const {
establishCharacterFoundation,
thinnestCharacter,
rankFoundationCharacters,
+ seriesFoundationCharacters,
foundationInputsHash,
FOUNDATION_DIMENSIONS,
FOUNDATION_WEIGHTS,
@@ -194,6 +195,25 @@ describe('foundationInputsHash + staleness — fast-pass pinning', () => {
const uni2 = { characters: [{ id: 'c1', name: 'Ana', wound: 'abandoned as a child' }] };
expect(foundationInputsHash({}, uni1)).not.toBe(foundationInputsHash({}, uni2));
});
+ it('ignores unrelated universe-only characters once the series cast is identifiable', () => {
+ const series = { premise: 'Lead crosses the flooded city.' };
+ const base = {
+ characters: [
+ { id: 'lead', name: 'Lead', wound: 'abandoned' },
+ { id: 'extra', name: 'Unrelated Extra', wound: '' },
+ ],
+ };
+ const unrelatedEdit = {
+ characters: [
+ base.characters[0],
+ { ...base.characters[1], wound: 'changed outside this series' },
+ ],
+ };
+ expect(foundationInputsHash(series, base)).toBe(foundationInputsHash(series, unrelatedEdit));
+ expect(foundationInputsHash(series, base)).not.toBe(foundationInputsHash(series, {
+ characters: [{ ...base.characters[0], wound: 'changed in this series' }, base.characters[1]],
+ }));
+ });
it('changes when episode synopses, character arcs, or series voice changes', () => {
const series = {
seasons: [{ id: 'sea-1', number: 1, synopsis: 'Volume plan' }],
@@ -243,6 +263,28 @@ describe('rankFoundationCharacters — core-cast repair targets', () => {
const issues = [{ stages: { idea: { input: 'Lead risks everything.' } } }];
expect(rankFoundationCharacters(characters, series, issues)[0].character.id).toBe('chr-lead');
});
+
+ it('keeps every story-referenced character instead of truncating after six', () => {
+ const characters = Array.from({ length: 9 }, (_, index) => ({
+ id: `chr-${index + 1}`,
+ name: `Cast ${index + 1}`,
+ }));
+ const series = {
+ characterArcs: characters.map((character) => ({
+ characterId: character.id,
+ characterName: character.name,
+ })),
+ };
+ expect(seriesFoundationCharacters(characters, series)).toHaveLength(9);
+ });
+
+ it('uses a six-character fallback only before story references exist', () => {
+ const characters = Array.from({ length: 9 }, (_, index) => ({
+ id: `chr-${index + 1}`,
+ name: `Cast ${index + 1}`,
+ }));
+ expect(seriesFoundationCharacters(characters, {})).toHaveLength(6);
+ });
});
describe('renderArc — episode-list budget', () => {
@@ -334,6 +376,29 @@ describe('foundation judge context — complete planning altitude', () => {
expect(ctx.worldEntitiesSummary).toContain('rituals: The Naming Tax');
expect(ctx.characterRoster).toContain('wound: Abandoned during the Naming Tax');
});
+
+ it('judges the complete story-referenced cast and excludes unrelated universe assets', () => {
+ const storyCast = Array.from({ length: 8 }, (_, index) => ({
+ id: `chr-${index + 1}`,
+ name: `Story Cast ${index + 1}`,
+ wound: `Wound ${index + 1}`,
+ }));
+ const unrelated = { id: 'chr-unrelated', name: 'Universe Only', wound: '' };
+ const ctx = __testing.buildFoundationContext({
+ series: {
+ name: 'Example Series',
+ characterArcs: storyCast.map((character) => ({ characterId: character.id })),
+ seasons: [],
+ },
+ universe: {},
+ canon: { characters: [...storyCast, unrelated] },
+ issues: [],
+ contentMax: 30_000,
+ });
+ expect(ctx.characterCount).toBe(8);
+ expect(ctx.characterRoster).toContain('Story Cast 8');
+ expect(ctx.characterRoster).not.toContain('Universe Only');
+ });
});
describe('judgeFoundation — cache / fast-pass', () => {
@@ -392,6 +457,51 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()
expect(r).toMatchObject({ dimension: 'character', applied: true, characterArcsUpdated: true });
});
+ it('repairs a large referenced cast through exhaustive sequential batches', async () => {
+ const characters = Array.from({ length: 8 }, (_, index) => ({
+ id: `chr-${index + 1}`,
+ name: `Cast ${index + 1}`,
+ }));
+ const series = {
+ id: 'ser-1', name: 'S', premise: 'P', universeId: 'uni-1',
+ characterArcs: characters.map((character) => ({
+ characterId: character.id,
+ characterName: character.name,
+ })),
+ };
+ const uni = { id: 'uni-1', characters };
+ seriesSvc.getSeries.mockResolvedValue(series);
+ universeBuilder.getUniverse.mockResolvedValue(uni);
+ universeBuilder.updateUniverse.mockImplementation(async (id, mutator) => ({ id, ...(mutator(uni) || {}) }));
+ stageRunner.runStagedLLM.mockImplementation(async (_stage, vars) => {
+ const payload = JSON.parse(vars.charactersJson);
+ return {
+ content: {
+ characters: payload.targetCharacters.map((character) => ({
+ ...character,
+ ghost: 'A failed rescue', wound: 'Fears dependence', lie: 'Trust kills',
+ want: 'Work alone', need: 'Choose interdependence', coreTheme: 'trust',
+ motivations: 'Protect the crew', speechPattern: 'clipped clauses',
+ arcType: 'positive', secrets: ['Caused the breach'],
+ })),
+ },
+ };
+ });
+
+ const r = await applyFoundationFix('ser-1', 'character', {
+ finding: { gap: 'incomplete ensemble', fix: 'complete every referenced character' },
+ });
+
+ const calls = stageRunner.runStagedLLM.mock.calls
+ .filter(([stage]) => stage === 'pipeline-character-foundation');
+ expect(calls).toHaveLength(2);
+ expect(calls.map(([, vars]) => JSON.parse(vars.charactersJson).targetCharacters.length)).toEqual([6, 2]);
+ expect(calls.every(([, vars]) => JSON.parse(vars.charactersJson).fullSeriesRoster.length === 8)).toBe(true);
+ const secondRoster = JSON.parse(calls[1][1].charactersJson).fullSeriesRoster;
+ expect(secondRoster.find((character) => character.id === 'chr-1').wound).toBe('Fears dependence');
+ expect(r).toMatchObject({ applied: true, entryIds: characters.map((character) => character.id) });
+ });
+
it('adds a genuinely missing story character and links its authored arc', async () => {
const uni = { id: 'uni-1', characters: [] };
seriesSvc.getSeries.mockResolvedValue({