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
feat([resolve-issues-inherits-verify-gaps-verify-the]): anchor auto-resolve in per-episode synopses
[._.]/ Adam Eivy6854b55ce914
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex be6e0226f9..06fdec48f3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -30,6 +30,7 @@### Pipeline- **Manual canon extraction from comicScript / teleplay stages.** Auto-extract still runs only after `prose`, but a new "Extract canon" button on both script stages lets writers pull characters/places/objects that surface only in panel directions or dialogue cues (a barkeep in a stage direction, a recurring location named only in the script) into the linked universe on demand. New route `POST /api/pipeline/issues/:id/stages/:stageId/extract-canon` (`stageId` must be `comicScript` or `teleplay`) reads the stage's `output` as the corpus and reuses the generic `extractCanonFromProse` with the same `parallel: true` + `autoLock: true` + `sourceSeriesId` stamping as the prose auto-extract, so script-derived entries survive later AI refines and stay attributable. Returns the merged universe + per-kind counts so the UI toast can summarize the merge. Three precondition errors: `PIPELINE_CANON_EXTRACT_BAD_STAGE`, `PIPELINE_CANON_EXTRACT_NO_CORPUS`, `PIPELINE_CANON_EXTRACT_NO_UNIVERSE`. New shared component `ExtractCanonButton.jsx` (gated on stage content + linked universe; tooltip explains the specific blocker when disabled); wired into `TeleplayStage` via `TextStagePanel.extraActions` and `ComicScriptStage` directly in its header. Client helper `extractPipelineCanonFromScript` in `apiPipeline.js`. 5 new vitest cases cover all precondition guards + happy path for both stage IDs.+- **Auto-resolve prompt now anchors edits in per-episode synopses.** `buildVerifyContext` already wires `seasonsTreeJson.episodes[].synopsis` into both the verify AND resolve passes (resolve reuses verify's context via `buildResolveContext`), but the resolve prompt's "How to resolve" list never explicitly told the LLM to USE those episode-level entries — so the auto-resolve pass could rewrite a volume's `synopsis` in ways that contradicted what its child episodes already describe. New first bullet in `data.sample/prompts/stages/pipeline-arc-resolve.md` pins the LLM to treat episode synopses as ground truth: volume-level synopsis rewrites must summarize what the child episodes describe, can't invent beats no episode covers, and can't paper over contradictions that originate at the episode level. Empty/null episode synopses are called out as the "user hasn't drafted that issue yet" signal so the LLM doesn't infer the volume has no content. Migration `023-resolve-prompt-episode-anchor.js` auto-bumps unmodified installs from any of the three prior shipped hashes (pre-005, pre-019, post-019) to the new template; customized installs get a manual-merge warning. Migration 019's `NEW_SHIPPED_MD5` for `pipeline-arc-resolve.md` is bumped to track the live sample so fresh installs (where `data/` is seeded post-023) don't trip 019's "customized" warning. 7 new tests in `023-resolve-prompt-episode-anchor.test.js`. Closes PLAN.md `[resolve-issues-inherits-verify-gaps-verify-the]`.### Brain / Notesdiff --git a/data.sample/prompts/stages/pipeline-arc-resolve.md b/data.sample/prompts/stages/pipeline-arc-resolve.mdindex 44d7919e03..029cb4afda 100644--- a/data.sample/prompts/stages/pipeline-arc-resolve.md+++ b/data.sample/prompts/stages/pipeline-arc-resolve.md@@ -82,13 +82,14 @@ The verification pass flagged these problems. Resolve **every** one of them in y## How to resolve-1. **Read each finding's `problem` + `suggestion`.** The suggestion is a hint, not gospel — feel free to take a different path if it cleans up the arc better, but the resulting arc MUST make the finding go away.-2. **Volume-count-vs-weight mismatches** (the most common finding) — usually the right fix is to **trim or expand a volume's `synopsis`** so it matches its `episodeCountTarget`, OR adjust `episodeCountTarget` toward the structural recommendation. Don't split a volume into two unless the structural recommendation calls for more volumes than currently exist.-3. **Character contradictions** — adjust the offending volume's `synopsis` (or the protagonist arc) so the contradiction disappears. Do not silently delete the contradicting beat — replace it with one that preserves the dramatic intent.-4. **Dropped subplots** — add the missing payoff to a later volume's `synopsis` or `endingHook`, OR remove the dangling setup from the earlier volume if the payoff would derail the arc.-5. **Unresolved finale hooks / theme drift** — surface the missing theme or arc payoff in the final volume's `synopsis`.-6. **Preserve volume `id`** for every existing volume you keep. Only assign no `id` to brand-new volumes you are adding. If you remove a volume, simply omit it from the response — the server will reconcile child issues separately.-7. **Do NOT edit per-episode (issue) records.** Those are the user's hand-authored scripts. If a finding only resolves by deleting issues, write that in the `notes` field instead of doing it.+1. **Anchor every edit in the per-episode `synopsis` entries.** Each volume's `episodes[]` array carries the user's authored episode lineup — those `synopsis` strings are the ground truth for what actually happens. Volume-level `synopsis` rewrites must summarize what the child episodes describe; don't invent beats no episode synopsis covers, and don't paper over contradictions that originate at the episode level. When a finding cites an episode (e.g. `season:2 / episode:5`), the fix usually means re-framing the volume around what that episode already shows — not contradicting it. Empty/null episode synopses mean the user hasn't drafted that issue yet; treat that volume as load-bearing on its own `synopsis` only.+2. **Read each finding's `problem` + `suggestion`.** The suggestion is a hint, not gospel — feel free to take a different path if it cleans up the arc better, but the resulting arc MUST make the finding go away.+3. **Volume-count-vs-weight mismatches** (the most common finding) — usually the right fix is to **trim or expand a volume's `synopsis`** so it matches its `episodeCountTarget`, OR adjust `episodeCountTarget` toward the structural recommendation. Don't split a volume into two unless the structural recommendation calls for more volumes than currently exist.+4. **Character contradictions** — adjust the offending volume's `synopsis` (or the protagonist arc) so the contradiction disappears. Do not silently delete the contradicting beat — replace it with one that preserves the dramatic intent.+5. **Dropped subplots** — add the missing payoff to a later volume's `synopsis` or `endingHook`, OR remove the dangling setup from the earlier volume if the payoff would derail the arc.+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 keep. Only assign no `id` to brand-new volumes you are adding. If you remove a volume, simply omit it from the response — the server will reconcile child issues separately.+8. **Do NOT edit per-episode (issue) records.** Those are the user's hand-authored scripts. If a finding only resolves by deleting issues, write that in the `notes` field instead of doing it.## Output contractdiff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.jsindex c35fab86f2..45231e35db 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js@@ -62,14 +62,21 @@ export const ACCEPTED_OLD_MD5 = {],};-// New shipped hashes — what data.sample carries post-migration.+// New shipped hashes — tracks the LIVE `data.sample` hash, not strictly the+// post-019 commit-time hash. Later migrations that further evolve any of+// these files (e.g. migration 023 amended `pipeline-arc-resolve.md`) must+// also bump the corresponding entry here so that:+// - fresh installs whose `data/` was seeded from the latest sample report+// `alreadyCurrent` instead of a misleading "customized" warning, and+// - the drift-catch test below stays in lock-step with the live sample.+// Each entry comment records who last advanced it.// Exported so the test suite can import and assert against these tables// directly rather than maintaining local copies.export const NEW_SHIPPED_MD5 = {- 'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0',- 'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c',- 'pipeline-arc-resolve.md': '8e348f3d1894382889f9f0ee7d5c6792',- 'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',+ 'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0', // post-019+ 'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019+ 'pipeline-arc-resolve.md': '5b340885c6e8f8afc63424d6b5bc7eb7', // post-023 (episode-synopsis anchor)+ 'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019};// Pure core — exposed for unit tests so the OLD→NEW upgrade branch can bediff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.jsnew file mode 100644index 0000000000..ae31cbda83--- /dev/null+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js@@ -0,0 +1,130 @@+/**+ * Add an "Anchor every edit in the per-episode `synopsis` entries" bullet at+ * the top of the `pipeline-arc-resolve.md` "How to resolve" list.+ *+ * Why:+ * `buildResolveContext` already feeds episode-level `synopsis` strings into+ * `seasonsTreeJson` (via `buildVerifyContext`), but none of the prior+ * numbered guidance steps told the LLM to use them. The auto-resolve pass+ * could rewrite a volume's `synopsis` in a way that contradicted the+ * per-episode `synopsis` entries underneath. This bullet pins the LLM to+ * treat episode synopses as ground truth when adjusting volume framing.+ *+ * The pre-resolve verify prompt (`pipeline-arc-verify.md`) already calls+ * out episode-level evidence explicitly ("Did a character die in episode 4+ * but get dialogue in episode 7?"). Resolve inherited the same data path+ * but not the same instruction shape — see PLAN.md+ * `[resolve-issues-inherits-verify-gaps-verify-the]`.+ *+ * Strategy — unmodified-only update, mirrors migrations 003 / 019:+ * - If the on-disk file matches the prior shipped MD5 (the post-019+ * hash that {{worldCanonText}} introduced), replace with the+ * data.sample version that includes the new anchor bullet.+ * - If diverged (user customized), warn and skip.+ *+ * Idempotent: a re-run on the new hash is a no-op.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';++const md5 = (str) => {+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+};++// Hashes the file may have on disk pre-migration. Most recent shipped first,+// then older. Any match is "unmodified by user → safe to replace."+// Exported so the test suite can import them and detect drift without+// maintaining local copies.+export const ACCEPTED_OLD_MD5 = {+ 'pipeline-arc-resolve.md': [+ '8e348f3d1894382889f9f0ee7d5c6792', // post-019 (worldCanonText) shipped — current pre-023+ 'a8677bbe1eb38f871fb152a5b0fec7c6', // pre-019 (pre-canon), still in setup-data.js OLD list+ '87bc5c01f1a8a97b681727a38b05edc6', // pre-005 (shape-aware), still in setup-data.js OLD list+ ],+};++// New shipped hash — what data.sample carries post-migration.+export const NEW_SHIPPED_MD5 = {+ 'pipeline-arc-resolve.md': '5b340885c6e8f8afc63424d6b5bc7eb7',+};++// Pure core — exposed for unit tests so the OLD→NEW upgrade branch can be+// exercised with synthetic hash tables instead of pinning to a git commit.+export async function applyMigration({ rootDir, accepted = ACCEPTED_OLD_MD5, current = NEW_SHIPPED_MD5 }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');++ let updated = 0;+ let alreadyCurrent = 0;+ let skipped = 0;++ for (const filename of Object.keys(accepted)) {+ const dataPath = join(stagesDir, filename);+ const samplePath = join(sampleDir, filename);++ const existing = await readFile(dataPath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return null;+ });++ if (existing === null) {+ // setup-data.js will copy it on next run; nothing for us to do.+ console.log(`📄 resolve-prompt ${filename}: not present in data/, will be created by setup-data.js`);+ continue;+ }++ const existingMd5 = md5(existing);++ if (existingMd5 === current[filename]) {+ alreadyCurrent++;+ continue;+ }++ const acceptedOld = accepted[filename];+ if (!acceptedOld.includes(existingMd5)) {+ console.warn(+ `⚠️ resolve-prompt ${filename} has been customized — skipping auto-update.\n` ++ ` To pick up the new "anchor in per-episode synopses" guidance manually, diff:\n` ++ ` data.sample/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the new bullet 1 in the "How to resolve" list.`,+ );+ skipped++;+ continue;+ }++ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated resolve-prompt: ${filename}`);+ updated++;+ }++ return { updated, alreadyCurrent, skipped };+}++export default {+ async up({ rootDir }) {+ const { updated, alreadyCurrent, skipped } = await applyMigration({ rootDir });++ if (updated > 0) {+ console.log(`📝 resolve-prompt episode-anchor migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);+ } else if (skipped > 0) {+ console.log(`📝 resolve-prompt episode-anchor migration: all files either current or customized (${skipped} skipped)`);+ } else {+ console.log(`📝 resolve-prompt episode-anchor migration: all files already up to date`);+ }++ if (skipped > 0) {+ console.warn(+ `\n⚠️ ${skipped} resolve prompt could not be auto-updated because it was customized.\n` ++ ` The auto-resolve pass will keep working but won't be explicitly told to anchor\n` ++ ` volume-synopsis edits in the per-episode \`synopsis\` entries from\n` ++ ` \`seasonsTreeJson.episodes[].synopsis\`. See data.sample/prompts/stages/.`,+ );+ }+ },+};diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.test.js b/scripts/migrations/023-resolve-prompt-episode-anchor.test.jsnew file mode 100644index 0000000000..e3eff33ddf--- /dev/null+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.test.js@@ -0,0 +1,113 @@+/**+ * Test for migration 023 — resolve prompt gains a per-episode-synopsis+ * anchor bullet at the top of "How to resolve."+ *+ * Picked up via the vitest include glob in server/vitest.config.js+ * (`../scripts/migrations/**\/*.test.js`).+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { createHash } from 'crypto';++import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './023-resolve-prompt-episode-anchor.js';++const md5 = (str) => createHash('md5')+ .update(str.replace(/\r\n/g, '\n').replace(/\r/g, '\n'))+ .digest('hex');++// Lookup the real data.sample file. Use fileURLToPath so a checkout under a+// path with spaces decodes correctly.+const repoRoot = join(import.meta.dirname || dirname(fileURLToPath(import.meta.url)), '..', '..');+const sampleBody = (filename) =>+ readFileSync(join(repoRoot, 'data.sample', 'prompts', 'stages', filename), 'utf-8');++const customizedBody = (filename) => `# CUSTOMIZED ${filename}\n\nuser-modified content not matching any shipped hash\n`;++describe('migration 023 — resolve prompt episode-synopsis anchor', () => {+ let rootDir;+ let stagesDir;+ let sampleDir;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-023-'));+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');+ mkdirSync(stagesDir, { recursive: true });+ mkdirSync(sampleDir, { recursive: true });+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(sampleDir, filename), sampleBody(filename));+ }+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('no-ops when the stage prompt is missing (setup-data.js will create it)', async () => {+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ expect(existsSync(join(stagesDir, filename))).toBe(false);+ }+ });++ it('skips files already at the new hash (idempotent re-run)', async () => {+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(stagesDir, filename), sampleBody(filename));+ }+ const result = await applyMigration({ rootDir });+ expect(result).toMatchObject({+ updated: 0,+ alreadyCurrent: Object.keys(NEW_SHIPPED_MD5).length,+ skipped: 0,+ });+ });++ it('NEW_SHIPPED_MD5 matches the live data.sample body (drift catch)', () => {+ // Without this assertion, a future template edit that forgets to bump+ // NEW_SHIPPED_MD5 would make the migration classify the sample-shaped+ // file as "customized" and silently skip the upgrade.+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ expect(md5(sampleBody(filename))).toBe(NEW_SHIPPED_MD5[filename]);+ }+ });++ it('upgrades when on-disk hash matches an accepted-old entry (synthetic fixture)', async () => {+ const filename = 'pipeline-arc-resolve.md';+ const fakeOldBody = `# synthetic pre-migration body for ${filename}\n`;+ const fakeOldHash = md5(fakeOldBody);++ writeFileSync(join(stagesDir, filename), fakeOldBody);+ const result = await applyMigration({+ rootDir,+ accepted: { [filename]: [fakeOldHash] },+ current: { [filename]: md5(sampleBody(filename)) },+ });+ expect(result).toMatchObject({ updated: 1, skipped: 0 });+ expect(readFileSync(join(stagesDir, filename), 'utf-8')).toBe(sampleBody(filename));+ });++ it('skips (does not clobber) a customized file whose hash matches neither old nor new', async () => {+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ writeFileSync(join(stagesDir, filename), customizedBody(filename));+ }+ await migration.up({ rootDir });+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {+ expect(readFileSync(join(stagesDir, filename), 'utf-8')).toBe(customizedBody(filename));+ }+ });++ it('exposes ACCEPTED_OLD_MD5 and NEW_SHIPPED_MD5 with consistent shapes', () => {+ expect(Object.keys(ACCEPTED_OLD_MD5).sort()).toEqual(Object.keys(NEW_SHIPPED_MD5).sort());+ for (const old of Object.values(ACCEPTED_OLD_MD5)) {+ expect(Array.isArray(old)).toBe(true);+ expect(old.length).toBeGreaterThan(0);+ for (const h of old) expect(h).toMatch(/^[0-9a-f]{32}$/);+ }+ for (const h of Object.values(NEW_SHIPPED_MD5)) {+ expect(h).toMatch(/^[0-9a-f]{32}$/);+ }+ });+});diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 827d724b70..dc9281dd30 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -157,9 +157,10 @@ const SHIPPED_PROMPT_OLD_MD5 = {// volume-verify: c6ea28… (pre-005) and 03f3c8… (post-005, pre-019) both// auto-updatable to the post-019 (worldCanonText) hash.'pipeline-volume-verify.md': ['c6ea28e972ad6e229bafb2d602b4dda3', '03f3c874cb80e1c98abcf03168fa7a92'],- // arc-resolve: 87bc5c… (pre-005) and a8677b… (post-005, pre-019) both- // auto-updatable to the post-019 (worldCanonText) hash.- 'pipeline-arc-resolve.md': ['87bc5c01f1a8a97b681727a38b05edc6', 'a8677bbe1eb38f871fb152a5b0fec7c6'],+ // arc-resolve: 87bc5c… (pre-005), a8677b… (post-005, pre-019), and+ // 8e348f… (post-019, pre-023) all auto-updatable to the post-023+ // (per-episode-synopsis anchor) hash.+ 'pipeline-arc-resolve.md': ['87bc5c01f1a8a97b681727a38b05edc6', 'a8677bbe1eb38f871fb152a5b0fec7c6', '8e348f3d1894382889f9f0ee7d5c6792'],// Shot decomposition additions (migration 006).'pipeline-extract-scenes.md': '59fa5ee305ce53d91eb15224d8b546d3',// setting→place rename, migration 022. Two known auto-updatable hashes:@@ -188,7 +189,7 @@ const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-arc-overview.md': '0a1f6ffa6908522e3690c5e9e53a6ee0','pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c','pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',- 'pipeline-arc-resolve.md': '8e348f3d1894382889f9f0ee7d5c6792',+ 'pipeline-arc-resolve.md': '5b340885c6e8f8afc63424d6b5bc7eb7','pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba','writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4','cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a',