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

feat(creative-director): multi-frame evaluator sampling + prompts manager migration

Adam Eivy447d2b5e34a6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3c02a8debb..64b3371451 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,10 @@
## Fixed
+- **Creative Director smoke-test fixture is ~2× faster.** Drops scene `durationSeconds` from 3s → 2s and switches `aspectRatio` from `1:1` (512×512) to a new hidden `1:1-small` preset (384×384, ~44% fewer pixels) — total compute budget goes from `3 × 3s × 512²` to `3 × 2s × 384²`, roughly a 63% pixel-frame reduction. The smaller preset is registered in `ASPECT_PRESETS` only (not `ASPECT_RATIOS`), so the user-facing dropdown and route validation surface stay unchanged; the smoke route bypasses validation by constructing the project internally. `targetDurationSeconds` updated to 6 to match (3 × 2s). Lets the post-pipeline-change health check finish in render time only without waiting on full-resolution clips.
+- **Creative Director agent prompts moved into the Prompts Manager.** `buildTreatmentPrompt` and `buildEvaluatePrompt` (in `server/lib/creativeDirectorPrompts.js`) now compute a flat view object and delegate to `buildPrompt('cd-treatment', view)` / `buildPrompt('cd-evaluate', view)`. The actual prompt text lives in `data/prompts/stages/cd-treatment.md` and `cd-evaluate.md` — editable from the Prompts Manager UI without code changes. The view object precomputes everything the template engine can't (aspect dims, render params, multi-frame list with timeline-position labels, scene strategy line, retry budget delta), so authors can rearrange wording and sections freely. `agentBridge.js` updated to await the now-async builders. Bundled source templates ship in `server/services/creativeDirector/prompts/` and are seeded into `data/prompts/stages/` on server boot via `seedCreativeDirectorPrompts()` — first-run installs get the stages automatically, and existing user customizations are never overwritten (the seeder only writes when files don't exist).
+- **Prompt template engine upgraded to support dot notation.** `server/lib/promptTemplate.js` ships an enhanced Mustache-flavored renderer that handles `{{a.b.c}}` lookups, object section scopes (`{{#user}}{{first}}{{/user}}`), array iteration with parent-scope fall-through (so `{{project.id}}` still resolves inside `{{#frames}}`), `{{.}}` for primitive iteration items, inverted sections (`{{^x}}`), and triple-mustache (`{{{x}}}`). Routed through `server/services/promptService.js#buildPrompt` so every PortOS template (including legacy ones like `cos-evaluate.md` that were silently leaving `{{metadata.context}}` literals in the output because the upstream toolkit's `\w+`-only regex doesn't match dots) now renders correctly. Storage stays in the toolkit (`stage-config.json`, `variables.json`, `.md` files); only the templating step is local. 17 engine tests + 12 CD prompt-rendering tests cover the surface.
+- **Creative Director multi-frame evaluator sampling.** The cognitive evaluator previously only Read the rendered video's frame-0 thumbnail, so 5s i2v scenes whose intent develops mid- or late-clip (archway appearing, light bloom, particles converging) were getting rejected even when the render delivered. The server now samples 5 evenly-spaced frames at render-completion time via a new `extractEvaluationFrames()` helper in `server/lib/ffmpeg.js` (probes total frames with `ffprobe`, then uses `ffmpeg -vf "select='eq(n,0)+eq(n,N/4)+eq(n,N/2)+eq(n,3*N/4)+eq(n,N-1)'" -vsync vfr`), writes them as `<jobId>-f1.jpg ... -f5.jpg` in `data/video-thumbnails/`, persists the basenames to `scene.evaluationFrames`, and `buildEvaluatePrompt` now lists every frame with timeline position tags ("start (0%)", "~50% through", "end (~100%)") and instructs the agent to Read each one. Includes explicit "intent that arrives late still counts as delivered" guidance to fix the false-reject pattern observed on the first real E2E run. Falls back to single-thumbnail Read when extraction fails (ffmpeg/ffprobe missing, probe returns 0 frames).
- **Creative Director stuck projects now self-recover** — `completionHook` always re-evaluates project state after any CD task completes (regardless of task kind), so legacy `scene`-kind tasks from before the treatment/evaluate split no longer leave a project frozen. PATCHing a scene to a terminal status (`accepted` or `failed`) also nudges the orchestrator to start the next scene immediately.
- **Creative Director projects auto-resume on server restart.** New `recoverInFlightProjects()` runs at boot (after `initMediaJobQueue` reclassifies running jobs as `failed (interrupted by restart)`): for every project in `planning`/`rendering`/`stitching`, it resets any scenes stuck in `rendering` or `evaluating` (whose in-memory listeners died with the previous process) back to `pending` and fires `advanceAfterSceneSettled` so the orchestrator picks up where it left off. Without this, a pm2 reload mid-render left the project frozen — scene status pointed at a dead job, no listener to advance.
- **Creative Director smoke-test fixture** — `POST /api/creative-director/smoke-test` (or the "Run smoke test" button on the CD list page) creates a deterministic 3-scene colored-ball project: scene 1 generates a red ball bouncing on white (text-to-video), scene 2 continues from scene 1's last frame with a "blue ball" prompt to verify the i2v honors a prompt-driven color change while preserving motion, scene 3 continues from scene 2 with the same prompt to verify pure i2v continuity. The fixture sets `disableAudio: true` (skips the mlx_video audio pass to roughly halve wall-clock per scene) and `autoAcceptScenes: true` (sceneRunner short-circuits the cognitive evaluator with a synthetic `accepted` evaluation, so a smoke run completes in render time only — no Claude in the loop). Adds `disableAudio` and `autoAcceptScenes` as CD project fields and plumbs them through to the queue params.
diff --git a/PLAN.md b/PLAN.md
index 412d7788bb..cf54599328 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -16,12 +16,13 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
The PR landed with full pipeline mechanics + auto-recovery + smoke-test fixture, but the first real E2E run (1 of 6 scenes accepted on subjective grounds, 3 of 6 rejected, terminated cleanly) surfaced concrete improvement targets:
-- [ ] **Multi-frame evaluator sampling.** The cognitive evaluator currently reads only the rendered video's thumbnail (typically frame 0). For 5s i2v clips, scene intent that develops mid-or-late (archway appearing, light bloom, particles) gets missed and the evaluator rejects renders that actually delivered. Sample 3–5 frames evenly across the video at render-completion time (extract via ffmpeg `select='eq(n,0)+eq(n,N/4)+eq(n,N/2)+eq(n,3*N/4)+eq(n,N-1)'`), save as `<jobId>-f1.jpg ... -f5.jpg`, and update `buildEvaluatePrompt` to instruct the agent to Read all of them and judge intent across the timeline. Most-impactful single change.
+- [x] ~~**Multi-frame evaluator sampling.**~~ Done — `extractEvaluationFrames` in `server/lib/ffmpeg.js` probes total frames and uses ffmpeg `select='eq(n,0)+...'` to write `<jobId>-f1.jpg ... -f5.jpg`; `sceneRunner.handleRenderCompleted` calls it before enqueuing the evaluator and persists the basenames to `scene.evaluationFrames`; `buildEvaluatePrompt` now lists every sampled frame with timeline tags ("start (0%)", "~50% through", "end (~100%)") and instructs the agent to Read each one with explicit late-intent guidance. Falls back to single thumbnail when extraction fails.
- [ ] **i2v continuity fidelity.** `useContinuationFromPrior: true` currently feeds the prior scene's last frame as `sourceImagePath` but doesn't pin `imageStrength`. Renders sometimes drift hard from the seed (a "blue ball" continuation generates a totally new scene that loosely starts from the seed). Surface `imageStrength` as a per-scene knob in the treatment schema (default ~0.85 for continuation scenes, lower if the prompt deliberately changes the subject) and pipe it through `sceneRunner.params`.
- [ ] **Audio continuity across scenes.** mlx-video-with-audio generates audio per-clip; concatenated scenes have audible cuts at scene boundaries. Either render scenes silently and add a single backing audio pass at stitch time, or apply a short crossfade in `videoTimeline/local.js#buildFfmpegArgs` (already does video crossfades — extend to audio with `acrossfade`).
- [ ] **Duplicate evaluator spawn dedup.** During the long E2E run, server logs showed `Task already being spawned, skipping duplicate` followed seconds later by a *second* agent spawning for the exact same task id. The CoS task lane logic ends up double-acquiring. Reproduce in a unit test against `taskSchedule` / `agentLifecycle` and fix the de-dup window.
- [ ] **Render slowness on long sessions.** Per-scene render time degraded from ~3.5 min (early) to 10–30 min (late) within one project — likely accumulated listeners + queue races. Profile after sustained use; the round-22 dedup work probably already helps; verify.
- [ ] **Auto-accept watchdog.** `autoAcceptScenes: true` skips the Claude evaluator entirely. Add a server-side sanity check (file exists, file size > 0, ffprobe can read at least 1 frame) before writing the synthetic accepted evaluation — without it a black/zero-frame render would still be marked accepted.
+- [x] ~~**Smoke-test cost reduction.**~~ Done — dropped `durationSeconds` 3s→2s, added a hidden `1:1-small` (384×384) aspect preset for the smoke fixture only (kept out of `ASPECT_RATIOS` so the user-facing dropdown is unchanged). Smoke run now ~63% cheaper in pixel-frame terms. Lets pipeline health checks complete in render time only.
### Other backlog
diff --git a/server/index.js b/server/index.js
index cd8ed83201..8a7d989062 100644
--- a/server/index.js
+++ b/server/index.js
@@ -85,6 +85,7 @@ import mediaJobsRoutes from './routes/mediaJobs.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
import { initMediaJobQueue } from './services/mediaJobQueue/index.js';
import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';
+import { seedCreativeDirectorPrompts } from './services/creativeDirector/promptSeeder.js';
import imageVideoModelsRoutes from './routes/imageVideoModels.js';
import sdapiRoutes from './routes/sdapi.js';
import openclawRoutes from './routes/openclaw.js';
@@ -457,6 +458,13 @@ ensureSelf()
// orchestrator so projects don't sit frozen waiting for listeners that
// no longer exist. Doesn't block startup.
recoverInFlightProjects().catch((e) => console.log(`⚠️ CD boot recovery failed: ${e.message}`));
+ // Seed cd-treatment / cd-evaluate prompt stages on first run if the user
+ // hasn't customized them yet. data/prompts/ is gitignored so without
+ // this, fresh installs would break with "Stage cd-treatment not found"
+ // the first time the Creative Director enqueues an agent task.
+ seedCreativeDirectorPrompts()
+ .then(() => aiToolkit.services.prompts.init())
+ .catch((e) => console.log(`⚠️ CD prompt seeder failed: ${e.message}`));
})
.then(() => {
// Start server only after sync log + media job queue are initialized.
diff --git a/server/lib/creativeDirectorPresets.js b/server/lib/creativeDirectorPresets.js
index 20e47ee23e..9fcddc8a2f 100644
--- a/server/lib/creativeDirectorPresets.js
+++ b/server/lib/creativeDirectorPresets.js
@@ -11,10 +11,18 @@
// Width/height pairs are 64-aligned (videoGen rounds down to multiples of
// 64 anyway) and chosen for sensible LTX defaults.
+//
+// `1:1-small` is intentionally NOT exported in ASPECT_RATIOS — it's a
+// hidden preset used only by the smoke-test fixture (cuts pixel count by
+// ~44% vs 1:1 to keep the CI/dev health-check render time low). The smoke
+// route bypasses the route-level enum validation (it calls createProject
+// directly), so the smaller dimensions land in the render queue without
+// the user-facing dropdown ever seeing it.
export const ASPECT_PRESETS = Object.freeze({
'16:9': { width: 768, height: 432 },
'9:16': { width: 432, height: 768 },
'1:1': { width: 512, height: 512 },
+ '1:1-small': { width: 384, height: 384 },
});
// `steps` and `guidance` are mlx_video knobs. `fps` is the render frame
diff --git a/server/lib/creativeDirectorPrompts.js b/server/lib/creativeDirectorPrompts.js
index 4d2920e289..d5fac75de3 100644
--- a/server/lib/creativeDirectorPrompts.js
+++ b/server/lib/creativeDirectorPrompts.js
@@ -1,183 +1,132 @@
/**
- * Creative Director — agent prompt templates.
+ * Creative Director — agent prompt builders.
*
- * Only two cognitive steps require an agent:
+ * Two cognitive steps require an agent:
* - `treatment`: write the story + scene plan
- * - `evaluate` : judge a single rendered scene against the style spec
+ * - `evaluate` : judge a freshly-rendered scene against the style spec
*
- * Programmatic steps (per-scene render orchestration, final stitch) live
- * server-side in services/creativeDirector/{sceneRunner,stitchRunner}.js
+ * Both build their prompt text by calling `buildPrompt(stageName, view)`
+ * against templates registered in the Prompts Manager
+ * (`data/prompts/stages/cd-treatment.md`, `cd-evaluate.md`). The agent text
+ * is editable from the UI; this module's only job is to compute the
+ * **view object** the template renders against — i.e. the precomputed
+ * scalars/sections (aspect dimensions, render params, multi-frame list,
+ * timeline-position labels, retry deltas) that the template engine alone
+ * can't derive.
+ *
+ * Programmatic non-cognitive steps (per-scene render orchestration, final
+ * stitch) live in services/creativeDirector/{sceneRunner,stitchRunner}.js
* and never spawn an agent.
*/
-import { ASPECT_PRESETS, QUALITY_PRESETS, presetToRenderParams } from './creativeDirectorPresets.js';
+import {
+ ASPECT_PRESETS,
+ QUALITY_PRESETS,
+ presetToRenderParams,
+} from './creativeDirectorPresets.js';
import { PORTOS_API_URL } from './ports.js';
+import { buildPrompt } from '../services/promptService.js';
+
+// Shared project-block view used by both prompt stages. Defaults out
+// nullable fields to `''` so the templates' `{{#x}}`/`{{^x}}` Mustache-spec
+// emptiness checks fire on missing values without each template having to
+// guard `null` separately.
+function buildProjectView(project) {
+ return {
+ id: project.id,
+ name: project.name,
+ aspectRatio: project.aspectRatio,
+ quality: project.quality,
+ modelId: project.modelId,
+ targetDurationSeconds: project.targetDurationSeconds,
+ targetDurationMinutes: Math.round((project.targetDurationSeconds || 0) / 60),
+ collectionId: project.collectionId,
+ startingImageFile: project.startingImageFile || '',
+ styleSpec: project.styleSpec || '',
+ userStory: project.userStory || '',
+ };
+}
-// Common header. Project context the agent always needs to know.
-function projectBlock(project) {
- const aspect = ASPECT_PRESETS[project.aspectRatio];
- const q = QUALITY_PRESETS[project.quality];
- return [
- `## Project: "${project.name}" (id: ${project.id})`,
- ``,
- `- Aspect ratio: ${project.aspectRatio} (${aspect.width}×${aspect.height})`,
- `- Quality: ${project.quality} (${q.steps} denoising steps, guidance ${q.guidance}, ${q.fps}fps)`,
- `- Model: ${project.modelId}`,
- `- Target episode duration: ${project.targetDurationSeconds}s (~${Math.round(project.targetDurationSeconds / 60)} min)`,
- `- Collection id (group all rendered segments here): ${project.collectionId}`,
- project.startingImageFile ? `- Starting image: /data/images/${project.startingImageFile}` : `- Starting image: none`,
- ``,
- `## Style spec (apply to every prompt)`,
- project.styleSpec || '(none — derive a coherent visual language from the project name + first scene intent)',
- ``,
- ].join('\n');
+function buildTreatmentView(project) {
+ const aspect = ASPECT_PRESETS[project.aspectRatio] || { width: 0, height: 0 };
+ const quality = QUALITY_PRESETS[project.quality] || { steps: 0, guidance: 0, fps: 0 };
+ // The example block in the JSON output contract shows a literal value
+ // for `sourceImageFile` — either a quoted filename or `null`. Precompute
+ // because the template engine has no quoting helpers.
+ const startingImageFileLiteral = project.startingImageFile
+ ? `"${project.startingImageFile}"`
+ : 'null';
+ return {
+ project: buildProjectView(project),
+ aspect,
+ quality,
+ apiUrl: PORTOS_API_URL,
+ startingImageFileLiteral,
+ };
}
-export function buildTreatmentPrompt(project) {
- const userStoryBlock = project.userStory
- ? `## User-supplied story\n\nThe user provided this outline. Honor it; expand/refine but don't contradict.\n\n${project.userStory}\n\n`
- : `## Story\n\nThe user did not supply a story. Invent one that suits the style spec and target duration.\n\n`;
+export async function buildTreatmentPrompt(project) {
+ const view = buildTreatmentView(project);
+ return buildPrompt('cd-treatment', view);
+}
- return [
- `# Creative Director — Treatment task`,
- ``,
- `You are the Creative Director for a long-form generated-video project. Your job in this task is to produce a TREATMENT — a complete scene-by-scene plan that the server will then render scene-by-scene (no further agent task is needed for rendering — the server orchestrates that). After each render lands, a separate short evaluation task will judge it.`,
- ``,
- projectBlock(project),
- userStoryBlock,
- `## Task`,
- ``,
- `1. Design a story arc that fits ~${project.targetDurationSeconds}s of total runtime. Think in scenes that are 1–10 seconds each (most should be 4–6s; reserve short ones for cuts and long ones for held shots).`,
- `2. Each scene should have a clear visual intent and a render prompt that incorporates the style spec.`,
- `3. Decide for each scene whether it continues from the previous scene's last frame (\`useContinuationFromPrior: true\`) or starts from a new image (\`useContinuationFromPrior: false\`, optionally with a \`sourceImageFile\` basename if you want to seed from a specific gallery image). Scene 1 either uses the project starting image (if provided — copy its filename into \`sourceImageFile\`) or starts as text-to-video.`,
- `4. Don't pad with filler; if the natural arc is shorter than the target, that's fine — produce fewer scenes.`,
- ``,
- `## Output contract`,
- ``,
- `Issue ONE HTTP request to update the project with the treatment, then exit:`,
- ``,
- `\`\`\``,
- `PATCH ${PORTOS_API_URL}/api/creative-director/${project.id}/treatment`,
- `Content-Type: application/json`,
- ``,
- `{`,
- ` "logline": "<one-sentence high-concept>",`,
- ` "synopsis": "<short paragraph synopsis>",`,
- ` "scenes": [`,
- ` {`,
- ` "sceneId": "scene-1",`,
- ` "order": 0,`,
- ` "intent": "<what this scene does narratively/visually>",`,
- ` "prompt": "<full render prompt with style spec inlined>",`,
- ` "negativePrompt": "<optional>",`,
- ` "durationSeconds": 5,`,
- ` "useContinuationFromPrior": false,`,
- ` "sourceImageFile": ${project.startingImageFile ? `"${project.startingImageFile}"` : 'null'}`,
- ` },`,
- ` { "sceneId": "scene-2", "order": 1, ..., "useContinuationFromPrior": true }`,
- ` ]`,
- `}`,
- `\`\`\``,
- ``,
- `On a 200 response your task is complete. The server will automatically begin rendering scene 1 — do not create any additional tasks yourself.`,
- ``,
- `If the PATCH returns 4xx, fix the validation issue (read the error body) and retry. Do not retry on 5xx more than twice.`,
- ].join('\n');
+function frameTimelineLabel(i, total) {
+ if (total <= 1) return 'only frame';
+ const pct = Math.round((i / (total - 1)) * 100);
+ if (i === 0) return 'start (0%)';
+ if (i === total - 1) return `end (~${pct}%)`;
+ return `~${pct}% through`;
}
-export function buildEvaluatePrompt(project, scene) {
+function buildEvaluateView(project, scene) {
+ const aspect = ASPECT_PRESETS[project.aspectRatio] || { width: 0, height: 0 };
+ const quality = QUALITY_PRESETS[project.quality] || { steps: 0, guidance: 0, fps: 0 };
const renderParams = presetToRenderParams({
aspectRatio: project.aspectRatio,
quality: project.quality,
durationSeconds: scene.durationSeconds,
});
- const renderedId = scene.renderedJobId || '<unknown>';
- return [
- `# Creative Director — Scene evaluation task`,
- ``,
- `Your ONLY job is to evaluate a freshly-rendered scene and decide whether it works. The render itself was done by the server (no upstream task to do); the rendered video and its thumbnail are already on disk.`,
- ``,
- projectBlock(project),
- `## Scene to evaluate`,
- ``,
- `- Scene id: \`${scene.sceneId}\` (${scene.order + 1}/${project.treatment?.scenes?.length || '?'})`,
- `- Intent: ${scene.intent}`,
- `- Render prompt: ${JSON.stringify(scene.prompt)}`,
- `- Render: \`${renderParams.width}×${renderParams.height}\`, ${renderParams.numFrames} frames @ ${renderParams.fps}fps`,
- `- Strategy: ${scene.useContinuationFromPrior ? 'continued from prior scene last-frame' : (scene.sourceImageFile ? `seeded from image \`${scene.sourceImageFile}\`` : 'text-to-video')}`,
- `- Retry count: ${scene.retryCount || 0} (max 3)`,
- `- Rendered video: \`/data/videos/${renderedId}.mp4\``,
- `- Thumbnail (use this for evaluation): \`/data/video-thumbnails/${renderedId}.jpg\``,
- ``,
- `## Step 1 — Read the thumbnail using your vision capability`,
- ``,
- `Open the thumbnail file (Read tool) and inspect the frame.`,
- ``,
- `## Step 2 — Score against three dimensions`,
- ``,
- `1. **Style adherence**: does it match the project style spec?`,
- `2. **Continuity**: does it flow from the prior accepted scene's tone, color, characters? (If this is scene 1, just check it stands on its own.)`,
- `3. **Scene intent**: does it actually depict "${scene.intent}"?`,
- ``,
- `## Step 3 — Decide`,
- ``,
- `Issue ONE PATCH to record your verdict, then exit. Do not request renders, do not call last-frame, do not create follow-up tasks — the server handles all of that.`,
- ``,
- `\`\`\``,
- `PATCH ${PORTOS_API_URL}/api/creative-director/${project.id}/scene/${scene.sceneId}`,
- `Content-Type: application/json`,
- `\`\`\``,
- ``,
- `**If the render is acceptable** (good enough — perfect is the enemy of done):`,
- `\`\`\`json`,
- `{`,
- ` "status": "accepted",`,
- ` "evaluation": {`,
- ` "accepted": true,`,
- ` "score": 0.0–1.0,`,
- ` "notes": "<one-sentence reason>",`,
- ` "sampledAt": "<ISO 8601 timestamp>"`,
- ` }`,
- `}`,
- `\`\`\``,
- ``,
- `Then (and ONLY in the accepted case) add the rendered video to the project's collection:`,
- `\`\`\``,
- `POST ${PORTOS_API_URL}/api/media/collections/${project.collectionId}/items`,
- `Content-Type: application/json`,
- ``,
- `{ "kind": "video", "ref": "${renderedId}" }`,
- `\`\`\``,
- `Do NOT issue this POST for the retry or failed branches below — rejected renders should not enter the collection.`,
- ``,
- `**If the render misses the mark and retries are still available** (\`retryCount < 3\`): tweak the prompt and request a re-render. The server will run the new render and then send you back here for another evaluation.`,
- `\`\`\`json`,
- `{`,
- ` "status": "pending",`,
- ` "prompt": "<refined render prompt>",`,
- ` "retryCount": ${(scene.retryCount || 0) + 1},`,
- ` "evaluation": {`,
- ` "accepted": false,`,
- ` "score": 0.0–1.0,`,
- ` "notes": "<what to fix>",`,
- ` "sampledAt": "<ISO 8601 timestamp>"`,
- ` }`,
- `}`,
- `\`\`\``,
- ``,
- `**If retries are exhausted** (\`retryCount >= 3\`) and the render is still not acceptable, give up on this scene:`,
- `\`\`\`json`,
- `{`,
- ` "status": "failed",`,
- ` "evaluation": {`,
- ` "accepted": false,`,
- ` "score": 0.0–1.0,`,
- ` "notes": "<why no further retry helps>",`,
- ` "sampledAt": "<ISO 8601 timestamp>"`,
- ` }`,
- `}`,
- `\`\`\``,
- ``,
- `Then exit. The server picks up from there.`,
- ].join('\n');
+ const renderedJobId = scene.renderedJobId || '<unknown>';
+ const totalScenes = project.treatment?.scenes?.length;
+ const positionLabel = totalScenes
+ ? `${(scene.order ?? 0) + 1}/${totalScenes}`
+ : `${(scene.order ?? 0) + 1}/?`;
+ const evaluationFrames = Array.isArray(scene.evaluationFrames) ? scene.evaluationFrames : [];
+ const frames = evaluationFrames.map((filename, i) => ({
+ position: i + 1,
+ filename,
+ label: frameTimelineLabel(i, evaluationFrames.length),
+ }));
+ // Precomputed so the JSON example in the template can render `retryCount`
+ // for the next attempt without the engine doing arithmetic.
+ const nextRetryCount = (scene.retryCount || 0) + 1;
+ const strategy = scene.useContinuationFromPrior
+ ? 'continued from prior scene last-frame'
+ : (scene.sourceImageFile
+ ? `seeded from image \`${scene.sourceImageFile}\``
+ : 'text-to-video');
+ return {
+ project: buildProjectView(project),
+ aspect,
+ quality,
+ apiUrl: PORTOS_API_URL,
+ scene: {
+ sceneId: scene.sceneId,
+ intent: scene.intent,
+ promptJson: JSON.stringify(scene.prompt),
+ renderedJobId,
+ retryCount: scene.retryCount || 0,
+ nextRetryCount,
+ positionLabel,
+ strategy,
+ },
+ render: renderParams,
+ multiFrame: frames.length >= 2,
+ evaluationFrames: frames,
+ };
+}
+
+export async function buildEvaluatePrompt(project, scene) {
+ const view = buildEvaluateView(project, scene);
+ return buildPrompt('cd-evaluate', view);
}
diff --git a/server/lib/creativeDirectorPrompts.test.js b/server/lib/creativeDirectorPrompts.test.js
new file mode 100644
index 0000000000..8336c71ce3
--- /dev/null
+++ b/server/lib/creativeDirectorPrompts.test.js
@@ -0,0 +1,170 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFile } from 'fs/promises';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { applyTemplate } from './promptTemplate.js';
+
+// Resolve the templates from disk so the tests exercise the real Prompts
+// Manager templates — if a future edit breaks an unwrapped {{var}} or a
+// mistyped section name, the test catches it.
+const STAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'data', 'prompts', 'stages');
+const loadStage = async (stageName) => readFile(join(STAGES_DIR, `${stageName}.md`), 'utf-8');
+
+// Mock the prompt-service buildPrompt to render the on-disk template through
+// the same engine production uses, without needing a live aiToolkit instance.
+vi.mock('../services/promptService.js', () => ({
+ buildPrompt: vi.fn(async (stageName, view) => {
+ const template = await loadStage(stageName);
+ return applyTemplate(template, view);
+ }),
+}));
+
+const { buildTreatmentPrompt, buildEvaluatePrompt } = await import('./creativeDirectorPrompts.js');
+
+const baseProject = {
+ id: 'cd-1',
+ name: 'Test Project',
+ aspectRatio: '16:9',
+ quality: 'standard',
+ modelId: 'ltx-video',
+ targetDurationSeconds: 30,
+ styleSpec: 'neon noir',
+ collectionId: 'col-1',
+ startingImageFile: null,
+ userStory: null,
+ treatment: { scenes: [{}, {}, {}] },
+};
+
+const baseScene = {
+ sceneId: 'scene-2',
+ order: 1,
+ intent: 'archway opens to reveal city',
+ prompt: 'long shot, archway opens',
+ durationSeconds: 5,
+ useContinuationFromPrior: false,
+ retryCount: 0,
+ renderedJobId: 'job-abc-123',
+};
+
+beforeEach(() => {
+ // Templates are loaded fresh from disk — no state to reset.
+});
+
+describe('buildTreatmentPrompt — template-rendered output', () => {
+ it('renders project header and resolves aspect/quality dimensions', async () => {
+ const out = await buildTreatmentPrompt(baseProject);
+ expect(out).toContain('# Creative Director — Treatment task');
+ expect(out).toContain('"Test Project" (id: cd-1)');
+ // Aspect dims come from ASPECT_PRESETS['16:9'] = 768×432.
+ expect(out).toContain('Aspect ratio: 16:9 (768×432)');
+ // Quality dims from QUALITY_PRESETS.standard = { steps: 20, guidance: 3, fps: 24 }.
+ expect(out).toContain('Quality: standard (20 denoising steps, guidance 3, 24fps)');
+ expect(out).toContain('Target episode duration: 30s (~1 min)');
+ });
+
+ it('uses the "Story" branch when no userStory provided', async () => {
+ const out = await buildTreatmentPrompt(baseProject);
+ expect(out).toContain('## Story');
+ expect(out).toContain('The user did not supply a story');
+ expect(out).not.toContain('## User-supplied story');
+ });
+
+ it('uses the "User-supplied story" branch when userStory is set', async () => {
+ const out = await buildTreatmentPrompt({ ...baseProject, userStory: 'A heist on Mars.' });
+ expect(out).toContain('## User-supplied story');
+ expect(out).toContain('A heist on Mars.');
+ expect(out).not.toContain('The user did not supply a story');
+ });
+
+ it('renders sourceImageFile literal as JSON null when no starting image', async () => {
+ const out = await buildTreatmentPrompt(baseProject);
+ expect(out).toContain('"sourceImageFile": null');
+ });
+
+ it('renders sourceImageFile literal as a quoted filename when starting image is set', async () => {
+ const out = await buildTreatmentPrompt({ ...baseProject, startingImageFile: 'hero.png' });
+ expect(out).toContain('"sourceImageFile": "hero.png"');
+ expect(out).toContain('Starting image: /data/images/hero.png');
+ });
+});
+
+describe('buildEvaluatePrompt — multi-frame sampling', () => {
+ it('lists every sampled frame with timeline-position tags when frames are present', async () => {
+ const scene = {
+ ...baseScene,
+ evaluationFrames: [
+ 'job-abc-123-f1.jpg',
+ 'job-abc-123-f2.jpg',
+ 'job-abc-123-f3.jpg',
+ 'job-abc-123-f4.jpg',
+ 'job-abc-123-f5.jpg',
+ ],
+ };
+ const out = await buildEvaluatePrompt(baseProject, scene);
+ for (const f of scene.evaluationFrames) {
+ expect(out).toContain(`/data/video-thumbnails/${f}`);
+ }
+ expect(out).toContain('start (0%)');
+ expect(out).toContain('end (~100%)');
+ expect(out).toContain('~50% through');
+ expect(out).toContain('Read EACH ONE');
+ expect(out).toContain('Read every sampled frame');
+ expect(out).toContain('Intent that arrives late still counts as delivered');
+ });
+
+ it('falls back to the single thumbnail line when no frames were extracted', async () => {
+ const scene = { ...baseScene, evaluationFrames: [] };
+ const out = await buildEvaluatePrompt(baseProject, scene);
+ expect(out).toContain(`/data/video-thumbnails/${scene.renderedJobId}.jpg`);
+ expect(out).toContain('Read the thumbnail using your vision capability');
+ expect(out).not.toContain('Read EACH ONE');
+ });
+
+ it('falls back when evaluationFrames is missing entirely (legacy projects)', async () => {
+ const scene = { ...baseScene };
+ delete scene.evaluationFrames;
+ const out = await buildEvaluatePrompt(baseProject, scene);
+ expect(out).toContain(`/data/video-thumbnails/${scene.renderedJobId}.jpg`);
+ expect(out).not.toContain('Sampled frames across the timeline');
+ });
+});
+
+describe('buildEvaluatePrompt — scene metadata', () => {
+ it('includes scene position label, retry budget, and quote-escaped prompt', async () => {
+ const scene = {
+ ...baseScene,
+ evaluationFrames: [],
+ retryCount: 1,
+ prompt: 'a "smart" prompt with quotes',
+ };
+ const out = await buildEvaluatePrompt(baseProject, scene);
+ expect(out).toContain('Scene id: `scene-2` (2/3)');
+ expect(out).toContain('Retry count: 1 (max 3)');
+ // promptJson view value is JSON.stringify so embedded quotes are escaped.
+ expect(out).toContain('"a \\"smart\\" prompt with quotes"');
+ expect(out).toContain('"retryCount": 2');
+ });
+
+ it('reports text-to-video strategy when no continuation and no source image', async () => {
+ const out = await buildEvaluatePrompt(baseProject, { ...baseScene, evaluationFrames: [] });
+ expect(out).toContain('Strategy: text-to-video');
+ });
+
+ it('reports continuation strategy when useContinuationFromPrior is true', async () => {
+ const out = await buildEvaluatePrompt(baseProject, {
+ ...baseScene,
+ evaluationFrames: [],
+ useContinuationFromPrior: true,
+ });
+ expect(out).toContain('Strategy: continued from prior scene last-frame');
+ });
+
+ it('reports seeded-image strategy when sourceImageFile is set', async () => {
+ const out = await buildEvaluatePrompt(baseProject, {
+ ...baseScene,
+ evaluationFrames: [],
+ sourceImageFile: 'hero.png',
+ });
+ expect(out).toContain('Strategy: seeded from image `hero.png`');
+ });
+});
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index ce5650d01c..dfb0de83be 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -84,6 +84,94 @@ export const generateThumbnail = async (videoPath, jobId) => {
});
};
+// Probe the video's total frame count. Tries the fast metadata path first
+// (`stream=nb_frames`) and falls back to an actual frame count
+// (`-count_frames stream=nb_read_frames`) for containers that don't expose
+// nb_frames in their header. Returns null when both paths fail or the
+// reported count is unusable.
+const probeFrameCount = async (videoPath) => {
+ const ffprobe = await findFfprobe();
+ if (!ffprobe) return null;
+ const run = async (countFrames) => {
+ const args = [
+ '-v', 'error',
+ ...(countFrames ? ['-count_frames'] : []),
+ '-select_streams', 'v:0',
+ '-show_entries', `stream=${countFrames ? 'nb_read_frames' : 'nb_frames'}`,
+ '-of', 'default=nokey=1:noprint_wrappers=1',
+ videoPath,
+ ];
+ const { stdout } = await execFileAsync(ffprobe, args, { timeout: 15000 }).catch(() => ({ stdout: '' }));
+ const n = parseInt((stdout || '').trim(), 10);
+ return Number.isFinite(n) && n > 0 ? n : null;
+ };
+ return (await run(false)) ?? (await run(true));
+};
+
+// Extract `count` evenly-spaced frames across the video for the cognitive
+// evaluator. Saved as `<jobId>-f1.jpg ... -f<count>.jpg` in
+// `data/video-thumbnails/`. Returns the array of basenames in timeline order
+// on success, or `[]` on any failure — callers should fall back to the
+// single-frame thumbnail rather than aborting.
+//
+// Why this exists: i2v scenes whose intent develops mid-or-late (archway
+// appears at 60%, light bloom at 80%) get rejected by the evaluator when it
+// only sees frame 0. Sampling 5 frames lets the agent judge intent across
+// the entire timeline rather than just the opening pose.
+export const extractEvaluationFrames = async (videoPath, jobId, count = 5) => {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return [];
+
+ const totalFrames = await probeFrameCount(videoPath);
+ if (!totalFrames) return [];
+
+ await ensureDir(PATHS.videoThumbnails);
+
+ const frameIndices = totalFrames <= count
+ ? Array.from({ length: totalFrames }, (_, i) => i)
+ : (() => {
+ const last = totalFrames - 1;
+ // Quartile sampling (start, 25%, 50%, 75%, end). Generalizes to any
+ // `count` ≥ 2 — for count=5 this matches the spec exactly.
+ const positions = [];
+ if (count === 1) return [0];
+ for (let i = 0; i < count; i++) {
+ positions.push(Math.round((i * last) / (count - 1)));
+ }
+ // Dedup in case rounding collapses adjacent indices on tiny clips.
+ return Array.from(new Set(positions));
+ })();
+
+ // Filter expression: select frames matching any of the target indices.
+ // Single-quoting the expression lets ffmpeg's filter parser treat the
+ // commas inside `eq(n,X)` as expression args rather than filter-chain
+ // separators. `-vsync vfr` prevents the image2 muxer from padding output
+ // to maintain input fps (which would re-emit each match repeatedly).
+ const selectExpr = frameIndices.map((i) => `eq(n,${i})`).join('+');
+ const outPattern = join(PATHS.videoThumbnails, `${jobId}-f%d.jpg`);
+
+ const ok = await new Promise((resolve) => {
+ const proc = spawn(ffmpeg, [
+ '-i', videoPath,
+ '-vf', `select='${selectExpr}'`,
+ '-vsync', 'vfr',
+ '-q:v', '5',
+ '-y',
+ outPattern,
+ ], { stdio: 'ignore' });
+ proc.on('close', (code) => resolve(code === 0));
+ proc.on('error', (err) => {
+ console.log(`⚠️ ffmpeg multi-frame extract failed to spawn: ${err.message}`);
+ resolve(false);
+ });
+ });
+
+ if (!ok) return [];
+ // ffmpeg's image2 muxer numbers output starting at 1 in match order, so
+ // the basenames map 1:1 to our frameIndices in timeline order.
+ return frameIndices.map((_, i) => `${jobId}-f${i + 1}.jpg`);
+};
+
// MP4s with the moov atom at the END require browsers to download the entire
// file before they can render the first-frame poster on preload="metadata".
// Remux with -movflags +faststart to move moov to the front. Stream copy —
diff --git a/server/lib/promptTemplate.js b/server/lib/promptTemplate.js
new file mode 100644
index 0000000000..497420e89a
--- /dev/null
+++ b/server/lib/promptTemplate.js
@@ -0,0 +1,120 @@
+/**
+ * Enhanced prompt template engine — Mustache-flavored, dot-notation aware.
+ *
+ * This replaces the templating in `portos-ai-toolkit`'s prompts service so
+ * PortOS templates can reference nested objects naturally:
+ *
+ * {{project.name}} — looks up `data.project.name`
+ * {{#scene}}{{intent}}{{/scene}} — opens scope into `data.scene`, then
+ * `intent` resolves against the scene
+ * {{#frames}} {{label}} {{/frames}} — iterates the array, opening scope
+ * into each item per iteration
+ * {{^frames}}fallback{{/frames}} — renders only when frames is empty/falsy
+ * {{{html}}} — emits the value as-is (no future-proof
+ * escaping; aligns with markdown prompts)
+ *
+ * Why this exists: the upstream toolkit engine matches `\w+` for keys, which
+ * silently drops every `{{a.b}}` reference and leaves the literal text in
+ * the output — a real bug today (cos-evaluate.md `{{metadata.context}}` is
+ * dead code). Routing every prompt through this engine fixes those legacy
+ * templates AND lets new templates author dotted lookups directly.
+ *
+ * The engine is intentionally small: lookups, sections, inverted sections,
+ * triple-mustache. No partials, no lambdas, no caching — prompts are built
+ * once per agent task, the cost is negligible, and a smaller surface keeps
+ * the templates predictable for users editing them in the Prompts Manager.
+ */
+
+// Resolve a dotted key path against a context, walking one segment at a
+// time. Returns `undefined` for any miss so the caller can decide whether
+// to render an empty string (variable miss) or skip a section (falsy guard).
+const resolveKey = (context, key) => {
+ if (!context || typeof context !== 'object') return undefined;
+ if (key === '.') {
+ // During primitive-array iteration the engine stashes the current item
+ // under the literal `'.'` key on a wrapper object — return that
+ // ahead of the wrapper itself. For object-array iteration no `'.'` is
+ // set; fall back to the spread context.
+ return Object.prototype.hasOwnProperty.call(context, '.') ? context['.'] : context;
+ }
+ const segments = key.split('.');
+ let cursor = context;
+ for (const segment of segments) {
+ if (cursor == null || typeof cursor !== 'object') return undefined;
+ cursor = cursor[segment];
+ }
+ return cursor;
+};
+
+// Mustache-truthy: empty arrays and empty strings are falsy (matches Mustache
+// spec; deliberately stricter than JS truthiness so optional sections behave
+// intuitively when a list comes back empty).
+const isTruthySectionValue = (value) => {
+ if (value == null || value === false) return false;
+ if (Array.isArray(value)) return value.length > 0;
+ if (typeof value === 'string') return value.length > 0;
+ return true;
+};
+
+const SECTION_RE = /\{\{#([\w.]+)\}\}([\s\S]*?)\{\{\/\1\}\}/g;
+const INVERTED_RE = /\{\{\^([\w.]+)\}\}([\s\S]*?)\{\{\/\1\}\}/g;
+const TRIPLE_RE = /\{\{\{([\w.]+)\}\}\}/g;
+const VAR_RE = /\{\{([\w.]+)\}\}/g;
+
+// Sections must be processed before inverted sections to avoid the inverted
+// regex matching a `{{^x}}...{{/x}}` that's nested inside a `{{#y}}`. Both
+// run before variable substitution so the section bodies can themselves
+// reference variables resolved against the section's scope. We loop until
+// no further rewrites happen so nested sections at any depth resolve.
+export function applyTemplate(template, data = {}) {
+ if (typeof template !== 'string') return '';
+ let result = template;
+ let prev;
+ // Sections (including nested) — repeat until stable.
+ do {
+ prev = result;
+ result = result.replace(SECTION_RE, (_match, key, content) => {
+ const value = resolveKey(data, key);
+ if (!isTruthySectionValue(value)) return '';
+ if (Array.isArray(value)) {
+ return value
+ .map((item) => {
+ // Mustache spec: when iterating an array of primitives, `{{.}}`
+ // refers to the current item; when iterating objects, the item
+ // becomes the new context (with the parent context still
+ // shadowed for the duration of the section body).
+ const itemCtx = (item && typeof item === 'object') ? { ...data, ...item } : { ...data, '.': item };
+ return applyTemplate(content, itemCtx);
+ })
+ .join('');
+ }
+ if (value && typeof value === 'object') {
+ // Object section — narrow the context by spreading the object on
+ // top of the parent so dotted lookups inside still see ambient
+ // variables (matches the cos-agent-briefing pattern of opening
+ // {{#task}} then referencing {{task.id}} or just {{id}}).
+ return applyTemplate(content, { ...data, ...value });
+ }
+ // Truthy primitive (non-empty string, true, number) — keep parent
+ // context, just render the body.
+ return applyTemplate(content, data);
+ });
+ result = result.replace(INVERTED_RE, (_match, key, content) => {
+ const value = resolveKey(data, key);
+ return isTruthySectionValue(value) ? '' : applyTemplate(content, data);
+ });
+ } while (result !== prev);
+
+ // Triple-mustache emits raw value (already-formatted markdown blocks pass
+ // through without HTML-escape semantics — we don't HTML-escape anyway, but
+ // surface the distinction so authors can document intent.)
+ result = result.replace(TRIPLE_RE, (_match, key) => {
+ const value = resolveKey(data, key);
+ return value == null ? '' : String(value);
+ });
+ result = result.replace(VAR_RE, (_match, key) => {
+ const value = resolveKey(data, key);
+ return value == null ? '' : String(value);
+ });
+ return result;
+}
diff --git a/server/lib/promptTemplate.test.js b/server/lib/promptTemplate.test.js
new file mode 100644
index 0000000000..8299c0283d
--- /dev/null
+++ b/server/lib/promptTemplate.test.js
@@ -0,0 +1,101 @@
+import { describe, it, expect } from 'vitest';
+import { applyTemplate } from './promptTemplate.js';
+
+describe('applyTemplate — variables', () => {
+ it('substitutes flat keys', () => {
+ expect(applyTemplate('Hello {{name}}', { name: 'World' })).toBe('Hello World');
+ });
+
+ it('substitutes nested keys via dot notation', () => {
+ expect(applyTemplate('Hi {{user.first}} {{user.last}}', {
+ user: { first: 'Adam', last: 'E' },
+ })).toBe('Hi Adam E');
+ });
+
+ it('returns empty string for missing keys (does not leak literal {{x}})', () => {
+ expect(applyTemplate('a={{a}} b={{b}}', { a: 1 })).toBe('a=1 b=');
+ });
+
+ it('handles deep nesting', () => {
+ expect(applyTemplate('{{a.b.c.d}}', { a: { b: { c: { d: 'deep' } } } })).toBe('deep');
+ });
+
+ it('triple-mustache emits the raw value', () => {
+ // Behaves the same as double for plain strings (we don't HTML-escape)
+ // but documents intent for templates that emit pre-formatted markdown.
+ expect(applyTemplate('{{{html}}}', { html: '## heading' })).toBe('## heading');
+ });
+});
+
+describe('applyTemplate — sections', () => {
+ it('renders a truthy section', () => {
+ expect(applyTemplate('{{#flag}}yes{{/flag}}', { flag: true })).toBe('yes');
+ });
+
+ it('skips a falsy section', () => {
+ expect(applyTemplate('before{{#flag}}MID{{/flag}}after', { flag: false })).toBe('beforeafter');
+ });
+
+ it('treats an empty array as falsy (Mustache spec)', () => {
+ expect(applyTemplate('{{#items}}item{{/items}}', { items: [] })).toBe('');
+ });
+
+ it('treats an empty string as falsy', () => {
+ expect(applyTemplate('a{{#name}}={{name}}{{/name}}', { name: '' })).toBe('a');
+ });
+
+ it('opens an object scope so child keys resolve naturally', () => {
+ expect(applyTemplate('{{#user}}{{first}}{{/user}}', { user: { first: 'A' } })).toBe('A');
+ });
+
+ it('keeps parent scope visible inside a section body', () => {
+ // user.first is in scope inside {{#flag}} since the parent context is
+ // preserved (the section is truthy-but-non-object, so context is unchanged).
+ expect(applyTemplate('{{#flag}}{{user.first}}{{/flag}}', {
+ flag: true,
+ user: { first: 'A' },
+ })).toBe('A');
+ });
+});
+
+describe('applyTemplate — array iteration', () => {
+ it('iterates an array of objects, opening each as scope', () => {
+ const out = applyTemplate('{{#items}}- {{name}}\n{{/items}}', {
+ items: [{ name: 'a' }, { name: 'b' }, { name: 'c' }],
+ });
+ expect(out).toBe('- a\n- b\n- c\n');
+ });
+
+ it('iterates an array of primitives via {{.}}', () => {
+ expect(applyTemplate('{{#xs}}[{{.}}]{{/xs}}', { xs: [1, 2, 3] })).toBe('[1][2][3]');
+ });
+
+ it('preserves outer context inside iteration', () => {
+ // The cd-evaluate template needs `{{project.id}}` to remain visible
+ // inside `{{#evaluationFrames}}` — this asserts that contract.
+ const out = applyTemplate(
+ '{{#frames}}{{label}}@{{project.id}};{{/frames}}',
+ { project: { id: 'cd-1' }, frames: [{ label: 'a' }, { label: 'b' }] },
+ );
+ expect(out).toBe('a@cd-1;b@cd-1;');
+ });
+});
+
+describe('applyTemplate — inverted sections', () => {
+ it('renders content when key is missing or falsy', () => {
+ expect(applyTemplate('{{^flag}}nope{{/flag}}', {})).toBe('nope');
+ expect(applyTemplate('{{^flag}}nope{{/flag}}', { flag: false })).toBe('nope');
+ expect(applyTemplate('{{^items}}empty{{/items}}', { items: [] })).toBe('empty');
+ });
+
+ it('hides content when key is truthy', () => {
+ expect(applyTemplate('{{^flag}}nope{{/flag}}', { flag: true })).toBe('');
+ expect(applyTemplate('{{^items}}nope{{/items}}', { items: [1] })).toBe('');
+ });
+
+ it('pairs naturally with truthy sections for if/else', () => {
+ const tpl = '{{#multiFrame}}MULTI{{/multiFrame}}{{^multiFrame}}SINGLE{{/multiFrame}}';
+ expect(applyTemplate(tpl, { multiFrame: true })).toBe('MULTI');
+ expect(applyTemplate(tpl, { multiFrame: false })).toBe('SINGLE');
+ });
+});
diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.js
index b57d47449e..b6d6d22706 100644
--- a/server/services/creativeDirector/agentBridge.js
+++ b/server/services/creativeDirector/agentBridge.js
@@ -78,14 +78,14 @@ async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {
}
export async function enqueueTreatmentTask(project) {
- const context = buildTreatmentPrompt(project);
+ const context = await buildTreatmentPrompt(project);
const built = buildTaskRecord(project, 'treatment', null, context);
return persistAndEmit(built, project, 'treatment', null);
}
export async function enqueueEvaluateTask(project, scene) {
if (!scene) throw new Error('enqueueEvaluateTask: scene is required');
- const context = buildEvaluatePrompt(project, scene);
+ const context = await buildEvaluatePrompt(project, scene);
const built = buildTaskRecord(project, 'evaluate', scene, context);
return persistAndEmit(built, project, 'evaluate', scene.sceneId);
}
diff --git a/server/services/creativeDirector/promptSeeder.js b/server/services/creativeDirector/promptSeeder.js
new file mode 100644
index 0000000000..eb14e0d2e5
--- /dev/null
+++ b/server/services/creativeDirector/promptSeeder.js
@@ -0,0 +1,87 @@
+/**
+ * Creative Director — bundled prompt-stage seeder.
+ *
+ * Why this exists: PortOS treats `data/prompts/` as user-editable runtime
+ * state and gitignores it, so prompt stages added at the code level never
+ * land on a fresh install. This seeder bundles the CD treatment + evaluate
+ * templates inside the PortOS repo (alongside `agentBridge.js`) and copies
+ * them into `data/prompts/stages/` on server boot when they're missing.
+ *
+ * The user's own edits in the Prompts Manager are sticky — once a stage
+ * exists in `stage-config.json` we DON'T overwrite the .md template, so a
+ * customized prompt survives a server restart. The seeder is purely a
+ * "create on first run" hook.
+ */
+
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { PATHS } from '../../lib/fileUtils.js';
+
+const SEED_DIR = join(dirname(fileURLToPath(import.meta.url)), 'prompts');
+
+const CD_STAGES = [
+ {
+ name: 'cd-treatment',
+ config: {
+ name: 'Creative Director — Treatment',
+ description: 'Plan a long-form generated-video project: write the logline, synopsis, and scene-by-scene treatment.',
+ model: 'default',
+ returnsJson: false,
+ variables: [],
+ },
+ },
+ {
+ name: 'cd-evaluate',
+ config: {
+ name: 'Creative Director — Scene Evaluation',
+ description: 'Evaluate a freshly-rendered scene against the project style spec and scene intent. Reads multi-frame samples to judge intent across the full clip timeline.',
+ model: 'default',
+ returnsJson: false,
+ variables: [],
+ },
+ },
+];
+
+export async function seedCreativeDirectorPrompts() {
+ const promptsRoot = join(PATHS.data, 'prompts');
+ const stagesDir = join(promptsRoot, 'stages');
+ const configPath = join(promptsRoot, 'stage-config.json');
+
+ if (!existsSync(stagesDir)) await mkdir(stagesDir, { recursive: true });
+
+ // Read-or-init the stage config. Toolkit's prompts service treats a
+ // missing file as `{ stages: {} }`; mirror that so we don't crash the
+ // seeder on a fresh install.
+ let stageConfig = { stages: {} };
+ if (existsSync(configPath)) {
+ const raw = await readFile(configPath, 'utf-8').catch(() => null);
+ if (raw) stageConfig = JSON.parse(raw);
+ if (!stageConfig.stages) stageConfig.stages = {};
+ }
+
+ let configChanged = false;
+ let templatesWritten = 0;
+
+ for (const { name, config } of CD_STAGES) {
+ if (!stageConfig.stages[name]) {
+ stageConfig.stages[name] = config;
+ configChanged = true;
+ }
+ const targetTemplate = join(stagesDir, `${name}.md`);
+ if (!existsSync(targetTemplate)) {
+ const sourceTemplate = join(SEED_DIR, `${name}.md`);
+ const body = await readFile(sourceTemplate, 'utf-8');
+ await writeFile(targetTemplate, body);
+ templatesWritten += 1;
+ }
+ }
+
+ if (configChanged) {
+ await writeFile(configPath, JSON.stringify(stageConfig, null, 2));
+ }
+ if (configChanged || templatesWritten > 0) {
+ console.log(`📝 CD prompt seeder: ${configChanged ? 'config updated, ' : ''}${templatesWritten} template(s) written`);
+ }
+}
diff --git a/server/services/creativeDirector/prompts/cd-evaluate.md b/server/services/creativeDirector/prompts/cd-evaluate.md
new file mode 100644
index 0000000000..65f633e1c6
--- /dev/null
+++ b/server/services/creativeDirector/prompts/cd-evaluate.md
@@ -0,0 +1,114 @@
+# Creative Director — Scene evaluation task
+
+Your ONLY job is to evaluate a freshly-rendered scene and decide whether it works. The render itself was done by the server (no upstream task to do); the rendered video and sampled frames are already on disk.
+
+## Project: "{{project.name}}" (id: {{project.id}})
+
+- Aspect ratio: {{project.aspectRatio}} ({{aspect.width}}×{{aspect.height}})
+- Quality: {{project.quality}} ({{quality.steps}} denoising steps, guidance {{quality.guidance}}, {{quality.fps}}fps)
+- Model: {{project.modelId}}
+- Target episode duration: {{project.targetDurationSeconds}}s (~{{project.targetDurationMinutes}} min)
+- Collection id (group all rendered segments here): {{project.collectionId}}
+{{#project.startingImageFile}}- Starting image: /data/images/{{project.startingImageFile}}{{/project.startingImageFile}}
+{{^project.startingImageFile}}- Starting image: none{{/project.startingImageFile}}
+
+## Style spec (apply to every prompt)
+
+{{#project.styleSpec}}{{project.styleSpec}}{{/project.styleSpec}}{{^project.styleSpec}}(none — derive a coherent visual language from the project name + first scene intent){{/project.styleSpec}}
+
+## Scene to evaluate
+
+- Scene id: `{{scene.sceneId}}` ({{scene.positionLabel}})
+- Intent: {{scene.intent}}
+- Render prompt: {{scene.promptJson}}
+- Render: `{{render.width}}×{{render.height}}`, {{render.numFrames}} frames @ {{render.fps}}fps
+- Strategy: {{scene.strategy}}
+- Retry count: {{scene.retryCount}} (max 3)
+- Rendered video: `/data/videos/{{scene.renderedJobId}}.mp4`
+{{#multiFrame}}
+- Sampled frames across the timeline (Read EACH ONE):
+{{#evaluationFrames}}
+ {{position}}. `/data/video-thumbnails/{{filename}}` — {{label}}
+{{/evaluationFrames}}
+{{/multiFrame}}
+{{^multiFrame}}
+- Thumbnail (use this for evaluation): `/data/video-thumbnails/{{scene.renderedJobId}}.jpg`
+{{/multiFrame}}
+
+{{#multiFrame}}
+## Step 1 — Read every sampled frame using your vision capability
+
+Open EVERY frame above (Read tool, one per file) before deciding. Scene intent often develops mid- or late-clip — judging on frame 1 alone causes false rejects when the payoff (archway appearing, light bloom, particles converging) lands later in the timeline. Hold all frames in mind together as a sequence.
+{{/multiFrame}}
+{{^multiFrame}}
+## Step 1 — Read the thumbnail using your vision capability
+
+Open the thumbnail file (Read tool) and inspect the frame.
+{{/multiFrame}}
+
+## Step 2 — Score against three dimensions
+
+1. **Style adherence**: does it match the project style spec? (Across the whole sequence, not just frame 1.)
+2. **Continuity**: does it flow from the prior accepted scene's tone, color, characters? (If this is scene 1, just check it stands on its own.)
+3. **Scene intent**: does it actually depict "{{scene.intent}}" by the end of the clip? Intent that arrives late still counts as delivered — accept it.
+
+## Step 3 — Decide
+
+Issue ONE PATCH to record your verdict, then exit. Do not request renders, do not call last-frame, do not create follow-up tasks — the server handles all of that.
+
+```
+PATCH {{apiUrl}}/api/creative-director/{{project.id}}/scene/{{scene.sceneId}}
+Content-Type: application/json
+```
+
+**If the render is acceptable** (good enough — perfect is the enemy of done):
+```json
+{
+ "status": "accepted",
+ "evaluation": {
+ "accepted": true,
+ "score": 0.0–1.0,
+ "notes": "<one-sentence reason>",
+ "sampledAt": "<ISO 8601 timestamp>"
+ }
+}
+```
+
+Then (and ONLY in the accepted case) add the rendered video to the project's collection:
+```
+POST {{apiUrl}}/api/media/collections/{{project.collectionId}}/items
+Content-Type: application/json
+
+{ "kind": "video", "ref": "{{scene.renderedJobId}}" }
+```
+Do NOT issue this POST for the retry or failed branches below — rejected renders should not enter the collection.
+
+**If the render misses the mark and retries are still available** (`retryCount < 3`): tweak the prompt and request a re-render. The server will run the new render and then send you back here for another evaluation.
+```json
+{
+ "status": "pending",
+ "prompt": "<refined render prompt>",
+ "retryCount": {{scene.nextRetryCount}},
+ "evaluation": {
+ "accepted": false,
+ "score": 0.0–1.0,
+ "notes": "<what to fix>",
+ "sampledAt": "<ISO 8601 timestamp>"
+ }
+}
+```
+
+**If retries are exhausted** (`retryCount >= 3`) and the render is still not acceptable, give up on this scene:
+```json
+{
+ "status": "failed",
+ "evaluation": {
+ "accepted": false,
+ "score": 0.0–1.0,
+ "notes": "<why no further retry helps>",
+ "sampledAt": "<ISO 8601 timestamp>"
+ }
+}
+```
+
+Then exit. The server picks up from there.
diff --git a/server/services/creativeDirector/prompts/cd-treatment.md b/server/services/creativeDirector/prompts/cd-treatment.md
new file mode 100644
index 0000000000..59548c3346
--- /dev/null
+++ b/server/services/creativeDirector/prompts/cd-treatment.md
@@ -0,0 +1,68 @@
+# Creative Director — Treatment task
+
+You are the Creative Director for a long-form generated-video project. Your job in this task is to produce a TREATMENT — a complete scene-by-scene plan that the server will then render scene-by-scene (no further agent task is needed for rendering — the server orchestrates that). After each render lands, a separate short evaluation task will judge it.
+
+## Project: "{{project.name}}" (id: {{project.id}})
+
+- Aspect ratio: {{project.aspectRatio}} ({{aspect.width}}×{{aspect.height}})
+- Quality: {{project.quality}} ({{quality.steps}} denoising steps, guidance {{quality.guidance}}, {{quality.fps}}fps)
+- Model: {{project.modelId}}
+- Target episode duration: {{project.targetDurationSeconds}}s (~{{project.targetDurationMinutes}} min)
+- Collection id (group all rendered segments here): {{project.collectionId}}
+{{#project.startingImageFile}}- Starting image: /data/images/{{project.startingImageFile}}{{/project.startingImageFile}}
+{{^project.startingImageFile}}- Starting image: none{{/project.startingImageFile}}
+
+## Style spec (apply to every prompt)
+
+{{#project.styleSpec}}{{project.styleSpec}}{{/project.styleSpec}}{{^project.styleSpec}}(none — derive a coherent visual language from the project name + first scene intent){{/project.styleSpec}}
+
+{{#project.userStory}}
+## User-supplied story
+
+The user provided this outline. Honor it; expand/refine but don't contradict.
+
+{{project.userStory}}
+{{/project.userStory}}
+{{^project.userStory}}
+## Story
+
+The user did not supply a story. Invent one that suits the style spec and target duration.
+{{/project.userStory}}
+
+## Task
+
+1. Design a story arc that fits ~{{project.targetDurationSeconds}}s of total runtime. Think in scenes that are 1–10 seconds each (most should be 4–6s; reserve short ones for cuts and long ones for held shots).
+2. Each scene should have a clear visual intent and a render prompt that incorporates the style spec.
+3. Decide for each scene whether it continues from the previous scene's last frame (`useContinuationFromPrior: true`) or starts from a new image (`useContinuationFromPrior: false`, optionally with a `sourceImageFile` basename if you want to seed from a specific gallery image). Scene 1 either uses the project starting image (if provided — copy its filename into `sourceImageFile`) or starts as text-to-video.
+4. Don't pad with filler; if the natural arc is shorter than the target, that's fine — produce fewer scenes.
+
+## Output contract
+
+Issue ONE HTTP request to update the project with the treatment, then exit:
+
+```
+PATCH {{apiUrl}}/api/creative-director/{{project.id}}/treatment
+Content-Type: application/json
+
+{
+ "logline": "<one-sentence high-concept>",
+ "synopsis": "<short paragraph synopsis>",
+ "scenes": [
+ {
+ "sceneId": "scene-1",
+ "order": 0,
+ "intent": "<what this scene does narratively/visually>",
+ "prompt": "<full render prompt with style spec inlined>",
+ "negativePrompt": "<optional>",
+ "durationSeconds": 5,
+ "useContinuationFromPrior": false,
+ "sourceImageFile": {{startingImageFileLiteral}}
+ },
+ { "sceneId": "scene-2", "order": 1, ..., "useContinuationFromPrior": true }
+ ]
+}
+```
+
+On a 200 response your task is complete. The server will automatically begin rendering scene 1 — do not create any additional tasks yourself.
+
+If the PATCH returns 4xx, fix the validation issue (read the error body) and retry. Do not retry on 5xx more than twice.
diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.js
index 40ed40537d..17b3e11a2e 100644
--- a/server/services/creativeDirector/sceneRunner.js
+++ b/server/services/creativeDirector/sceneRunner.js
@@ -32,6 +32,7 @@ import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'path';
import { existsSync } from 'fs';
import { PATHS } from '../../lib/fileUtils.js';
import { presetToRenderParams } from '../../lib/creativeDirectorPresets.js';
+import { extractEvaluationFrames, safeUnder } from '../../lib/ffmpeg.js';
import { extractLastFrame } from '../videoGen/local.js';
import { enqueueJob, mediaJobEvents } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
@@ -224,11 +225,32 @@ async function handleRenderCompleted(projectId, sceneId, jobId) {
await advanceAfterSceneSettled(projectId);
return;
}
+ // Sample 5 evenly-spaced frames so the evaluator can judge intent across
+ // the full timeline rather than only the opening pose. i2v scenes whose
+ // payoff lands mid- or late-clip (archway appearing, light bloom) were
+ // getting rejected when the agent only saw frame 0.
+ const videoPath = safeUnder(PATHS.videos, `${jobId}.mp4`);
+ const evaluationFrames = videoPath
+ ? await extractEvaluationFrames(videoPath, jobId, 5).catch((e) => {
+ console.log(`⚠️ CD multi-frame extract failed for ${jobId.slice(0, 8)}: ${e.message}`);
+ return [];
+ })
+ : [];
+ if (evaluationFrames.length > 0) {
+ console.log(`🎞️ CD sampled ${evaluationFrames.length} evaluator frames for ${sceneId} (${jobId.slice(0, 8)})`);
+ }
+
await updateScene(projectId, sceneId, {
status: 'evaluating',
renderedJobId: jobId,
+ evaluationFrames,
+ });
+ await enqueueEvaluateTask(fresh, {
+ ...scene,
+ status: 'evaluating',
+ renderedJobId: jobId,
+ evaluationFrames,
});
- await enqueueEvaluateTask(fresh, scene);
}
async function handleRenderCanceled(projectId, sceneId) {
diff --git a/server/services/creativeDirector/smokeTest.js b/server/services/creativeDirector/smokeTest.js
index d2cffa31c0..18348b6679 100644
--- a/server/services/creativeDirector/smokeTest.js
+++ b/server/services/creativeDirector/smokeTest.js
@@ -19,10 +19,20 @@
* continuation doesn't
* drift)
*
- * Result: ~9s total runtime, no LLM in the loop after the project is
- * created, audio rendering disabled. Use as a fast E2E health check after
- * touching anything in the CD pipeline (sceneRunner, mediaJobQueue,
- * completionHook, stitchRunner).
+ * Result: ~6s total runtime at 384×384 (1:1-small hidden preset), no LLM
+ * in the loop after the project is created, audio rendering disabled. Use
+ * as a fast E2E health check after touching anything in the CD pipeline
+ * (sceneRunner, mediaJobQueue, completionHook, stitchRunner).
+ *
+ * Cost knobs the smoke test deliberately picks:
+ * - aspectRatio '1:1-small' (384×384, ~44% fewer pixels than 1:1's
+ * 512×512) — hidden from the user-facing dropdown via ASPECT_RATIOS,
+ * valid in ASPECT_PRESETS so render params resolve.
+ * - quality 'draft' (8 denoising steps, 24fps).
+ * - durationSeconds 2 per scene → numFrames rounds to 48 per scene.
+ * - 3 scenes (T2V baseline, color-change continuation, pure
+ * continuation) — all three earn their keep verifying distinct
+ * pipeline behaviors.
*/
import { createProject, setTreatment } from './local.js';
@@ -34,7 +44,7 @@ const SMOKE_SCENES = [
intent: 'Establish: a red ball bouncing on a plain white background.',
prompt: 'A red rubber ball bouncing up and down on a plain white background. Simple flat lighting, centered framing, slow gentle bounce, no other objects.',
negativePrompt: 'text, watermark, blur, motion blur, multiple balls, complex background, shadows, people',
- durationSeconds: 3,
+ durationSeconds: 2,
useContinuationFromPrior: false,
sourceImageFile: null,
},
@@ -44,7 +54,7 @@ const SMOKE_SCENES = [
intent: 'Color change: the same bouncing ball is now blue. Tests that the i2v render honors a prompt-driven color change while preserving the bouncing motion seeded by scene 1\'s last frame.',
prompt: 'A blue rubber ball bouncing up and down on a plain white background. Simple flat lighting, centered framing, slow gentle bounce, no other objects.',
negativePrompt: 'text, watermark, blur, motion blur, multiple balls, complex background, shadows, people, red',
- durationSeconds: 3,
+ durationSeconds: 2,
useContinuationFromPrior: true,
sourceImageFile: null,
},
@@ -54,7 +64,7 @@ const SMOKE_SCENES = [
intent: 'Pure continuation: same blue ball, same scene. Tests that i2v chaining holds visual identity across a same-prompt continuation step.',
prompt: 'A blue rubber ball bouncing up and down on a plain white background. Simple flat lighting, centered framing, slow gentle bounce, no other objects.',
negativePrompt: 'text, watermark, blur, motion blur, multiple balls, complex background, shadows, people, red',
- durationSeconds: 3,
+ durationSeconds: 2,
useContinuationFromPrior: true,
sourceImageFile: null,
},
@@ -68,10 +78,10 @@ const SMOKE_TREATMENT = {
const SMOKE_DEFAULTS = {
name: 'CD smoke test (colored ball)',
- aspectRatio: '1:1',
+ aspectRatio: '1:1-small',
quality: 'draft',
modelId: 'ltx23_distilled_q4',
- targetDurationSeconds: 9,
+ targetDurationSeconds: 6,
styleSpec: 'Plain white background, single rubber ball, no text, no people. Flat lighting, centered framing.',
startingImageFile: null,
userStory: null,
diff --git a/server/services/creativeDirector/smokeTest.test.js b/server/services/creativeDirector/smokeTest.test.js
index 979199718c..ca8d5dea93 100644
--- a/server/services/creativeDirector/smokeTest.test.js
+++ b/server/services/creativeDirector/smokeTest.test.js
@@ -32,10 +32,16 @@ describe('createSmokeTestProject', () => {
const project = await createSmokeTestProject();
expect(project.disableAudio).toBe(true);
expect(project.autoAcceptScenes).toBe(true);
- expect(project.aspectRatio).toBe('1:1');
+ // Hidden small preset (384×384) keeps smoke renders fast — present in
+ // ASPECT_PRESETS but intentionally absent from ASPECT_RATIOS so the UI
+ // doesn't expose it.
+ expect(project.aspectRatio).toBe('1:1-small');
expect(project.quality).toBe('draft');
- expect(project.targetDurationSeconds).toBe(9);
+ expect(project.targetDurationSeconds).toBe(6);
expect(project.treatment.scenes).toHaveLength(3);
+ for (const scene of project.treatment.scenes) {
+ expect(scene.durationSeconds).toBe(2);
+ }
});
it('scene 1 is text-to-video (no continuation, no source image)', async () => {
diff --git a/server/services/promptService.js b/server/services/promptService.js
index 49b749cfc1..4ca3d7177b 100644
--- a/server/services/promptService.js
+++ b/server/services/promptService.js
@@ -1,8 +1,17 @@
/**
* Compatibility shim for PortOS services that import from promptService.js
- * Re-exports toolkit prompts service functions
+ * Re-exports toolkit prompts service functions, but routes `buildPrompt`
+ * (and `previewPrompt`) through PortOS's enhanced template engine so
+ * templates can use Mustache-style dot notation against nested objects
+ * (e.g. `{{project.name}}`, `{{#frames}}{{label}}{{/frames}}`).
+ *
+ * The toolkit's stored data (stage-config.json, variables.json, .md files)
+ * is unchanged — we just swap out the templating step. The toolkit-stored
+ * `templateEngine === 'mustache'` semantics still hold; we extend them.
*/
+import { applyTemplate } from '../lib/promptTemplate.js';
+
// This will be initialized by server/index.js and set via setAIToolkit()
let aiToolkitInstance = null;
@@ -65,12 +74,27 @@ export async function deleteVariable(key) {
return aiToolkitInstance.services.prompts.deleteVariable(key);
}
-export async function buildPrompt(stageName, data) {
+export async function buildPrompt(stageName, data = {}) {
if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.prompts.buildPrompt(stageName, data);
+ const prompts = aiToolkitInstance.services.prompts;
+ const stage = prompts.getStage(stageName);
+ if (!stage) throw new Error(`Stage ${stageName} not found`);
+ const template = await prompts.getStageTemplate(stageName);
+ if (!template) throw new Error(`Template for ${stageName} not found`);
+ // Auto-merge stage-declared shared variables (variables.json) into the
+ // render context so templates can reference `{{schemaSnippet}}` etc.
+ // without callers having to know which named variables their stage uses.
+ const allVars = { ...data };
+ const variables = prompts.getVariables() || {};
+ for (const varName of stage.variables || []) {
+ const v = variables[varName];
+ if (v && allVars[varName] === undefined) allVars[varName] = v.content;
+ }
+ return applyTemplate(template, allVars);
}
-export async function previewPrompt(stageName, testData) {
- if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized');
- return aiToolkitInstance.services.prompts.previewPrompt(stageName, testData);
+export async function previewPrompt(stageName, testData = {}) {
+ // Delegate to the local buildPrompt so the preview pane in the Prompts
+ // Manager renders with the same engine that production prompts use.
+ return buildPrompt(stageName, testData);
}