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

fix([issue-863]): tile cues by count + seed cue prompt via migration

[._.]/ Adam Eivy57f53e561825
diff --git a/scripts/migrations/068-pipeline-audio-cues-prompt.js b/scripts/migrations/068-pipeline-audio-cues-prompt.js
new file mode 100644
index 0000000000..65ebe57185
--- /dev/null
+++ b/scripts/migrations/068-pipeline-audio-cues-prompt.js
@@ -0,0 +1,84 @@
+/**
+ * Seed the whole-episode audio cue-planner prompt stage into existing installs
+ * (issue #863, step 3 — docs/plans/2026-06-03-whole-episode-audio-strategy.md).
+ *
+ * Single-stage sibling of the writers-room prompt seeds (migration 065): copies
+ * the `pipeline-audio-cues.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 the full setup) would otherwise
+ * leave the new stage unseeded and the first POST .../cues/generate call would
+ * throw "Stage not found".
+ *
+ * FIRST-SHIPMENT SEED ONLY — no MD5 hashing: it copies the template only when
+ * missing and never overwrites an install's existing prompt. A FUTURE migration
+ * that AMENDS this prompt must follow migration 003's hash-driven pattern
+ * (normalize line endings, ship OLD + NEW shipped hashes) instead.
+ */
+
+import { access, copyFile, mkdir, readFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+
+// The prompt file's basename doubles as its stage-config key (sans `.md`).
+const STAGE = 'pipeline-audio-cues';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ // 1. Copy the prompt template if it's missing.
+ const filename = `${STAGE}.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(`📝 audio-cues prompt: ${filename} already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ audio-cues: sample missing for ${filename} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${filename}`);
+ } catch (err) {
+ console.warn(`⚠️ audio-cues: copy failed for ${filename}: ${err.message}`);
+ }
+ }
+ }
+
+ // 2. Merge the stage-config entry if it's missing.
+ 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('⚠️ audio-cues: data.reference stage-config.json missing — 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 || {};
+ if (installed.stages[STAGE]) {
+ console.log(`📝 audio-cues stage-config: ${STAGE} already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE]) {
+ console.warn(`⚠️ audio-cues: sample stage-config missing ${STAGE} — skipping`);
+ return;
+ }
+ installed.stages[STAGE] = sample.stages[STAGE];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 audio-cues stage-config (${action}): ${STAGE} added`);
+ } catch (err) {
+ console.warn(`⚠️ audio-cues: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/068-pipeline-audio-cues-prompt.test.js b/scripts/migrations/068-pipeline-audio-cues-prompt.test.js
new file mode 100644
index 0000000000..068d54c3b3
--- /dev/null
+++ b/scripts/migrations/068-pipeline-audio-cues-prompt.test.js
@@ -0,0 +1,58 @@
+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 './068-pipeline-audio-cues-prompt.js';
+
+const STAGE = 'pipeline-audio-cues';
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 068 — seed whole-episode audio cue-planner prompt', () => {
+ let rootDir;
+ let installedStagesDir;
+ let installedConfigPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-068-'));
+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ mkdirSync(refStagesDir, { recursive: true });
+ writeFileSync(join(refStagesDir, `${STAGE}.md`), `# ${STAGE}\n\nbody\n`);
+ const refConfig = { stages: { [STAGE]: { name: STAGE, model: 'default', returnsJson: true, variables: [] } } };
+ writeFileSync(join(rootDir, 'data.reference', 'prompts', 'stage-config.json'), JSON.stringify(refConfig, 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 the prompt file + stage-config entry on a fresh install', async () => {
+ await migration.up({ rootDir });
+ expect(existsSync(join(installedStagesDir, `${STAGE}.md`))).toBe(true);
+ expect(readJson(installedConfigPath).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();
+ expect(config.stages[STAGE]).toBeTruthy();
+ });
+
+ it('is idempotent and preserves a user-customized installed prompt', async () => {
+ mkdirSync(installedStagesDir, { recursive: true });
+ const customPath = join(installedStagesDir, `${STAGE}.md`);
+ writeFileSync(customPath, '# CUSTOM cue planner\n');
+ await migration.up({ rootDir });
+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');
+ // Second run is a clean no-op.
+ await migration.up({ rootDir });
+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');
+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();
+ });
+});
diff --git a/server/services/pipeline/audioCuePlacement.js b/server/services/pipeline/audioCuePlacement.js
index 351104dbb6..f5784fd0f1 100644
--- a/server/services/pipeline/audioCuePlacement.js
+++ b/server/services/pipeline/audioCuePlacement.js
@@ -7,12 +7,14 @@
* duration (storyboard scenes carry no per-scene duration, and the VO
* `offsetSec` is a manually-placed audio offset, not a scene-timing source).
*
- * This module owns that placement: given the ordered cues and the total episode
- * duration (ffprobed at stitch time), it lays each story-order cue onto the
- * absolute timeline so the cues tile the episode end-to-end. A cue's own
- * rendered `durationSec` is honored when present (so a 30s sting stays 30s);
- * unrendered cues split the remaining time evenly. The result is the
- * `startSec`/`endSec` the cue muxer (`buildCueMuxArgs`) places each cue at.
+ * This module owns that auto-placement: given the ordered cues and the total
+ * episode duration (ffprobed at stitch time), it tiles the cues evenly across
+ * the episode end-to-end. The cue muxer loops + trims each cue to the span it's
+ * placed at, so a cue's *rendered* `durationSec` is irrelevant to its span —
+ * tiling by COUNT (not by rendered length) is correct, and it's what keeps the
+ * arc shape: each beat gets an equal stretch rather than collapsing to a short
+ * default-duration render with the final cue absorbing the rest. `durationSec`
+ * stays render metadata only.
*
* Pure + unit-tested — no ffprobe, no filesystem. The caller probes the
* duration and passes it in.
@@ -22,14 +24,12 @@
* Place an ordered cue list onto a timeline of `totalDurationSec`. Returns a NEW
* cue array (cues unchanged in identity) with `startSec`/`endSec` filled.
*
- * Strategy: walk cues in order, advancing a cursor. Each cue spans from the
- * cursor to cursor + its length, where length is the cue's rendered
- * `durationSec` when it's a finite positive number, otherwise an even share of
- * the time still unclaimed by the remaining cues. The final cue is pinned to
- * end exactly at `totalDurationSec` so the bed covers the whole episode (no
- * trailing gap from rounding). Cues that would start past the episode end are
- * clamped to a zero-length tail at the end (the muxer drops zero/negative-span
- * cues via its placed-cue filter).
+ * Strategy: split the episode into N equal stretches, one per cue, in story
+ * order — N = cues.length. The cue muxer loops each cue to fill its stretch, so
+ * the placement is purely "how much of the episode does this beat own," not "how
+ * long was it rendered." The last cue is pinned to end exactly at
+ * `totalDurationSec` so the bed covers the whole episode with no trailing gap
+ * from float rounding.
*
* @param {Array} cues ordered cue objects (need at least `id`)
* @param {number} totalDurationSec episode length in seconds (> 0)
@@ -43,31 +43,13 @@ export function placeCuesOnTimeline(cues, totalDurationSec) {
return cues.map((c) => ({ ...c, startSec: null, endSec: null }));
}
- const out = [];
- let cursor = 0;
- for (let i = 0; i < cues.length; i += 1) {
- const cue = cues[i];
- const remainingCues = cues.length - i;
- const remainingTime = Math.max(0, total - cursor);
- const rendered = Number(cue?.durationSec);
- const hasRendered = Number.isFinite(rendered) && rendered > 0;
-
- let length;
- if (i === cues.length - 1) {
- // Last cue: fill to the end so the bed covers the whole episode.
- length = remainingTime;
- } else if (hasRendered) {
- // Honor the cue's actual rendered length, but never overrun the timeline.
- length = Math.min(rendered, remainingTime);
- } else {
- // Even share of the time still unclaimed by the cues that remain.
- length = remainingTime / remainingCues;
- }
-
- const startSec = Math.min(cursor, total);
- const endSec = Math.min(cursor + length, total);
- out.push({ ...cue, startSec, endSec });
- cursor = endSec;
- }
- return out;
+ // Equal stretch per cue (by count, NOT by rendered durationSec — see header).
+ const slice = total / cues.length;
+ return cues.map((cue, i) => ({
+ ...cue,
+ startSec: i * slice,
+ // Pin the last cue's end to the exact episode length so float accumulation
+ // can't leave a sub-second gap at the tail.
+ endSec: i === cues.length - 1 ? total : (i + 1) * slice,
+ }));
}
diff --git a/server/services/pipeline/audioCuePlacement.test.js b/server/services/pipeline/audioCuePlacement.test.js
index ebcc9098d2..bc5d1a440a 100644
--- a/server/services/pipeline/audioCuePlacement.test.js
+++ b/server/services/pipeline/audioCuePlacement.test.js
@@ -19,42 +19,40 @@ describe('placeCuesOnTimeline', () => {
expect(placed[0].startSec).toBeNull();
});
- it('tiles cues end-to-end across the episode, last cue pinned to the end', () => {
+ it('tiles cues evenly end-to-end across the episode, last cue pinned to the end', () => {
const cues = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
const placed = placeCuesOnTimeline(cues, 90);
- // Even split (no rendered durations): 30s each.
+ // Equal stretch per cue: 30s each.
expect(placed[0].startSec).toBe(0);
expect(placed[0].endSec).toBeCloseTo(30, 5);
expect(placed[1].startSec).toBeCloseTo(30, 5);
- expect(placed[2].endSec).toBe(90); // pinned to the episode end
+ expect(placed[2].endSec).toBe(90); // last pinned to the episode end
// Contiguous: each cue starts where the previous ended.
expect(placed[1].startSec).toBeCloseTo(placed[0].endSec, 5);
expect(placed[2].startSec).toBeCloseTo(placed[1].endSec, 5);
});
- it('honors a cue rendered durationSec, splitting the rest evenly', () => {
+ it('ignores a cue rendered durationSec for span — tiles by count, not render length', () => {
+ // Cues are typically rendered with engine-default lengths (12–20s) BEFORE
+ // stitch placement; honoring those would collapse early cues to short spans
+ // and dump the rest on the last cue. The muxer loops each cue to fill its
+ // placed span, so span is purely "share of the episode," set by count.
const cues = [
- { id: 'a', durationSec: 20 }, // honored
- { id: 'b' },
- { id: 'c' },
+ { id: 'a', durationSec: 12 },
+ { id: 'b', durationSec: 18 },
+ { id: 'c', durationSec: 15 },
];
- const placed = placeCuesOnTimeline(cues, 100);
- expect(placed[0].endSec).toBeCloseTo(20, 5); // honored rendered length
- // remaining 80s split across the 2 remaining cues → 40 each, last pinned to 100
- expect(placed[1].startSec).toBeCloseTo(20, 5);
- expect(placed[1].endSec).toBeCloseTo(60, 5);
- expect(placed[2].endSec).toBe(100);
+ const placed = placeCuesOnTimeline(cues, 90);
+ expect(placed[0].endSec).toBeCloseTo(30, 5); // NOT 12
+ expect(placed[1].startSec).toBeCloseTo(30, 5);
+ expect(placed[1].endSec).toBeCloseTo(60, 5); // NOT 30 (12+18)
+ expect(placed[2].endSec).toBe(90);
});
- it('clamps a rendered duration that would overrun the timeline', () => {
- const cues = [{ id: 'a', durationSec: 500 }, { id: 'b' }];
- const placed = placeCuesOnTimeline(cues, 60);
- // First cue can't run past the episode; last cue pinned to the end.
- expect(placed[0].endSec).toBeLessThanOrEqual(60);
- expect(placed[1].endSec).toBe(60);
- // A clamped first cue can leave the last cue a zero-length tail — that's fine,
- // the muxer's placed-cue filter drops zero/negative spans.
- expect(placed[1].startSec).toBeLessThanOrEqual(60);
+ it('gives a single cue the whole episode', () => {
+ const placed = placeCuesOnTimeline([{ id: 'only', durationSec: 12 }], 75);
+ expect(placed[0].startSec).toBe(0);
+ expect(placed[0].endSec).toBe(75);
});
it('preserves cue identity fields (id/label/prompt) while adding timing', () => {