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: move migrations to scripts/, keep data/ for runtime only

Ilya Eivy645ca3d66aec
diff --git a/.gitignore b/.gitignore
index 0fe1916ea0..95a54923e4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,14 +5,15 @@ node_modules/
dist/
build/
-# Runtime data (app registry, history, runs). Override the directory-level
-# `data/` rule from the global ~/.gitignore so git descends into data/ and
-# evaluates the negations below; then re-exclude everything inside, and
-# re-include the source-controlled migration scripts.
+# Runtime data (app registry, history, runs, migration state). Override the
+# directory-level `data/` rule from the global ~/.gitignore so git descends
+# into data/ and evaluates the negation below; then re-exclude everything
+# inside except the .gitkeep that pins the empty directory. Seed/template
+# content lives in data.sample/ and is copied in by scripts/setup-data.js;
+# migration scripts live in scripts/migrations/.
!data/
data/*
-!data/migrations/
-data/migrations/.applied.json
+!data/.gitkeep
# Environment files
.env
diff --git a/CLAUDE.md b/CLAUDE.md
index 5f0ffbd27d..5dbe383e65 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -174,7 +174,7 @@ When working **directly in the Claude Code TUI** with the user driving, edit the
- **"Run Now" actions must gate on saved state, not the form input.** When a settings page has a companion "Run this now" button that triggers a server action reading server-side settings (not the local form values), the button must be gated on the *saved* value, not the in-memory input. Track a parallel `saved*` state for each setting the action depends on, update it on successful save, and use it for the action's enabled gate. Disable the action while the form is dirty *or* a save is in flight — a tooltip-only warning is missed on touch and produces surprising "I edited X and ran, but X didn't apply" bugs.
- **In-flight saves must gate dependent actions, not just the form.** When a field's PATCH is async and a button triggers server-side work that reads that field (auto-run, regenerate, etc.), the button must disable while the PATCH is in flight — not just while the input is "dirty." Otherwise the user picks a new value, the input clears, and they click the action before the server has the new value persisted. Track a `<field>Saving` boolean alongside the action's other disable predicates, set it before the PATCH and clear it in `.finally()`. See `PipelineIssue.jsx` `lengthProfileSaving` for the canonical example.
- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.
-- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.sample/prompts/stages/*.md` file, also add an entry to `data/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. See `data/migrations/003-update-pipeline-stage-prompts.js`.
+- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.sample/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.
- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgents.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.
- **Socket event-driven state — don't pre-clear before the server confirms.** When swapping which entity a socket-driven UI is showing (shell session, agent run, etc.), wait for the server's success event to drive the swap atomically; the error event is the recovery point. Pre-clearing the local `*Ref` / visible state up front leaves the UI stranded on a dead URL when the success event never arrives (target died mid-request, server rejected the switch). Pair every `socket.on('X:error')` that follows a stateful request with a recovery branch that restores the previously-displayed state or falls back to a live alternative.
- **Single-subscriber socket resources need notify + recipient-relative advertise + filter + claim.** Some server-side resources (PTY shell sessions, etc.) intentionally store one attached socket and fan output to it. The contract: (1) emit `<resource>:detached` on the previous socket when a new socket takes over so the displaced client can drop its local view; (2) include an `attached: boolean` field on each list-entry payload, computed *relative to the recipient socket* (true only when bound to a different socket) — a globally-truthy `attached` makes a client's own sessions look unavailable to itself; (3) broadcast list updates from both attach AND detach paths; (4) auto-pick paths send `claim: true` and the server refuses to displace a different socket. Manual paths (tab click, deep-link URL) default to `claim: false` so explicit intent still wins. See `server/services/shell.js` for the canonical implementation.
diff --git a/PLAN.md b/PLAN.md
index aa34d9e032..90cc6d7d14 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -235,7 +235,7 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx
- [ ] **Voice-controlled stage advancement.** "Next stage", "rerun comic script" via the existing voice agent. Register pipeline stage navigation actions in `server/services/voice/tools.js`.
- [x] **Recent-issues dynamic children under the Pipeline sidebar entry.** Shipped — Layout.jsx's `decoratePipelineChild` now hydrates Pipeline with one grandchild per series (`dynamic: 'pipelineSeries'`), focus-debounced refresh, alphabetical sort. Originally landed showing 10 recent issues; reworked 2026-05-14 to show all series so the sidebar stays coherent across many series. Recursive grandchildren render works in `renderNavItem`.
- [ ] **AI-assisted panel/scene prompt generation.** Reserve `pipeline-comic-panel-image-prompt.md` and `pipeline-storyboard-image-prompt.md` template files for a future "AI: turn the script fragment into N image-gen prompts" button on the ComicPages and Storyboards stages.
-- [ ] **Extract migration scaffolding into `data/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift `replaceUnmodifiedStagePrompts({ rootDir, oldHashes, newHashes, featureName, customizedHint })` into a shared helper so the next prompt-replace migration is ~15 lines. While at it, have `scripts/setup-data.js` import the same hash maps from each migration so the drift table stops duplicating them. Skipped during the 006 commit to keep diff focused.
+- [ ] **Extract migration scaffolding into `scripts/migrations/_lib.js`.** Migrations 003 and 006 both implement the same hash-driven prompt-replace pattern (~75 lines of boilerplate each). Lift `replaceUnmodifiedStagePrompts({ rootDir, oldHashes, newHashes, featureName, customizedHint })` into a shared helper so the next prompt-replace migration is ~15 lines. While at it, have `scripts/setup-data.js` import the same hash maps from each migration so the drift table stops duplicating them. Skipped during the 006 commit to keep diff focused.
- [ ] **Shots-aware scene-output-contract partial.** `data.sample/prompts/stages/pipeline-extract-scenes.md` now inlines the JSON output contract (with `shots[]`) instead of using `{{> scene-output-contract }}`. If a third shots-using stage ever appears (or a top-level scene field gets added), the partial and the inlined copy in extract-scenes will drift. Split into composable partials (`_partials/scene-fields-core.md` + `_partials/scene-fields-shots.md`) when that third caller materializes — until then the inline copy is the smaller risk.
- [ ] **Voice picker on character cards (Pipeline Audio 4b follow-up).** AudioStage renders fine without it (per-line render falls through to the project default voice), but binding `character.voiceId` today requires hand-editing JSON or PATCHing the universe canon. The picker should live on `CanonCard` (`client/src/components/pipeline/CanonCard.jsx`) when `kind === 'character'`: chip with current voice id, dropdown reading `/api/pipeline/tts/voices`, audition button that fetches `/api/pipeline/tts/preview` and plays inline, and a Save handler that PATCHes the universe canon entry (`updateUniverseCharacter` — needs to exist in `apiUniverseBuilder.js`). Same picker re-usable on a per-line override in `AudioStage.jsx`. Local OSS (Kokoro/Piper) always included; 3rd-party engines surface through the same merged list.
- [ ] **Pipeline Audio — music generation + VO mux (Phase 4c.2 / 4d.2).** Per the AnyFilm comparison plan (`~/.claude/plans/i-want-to-examine-polished-meteor.md` cluster C). 4c (user-upload + library + picker) **shipped 2026-05-16**; 4d music-bed mux **shipped 2026-05-16**. Remaining:
diff --git a/data/prompts/skills/feature-agent.md b/data.sample/prompts/skills/feature-agent.md
similarity index 100%
rename from data/prompts/skills/feature-agent.md
rename to data.sample/prompts/skills/feature-agent.md
diff --git a/data/.gitkeep b/data/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/data/migrations/001-merge-worldbuilder-collections.js b/scripts/migrations/001-merge-worldbuilder-collections.js
similarity index 100%
rename from data/migrations/001-merge-worldbuilder-collections.js
rename to scripts/migrations/001-merge-worldbuilder-collections.js
diff --git a/data/migrations/002-cd-evaluate-image-strength.js b/scripts/migrations/002-cd-evaluate-image-strength.js
similarity index 100%
rename from data/migrations/002-cd-evaluate-image-strength.js
rename to scripts/migrations/002-cd-evaluate-image-strength.js
diff --git a/data/migrations/003-update-pipeline-stage-prompts.js b/scripts/migrations/003-update-pipeline-stage-prompts.js
similarity index 100%
rename from data/migrations/003-update-pipeline-stage-prompts.js
rename to scripts/migrations/003-update-pipeline-stage-prompts.js
diff --git a/data/migrations/004-augment-idea-expansion-context.js b/scripts/migrations/004-augment-idea-expansion-context.js
similarity index 100%
rename from data/migrations/004-augment-idea-expansion-context.js
rename to scripts/migrations/004-augment-idea-expansion-context.js
diff --git a/data/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.js
similarity index 100%
rename from data/migrations/005-shape-aware-arc-prompts.js
rename to scripts/migrations/005-shape-aware-arc-prompts.js
diff --git a/data/migrations/006-extract-scenes-shots.js b/scripts/migrations/006-extract-scenes-shots.js
similarity index 100%
rename from data/migrations/006-extract-scenes-shots.js
rename to scripts/migrations/006-extract-scenes-shots.js
diff --git a/data/migrations/007-places-int-ext-time-of-day.js b/scripts/migrations/007-places-int-ext-time-of-day.js
similarity index 100%
rename from data/migrations/007-places-int-ext-time-of-day.js
rename to scripts/migrations/007-places-int-ext-time-of-day.js
diff --git a/data/migrations/008-default-to-claude-code-tui.js b/scripts/migrations/008-default-to-claude-code-tui.js
similarity index 100%
rename from data/migrations/008-default-to-claude-code-tui.js
rename to scripts/migrations/008-default-to-claude-code-tui.js
diff --git a/data/migrations/009-heal-sharing-cursor-drops.js b/scripts/migrations/009-heal-sharing-cursor-drops.js
similarity index 100%
rename from data/migrations/009-heal-sharing-cursor-drops.js
rename to scripts/migrations/009-heal-sharing-cursor-drops.js
diff --git a/data/migrations/009-simplify-cos-agent-briefing.js b/scripts/migrations/009-simplify-cos-agent-briefing.js
similarity index 100%
rename from data/migrations/009-simplify-cos-agent-briefing.js
rename to scripts/migrations/009-simplify-cos-agent-briefing.js
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index ffe6b70c59..bf227212a1 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -5,12 +5,13 @@ import { fileURLToPath, pathToFileURL } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
-const migrationsDir = join(rootDir, 'data', 'migrations');
-const appliedFile = join(migrationsDir, '.applied.json');
+const migrationsDir = join(__dirname, 'migrations');
+const appliedFile = join(rootDir, 'data', 'migrations.applied.json');
async function run() {
- // Ensure migrations directory exists
- await mkdir(migrationsDir, { recursive: true });
+ // Ensure data/ exists so we can persist applied state (migrationsDir
+ // ships in the repo and always exists).
+ await mkdir(dirname(appliedFile), { recursive: true });
// Load applied migrations list (default to [] on missing/unreadable file, throw on corrupted JSON)
let applied = [];
diff --git a/scripts/setup-data.js b/scripts/setup-data.js
index 39a351ac31..3cb512405b 100644
--- a/scripts/setup-data.js
+++ b/scripts/setup-data.js
@@ -104,13 +104,6 @@ for (const { relPath, mergeKey } of JSON_MERGE_TARGETS) {
mergeJsonStarter(relPath, mergeKey);
}
-// Ensure migrations directory exists (not in data.sample, needed for both fresh and existing installs)
-const migrationsDir = join(dataDir, 'migrations');
-if (!existsSync(migrationsDir)) {
- console.log('📁 Creating missing directory: migrations');
- mkdirSync(migrationsDir, { recursive: true });
-}
-
// Drift detection — warn when a data.sample/prompts/stages/*.md differs from
// the installed data/prompts/stages/*.md copy. Only fires on existing installs
// (fresh installs already got a full copy above). Prompt templates drift when
@@ -118,11 +111,11 @@ if (!existsSync(migrationsDir)) {
// existing installs won't pick up because setup-data.js only copies *missing*
// files.
//
-// NOTE: only the files managed by data/migrations/003+ are checked here —
+// NOTE: only the files managed by scripts/migrations/003+ are checked here —
// scanning all stage prompts would produce misleading warnings for prompts
// that have no migration counterpart (e.g. cd-evaluate.md, writers-room prompts).
//
-// Mirror data/migrations/003+ NEW/OLD hashes. Array values let the check
+// Mirror scripts/migrations/003+ NEW/OLD hashes. Array values let the check
// 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 = {
diff --git a/server/services/sharing/healCursorMigration.test.js b/server/services/sharing/healCursorMigration.test.js
index f64f87dd23..721e000b38 100644
--- a/server/services/sharing/healCursorMigration.test.js
+++ b/server/services/sharing/healCursorMigration.test.js
@@ -1,5 +1,5 @@
/**
- * Tests for `data/migrations/009-heal-sharing-cursor-drops.js` — the
+ * Tests for `scripts/migrations/009-heal-sharing-cursor-drops.js` — the
* one-shot heal that clears sharing cursor entries whose manifests are
* still on disk but whose records never got inserted locally.
*/
@@ -9,7 +9,7 @@ import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync
import { tmpdir } from 'os';
import { join } from 'path';
-import { healSharingCursorDrops } from '../../../data/migrations/009-heal-sharing-cursor-drops.js';
+import { healSharingCursorDrops } from '../../../scripts/migrations/009-heal-sharing-cursor-drops.js';
const writeJson = (path, value) =>
writeFileSync(path, JSON.stringify(value, null, 2) + '\n');