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: enforce foundation repair contracts
[._.]/ Adam Eivyf97e4f946a62
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f045006732..b77b2c5e6f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -46,6 +46,12 @@- Track foundation convergence per owning editor instead of against one global weighted-score high-water mark, so deepening a character can legitimately surface a new structure or craft gap without Autopilot pausing before that newly selected editor gets its first bounded repair attempt.+- Reject and retry foundation craft repairs that would be silently clipped by the persisted voice-guide schema. The repair prompt now receives the exact passage/note limits as a hard contract, and an oversized or incomplete exemplar response gets one focused rewrite before any series state is changed, so a strong reference scene cannot be stored mid-sentence and then mistaken for valid evidence by the next judge.++- Show the foundation judge every authored character transition, not just each arc's start and end. The judge now reuses the canonical character-arc prompt renderer, so a confession, relapse, sacrifice, or point of no return already placed in an issue cannot be reported missing and sent through another expensive character-repair pass.++- Validate foundation world-repair prose before Universe Builder's scalar sanitizer can silently slice it. An over-limit logline, premise, or style guide now gets one focused compression retry with the exact failed size, and the repair errors without changing canon if the retry still cannot fit, instead of saving a civic rule or paragraph that stops mid-sentence.+- **A successful agent run is no longer failed just because someone pulled `main` while it worked.** The branch-jack detector — which watches whether a worktree-isolated agent committed into the primary checkout instead of its own worktree — treated *any* movement of the primary as a branch-jack. So an ordinary `git pull` landing an already-merged PR flipped a run that had shipped its own PR into a failure, and told the user to consider `git reset --hard origin/main` over commits that already *were* `origin/main`. The guard now reports what a branch-jack actually leaves behind: commits the branch's upstream does not have, or the checkout parked on a different branch than it started on. A pure fast-forward onto upstream commits is logged as movement and nothing more. When damage is real, the recovery advice is sharper too — it quotes the number of *stranded* commits rather than how far HEAD travelled, and a checkout merely left on the wrong branch with nothing stranded is told to `git checkout` back instead of being pointed at a `--hard` reset that would discard nothing. A branch with no upstream to compare against still reports, since an unpushed commit is unreviewed by definition.- **Recovering an AI provider now affects the very next routed run.** PortOS accidentally kept two in-memory provider-status services over the same JSON file: the Providers UI updated one while the AI Toolkit's runner consulted the other. A manual “Recover now” therefore looked successful and persisted correctly, yet a run started moments later could still bypass the recovered primary and spend time on a fallback. All legacy callers and the PortOS status routes now delegate to the Toolkit-owned singleton, and provider status socket events have one broadcast path instead of being emitted twice.diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.jsindex f4eafdc502..a6c2b168a6 100644--- a/server/services/pipeline/foundationJudge.js+++ b/server/services/pipeline/foundationJudge.js@@ -41,8 +41,8 @@ import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../..import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../../lib/stageRunner.js';import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';import { getStage } from '../promptService.js';-import { composeStyleNotes, sanitizeStyleGuide } from '../../lib/styleGuide.js';-import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';+import { composeStyleNotes, sanitizeStyleGuide, STYLE_GUIDE_LIMITS } from '../../lib/styleGuide.js';+import { renderCharacterArcsForPrompt, sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';import { BIBLE_SOURCE, sanitizeCharacter } from '../../lib/storyBible.js';import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { getUniverse, updateUniverse } from '../universeBuilder.js';@@ -447,7 +447,7 @@ const joinedLength = (lines) => lines.reduce((total, line) => total + line.lengt* Unbudgeted (the default) the output is byte-identical to the pre-budget* render, so the foundation judge's own section-level truncation is unchanged.*/-function renderArc(series, issues = [], { maxChars = Infinity } = {}) {+function renderArc(series, issues = [], { maxChars = Infinity, includeArcTransitions = false } = {}) {const arc = series?.arc || {};const seasons = Array.isArray(series?.seasons) ? [...series.seasons].sort((a, b) => (a.number || 0) - (b.number || 0)) : [];const orderedIssues = [...(Array.isArray(issues) ? issues : [])]@@ -475,8 +475,12 @@ function renderArc(series, issues = [], { maxChars = Infinity } = {}) {});const characterArcs = Array.isArray(series?.characterArcs) ? series.characterArcs : [];const tail = ['', `Authored character arcs (${characterArcs.length}):`];- for (const characterArc of characterArcs) {- tail.push(` - ${characterArc.characterName || characterArc.characterId || 'Unnamed'}: ${characterArc.startState || '(no start)'} → ${characterArc.endState || '(no end)'}; want=${characterArc.want || '—'}; need=${characterArc.need || '—'}`);+ if (includeArcTransitions) {+ tail.push(renderCharacterArcsForPrompt(characterArcs) || '(none)');+ } else {+ for (const characterArc of characterArcs) {+ tail.push(` - ${characterArc.characterName || characterArc.characterId || 'Unnamed'}: ${characterArc.startState || '(no start)'} → ${characterArc.endState || '(no end)'}; want=${characterArc.want || '—'}; need=${characterArc.need || '—'}`);+ }}// The spine is unconditional; episodes fill whatever is left. `remaining` goes@@ -537,8 +541,13 @@ function buildFoundationContext({ series, universe, canon, issues = [], contentMconst 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));+ // Character quality lives in the choices between start and end, not merely+ // the endpoints. Reuse the canonical authored-arc renderer here so the judge+ // sees decisions, relapses, sacrifices, and their issue placement. The+ // 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 world = worldEntitiesSummary.length > sectionMax? `${worldEntitiesSummary.slice(0, sectionMax)}\n\n[world summary truncated for judging]`: worldEntitiesSummary;@@ -725,6 +734,38 @@ const CHARACTER_FOUNDATION_BATCH_SIZE = 6;// material a reasoning model will chew through before the wall clock runs out,// not how much its context can hold.const REPAIR_OUTLINE_MAX_CHARS = 12_000;+const CRAFT_REPAIR_MAX_ATTEMPTS = 2;++function craftRepairViolations(proposal) {+ const guide = proposal?.styleGuide;+ if (!guide || typeof guide !== 'object') return ['styleGuide is missing'];+ const violations = [];+ const validateEntries = (key, { min, max }) => {+ const entries = guide[key];+ if (!Array.isArray(entries)) {+ violations.push(`${key} must be an array`);+ return;+ }+ if (entries.length < min || entries.length > max) {+ violations.push(`${key} must contain ${min}-${max} entries`);+ }+ for (const [index, entry] of entries.entries()) {+ const passage = typeof entry?.passage === 'string' ? entry.passage.trim() : '';+ const note = typeof entry?.note === 'string' ? entry.note.trim() : '';+ if (!passage) violations.push(`${key}[${index}].passage is required`);+ else if (passage.length > STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX) {+ violations.push(`${key}[${index}].passage exceeds ${STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX} characters`);+ }+ if (!note) violations.push(`${key}[${index}].note is required`);+ else if (note.length > STYLE_GUIDE_LIMITS.EXEMPLAR_NOTE_MAX) {+ violations.push(`${key}[${index}].note exceeds ${STYLE_GUIDE_LIMITS.EXEMPLAR_NOTE_MAX} characters`);+ }+ }+ };+ validateEntries('voiceExemplars', { min: 1, max: 2 });+ validateEntries('voiceAntiExemplars', { min: 1, max: STYLE_GUIDE_LIMITS.EXEMPLARS_MAX });+ return violations;+}async function runFoundationRepair(series, issues, dimension, finding, characters, options) {const stage = dimension === 'character' ? CHARACTER_FOUNDATION_STAGE : REPAIR_STAGE;@@ -743,30 +784,51 @@ async function runFoundationRepair(series, issues, dimension, finding, characterfullSeriesRoster: (options.ensembleCharacters || characters).map(renderPromptCharacter),}: characters.map(renderPromptCharacter);- const result = await runStagedLLM(stage, {- dimension,- phase: options.phase || (dimension === 'character' ? 'post-arc reconciliation' : 'foundation repair'),- foundationFindingJson: JSON.stringify({ gap: finding?.gap || '', fix: finding?.fix || '' }, null, 2),- seriesJson: JSON.stringify({- id: series.id,- name: series.name,- premise: series.premise,- targetFormat: series.targetFormat,- issueCountTarget: series.issueCountTarget,- styleNotes: series.styleNotes,- styleGuide: series.styleGuide,- characterArcs: series.characterArcs,- }, null, 2),- outline: renderArc(series, issues, { maxChars: REPAIR_OUTLINE_MAX_CHARS }),- charactersJson: JSON.stringify(charactersPayload, null, 2),- }, {- returnsJson: true,- providerDefault: options.providerId,- modelDefault: options.model,- effortDefault: options.effort,- source: stage,- });- return result?.content && typeof result.content === 'object' ? result.content : {};+ let violations = [];+ const maxAttempts = dimension === 'craft' ? CRAFT_REPAIR_MAX_ATTEMPTS : 1;+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {+ const findingPayload = { gap: finding?.gap || '', fix: finding?.fix || '' };+ if (dimension === 'craft') {+ findingPayload.hardStorageContract = {+ voiceExemplars: '1-2 entries',+ voiceAntiExemplars: `1-${STYLE_GUIDE_LIMITS.EXEMPLARS_MAX} entries`,+ passageMaxChars: STYLE_GUIDE_LIMITS.EXEMPLAR_PASSAGE_MAX,+ noteMaxChars: STYLE_GUIDE_LIMITS.EXEMPLAR_NOTE_MAX,+ requirement: 'Every passage and note must end as complete prose within these limits; storage never preserves overflow.',+ };+ if (violations.length > 0) {+ findingPayload.retryReason = `The previous proposal violated the hard storage contract: ${violations.join('; ')}. Rewrite it shorter; do not merely cut it off.`;+ }+ }+ const result = await runStagedLLM(stage, {+ dimension,+ phase: options.phase || (dimension === 'character' ? 'post-arc reconciliation' : 'foundation repair'),+ foundationFindingJson: JSON.stringify(findingPayload, null, 2),+ seriesJson: JSON.stringify({+ id: series.id,+ name: series.name,+ premise: series.premise,+ targetFormat: series.targetFormat,+ issueCountTarget: series.issueCountTarget,+ styleNotes: series.styleNotes,+ styleGuide: series.styleGuide,+ characterArcs: series.characterArcs,+ }, null, 2),+ outline: renderArc(series, issues, { maxChars: REPAIR_OUTLINE_MAX_CHARS }),+ charactersJson: JSON.stringify(charactersPayload, null, 2),+ }, {+ returnsJson: true,+ providerDefault: options.providerId,+ modelDefault: options.model,+ effortDefault: options.effort,+ source: stage,+ });+ const proposal = result?.content && typeof result.content === 'object' ? result.content : {};+ if (dimension !== 'craft') return proposal;+ violations = craftRepairViolations(proposal);+ if (violations.length === 0) return proposal;+ }+ throw new Error(`foundation craft repair failed its storage contract after ${CRAFT_REPAIR_MAX_ATTEMPTS} attempts: ${violations.join('; ')}`);}async function repairCharacters(series, issues, universe, finding, options) {diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.jsindex a68ce01f23..5c0499912a 100644--- a/server/services/pipeline/foundationJudge.test.js+++ b/server/services/pipeline/foundationJudge.test.js@@ -346,7 +346,14 @@ describe('foundation repair prompt — bounded outline', () => {number: i + 1, seasonId: 'sea-1', title: `Ep ${i + 1}`,stages: { idea: { input: 'y'.repeat(500) } },})));- stageRunner.runStagedLLM.mockResolvedValue({ content: {} });+ stageRunner.runStagedLLM.mockResolvedValue({+ content: {+ styleGuide: {+ voiceExemplars: [{ passage: 'Example passage.', note: 'example constraint' }],+ voiceAntiExemplars: [{ passage: 'Infinity shimmered.', note: 'generic abstraction' }],+ },+ },+ });await applyFoundationFix('ser-1', 'craft', { finding: { gap: 'g', fix: 'f' } });@@ -399,6 +406,30 @@ describe('foundation judge context — complete planning altitude', () => {expect(ctx.characterRoster).toContain('Story Cast 8');expect(ctx.characterRoster).not.toContain('Universe Only');});++ it('shows authored character transition beats instead of judging endpoints alone', () => {+ const ctx = __testing.buildFoundationContext({+ series: {+ name: 'Example Series',+ seasons: [],+ characterArcs: [{+ characterId: 'chr-1',+ characterName: 'Captain Example',+ want: 'Keep sole command',+ need: 'Become answerable to the crew',+ startState: 'Hides a fatal log entry',+ endState: 'Accepts conditional trust',+ transitions: [{ kind: 'point-of-no-return', atIssue: 7, label: 'Confesses the altered log to the crew and yields crisis authority.' }],+ }],+ },+ universe: {},+ canon: { characters: [{ id: 'chr-1', name: 'Captain Example' }] },+ issues: [],+ contentMax: 30_000,+ });+ expect(ctx.arc).toContain('point-of-no-return (issue 7)');+ expect(ctx.arc).toContain('Confesses the altered log to the crew and yields crisis authority.');+ });});describe('judgeFoundation — cache / fast-pass', () => {@@ -659,6 +690,41 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()expect(r).toMatchObject({ dimension: 'craft', applied: true });});+ it('retries an oversized craft proposal instead of silently truncating its evidence', async () => {+ stageRunner.runStagedLLM+ .mockResolvedValueOnce({+ content: {+ styleGuide: {+ voiceExemplars: [{ passage: 'x'.repeat(2_001), note: 'too long to persist intact' }],+ voiceAntiExemplars: [{ passage: 'Flat prose.', note: 'generic' }],+ },+ },+ })+ .mockResolvedValueOnce({+ content: {+ styleNotes: 'Concrete, controlled omniscience.',+ styleGuide: {+ voiceExemplars: [{ passage: 'The bell moved. Captain Example felt its answer in the rope.', note: 'complete material handoff' }],+ voiceAntiExemplars: [{ passage: 'Infinity shimmered sadly.', note: 'unearned abstraction' }],+ },+ },+ });++ const r = await applyFoundationFix('ser-1', 'craft', { finding: { gap: 'truncated proof', fix: 'complete the relay' } });++ expect(stageRunner.runStagedLLM).toHaveBeenCalledTimes(2);+ const firstFinding = JSON.parse(stageRunner.runStagedLLM.mock.calls[0][1].foundationFindingJson);+ const retryFinding = JSON.parse(stageRunner.runStagedLLM.mock.calls[1][1].foundationFindingJson);+ expect(firstFinding.hardStorageContract).toMatchObject({ passageMaxChars: 2_000, noteMaxChars: 200 });+ expect(retryFinding.retryReason).toMatch(/exceeds 2000 characters/);+ expect(seriesSvc.updateSeries).toHaveBeenCalledWith('ser-1', expect.objectContaining({+ styleGuide: expect.objectContaining({+ voiceExemplars: [expect.objectContaining({ passage: expect.stringContaining('Captain Example felt') })],+ }),+ }));+ expect(r).toMatchObject({ dimension: 'craft', applied: true });+ });+it('reports applied:false (not a throw) when a world fix has no linked universe', async () => {seriesSvc.getSeries.mockResolvedValue({ id: 'ser-1', name: 'S', universeId: null });const r = await applyFoundationFix('ser-1', 'worldbuilding', {});diff --git a/server/services/universeBuilderExpand.effort.test.js b/server/services/universeBuilderExpand.effort.test.jsindex 33d326a159..ef9f1d0805 100644--- a/server/services/universeBuilderExpand.effort.test.js+++ b/server/services/universeBuilderExpand.effort.test.js@@ -73,4 +73,39 @@ describe('expandWorldTemplate reasoning effort', () => {expect(call.prompt).not.toContain('Generate 5-12 categories');expect(call.prompt).not.toContain('world_pitch_poster');});++ it('retries an oversized narrative repair before persistence can clip it mid-sentence', async () => {+ runPromptThroughProviderMock+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'x'.repeat(4_001),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-oversized',+ })+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'Trade, authority, and travel now end in a complete rule.',+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-bounded',+ });++ const result = await expandWorldTemplate({+ starterPrompt: 'Example Universe',+ foundationDirective: 'Define ordinary governance.',+ providerId: 'codex-tui',+ model: 'gpt-5.6-sol',+ effort: 'ultra',+ narrativeOnly: true,+ });++ expect(runPromptThroughProviderMock).toHaveBeenCalledTimes(2);+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('premise exceeds 4000 characters (got 4001)');+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('Do not cut a sentence');+ expect(result.premise).toBe('Trade, authority, and travel now end in a complete rule.');+ expect(result.llm).toMatchObject({ provider: 'codex-tui', model: 'gpt-5.6-sol' });+ });});diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex 93859ef50b..00f4ed2064 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -40,6 +40,7 @@ import {} from "../lib/promptRunner.js";const LABEL_MAX = 80;+const NARRATIVE_REPAIR_MAX_ATTEMPTS = 2;// Bible/prompt fields the LLM sees as "current universe state" so re-expansion// stays consistent with prior refinements. Derived from LOCKABLE_FIELDS so a@@ -261,6 +262,16 @@ const extractJson = (raw) => {);};+const narrativeRepairViolations = (parsed) => [+ ['logline', LOGLINE_MAX],+ ['premise', PREMISE_MAX],+ ['styleNotes', STYLE_NOTES_MAX],+].flatMap(([key, max]) => {+ const value = typeof parsed?.[key] === 'string' ? parsed[key].trim() : '';+ if (!value) return [`${key} is missing`];+ return value.length > max ? [`${key} exceeds ${max} characters (got ${value.length})`] : [];+});+const normalizeCategories = (raw) => {// The LLM occasionally returns variations as a flat array of strings or// skips the wrapping `{ variations: [...] }` object. Coerce both shapes@@ -423,25 +434,53 @@ export async function expandWorldTemplate({`🌍 Universe Builder ${narrativeOnly ? 'repairing narrative bible' : 'expanding'} via ${provider.name}/${selectedModel || "default"} — influences in: ${totalIn ? `embrace=${safeInfluences.embrace.length} avoid=${safeInfluences.avoid.length}` : "none"} preserved: variations=${preservedVarCount} sheets=${preservedSheetCount}`,);- // runId is logged so a user debugging an empty expansion can find the- // raw stdout at data/runs/<runId>/output.txt.- const { text: raw, runId } = await runPromptThroughProvider({- provider,- model: selectedModel,- effort,- prompt: fullPrompt,- source: narrativeOnly ? "universe-builder-narrative-repair" : "universe-builder-expansion",- });- // Log raw response shape so a "0 variations" outcome is debuggable from- // the server console alone — the runId points at data/runs/<id>/output.txt- // for the full transcript.- console.log(- `🌍 Universe Builder raw response — runId=${runId} length=${raw?.length || 0}`,- );- const parsed = extractJson(raw);- console.log(- `🌍 Universe Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(",")}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(",")}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`,- );+ // runId is logged so a user debugging an empty expansion can find the raw+ // stdout at data/runs/<runId>/output.txt. Narrative repairs are prose canon:+ // silently slicing one at the persistence boundary can leave a sentence and+ // an operating rule half-written while still reporting success. Validate the+ // model's raw scalar lengths before normalization and spend one focused retry+ // that asks it to rewrite/compress within the already-declared limits.+ let raw;+ let runId;+ let parsed;+ let narrativeViolations = [];+ const maxAttempts = narrativeOnly ? NARRATIVE_REPAIR_MAX_ATTEMPTS : 1;+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {+ const retrySection = narrativeViolations.length > 0+ ? `\n\n# Storage-contract retry\nThe previous proposal could not be persisted intact: ${narrativeViolations.join('; ')}. Rewrite and compress the complete JSON fields within their declared limits. Do not cut a sentence, paragraph, rule, or list item off at the boundary.`+ : '';+ const result = await runPromptThroughProvider({+ provider,+ model: selectedModel,+ effort,+ prompt: `${fullPrompt}${retrySection}`,+ source: narrativeOnly ? "universe-builder-narrative-repair" : "universe-builder-expansion",+ });+ raw = result.text;+ runId = result.runId;+ // Log raw response shape so a "0 variations" outcome is debuggable from+ // the server console alone — the runId points at data/runs/<id>/output.txt+ // for the full transcript.+ console.log(+ `🌍 Universe Builder raw response — runId=${runId} length=${raw?.length || 0}`,+ );+ parsed = extractJson(raw);+ console.log(+ `🌍 Universe Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(",")}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(",")}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`,+ );+ if (!narrativeOnly) break;+ narrativeViolations = narrativeRepairViolations(parsed);+ if (narrativeViolations.length === 0) break;+ if (attempt + 1 < maxAttempts) {+ console.warn(`⚠️ Universe Builder narrative repair exceeded its storage contract — retrying once: ${narrativeViolations.join('; ')}`);+ }+ }+ if (narrativeViolations.length > 0) {+ throw new ServerError(+ `Universe Builder narrative repair failed its storage contract after ${NARRATIVE_REPAIR_MAX_ATTEMPTS} attempts: ${narrativeViolations.join('; ')}`,+ { status: 502, code: 'LLM_OUTPUT_CONTRACT' },+ );+ }// Distinguish "LLM omitted this key" (return null → client keeps draft)// from "LLM returned ''" (return "" → client applies the clear). The