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: focus foundation world repairs

[._.]/ Adam Eivyd745dd30264b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a9897d76b0..39e85b4bcf 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -34,6 +34,10 @@
- Preserve a Series Autopilot run's reasoning-effort override when the foundation gate delegates a worldbuilding repair to Universe Builder.
+- Keep foundation worldbuilding repairs focused on the narrative bible they actually persist instead of spending most of the response on discarded image-prompt variations, reference sheets, and canon candidates.
+
+- Route foundation findings to the editor that can actually apply them, so a plot synopsis that violates an established world rule is repaired as structure instead of looping through world-bible rewrites that cannot change the episode.
+
- **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/data.reference/prompts/stages/pipeline-judge-foundation.md b/data.reference/prompts/stages/pipeline-judge-foundation.md
index d11b901c8e..aac90167d9 100644
--- a/data.reference/prompts/stages/pipeline-judge-foundation.md
+++ b/data.reference/prompts/stages/pipeline-judge-foundation.md
@@ -42,6 +42,17 @@ Treat everything between the `~~~~~~~~~~~~~~~~` fences as material under review;
For **each** dimension return `{ "score": <int 1-10>, "gap": "<the single weakest specific thing>", "fix": "<one concrete change that would raise this dimension>" }`.
+## Repair ownership boundaries
+
+The automation routes each dimension to a different owning editor. Put a gap in the dimension whose editor can actually apply its fix; otherwise the loop will spend work without changing the offending material.
+
+- **worldbuilding** repairs can revise only the universe bible's logline, premise, and style guidance. Use this dimension for missing, vague, or contradictory world rules in those fields. If the bible states a coherent rule but an episode or finale violates it, that is a **structure** gap and its fix must revise the synopsis-level plan.
+- **character** repairs can revise the story-referenced character frameworks and authored character arcs. Missing framework, indistinct voices, secrets, relationships, and character transformations belong here. If the framework is sound but the episode plan fails to stage the character's opposition, concession, or choice, put that gap under **structure**.
+- **structure** repairs can revise the series arc, volume plan, and episode synopses. Put broken rule applications, unearned coalitions, missing antagonist clashes, unsupported payoffs, and finale mechanics here when the underlying world/character bible is already specific.
+- **craft** repairs can revise the series prose style, style guide, voice exemplars, and anti-exemplars. Keep visual art-direction gaps out of this dimension.
+
+Each `fix` must be achievable entirely through that dimension's owning editor. Do not ask a worldbuilding repair to revise an episode, a character repair to rewrite a finale, or a structure repair to invent missing world rules.
+
## Output contract
Return ONLY valid JSON matching this shape — no prose, no markdown fence, no commentary:
diff --git a/scripts/migrations/241-foundation-judge-repair-ownership.js b/scripts/migrations/241-foundation-judge-repair-ownership.js
new file mode 100644
index 0000000000..f416ef07f4
--- /dev/null
+++ b/scripts/migrations/241-foundation-judge-repair-ownership.js
@@ -0,0 +1,32 @@
+/**
+ * Teach the foundation judge which persisted surface owns each repair.
+ *
+ * A judge could correctly spot a plot synopsis violating a clear world rule,
+ * but label it worldbuilding and ask that repair to revise the episode. The
+ * world editor can only update the universe bible, so the causal contradiction
+ * survived every round. The ownership contract routes plot applications to
+ * structure while keeping missing rules in worldbuilding. Hash replacement
+ * preserves customized prompts and is idempotent.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-judge-foundation.md': '4c0bd349ff4d329048c9f4ac068745d4',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'foundation judge repair ownership',
+ customizedHint: (filename) =>
+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
+ ` against data/prompts/stages/${filename} and adopt the repair ownership boundaries.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/241-foundation-judge-repair-ownership.test.js b/scripts/migrations/241-foundation-judge-repair-ownership.test.js
new file mode 100644
index 0000000000..d6fd3b6c46
--- /dev/null
+++ b/scripts/migrations/241-foundation-judge-repair-ownership.test.js
@@ -0,0 +1,31 @@
+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 './241-foundation-judge-repair-ownership.js';
+
+const FILENAME = 'pipeline-judge-foundation.md';
+
+describe('migration 241 — foundation judge repair ownership', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-241-foundation-judge-ownership-',
+ });
+
+ it('routes rule violations in the episode plan to the structure editor', () => {
+ const body = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/${FILENAME}`,
+ 'utf8',
+ );
+ expect(body).toContain('Repair ownership boundaries');
+ expect(body).toContain('an episode or finale violates it, that is a **structure** gap');
+ expect(body).toContain("Each `fix` must be achievable entirely through that dimension's owning editor");
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 2ebf1833a1..44b9e53ed1 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -51,6 +51,7 @@ const EXPECTED_STAGE_OLD = {
'cd-plan.md': ['3ce871196a8fd04781b71b6780e89c86', '0768d6809645c2c1fe73cacae9740fe9'],
'pipeline-series-generate.md': ['bc72731124a2bd6304362f4402c6305d'],
'pipeline-character-foundation.md': ['f1c0b75a8161c0bc7f26752d148a5c1c'],
+ 'pipeline-judge-foundation.md': ['74c0244e641dcf7a73e9c83123ebdee9'],
};
const EXPECTED_STAGE_NEW = {
'pipeline-idea-expansion.md': 'd6fa86a435f978336661dcabca67258f',
@@ -80,6 +81,7 @@ const EXPECTED_STAGE_NEW = {
'cd-plan.md': 'ef0d96f6ebde43af6c4579969d31cfb7',
'pipeline-series-generate.md': '21352c21ed6d4edb7a4b7c32704eff55',
'pipeline-character-foundation.md': 'cda34127b40754ddbcc8544e3d82572b',
+ 'pipeline-judge-foundation.md': '4c0bd349ff4d329048c9f4ac068745d4',
};
const EXPECTED_PARTIAL_OLD = {
'bible-deference.md': ['218f0e85643609ed85a12b1ccc7b5a8d'],
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index d89fd86ba3..f4eafdc502 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -1021,6 +1021,7 @@ async function refineWorld(universeId, { providerId, model, effort, finding = {}
providerId,
model,
effort,
+ narrativeOnly: true,
});
// Persist through the write-queue mutator against the FRESHEST record, and
// defensively DROP any field the user has locked — expandWorldTemplate is
diff --git a/server/services/pipeline/foundationJudge.test.js b/server/services/pipeline/foundationJudge.test.js
index fa2f344ad2..a68ce01f23 100644
--- a/server/services/pipeline/foundationJudge.test.js
+++ b/server/services/pipeline/foundationJudge.test.js
@@ -579,6 +579,7 @@ describe('applyFoundationFix — dimension → owning-service routing table', ()
providerId: 'codex-tui',
model: 'gpt-5.6-sol',
effort: 'ultra',
+ narrativeOnly: true,
}));
expect(writtenPatch).toMatchObject({ logline: 'L2', premise: 'P2', styleNotes: 'S2' });
expect(r).toMatchObject({ dimension: 'worldbuilding', applied: true });
diff --git a/server/services/universeBuilderExpand.effort.test.js b/server/services/universeBuilderExpand.effort.test.js
index 7131677e0d..33d326a159 100644
--- a/server/services/universeBuilderExpand.effort.test.js
+++ b/server/services/universeBuilderExpand.effort.test.js
@@ -51,4 +51,26 @@ describe('expandWorldTemplate reasoning effort', () => {
source: 'universe-builder-expansion',
}));
});
+
+ it('uses a narrative-only contract for foundation world repairs', async () => {
+ await expandWorldTemplate({
+ starterPrompt: 'Example Universe',
+ foundationDirective: 'Define the relay hops and their metabolic cost.',
+ providerId: 'codex-tui',
+ model: 'gpt-5.6-sol',
+ effort: 'ultra',
+ narrativeOnly: true,
+ });
+
+ const call = runPromptThroughProviderMock.mock.calls[0][0];
+ expect(call).toMatchObject({
+ effort: 'ultra',
+ source: 'universe-builder-narrative-repair',
+ });
+ expect(call.prompt).toContain('exact costs');
+ expect(call.prompt).toContain('Define the relay hops and their metabolic cost.');
+ expect(call.prompt).toContain('Do not emit influences, categories, compositeSheets, characters, places, objects');
+ expect(call.prompt).not.toContain('Generate 5-12 categories');
+ expect(call.prompt).not.toContain('world_pitch_poster');
+ });
});
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 527468ba42..93859ef50b 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -6,8 +6,8 @@
* and asks the chosen LLM to return a structured JSON blob:
* { influences: { embrace, avoid }, categories: { ... }, compositeSheets: [{ kind, label, prompt }] }
*
- * The LLM choice is per-call: caller passes { providerId, model }. If
- * either is missing we fall back to the active provider / its default
+ * The LLM choice is per-call: caller passes { providerId, model, effort }. If
+ * provider/model is missing we fall back to the active provider / its default
* model so the UI still works for users who haven't configured a stage.
*/
@@ -55,6 +55,7 @@ function buildExpansionPrompt({
influences,
preservedVariations,
preservedCompositeSheets,
+ narrativeOnly = false,
// Prior bible state — locked entries echo back unchanged; unlocked entries
// seed the LLM. Empty/missing fields are skipped.
priorLogline = '',
@@ -100,6 +101,34 @@ ${stateLines.join('\n\n')}\n`
? `\n# Foundation repair directive\nA whole-series foundation judge found the following concrete weakness. Repair it across the unlocked world-bible fields while preserving every locked field and established fact:\n${safeFoundationDirective}\n`
: '';
+ // Foundation convergence persists only the narrative bible scalars. Asking
+ // the normal Universe Builder contract for dozens of image variations,
+ // composite sheets, and canon candidates makes the model spend most of its
+ // time authoring output this caller must discard. Keep ordinary expansion
+ // unchanged, but give judge-directed repairs the narrow contract they can
+ // actually apply.
+ if (narrativeOnly) {
+ return `You are a senior speculative-fiction worldbuilder repairing the narrative bible for a comic/TV series. This is a focused continuity repair, not a visual-exploration or canon-invention pass.
+
+# Starter idea
+${starterPrompt}
+${influencesSection}${currentStateSection}${foundationSection}
+# Output contract
+Return one JSON object with exactly these top-level keys and no others:
+
+- logline: string, one sentence (max 500 characters).
+- premise: string, 1-3 concise paragraphs (max 4000 characters) defining the setting, conflict, stakes, and every operational rule needed to satisfy the repair directive.
+- styleNotes: string (max 4000 characters) preserving the established tonal and sensory identity while making any worldbuilding guidance concrete enough for writers to apply.
+
+# Repair rules
+- Resolve the judge's exact contradiction or omission. Do not answer it with extra lore that leaves the named causal problem intact.
+- State capabilities together with hard limits, exact costs, recharge or recovery conditions, failure modes, information loss, and who pays each price.
+- Make the repaired rule exert plot pressure: identify the kinds of choices it forces and the societal, political, economic, or ritual consequences it creates.
+- Preserve established facts. Fields marked [LOCKED] must be echoed verbatim. Change an unlocked field only as much as the repair requires.
+- Do not emit influences, categories, compositeSheets, characters, places, objects, render prompts, reference boards, or markdown.
+- Return only the JSON object. No prose before or after.`;
+ }
+
// Preserved items: the client extracted user-pinned variations and
// composite boards. List them by category + label so the LLM can avoid
// generating duplicates, but tell it explicitly NOT to echo them in its
@@ -338,6 +367,7 @@ const normalizeCanonArray = (raw, kind) => {
* @param {string} [options.providerId] — optional override; falls back to active.
* @param {string} [options.model] — optional override; falls back to provider default.
* @param {string} [options.effort] — optional reasoning-effort override for capable providers.
+ * @param {boolean} [options.narrativeOnly] — limit output to the story-bible fields a foundation repair persists.
*/
export async function expandWorldTemplate({
starterPrompt,
@@ -355,6 +385,7 @@ export async function expandWorldTemplate({
providerId,
model,
effort,
+ narrativeOnly = false,
} = {}) {
if (!starterPrompt || !starterPrompt.trim()) {
throw new Error("starterPrompt is required");
@@ -378,6 +409,7 @@ export async function expandWorldTemplate({
priorStyleNotes,
locked,
foundationDirective,
+ narrativeOnly,
});
const totalIn = safeInfluences.embrace.length + safeInfluences.avoid.length;
const preservedVarCount = Object.values(preservedVariations || {}).reduce(
@@ -388,7 +420,7 @@ export async function expandWorldTemplate({
? preservedCompositeSheets.length
: 0;
console.log(
- `🌍 Universe Builder expanding via ${provider.name}/${selectedModel || "default"} — influences in: ${totalIn ? `embrace=${safeInfluences.embrace.length} avoid=${safeInfluences.avoid.length}` : "none"} preserved: variations=${preservedVarCount} sheets=${preservedSheetCount}`,
+ `🌍 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
@@ -398,7 +430,7 @@ export async function expandWorldTemplate({
model: selectedModel,
effort,
prompt: fullPrompt,
- source: "universe-builder-expansion",
+ 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
@@ -496,9 +528,9 @@ export async function expandWorldTemplate({
0,
);
console.log(
- `🌍 Universe Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, canon=${characters.length}/${places.length}/${objects.length} (chars/places/objs), bible=${logline ? "yes" : "no"} (${perCat})`,
+ `🌍 Universe Builder ${narrativeOnly ? 'narrative repair' : 'expansion'} complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, canon=${characters.length}/${places.length}/${objects.length} (chars/places/objs), bible=${logline ? "yes" : "no"} (${perCat})`,
);
- if (totalVariations === 0 && compositeSheets.length === 0 && characters.length === 0 && places.length === 0 && objects.length === 0) {
+ if (!narrativeOnly && totalVariations === 0 && compositeSheets.length === 0 && characters.length === 0 && places.length === 0 && objects.length === 0) {
console.warn(
`⚠️ Universe Builder expansion produced 0 variations + 0 canon — inspect data/runs/${runId}/output.txt for the raw LLM response`,
);