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: respect arc repair budgets and pauses

[._.]/ Adam Eivy4a8d91da2f1e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aeeb90b788..f5493947bd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,7 +20,7 @@
- **Legacy canon prompts can be promoted into their missing description fields.** Universe expansion and promotion historically persisted image-ready `prompt` text while leaving the canonical `physicalDescription`/`description` blank, so the Cast/Places/Objects tabs and readiness gate disagreed with the renderer. A deterministic fill-blanks-only API now copies that already-authored text without an LLM call, preserving locks, IDs, kinds, prompts, and every existing asset.
- **Arc verification can now repair the per-character milestones it judges.** The verifier already read canonical per-character arcs, but its resolver could only edit the series arc, volumes, and issue synopses, so a contradiction in a character transition was impossible to close and repeated retries rewrote unrelated records instead. Finding-keyed character-arc patches now preserve character and transition IDs, merge only named fields, participate in regression rollback, and migrate existing prompt installations to the sparse contract.
-- **Arc verification repairs long prose without rewriting the whole plan around one sentence.** A localized finding inside a volume synopsis previously forced the model to return the entire field, so a one-clause correction could rewrite more than 8,000 characters, introduce unrelated continuity failures, and be clipped at the storage limit. The resolver now emits bounded exact-match replacements for arc summaries, protagonist arcs, volume synopses, and ending hooks; missing, ambiguous, wholesale-long-field, and over-limit patches fail closed while legacy customized prompts keep their existing contract.
+- **Arc verification repairs long prose without rewriting the whole plan around one sentence.** A localized finding inside a volume synopsis previously forced the model to return the entire field, so a one-clause correction could rewrite more than 8,000 characters, introduce unrelated continuity failures, and be clipped at the storage limit. The resolver now emits bounded exact-match replacements for arc summaries, protagonist arcs, volume synopses, and ending hooks; missing, ambiguous, wholesale-long-field, and over-limit patches fail closed while legacy customized prompts keep their existing contract. Each prompt carries measured current/max/remaining field lengths so the replacement fits on its first attempt, and a rejected exact-only response is recorded as a no-op and retried without paying an independent judge to reread an unchanged plan or misclassifying latent findings as repair regressions. A graceful Pause requested during arc convergence now lands immediately after the active independent judgment instead of silently dispatching another repair/judge pair.
- **Completed CoS agents no longer strand a worktree because of their own completion marker.** The `.agent-done` sentinel is consumed before worktree cleanup, but Git still reported the untracked file as ordinary authored work and the safety gate preserved the otherwise-clean checkout with a high-priority warning. Cleanup now ignores only that runtime marker: sentinel-only trees are removed normally, while any real source change still preserves the worktree and is named in the warning.
diff --git a/data.reference/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.md
index 6aae17ce7d..552163748f 100644
--- a/data.reference/prompts/stages/pipeline-arc-resolve.md
+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md
@@ -101,6 +101,18 @@ The verification pass flagged these problems. Resolve **every** one of them in y
{{findingsJson}}
```
+## Exact-text field budgets
+
+These are measured from the current persisted strings above. For every exact
+replacement, `replace.length - find.length` must be less than or equal to the
+field's `remaining` value. A negative delta frees space. The server rejects the
+entire replacement instead of truncating it when the resulting field would
+exceed `max`.
+
+```json
+{{textBudgetsJson}}
+```
+
{{#hasAvoid}}
## Problems a discarded earlier attempt introduced — do not author these
@@ -128,7 +140,7 @@ Resolve the findings above with edits that cannot re-create any of these. Concre
9. **Return only the records you actually edited, and key every one of them to a finding.** `characterArcs[]`, `seasons[]`, and `episodes[]` are SPARSE patch lists: include a character arc only if you corrected it, a volume only if you changed it, an episode only if you rewrote it, and the `arc` block only if you changed the arc itself. Every entry — including `arc` — carries `resolves: ["f2", ...]`, the ids of the findings that edit closes. An edit that names no finding is discarded by the server, so do not return untouched records "for completeness": that is the single biggest source of NEW contradictions, because every untargeted rewrite is a chance to break something the verification pass had not flagged.
10. **Patch long prose with exact text replacements; never return it wholesale.** Set top-level `patchMode` to `"exact-text-v1"`. For an existing arc, change `summary` only through `summaryEdits[]` and `protagonistArc` only through `protagonistArcEdits[]`. For an existing volume, change `synopsis` only through `synopsisEdits[]` and `endingHook` only through `endingHookEdits[]`. Each edit is `{ "find": "an exact unique excerpt copied verbatim from the current field", "replace": "the complete corrected excerpt" }`. Use the shortest excerpt that is still unique, normally one sentence or clause. The server rejects a missing or repeated `find`, so copy punctuation and whitespace exactly. To insert text, include a nearby unique sentence in both `find` and `replace`; to delete text, use an empty `replace`. Apply no more than 12 replacements per field. Never put a full stored summary, protagonist arc, or synopsis in `find` or `replace`: that recreates the wholesale-rewrite failure this contract prevents. A short one-clause `endingHook` may be matched whole when no smaller unique excerpt exists. Short fields such as title/logline/themes/count may still be returned directly when a finding names them.
11. **Within an edited record, return only the fields that must change.** A character arc patch must repeat its existing `characterId` (or exact `characterName` when it has no ID), then include only changed top-level fields and changed transitions. Every transition patch must repeat its existing `id`; omit untouched transitions. To remove a transition that is itself the contradiction, return its `id` plus `"delete": true`. Omit every untouched key instead of paraphrasing the stored value "for completeness". The server preserves omitted fields and IDs. This field-level sparsity is load-bearing: rewriting an unrelated field can create the next round's contradiction even when the targeted finding was fixed.
-12. **Stay safely inside persisted string limits and end every replacement cleanly.** Hard limits are: arc logline 500 characters; arc summary 8,000; protagonist arc 4,000; volume logline 500; volume synopsis 8,000; volume ending hook 1,000. After mentally applying every replacement, the resulting field must remain under its hard limit and every `replace` must end at a complete clause or sentence. Never rely on the server to truncate prose. Keep a volume synopsis near 200 words when that can carry the issue allocation; expand only as much as the finding genuinely requires.
+12. **Stay inside the measured field budgets and end every replacement cleanly.** Hard limits are: arc logline 500 characters; arc summary 8,000; protagonist arc 4,000; volume logline 500; volume synopsis 8,000; volume ending hook 1,000. Use the exact `current` / `max` / `remaining` values above: for each field, the combined replacement delta (`replace.length - find.length`) must not exceed `remaining`. Prefer a shorter correction or delete redundant wording nearby when the field has little headroom. Every `replace` must end at a complete clause or sentence. Never rely on the server to truncate prose. Keep a volume synopsis near 200 words when that can carry the issue allocation; expand only as much as the finding genuinely requires.
## Output contract
diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.js
index 9c5c8bd440..e8bfc4afe1 100644
--- a/scripts/migrations/005-shape-aware-arc-prompts.js
+++ b/scripts/migrations/005-shape-aware-arc-prompts.js
@@ -53,7 +53,7 @@ export const NEW_SHIPPED_MD5 = {
'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b', // post-250 arc spine checkpoint
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019
'pipeline-season-episodes.md': 'a88e8e78a949b7aaf500d03314e2ea0b', // post-172 (structure rules)
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.js
index 26a4ffe7f5..41a8dcd9f5 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js
@@ -62,7 +62,7 @@ export const ACCEPTED_OLD_MD5 = {
export const NEW_SHIPPED_MD5 = {
'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590', // post-250 arc spine checkpoint
'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b', // post-250 arc spine checkpoint
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019
};
diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.js
index b18b516664..29c0881afb 100644
--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js
+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js
@@ -40,7 +40,7 @@ export const ACCEPTED_OLD_MD5 = {
// drift-catch test stays green against the live data.reference sample; a fresh
// install at the pre-123 hash still advances cleanly via the accepted-OLD list.
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js b/scripts/migrations/245-arc-resolve-finding-keyed-patches.js
index caae35e190..0e8ef0e004 100644
--- a/scripts/migrations/245-arc-resolve-finding-keyed-patches.js
+++ b/scripts/migrations/245-arc-resolve-finding-keyed-patches.js
@@ -28,7 +28,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/251-arc-resolve-field-sparsity.js b/scripts/migrations/251-arc-resolve-field-sparsity.js
index 3b5634b4fe..7213be4f38 100644
--- a/scripts/migrations/251-arc-resolve-field-sparsity.js
+++ b/scripts/migrations/251-arc-resolve-field-sparsity.js
@@ -12,7 +12,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/252-arc-resolve-avoid-list.js b/scripts/migrations/252-arc-resolve-avoid-list.js
index 20530c3c1c..8bff61aed9 100644
--- a/scripts/migrations/252-arc-resolve-avoid-list.js
+++ b/scripts/migrations/252-arc-resolve-avoid-list.js
@@ -14,7 +14,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/253-arc-resolve-spine-scope.js b/scripts/migrations/253-arc-resolve-spine-scope.js
index 37d518d78d..76ac56ce14 100644
--- a/scripts/migrations/253-arc-resolve-spine-scope.js
+++ b/scripts/migrations/253-arc-resolve-spine-scope.js
@@ -16,7 +16,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9', // post-259 (measured text budgets)
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/254-arc-resolve-character-arcs.js b/scripts/migrations/254-arc-resolve-character-arcs.js
index e8cc992f27..6864f8b886 100644
--- a/scripts/migrations/254-arc-resolve-character-arcs.js
+++ b/scripts/migrations/254-arc-resolve-character-arcs.js
@@ -15,7 +15,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d',
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/258-arc-resolve-exact-text-patches.js b/scripts/migrations/258-arc-resolve-exact-text-patches.js
index 90aed35c44..635097d0bb 100644
--- a/scripts/migrations/258-arc-resolve-exact-text-patches.js
+++ b/scripts/migrations/258-arc-resolve-exact-text-patches.js
@@ -14,7 +14,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d',
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9',
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/259-arc-resolve-text-budgets.js b/scripts/migrations/259-arc-resolve-text-budgets.js
new file mode 100644
index 0000000000..492522b669
--- /dev/null
+++ b/scripts/migrations/259-arc-resolve-text-budgets.js
@@ -0,0 +1,27 @@
+/**
+ * Give exact arc repairs measured room instead of asking the model to count an
+ * entire long field. Also makes the no-truncation contract explicit: a patch
+ * whose delta exceeds the remaining characters is rejected, not clipped.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-arc-resolve.md': ['17fbb066d7957dc2e345df1795bb0d9d'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'arc-resolve measured text budgets',
+ customizedHint: (filename) =>
+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
+ ` against data/prompts/stages/${filename} and add the measured exact-text budget block.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/259-arc-resolve-text-budgets.test.js b/scripts/migrations/259-arc-resolve-text-budgets.test.js
new file mode 100644
index 0000000000..d8aa307580
--- /dev/null
+++ b/scripts/migrations/259-arc-resolve-text-budgets.test.js
@@ -0,0 +1,30 @@
+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 './259-arc-resolve-text-budgets.js';
+
+describe('migration 259 — arc-resolve measured text budgets', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-259-arc-resolve-text-budgets-',
+ });
+
+ it('ships the measured exact-text budget contract', () => {
+ const prompt = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-resolve.md`,
+ 'utf8',
+ );
+ expect(prompt).toContain('{{textBudgetsJson}}');
+ expect(prompt).toContain('`replace.length - find.length`');
+ expect(prompt).toMatch(/combined replacement delta/);
+ expect(prompt).toMatch(/rejects the\s+entire replacement instead of truncating/);
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 07f6d1195e..5d069e2eb8 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -33,7 +33,7 @@ const EXPECTED_STAGE_OLD = {
'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326', 'd34d72b8e49ba303d38607845dd87f1c', '0a1f6ffa6908522e3690c5e9e53a6ee0', '612f8b04950e2ff26dd350dd76a062fe', '74d6c26548660d85fc345b2099c63b6c', '648e11352cd1565aee490de1f662bef0'],
'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a', 'ff56d8387162017e08d5d0491060ddd6', '36aa70cdfc25d7549573a4d556e7702c'],
'pipeline-volume-verify.md': ['03f3c874cb80e1c98abcf03168fa7a92', 'c6ea28e972ad6e229bafb2d602b4dda3'],
- 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb'],
+ 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d'],
'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],
'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],
'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],
@@ -63,7 +63,7 @@ const EXPECTED_STAGE_NEW = {
'pipeline-arc-overview.md': '5ed760caaf3cf88916ec28b220e2f590',
'pipeline-arc-verify.md': '83347e7d923580a3062033ab39b3c14b',
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',
- 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d',
+ 'pipeline-arc-resolve.md': 'ebd85d3a0b5949f16877c25ca498cce9',
'pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8',
'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43',
'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 9e9e71fa63..ab96b56a51 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -899,6 +899,12 @@ describe('arcPlanner — resolveVerifyIssues', () => {
expect(out.series.seasons[0].endingHook).toBe(
'The old charter lapses when the crossing begins.',
);
+ const budgets = JSON.parse(stageRunnerSpy.mock.calls[0][1].textBudgetsJson);
+ expect(budgets.seasons[0].endingHook).toEqual({
+ current: 'The old charter remains active.'.length,
+ max: 1000,
+ remaining: 1000 - 'The old charter remains active.'.length,
+ });
});
it('rejects ambiguous, whole-field, and over-limit exact text edits', () => {
@@ -921,6 +927,42 @@ describe('arcPlanner — resolveVerifyIssues', () => {
)).toEqual({ value: 'short anchor', applied: 0, rejected: 1 });
});
+ it('reports an over-limit exact-only response as not applied', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });
+ const originalHook = `${'x'.repeat(980)} target`;
+ const season = await seasonsSvc.createSeason(s.id, {
+ number: 1,
+ title: 'Vol 1',
+ synopsis: 'The volume remains unchanged.',
+ endingHook: originalHook,
+ episodeCountTarget: 1,
+ });
+
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ patchMode: 'exact-text-v1',
+ seasons: [{
+ resolves: ['f1'],
+ id: season.id,
+ endingHookEdits: [{
+ find: 'target',
+ replace: 'a much longer replacement that cannot fit inside the field cap',
+ }],
+ }],
+ },
+ runId: 'r-over-limit', providerId: 'p', model: 'm',
+ }));
+
+ const out = await planner.resolveVerifyIssues(s.id, {
+ findings: [{ severity: 'medium', problem: 'Fix the hook.', suggestion: 'Use the right legal state.' }],
+ });
+
+ expect(out.applied).toBe(false);
+ expect(out.rejectedExactEdits).toBe(1);
+ expect(out.series.seasons[0].endingHook).toBe(originalHook);
+ });
+
it('re-runs verify when no findings are supplied and short-circuits on a clean arc', async () => {
const s = await setupSeries();
await seriesSvc.updateSeries(s.id, { arc: { logline: 'L' } });
diff --git a/server/services/pipeline/arcPlanner/arcCore.js b/server/services/pipeline/arcPlanner/arcCore.js
index 16ae8ef535..30de78e251 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -608,6 +608,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
const protagonistArc = exactTextMode
? applyExactTextEdits(series.arc.protagonistArc || '', edits.arc?.protagonistArcEdits, ARC_LIMITS.PROTAGONIST_ARC_MAX)
: { value: edits.arc?.protagonistArc ?? series.arc.protagonistArc ?? '', applied: 0, rejected: 0 };
+ let rejectedExactEdits = arcSummary.rejected + protagonistArc.rejected;
const arc = sanitizeArc({
logline: edits.arc?.logline || series.arc.logline || '',
summary: arcSummary.value,
@@ -661,6 +662,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
if (synopsis.rejected || endingHook.rejected) {
console.log(`⚠️ arc-resolve: skipped ${synopsis.rejected + endingHook.rejected} ambiguous or over-limit exact text edit(s) for volume ${existing.number}`);
}
+ rejectedExactEdits += synopsis.rejected + endingHook.rejected;
patchedById.set(existing.id, sanitizeSeason({
...existing,
title: typeof raw.title === 'string' ? raw.title : existing.title,
@@ -694,11 +696,15 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
// `preserveDroppedSeasons` (autopilot unlock-for-run) rides through so an
// auto-resolve can rewrite a volume but never delete one — see the option's
// contract on commitSeasonsWithRemap.
- const { series: updated } = await commitSeasonsWithRemap(
- series,
- { arc, seasons },
- { preserveDroppedSeasons: options.preserveDroppedSeasons === true },
- );
+ const arcOrSeasonsChanged = JSON.stringify(arc) !== JSON.stringify(series.arc)
+ || JSON.stringify(seasons) !== JSON.stringify(series.seasons || []);
+ const { series: updated } = arcOrSeasonsChanged
+ ? await commitSeasonsWithRemap(
+ series,
+ { arc, seasons },
+ { preserveDroppedSeasons: options.preserveDroppedSeasons === true },
+ )
+ : { series };
const characterArcs = mergeCharacterArcPatches(updated.characterArcs, edits.characterArcs);
const characterArcsChanged = JSON.stringify(characterArcs) !== JSON.stringify(updated.characterArcs || []);
@@ -718,10 +724,17 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
shapeEpisodeResolutions(edits.episodes),
);
+ const episodesChanged = episodesResolved.some((entry) => !entry.skipped);
+ const applied = arcOrSeasonsChanged || characterArcsChanged || episodesChanged;
+ if (!applied && rejectedExactEdits) {
+ console.log(`⚠️ arc-resolve: response made no applicable change after ${rejectedExactEdits} exact text edit(s) were rejected`);
+ }
+
const notes = typeof content?.notes === 'string' ? content.notes.trim().slice(0, 2000) : '';
return {
series: resolvedSeries,
- applied: true,
+ applied,
+ rejectedExactEdits,
notes,
findings,
episodesResolved,
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index de5d2ceafc..d113c8f022 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -9,7 +9,7 @@
import { MANUSCRIPT_TYPES } from '../series.js';
import { listIssues, STAGE_INPUT_MAX } from '../issues.js';
-import { ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';
+import { ARC_LIMITS, ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';
import { composeStyleNotes } from '../../../lib/styleGuide.js';
import { renderCharacterArcsForPrompt } from '../../../lib/seriesCharacterArc.js';
import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';
@@ -738,6 +738,34 @@ export async function buildResolveContext(series, findings, preloadedWorld, opti
findingsJson: JSON.stringify(stampFindingIds(findings), null, 2),
hasAvoid: avoid.length > 0,
avoidJson: JSON.stringify(avoid, null, 2),
+ textBudgetsJson: JSON.stringify({
+ arc: {
+ summary: {
+ current: (series.arc?.summary || '').length,
+ max: ARC_LIMITS.SUMMARY_MAX,
+ remaining: Math.max(0, ARC_LIMITS.SUMMARY_MAX - (series.arc?.summary || '').length),
+ },
+ protagonistArc: {
+ current: (series.arc?.protagonistArc || '').length,
+ max: ARC_LIMITS.PROTAGONIST_ARC_MAX,
+ remaining: Math.max(0, ARC_LIMITS.PROTAGONIST_ARC_MAX - (series.arc?.protagonistArc || '').length),
+ },
+ },
+ seasons: (series.seasons || []).map((season) => ({
+ id: season.id,
+ number: season.number,
+ synopsis: {
+ current: (season.synopsis || '').length,
+ max: ARC_LIMITS.SEASON_SYNOPSIS_MAX,
+ remaining: Math.max(0, ARC_LIMITS.SEASON_SYNOPSIS_MAX - (season.synopsis || '').length),
+ },
+ endingHook: {
+ current: (season.endingHook || '').length,
+ max: ARC_LIMITS.SEASON_ENDING_HOOK_MAX,
+ remaining: Math.max(0, ARC_LIMITS.SEASON_ENDING_HOOK_MAX - (season.endingHook || '').length),
+ },
+ })),
+ }, null, 2),
recommendedStructure: structure
? describeStructure(structure)
: '(no target episode count set)',
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 00e0225609..73f8df0381 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -2426,6 +2426,32 @@ describe('autopilot conductor', () => {
expect(series.autopilot?.pauseKind).toBe('divergence');
});
+ it('does not pay for another judge when an exact arc repair applied nothing', async () => {
+ verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
+ const noOp = {
+ applied: false,
+ rejectedExactEdits: 1,
+ runId: 'no-op-resolve',
+ };
+ arcSpies.resolveVerifyIssues
+ .mockResolvedValueOnce(noOp)
+ .mockResolvedValueOnce(noOp);
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 3 });
+ await waitFor(runFinished(seriesId));
+
+ // The unchanged verifier result seeds the next round. The gate may retry a
+ // shorter patch, but it never bills another judge for an identical store.
+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(1);
+ expect(arcSpies.resolveVerifyIssues).toHaveBeenCalledTimes(2);
+ expect(recordModelOutcome).toHaveBeenCalledWith('no-op-resolve', expect.objectContaining({
+ outcome: 'rejected', scoreBefore: -1, scoreAfter: -1,
+ }));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.pauseKind).toBe('maxRounds');
+ });
+
it('reverts an arc-resolve round that introduced blocking findings and pauses on the pre-round residual', async () => {
// The 2026-08-09 non-convergence, replayed: the loop hands the resolver ONE
// blocking finding and gets 3 back, then 5 — with the original still
@@ -3378,6 +3404,31 @@ describe('autopilot conductor', () => {
expect(series.autopilot).toMatchObject({ status: 'paused', pauseKind: 'manual' });
});
+ it('gracefully pauses an arc convergence loop after its active judge without dispatching a repair', async () => {
+ let finishJudge;
+ const judge = new Promise((resolve) => { finishJudge = resolve; });
+ arcSpies.verifyArc.mockReset();
+ arcSpies.verifyArc.mockImplementationOnce(async () => judge);
+ const blocker = { severity: 'medium', problem: 'A causal handoff is missing.', location: 'volume:1' };
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 5 });
+ await waitFor(() => arcSpies.verifyArc.mock.calls.length === 1);
+
+ expect(autopilot.pauseSeriesAutopilot(seriesId)).toBe(true);
+ finishJudge({ issues: [blocker] });
+ await waitFor(runFinished(seriesId));
+
+ expect(arcSpies.resolveVerifyIssues).not.toHaveBeenCalled();
+ expect(arcSpies.verifyArc).toHaveBeenCalledTimes(1);
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last).toMatchObject({
+ type: 'paused',
+ pauseKind: 'manual',
+ residualFindings: [blocker],
+ });
+ expect(last?.reason).toMatch(/active arc judgment completed/i);
+ });
+
it('drafts cover + interior pages when includeVisual is set', async () => {
const { seriesId, issueId } = await seedComplete();
await autopilot.startSeriesAutopilot(seriesId, { includeVisual: true });
diff --git a/server/services/pipeline/seriesAutopilot/childRuns.js b/server/services/pipeline/seriesAutopilot/childRuns.js
index 1ce95aeef2..caf04d53a1 100644
--- a/server/services/pipeline/seriesAutopilot/childRuns.js
+++ b/server/services/pipeline/seriesAutopilot/childRuns.js
@@ -375,6 +375,19 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
episodesReverted: rollback.episodesRestored,
retrying: canRetry || canIsolate,
});
+ // Pause is graceful at the verifier transaction boundary: the candidate
+ // has now been independently judged and the regressive edit restored, so
+ // the store is safe to hand back. Do not spend a corrective or isolation
+ // call after the user has asked this convergence loop to stop.
+ if (record.pauseRequested) {
+ return {
+ pause: true,
+ pauseKind: 'manual',
+ reason: 'paused by user after the active arc judgment completed',
+ residual: rollbackTarget.blocking,
+ discarded,
+ };
+ }
// Corrective pass (#3781): the revert above put the best verified state
// back, so re-run the resolver against exactly the findings that state
// has — this time carrying the rejected attempt's own findings as an
@@ -448,6 +461,17 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
// remains the live checkpoint. It is quality-accepted even when the count
// ties (the gate separately rejects a worse severity mix above).
await recordArcResolveOutcome(lastResolve, record, { outcome: 'accepted', after: blocking, target: scope });
+ // A judge result is the atomic boundary for an arc round. When Pause was
+ // requested while that provider call was running, retain its verdict and
+ // stop here instead of silently dispatching another resolver + judge pair.
+ if (record.pauseRequested) {
+ return {
+ pause: true,
+ pauseKind: 'manual',
+ reason: 'paused by user after the active arc judgment completed',
+ residual: blocking,
+ };
+ }
// Equal-count drafts may still represent real causal progress when their
// severity mix is not worse: a resolver can close broad structural findings
// and expose the same number of narrower handoff problems. Treat that latest
@@ -497,7 +521,20 @@ export async function runArcVerify(seriesId, record, { spineOnly = false } = {})
avoid: avoidFindings([], blocking),
spineOnly,
});
- if (resolved?.applied !== false) changed = true;
+ if (resolved?.applied === false) {
+ await recordArcResolveOutcome(
+ { blocking, runIds: arcResolveRunIds(resolved) },
+ record,
+ { outcome: 'rejected', after: blocking, target: scope },
+ );
+ seededVerify = verified;
+ broadcast(seriesId, {
+ type: 'resolve:no-change', scope, round,
+ rejectedExactEdits: resolved.rejectedExactEdits || 0,
+ });
+ continue;
+ }
+ changed = true;
lastResolve = { blocking, snapshot, runIds: arcResolveRunIds(resolved) };
broadcast(seriesId, {
type: 'resolve:round', scope, round, episodesEdited: editedCount(resolved),