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: converge world repair compression
[._.]/ Adam Eivyf79fa9182d4a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b77b2c5e6f..c1e43c7202 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -50,7 +50,9 @@- 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.+- Validate foundation world-repair prose before Universe Builder's scalar sanitizer can silently slice it. An over-limit logline, premise, or style-notes field now gets up to two focused compression retries with the exact failed size, and the repair errors without changing canon if neither retry can fit, instead of saving a civic rule or paragraph that stops mid-sentence.++- Make over-limit world-bible retries compress the rejected draft itself instead of rerunning the original generation prompt. Two progressively tighter headroom passes preserve the draft's names, causal mechanics, costs, jurisdictions, and site operations while removing repetition, so an otherwise strong repair can converge on the persisted contract without regenerating the same oversized answer.- **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.diff --git a/server/services/universeBuilderExpand.effort.test.js b/server/services/universeBuilderExpand.effort.test.jsindex ef9f1d0805..4be7852715 100644--- a/server/services/universeBuilderExpand.effort.test.js+++ b/server/services/universeBuilderExpand.effort.test.js@@ -74,7 +74,7 @@ describe('expandWorldTemplate reasoning effort', () => {expect(call.prompt).not.toContain('world_pitch_poster');});- it('retries an oversized narrative repair before persistence can clip it mid-sentence', async () => {+ it('compresses the actual oversized narrative draft before persistence can clip it', async () => {runPromptThroughProviderMock.mockResolvedValueOnce({text: JSON.stringify({@@ -104,8 +104,86 @@ describe('expandWorldTemplate reasoning effort', () => {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(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain(`"premise": "${'x'.repeat(200)}`);+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('premise: at most 3600 characters');+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('Do not cut off a sentence');+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).not.toContain('# Starter idea');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' });});++ it('tightens headroom while carrying the latest rejected draft into a final compression pass', async () => {+ runPromptThroughProviderMock+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'a'.repeat(5_000),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-oversized',+ })+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'b'.repeat(4_200),+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-still-oversized',+ })+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'A complete, compact operating 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(3);+ expect(runPromptThroughProviderMock.mock.calls[2][0].prompt).toContain(`"premise": "${'b'.repeat(200)}`);+ expect(runPromptThroughProviderMock.mock.calls[2][0].prompt).toContain('premise: at most 3200 characters');+ expect(runPromptThroughProviderMock.mock.calls[2][0].prompt).not.toContain(`"premise": "${'a'.repeat(200)}`);+ expect(result.premise).toBe('A complete, compact operating rule.');+ });++ it('retries the source task when there is no complete draft to compress', async () => {+ runPromptThroughProviderMock+ .mockResolvedValueOnce({+ text: JSON.stringify({+ premise: 'A world without its required pitch.',+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-missing-field',+ })+ .mockResolvedValueOnce({+ text: JSON.stringify({+ logline: 'A repaired world.',+ premise: 'A complete operating rule.',+ styleNotes: 'Specific and tactile.',+ }),+ runId: 'run-complete',+ });++ await expandWorldTemplate({+ starterPrompt: 'Example Universe',+ foundationDirective: 'Define ordinary governance.',+ providerId: 'codex-tui',+ model: 'gpt-5.6-sol',+ effort: 'ultra',+ narrativeOnly: true,+ });++ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('# Starter idea');+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('logline is missing');+ expect(runPromptThroughProviderMock.mock.calls[1][0].prompt).toContain('Return a complete replacement');+ });});diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex 00f4ed2064..bf408023fd 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -40,7 +40,8 @@ import {} from "../lib/promptRunner.js";const LABEL_MAX = 80;-const NARRATIVE_REPAIR_MAX_ATTEMPTS = 2;+const NARRATIVE_REPAIR_MAX_ATTEMPTS = 3;+const NARRATIVE_REPAIR_HEADROOM = [0.9, 0.8];// Bible/prompt fields the LLM sees as "current universe state" so re-expansion// stays consistent with prior refinements. Derived from LOCKABLE_FIELDS so a@@ -272,6 +273,50 @@ const narrativeRepairViolations = (parsed) => [return value.length > max ? [`${key} exceeds ${max} characters (got ${value.length})`] : [];});+const hasCompleteNarrativeCandidate = (candidate) => (+ ['logline', 'premise', 'styleNotes'].every((key) => (+ typeof candidate?.[key] === 'string' && candidate[key].trim()+ ))+);++function buildNarrativeCompressionPrompt({ candidate, violations, compressionAttempt }) {+ const headroom = NARRATIVE_REPAIR_HEADROOM[Math.min(+ compressionAttempt - 1,+ NARRATIVE_REPAIR_HEADROOM.length - 1,+ )];+ const targets = {+ logline: Math.floor(LOGLINE_MAX * headroom),+ premise: Math.floor(PREMISE_MAX * headroom),+ styleNotes: Math.floor(STYLE_NOTES_MAX * headroom),+ };+ const source = Object.fromEntries(['logline', 'premise', 'styleNotes'].map((key) => [+ key,+ typeof candidate?.[key] === 'string' ? candidate[key].trim() : '',+ ]));+ return `You are a senior story-bible compression editor. Shorten the supplied candidate in place; do not rebuild the world from its original prompt.++# Why this rewrite is required+The candidate failed persistence validation: ${violations.join('; ')}.++# Hard output contract with safety headroom+Return one JSON object with exactly these string keys and no others:+- logline: at most ${targets.logline} characters.+- premise: at most ${targets.premise} characters.+- styleNotes: at most ${targets.styleNotes} characters.++The application rejects the entire response if any field exceeds its target. Aim comfortably below each target and silently count before answering.++# Compression priorities+- Preserve proper nouns, character identities and roles, causal rules, hard limits, costs, failure modes, jurisdictions, and distinct site-specific operations.+- Preserve the setting's conflict, stakes, tone, and every detail that makes a later plot choice possible or constrained.+- Remove repetition, ornamental restatement, redundant examples, and throat-clearing first. Combine parallel rules into precise sentences.+- Do not replace concrete mechanics with vague summary. Do not invent new lore. Do not cut off a sentence, paragraph, rule, or list item.+- Return only valid JSON. No markdown or commentary.++# Candidate to compress+${JSON.stringify(source, null, 2)}`;+}+const normalizeCategories = (raw) => {// The LLM occasionally returns variations as a flat array of strings or// skips the wrapping `{ variations: [...] }` object. Coerce both shapes@@ -438,22 +483,31 @@ export async function expandWorldTemplate({// 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.+ // model's raw scalar lengths before normalization. An over-limit retry+ // receives the rejected draft itself and a progressively smaller headroom+ // target; asking the original worldbuilding prompt to start over just+ // reproduces the same long answer without converging. A missing-field retry+ // still receives the source task because there is no complete draft to edit.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 prompt = narrativeViolations.length > 0+ ? hasCompleteNarrativeCandidate(parsed)+ ? buildNarrativeCompressionPrompt({+ candidate: parsed,+ violations: narrativeViolations,+ compressionAttempt: attempt,+ })+ : `${fullPrompt}\n\n# Storage-contract retry\nThe previous response was incomplete: ${narrativeViolations.join('; ')}. Return a complete replacement with every required field; do not omit or leave any field blank.`+ : fullPrompt;const result = await runPromptThroughProvider({provider,model: selectedModel,effort,- prompt: `${fullPrompt}${retrySection}`,+ prompt,source: narrativeOnly ? "universe-builder-narrative-repair" : "universe-builder-expansion",});raw = result.text;@@ -472,7 +526,10 @@ export async function expandWorldTemplate({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('; ')}`);+ const retryMode = hasCompleteNarrativeCandidate(parsed)+ ? 'compressing prior draft'+ : 'regenerating incomplete response';+ console.warn(`⚠️ Universe Builder narrative repair exceeded its storage contract — ${retryMode} (attempt ${attempt + 2}/${maxAttempts}): ${narrativeViolations.join('; ')}`);}}if (narrativeViolations.length > 0) {