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

feat([pipeline-idea-stage-character-detail-plumbing]): plumb char bible into idea-stage + extract migration scaffold

[._.]/ Adam Eivyfb6e76fb0615
diff --git a/DONE.md b/DONE.md
index 66bbdca290..633912771f 100644
--- a/DONE.md
+++ b/DONE.md
@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
### 2026-05-18
+- **[pipeline-idea-stage-character-detail-plumbing] Plumb richer character bible into idea-stage prompt + extract migration scaffold.** Three slugs landed in one PR. (1) `data.sample/prompts/stages/pipeline-idea-expansion.md`'s `{{#series.characters}}` iteration now matches the prose/comicScript/teleplay templates verbatim: `**{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}`. The beat-sheet LLM now sees the same character interiority + role that downstream stages see, so arc decisions made at idea-stage don't lose context the bible already carries. New migration `scripts/migrations/025-idea-stage-character-detail.js` rewrites any of three legacy shipped hashes (pre-003, post-003/pre-004, post-004/pre-025) onto the new shape; customized installs get a manual-merge warning. `scripts/setup-data.js` drift table updated in parallel (`1ee44cf95851ff8debf18729ebcd40b4` appended to the auto-updatable OLD list, NEW bumped to `1f3c5d077a5ef9a4b610335d5e3edd9c`). (2) `[extract-migration-scaffolding-into-scripts]` shipped — `scripts/migrations/_lib.js` exposes `md5`, `applyPromptReplaceMigration({ rootDir, accepted, current, label, customizedHint })`, and `makePromptReplaceMigration({ accepted, current, label, customizedHint, skipFooter? })` returning `{ applyMigration, up }`. Per-migration files collapse to ~50 LOC of hash table + label + hint. (3) `[extract-migration-test-helpers]` shipped — `scripts/migrations/_testHelpers.js` exposes `md5` (re-exported from `_lib.js`), `repoRoot`, `sampleBody(filename, subdir?)`, `customizedBody(filename)`, and a `runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5, prefix, subdir? })` describe-block builder that fires the six standard cases (missing-file no-op / idempotent / drift-catch / synthetic-OLD upgrade / customized preservation / hash-table shape) inside the surrounding describe. Per-migration test files collapse to a single `runPromptMigrationTests` call. Migration 023 refactored as proof-of-pattern: source went 130→58 LOC, test went 113→21 LOC. `scripts/run-migrations.js` filter gained `&& !f.startsWith('_')` so the shared helpers stay out of the migration sequence; new `scripts/run-migrations.test.js` regression case pins the exclusion against a phantom `_lib.js` fixture. All 257 server test files (5663 tests) + 48 migration/runner tests pass. Three `/simplify` follow-ups deferred to PLAN.md: `[backport-pre-023-migrations-to-_lib]` (collapse the other six prompt-replace migrations onto `_lib.js`), `[setup-data-import-drift-tables-from-migrations]` (drop the hand-mirrored hash tables in `setup-data.js` once every migration exports them), and `[parallelize-applypromptreplacemigration-files]` (theoretical, for the first multi-file migration).
- **[coverautofiler-dispatcher-redundant-getseries] `fileCoverIntoAutoCollection` dispatcher — pass preloaded series into the universe leaf.** `server/services/pipeline/coverUniverseFiler.js`'s dispatcher now forwards its already-fetched series to `fileCoverIntoUniverseCollection` via an optional `_preloadedSeries` arg; the universe leaf accepts the preload, skips its initial `getSeries`, and preserves the mid-flight race-detection re-read. Net effect for the dominant (universe-linked) path: 2 `getSeries` calls per cover completion instead of 3. The series leaf intentionally does NOT accept a preload — its own first read is load-bearing for the early re-route check (a universe link added between the dispatcher's fetch and the leaf's entry must trigger the re-route into the universe leaf, otherwise the cover would land in the per-series collection and merely get orphaned by the post-`addItem` recovery instead of filed to the universe). Direct callers of the universe leaf (no preload) keep the old shape via a `?? await getSeries(...).catch(() => null)` fallback. +1 test in `coverUniverseFiler.test.js` spies on `seriesSvc.getSeries` and pins the post-optimization universe-path call count (2 total) via the capture-restore-assert pattern so a failing assertion doesn't leak the spy. All 21 cover-filer tests + 349 pipeline-service tests pass.
- **[importer-canonprompt-preview-fragments-helper] Share a per-kind preview-fragments helper between Importer and `canonPrompt.js`.** New `previewCanonFragments(kind, entry)` helper in the mirrored `server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` returns `{ subtitle, body }` where `subtitle` is a single trimmed string and `body` is an ordered `[{ field, value }]` array of non-blank fields. Backed by a new `PREVIEW_SPEC` keyed by canonical kind name (`characters` → `{ subtitleField: 'role', bodyFields: ['physicalDescription','personality','background'] }`, `places` → `{ subtitleField: 'slugline', bodyFields: ['description'] }`, `objects` → `{ subtitleField: null, bodyFields: ['description','significance'] }`). Intentionally wider than `shortCanonDescriptorFragments` (which is scoped to the visual subset that drives render-prompts) — preview exists so the user can disambiguate which entry to commit, so it surfaces narrative-only fields (`personality`, `background`, `slugline`) that have no visual role. The three `CanonReviewSection` callsites in `client/src/pages/Importer.jsx` no longer pass `renderSubtitle`/`renderBody` props — `CanonReviewSection` now calls the helper directly with the `kind` prop it was already passing, collapsing 18 lines of inline ternaries + filter/join calls onto a single helper invocation. 11 new vitest cases in `server/lib/canonPrompt.test.js` cover null/non-object/unknown-kind edge shapes, kind plural/singular passthrough, per-kind field-presence semantics (characters: role subtitle + 3-field body, no description fallback; places: slugline + description only; objects: empty subtitle + description+significance), whitespace trimming, and confirms RICH-only fields (palette/era/weather/recurringDetails) are NOT in preview. PLAN.md's `'places' → 'settings'` alias note was stale — codebase already canonicalized on `'places'` as the kind name (`normalizeKind` returns `'places'` correctly), so no alias work was needed. All 5608 server tests + 92 client tests pass.
- **[resolve-issues-inherits-verify-gaps-verify-the] Resolve-issues inherits verify gaps.** The auto-resolve LLM pass (`pipeline-arc-resolve.md`) was receiving per-episode `synopsis` strings via `seasonsTreeJson.episodes[].synopsis` (wired in `buildVerifyContext` and inherited by `buildResolveContext`) but its "How to resolve" instructions never told the LLM to use them — only the sibling verify prompt ("Did a character die in episode 4 but get dialogue in episode 7?") called the data out by name. As a result the resolve pass could rewrite a volume's `synopsis` in ways that contradicted what its child episodes already described. Added a new first bullet to `data.sample/prompts/stages/pipeline-arc-resolve.md` that 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, can't paper over contradictions that originate at the episode level, and when a finding cites an episode (e.g. `season:2 / episode:5`) the fix means re-framing the volume around what that episode already shows. 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. New migration `scripts/migrations/023-resolve-prompt-episode-anchor.js` rewrites the installed prompt for any of three legacy shipped hashes (pre-005, pre-019, post-019); customized installs get a manual-merge warning. Migration 019's `NEW_SHIPPED_MD5['pipeline-arc-resolve.md']` bumped to the new post-023 live-sample hash so fresh installs (where `data/` is seeded from the latest sample) report `alreadyCurrent` instead of a misleading "customized" warning; the comment block above 019's table now documents the convention that later migrations re-touching a file must bump 019's entry too. `scripts/setup-data.js` drift table updated in parallel (`8e348f3d...` appended to the auto-updatable OLD list, NEW bumped to `5b340885...`). 6 new tests in `023-resolve-prompt-episode-anchor.test.js` cover missing-file no-op, idempotent re-run, drift-catch against the live sample, OLD→NEW upgrade via synthetic fixture, customized-file preservation, and table shape consistency. All 5604 server tests + 28 migration tests pass. Two `/simplify` follow-ups deferred to PLAN.md: `[extract-migration-scaffolding-into-scripts]` expanded to flag that 023 is the fourth clone of the migration scaffold, and new companion item `[extract-migration-test-helpers]` for lifting the test scaffold (md5 helper, repoRoot/sampleBody/customizedBody, mkdtemp seed beforeEach, 5 shared test bodies) alongside `_lib.js`.
diff --git a/PLAN.md b/PLAN.md
index f0fd30069c..a58bf53d56 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -28,7 +28,6 @@ _Nothing currently parked — pick the next item from the Backlog._
### Pipeline continuity / approval
- [ ] [per-season-and-per-field-locks-extend-arc-lock] **Per-season + per-field locks.** Arc-level lock shipped (`LOCKABLE_STAGES = ['arc']` in `server/services/pipeline/series.js:59`, enforced at `server/services/pipeline/arcPlanner.js:231`); extend to seasons and per-field. Gate bulk runners (`bulkReassignSeason` at `server/services/pipeline/issues.js:418` has no lock check today). Surface a stage-progress strip in `client/src/pages/PipelineIssue.jsx`.
-- [ ] [pipeline-idea-stage-character-detail-plumbing] **Plumb character `physicalDescription`/`personality`/`background` into idea-stage prompt.** Today `data.sample/prompts/stages/pipeline-idea-expansion.md:16` iterates `{{#series.characters}}` with `name`/`description` only — richer bible fields are dropped.
- [ ] [pipeline-visual-stages-setting-field-injection] **Inject setting `palette`/`era`/`weather`/`recurringDetails` into visual stages.** Storyboard/comic-panel prompts mention these in prose instructions but don't hydrate them from the matched bible entry. Tie this to the bible-SETTING→PLACE rename (`existingPlacesJson` carries them once that lands).
- [ ] [pipeline-text-stages-worldentitiessummary] **Add `worldEntitiesSummary` to text stages.** Zero occurrences in codebase today; a one-string canon synopsis (top-N entities by frequency, name + 1-line descriptor) keeps text-stage prompts under context budget while still giving the LLM continuity anchors.
- [ ] [bible-schema-speech-pattern-field] **Add a dedicated speech-pattern field to the character bible schema.** `voiceId` is the TTS engine pointer, not a written speech-pattern field. Add to `PROMPT_FIELDS[CHARACTER]` in `server/lib/storyBible.js:121` and pipe through extraction + script prompts.
@@ -144,8 +143,9 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [comic-book-pdf-export-once-stages-comicpages] **Comic-book PDF export.** Once `stages.comicPages` carries enough panel data + rendered images, export print-ready PDF.
- [ ] [voice-controlled-stage-advancement-register] **Voice-controlled stage advancement.** Register pipeline stage navigation actions in `voice/tools.js`.
- [ ] [ai-assisted-panel-scene-prompt-generation-reserve] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` for a future "turn script fragment into N image-gen prompts" button.
-- [ ] [extract-migration-scaffolding-into-scripts] **Extract migration scaffolding into `scripts/migrations/_lib.js`.** Migrations 003, 006, 019, and now 023 all implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift to a shared helper; next migration becomes ~15 lines. Migration 023 was the fourth migration to clone the scaffold — the next migration after 023 should block on this extraction first; the boilerplate cost is now larger than typical content changes.
-- [ ] [extract-migration-test-helpers] **Extract migration test scaffolding into `scripts/migrations/_testHelpers.js`.** Companion to `[extract-migration-scaffolding-into-scripts]`. `019.test.js` and `023.test.js` share near-verbatim setup: a newline-normalizing `md5`, a `repoRoot` + `sampleBody(filename)` helper, a `customizedBody(filename)` fixture, a `mkdtempSync`-based `beforeEach` that seeds `data.sample/`, and five of the test cases themselves (no-op-missing / idempotent / drift-catch / synthetic-old-upgrade / customized-skip / shape-consistency). Lift `{ md5, repoRoot, sampleBody, customizedBody, makeSandbox(prefix) }` and a shared describe-block builder so each per-migration test only carries migration-specific assertions. Land alongside `_lib.js` as one cleanup PR. Surfaced by /simplify during `[resolve-issues-inherits-verify-gaps-verify-the]`.
+- [ ] [backport-pre-023-migrations-to-_lib] **Back-port pre-023 prompt-replace migrations onto `scripts/migrations/_lib.js`.** 003 / 004 / 005 / 006 / 010 / 013 / 019 all clone the inline `applyMigration` + per-file scan + customized-skip warning pattern that `_lib.js` now centralizes. Wrap any `OLD_SHIPPED_MD5: string` entries (003 / 004 / 006) into single-element arrays to match the `accepted[filename]: string[]` shape. Drop ~70 LOC per migration; nothing changes behaviorally so the only risk is mis-typed hashes — review each diff alongside a re-run of its test against the `_testHelpers.js` `runPromptMigrationTests`. Settled-history migrations have a higher rewrite-bar than active code, so a separate PR with focused review is appropriate. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.
+- [ ] [setup-data-import-drift-tables-from-migrations] **`setup-data.js` should import drift tables from each migration file.** `SHIPPED_PROMPT_OLD_MD5` + `SHIPPED_PROMPT_NEW_MD5` in `scripts/setup-data.js:139-196` manually mirror the `ACCEPTED_OLD_MD5` + `NEW_SHIPPED_MD5` exports each migration file already maintains. The mirror is hand-edited every time a migration ships and is the most likely place to drift. After `[backport-pre-023-migrations-to-_lib]` lands, every prompt-replace migration will export those constants — `setup-data.js` can build `SHIPPED_PROMPT_OLD_MD5` / `SHIPPED_PROMPT_NEW_MD5` by `import * as m025 from './migrations/025-idea-stage-character-detail.js'`-style sweep (or by glob+dynamic import) and removing the mirror entirely. Single source of truth, no hand sync. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.
+- [ ] [parallelize-applypromptreplacemigration-files] **Parallelize `applyPromptReplaceMigration` per-file scan.** Today every prompt-replace migration covers exactly one file, so the serial `for (await readFile…)` loop in `scripts/migrations/_lib.js` costs nothing. When the first multi-file migration lands, fold the loop into `Promise.all(Object.keys(accepted).map(async filename => …))` and accumulate the `{ updated, alreadyCurrent, skipped }` counters post-flight. Theoretical until needed.
- [ ] [shots-aware-scene-output-contract-partial-split] **Shots-aware scene-output-contract partial.** Split into `_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md` when a third shots-using stage appears.
- [ ] [per-panel-scene-image-progress-in-the-pipeline-ui] **Per-panel/scene image progress in the Pipeline UI.** ComicPages and Storyboards record `jobId` but don't subscribe to the media-job SSE for live preview.
diff --git a/data.sample/prompts/stages/pipeline-idea-expansion.md b/data.sample/prompts/stages/pipeline-idea-expansion.md
index d2d0cb8412..d05f348893 100644
--- a/data.sample/prompts/stages/pipeline-idea-expansion.md
+++ b/data.sample/prompts/stages/pipeline-idea-expansion.md
@@ -14,7 +14,7 @@ You are a story consultant who turns a rough seed idea into a tight beat sheet f
### Characters in the series
{{#series.characters}}
-- **{{name}}** — {{description}}
+- **{{name}}**{{#role}} ({{role}}){{/role}} — {{#physicalDescription}}{{physicalDescription}}{{/physicalDescription}}{{^physicalDescription}}{{description}}{{/physicalDescription}}{{#personality}} | personality: {{personality}}{{/personality}}{{#background}} | background: {{background}}{{/background}}
{{/series.characters}}
{{^series.characters}}
*(No characters defined yet — invent placeholders only if absolutely required.)*
diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.js
index ae31cbda83..66be027e92 100644
--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js
+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js
@@ -16,23 +16,10 @@
* 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.
+ * Implementation: hash-driven prompt-replace via `./_lib.js`. Idempotent.
*/
-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');
-};
+import { makePromptReplaceMigration } from './_lib.js';
// Hashes the file may have on disk pre-migration. Most recent shipped first,
// then older. Any match is "unmodified by user → safe to replace."
@@ -51,80 +38,22 @@ 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/.`,
- );
- }
- },
-};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'resolve-prompt',
+ customizedHint: (filename) =>
+ ` 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.`,
+ skipFooter: (count) =>
+ `⚠️ ${count} 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/.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.test.js b/scripts/migrations/023-resolve-prompt-episode-anchor.test.js
index e3eff33ddf..ebdde9e172 100644
--- a/scripts/migrations/023-resolve-prompt-episode-anchor.test.js
+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.test.js
@@ -3,111 +3,20 @@
* 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`).
+ * (`../scripts/migrations/**\/*.test.js`). The 6 standard prompt-migration
+ * test bodies live in `./_testHelpers.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 { describe } from 'vitest';
+import { runPromptMigrationTests } from './_testHelpers.js';
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}$/);
- }
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-023-',
});
});
diff --git a/scripts/migrations/025-idea-stage-character-detail.js b/scripts/migrations/025-idea-stage-character-detail.js
new file mode 100644
index 0000000000..774ea252cf
--- /dev/null
+++ b/scripts/migrations/025-idea-stage-character-detail.js
@@ -0,0 +1,59 @@
+/**
+ * Extend the idea / beat-sheet expansion prompt's `{{#series.characters}}`
+ * iteration to surface `role`, `physicalDescription`, `personality`, and
+ * `background` — matching the prose / comic-script / teleplay templates.
+ *
+ * Why:
+ * The character bible carries rich per-character context
+ * (`physicalDescription`, `personality`, `background`, `role`, etc.) but the
+ * first stage of the pipeline — idea / beat-sheet expansion — was rendering
+ * only `**{{name}}** — {{description}}`. Downstream stages (prose,
+ * comic-script, teleplay) already inject the richer fields with the same
+ * mustache pattern. The beat sheet is the spine every later stage hangs
+ * from, so letting the LLM see character interiority + role here produces
+ * better arc decisions that downstream stages can keep building on.
+ *
+ * See PLAN.md `[pipeline-idea-stage-character-detail-plumbing]`.
+ *
+ * Implementation: hash-driven prompt-replace via `./_lib.js`. Idempotent.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+// 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-idea-expansion.md': [
+ '1ee44cf95851ff8debf18729ebcd40b4', // post-004 shipped — current pre-025
+ '41facefbc0c0549d456bef9111f95ab9', // post-003, pre-004, still in setup-data.js OLD list
+ 'aee25112b2c596f643b17c559b772c22', // pre-003, still in setup-data.js OLD list
+ ],
+};
+
+// New shipped hash — what data.sample carries post-migration.
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-idea-expansion.md': '1f3c5d077a5ef9a4b610335d5e3edd9c',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'idea-stage-character-detail',
+ customizedHint: (filename) =>
+ ` To pick up the new {{#series.characters}} role/physicalDescription/personality/background\n` +
+ ` plumbing manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and replace the character iteration block with the new shape.`,
+ skipFooter: (count) =>
+ `⚠️ ${count} idea-stage prompt could not be auto-updated because it was customized.\n` +
+ ` The idea / beat-sheet expansion will keep working but won't see character\n` +
+ ` \`role\`, \`physicalDescription\`, \`personality\`, or \`background\` from the bible.\n` +
+ ` See data.sample/prompts/stages/pipeline-idea-expansion.md.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/025-idea-stage-character-detail.test.js b/scripts/migrations/025-idea-stage-character-detail.test.js
new file mode 100644
index 0000000000..0ee1219700
--- /dev/null
+++ b/scripts/migrations/025-idea-stage-character-detail.test.js
@@ -0,0 +1,24 @@
+/**
+ * Test for migration 025 — idea / beat-sheet expansion stage prompt gains the
+ * richer `{{#series.characters}}` iteration (role + physicalDescription /
+ * description fallback + personality + background) that the prose,
+ * comic-script, and teleplay templates already use.
+ *
+ * Picked up via the vitest include glob in server/vitest.config.js
+ * (`../scripts/migrations/**\/*.test.js`). The 6 standard prompt-migration
+ * test bodies live in `./_testHelpers.js`.
+ */
+import { describe } from 'vitest';
+
+import { runPromptMigrationTests } from './_testHelpers.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './025-idea-stage-character-detail.js';
+
+describe('migration 025 — idea-stage character detail plumbing', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-025-',
+ });
+});
diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.js
new file mode 100644
index 0000000000..f1a76bd1f2
--- /dev/null
+++ b/scripts/migrations/_lib.js
@@ -0,0 +1,123 @@
+/**
+ * Shared scaffolding for hash-driven prompt-replace migrations.
+ *
+ * Migrations 023 and 025 use `makePromptReplaceMigration` to collapse each
+ * migration onto ~50 lines (hash table + label + customized-skip hint).
+ * 003, 006, 019 are inline copies of the same pattern — candidates for a
+ * back-port pass; see PLAN.md `[backport-pre-023-migrations-to-_lib]`.
+ *
+ * The runner (`scripts/run-migrations.js`) explicitly skips `_`-prefixed
+ * files so this module is never imported as a migration.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { createHash } from 'crypto';
+
+/**
+ * Newline-normalized MD5. Both `\r\n` and bare `\r` collapse to `\n` before
+ * hashing so Windows checkouts of the same template hash identically.
+ */
+export const md5 = (str) => {
+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
+ return createHash('md5').update(normalized).digest('hex');
+};
+
+/**
+ * Core scan — exposed so tests can pass synthetic `accepted` / `current`
+ * tables to exercise the OLD→NEW branch without pinning to a real shipped
+ * hash. Files missing from `data/` are no-ops — `setup-data.js` creates them.
+ */
+export async function applyPromptReplaceMigration({
+ rootDir,
+ accepted,
+ current,
+ label,
+ customizedHint,
+}) {
+ 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) {
+ console.log(`📄 ${label} ${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(
+ `⚠️ ${label} ${filename} has been customized — skipping auto-update.\n` +
+ customizedHint(filename),
+ );
+ skipped++;
+ continue;
+ }
+
+ const sampleContent = await readFile(samplePath, 'utf-8');
+ await writeFile(dataPath, sampleContent);
+ console.log(`✅ updated ${label}: ${filename}`);
+ updated++;
+ }
+
+ return { updated, alreadyCurrent, skipped };
+}
+
+/**
+ * Factory: returns `{ applyMigration, up }`. `skipFooter(count)` is optional
+ * — when provided, the wrapped `up()` logs it after the per-file pass if any
+ * file was skipped (user-facing guidance about what the customized files miss).
+ */
+export function makePromptReplaceMigration({
+ accepted,
+ current,
+ label,
+ customizedHint,
+ skipFooter,
+}) {
+ const applyMigration = (opts = {}) =>
+ applyPromptReplaceMigration({
+ accepted,
+ current,
+ label,
+ customizedHint,
+ ...opts,
+ });
+
+ const up = async ({ rootDir }) => {
+ const { updated, alreadyCurrent, skipped } = await applyMigration({ rootDir });
+
+ if (updated > 0) {
+ console.log(`📝 ${label} migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
+ } else if (skipped > 0) {
+ console.log(`📝 ${label} migration: all files either current or customized (${skipped} skipped)`);
+ } else {
+ console.log(`📝 ${label} migration: all files already up to date`);
+ }
+
+ if (skipped > 0 && skipFooter) {
+ console.warn('\n' + skipFooter(skipped));
+ }
+ };
+
+ return { applyMigration, up };
+}
diff --git a/scripts/migrations/_testHelpers.js b/scripts/migrations/_testHelpers.js
new file mode 100644
index 0000000000..61c6cb7a56
--- /dev/null
+++ b/scripts/migrations/_testHelpers.js
@@ -0,0 +1,127 @@
+/**
+ * Shared test scaffolding for hash-driven prompt-replace migrations.
+ * Companion to `./_lib.js`. The runner skips `_`-prefixed files.
+ *
+ * Per-migration `*.test.js` collapses to a `describe` + a single
+ * `runPromptMigrationTests({ migration, applyMigration, ACCEPTED_OLD_MD5,
+ * NEW_SHIPPED_MD5, prefix })` call — six standard cases fire inside it.
+ */
+
+import { 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 { md5 } from './_lib.js';
+
+export { md5 };
+
+// scripts/migrations/_testHelpers.js → ../.. is the repo root.
+const __dirname = dirname(fileURLToPath(import.meta.url));
+export const repoRoot = join(__dirname, '..', '..');
+
+export const sampleBody = (filename, subdir = 'stages') =>
+ readFileSync(join(repoRoot, 'data.sample', 'prompts', subdir, filename), 'utf-8');
+
+/** Synthetic body that won't match any shipped hash. */
+export const customizedBody = (filename) =>
+ `# CUSTOMIZED ${filename}\n\nuser-modified content not matching any shipped hash\n`;
+
+/**
+ * `prefix` is the `mkdtempSync` directory name — keep migration-specific
+ * (`'migration-025-'`) so a debugger leaves a recognizable sandbox in `/tmp`.
+ * `subdir` defaults to `'stages'`; pass `'_partials'` for shared mustache
+ * fragments that live under `data/prompts/_partials/` instead.
+ */
+export function runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix,
+ subdir = 'stages',
+}) {
+ let rootDir;
+ let stagesDir;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), prefix));
+ stagesDir = join(rootDir, 'data', 'prompts', subdir);
+ const sampleDir = join(rootDir, 'data.sample', 'prompts', subdir);
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(sampleDir, { recursive: true });
+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {
+ writeFileSync(join(sampleDir, filename), sampleBody(filename, subdir));
+ }
+ });
+
+ 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, subdir));
+ }
+ 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, subdir))).toBe(NEW_SHIPPED_MD5[filename]);
+ }
+ });
+
+ it('upgrades when on-disk hash matches an accepted-old entry (synthetic fixture)', async () => {
+ const [filename] = Object.keys(NEW_SHIPPED_MD5);
+ 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, subdir)) },
+ });
+ expect(result).toMatchObject({ updated: 1, skipped: 0 });
+ expect(readFileSync(join(stagesDir, filename), 'utf-8')).toBe(sampleBody(filename, subdir));
+ });
+
+ 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/run-migrations.js b/scripts/run-migrations.js
index f8d5343711..c0ed43836c 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -50,9 +50,11 @@ export async function runMigrations({
// files (*.test.js) are excluded — they don't export `up()` and would
// throw the runner if imported as migrations. The vitest config picks
// them up via its own glob (`../scripts/**/*.test.js` in
- // server/vitest.config.js).
+ // server/vitest.config.js). `_`-prefixed files (e.g. `_lib.js`,
+ // `_testHelpers.js`) are shared helpers consumed by migration files and
+ // their tests — they're never migrations themselves.
const files = (await readdir(migrationsDir))
- .filter(f => f.endsWith('.js') && !f.endsWith('.test.js'))
+ .filter(f => f.endsWith('.js') && !f.endsWith('.test.js') && !f.startsWith('_'))
.sort();
let ran = 0;
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index afde20fef2..1a525256d8 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -93,4 +93,19 @@ export default {
expect(corruptSiblings()).toHaveLength(0);
expect(warnSpy).not.toHaveBeenCalled();
});
+
+ it('skips `_`-prefixed shared-helper files (never imports them as migrations)', async () => {
+ // _lib.js / _testHelpers.js are imported by migration files + tests but
+ // they don't export `up()` — if the runner tried to load them it would
+ // throw "does not export an up() function".
+ writeFileSync(join(migrationsDir, '_lib.js'), `
+export const md5 = (s) => s;
+// no default export, no up() — would throw if the runner picked this up.
+`);
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(1); // only 001-fixture.js ran
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['001-fixture.js']);
+ });
});
diff --git a/scripts/setup-data.js b/scripts/setup-data.js
index dc9281dd30..4885c4b6c0 100644
--- a/scripts/setup-data.js
+++ b/scripts/setup-data.js
@@ -1,9 +1,10 @@
#!/usr/bin/env node
import { existsSync, mkdirSync, cpSync, readdirSync, statSync, readFileSync, writeFileSync, renameSync, rmdirSync } from 'fs';
-import { createHash } from 'crypto';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
+import { md5 } from './migrations/_lib.js';
+
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
const dataDir = join(rootDir, 'data');
@@ -137,9 +138,10 @@ for (const { relPath, mergeKey } of JSON_MERGE_TARGETS) {
// recognize multi-migration lineages (file evolved through 003 → 004 → 005);
// a user at any intermediate hash still gets the "run migrations" prompt.
const SHIPPED_PROMPT_OLD_MD5 = {
- // idea-expansion: aee… (pre-003) and 41fa… (post-003, pre-004) both
- // auto-updatable to the post-004 hash.
- 'pipeline-idea-expansion.md': ['aee25112b2c596f643b17c559b772c22', '41facefbc0c0549d456bef9111f95ab9'],
+ // idea-expansion: aee… (pre-003), 41fa… (post-003, pre-004), and
+ // 1ee44c… (post-004, pre-025) all auto-updatable to the post-025
+ // (role/physicalDescription/personality/background plumbing) hash.
+ 'pipeline-idea-expansion.md': ['aee25112b2c596f643b17c559b772c22', '41facefbc0c0549d456bef9111f95ab9', '1ee44cf95851ff8debf18729ebcd40b4'],
'pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7',
// comic-script: 40e5fd… (pre-003) and beab03… (post-003, pre-011) both
// auto-updatable to the post-011 (back-cover) hash.
@@ -181,7 +183,7 @@ const SHIPPED_PROMPT_OLD_MD5 = {
],
};
const SHIPPED_PROMPT_NEW_MD5 = {
- 'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4',
+ 'pipeline-idea-expansion.md': '1f3c5d077a5ef9a4b610335d5e3edd9c',
'pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6',
'pipeline-comic-script.md': '1e0af305c27d0c80c4b482d2ebcb4a0d',
'pipeline-teleplay.md': '376f779f4687b598f1c92ca4e770fd5a',
@@ -210,11 +212,6 @@ const SHIPPED_PARTIAL_NEW_MD5 = {
};
const SHIPPED_PARTIAL_FILES = Object.keys(SHIPPED_PARTIAL_OLD_MD5);
-const md5 = (s) => {
- const normalized = s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
- return createHash('md5').update(normalized).digest('hex');
-};
-
// Walk one directory's worth of shipped prompt files against a hash table
// and partition them into auto-updatable (still on a known old hash) vs.
// customized (hash matches neither old nor new). Used twice — once for