Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve character evidence during foundation repair (#7152)
[._.]/81239ed90bcd
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex dfd7d5b859..6c8d089a10 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -42,7 +42,7 @@ import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBimport { getStage } from '../promptService.js';import { composeStyleNotes, sanitizeStyleGuide, STYLE_GUIDE_LIMITS } from '../../lib/styleGuide.js';import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';-import { BIBLE_KEYS, BIBLE_SOURCE, sanitizeCharacter } from '../../lib/storyBible.js';+import { BIBLE_KEYS, BIBLE_SOURCE, normalizeBibleName, sanitizeCharacter } from '../../lib/storyBible.js';import { getUniverse, updateUniverse } from '../universeBuilder.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';import { expandWorldTemplate, narrativeRepairTargets } from '../universeBuilderExpand.js';@@ -77,7 +77,7 @@ import {repairableSeriesFoundationCharacters,seriesFoundationCharacters,} from './foundationJudgeContext.js';-import { trimTo, isNonBlankStr } from '../../lib/textUtils.js';+import { escapeRegExp, trimTo, isNonBlankStr } from '../../lib/textUtils.js';// Compatibility surface: callers keep importing these projection helpers from// foundationJudge.js while their implementation lives with the context builder.@@ -826,25 +826,24 @@ function craftRepairViolations(proposal) {return violations;}+const renderPromptCharacter = (character) => ({+ id: character.id,+ name: character.name,+ role: character.role,+ ...Object.fromEntries(PROFILE_STRING_FIELDS.map((field) => [field, character[field] || ''])),+ ...pickFrameworkFields(character),+ ...pickVisualFoundationFields(character),+ postureNotes: character.postureNotes || '',+ specialTraits: character.specialTraits || '',+ stats: Array.isArray(character.stats) ? character.stats : [],+ props: Array.isArray(character.props) ? character.props : [],+ expressions: Array.isArray(character.expressions) ? character.expressions : [],+ handGestures: Array.isArray(character.handGestures) ? character.handGestures : [],+ wardrobes: Array.isArray(character.wardrobes) ? character.wardrobes : [],+});+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),- ...pickVisualFoundationFields(character),- postureNotes: character.postureNotes || '',- specialTraits: character.specialTraits || '',- stats: Array.isArray(character.stats) ? character.stats : [],- props: Array.isArray(character.props) ? character.props : [],- expressions: Array.isArray(character.expressions) ? character.expressions : [],- handGestures: Array.isArray(character.handGestures) ? character.handGestures : [],- wardrobes: Array.isArray(character.wardrobes) ? character.wardrobes : [],- });const charactersPayload = dimension === 'character'? {targetCharacters: characters.map(renderPromptCharacter),@@ -901,7 +900,18 @@ async function runFoundationRepair(series, issues, dimension, finding, characterasync function repairCharacters(series, issues, universe, finding, options) {const seriesRoster = seriesFoundationCharacters(universe?.characters, series, issues);- const targets = seriesRoster.filter((character) => character?.locked !== true);+ const repairable = seriesRoster.filter((character) => character?.locked !== true);+ const directive = normalizeBibleName(`${finding?.gap || ''} ${finding?.fix || ''}`);+ const namedCast = seriesRoster.filter((character) => [character.name, ...(Array.isArray(character.aliases) ? character.aliases : [])]+ .some((name) => typeof name === 'string' && name.trim()+ && new RegExp(`(?<![\\p{L}\\p{N}_])${escapeRegExp(normalizeBibleName(name))}(?![\\p{L}\\p{N}_])`, 'u').test(directive)));+ // A named post-arc finding owns that character's repair. Starting a new+ // foundation or reconciling an ensemble-wide finding still covers the cast.+ const namedRepair = options.phase !== 'pre-arc character foundation' && namedCast.length > 0;+ const targets = namedRepair+ ? namedCast.filter((character) => character.locked !== true)+ : repairable;+ if (namedRepair && targets.length === 0) return { applied: false, reason: 'the named character repair targets are locked' };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)@@ -910,20 +920,41 @@ async function repairCharacters(series, issues, universe, finding, options) {const proposals = [];let workingRoster = [...seriesRoster];const workingNewCharacters = [];- for (const originalBatch of targetBatches) {+ while (targetBatches.length > 0) {+ const originalBatch = targetBatches.shift();const batchIds = new Set(originalBatch.map((character) => character.id));const targetBatch = workingRoster.filter((character) => batchIds.has(character.id));+ const ensembleCharacters = [...workingRoster, ...workingNewCharacters];+ const preview = JSON.parse(renderRepairCharactersJson({+ targetCharacters: targetBatch.map(renderPromptCharacter),+ fullSeriesRoster: ensembleCharacters.map(renderPromptCharacter),+ }));+ if (preview.targetNote) {+ // Shrink the batch before shrinking the records it is allowed to edit.+ // A 40-character field cap erased whole designs in a real repair prompt.+ if (originalBatch.length > 1) {+ const midpoint = Math.ceil(originalBatch.length / 2);+ targetBatches.unshift(originalBatch.slice(0, midpoint), originalBatch.slice(midpoint));+ continue;+ }+ throw new Error(`Character foundation cannot safely fit the complete repair context for ${targetBatch[0]?.name || 'the target character'} within ${REPAIR_CHARACTERS_MAX_CHARS} characters. Shorten that character's supporting detail before retrying; no truncated character repair was sent.`);+ }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],+ ensembleCharacters,});- proposals.push(proposal);+ const boundedProposal = {+ ...proposal,+ characters: (Array.isArray(proposal.characters) ? proposal.characters : [])+ .filter((character) => batchIds.has(character?.id)),+ };+ proposals.push(boundedProposal);- const proposedById = new Map((Array.isArray(proposal.characters) ? proposal.characters : [])+ const proposedById = new Map(boundedProposal.characters.filter((character) => typeof character?.id === 'string').map((character) => [character.id, character]));workingRoster = workingRoster.map((character) => {@@ -1014,7 +1045,9 @@ async function repairCharacters(series, issues, universe, finding, options) {.map((arc) => ({...arc,characterId: characterIdByName.get(String(arc?.characterName || '').trim().toLowerCase()) || arc?.characterId,- })));+ })))+ .filter((arc) => !namedRepair || targetIds.has(arc.characterId)+ || addedCharacters.some((character) => character.id === arc.characterId));let arcsApplied = false;if (proposedArcs.length > 0) {const latestSeries = await getSeries(series.id);diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex e7d951550d..0979787109 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -897,6 +897,18 @@ describe('foundation repair prompt — bounded outline', () => {});describe('foundation judge context — complete planning altitude', () => {+ it('retains the causal end of a character history and each secret in the judge context', () => {+ const ghost = 'After an earlier rescue failed, the lead spent a long night completing incident paperwork at the office. A friend stayed without asking anything in return; she mistook care for payment for her useful work.';+ const secrets = ['She altered the original report.', 'Her friend has already seen the unedited copy.', 'The supervisor kept a duplicate.'];+ const ctx = __testing.buildFoundationContext({+ series: { characterArcs: [{ characterId: 'chr-1' }] }, universe: {},+ canon: { characters: [{ id: 'chr-1', name: 'Lead', ghost, secrets }] },+ issues: [], contentMax: 30_000,+ });+ expect(ctx.characterRoster).toContain(ghost);+ for (const secret of secrets) expect(ctx.characterRoster).toContain(secret);+ });+it('shows narrative canon but omits noncanonical visual prompt families the repair cannot change', () => {const ctx = __testing.buildFoundationContext({series: { name: 'Example Series', seasons: [] },@@ -1176,6 +1188,69 @@ describe('judgeFoundation — cache / fast-pass', () => {});describe('applyFoundationFix — dimension → owning-service routing table', () => {+ it('repairs a named character without rewriting the already-developed ensemble', async () => {+ const characters = [+ { id: 'lead', name: 'Lead', want: 'Stay with the crew' },+ { id: 'handler', name: 'Rival handler', aliases: ['Corin Voss'], age: '46', pronouns: 'he/him' },+ ];+ const universe = { id: 'uni-1', characters };+ seriesSvc.getSeries.mockResolvedValue({ id: 'ser-1', universeId: 'uni-1', characterArcs: characters.map((c) => ({ characterId: c.id })) });+ universeBuilder.getUniverse.mockResolvedValue(universe);+ let saved;+ universeBuilder.updateUniverse.mockImplementation(async (_id, mutator) => {+ saved = { ...universe, ...mutator(universe) }; return saved;+ });+ stageRunner.runStagedLLM.mockResolvedValue({ content: {+ characters: [+ { id: 'handler', wound: 'Unplanned movement recalls the crush.' },+ { id: 'lead', want: 'An unrelated new ambition' },+ ],+ characterArcs: [{ characterId: 'lead', characterName: 'Lead', want: 'An unrelated new ambition', startState: 'alone', endState: 'famous' }],+ } });++ await applyFoundationFix('ser-1', 'character', { finding: { gap: 'Corin Voss lacks a specific control belief.', fix: 'Complete his psychology.' } });++ const payload = JSON.parse(stageRunner.runStagedLLM.mock.calls[0][1].charactersJson);+ expect(payload.targetCharacters).toEqual([expect.objectContaining({ id: 'handler', age: '46', pronouns: 'he/him' })]);+ expect(saved.characters.find((c) => c.id === 'lead').want).toBe('Stay with the crew');+ expect(saved.characters.find((c) => c.id === 'handler').wound).toBe('Unplanned movement recalls the crush.');+ expect(seriesSvc.updateSeries).not.toHaveBeenCalled();+ });++ it('splits large character repairs before any target history or design is truncated', async () => {+ const characters = Array.from({ length: 6 }, (_, index) => ({+ id: `chr-${index}`, name: `Cast ${index}`, background: 'Known life and consequences. '.repeat(80),+ physicalDescription: 'Established appearance and clothing. '.repeat(50),+ }));+ const universe = { id: 'uni-1', characters };+ seriesSvc.getSeries.mockResolvedValue({ id: 'ser-1', universeId: 'uni-1', characterArcs: characters.map((c) => ({ characterId: c.id })) });+ universeBuilder.getUniverse.mockResolvedValue(universe);+ stageRunner.runStagedLLM.mockResolvedValue({ content: { characters: [] } });++ await applyFoundationFix('ser-1', 'character', { finding: { gap: 'The ensemble needs distinct drives.', fix: 'Complete the cast.' } });++ const payloads = stageRunner.runStagedLLM.mock.calls.map(([, vars]) => JSON.parse(vars.charactersJson));+ expect(payloads.length).toBeGreaterThan(1);+ expect(payloads.flatMap((p) => p.targetCharacters).map((c) => c.id)).toEqual(characters.map((c) => c.id));+ for (const payload of payloads) {+ expect(payload.targetNote).toBeUndefined();+ for (const target of payload.targetCharacters) {+ const original = characters.find((c) => c.id === target.id);+ expect(target.background).toBe(original.background);+ expect(target.physicalDescription).toBe(original.physicalDescription);+ }+ }+ });++ it('refuses an oversized single-character repair before calling a provider or writing canon', async () => {+ const universe = { id: 'uni-1', characters: [{ id: 'lead', name: 'Lead', background: 'x'.repeat(20_000) }] };+ universeBuilder.getUniverse.mockResolvedValue(universe);+ await expect(applyFoundationFix('ser-1', 'character', { finding: { gap: 'Lead needs a clearer fear.' } }))+ .rejects.toThrow('cannot safely fit the complete repair context for Lead');+ expect(stageRunner.runStagedLLM).not.toHaveBeenCalled();+ expect(universeBuilder.updateUniverse).not.toHaveBeenCalled();+ });+it('routes structure → arc resolve (resolveVerifyIssues) with a synthesized finding', async () => {const r = await applyFoundationFix('ser-1', 'structure', { finding: { gap: 'thin midpoint', fix: 'add a reversal' } });expect(arcPlanner.resolveVerifyIssues).toHaveBeenCalledWith('ser-1', expect.objectContaining({diff --git a/server/services/pipeline/foundationJudgeContext.js b/server/services/pipeline/foundationJudgeContext.jsindex 932fc67da3..42744e9172 100644--- a/server/services/pipeline/foundationJudgeContext.js+++ b/server/services/pipeline/foundationJudgeContext.js@@ -241,6 +241,7 @@ export function foundationInputs(series, universe, issues = []) {synopsis: issue?.stages?.idea?.input || '',}));return {+ judgeContextVersion: 2,world: universe? {// The starter prompt is the author's protected originating intent, not@@ -308,7 +309,7 @@ export function renderCharacterLine(c, { core = false } = {}) {return compact.length <= maxChars ? compact : `${compact.slice(0, maxChars - 1).trimEnd()}…`;};const framework = FRAMEWORK_STRING_FIELDS- .map((field) => `${field}: ${concise(c?.[field])}`)+ .map((field) => `${field}: ${concise(c?.[field], field === 'ghost' ? 1_000 : 600)}`).join(' | ');const aliases = (Array.isArray(c?.aliases) ? c.aliases : []).filter((alias) => typeof alias === 'string' && alias.trim())@@ -318,7 +319,7 @@ export function renderCharacterLine(c, { core = false } = {}) {.map((field) => `${field}: ${concise(c?.[field])}`).join(' | ');const secrets = (Array.isArray(c?.secrets) ? c.secrets : [])- .map(concise)+ .map((secret) => concise(secret, 300)).slice(0, 3).join('; ');// The harsh judge needs the actual render identity, not a presence marker.