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: collapse multi-stage seed migrations onto makeSeedMigrations (#1891)

[._.]/ Adam Eivy76f5258fdbfc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fe77a529ca..4a2681ab14 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -45,6 +45,7 @@
- **[issue-1836] Moved socket-handler orchestration into services** — the `standardize:start` and `app:deploy` Socket.IO handlers (`server/services/socket.js`) implemented their multi-step flows inline in the socket layer, where they couldn't be unit-tested or reused from an HTTP route. The PM2 standardization flow (analyze → git backup → apply) is now `pm2Standardizer.runStandardizeFlow()` and the deploy flow (resolve app → check deploy script → run) is now `appDeployer.runDeployFlow()`; each takes progress callbacks and returns a terminal outcome, so the socket handler is a thin adapter. Both are covered by new unit tests. Behavior-preserving. (#1836)
- **Extracted a shared helper for the copy-paste stage-seed migrations** — 44 first-shipment "seed a new pipeline stage" migrations under `scripts/migrations/` (e.g. `130-editorial-character-consistency-stage.js`) were near-identical: only the stage key differed while ~65 lines of read-reference → no-clobber-copy → merge-stage-config were verbatim copies, each with its own copy-paste test. They now collapse to a 3-line `export default makeSeedMigration(stageKey)` call from a new `scripts/migrations/_seedStageHelpers.js` (companion to the existing `_lib.js`/`_testHelpers.js`; the runner skips `_`-prefixed files). The helper reproduces the migrations' on-disk effects exactly — fresh-seed, idempotent no-clobber of a customized `.md`/config, and missing-reference no-throw; `filename` defaults to `${stageKey}.md` (the universal convention, overridable for a divergent template), and no `down()` is emitted because the runner (`run-migrations.js`) only ever calls `up()` and tracks applied migrations by filename. Boot-log copy is incidental and now uniformly keyed on `stageKey`. Net −2,500 lines; all 757 `scripts/` tests pass unchanged, and the new `_seedStageHelpers.test.js` covers the helper directly. (#1838)
+- **[issue-1891] Extended the stage-seed helper to the multi-stage migrations** — #1838 collapsed the 44 single-stage seed migrations onto `makeSeedMigration`, but left the four genuinely multi-stage ones (`091`/`094`/`095`/`107`) as hand-rolled `for (const stageKey of STAGES)` loops — ~70 near-identical lines apiece. `scripts/migrations/_seedStageHelpers.js` now exports `makeSeedMigrations(stageSpecs)` (array of bare `stageKey` strings or `{ stageKey, filename }`) that runs the same copy-if-missing + merge-if-absent body per stage and writes the installed `stage-config.json` once with an `N added` summary; `makeSeedMigration` is now a one-stage wrapper over it. All four migrations collapse to a 3-line call — including `095`, whose per-stage `returnsJson` flag lives only in the shipped stage-config sample and is copied verbatim (the migration never inspects it), so the shared helper is fully equivalent. On-disk results are byte-identical to the prior loops (templates copied only when missing, entries merged only when absent, single pretty-printed write); the boot-log copy is incidental. `_seedStageHelpers.test.js` gains direct coverage of the array form and all `scripts/` tests pass unchanged. (#1891)
- **Extracted a shared `withAbortTimeout` helper for the duplicated peer-fetch timeout boilerplate** — the `new AbortController()` + `setTimeout(abort)` + `finally{clearTimeout}` triple was hand-rolled at 12 federation/probe call sites (4 in `instances.js`, plus `peerSocketRelay`, `peerSync`, `peerCosSync`×2, `peerSyncAssets`, `peerSyncPush`, `peerMediaLibrarySync`, `sidecarSync`). It can't reuse `fetchWithTimeout` because `peerFetch` needs the Tailnet-insecure HTTPS agent. The new `server/lib/abortTimeout.js` `withAbortTimeout(timeoutMs, fn)` runs `fn(signal)` under a timed `AbortController` and always clears the timer on settle — covering both the headers-only idiom (peer-sync pulls/pushes, body separately size-capped) and the whole-operation idiom (`probePeer` shares one signal across three parallel fetches and their body reads). The `peerFetch` call stays in each module (so existing test mocks/assertions are unchanged); behavior-preserving. (#1839)
- **Replaced aiToolkit runner monkey-patching with declared extension points** — `server/index.js` previously reached into the toolkit runner's private surface, overwriting `executeCliRun`/`executeTuiRun` and re-wrapping `stopRun`/`isRunActive`/`deleteRun` to consult an ad-hoc `_portosActiveRuns` map, plus inlining a 34-line update-marker IIFE in bootstrap. The toolkit runner (`server/lib/aiToolkit/runner.js`) now exposes `setCliRunner()`/`setTuiRunner()` and an external-run registry (`registerExternalRun`/`unregisterExternalRun`/`hasExternalRun`) that its own `stopRun`/`isRunActive`/`deleteRun` consult first — so the host registers its CLI/TUI runners through a documented contract instead of mutating private props, and adding a new lifecycle method no longer requires a matching monkey-patch. `server/services/runner.js` tracks its child processes via the registry, and the update-marker read/validate/record/cleanup lifecycle moved into a unit-tested `processUpdateMarker()` in `server/services/updateChecker.js`. Behavior-preserving; the aiToolkit override contract (`server/lib/aiToolkit/CLAUDE.md`) is updated to match. (#1834)
- **Decomposed two remaining large files: `server/routes/meatspace.js` + `server/services/videoGen/local.js`** — the 1,069-line `meatspace.js` router (14 health sub-domains, each backed by its own service import) is split one concern per file (`meatspaceCoreRoutes.js` overview/config/birth-date/death-clock/LEV, `meatspaceAlcoholRoutes.js`, `meatspaceNicotineRoutes.js`, `meatspaceHealthRoutes.js` blood/body/BP/workouts/epigenetic/eyes, `meatspacePostRoutes.js` POST drills + training + memory builder, `meatspaceCalendarRoutes.js` life calendar/activities/events, `meatspaceExportRoutes.js` MortalLoom export), assembled by a thin `meatspace.js` barrel that mounts each under `/api/meatspace` — the same pattern `routes/cos.js`/`routes/brain.js` use; the split is wiring-only (the 70-route surface is byte-identical, verified). The 1,805-line `videoGen/local.js` had its BYOV runtime management (venv/helper-script path constants, `BYOV_RUNTIME_INFO`, install/ready/fingerprint probes) extracted to `videoGen/runtimes.js` and its render-history I/O (`loadHistory`/`saveHistory`) to `videoGen/history.js`; `local.js` keeps generation + post-processing and re-exports the extracted surface so every existing deep import (`from '../videoGen/local.js'`) keeps resolving unchanged (all 30 prior exports preserved, verified). (#1833)
diff --git a/scripts/migrations/091-seed-image-prompt-stages.js b/scripts/migrations/091-seed-image-prompt-stages.js
index 27014b669a..38c04a8699 100644
--- a/scripts/migrations/091-seed-image-prompt-stages.js
+++ b/scripts/migrations/091-seed-image-prompt-stages.js
@@ -23,79 +23,9 @@
* `buildPromptDriftTables` sweep can auto-update other installs.
*/
-import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
-import { dirname, join } from 'path';
+import { makeSeedMigrations } from './_seedStageHelpers.js';
-const STAGES = [
- { filename: 'pipeline-comic-panel-image-prompt.md', stageKey: 'pipeline-comic-panel-image-prompt' },
- { filename: 'pipeline-storyboard-image-prompt.md', stageKey: 'pipeline-storyboard-image-prompt' },
-];
-
-export default {
- async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- await mkdir(stagesDir, { recursive: true });
-
- // 1) Seed each `.md` template when missing.
- for (const { filename } of STAGES) {
- const dataPath = join(stagesDir, filename);
- const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
-
- const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
- if (exists) {
- console.log(`📝 image-prompt stages: ${filename} already present`);
- continue;
- }
- const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
- if (!sampleExists) {
- console.warn(`⚠️ image-prompt stages: sample missing for ${filename} — skipping copy`);
- continue;
- }
- try {
- await copyFile(samplePath, dataPath);
- console.log(`✅ seeded ${filename}`);
- } catch (err) {
- console.warn(`⚠️ image-prompt stages: copy failed for ${filename}: ${err.message}`);
- }
- }
-
- // 2) Merge each stage-config entry when absent.
- const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
- const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
- const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
- if (!sampleConfigExists) {
- console.warn('⚠️ image-prompt stages: data.reference stage-config.json missing — cannot resolve entries; skipping config write');
- return;
- }
- try {
- const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
- const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
- const installed = installedExists
- ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
- : { stages: {} };
- installed.stages = installed.stages || {};
-
- let added = 0;
- for (const { stageKey } of STAGES) {
- if (installed.stages[stageKey]) {
- console.log(`📝 image-prompt stage-config: ${stageKey} already present`);
- continue;
- }
- if (!sample?.stages?.[stageKey]) {
- console.warn(`⚠️ image-prompt stages: sample stage-config missing ${stageKey} — skipping`);
- continue;
- }
- installed.stages[stageKey] = sample.stages[stageKey];
- added += 1;
- }
-
- if (added === 0) return;
- await mkdir(dirname(installedConfigPath), { recursive: true });
- await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
- const action = installedExists ? 'merged' : 'created';
- console.log(`📝 image-prompt stage-config (${action}): ${added} added`);
- } catch (err) {
- console.warn(`⚠️ image-prompt stages: stage-config merge failed: ${err.message}`);
- }
- },
-};
+export default makeSeedMigrations([
+ 'pipeline-comic-panel-image-prompt',
+ 'pipeline-storyboard-image-prompt',
+]);
diff --git a/scripts/migrations/094-object-attachment-check-stages.js b/scripts/migrations/094-object-attachment-check-stages.js
index 6377ad47e1..9108c53634 100644
--- a/scripts/migrations/094-object-attachment-check-stages.js
+++ b/scripts/migrations/094-object-attachment-check-stages.js
@@ -12,83 +12,9 @@
* the first time they run.
*/
-import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
-import { dirname, join } from 'path';
+import { makeSeedMigrations } from './_seedStageHelpers.js';
-const STAGES = [
+export default makeSeedMigrations([
'pipeline-editorial-object-motivation',
'pipeline-editorial-object-backstory',
-];
-
-export default {
- async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- await mkdir(stagesDir, { recursive: true });
-
- // 1) Copy each prompt template if it isn't already present.
- for (const stageKey of STAGES) {
- const filename = `${stageKey}.md`;
- const dataPath = join(stagesDir, filename);
- const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
-
- const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
- if (exists) {
- console.log(`📝 ${stageKey} prompt: already present`);
- continue;
- }
- const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
- if (!sampleExists) {
- console.warn(`⚠️ ${stageKey}: sample missing for ${filename} — skipping copy`);
- continue;
- }
- try {
- await copyFile(samplePath, dataPath);
- console.log(`✅ seeded ${filename}`);
- } catch (err) {
- console.warn(`⚠️ ${stageKey}: copy failed for ${filename}: ${err.message}`);
- }
- }
-
- // 2) Merge each stage-config entry (skip any already present).
- const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
- const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
- const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
- if (!sampleConfigExists) {
- console.warn('⚠️ 094-object-attachment-check-stages: data.reference stage-config.json missing — cannot resolve entries; skipping config write');
- return;
- }
- try {
- const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
- const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
- const installed = installedExists
- ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
- : { stages: {} };
- installed.stages = installed.stages || {};
-
- let added = 0;
- for (const stageKey of STAGES) {
- if (installed.stages[stageKey]) {
- console.log(`📝 ${stageKey} stage-config: already present`);
- continue;
- }
- if (!sample?.stages?.[stageKey]) {
- console.warn(`⚠️ 094-object-attachment-check-stages: sample stage-config missing ${stageKey} — skipping`);
- continue;
- }
- installed.stages[stageKey] = sample.stages[stageKey];
- added += 1;
- }
-
- if (added === 0) {
- console.log('📝 094-object-attachment-check-stages: no stage-config entries to add');
- return;
- }
- await mkdir(dirname(installedConfigPath), { recursive: true });
- await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
- const action = installedExists ? 'merged' : 'created';
- console.log(`📝 094-object-attachment-check-stages stage-config (${action}): ${added} added`);
- } catch (err) {
- console.warn(`⚠️ 094-object-attachment-check-stages: stage-config merge failed: ${err.message}`);
- }
- },
-};
+]);
diff --git a/scripts/migrations/095-pov-rewrite-stages.js b/scripts/migrations/095-pov-rewrite-stages.js
index 2dc78591c4..78699b6c7d 100644
--- a/scripts/migrations/095-pov-rewrite-stages.js
+++ b/scripts/migrations/095-pov-rewrite-stages.js
@@ -10,81 +10,15 @@
* `buildPrompt('pipeline-pov-rewrite')` would throw "Stage not found" the first
* time a user runs a perspective rewrite.
*
- * Two stages ship together (rewrite + analysis), so this loops over both rather
- * than the single-stage shape of 093.
+ * Two stages ship together (rewrite + analysis). Each stage-config entry — and
+ * its per-stage `returnsJson` flag — is copied verbatim from the shipped sample
+ * by `makeSeedMigrations`; the migration never inspects or branches on it, so the
+ * shared multi-stage helper is fully equivalent to the prior hand-rolled loop.
*/
-import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
-import { dirname, join } from 'path';
+import { makeSeedMigrations } from './_seedStageHelpers.js';
-const STAGE_KEYS = ['pipeline-pov-rewrite', 'pipeline-pov-analysis'];
-
-export default {
- async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- await mkdir(stagesDir, { recursive: true });
-
- // 1. Copy each prompt template that isn't already present.
- for (const key of STAGE_KEYS) {
- const filename = `${key}.md`;
- const dataPath = join(stagesDir, filename);
- const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
-
- const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
- if (exists) {
- console.log(`📝 ${key} prompt: already present`);
- continue;
- }
- const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
- if (!sampleExists) {
- console.warn(`⚠️ pov-rewrite: sample missing for ${filename} — skipping copy`);
- continue;
- }
- try {
- await copyFile(samplePath, dataPath);
- console.log(`✅ seeded ${filename}`);
- } catch (err) {
- console.warn(`⚠️ pov-rewrite: copy failed for ${filename}: ${err.message}`);
- }
- }
-
- // 2. Merge the stage-config entries.
- const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
- const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
- const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
- if (!sampleConfigExists) {
- console.warn('⚠️ pov-rewrite: data.reference stage-config.json missing — cannot resolve entries; skipping config write');
- return;
- }
- try {
- const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
- const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
- const installed = installedExists
- ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
- : { stages: {} };
- installed.stages = installed.stages || {};
-
- let added = 0;
- for (const key of STAGE_KEYS) {
- if (installed.stages[key]) {
- console.log(`📝 ${key} stage-config: already present`);
- continue;
- }
- if (!sample?.stages?.[key]) {
- console.warn(`⚠️ pov-rewrite: sample stage-config missing ${key} — skipping`);
- continue;
- }
- installed.stages[key] = sample.stages[key];
- added += 1;
- }
- if (added > 0) {
- await mkdir(dirname(installedConfigPath), { recursive: true });
- await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
- const action = installedExists ? 'merged' : 'created';
- console.log(`📝 pov-rewrite stage-config (${action}): ${added} added`);
- }
- } catch (err) {
- console.warn(`⚠️ pov-rewrite: stage-config merge failed: ${err.message}`);
- }
- },
-};
+export default makeSeedMigrations([
+ 'pipeline-pov-rewrite',
+ 'pipeline-pov-analysis',
+]);
diff --git a/scripts/migrations/107-editorial-sensory-grounding-stages.js b/scripts/migrations/107-editorial-sensory-grounding-stages.js
index 8a625c40d6..d4a14b1ad6 100644
--- a/scripts/migrations/107-editorial-sensory-grounding-stages.js
+++ b/scripts/migrations/107-editorial-sensory-grounding-stages.js
@@ -11,83 +11,9 @@
* would throw "Stage not found" the first time they run.
*/
-import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
-import { dirname, join } from 'path';
+import { makeSeedMigrations } from './_seedStageHelpers.js';
-const STAGES = [
+export default makeSeedMigrations([
'pipeline-editorial-sensory-balance',
'pipeline-editorial-white-room',
-];
-
-export default {
- async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- await mkdir(stagesDir, { recursive: true });
-
- // 1) Copy each prompt template if it isn't already present.
- for (const stageKey of STAGES) {
- const filename = `${stageKey}.md`;
- const dataPath = join(stagesDir, filename);
- const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
-
- const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
- if (exists) {
- console.log(`📝 ${stageKey} prompt: already present`);
- continue;
- }
- const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
- if (!sampleExists) {
- console.warn(`⚠️ ${stageKey}: sample missing for ${filename} — skipping copy`);
- continue;
- }
- try {
- await copyFile(samplePath, dataPath);
- console.log(`✅ seeded ${filename}`);
- } catch (err) {
- console.warn(`⚠️ ${stageKey}: copy failed for ${filename}: ${err.message}`);
- }
- }
-
- // 2) Merge each stage-config entry (skip any already present).
- const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
- const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
- const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
- if (!sampleConfigExists) {
- console.warn('⚠️ 107-editorial-sensory-grounding-stages: data.reference stage-config.json missing — cannot resolve entries; skipping config write');
- return;
- }
- try {
- const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
- const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
- const installed = installedExists
- ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
- : { stages: {} };
- installed.stages = installed.stages || {};
-
- let added = 0;
- for (const stageKey of STAGES) {
- if (installed.stages[stageKey]) {
- console.log(`📝 ${stageKey} stage-config: already present`);
- continue;
- }
- if (!sample?.stages?.[stageKey]) {
- console.warn(`⚠️ 107-editorial-sensory-grounding-stages: sample stage-config missing ${stageKey} — skipping`);
- continue;
- }
- installed.stages[stageKey] = sample.stages[stageKey];
- added += 1;
- }
-
- if (added === 0) {
- console.log('📝 107-editorial-sensory-grounding-stages: no stage-config entries to add');
- return;
- }
- await mkdir(dirname(installedConfigPath), { recursive: true });
- await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
- const action = installedExists ? 'merged' : 'created';
- console.log(`📝 107-editorial-sensory-grounding-stages stage-config (${action}): ${added} added`);
- } catch (err) {
- console.warn(`⚠️ 107-editorial-sensory-grounding-stages: stage-config merge failed: ${err.message}`);
- }
- },
-};
+]);
diff --git a/scripts/migrations/_seedStageHelpers.js b/scripts/migrations/_seedStageHelpers.js
index eb8c2a47d2..79b9bf08e1 100644
--- a/scripts/migrations/_seedStageHelpers.js
+++ b/scripts/migrations/_seedStageHelpers.js
@@ -23,6 +23,17 @@
* across every seed migration); pass it only for the rare template whose basename
* diverges from its stage key.
*
+ * `makeSeedMigrations(stageSpecs)` is the multi-stage form: it runs the same
+ * copy-if-missing + merge-if-absent body for each stage but writes the installed
+ * `stage-config.json` exactly once with an `N added` summary log. It is behaviour-
+ * identical to the hand-rolled `for (const stageKey of STAGES)` loops the genuine
+ * multi-stage seed migrations (091/094/095/107) used to carry — the on-disk
+ * results (templates copied only when missing, config entries merged only when
+ * absent, single pretty-printed write) match byte-for-byte. Each spec is either a
+ * bare `stageKey` string (filename derived as `${stageKey}.md`) or a
+ * `{ stageKey, filename }` object for the rare diverging basename. `makeSeedMigration`
+ * is the single-stage convenience wrapper over the same machinery.
+ *
* The data effects above are what these migrations are responsible for — the
* console log copy is incidental and not preserved verbatim from the pre-refactor
* files (all now log under `stageKey`).
@@ -34,41 +45,62 @@ import { join } from 'path';
import { atomicWrite } from '../../server/lib/fileUtils.js';
/**
- * @param {string} stageKey - stage-config key, e.g. `pipeline-editorial-character-consistency`
- * @param {{ filename?: string }} [opts] - template basename under `prompts/stages/` (defaults to `${stageKey}.md`)
+ * Normalize a stage spec (bare `stageKey` string or `{ stageKey, filename }`)
+ * into `{ stageKey, filename }` with the universal `${stageKey}.md` default.
+ * @param {string | { stageKey: string, filename?: string }} spec
+ * @returns {{ stageKey: string, filename: string }}
+ */
+function normalizeStageSpec(spec) {
+ if (typeof spec === 'string') return { stageKey: spec, filename: `${spec}.md` };
+ const { stageKey, filename } = spec;
+ return { stageKey, filename: filename || `${stageKey}.md` };
+}
+
+/**
+ * Multi-stage seed migration: copy each `.md` template when missing and merge
+ * each `stage-config.json` entry when absent, writing the installed config once
+ * with an `N added` summary. Behaviour-identical to the hand-rolled
+ * `for (const stageKey of STAGES)` loops it replaces.
+ *
+ * @param {Array<string | { stageKey: string, filename?: string }>} stageSpecs
* @returns {{ up: (ctx: { rootDir: string }) => Promise<void> }}
*/
-export function makeSeedMigration(stageKey, { filename = `${stageKey}.md` } = {}) {
+export function makeSeedMigrations(stageSpecs) {
+ const stages = stageSpecs.map(normalizeStageSpec);
return {
async up({ rootDir }) {
const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
await mkdir(stagesDir, { recursive: true });
- const dataPath = join(stagesDir, filename);
- const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
+ // 1) Copy each prompt template that isn't already present.
+ for (const { stageKey, filename } of stages) {
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
- const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
- if (exists) {
- console.log(`📝 ${stageKey} prompt: already present`);
- } else {
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 ${stageKey} prompt: already present`);
+ continue;
+ }
const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
if (!sampleExists) {
console.warn(`⚠️ ${stageKey}: sample missing for ${filename} — skipping copy`);
- } else {
- try {
- await copyFile(samplePath, dataPath);
- console.log(`✅ seeded ${filename}`);
- } catch (err) {
- console.warn(`⚠️ ${stageKey}: copy failed for ${filename}: ${err.message}`);
- }
+ continue;
+ }
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${filename}`);
+ } catch (err) {
+ console.warn(`⚠️ ${stageKey}: copy failed for ${filename}: ${err.message}`);
}
}
+ // 2) Merge each stage-config entry (skip any already present), writing once.
const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
if (!sampleConfigExists) {
- console.warn(`⚠️ ${stageKey}: data.reference stage-config.json missing — cannot resolve entry; skipping config write`);
+ console.warn('⚠️ seed-stages: data.reference stage-config.json missing — cannot resolve entries; skipping config write');
return;
}
try {
@@ -78,23 +110,40 @@ export function makeSeedMigration(stageKey, { filename = `${stageKey}.md` } = {}
? JSON.parse(await readFile(installedConfigPath, 'utf8'))
: { stages: {} };
installed.stages = installed.stages || {};
- if (installed.stages[stageKey]) {
- console.log(`📝 ${stageKey} stage-config: already present`);
- return;
- }
- if (!sample?.stages?.[stageKey]) {
- console.warn(`⚠️ ${stageKey}: sample stage-config missing ${stageKey} — skipping`);
- return;
+
+ let added = 0;
+ for (const { stageKey } of stages) {
+ if (installed.stages[stageKey]) {
+ console.log(`📝 ${stageKey} stage-config: already present`);
+ continue;
+ }
+ if (!sample?.stages?.[stageKey]) {
+ console.warn(`⚠️ ${stageKey}: sample stage-config missing ${stageKey} — skipping`);
+ continue;
+ }
+ installed.stages[stageKey] = sample.stages[stageKey];
+ added += 1;
}
- installed.stages[stageKey] = sample.stages[stageKey];
+
+ if (added === 0) return;
// Canonical atomic write (temp + rename) so an interrupted boot/upgrade
// can't leave a truncated stage-config.json; atomicWrite ensures the dir.
await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);
const action = installedExists ? 'merged' : 'created';
- console.log(`📝 ${stageKey} stage-config (${action}): 1 added`);
+ console.log(`📝 seed-stages stage-config (${action}): ${added} added`);
} catch (err) {
- console.warn(`⚠️ ${stageKey}: stage-config merge failed: ${err.message}`);
+ console.warn(`⚠️ seed-stages: stage-config merge failed: ${err.message}`);
}
},
};
}
+
+/**
+ * Single-stage convenience wrapper over {@link makeSeedMigrations}.
+ * @param {string} stageKey - stage-config key, e.g. `pipeline-editorial-character-consistency`
+ * @param {{ filename?: string }} [opts] - template basename under `prompts/stages/` (defaults to `${stageKey}.md`)
+ * @returns {{ up: (ctx: { rootDir: string }) => Promise<void> }}
+ */
+export function makeSeedMigration(stageKey, { filename = `${stageKey}.md` } = {}) {
+ return makeSeedMigrations([{ stageKey, filename }]);
+}
diff --git a/scripts/migrations/_seedStageHelpers.test.js b/scripts/migrations/_seedStageHelpers.test.js
index 1d95e74ab5..008ef470a8 100644
--- a/scripts/migrations/_seedStageHelpers.test.js
+++ b/scripts/migrations/_seedStageHelpers.test.js
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync
import { tmpdir } from 'os';
import { join } from 'path';
-import { makeSeedMigration } from './_seedStageHelpers.js';
+import { makeSeedMigration, makeSeedMigrations } from './_seedStageHelpers.js';
const STAGE_KEY = 'pipeline-test-seed-stage';
const FILENAME = 'pipeline-test-seed-stage.md';
@@ -97,13 +97,13 @@ describe('makeSeedMigration', () => {
expect(existsSync(installedConfigPath)).toBe(false);
});
- it('defaults filename to `${stageKey}.md` and logs under the stageKey', async () => {
+ it('defaults filename to `${stageKey}.md` and logs an `N added` config summary', async () => {
seedReference();
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
// No filename passed — must derive `${STAGE_KEY}.md` (which is FILENAME here).
await makeSeedMigration(STAGE_KEY).up({ rootDir });
expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);
- expect(logSpy.mock.calls.some(([msg]) => String(msg).includes(`${STAGE_KEY} stage-config`))).toBe(true);
+ expect(logSpy.mock.calls.some(([msg]) => /stage-config \((merged|created)\): 1 added/.test(String(msg)))).toBe(true);
});
it('honors an explicit filename override that diverges from the stageKey', async () => {
@@ -118,3 +118,104 @@ describe('makeSeedMigration', () => {
expect(existsSync(join(stagesDir, FILENAME))).toBe(false);
});
});
+
+describe('makeSeedMigrations (multi-stage)', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const KEYS = ['pipeline-multi-a', 'pipeline-multi-b'];
+ const bodyFor = (key) => `# ${key}\n\nshipped body\n`;
+
+ const seedReference = ({ withConfig = true, keys = KEYS } = {}) => {
+ for (const key of keys) writeFileSync(join(refStagesDir, `${key}.md`), bodyFor(key));
+ if (withConfig) {
+ const stages = {};
+ for (const key of keys) stages[key] = { name: key, model: 'default', returnsJson: true, variables: [] };
+ writeFileSync(
+ join(rootDir, 'data.reference', 'prompts', 'stage-config.json'),
+ JSON.stringify({ stages }, null, 2) + '\n',
+ );
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'seed-stages-helper-'));
+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ mkdirSync(stagesDir, { recursive: true });
+ mkdirSync(refStagesDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+ });
+
+ it('seeds every .md template and merges every config entry in one write on a fresh install', async () => {
+ seedReference();
+ await expect(makeSeedMigrations(KEYS).up({ rootDir })).resolves.not.toThrow();
+ for (const key of KEYS) {
+ expect(readFileSync(join(stagesDir, `${key}.md`), 'utf8')).toBe(bodyFor(key));
+ expect(JSON.parse(readFileSync(installedConfigPath, 'utf8')).stages[key]).toMatchObject({ returnsJson: true });
+ }
+ });
+
+ it('writes the installed config exactly once with an `N added` summary', async () => {
+ seedReference();
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ await makeSeedMigrations(KEYS).up({ rootDir });
+ expect(logSpy.mock.calls.some(([msg]) => /stage-config \(created\): 2 added/.test(String(msg)))).toBe(true);
+ });
+
+ it('only adds absent entries — existing entries are preserved verbatim', async () => {
+ seedReference();
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [KEYS[0]]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+ await makeSeedMigrations(KEYS).up({ rootDir });
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ expect(installed.stages[KEYS[0]]).toEqual({ name: 'user-tuned', model: 'custom' });
+ expect(installed.stages[KEYS[1]]).toMatchObject({ name: KEYS[1] });
+ });
+
+ it('never clobbers a customized .md that is already present', async () => {
+ seedReference();
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ writeFileSync(join(stagesDir, `${KEYS[0]}.md`), customBody);
+ await makeSeedMigrations(KEYS).up({ rootDir });
+ expect(readFileSync(join(stagesDir, `${KEYS[0]}.md`), 'utf8')).toBe(customBody);
+ expect(readFileSync(join(stagesDir, `${KEYS[1]}.md`), 'utf8')).toBe(bodyFor(KEYS[1]));
+ });
+
+ it('does not write the config when every entry is already present', async () => {
+ seedReference();
+ const stages = {};
+ for (const key of KEYS) stages[key] = { name: 'preexisting' };
+ const original = JSON.stringify({ stages }, null, 2) + '\n';
+ writeFileSync(installedConfigPath, original);
+ await makeSeedMigrations(KEYS).up({ rootDir });
+ expect(readFileSync(installedConfigPath, 'utf8')).toBe(original);
+ });
+
+ it('does not throw and seeds nothing when the data.reference samples are missing', async () => {
+ await expect(makeSeedMigrations(KEYS).up({ rootDir })).resolves.not.toThrow();
+ for (const key of KEYS) expect(existsSync(join(stagesDir, `${key}.md`))).toBe(false);
+ expect(existsSync(installedConfigPath)).toBe(false);
+ });
+
+ it('accepts `{ stageKey, filename }` specs with a diverging basename', async () => {
+ const altFile = 'pipeline-multi-a-alt.md';
+ writeFileSync(join(refStagesDir, altFile), bodyFor(KEYS[0]));
+ writeFileSync(
+ join(rootDir, 'data.reference', 'prompts', 'stage-config.json'),
+ JSON.stringify({ stages: { [KEYS[0]]: { name: KEYS[0], returnsJson: true } } }, null, 2) + '\n',
+ );
+ await makeSeedMigrations([{ stageKey: KEYS[0], filename: altFile }]).up({ rootDir });
+ expect(readFileSync(join(stagesDir, altFile), 'utf8')).toBe(bodyFor(KEYS[0]));
+ expect(existsSync(join(stagesDir, `${KEYS[0]}.md`))).toBe(false);
+ });
+});