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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): seed beat-continuity prompts via migration + clear stale downstream drafts
Adam Eivyb75920fd3554
diff --git a/scripts/migrations/125-beat-continuity-prompts.js b/scripts/migrations/125-beat-continuity-prompts.jsnew file mode 100644index 0000000000..119a363b6c--- /dev/null+++ b/scripts/migrations/125-beat-continuity-prompts.js@@ -0,0 +1,91 @@+/**+ * Seed the two `pipeline-beat-continuity` stages into existing installs (#1510).+ *+ * Mirrors `087-manuscript-reformat-stage.js`: copies each `.md` template from+ * `data.reference/prompts/stages/` and merges its stage-config entry into+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than+ * running `update.sh`) would otherwise leave the new whole-manuscript+ * beat-continuity stages unseeded — and Series Autopilot, whose new+ * `maxBeatContinuityRounds` defaults > 0, would throw "Stage not found" the+ * first time it reached `runStagedLLM('pipeline-beat-continuity')`.+ *+ * Two stages this seeds (idempotent — a present file/entry is left as-is):+ * - pipeline-beat-continuity (the whole-book beat verify)+ * - pipeline-beat-continuity-resolve (the per-issue beat auto-resolve)+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++const STAGE_KEYS = ['pipeline-beat-continuity', 'pipeline-beat-continuity-resolve'];++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });++ // 1. Copy each missing prompt template.+ 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(`⚠️ beat-continuity: sample missing for ${filename} — skipping copy`);+ continue;+ }+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${filename}`);+ } catch (err) {+ console.warn(`⚠️ beat-continuity: copy failed for ${filename}: ${err.message}`);+ }+ }++ // 2. Merge each missing stage-config entry.+ 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('⚠️ beat-continuity: 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(`⚠️ beat-continuity: sample stage-config missing ${key} — skipping`);+ continue;+ }+ installed.stages[key] = sample.stages[key];+ 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(`📝 beat-continuity stage-config (${action}): ${added} added`);+ } catch (err) {+ console.warn(`⚠️ beat-continuity: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/125-beat-continuity-prompts.test.js b/scripts/migrations/125-beat-continuity-prompts.test.jsnew file mode 100644index 0000000000..f97842688d--- /dev/null+++ b/scripts/migrations/125-beat-continuity-prompts.test.js@@ -0,0 +1,69 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './125-beat-continuity-prompts.js';++const STAGES = ['pipeline-beat-continuity', 'pipeline-beat-continuity-resolve'];+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 125 — seed whole-manuscript beat-continuity prompts (#1510)', () => {+ let rootDir;+ let installedStagesDir;+ let installedConfigPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-125-'));+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ mkdirSync(refStagesDir, { recursive: true });+ const refStages = {};+ for (const stage of STAGES) {+ writeFileSync(join(refStagesDir, `${stage}.md`), `# ${stage}\n\nbody\n`);+ refStages[stage] = { name: stage, model: 'heavy', returnsJson: true, variables: [] };+ }+ writeFileSync(+ join(rootDir, 'data.reference', 'prompts', 'stage-config.json'),+ JSON.stringify({ stages: refStages }, null, 2) + '\n',+ );++ installedStagesDir = join(rootDir, 'data', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds both prompt files + stage-config entries on a fresh install', async () => {+ await migration.up({ rootDir });+ const config = readJson(installedConfigPath);+ for (const stage of STAGES) {+ expect(existsSync(join(installedStagesDir, `${stage}.md`))).toBe(true);+ expect(config.stages[stage]).toBeTruthy();+ }+ });++ it('merges into an existing stage-config without clobbering other stages', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ writeFileSync(installedConfigPath, JSON.stringify({ stages: { 'pipeline-prose': { name: 'Prose' } } }, null, 2) + '\n');+ await migration.up({ rootDir });+ const config = readJson(installedConfigPath);+ expect(config.stages['pipeline-prose']).toBeTruthy();+ for (const stage of STAGES) expect(config.stages[stage]).toBeTruthy();+ });++ it('is idempotent and preserves a user-customized installed prompt', async () => {+ mkdirSync(installedStagesDir, { recursive: true });+ const customPath = join(installedStagesDir, 'pipeline-beat-continuity.md');+ writeFileSync(customPath, '# CUSTOM beat continuity\n');+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ // The other (non-customized) stage is still seeded.+ expect(existsSync(join(installedStagesDir, 'pipeline-beat-continuity-resolve.md'))).toBe(true);+ // Second run is a clean no-op.+ await migration.up({ rootDir });+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');+ for (const stage of STAGES) expect(readJson(installedConfigPath).stages[stage]).toBeTruthy();+ });+});diff --git a/server/services/pipeline/arcPlanner/beatContinuity.js b/server/services/pipeline/arcPlanner/beatContinuity.jsindex 263b630654..378541d814 100644--- a/server/services/pipeline/arcPlanner/beatContinuity.js+++ b/server/services/pipeline/arcPlanner/beatContinuity.js@@ -27,7 +27,7 @@import { runStagedLLM } from '../../../lib/stageRunner.js';import { ServerError } from '../../../lib/errorHandler.js';import { getSeries } from '../series.js';-import { listIssues, updateStageWithLatest } from '../issues.js';+import { listIssues, updateStageWithLatest, TEXT_STAGE_IDS } from '../issues.js';import {buildBeatContinuityContext,buildBeatContinuityResolveContext,@@ -36,6 +36,11 @@ import {shapeBeatResolutions,} from './context.js';+// Text stages generated FROM the beats — stale once the beats are rewritten, so+// a beat correction must clear them for regeneration. `idea` (which holds the+// beats) is excluded; the rest of the text chain (prose → scripts) is downstream.+const DOWNSTREAM_TEXT_STAGES = TEXT_STAGE_IDS.filter((s) => s !== 'idea');+// Cross-issue BEAT continuity pass over the whole series. Read-only — returns// `{ issues }` shaped like verifyArc. Issues without beats are reviewed at// synopsis depth (renderVolumeIssue falls back), so a partially-expanded series@@ -119,12 +124,16 @@ export async function resolveBeatContinuity(seriesId, options = {}) {* `applyEpisodeResolutions`). Writes the new beats to `idea.output` while* preserving the existing `idea.input` synopsis.*+ * After rewriting an issue's beats, the now-stale downstream text stages+ * (prose/comicScript/teleplay) are cleared so the conductor regenerates them from+ * the corrected beats — see the inline note below.+ ** Three guards: a locked `idea` stage is left untouched (the user froze it); an* issue that has NO beats yet is skipped (the corpus is beat-level — fabricating* beats for a still-synopsis-only issue would be out of band, and a later* beat-sheet run would overwrite them anyway); an unmatched correction is* dropped with a log so a number-scheme mismatch is diagnosable. Never throws.- * Returns `[{ issueId, number, seasonNumber, corrected, skipped }]`.+ * Returns `[{ issueId, number, seasonNumber, corrected, clearedStages, skipped }]`.*/export async function applyBeatResolutions(seriesId, series, episodes) {if (!Array.isArray(episodes) || episodes.length === 0) return [];@@ -161,7 +170,26 @@ export async function applyBeatResolutions(seriesId, series, episodes) {})).catch((err) => {console.log(`⚠️ beat-continuity: episode ${edit.episodeNumber} beat edit failed: ${err.message}`);});- applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, corrected: true });+ // The beats just changed, so any already-generated prose/scripts derived from+ // them are stale. Clear the unlocked downstream text stages so the conductor's+ // textStages step regenerates them from the corrected beats — otherwise+ // `textReady` sees the old scripts as ready and the run finishes with scripts+ // that contradict the fixed beats. In the normal forward flow these stages are+ // still empty (beat continuity runs before textStages), so this only bites on a+ // re-run / resume over already-drafted issues. Mirrors how applyEpisodeResolutions+ // clears beats when it rewrites a synopsis. A locked downstream stage is the+ // user's frozen work — leave it untouched.+ const clearedStages = [];+ for (const stageId of DOWNSTREAM_TEXT_STAGES) {+ const st = issue.stages?.[stageId];+ if (!st || st.locked === true) continue;+ if (!(st.output && st.output.trim())) continue; // nothing generated → nothing to clear+ await updateStageWithLatest(issue.id, stageId, () => ({ status: 'empty', output: '', errorMessage: '' })).catch((err) => {+ console.log(`⚠️ beat-continuity: clear ${stageId} for episode ${edit.episodeNumber} failed: ${err.message}`);+ });+ clearedStages.push(stageId);+ }+ applied.push({ issueId: issue.id, number: issue.number, seasonNumber: edit.seasonNumber, corrected: true, clearedStages });}if (applied.length) {const fixed = applied.filter((a) => a.corrected).length;diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.jsindex a7eb90afb8..19e0e12515 100644--- a/server/services/pipeline/seriesAutopilot.test.js+++ b/server/services/pipeline/seriesAutopilot.test.js@@ -912,6 +912,29 @@ describe('beat-continuity resolve (#1510)', () => {expect(issue.stages.idea.status).toBe('ready');});+ it('clears stale downstream prose/scripts so they regenerate from the corrected beats', async () => {+ const { series, issueId } = await seedIssueWithBeats();+ // Pre-existing downstream drafts (the re-run / resume case): prose + comicScript+ // were generated from the OLD beats.+ await issuesSvc.updateStage(issueId, 'prose', { status: 'ready', output: 'old prose' });+ await issuesSvc.updateStage(issueId, 'comicScript', { status: 'ready', output: 'old script' });+ const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected beats' }]);+ expect(applied[0].clearedStages).toEqual(expect.arrayContaining(['prose', 'comicScript']));+ const issue = await issuesSvc.getIssue(issueId);+ expect(issue.stages.idea.output).toBe('corrected beats'); // new beats applied+ expect(issuesSvc.isStageReady(issue.stages.prose)).toBe(false); // stale → cleared+ expect(issuesSvc.isStageReady(issue.stages.comicScript)).toBe(false); // stale → cleared+ });++ it('does NOT clear a locked downstream stage when rewriting beats', async () => {+ const { series, issueId } = await seedIssueWithBeats();+ await issuesSvc.updateStage(issueId, 'comicScript', { status: 'ready', output: 'frozen script', locked: true });+ const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected beats' }]);+ expect(applied[0].clearedStages).not.toContain('comicScript');+ const issue = await issuesSvc.getIssue(issueId);+ expect(issue.stages.comicScript.output).toBe('frozen script'); // untouched+ });+it('skips a locked idea stage', async () => {const { series, issueId } = await seedIssueWithBeats({ locked: true });const applied = await applyBeatResolutions(series.id, series, [{ seasonNumber: 1, episodeNumber: 1, beats: 'corrected' }]);