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: track Video source revision changes in saved artifacts (#6547)

[._.]/ Adam Eivy6eb9d03a8086
diff --git a/client/src/components/creative-director/VideoArtifactsTab.jsx b/client/src/components/creative-director/VideoArtifactsTab.jsx
index 1a0b53448d..9873f921f0 100644
--- a/client/src/components/creative-director/VideoArtifactsTab.jsx
+++ b/client/src/components/creative-director/VideoArtifactsTab.jsx
@@ -81,11 +81,12 @@ export default function VideoArtifactsTab({ project, basePath }) {
</section>
<section aria-labelledby="video-artifact-references" className="space-y-2">
<h3 id="video-artifact-references" className="font-medium">Saved references ({artifact.references.length})</h3>
- <p className="text-sm text-port-text-muted">References belong to this artifact revision. Availability is checked against this install and does not certify that source content matches its recorded revision.</p>
+ <p className="text-sm text-port-text-muted">References belong to this artifact revision. Source revision stamps are checked against this install. Older references or sources without revision metadata have unknown freshness.</p>
{!artifact.references.length && <p className="text-sm">No attached sources in this revision.</p>}
<ul className="space-y-2">
{artifact.references.map(reference => {
- const available = sourceState?.artifact.find(source => source.referenceId === reference.referenceId)?.available;
+ const status = sourceState?.artifact.find(source => source.referenceId === reference.referenceId);
+ const available = status?.available;
const sourcePath = reference.kind === 'universe' ? `/universes/${encodeURIComponent(reference.id)}`
: reference.kind === 'series' ? `/pipeline/series/${encodeURIComponent(reference.id)}` : null;
return <li key={reference.referenceId} className="bg-port-card border border-port-border rounded p-3 text-sm space-y-1 break-words">
@@ -96,6 +97,10 @@ export default function VideoArtifactsTab({ project, basePath }) {
{available === true ? 'Source available'
: available === false ? 'Source missing — repair the draft and save a revised treatment' : 'Source availability unknown'}
</p>
+ {available && <p className={status?.revisionChanged ? 'text-port-warning' : 'text-port-text-muted'}>
+ {status?.revisionChanged === true ? 'Source changed since this artifact was saved. Review the source and save a revised treatment before production.'
+ : status?.revisionChanged === false ? 'Source revision stamp matches the saved artifact' : 'Source revision freshness unknown. Review the source before saving a revised treatment.'}
+ </p>}
{sourcePath && <Link className="text-port-accent hover:underline" to={sourcePath}>Open {reference.kind}</Link>}
</li>;
})}
diff --git a/client/src/pages/CreativeDirectorDetail.test.jsx b/client/src/pages/CreativeDirectorDetail.test.jsx
index 2ae04c773f..45a1db7ada 100644
--- a/client/src/pages/CreativeDirectorDetail.test.jsx
+++ b/client/src/pages/CreativeDirectorDetail.test.jsx
@@ -165,6 +165,24 @@ describe('Video saved artifacts', () => {
expect(screen.getByText('No tool plan saved.')).toBeInTheDocument();
});
+ it('distinguishes changed, matching, and unknown source revisions without replacing saved labels', async () => {
+ const user = userEvent.setup();
+ cdApi.getCreativeDirectorSources.mockResolvedValueOnce({ draft: [], artifact: [
+ { referenceId: 'universe:example-universe', available: true, revisionChanged: true },
+ { referenceId: 'voice:example-voice', available: true, revisionChanged: null },
+ ] });
+ renderVideo();
+ expect(await screen.findByText(/Source changed since this artifact was saved/)).toBeInTheDocument();
+ expect(screen.getByText(/Source revision freshness unknown/)).toBeInTheDocument();
+ cdApi.getCreativeDirectorSources.mockResolvedValueOnce({ draft: [], artifact: [
+ { referenceId: 'universe:example-universe', available: true, revisionChanged: false },
+ ] });
+ await user.click(screen.getByRole('button', { name: 'Check again' }));
+ expect(await screen.findByText('Source revision stamp matches the saved artifact')).toBeInTheDocument();
+ expect(screen.getByText('Source revision: rev-4')).toBeInTheDocument();
+ expect(cdApi.startCreativeDirectorProject).not.toHaveBeenCalled();
+ });
+
it('reports missing sources, links to repair, and retries failed checks without altering saved revisions', async () => {
const user = userEvent.setup();
cdApi.getCreativeDirectorSources.mockRejectedValueOnce(new Error('Unavailable'));
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 703adbb372..398c1382fe 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -95,8 +95,8 @@ describe('creativeDirector routes', () => {
const res = await request(app).get('/api/creative-director/cd-video/sources');
expect(res.status).toBe(200);
expect(res.body).toEqual({
- draft: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, available: true })),
- artifact: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, revision: 'older-revision', available: true })),
+ draft: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, available: true, currentRevision: null, revisionChanged: null })),
+ artifact: sources.map(source => ({ ...source, referenceId: `${source.kind}:${source.id}`, revision: 'older-revision', available: true, currentRevision: null, revisionChanged: null })),
});
expect(getUniverse).toHaveBeenCalledTimes(1);
expect(cdService.updateProject).not.toHaveBeenCalled();
diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.js
index 13530a95b6..cf34c2181c 100644
--- a/server/services/creativeDirector/local.js
+++ b/server/services/creativeDirector/local.js
@@ -133,8 +133,6 @@ export async function deleteProject(id) {
}
export async function setTreatment(id, treatmentInput) {
- const { assertVideoSourcesAvailable } = await import('./videoSources.js');
- await assertVideoSourcesAvailable(await getProject(id));
const next = await (await selectBackend()).setTreatment(id, treatmentInput);
emitRecordUpdated('creativeDirectorProject', id);
// Scene reference frames (#1867): the user opts into first-pass gen at
diff --git a/server/services/creativeDirector/local.test.js b/server/services/creativeDirector/local.test.js
index 55fa6ee173..7c2fdf36d9 100644
--- a/server/services/creativeDirector/local.test.js
+++ b/server/services/creativeDirector/local.test.js
@@ -73,7 +73,7 @@ describe('setTreatment — first-pass scene frames (#1867/#1938)', () => {
expect(mockAtomicWrite).not.toHaveBeenCalled();
getIngredient.mockResolvedValue({ id: 'example-catalog', updatedAt: 'newer-source-revision' });
const saved = await setTreatment(project.id, treatment);
- expect(saved.treatment.artifact.references).toEqual([{ kind: 'catalog', id: 'example-catalog', referenceId: 'catalog:example-catalog', revision: 'revision-1' }]);
+ expect(saved.treatment.artifact.references).toEqual([{ kind: 'catalog', id: 'example-catalog', referenceId: 'catalog:example-catalog', revision: 'revision-1', sourceRevision: expect.any(String) }]);
expect(saved.status).toBe('draft');
await expect(setPlan(project.id, plan)).resolves.toMatchObject({ status: 'draft' });
expect(firstPassGen.enqueueFirstPassSceneFrames).not.toHaveBeenCalled();
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index 50773c7781..ddc0ad58d3 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -43,7 +43,11 @@ export async function createProject(input) {
}
export async function setTreatment(id, treatmentInput) {
- const { project } = await withLockedProject(id, (current) => ({ project: logic.applyTreatment(current, treatmentInput) }));
+ const { assertVideoSourcesAvailable } = await import('./videoSources.js');
+ const { project } = await withLockedProject(id, async (current) => {
+ const sourceRevisions = await assertVideoSourcesAvailable(current);
+ return { project: logic.applyTreatment(current, treatmentInput, sourceRevisions) };
+ });
return project;
}
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index be6957d03b..35c5fca40a 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -40,7 +40,9 @@ export async function createProject(input) {
export async function setTreatment(id, treatmentInput) {
const { all, idx } = await loadAllAndIndex(id);
- all[idx] = logic.applyTreatment(all[idx], treatmentInput);
+ const { assertVideoSourcesAvailable } = await import('./videoSources.js');
+ const sourceRevisions = await assertVideoSourcesAvailable(all[idx]);
+ all[idx] = logic.applyTreatment(all[idx], treatmentInput, sourceRevisions);
await saveAll(all);
return all[idx];
}
diff --git a/server/services/creativeDirector/projectsFile.test.js b/server/services/creativeDirector/projectsFile.test.js
index 2bc8678106..d1f333f430 100644
--- a/server/services/creativeDirector/projectsFile.test.js
+++ b/server/services/creativeDirector/projectsFile.test.js
@@ -37,6 +37,9 @@ vi.mock('../mediaCollections.js', () => ({
createCollection: vi.fn(async () => ({ id: 'col-test' })),
}));
+vi.mock('../universeBuilder/crud.js', () => ({ getUniverse: vi.fn(async () => ({ id: 'example-universe', updatedAt: '2026-09-01T00:00:00.000Z' })) }));
+import { getUniverse } from '../universeBuilder/crud.js';
+const { getVideoSourceStatus } = await import('./videoSources.js');
const file = await import('./projectsFile.js');
const cj = await import('../../lib/conflictJournal.js');
@@ -119,7 +122,7 @@ describe('Video treatment artifacts', () => {
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' }],
+ references: [{ kind: 'universe', id: 'example-universe', revision: 'revision-1', referenceId: 'universe:example-universe', sourceRevision: expect.any(String) }],
});
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,
@@ -128,6 +131,13 @@ describe('Video treatment artifacts', () => {
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.');
+ const reference = revised.artifact.references[0];
+ expect((await getVideoSourceStatus(await file.getProject(p.id))).artifact[0].revisionChanged).toBe(false);
+ getUniverse.mockResolvedValueOnce({ id: 'example-universe', updatedAt: '2026-09-02T00:00:00.000Z' });
+ expect((await getVideoSourceStatus(await file.getProject(p.id))).artifact[0].revisionChanged).toBe(true);
+ expect((await file.getProject(p.id)).treatment.artifact.references[0]).toEqual(reference);
+ getUniverse.mockResolvedValueOnce({ id: 'example-universe' });
+ expect((await getVideoSourceStatus(await file.getProject(p.id))).artifact[0].revisionChanged).toBeNull();
});
it('rejects ambiguous scene identities, ordering and a mismatched duration without replacing the saved artifact', async () => {
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index 0e7785284b..f186e66ddc 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -386,7 +386,7 @@ function validateVideoShot(project, scene, isFirst) {
}
/** Compile the existing treatment into a persisted Video artifact, without dispatch. */
-function compileVideoArtifact(project, treatment) {
+function compileVideoArtifact(project, treatment, sourceRevisions) {
if (!treatment.script) {
throw new ServerError('Video treatments require a production script. Add script text and resubmit the treatment.', {
status: 400, code: 'VALIDATION_ERROR',
@@ -418,6 +418,7 @@ function compileVideoArtifact(project, treatment) {
}
const references = (project.videoDraft?.sources || []).map((source) => ({
...source, referenceId: `${source.kind}:${source.id}`,
+ ...(sourceRevisions ? { sourceRevision: sourceRevisions[`${source.kind}:${source.id}`] ?? null } : {}),
}));
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' });
@@ -439,7 +440,7 @@ function compileVideoArtifact(project, treatment) {
* each scene's runtime fields if the agent didn't supply them, and preserves
* paused/failed status (otherwise flips the project to 'rendering').
*/
-export function applyTreatment(project, treatmentInput) {
+export function applyTreatment(project, treatmentInput, sourceRevisions) {
const parsed = creativeDirectorTreatmentSchema.safeParse(treatmentInput);
if (!parsed.success) {
throw new ServerError(
@@ -455,7 +456,7 @@ export function applyTreatment(project, treatmentInput) {
evaluation: s.evaluation ?? null,
}));
const treatment = { ...parsed.data, scenes };
- if (project.workspace === 'video') treatment.artifact = compileVideoArtifact(project, treatment);
+ if (project.workspace === 'video') treatment.artifact = compileVideoArtifact(project, treatment, sourceRevisions);
const nextStatus = (project.workspace === 'video' || project.status === 'paused' || project.status === 'failed')
? project.status
: 'rendering';
diff --git a/server/services/creativeDirector/sourceRevisionPersistence.test.js b/server/services/creativeDirector/sourceRevisionPersistence.test.js
new file mode 100644
index 0000000000..047cf479b7
--- /dev/null
+++ b/server/services/creativeDirector/sourceRevisionPersistence.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ project: null, writes: 0 }));
+vi.mock('../../lib/db.js', () => {
+ const query = vi.fn(async (sql, values) => {
+ if (sql.startsWith('SELECT')) return { rows: [{ id: state.project.id, data: structuredClone(state.project) }] };
+ if (sql.startsWith('INSERT')) {
+ state.project = JSON.parse(values[2]);
+ state.writes += 1;
+ return { rows: [] };
+ }
+ throw new Error('Unexpected SQL');
+ });
+ return { query, withTransaction: async fn => fn({ query }) };
+});
+vi.mock('../mediaCollections.js', () => ({ createCollection: vi.fn() }));
+vi.mock('../../lib/conflictJournal.js', () => ({
+ maybeJournalBeforeOverwrite: vi.fn(), setSyncBaseHash: vi.fn(), contentHashForRecord: vi.fn(),
+ flushBaseHashes: vi.fn(), deleteSyncBaseHash: vi.fn(), withBaseHashFlushBatch: vi.fn(),
+}));
+vi.mock('../catalogDB/ingredients.js', () => ({ getIngredient: vi.fn() }));
+import { getIngredient } from '../catalogDB/ingredients.js';
+import { setTreatment, getProject } from './projectsDB.js';
+import { getVideoSourceStatus } from './videoSources.js';
+
+describe('Video source revision persistence through the PostgreSQL adapter', () => {
+ it('awaits source resolution, preserves the captured stamp across reads, and refuses an unavailable source', async () => {
+ state.project = {
+ id: 'cd-example', workspace: 'video', status: 'draft', targetDurationSeconds: 60, aspectRatio: '16:9',
+ videoDraft: { sources: [{ kind: 'catalog', id: 'example-catalog', revision: 'user-label' }] },
+ };
+ state.writes = 0;
+ const source = { id: 'example-catalog', updatedAt: '2026-09-01T00:00:00.000Z', payload: { description: 'Example scene' } };
+ getIngredient.mockResolvedValue(source);
+ const treatment = {
+ logline: 'A visitor arrives.', synopsis: 'A visitor explores an imaginary garden.', script: 'The visitor follows a path.',
+ scenes: Array.from({ length: 6 }, (_, order) => ({ sceneId: `scene-${order}`, order, intent: 'Explore', prompt: 'A garden path', durationSeconds: 10 })),
+ artifact: { references: [{ sourceRevision: 'forged' }] },
+ };
+ await setTreatment(state.project.id, treatment);
+ const saved = await getProject(state.project.id);
+ expect(saved.treatment.artifact.references[0]).toEqual({
+ kind: 'catalog', id: 'example-catalog', revision: 'user-label', referenceId: 'catalog:example-catalog', sourceRevision: expect.stringMatching(/^[a-f0-9]{32}$/),
+ });
+ expect((await getVideoSourceStatus(saved)).artifact[0].revisionChanged).toBe(false);
+ getIngredient.mockResolvedValue({ ...source, updatedAt: '2026-09-02T00:00:00.000Z' });
+ expect((await getVideoSourceStatus(saved)).artifact[0].revisionChanged).toBe(true);
+ expect(await getProject(state.project.id)).toEqual(saved);
+ getIngredient.mockResolvedValue(null);
+ await expect(setTreatment(state.project.id, treatment)).rejects.toMatchObject({ code: 'VIDEO_SOURCE_MISSING' });
+ expect(state.writes).toBe(1);
+ expect(source.payload).toEqual({ description: 'Example scene' });
+ });
+});
diff --git a/server/services/creativeDirector/videoSources.js b/server/services/creativeDirector/videoSources.js
index 459180d24d..fd960ca214 100644
--- a/server/services/creativeDirector/videoSources.js
+++ b/server/services/creativeDirector/videoSources.js
@@ -1,5 +1,6 @@
/** Read-only, machine-local availability checks for Video draft/artifact sources. */
import { creativeDirectorVideoDraftSchema } from '../../lib/creativeDirectorValidation.js';
+import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';
import { ServerError } from '../../lib/errorHandler.js';
const sourceSchema = creativeDirectorVideoDraftSchema.shape.sources.unwrap().element;
@@ -14,14 +15,22 @@ const readers = {
voice: async (id) => (await import('../voice/profiles.js')).getVoiceProfile(id),
};
-async function sourceAvailable(source) {
+async function readSourceStatus(source) {
const record = await readers[source.kind](source.id).catch(error => {
// These stores deliberately use different not-found contracts. An outage
// must propagate: it is not evidence that a source was deleted.
if (error.code === 'NOT_FOUND' || error.code === 'PIPELINE_SERIES_NOT_FOUND') return null;
throw error;
});
- return Boolean(record && !record.deleted);
+ const available = Boolean(record && !record.deleted);
+ // Use the source store's own revision/update contract, never hash or export
+ // source content (especially local voice bindings). Missing metadata means
+ // unknown, not proof that an old source still matches.
+ const stamps = available ? Object.fromEntries(['revision', 'updatedAt']
+ .map(key => [key, record[key]])
+ .filter(([, value]) => (typeof value === 'string' && value.trim().length > 0)
+ || (typeof value === 'number' && Number.isFinite(value)))) : {};
+ return { available, currentRevision: Object.keys(stamps).length ? canonicalSnapshotChecksum(stamps) : null };
}
/** Checks both snapshots while retaining each snapshot's declared revision. */
@@ -30,8 +39,12 @@ export async function getVideoSourceStatus(project) {
const check = async (references) => Promise.all(references.map(reference => {
const source = sourceSchema.parse({ kind: reference.kind, id: reference.id, revision: reference.revision });
const referenceId = `${source.kind}:${source.id}`;
- if (!availability.has(referenceId)) availability.set(referenceId, sourceAvailable(source));
- return availability.get(referenceId).then(available => ({ ...source, referenceId, available }));
+ if (!availability.has(referenceId)) availability.set(referenceId, readSourceStatus(source));
+ return availability.get(referenceId).then(status => ({
+ ...source, referenceId, ...status,
+ revisionChanged: typeof reference.sourceRevision === 'string' && status.currentRevision
+ ? reference.sourceRevision !== status.currentRevision : null,
+ }));
}));
const [draft, artifact] = await Promise.all([
check(project.videoDraft?.sources || []),
@@ -42,7 +55,7 @@ export async function getVideoSourceStatus(project) {
/** All public treatment/plan writers share this guard; draft edits stay repairable. */
export async function assertVideoSourcesAvailable(project) {
- if (project?.workspace !== 'video') return;
+ if (project?.workspace !== 'video') return undefined;
const { draft } = await getVideoSourceStatus({ ...project, treatment: null });
const missing = draft.filter(source => !source.available);
if (missing.length) {
@@ -50,4 +63,5 @@ export async function assertVideoSourcesAvailable(project) {
status: 409, code: 'VIDEO_SOURCE_MISSING',
});
}
+ return Object.fromEntries(draft.map(source => [source.referenceId, source.currentRevision]));
}
diff --git a/server/services/projectDbStore.js b/server/services/projectDbStore.js
index 1a088f3148..6081d3d4f9 100644
--- a/server/services/projectDbStore.js
+++ b/server/services/projectDbStore.js
@@ -102,7 +102,7 @@ export function createProjectDbStore({ table, kind, idPrefix, logEmoji, logLabel
if (allowMissing) return { __missing: true };
throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });
}
- const { project: next, result, skipPersist } = mutate(project);
+ const { project: next, result, skipPersist } = await mutate(project);
const persisted = skipPersist ? next : await persist(client.query.bind(client), next);
return { project: persisted, result };
});