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

seed image-prompt stage prompts via migration so pm2-restart upgrades don't 404 'Stage not found'

[._.]/ Adam Eivye0d28be184ee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3fabf7dc6f..e3f38cd090 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -38,6 +38,8 @@
## Fixed
+- **The comic-panel and storyboard "AI: refine" image-prompt buttons no longer throw "Stage not found" on pm2-restart-only upgrades.** Both stage prompts (`pipeline-comic-panel-image-prompt`, `pipeline-storyboard-image-prompt`) ship in `data.reference/` and are wired to the comic-panel / storyboard image-prompt refine buttons, but they were added without a seed migration. Boot runs migrations but **not** `setup-data.js`, so an install that upgraded by pulling + `pm2 restart` (instead of running `update.sh`) never received them — `buildPrompt('pipeline-comic-panel-image-prompt')` then threw "Stage not found" the first time the user clicked "AI: refine." A new first-shipment seed migration (mirrors 090) copies each `.md` into `data/prompts/stages/` and merges its `stage-config.json` entry, only when missing — never clobbering a customized install. (`scripts/migrations/091-seed-image-prompt-stages.js`)
+
- **Imported ChatGPT conversations now sort by their original recency in the Brain ▸ Memory list, instead of arbitrary export order.** A ChatGPT export isn't ordered chronologically, and a bulk import stamps every entry's `createdAt`/`updatedAt` with the same import time — so the memory list (which returned records in insertion order and showed "Updated {import time}" on every card) left imports jumbled and indistinguishable. The importer now persists **both** source clocks (`sourceCreatedAt` *and* the previously-dropped `sourceUpdatedAt`, the conversation's last-activity time), `getMemoryEntries()` orders entries newest-first by an effective recency timestamp (`memoryRecencyMs`: prefers the source clock for imports, falls back to the storage clock for hand-written notes), and the card footer shows "Conversation {N ago}" using the source date for imported entries (matching the sort) rather than the misleading bulk-import time. Existing imports (which already carry `sourceCreatedAt`) sort correctly without a migration. The memory create/update Zod schema (`memoryInputSchema`) gains the provenance fields (`source`, `sourceRef`, `sourceCreatedAt`, `sourceUpdatedAt`) for schema parity with what `createMemoryEntry` persists. (`server/services/brainStorage.js`, `server/services/chatgptImport.js`, `server/lib/brainValidation.js`, `client/src/components/brain/tabs/MemoryTab.jsx`)
- **The pipeline Nouns stage showed "No description yet" for characters that are actually described.** Characters store their renderable text in `physicalDescription`, but `NounsStage`'s per-kind config omitted `descField`, so `CanonCard` fell back to reading the (usually empty) `description` field — making a fully-described character like `ASTER-9 CHANDELIER` (457 chars of `physicalDescription`) read as undescribed, and also leaving its description un-editable inline (the editor gates on `descField`). Wired `NounsStage`'s `KINDS` to the same `descField`/`descFieldFallback`/`descFieldMax` the universe view (`UniverseCanonSection`) already uses — characters → `physicalDescription` (fallback `description`), objects → `description` (fallback `significance`), places → `description` — so the pipeline and universe canon views render and edit identically. (`client/src/components/pipeline/stages/NounsStage.jsx`)
diff --git a/scripts/migrations/091-seed-image-prompt-stages.js b/scripts/migrations/091-seed-image-prompt-stages.js
new file mode 100644
index 0000000000..27014b669a
--- /dev/null
+++ b/scripts/migrations/091-seed-image-prompt-stages.js
@@ -0,0 +1,101 @@
+/**
+ * Seed the `pipeline-comic-panel-image-prompt` and
+ * `pipeline-storyboard-image-prompt` stages into existing installs.
+ *
+ * Mirrors `090-script-verify-stage.js`: copies each `.md` template from
+ * `data.reference/prompts/stages/` and merges its stage-config entry into
+ * `data/prompts/stage-config.json`.
+ *
+ * Why this exists: both prompts ship in `data.reference/` and are wired to the
+ * comic-panel / storyboard "AI: refine" buttons (`refineComicPanelPrompt` /
+ * `refineStoryboardScenePrompt` in `server/services/pipeline/visualStages.js`),
+ * but they were added before this migration without a seed step. Boot runs
+ * migrations (server/index.js) but NOT `setup-data.js`, so an install that
+ * upgrades by pulling + `pm2 restart` (rather than running `update.sh`) never
+ * received them — `buildPrompt('pipeline-comic-panel-image-prompt')` then throws
+ * "Stage not found" the first time the user clicks "AI: refine".
+ *
+ * First-shipment seed: copy only when the file is missing (never clobber a
+ * customized install) and merge each stage-config key only when absent. No MD5
+ * hashing — there is no prior shipped-via-migration baseline to upgrade from.
+ * NOTE: a FUTURE edit to either `.md` must add `ACCEPTED_OLD_MD5` /
+ * `NEW_SHIPPED_MD5` exports (see migration 003) so `setup-data.js`'s
+ * `buildPromptDriftTables` sweep can auto-update other installs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+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}`);
+ }
+ },
+};
diff --git a/scripts/migrations/091-seed-image-prompt-stages.test.js b/scripts/migrations/091-seed-image-prompt-stages.test.js
new file mode 100644
index 0000000000..95a3475660
--- /dev/null
+++ b/scripts/migrations/091-seed-image-prompt-stages.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+import migration from './091-seed-image-prompt-stages.js';
+
+// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).
+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// First-shipment seed migration (089/090 family) — the shared hash-driven
+// `_testHelpers.runPromptMigrationTests` doesn't apply (no MD5 bookkeeping),
+// so the seed/no-clobber behavior is asserted directly here.
+
+const FILES = [
+ { filename: 'pipeline-comic-panel-image-prompt.md', stageKey: 'pipeline-comic-panel-image-prompt', body: '# Comic panel image prompt\n\nshipped body\n' },
+ { filename: 'pipeline-storyboard-image-prompt.md', stageKey: 'pipeline-storyboard-image-prompt', body: '# Storyboard image prompt\n\nshipped body\n' },
+];
+
+describe('migration 091 — seed image-prompt stages', () => {
+ let rootDir;
+ let stagesDir;
+ let refStagesDir;
+ let installedConfigPath;
+
+ const seedReference = ({ withConfig = true } = {}) => {
+ for (const { filename, body } of FILES) {
+ writeFileSync(join(refStagesDir, filename), body);
+ }
+ if (withConfig) {
+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const stages = {};
+ for (const { stageKey } of FILES) {
+ stages[stageKey] = { name: stageKey, description: `${stageKey} desc`, model: 'default', returnsJson: true, variables: [] };
+ }
+ writeFileSync(refConfigPath, JSON.stringify({ stages }, null, 2) + '\n');
+ }
+ };
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-091-'));
+ 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 });
+ });
+
+ it('seeds both .md templates and merges both stage-config entries on a fresh install', async () => {
+ seedReference();
+
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+
+ for (const { filename, stageKey, body } of FILES) {
+ expect(readFileSync(join(stagesDir, filename), 'utf8')).toBe(body);
+ }
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ for (const { stageKey } of FILES) {
+ expect(installed.stages[stageKey]).toMatchObject({ name: stageKey, returnsJson: true });
+ }
+ });
+
+ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {
+ seedReference();
+ // Pre-existing customized install: different prompt bodies + a hand-tuned config entry.
+ const customBody = '# CUSTOMIZED — do not overwrite\n';
+ for (const { filename } of FILES) {
+ writeFileSync(join(stagesDir, filename), customBody);
+ }
+ writeFileSync(
+ installedConfigPath,
+ JSON.stringify({ stages: { [FILES[0].stageKey]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',
+ );
+
+ await migration.up({ rootDir });
+
+ // .md untouched.
+ for (const { filename } of FILES) {
+ expect(readFileSync(join(stagesDir, filename), 'utf8')).toBe(customBody);
+ }
+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));
+ // Existing entry preserved verbatim; the missing second one is added.
+ expect(installed.stages[FILES[0].stageKey]).toEqual({ name: 'user-tuned', model: 'custom' });
+ expect(installed.stages[FILES[1].stageKey]).toMatchObject({ name: FILES[1].stageKey });
+ });
+
+ it('does not throw when the data.reference samples are missing', async () => {
+ // No reference files seeded.
+ await expect(migration.up({ rootDir })).resolves.not.toThrow();
+ for (const { filename } of FILES) {
+ expect(existsSync(join(stagesDir, filename))).toBe(false);
+ }
+ });
+
+ it('matches the live shipped stage-config keys (drift catch)', () => {
+ // Guards against the migration drifting from the real shipped stage ids.
+ const refConfig = JSON.parse(
+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),
+ );
+ for (const { stageKey, filename } of FILES) {
+ expect(refConfig.stages[stageKey], `stage-config missing ${stageKey}`).toBeTruthy();
+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', filename))).toBe(true);
+ }
+ });
+});