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: patch arc prose without wholesale rewrites

[._.]/ Adam Eivy139ba25d0bed
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 70babce563..3fb82db8f6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +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.
- **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 bfe6b831bc..6aae17ce7d 100644
--- a/data.reference/prompts/stages/pipeline-arc-resolve.md
+++ b/data.reference/prompts/stages/pipeline-arc-resolve.md
@@ -125,9 +125,10 @@ Resolve the findings above with edits that cannot re-create any of these. Concre
6. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.
7. **Preserve volume `id`** for every existing volume you edit. Only assign no `id` to brand-new volumes you are adding. Never delete a volume — if a finding could only be resolved by removing one, write that in the `notes` field instead of doing it.
8. **Correct an episode synopsis when the contradiction *originates* in that episode.** Sometimes a finding can't be fixed at the volume level because the wrong content lives in a specific episode's `synopsis` — e.g. an episode stages an event that a later volume reserves as its own "first" occurrence, or a promised through-line silently disappears from the episodes that should carry it. In those cases the only convergent fix is to rewrite the offending episode's `synopsis` so it stops contradicting the rest of the arc. Return those rewrites in the `episodes[]` output array below, keyed by `seasonNumber` + `episodeNumber`. These are early planning synopses (no script has been drafted yet), so editing them is safe and is preferred over papering over the conflict at the volume level. Rules: edit an episode synopsis ONLY when a finding genuinely originates there; make the smallest change that removes the contradiction while preserving the episode's dramatic purpose; never delete an episode (omit it from `episodes[]` to leave it untouched). If a finding could only be resolved by removing issues entirely, write that in the `notes` field instead of doing it.
-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 rewrote it, an episode only if you rewrote it, and the `arc` block only if you rewrote 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. **Within an edited record, return only the fields that must change.** A season may need a new `synopsis` without needing a new `logline`, `endingHook`, title, count, or themes. 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.
-11. **Stay safely inside persisted string limits and end every field 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. Target at most 450 / 7,500 / 3,700 / 450 / 7,500 / 900 characters respectively so punctuation and later edits have headroom. Before returning, check every changed string: it must be below its target and 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.
+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.
## Output contract
@@ -135,12 +136,17 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
```json
{
+ "patchMode": "exact-text-v1",
"arc": {
"resolves": ["f1"],
"logline": "string",
- "summary": "string (~500 words, multi-paragraph; escape newlines as \\n)",
+ "summaryEdits": [
+ { "find": "exact unique existing sentence", "replace": "complete corrected sentence" }
+ ],
"themes": ["string", "..."],
- "protagonistArc": "string"
+ "protagonistArcEdits": [
+ { "find": "exact unique existing clause", "replace": "complete corrected clause" }
+ ]
},
"characterArcs": [
{
@@ -163,8 +169,12 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
"number": 1,
"title": "string",
"logline": "string",
- "synopsis": "string",
- "endingHook": "string",
+ "synopsisEdits": [
+ { "find": "exact unique existing sentence", "replace": "complete corrected sentence" }
+ ],
+ "endingHookEdits": [
+ { "find": "exact unique existing clause", "replace": "complete corrected clause" }
+ ],
"episodeCountTarget": 8,
"themes": ["string"]
}
@@ -181,10 +191,10 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c
}
```
-The `seasons[]` array is a SPARSE list of volume rewrites — include only the volumes you actually edited, each carrying its `resolves` ids. Volumes you don't list are left exactly as they are; nothing is deleted by omission. Omit the array entirely (or leave it empty) when no volume needed editing.
+The `seasons[]` array is a SPARSE list of volume patches — include only the volumes you actually edited, each carrying its `resolves` ids. For existing volumes, use exact `synopsisEdits` / `endingHookEdits`; only a genuinely brand-new volume may carry complete `synopsis` / `endingHook` fields. Volumes you don't list are left exactly as they are; nothing is deleted by omission. Omit the array entirely (or leave it empty) when no volume needed editing.
The `characterArcs[]` array is a SPARSE list of existing character-arc patches — include only the character and transition fields you actually corrected, preserve every supplied ID, and carry the finding's `resolves` ids on the character-arc entry. Character arcs and transitions you don't list are left exactly as they are. Unmatched/new IDs are discarded rather than minted.
The `episodes[]` array is a SPARSE list of episode-synopsis corrections — include only the episodes you actually rewrote (per rule 8). Omit the array entirely (or leave it empty) when every finding was resolved at the arc/volume level. Episodes you don't list are left exactly as they are.
-Omit the `arc` block entirely when the arc itself needed no rewrite. Within every record you do return, omit fields that do not need to change. Every field you include must be complete and within the limits above — the server keeps the stored value for any field you leave out, but it does not merge two halves of a sentence.
+Omit the `arc` block entirely when the arc itself needed no edit. Within every record you do return, omit fields that do not need to change. Every direct short field and every exact replacement must be complete and leave the resulting persisted field within the limits above. The server keeps the stored value for every field and substring you leave untouched.
diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.js
index 510e0bea1a..9c5c8bd440 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
};
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 9773cc4a6a..26a4ffe7f5 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
'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 d7fe4c52b1..b18b516664 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
};
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 bb26554fd9..caae35e190 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
};
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 e95e0f5c93..3b5634b4fe 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
};
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 ce20d58f90..20530c3c1c 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
};
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 d55d5da557..37d518d78d 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': '31eca76b68f40de1b93734fe9bc9f4bb', // post-254 (sparse character-arc repairs)
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d', // post-258 (exact long-text patches)
};
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 b46a4c98f2..e8cc992f27 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': '31eca76b68f40de1b93734fe9bc9f4bb',
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d',
};
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
new file mode 100644
index 0000000000..90aed35c44
--- /dev/null
+++ b/scripts/migrations/258-arc-resolve-exact-text-patches.js
@@ -0,0 +1,30 @@
+/**
+ * Keep arc verification repairs local inside long prose fields.
+ *
+ * A finding against one sentence in an 8,000-character volume synopsis used to
+ * require returning the whole synopsis. That gave each repair thousands of
+ * unrelated words of blast radius and could exceed the persistence limit. The
+ * new prompt emits bounded, exact-match replacements for long arc/volume text.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-arc-resolve.md': ['31eca76b68f40de1b93734fe9bc9f4bb'],
+};
+
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'arc-resolve exact text patches',
+ customizedHint: (filename) =>
+ ` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
+ ` against data/prompts/stages/${filename} and add the exact-text-v1 patch contract.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/258-arc-resolve-exact-text-patches.test.js b/scripts/migrations/258-arc-resolve-exact-text-patches.test.js
new file mode 100644
index 0000000000..44d8a3d11e
--- /dev/null
+++ b/scripts/migrations/258-arc-resolve-exact-text-patches.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 './258-arc-resolve-exact-text-patches.js';
+
+describe('migration 258 — arc-resolve exact text patches', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-258-arc-resolve-exact-text-patches-',
+ });
+
+ it('ships the exact long-text patch contract', () => {
+ const prompt = readFileSync(
+ `${repoRoot}/data.reference/prompts/stages/pipeline-arc-resolve.md`,
+ 'utf8',
+ );
+ expect(prompt).toContain('"patchMode": "exact-text-v1"');
+ expect(prompt).toContain('`summaryEdits[]`');
+ expect(prompt).toContain('`synopsisEdits[]`');
+ expect(prompt).toContain('exact unique excerpt copied verbatim');
+ expect(prompt).toMatch(/Never put a full stored summary/);
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 07b11454ff..07f6d1195e 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'],
+ 'pipeline-arc-resolve.md': ['0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb'],
'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': '31eca76b68f40de1b93734fe9bc9f4bb',
+ 'pipeline-arc-resolve.md': '17fbb066d7957dc2e345df1795bb0d9d',
'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 369b6b1b3e..9e9e71fa63 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -840,6 +840,87 @@ describe('arcPlanner — resolveVerifyIssues', () => {
});
});
+ it('applies exact long-text edits without accepting a wholesale synopsis rewrite', async () => {
+ const s = await setupSeries();
+ await seriesSvc.updateSeries(s.id, {
+ arc: {
+ logline: 'old logline',
+ summary: 'Opening stays. The route opens before consent. Finale stays.',
+ protagonistArc: 'They begin afraid. They end accountable.',
+ },
+ });
+ const existingSeason = await seasonsSvc.createSeason(s.id, {
+ title: 'Season 1',
+ synopsis: 'Issue one stays. Ledger D opens before the vote. Issue three stays.',
+ endingHook: 'The old charter remains active.',
+ episodeCountTarget: 3,
+ });
+
+ stageRunnerSpy = vi.fn(async () => ({
+ content: {
+ patchMode: 'exact-text-v1',
+ arc: {
+ resolves: ['f1'],
+ summary: 'WHOLESALE ARC REWRITE MUST BE IGNORED',
+ summaryEdits: [{
+ find: 'The route opens before consent.',
+ replace: 'The route opens only after affected delegates consent.',
+ }],
+ },
+ seasons: [{
+ resolves: ['f1'],
+ id: existingSeason.id,
+ synopsis: 'WHOLESALE VOLUME REWRITE MUST BE IGNORED',
+ synopsisEdits: [{
+ find: 'Ledger D opens before the vote.',
+ replace: 'Ledger D remains dark until the vote passes.',
+ }],
+ endingHookEdits: [{
+ find: 'The old charter remains active.',
+ replace: 'The old charter lapses when the crossing begins.',
+ }],
+ }],
+ notes: '',
+ },
+ runId: 'r1', providerId: 'p', model: 'm',
+ }));
+
+ const out = await planner.resolveVerifyIssues(s.id, {
+ findings: [{ severity: 'high', problem: 'The crossing precedes consent.', suggestion: 'Move consent first.' }],
+ });
+
+ expect(out.series.arc.summary).toBe(
+ 'Opening stays. The route opens only after affected delegates consent. Finale stays.',
+ );
+ expect(out.series.arc.protagonistArc).toBe('They begin afraid. They end accountable.');
+ expect(out.series.seasons[0].synopsis).toBe(
+ 'Issue one stays. Ledger D remains dark until the vote passes. Issue three stays.',
+ );
+ expect(out.series.seasons[0].endingHook).toBe(
+ 'The old charter lapses when the crossing begins.',
+ );
+ });
+
+ it('rejects ambiguous, whole-field, and over-limit exact text edits', () => {
+ expect(planner.applyExactTextEdits(
+ 'repeat here; repeat here',
+ [{ find: 'repeat here', replace: 'changed' }],
+ 100,
+ )).toEqual({ value: 'repeat here; repeat here', applied: 0, rejected: 1 });
+
+ expect(planner.applyExactTextEdits(
+ 'the complete field',
+ [{ find: 'the complete field', replace: 'wholesale replacement' }],
+ 8000,
+ )).toEqual({ value: 'the complete field', applied: 0, rejected: 1 });
+
+ expect(planner.applyExactTextEdits(
+ 'short anchor',
+ [{ find: 'anchor', replace: 'a replacement that exceeds the cap' }],
+ 20,
+ )).toEqual({ value: 'short anchor', applied: 0, rejected: 1 });
+ });
+
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 f26354bc6c..16ae8ef535 100644
--- a/server/services/pipeline/arcPlanner/arcCore.js
+++ b/server/services/pipeline/arcPlanner/arcCore.js
@@ -14,7 +14,7 @@ import { ARC_LOCKABLE_FIELDS, getSeries, updateSeries } from '../series.js';
import { listIssues, listIssuesForSeries, recomputeIssueNumbersForSeries, updateIssue, updateStageWithLatest, updateStagesWithLatest } from '../issues.js';
import { emitRecordUpdated, withReexportSuppressed } from '../../sharing/recordEvents.js';
import { getSeason } from '../seasons.js';
-import { READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';
+import { ARC_LIMITS, READER_MAP_BEAT_KINDS, buildSeason, cleanThemes, renderArcShapeGuidance, renderArcShapePositionSummary, sanitizeArc, sanitizeReaderMap, sanitizeSeason, sanitizeSeasonList } from '../../../lib/storyArc.js';
import { sanitizeCharacterArcList } from '../../../lib/seriesCharacterArc.js';
import { runPromptRefineRaw, trimChanges } from '../refineHelpers.js';
import { ERR_VALIDATION, SHAPE_GUIDANCE_NONE, appendTickingClock, buildArcBaseContext, buildArcOverviewContext, buildNeighborVolumes, buildReaderMapContext, buildResolveContext, buildVerifyContext, compareIssuesByPosition, findingIdSet, makeErr, matchIssueForEpisodeEdit, matchResolvedFindings, renderVolumeIssue, resolveWorldContext, seasonIdByNumberOf, shapeEpisodeResolutions, shapeFindings, shapeSeasonOutlines, shapeVerifyIssues } from './context.js';
@@ -462,6 +462,52 @@ export function mergeCharacterArcPatches(existingArcs, patches) {
return sanitizeCharacterArcList(merged);
}
+const EXACT_TEXT_PATCH_MODE = 'exact-text-v1';
+const EXACT_TEXT_EDITS_MAX = 12;
+
+/**
+ * Apply bounded exact-match replacements to one persisted long-form field.
+ *
+ * Arc verification findings are usually sentence-local, but `synopsis` and
+ * `summary` are monolithic strings. Asking the resolver to return either field
+ * wholesale gave a one-sentence repair thousands of unrelated words of blast
+ * radius, and an over-limit rewrite could then be truncated mid-sentence by the
+ * canonical sanitizer. Exact replacements keep the untouched text byte-for-byte
+ * stable. Ambiguous/missing anchors and over-limit results are skipped rather
+ * than guessed at; the next verification round will leave the original finding
+ * visible instead of persisting a speculative rewrite.
+ */
+export function applyExactTextEdits(current, rawEdits, maxLength) {
+ const original = typeof current === 'string' ? current : '';
+ if (!Array.isArray(rawEdits) || rawEdits.length === 0) {
+ return { value: original, applied: 0, rejected: 0 };
+ }
+ let value = original;
+ let applied = 0;
+ let rejected = 0;
+ for (const raw of rawEdits.slice(0, EXACT_TEXT_EDITS_MAX)) {
+ const find = typeof raw?.find === 'string' ? raw.find : '';
+ const replacement = typeof raw?.replace === 'string' ? raw.replace : null;
+ const first = find ? value.indexOf(find) : -1;
+ const duplicate = first >= 0 && value.indexOf(find, first + find.length) >= 0;
+ const replacesWholeLongField = find.length === value.length
+ && maxLength > ARC_LIMITS.SEASON_ENDING_HOOK_MAX;
+ if (!find || replacement == null || first < 0 || duplicate || replacesWholeLongField) {
+ rejected += 1;
+ continue;
+ }
+ const candidate = `${value.slice(0, first)}${replacement}${value.slice(first + find.length)}`;
+ if (candidate.length > maxLength) {
+ rejected += 1;
+ continue;
+ }
+ value = candidate;
+ applied += 1;
+ }
+ rejected += Math.max(0, rawEdits.length - EXACT_TEXT_EDITS_MAX);
+ return { value, applied, rejected };
+}
+
// Character arcs are patched in place by existing IDs; episode (issue) records
// are never CREATED or DELETED here, and their drafted scripts are never
// clobbered — a full-arc round may rewrite an episode's planning synopsis (see
@@ -539,6 +585,7 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
// volume it touches is a chance to author the contradiction the next verify
// files as a brand-new blocker.
const edits = selectFindingKeyedEdits(content, findings, { spineOnly });
+ const exactTextMode = content?.patchMode === EXACT_TEXT_PATCH_MODE;
// Only worth saying when there is actually something to apply unkeyed — a
// response that proposed NO edits reads as legacy too, and warning about a
// stale prompt there would be a lie.
@@ -555,11 +602,17 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
console.log(`⚠️ arc-resolve: discarded ${edits.episodesOutOfScope} episode edit(s) — the arc-spine gate resolves at arc/volume scope only`);
}
+ const arcSummary = exactTextMode
+ ? applyExactTextEdits(series.arc.summary || '', edits.arc?.summaryEdits, ARC_LIMITS.SUMMARY_MAX)
+ : { value: edits.arc?.summary || series.arc.summary || '', applied: 0, rejected: 0 };
+ 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 };
const arc = sanitizeArc({
logline: edits.arc?.logline || series.arc.logline || '',
- summary: edits.arc?.summary || series.arc.summary || '',
+ summary: arcSummary.value,
themes: edits.arc?.themes ?? series.arc.themes,
- protagonistArc: edits.arc?.protagonistArc ?? series.arc.protagonistArc ?? '',
+ protagonistArc: protagonistArc.value,
shape: edits.arc?.shape ?? series.arc.shape ?? null,
// The resolve prompt doesn't author the reader map — preserve any existing
// one so auto-resolve never silently wipes a reader map the user already
@@ -599,13 +652,22 @@ export async function resolveVerifyIssues(seriesId, options = {}) {
proposedSeasons.forEach((raw, idx) => {
const existing = matchedExisting[idx];
if (existing) {
+ const synopsis = exactTextMode
+ ? applyExactTextEdits(existing.synopsis || '', raw.synopsisEdits, ARC_LIMITS.SEASON_SYNOPSIS_MAX)
+ : { value: typeof raw.synopsis === 'string' ? raw.synopsis : existing.synopsis, applied: 0, rejected: 0 };
+ const endingHook = exactTextMode
+ ? applyExactTextEdits(existing.endingHook || '', raw.endingHookEdits, ARC_LIMITS.SEASON_ENDING_HOOK_MAX)
+ : { value: typeof raw.endingHook === 'string' ? raw.endingHook : existing.endingHook, applied: 0, rejected: 0 };
+ 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}`);
+ }
patchedById.set(existing.id, sanitizeSeason({
...existing,
title: typeof raw.title === 'string' ? raw.title : existing.title,
number: Number.isFinite(raw.number) ? raw.number : existing.number,
logline: typeof raw.logline === 'string' ? raw.logline : existing.logline,
- synopsis: typeof raw.synopsis === 'string' ? raw.synopsis : existing.synopsis,
- endingHook: typeof raw.endingHook === 'string' ? raw.endingHook : existing.endingHook,
+ synopsis: synopsis.value,
+ endingHook: endingHook.value,
episodeCountTarget: Number.isFinite(raw.episodeCountTarget)
? raw.episodeCountTarget
: existing.episodeCountTarget,