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
refactor(creative-director): seed CD prompt stages via data.sample instead of custom seeder
Adam Eivy22a0aced0546
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 64b3371451..3482a63c63 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,7 +25,7 @@## 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).+- **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. The two new stages ship as starters under `data.sample/prompts/stages/cd-{treatment,evaluate}.md` plus `cd-*` entries in `data.sample/prompts/stage-config.json` — `npm run setup` / `npm run setup:data` copies them into `data/prompts/` on fresh installs (and fills in any missing files on existing installs without overwriting user customizations).- **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.diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex e9c42aa339..dd36a7ac27 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -1,5 +1,19 @@{"stages": {+ "cd-treatment": {+ "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": []+ },+ "cd-evaluate": {+ "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": []+ },"app-detection": {"name": "App Detection","description": "Analyze a project directory and detect its configuration",diff --git a/server/services/creativeDirector/prompts/cd-evaluate.md b/data.sample/prompts/stages/cd-evaluate.mdsimilarity index 100%rename from server/services/creativeDirector/prompts/cd-evaluate.mdrename to data.sample/prompts/stages/cd-evaluate.mddiff --git a/server/services/creativeDirector/prompts/cd-treatment.md b/data.sample/prompts/stages/cd-treatment.mdsimilarity index 100%rename from server/services/creativeDirector/prompts/cd-treatment.mdrename to data.sample/prompts/stages/cd-treatment.mddiff --git a/server/index.js b/server/index.jsindex 8a7d989062..cd8ed83201 100644--- a/server/index.js+++ b/server/index.js@@ -85,7 +85,6 @@ 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';@@ -458,13 +457,6 @@ 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/services/creativeDirector/promptSeeder.js b/server/services/creativeDirector/promptSeeder.jsdeleted file mode 100644index eb14e0d2e5..0000000000--- a/server/services/creativeDirector/promptSeeder.js+++ /dev/null@@ -1,87 +0,0 @@-/**- * 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`);- }-}