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

refactor([backport-pre-023-migrations-to-_lib]): collapse 003/004/005/006/010/013/019 onto _lib.js helper

[._.]/ Adam Eivy46ab3407c3be
diff --git a/scripts/migrations/003-update-pipeline-stage-prompts.js b/scripts/migrations/003-update-pipeline-stage-prompts.js
index 66b3e3ec69..ec5294c9d6 100644
--- a/scripts/migrations/003-update-pipeline-stage-prompts.js
+++ b/scripts/migrations/003-update-pipeline-stage-prompts.js
@@ -1,5 +1,5 @@
/**
- * Update five pipeline stage prompt templates that were updated in the
+ * Update pipeline stage prompt templates that were updated in the
* "length profile" feature (feat/pipeline-genconfig-length-cover).
*
* The prompts now carry `{{lengthTargets.*}}` variables so the idea, prose,
@@ -7,144 +7,50 @@
* and page/minute targets with the per-issue length profile picker instead of
* using the old hardcoded numbers.
*
- * Strategy — "unmodified-only" update:
- * Each file is compared against the MD5 of the version that shipped before
- * this feature landed (the "old shipped" hash). If the file on disk still
- * matches that hash, the user hasn't customized it and we replace it with
- * the current data.sample version. If the hash diverges (customized), we
- * skip and warn so the user can merge manually.
+ * `pipeline-tv-script.md` was renamed to `pipeline-teleplay.md` in 96bc7f17;
+ * an older install that never ran migration 003 still carries the obsolete
+ * file in `data/`. `retireOnSampleMissing: true` lets the shared helper soft-
+ * delete it when unmodified and warn when customized, instead of crashing on
+ * the sample-side ENOENT.
*
- * Idempotent — a re-run that finds the current data.sample hash on disk
- * is a no-op.
+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
*/
-import { readFile, writeFile, unlink } from 'fs/promises';
-import { join } from 'path';
-import { createHash } from 'crypto';
+import { makePromptReplaceMigration } from './_lib.js';
-const md5 = (str) => {
- const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
- return createHash('md5').update(normalized).digest('hex');
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-idea-expansion.md': ['aee25112b2c596f643b17c559b772c22'],
+ 'pipeline-prose.md': ['bfea5aeeb471aae9749baee765b473a7'],
+ 'pipeline-comic-script.md': ['40e5fdc1a1e68a7419b7dad936366c1a'],
+ 'pipeline-tv-script.md': ['3f6fecc25573ed054b47db392250034a'],
+ 'pipeline-season-episodes.md': ['6e349ad26bed8a0ccb042571f03f03eb'],
};
-// MD5 hashes of the version shipped BEFORE the length-profile feature.
-// Computed from git show <merge-base>:data.sample/prompts/stages/<file>.
-// If the live file matches one of these, the user hasn't customized it.
-const OLD_SHIPPED_MD5 = {
- 'pipeline-idea-expansion.md': 'aee25112b2c596f643b17c559b772c22',
- 'pipeline-prose.md': 'bfea5aeeb471aae9749baee765b473a7',
- 'pipeline-comic-script.md': '40e5fdc1a1e68a7419b7dad936366c1a',
- 'pipeline-tv-script.md': '3f6fecc25573ed054b47db392250034a',
- 'pipeline-season-episodes.md':'6e349ad26bed8a0ccb042571f03f03eb',
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9',
+ 'pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6',
+ 'pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769',
+ 'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a',
+ 'pipeline-season-episodes.md': 'c4928e2a5f833358116b29d2d669888d',
};
-// MD5 hashes of the updated versions in data.sample (what this migration
-// copies in). Used to detect "already up to date" on re-runs.
-const NEW_SHIPPED_MD5 = {
- 'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9',
- 'pipeline-prose.md': '30ac30ec2b9d3e2a9eb869c181732cc6',
- 'pipeline-comic-script.md': 'beab031951859ca13579cdb9c4dbe769',
- 'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a',
- 'pipeline-season-episodes.md':'c4928e2a5f833358116b29d2d669888d',
-};
-
-export default {
- async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
-
- let updated = 0;
- let alreadyCurrent = 0;
- let skipped = 0;
- let retired = 0;
-
- for (const filename of Object.keys(OLD_SHIPPED_MD5)) {
- 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) {
- // File missing from data/ — setup-data.js will copy it on next run;
- // nothing for this migration to do.
- console.log(`📄 pipeline stage prompt ${filename}: not present in data/, will be created by setup-data.js`);
- continue;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_MD5[filename]) {
- // Already at the new version — idempotent no-op.
- alreadyCurrent++;
- continue;
- }
-
- // Read the sample now so we can both compare and detect a retired
- // file (sample missing = the prompt was renamed/retired in a later
- // commit, e.g. pipeline-tv-script.md → pipeline-teleplay.md).
- const sampleContent = await readFile(samplePath, 'utf-8').catch((err) => {
- if (err.code !== 'ENOENT') throw err;
- return null;
- });
-
- if (sampleContent === null) {
- // Sample file no longer exists — the prompt was renamed/retired
- // upstream. The replacement (if any) is already in data/ via
- // setup-data.js. Treat as a soft delete: drop the obsolete file
- // when unmodified; warn when customized.
- if (existingMd5 === OLD_SHIPPED_MD5[filename]) {
- await unlink(dataPath);
- console.log(`🗑️ pipeline stage prompt ${filename} was renamed/retired upstream — removed unmodified copy from data/`);
- retired++;
- } else {
- console.warn(
- `⚠️ pipeline stage prompt ${filename} was renamed/retired upstream but your local copy has been customized.\n` +
- ` Check data.sample/prompts/stages/ for the replacement file and merge any custom edits manually.`,
- );
- skipped++;
- }
- continue;
- }
-
- if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {
- // Diverged from the old shipped version — user has customized this file.
- // Warn and skip to avoid clobbering their edits.
- console.warn(
- `⚠️ pipeline stage prompt ${filename} has been customized — skipping auto-update.\n` +
- ` To apply the length-profile variables manually, diff:\n` +
- ` data.sample/prompts/stages/${filename}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${filename}\n` +
- ` and merge the {{lengthTargets.*}} template variables.`,
- );
- skipped++;
- continue;
- }
-
- // File matches the old shipped version — safe to replace.
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated pipeline stage prompt: ${filename}`);
- updated++;
- }
-
- if (updated > 0 || retired > 0) {
- console.log(`📝 pipeline stage prompt migration: ${updated} updated, ${retired} retired, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
- } else if (skipped > 0) {
- console.log(`📝 pipeline stage prompt migration: all files either current or customized (${skipped} skipped)`);
- } else {
- console.log(`📝 pipeline stage prompt migration: all files already up to date`);
- }
-
- if (skipped > 0) {
- console.warn(
- `\n⚠️ ${skipped} prompt(s) could not be auto-updated because they were customized.\n` +
- ` The length profile picker UI will work, but those prompts won't use\n` +
- ` {{lengthTargets.*}} variables until you merge them manually.\n` +
- ` See data.sample/prompts/stages/ for the updated templates.`,
- );
- }
- },
-};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'pipeline stage prompt',
+ retireOnSampleMissing: true,
+ customizedHint: (filename) =>
+ ` To apply the length-profile variables manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and merge the {{lengthTargets.*}} template variables.`,
+ skipFooter: (count) =>
+ `⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` +
+ ` The length profile picker UI will work, but those prompts won't use\n` +
+ ` {{lengthTargets.*}} variables until you merge them manually.\n` +
+ ` See data.sample/prompts/stages/ for the updated templates.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/004-augment-idea-expansion-context.js b/scripts/migrations/004-augment-idea-expansion-context.js
index 16e2def394..576b4d333e 100644
--- a/scripts/migrations/004-augment-idea-expansion-context.js
+++ b/scripts/migrations/004-augment-idea-expansion-context.js
@@ -6,88 +6,31 @@
* issue's beats / synopsis — same shape a human editor has open while
* writing beats.
*
- * Strategy mirrors migration 003: replace the installed file only when its
- * hash still matches the previous shipped version (= the migration-003 NEW
- * hash). Customized files are skipped with a manual-merge warning.
+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { createHash } from 'crypto';
+import { makePromptReplaceMigration } from './_lib.js';
-const md5 = (str) => {
- const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
- return createHash('md5').update(normalized).digest('hex');
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-idea-expansion.md': ['41facefbc0c0549d456bef9111f95ab9'], // post-003
};
-// The version shipped after migration 003 — the only state this migration
-// is willing to auto-update from.
-const OLD_SHIPPED_MD5 = {
- 'pipeline-idea-expansion.md': '41facefbc0c0549d456bef9111f95ab9',
-};
-
-// The version shipped with this migration — used to detect "already applied"
-// on re-runs.
-const NEW_SHIPPED_MD5 = {
+export const NEW_SHIPPED_MD5 = {
'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4',
};
-export default {
- async up({ rootDir }) {
- 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(OLD_SHIPPED_MD5)) {
- 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(`📄 pipeline stage prompt ${filename}: not present in data/, will be created by setup-data.js`);
- continue;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_MD5[filename]) {
- alreadyCurrent++;
- continue;
- }
-
- if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {
- console.warn(
- `⚠️ pipeline stage prompt ${filename} has been customized — skipping auto-update.\n` +
- ` To pick up the new arc / volume / neighbor-issue context blocks, diff:\n` +
- ` data.sample/prompts/stages/${filename}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${filename}\n` +
- ` and merge the {{#arc}}, {{#volume}}, {{#priorIssue}}, {{#nextIssue}},\n` +
- ` {{#priorVolume}}, {{#arcRole}}, and {{#positionInVolume}} sections.`,
- );
- skipped++;
- continue;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated pipeline stage prompt: ${filename}`);
- updated++;
- }
-
- if (updated > 0) {
- console.log(`📝 idea-expansion context migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
- } else if (skipped > 0) {
- console.log(`📝 idea-expansion context migration: file customized (${skipped} skipped)`);
- } else {
- console.log(`📝 idea-expansion context migration: already up to date`);
- }
- },
-};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'idea-expansion context',
+ customizedHint: (filename) =>
+ ` To pick up the new arc / volume / neighbor-issue context blocks, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and merge the {{#arc}}, {{#volume}}, {{#priorIssue}}, {{#nextIssue}},\n` +
+ ` {{#priorVolume}}, {{#arcRole}}, and {{#positionInVolume}} sections.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.js
index c6ba7428dd..02b5529db8 100644
--- a/scripts/migrations/005-shape-aware-arc-prompts.js
+++ b/scripts/migrations/005-shape-aware-arc-prompts.js
@@ -10,34 +10,25 @@
* pipeline-volume-verify — per-volume placement + volume-internal adherence check
* pipeline-arc-resolve — preserve picked shape during auto-resolve
*
- * Strategy mirrors migration 003: replace the installed file only when its
- * hash still matches the previous shipped version. Customized files are
- * skipped with a manual-merge warning.
- *
* `pipeline-arc-resolve.md` was never previously in data.sample/ (it shipped
- * in `27ef3c27` but only landed in `data/`). The OLD hash here is the
- * stable content of that pre-sample-installed copy; users who never received
- * it will get the new file copied in by setup-data.js on the next run.
+ * in `27ef3c27` but only landed in `data/`). `createIfMissing: true` keeps
+ * the migration self-contained for that case; for the other files the branch
+ * never fires because they already shipped in data.sample/.
+ *
+ * Strategy: 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';
-const OLD_SHIPPED_MD5 = {
- 'pipeline-arc-overview.md': '6a3ecab43d1f46b7ef9aab6c69ea0326',
- 'pipeline-arc-verify.md': '52e31abc93e3105176236fcaa5d1575a',
- 'pipeline-volume-verify.md': 'c6ea28e972ad6e229bafb2d602b4dda3',
- 'pipeline-season-episodes.md': 'c4928e2a5f833358116b29d2d669888d',
- 'pipeline-arc-resolve.md': '87bc5c01f1a8a97b681727a38b05edc6',
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-arc-overview.md': ['6a3ecab43d1f46b7ef9aab6c69ea0326'],
+ 'pipeline-arc-verify.md': ['52e31abc93e3105176236fcaa5d1575a'],
+ 'pipeline-volume-verify.md': ['c6ea28e972ad6e229bafb2d602b4dda3'],
+ 'pipeline-season-episodes.md': ['c4928e2a5f833358116b29d2d669888d'],
+ 'pipeline-arc-resolve.md': ['87bc5c01f1a8a97b681727a38b05edc6'],
};
-const NEW_SHIPPED_MD5 = {
+export const NEW_SHIPPED_MD5 = {
'pipeline-arc-overview.md': 'd34d72b8e49ba303d38607845dd87f1c',
'pipeline-arc-verify.md': 'ff56d8387162017e08d5d0491060ddd6',
'pipeline-volume-verify.md': '03f3c874cb80e1c98abcf03168fa7a92',
@@ -45,78 +36,23 @@ const NEW_SHIPPED_MD5 = {
'pipeline-arc-resolve.md': 'a8677bbe1eb38f871fb152a5b0fec7c6',
};
-export default {
- async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
-
- let updated = 0;
- let alreadyCurrent = 0;
- let skipped = 0;
- let created = 0;
-
- for (const filename of Object.keys(OLD_SHIPPED_MD5)) {
- 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) {
- // File missing from data/ — copy from sample so the shape-aware
- // prompt is in place on next server boot. setup-data.js would do this
- // too on its next pass, but running it here keeps the migration
- // self-contained for the case where it executes before setup-data.
- const sampleContent = await readFile(samplePath, 'utf-8').catch(() => null);
- if (sampleContent != null) {
- await writeFile(dataPath, sampleContent);
- console.log(`📄 created shape-aware prompt: ${filename}`);
- created++;
- }
- continue;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_MD5[filename]) {
- alreadyCurrent++;
- continue;
- }
-
- if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {
- console.warn(
- `⚠️ pipeline stage prompt ${filename} has been customized — skipping shape-aware auto-update.\n` +
- ` To apply the Vonnegut shape variables manually, diff:\n` +
- ` data.sample/prompts/stages/${filename}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${filename}\n` +
- ` and merge the {{{shapeGuidance}}} block (and {{shapePosition}} / {{volumeShapePosition}} where applicable).`,
- );
- skipped++;
- continue;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated pipeline stage prompt: ${filename}`);
- updated++;
- }
-
- const total = updated + alreadyCurrent + skipped + created;
- console.log(
- `📝 shape-aware prompt migration: ${updated} updated, ${created} created, ` +
- `${alreadyCurrent} already current, ${skipped} skipped (customized) — ${total} files checked`,
- );
-
- if (skipped > 0) {
- console.warn(
- `\n⚠️ ${skipped} prompt(s) could not be auto-updated because they were customized.\n` +
- ` Shape-aware features will work for un-customized prompts; the customized\n` +
- ` ones will continue using their existing templates (without the\n` +
- ` {{{shapeGuidance}}} block) until you merge manually.`,
- );
- }
- },
-};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'shape-aware prompt',
+ createIfMissing: true,
+ customizedHint: (filename) =>
+ ` To apply the Vonnegut shape variables manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and merge the {{{shapeGuidance}}} block (and {{shapePosition}} / {{volumeShapePosition}} where applicable).`,
+ skipFooter: (count) =>
+ `⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` +
+ ` Shape-aware features will work for un-customized prompts; the customized\n` +
+ ` ones will continue using their existing templates (without the\n` +
+ ` {{{shapeGuidance}}} block) until you merge manually.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/006-extract-scenes-shots.js b/scripts/migrations/006-extract-scenes-shots.js
index 1b4304717f..961e4feefd 100644
--- a/scripts/migrations/006-extract-scenes-shots.js
+++ b/scripts/migrations/006-extract-scenes-shots.js
@@ -4,91 +4,32 @@
* clip grouping with continuity chaining. Existing installs need the updated
* prompt to actually emit shots from the LLM.
*
- * Strategy mirrors migration 003: replace the file iff the on-disk hash still
- * matches the version shipped before this feature. Customized files are
- * skipped with a warning so manual edits aren't clobbered.
- *
- * Idempotent — a re-run that finds the new shipped hash on disk is a no-op.
+ * Strategy: 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';
-const OLD_SHIPPED_MD5 = {
- 'pipeline-extract-scenes.md': '59fa5ee305ce53d91eb15224d8b546d3',
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3'],
};
-const NEW_SHIPPED_MD5 = {
+export const NEW_SHIPPED_MD5 = {
'pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba',
};
-export default {
- async up({ rootDir }) {
- 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(OLD_SHIPPED_MD5)) {
- 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(`📄 pipeline stage prompt ${filename}: not present in data/, will be created by setup-data.js`);
- continue;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_MD5[filename]) {
- alreadyCurrent++;
- continue;
- }
-
- if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {
- console.warn(
- `⚠️ pipeline stage prompt ${filename} has been customized — skipping auto-update.\n` +
- ` Manually merge the shots[] additions from:\n` +
- ` data.sample/prompts/stages/${filename}\n` +
- ` into your current:\n` +
- ` data/prompts/stages/${filename}`,
- );
- skipped++;
- continue;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated pipeline stage prompt: ${filename}`);
- updated++;
- }
-
- if (updated > 0) {
- console.log(`📝 extract-scenes shots migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
- } else if (skipped > 0) {
- console.log(`📝 extract-scenes shots migration: ${skipped} customized (skipped)`);
- } else {
- console.log('📝 extract-scenes shots migration: already up to date');
- }
-
- if (skipped > 0) {
- console.warn(
- `\n⚠️ ${skipped} prompt(s) could not be auto-updated. Storyboard shot extraction\n` +
- ` will not produce shots[] until the prompt is updated manually.\n`,
- );
- }
- },
-};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'extract-scenes shots',
+ customizedHint: (filename) =>
+ ` Manually merge the shots[] additions from:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` into your current:\n` +
+ ` data/prompts/stages/${filename}`,
+ skipFooter: (count) =>
+ `⚠️ ${count} prompt(s) could not be auto-updated. Storyboard shot extraction\n` +
+ ` will not produce shots[] until the prompt is updated manually.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/006-extract-scenes-shots.test.js b/scripts/migrations/006-extract-scenes-shots.test.js
new file mode 100644
index 0000000000..a7d72a60e8
--- /dev/null
+++ b/scripts/migrations/006-extract-scenes-shots.test.js
@@ -0,0 +1,20 @@
+/**
+ * Test for migration 006 — pipeline-extract-scenes.md gains per-scene shots[].
+ *
+ * Picked up via the vitest include glob in server/vitest.config.js
+ * (`../scripts/migrations/**\/*.test.js`).
+ */
+import { describe } from 'vitest';
+
+import { runPromptMigrationTests } from './_testHelpers.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './006-extract-scenes-shots.js';
+
+describe('migration 006 — extract-scenes shots[]', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-006-',
+ });
+});
diff --git a/scripts/migrations/010-simplify-cos-agent-briefing.js b/scripts/migrations/010-simplify-cos-agent-briefing.js
index 5dc726e272..3ef58a2f9b 100644
--- a/scripts/migrations/010-simplify-cos-agent-briefing.js
+++ b/scripts/migrations/010-simplify-cos-agent-briefing.js
@@ -6,74 +6,36 @@
* serves API providers now (TUI and CLI agents get a runtime-built light
* prompt from buildLightContextPrompt), so this cleanup is API-facing only.
*
- * Strategy — "unmodified-only" update: if the installed file matches any
- * historical shipped hash, replace it with the current data.sample copy.
- * Diverged (customized) files are left alone with a warning.
- *
- * Idempotent — re-runs that find the current sample hash on disk are no-ops.
+ * Strategy: 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';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'cos-agent-briefing.md': [
+ '699d053875472df455258724a0162bd5', // e827e066 — abort standardization on dirty worktree
+ '181b26838e526427173e4dccfc884d01', // d086bdfc — remove git stash + enforce /do:push
+ '3e1ca7f7b14b799f89a193c568003624', // f4589187 — don't update PortOS changelog
+ 'af73fd50d6f29d561772474c12346e53', // 3b4ced6a — task-type skill templates
+ '9bcd3a0167dd4aed7cfff7f404494dfb', // cf41dd61 — context compaction
+ 'd761133753da290a0c02eca1c87709e4', // 9b4c4ba6 — initial CoS landing
+ ],
};
-const FILENAME = 'cos-agent-briefing.md';
-
-// Every shipped version of cos-agent-briefing.md prior to this migration.
-// If the installed file matches any of these, the user hasn't customized it
-// and we can safely replace it with the current sample.
-const OLD_SHIPPED_HASHES = [
- '699d053875472df455258724a0162bd5', // e827e066 — abort standardization on dirty worktree
- '181b26838e526427173e4dccfc884d01', // d086bdfc — remove git stash + enforce /do:push
- '3e1ca7f7b14b799f89a193c568003624', // f4589187 — don't update PortOS changelog
- 'af73fd50d6f29d561772474c12346e53', // 3b4ced6a — task-type skill templates
- '9bcd3a0167dd4aed7cfff7f404494dfb', // cf41dd61 — context compaction
- 'd761133753da290a0c02eca1c87709e4', // 9b4c4ba6 — initial CoS landing
-];
-
-// Hash of the version this migration copies in (data.sample current).
-const NEW_SHIPPED_HASH = 'dccb392a43cbd3dac900fee12c31619a';
-
-export default {
- async up({ rootDir }) {
- const dataPath = join(rootDir, 'data', 'prompts', 'stages', FILENAME);
- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);
-
- const existing = await readFile(dataPath, 'utf-8').catch((err) => {
- if (err.code !== 'ENOENT') throw err;
- return null;
- });
-
- if (existing === null) {
- console.log(`📄 ${FILENAME}: not present in data/, will be created by setup-data.js`);
- return;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_HASH) {
- console.log(`📝 ${FILENAME}: already up to date`);
- return;
- }
-
- if (!OLD_SHIPPED_HASHES.includes(existingMd5)) {
- console.warn(
- `⚠️ ${FILENAME} has been customized — skipping auto-update.\n` +
- ` To drop the obsolete header and role-play preamble manually, diff:\n` +
- ` data.sample/prompts/stages/${FILENAME}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${FILENAME}`,
- );
- return;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated CoS agent prompt template: ${FILENAME}`);
- },
+export const NEW_SHIPPED_MD5 = {
+ 'cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a',
};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'cos-agent-briefing',
+ customizedHint: (filename) =>
+ ` To drop the obsolete header and role-play preamble manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/010-simplify-cos-agent-briefing.test.js b/scripts/migrations/010-simplify-cos-agent-briefing.test.js
new file mode 100644
index 0000000000..504ebad8c9
--- /dev/null
+++ b/scripts/migrations/010-simplify-cos-agent-briefing.test.js
@@ -0,0 +1,21 @@
+/**
+ * Test for migration 010 — cos-agent-briefing.md drops the obsolete header
+ * and role-play preamble.
+ *
+ * Picked up via the vitest include glob in server/vitest.config.js
+ * (`../scripts/migrations/**\/*.test.js`).
+ */
+import { describe } from 'vitest';
+
+import { runPromptMigrationTests } from './_testHelpers.js';
+import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './010-simplify-cos-agent-briefing.js';
+
+describe('migration 010 — cos-agent-briefing preamble cleanup', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ prefix: 'migration-010-',
+ });
+});
diff --git a/scripts/migrations/013-comic-script-back-cover.js b/scripts/migrations/013-comic-script-back-cover.js
index fa4ee4d506..0f36547e7b 100644
--- a/scripts/migrations/013-comic-script-back-cover.js
+++ b/scripts/migrations/013-comic-script-back-cover.js
@@ -8,69 +8,33 @@
* `stages.comicPages.backCover.script` slot reads via the extract-pages
* route.
*
- * Strategy: same "unmodified-only" auto-update pattern as migration 003.
- * If the live file's MD5 matches any of the historical shipped hashes
- * (pre-003 or post-003), we replace it with the current data.sample/.
- * Diverged (user-customized) files are skipped with a merge hint.
+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { createHash } from 'crypto';
+import { makePromptReplaceMigration } from './_lib.js';
-const md5 = (str) => {
- const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
- return createHash('md5').update(normalized).digest('hex');
+export const ACCEPTED_OLD_MD5 = {
+ 'pipeline-comic-script.md': [
+ '40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (original)
+ 'beab031951859ca13579cdb9c4dbe769', // post-003 (length-profile feature)
+ ],
};
-// Every historical shipped MD5 of pipeline-comic-script.md. A user at any
-// of these is unmodified and can be auto-bumped to the new template.
-const HISTORICAL_SHIPPED_MD5 = [
- '40e5fdc1a1e68a7419b7dad936366c1a', // pre-003 (original)
- 'beab031951859ca13579cdb9c4dbe769', // post-003 (length-profile feature)
-];
-
-// MD5 of the new data.sample/pipeline-comic-script.md (with Back cover section).
-const NEW_SHIPPED_MD5 = '1e0af305c27d0c80c4b482d2ebcb4a0d';
-
-const FILENAME = 'pipeline-comic-script.md';
-
-export default {
- async up({ rootDir }) {
- const dataPath = join(rootDir, 'data', 'prompts', 'stages', FILENAME);
- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);
-
- const existing = await readFile(dataPath, 'utf-8').catch((err) => {
- if (err.code !== 'ENOENT') throw err;
- return null;
- });
-
- if (existing === null) {
- console.log(`📄 ${FILENAME}: not present in data/, will be created by setup-data.js`);
- return;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_MD5) {
- console.log(`📝 ${FILENAME}: already at new version (Back cover section present)`);
- return;
- }
-
- if (!HISTORICAL_SHIPPED_MD5.includes(existingMd5)) {
- console.warn(
- `⚠️ ${FILENAME} has been customized — skipping auto-update.\n` +
- ` To add the Back cover concept section manually, diff:\n` +
- ` data.sample/prompts/stages/${FILENAME}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${FILENAME}\n` +
- ` and merge the new \`## Back cover concept\` block.`,
- );
- return;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated ${FILENAME} — added Back cover concept section`);
- },
+export const NEW_SHIPPED_MD5 = {
+ 'pipeline-comic-script.md': '1e0af305c27d0c80c4b482d2ebcb4a0d',
};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'comic-script back-cover',
+ customizedHint: (filename) =>
+ ` To add the Back cover concept section manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and merge the new \`## Back cover concept\` block.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.js
index e97e9c8a53..3acfbc1d92 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js
@@ -17,32 +17,24 @@
* character roster entirely. arcPlanner exposes `worldCanonText` to every
* arc context now, but a context field without a template reference is
* silently ignored — so every prompt that gets the field must render it.
- * See PLAN.md → Phase B + the "arcPlanner prompt context — include canon"
- * backlog item it folded in.
*
- * Strategy — unmodified-only update, mirrors migration 003:
- * - If the on-disk file matches the prior shipped MD5 (either the pre-005
- * hash or the currently-shipped hash), replace with the data.sample
- * version that includes {{worldCanonText}}.
- * - If diverged (user customized), warn and skip.
+ * Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.
*
- * Idempotent: a re-run on the new hash is a no-op.
+ * NOTE on NEW_SHIPPED_MD5 — later migrations that further evolve any of these
+ * files (e.g. migration 023 amended `pipeline-arc-resolve.md`) must do TWO
+ * things:
+ * 1. Bump the corresponding entry in `NEW_SHIPPED_MD5` here so fresh
+ * installs (whose `data/` was seeded from the latest sample) report
+ * `alreadyCurrent` instead of a misleading "customized" warning, and so
+ * the drift-catch test stays in lock-step with the live sample.
+ * 2. Append the OLD `NEW_SHIPPED_MD5` value (the hash this migration
+ * originally produced) to `ACCEPTED_OLD_MD5` above so a re-run after a
+ * `data/migrations.applied.json` reset still cleanly advances an
+ * install at the intermediate state.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { createHash } from 'crypto';
+import { makePromptReplaceMigration } from './_lib.js';
-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 (per-file array — most
-// recent shipped hash first, then older). Any match is treated as
-// "unmodified by user → safe to replace."
-// Exported so the test suite can import these tables and detect drift without
-// maintaining local copies that can silently fall out of sync.
export const ACCEPTED_OLD_MD5 = {
'pipeline-arc-overview.md': [
'd34d72b8e49ba303d38607845dd87f1c', // current (pre-Phase B) shipped
@@ -63,22 +55,6 @@ export const ACCEPTED_OLD_MD5 = {
],
};
-// 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
-// do TWO things:
-// 1. Bump the corresponding entry in `NEW_SHIPPED_MD5` here so that fresh
-// installs (whose `data/` was seeded from the latest sample) report
-// `alreadyCurrent` instead of a misleading "customized" warning, and
-// so the drift-catch test stays in lock-step with the live sample.
-// 2. Append the OLD `NEW_SHIPPED_MD5` value (the hash this migration
-// originally produced) to `ACCEPTED_OLD_MD5` above so a re-run after a
-// `data/migrations.applied.json` reset still cleanly advances an
-// install at the intermediate state. Without this, re-running 019
-// on a post-019 install would misclassify it as "customized."
-// 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', // post-019
'pipeline-arc-verify.md': '36aa70cdfc25d7549573a4d556e7702c', // post-019
@@ -86,80 +62,22 @@ export const NEW_SHIPPED_MD5 = {
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940', // post-019
};
-// 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(`📄 arc-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(
- `⚠️ arc-prompt ${filename} has been customized — skipping auto-update.\n` +
- ` To pick up {{worldCanonText}} manually, diff:\n` +
- ` data.sample/prompts/stages/${filename}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${filename}\n` +
- ` and add the new "World canon" block in the same position as in the sample template.`,
- );
- skipped++;
- continue;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated arc-prompt: ${filename}`);
- updated++;
- }
-
- return { updated, alreadyCurrent, skipped };
-}
-
-export default {
- async up({ rootDir }) {
- const { updated, alreadyCurrent, skipped } = await applyMigration({ rootDir });
-
- if (updated > 0) {
- console.log(`📝 arc-prompt canon-context migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
- } else if (skipped > 0) {
- console.log(`📝 arc-prompt canon-context migration: all files either current or customized (${skipped} skipped)`);
- } else {
- console.log(`📝 arc-prompt canon-context migration: all files already up to date`);
- }
-
- if (skipped > 0) {
- console.warn(
- `\n⚠️ ${skipped} arc/volume prompt(s) could not be auto-updated because they were customized.\n` +
- ` The {{worldCanonText}} block will not render character names in arc-overview/\n` +
- ` arc-verify/arc-resolve/volume-verify until the files are merged manually. See\n` +
- ` data.sample/prompts/stages/.`,
- );
- }
- },
-};
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'arc-prompt canon-context',
+ customizedHint: (filename) =>
+ ` To pick up {{worldCanonText}} manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and add the new "World canon" block in the same position as in the sample template.`,
+ skipFooter: (count) =>
+ `⚠️ ${count} arc/volume prompt(s) could not be auto-updated because they were customized.\n` +
+ ` The {{worldCanonText}} block will not render character names in arc-overview/\n` +
+ ` arc-verify/arc-resolve/volume-verify until the files are merged manually. See\n` +
+ ` data.sample/prompts/stages/.`,
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
index 9fe60dcb07..76e46af257 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
@@ -5,137 +5,17 @@
* 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 { describe } from 'vitest';
+import { runPromptMigrationTests } from './_testHelpers.js';
import migration, { applyMigration, ACCEPTED_OLD_MD5, NEW_SHIPPED_MD5 } from './019-arc-volume-prompts-canon-context.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 for a given prompt; used to seed
-// fixtures and to compute "current" file bodies for round-trip checks.
-// Use fileURLToPath rather than `new URL(...).pathname` so a checkout under
-// a path with spaces (or other URL-escapable chars) 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');
-
-// A synthetic body that hashes to none of the accepted-old hashes — used to
-// stand in for a user-customized prompt template.
-const customizedBody = (filename) => `# CUSTOMIZED ${filename}\n\nuser-modified content not matching any shipped hash\n`;
-
describe('migration 019 — arc/volume prompt canon context', () => {
- let rootDir;
- let stagesDir;
- let sampleDir;
-
- beforeEach(() => {
- rootDir = mkdtempSync(join(tmpdir(), 'migration-019-'));
- stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
- mkdirSync(stagesDir, { recursive: true });
- mkdirSync(sampleDir, { recursive: true });
- // Seed the sample dir with the actual updated content from the repo so
- // the migration has something to copy when it finds an old-hash match.
- 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 () => {
- // No file in stagesDir; migration should skip without error.
- 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 () => {
- // Seed data/ with the same content as the sample (already migrated).
- for (const filename of Object.keys(NEW_SHIPPED_MD5)) {
- writeFileSync(join(stagesDir, filename), sampleBody(filename));
- }
- const before = Object.fromEntries(
- Object.keys(NEW_SHIPPED_MD5).map((f) => [f, readFileSync(join(stagesDir, f), 'utf-8')]),
- );
- // Use applyMigration with the migration's real tables (imported, not local
- // copies) so drift in the migration's hash constants is caught here — if
- // NEW_SHIPPED_MD5 no longer matches data.sample, applyMigration reports
- // skipped > 0 instead of alreadyCurrent, and this assertion fails.
- const result = await applyMigration({ rootDir });
- expect(result).toMatchObject({
- updated: 0,
- alreadyCurrent: Object.keys(NEW_SHIPPED_MD5).length,
- skipped: 0,
- });
- for (const filename of Object.keys(NEW_SHIPPED_MD5)) {
- const after = readFileSync(join(stagesDir, filename), 'utf-8');
- expect(after).toBe(before[filename]); // unchanged
- }
- });
-
- it('NEW_SHIPPED_MD5 matches the live data.sample bodies (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 — the idempotency
- // test below would still pass (it checks "stays unchanged"), masking
- // the regression. This assertion fails loudly at release time.
- for (const filename of Object.keys(NEW_SHIPPED_MD5)) {
- const liveHash = md5(sampleBody(filename));
- expect(liveHash).toBe(NEW_SHIPPED_MD5[filename]);
- }
- });
-
- it('upgrades when on-disk hash matches an accepted-old entry (synthetic fixture)', async () => {
- // Plants a fixture body, registers its MD5 as the migration's "accepted
- // old" hash via the pure applyMigration helper, then asserts the file
- // gets rewritten to the data.sample version. Exercises the OLD→NEW
- // upgrade branch without depending on git history (shallow clones +
- // archive downloads work).
- 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', () => {
- // Belt-and-suspenders: catch a future hash-table edit that forgets a file.
- 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-019-',
});
});
diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.js
index f1a76bd1f2..604f529b5b 100644
--- a/scripts/migrations/_lib.js
+++ b/scripts/migrations/_lib.js
@@ -1,16 +1,15 @@
/**
* 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]`.
+ * Every prompt-replace migration from 003 onward uses
+ * `makePromptReplaceMigration` to collapse onto ~50 lines (hash table + label
+ * + customized-skip hint).
*
* 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 { readFile, writeFile, unlink } from 'fs/promises';
import { join } from 'path';
import { createHash } from 'crypto';
@@ -26,7 +25,21 @@ export const md5 = (str) => {
/**
* 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.
+ * hash.
+ *
+ * Per-migration opt-ins (both default `false`):
+ *
+ * - `createIfMissing` — when the data-side file is absent, copy the sample
+ * file in. Used by migration 005, whose `pipeline-arc-resolve.md` may not
+ * have shipped in `data.sample/` yet at the time it was authored.
+ *
+ * - `retireOnSampleMissing` — when the sample-side file is absent (the prompt
+ * was renamed or retired by a later commit), treat it as a soft delete:
+ * unlink the data-side file when it still matches an accepted-old hash,
+ * and warn (counting as `skipped`) when it's been customized. Without this
+ * flag, a missing sample raises an ENOENT at read time. Used by migration
+ * 003 to handle the `pipeline-tv-script.md` → `pipeline-teleplay.md`
+ * rename.
*/
export async function applyPromptReplaceMigration({
rootDir,
@@ -34,6 +47,8 @@ export async function applyPromptReplaceMigration({
current,
label,
customizedHint,
+ createIfMissing = false,
+ retireOnSampleMissing = false,
}) {
const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
@@ -41,6 +56,8 @@ export async function applyPromptReplaceMigration({
let updated = 0;
let alreadyCurrent = 0;
let skipped = 0;
+ let created = 0;
+ let retired = 0;
for (const filename of Object.keys(accepted)) {
const dataPath = join(stagesDir, filename);
@@ -52,6 +69,15 @@ export async function applyPromptReplaceMigration({
});
if (existing === null) {
+ if (createIfMissing) {
+ const sampleContent = await readFile(samplePath, 'utf-8').catch(() => null);
+ if (sampleContent != null) {
+ await writeFile(dataPath, sampleContent);
+ console.log(`📄 created ${label}: ${filename}`);
+ created++;
+ continue;
+ }
+ }
console.log(`📄 ${label} ${filename}: not present in data/, will be created by setup-data.js`);
continue;
}
@@ -64,7 +90,34 @@ export async function applyPromptReplaceMigration({
}
const acceptedOld = accepted[filename];
- if (!acceptedOld.includes(existingMd5)) {
+ const matchesAcceptedOld = acceptedOld.includes(existingMd5);
+
+ if (retireOnSampleMissing) {
+ // Peek at the sample before the upgrade branch: a missing sample means
+ // the prompt was renamed or retired upstream, in which case the on-disk
+ // file is obsolete and should be removed (when unmodified) or flagged
+ // (when customized) rather than read-then-crash.
+ const sampleExists = await readFile(samplePath, 'utf-8').then(() => true, (err) => {
+ if (err.code === 'ENOENT') return false;
+ throw err;
+ });
+ if (!sampleExists) {
+ if (matchesAcceptedOld) {
+ await unlink(dataPath);
+ console.log(`🗑️ ${label} ${filename} was renamed/retired upstream — removed unmodified copy from data/`);
+ retired++;
+ } else {
+ console.warn(
+ `⚠️ ${label} ${filename} was renamed/retired upstream but your local copy has been customized.\n` +
+ ` Check data.sample/prompts/stages/ for the replacement file and merge any custom edits manually.`,
+ );
+ skipped++;
+ }
+ continue;
+ }
+ }
+
+ if (!matchesAcceptedOld) {
console.warn(
`⚠️ ${label} ${filename} has been customized — skipping auto-update.\n` +
customizedHint(filename),
@@ -79,7 +132,7 @@ export async function applyPromptReplaceMigration({
updated++;
}
- return { updated, alreadyCurrent, skipped };
+ return { updated, alreadyCurrent, skipped, created, retired };
}
/**
@@ -93,6 +146,8 @@ export function makePromptReplaceMigration({
label,
customizedHint,
skipFooter,
+ createIfMissing = false,
+ retireOnSampleMissing = false,
}) {
const applyMigration = (opts = {}) =>
applyPromptReplaceMigration({
@@ -100,14 +155,16 @@ export function makePromptReplaceMigration({
current,
label,
customizedHint,
+ createIfMissing,
+ retireOnSampleMissing,
...opts,
});
const up = async ({ rootDir }) => {
- const { updated, alreadyCurrent, skipped } = await applyMigration({ rootDir });
+ const { updated, alreadyCurrent, skipped, created, retired } = await applyMigration({ rootDir });
- if (updated > 0) {
- console.log(`📝 ${label} migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
+ if (updated > 0 || created > 0 || retired > 0) {
+ console.log(`📝 ${label} migration: ${updated} updated, ${created} created, ${retired} retired, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
} else if (skipped > 0) {
console.log(`📝 ${label} migration: all files either current or customized (${skipped} skipped)`);
} else {