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
feat: persist revisioned Video treatment artifacts (#6547)
[._.]/ Adam Eivy74180b46e210
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 334fffc954..cbd3a5a749 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -278,3 +278,18 @@ both HTTP start/resume and background advancement until revision-specific approvsupport ships. Selecting autonomous policy only saves intent; it cannot authorizedispatch while that barrier is present. Source references do not copy or mutatethe referenced creative-suite records.++Video treatments optionally carry a bounded `script` plus server-owned `artifact`+metadata inside that same project JSONB: stable project-scoped script/shot/reference+IDs, monotonically increasing treatment revision, exact contiguous shot timing,+and selected source IDs/revisions. Scene IDs and playback orders must be unique;+shot durations must sum to the exact project target. Treatment writes keep Video+projects in their current state and do not dispatch production. Creative shot+edits increment the artifact revision; runtime status updates do not. Changes to+brief, source selection or production settings mark the artifact stale until it+is compiled again. Source snapshots remain references, not copied source records.+This is additive optional metadata: legacy treatments are unchanged and existing+records are not backfilled. Sync advances to `creativeDirectorProjects` v5 because+a v4 peer can edit a shot without incrementing its artifact revision, or discard+the artifact on treatment replacement. The Video dispatch barrier remains in+force; this artifact does not certify backend compatibility or grant approval.diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 30df144891..63cefb7ffa 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -313,6 +313,8 @@ export const creativeDirectorSceneSchema = z.object({export const creativeDirectorTreatmentSchema = z.object({logline: z.string().min(1).max(500),synopsis: z.string().min(1).max(5000),+ // Optional standalone script; artifact IDs/revisions/timing are server-owned.+ script: z.string().trim().min(1).max(50000).optional(),scenes: z.array(creativeDirectorSceneSchema).min(1).max(120),});diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex ebbeca1f7d..268970b67b 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -448,7 +448,10 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// v4: Video drafts must stay inert. Older peers ignore workspace and could// start them through the legacy planner; reject transfers until they upgrade.// Existing records remain unchanged and need no data rewrite.- creativeDirectorProjects: 4,+ // v5: Video artifact revisions and stale-context tracking. A v4 peer can+ // edit a shot while preserving the old artifact revision, or replace the+ // treatment and drop its artifact. Gate that loss until both peers upgrade.+ creativeDirectorProjects: 5,// v1 = Mood boards (PostgreSQL `mood_boards`) federated via the per-record// peer-sync push pipeline (record kind `moodBoard`, sync category `moodBoards`,// #1564). Same posture as `creativeDirectorProjects` above: a brand-NEW synceddiff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.jsindex 31ed56d408..a597ab48b7 100644--- a/server/routes/creativeDirector.test.js+++ b/server/routes/creativeDirector.test.js@@ -337,6 +337,16 @@ describe('creativeDirector routes', () => {expect(r.status).toBe(200);expect(cdService.setTreatment).toHaveBeenCalled();});+ it('accepts a script but strips caller-supplied artifact metadata and rejects oversized scripts', async () => {+ cdService.setTreatment.mockResolvedValue({ id: 'cd-1' });+ const body = { ...treatmentBody, script: 'The cat enters.', artifact: { revision: 100 } };+ expect((await request(app).patch('/api/creative-director/cd-1/treatment').send(body)).status).toBe(200);+ expect(cdService.setTreatment.mock.lastCall[1].script).toBe(body.script);+ expect(cdService.setTreatment.mock.lastCall[1]).not.toHaveProperty('artifact');+ cdService.setTreatment.mockClear();+ expect((await request(app).patch('/api/creative-director/cd-1/treatment').send({ ...body, script: 'x'.repeat(50001) })).status).toBe(400);+ expect(cdService.setTreatment).not.toHaveBeenCalled();+ });// First-pass scene-frame seeding now fires from `setTreatment` itself// (the domain write, #1938) rather than this route, so its behavior is// asserted in services/creativeDirector/local.test.js.diff --git a/server/services/creativeDirector/projectsFile.test.js b/server/services/creativeDirector/projectsFile.test.jsindex a2e20ae819..984c61484f 100644--- a/server/services/creativeDirector/projectsFile.test.js+++ b/server/services/creativeDirector/projectsFile.test.js@@ -66,6 +66,85 @@ const project = (id, extra = {}) => ({});const journalEntries = () => cj.conflictJournalStore().loadAll();+const videoTreatment = () => ({+ logline: 'A journey through an imaginary garden.',+ synopsis: 'A visitor follows a trail and returns home.',+ script: 'The visitor enters. Leaves rustle. The visitor returns home.',+ scenes: Array.from({ length: 12 }, (_, order) => ({+ sceneId: `scene-${order}`, order, intent: 'Follow the trail',+ prompt: 'An imaginary garden path', durationSeconds: 10,+ })),+});+const createVideo = () => file.createProject({+ name: 'Example short', workspace: 'video', modelId: '', aspectRatio: '16:9', quality: 'draft',+ targetDurationSeconds: 120, videoDraft: {+ durationRange: { min: 60, max: 180 },+ sources: [{ kind: 'universe', id: 'example-universe', revision: 'revision-1' }],+ },+});++describe('Video treatment artifacts', () => {+ it('persists a timed two-minute script and stable identities across revised drafts and reloads', async () => {+ const p = await createVideo();+ const treatment = videoTreatment();+ // Input order need not be playback order; IDs remain the cross-artifact key.+ treatment.scenes.reverse();+ await file.setTreatment(p.id, { ...treatment, artifact: { scriptId: 'forged', revision: 99 } });+ const saved = await file.getProject(p.id);+ expect(saved.status).toBe('draft');+ expect(saved.treatment.script).toBe(treatment.script);+ expect(saved.treatment.artifact).toMatchObject({+ scriptId: `script-${p.id}`, revision: 1, targetDurationSeconds: 120, stale: false,+ references: [{ kind: 'universe', id: 'example-universe', revision: 'revision-1', referenceId: 'universe:example-universe' }],+ });+ expect(saved.treatment.artifact.shots).toEqual(Array.from({ length: 12 }, (_, i) => ({+ shotId: `shot-scene-${i}`, sceneId: `scene-${i}`, startSeconds: i * 10, endSeconds: (i + 1) * 10, durationSeconds: 10,+ })));+ await file.setTreatment(p.id, { ...treatment, script: 'The visitor takes a different path.' });+ const revised = (await file.getProject(p.id)).treatment;+ expect(revised.artifact).toEqual({ ...saved.treatment.artifact, revision: 2 });+ expect(revised.script).toBe('The visitor takes a different path.');+ });++ it('rejects ambiguous scene identities, ordering and a mismatched duration without replacing the saved artifact', async () => {+ const p = await createVideo();+ await file.setTreatment(p.id, videoTreatment());+ const saved = await file.getProject(p.id);+ const duplicateId = videoTreatment();+ duplicateId.scenes[1].sceneId = duplicateId.scenes[0].sceneId;+ const duplicateOrder = videoTreatment();+ duplicateOrder.scenes[1].order = 0;+ const wrongDuration = videoTreatment();+ wrongDuration.scenes[0].durationSeconds = 9;+ const writesBefore = writeCounter.project;+ await expect(file.setTreatment(p.id, duplicateId)).rejects.toThrow('unique sceneId');+ await expect(file.setTreatment(p.id, duplicateOrder)).rejects.toThrow('unique sceneId');+ await expect(file.setTreatment(p.id, wrongDuration)).rejects.toThrow('exact target of 120s');+ expect(writeCounter.project).toBe(writesBefore);+ expect(await file.getProject(p.id)).toEqual(saved);+ await file.updateProject(p.id, { videoDraft: { ...p.videoDraft, sources: [...p.videoDraft.sources, ...p.videoDraft.sources] } });+ await expect(file.setTreatment(p.id, videoTreatment())).rejects.toThrow('unique kind and id');+ expect((await file.getProject(p.id)).treatment).toEqual({ ...saved.treatment, artifact: { ...saved.treatment.artifact, stale: true } });+ });++ it('versions creative shot changes and marks changed draft context stale until a new compilation', async () => {+ const p = await createVideo();+ await file.setTreatment(p.id, videoTreatment());+ await file.updateScene(p.id, 'scene-0', { status: 'rendering' });+ expect((await file.getProject(p.id)).treatment.artifact.revision).toBe(1);+ await file.updateScene(p.id, 'scene-0', { prompt: 'An imaginary garden at dusk' });+ expect((await file.getProject(p.id)).treatment.artifact.revision).toBe(2);+ await file.updateProject(p.id, { name: 'A new title' });+ expect((await file.getProject(p.id)).treatment.artifact.stale).toBe(false);+ const videoDraft = { ...p.videoDraft, sources: [{ kind: 'universe', id: 'example-universe', revision: 'revision-2' }] };+ await file.updateProject(p.id, { videoDraft });+ const stale = (await file.getProject(p.id)).treatment.artifact;+ expect(stale).toMatchObject({ stale: true, revision: 2, references: [{ revision: 'revision-1' }] });+ await file.setTreatment(p.id, videoTreatment());+ expect((await file.getProject(p.id)).treatment.artifact).toMatchObject({ stale: false, revision: 3, references: [{ revision: 'revision-2' }] });+ });+});+describe('projectsFile federation merge', () => {it('bounds Video targets on create and range edits and preserves them across reload', async () => {const p = await file.createProject({ name: 'Example short', workspace: 'video', modelId: '', aspectRatio: '16:9', quality: 'draft', targetDurationSeconds: 240, videoDraft: { durationRange: { min: 60, max: 180 } } });diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex 7c266f641c..7d86242bcb 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -355,9 +355,56 @@ export function applyProjectPatch(project, patch) {// Normalize the whole override object on write so stored records never carry// empty/model-only stage stubs; the client sends the full object each save.if ('modelOverrides' in patch) next.modelOverrides = normalizeModelOverrides(patch.modelOverrides);+ if (project.workspace === 'video' && project.treatment?.artifact+ && ['videoDraft', 'targetDurationSeconds', 'aspectRatio', 'userStory', 'styleSpec', 'cast', 'startingImageFile', 'modelId', 'renderBackend', 'quality'].some((key) => key in patch && JSON.stringify(next[key]) !== JSON.stringify(project[key]))) {+ next.treatment = { ...project.treatment, artifact: { ...project.treatment.artifact, stale: true } };+ }return next;}+/** Compile the existing treatment into a persisted Video artifact, without dispatch. */+function compileVideoArtifact(project, treatment) {+ const scenes = [...treatment.scenes].sort((a, b) => a.order - b.order);+ const ids = new Set();+ const orders = new Set();+ let elapsed = 0;+ const shots = scenes.map((scene) => {+ if (ids.has(scene.sceneId) || orders.has(scene.order)) {+ throw new ServerError('Video scenes must have unique sceneId and order values', { status: 400, code: 'VALIDATION_ERROR' });+ }+ ids.add(scene.sceneId);+ orders.add(scene.order);+ const startSeconds = elapsed;+ elapsed = Math.round((elapsed + scene.durationSeconds) * 1000000) / 1000000;+ return {+ shotId: `shot-${scene.sceneId}`,+ sceneId: scene.sceneId,+ startSeconds,+ endSeconds: elapsed,+ durationSeconds: scene.durationSeconds,+ };+ });+ if (Math.abs(elapsed - project.targetDurationSeconds) > 0.000001) {+ throw new ServerError(`Video shots total ${elapsed}s; they must total the exact target of ${project.targetDurationSeconds}s`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ const references = (project.videoDraft?.sources || []).map((source) => ({+ ...source, referenceId: `${source.kind}:${source.id}`,+ }));+ if (new Set(references.map((ref) => ref.referenceId)).size !== references.length) {+ throw new ServerError('Video source references must have unique kind and id values', { status: 400, code: 'VALIDATION_ERROR' });+ }+ return {+ scriptId: project.treatment?.artifact?.scriptId || `script-${project.id}`,+ revision: (project.treatment?.artifact?.revision || 0) + 1,+ targetDurationSeconds: project.targetDurationSeconds,+ aspectRatio: project.aspectRatio,+ // Keep the selected IDs/revisions, never copy or mutate creative-suite records.+ references,+ shots,+ stale: false,+ };+}+/*** Validate + apply a treatment to a project. Returns the next record. Initializes* each scene's runtime fields if the agent didn't supply them, and preserves@@ -378,12 +425,14 @@ export function applyTreatment(project, treatmentInput) {renderedJobId: s.renderedJobId ?? null,evaluation: s.evaluation ?? null,}));- const nextStatus = (project.status === 'paused' || project.status === 'failed')+ const treatment = { ...parsed.data, scenes };+ if (project.workspace === 'video') treatment.artifact = compileVideoArtifact(project, treatment);+ const nextStatus = (project.workspace === 'video' || project.status === 'paused' || project.status === 'failed')? project.status: 'rendering';return {...project,- treatment: { logline: parsed.data.logline, synopsis: parsed.data.synopsis, scenes },+ treatment,status: nextStatus,updatedAt: new Date().toISOString(),};@@ -480,9 +529,15 @@ export function applySceneUpdate(project, sceneId, patch) {const updated = { ...project.treatment.scenes[sceneIdx], ...patch };const scenes = project.treatment.scenes.slice();scenes[sceneIdx] = updated;+ const treatment = { ...project.treatment, scenes };+ if (project.workspace === 'video' && treatment.artifact+ && ['prompt', 'imageStrength'].some((key) => key in patch && patch[key] !== project.treatment.scenes[sceneIdx][key])) {+ // A shot edit changes the reviewed content, but cannot refresh stale source context.+ treatment.artifact = { ...treatment.artifact, revision: treatment.artifact.revision + 1 };+ }const next = {...project,- treatment: { ...project.treatment, scenes },+ treatment,updatedAt: new Date().toISOString(),};return { project: next, updated };