Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(producer): segment manifest with content-addressed plan hash
Vance Ingalls5daaae849877
diff --git a/packages/producer/src/services/render/segmentManifest.test.ts b/packages/producer/src/services/render/segmentManifest.test.tsnew file mode 100644index 0000000000..0588816f37--- /dev/null+++ b/packages/producer/src/services/render/segmentManifest.test.ts@@ -0,0 +1,186 @@+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import {+ computeSegmentPlanHash,+ readSegmentManifest,+ segmentDirFor,+ validateCompletedSegments,+ writeSegmentManifest,+ type SegmentManifest,+ type SegmentPlanHashInput,+} from "./segmentManifest.js";++const hashInput: SegmentPlanHashInput = {+ compositionHash: "abc",+ cliVersion: "0.8.50",+ totalFrames: 9000,+ segmentFrames: 3000,+ fps: { num: 30, den: 1 },+ width: 1920,+ height: 1080,+ codec: "h264",+ preset: "ultrafast",+ quality: 28,+ bitrate: undefined,+ pixelFormat: "yuv420p",+ imageFormat: "jpeg",+};++describe("computeSegmentPlanHash", () => {+ it("is stable and 16 hex chars", () => {+ const a = computeSegmentPlanHash(hashInput);+ expect(a).toMatch(/^[0-9a-f]{16}$/);+ expect(computeSegmentPlanHash({ ...hashInput })).toBe(a);+ });++ it("changes when any byte-determining input changes", () => {+ // Every field here changes the encoded bytes, so reusing a segment across+ // a change in any of them would splice two different encodes together.+ const a = computeSegmentPlanHash(hashInput);+ expect(computeSegmentPlanHash({ ...hashInput, segmentFrames: 1500 })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, quality: 18 })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, compositionHash: "abd" })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, cliVersion: "0.8.51" })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, totalFrames: 8999 })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, fps: { num: 60, den: 1 } })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, width: 1280 })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, height: 720 })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, codec: "h265" })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, preset: "slow" })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, bitrate: "8M" })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, pixelFormat: "yuv420p10le" })).not.toBe(a);+ expect(computeSegmentPlanHash({ ...hashInput, imageFormat: "png" })).not.toBe(a);+ });++ it("does not collide across adjacent field boundaries", () => {+ // The fields are joined; without a separator "ab"+"c" and "a"+"bc" would+ // hash identically and resume across a different composition.+ expect(+ computeSegmentPlanHash({ ...hashInput, compositionHash: "ab", cliVersion: "c0.8.50" }),+ ).not.toBe(computeSegmentPlanHash({ ...hashInput, compositionHash: "abc" }));+ });+});++describe("manifest io", () => {+ let dir = "";+ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ it("round-trips and returns null when absent or malformed", () => {+ dir = mkdtempSync(join(tmpdir(), "hf-seg-"));+ expect(readSegmentManifest(dir)).toBeNull();+ const manifest: SegmentManifest = {+ version: 1,+ planHash: "0123456789abcdef",+ totalFrames: 7,+ segmentFrames: 3,+ completed: [+ {+ index: 0,+ startFrame: 0,+ endFrame: 3,+ path: join(dir, "segment_00000.mp4"),+ bytes: 10,+ completedAt: "2026-09-17T00:00:00.000Z",+ },+ ],+ };+ writeSegmentManifest(dir, manifest);+ expect(readSegmentManifest(dir)).toEqual(manifest);+ writeFileSync(join(dir, "segments.json"), "{not json");+ expect(readSegmentManifest(dir)).toBeNull();+ });++ it("rejects a manifest whose shape is wrong rather than resuming from it", () => {+ dir = mkdtempSync(join(tmpdir(), "hf-seg-"));+ writeFileSync(join(dir, "segments.json"), JSON.stringify({ version: 2, completed: [] }));+ expect(readSegmentManifest(dir)).toBeNull();+ writeFileSync(+ join(dir, "segments.json"),+ JSON.stringify({+ version: 1,+ planHash: "h",+ totalFrames: 3,+ segmentFrames: 3,+ completed: [{ index: 0, startFrame: 0 }],+ }),+ );+ expect(readSegmentManifest(dir)).toBeNull();+ });++ it("segmentDirFor nests under renders/.hf-segments", () => {+ dir = mkdtempSync(join(tmpdir(), "hf-seg-"));+ expect(segmentDirFor("/p/renders", "abc")).toBe("/p/renders/.hf-segments/abc");+ });+});++describe("validateCompletedSegments", () => {+ let dir = "";+ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ it("keeps only segments whose file exists and whose frame count matches", async () => {+ dir = mkdtempSync(join(tmpdir(), "hf-seg-"));+ mkdirSync(dir, { recursive: true });+ const ok = join(dir, "segment_00000.mp4");+ const short = join(dir, "segment_00001.mp4");+ writeFileSync(ok, "xx");+ writeFileSync(short, "xx");+ const manifest: SegmentManifest = {+ version: 1,+ planHash: "h",+ totalFrames: 9,+ segmentFrames: 3,+ completed: [+ { index: 0, startFrame: 0, endFrame: 3, path: ok, bytes: 2, completedAt: "" },+ { index: 1, startFrame: 3, endFrame: 6, path: short, bytes: 2, completedAt: "" },+ {+ index: 2,+ startFrame: 6,+ endFrame: 9,+ path: join(dir, "missing.mp4"),+ bytes: 2,+ completedAt: "",+ },+ ],+ };+ const probe = async (p: string) => (p === ok ? 3 : p === short ? 2 : null);+ expect([...(await validateCompletedSegments(manifest, "h", probe))]).toEqual([0]);+ });++ it("rejects a segment whose size no longer matches the manifest", async () => {+ // A half-written file from a kill can still exist and still probe; the+ // recorded size is what proves it is the same file that was finished.+ dir = mkdtempSync(join(tmpdir(), "hf-seg-"));+ const truncated = join(dir, "segment_00000.mp4");+ writeFileSync(truncated, "x");+ const manifest: SegmentManifest = {+ version: 1,+ planHash: "h",+ totalFrames: 3,+ segmentFrames: 3,+ completed: [+ { index: 0, startFrame: 0, endFrame: 3, path: truncated, bytes: 999, completedAt: "" },+ ],+ };+ expect((await validateCompletedSegments(manifest, "h", async () => 3)).size).toBe(0);+ });++ it("skips nothing when the plan hash differs", async () => {+ // The entry is otherwise perfectly reusable — present, right size, right+ // frame count — so only the hash check can reject it. With an empty+ // `completed` list this assertion would pass with the check deleted.+ dir = mkdtempSync(join(tmpdir(), "hf-seg-"));+ const good = join(dir, "segment_00000.mp4");+ writeFileSync(good, "xx");+ const manifest: SegmentManifest = {+ version: 1,+ planHash: "old",+ totalFrames: 3,+ segmentFrames: 3,+ completed: [{ index: 0, startFrame: 0, endFrame: 3, path: good, bytes: 2, completedAt: "" }],+ };+ expect((await validateCompletedSegments(manifest, "old", async () => 3)).size).toBe(1);+ expect((await validateCompletedSegments(manifest, "new", async () => 3)).size).toBe(0);+ });+});diff --git a/packages/producer/src/services/render/segmentManifest.ts b/packages/producer/src/services/render/segmentManifest.tsnew file mode 100644index 0000000000..1fcc268e22--- /dev/null+++ b/packages/producer/src/services/render/segmentManifest.ts@@ -0,0 +1,147 @@+/**+ * Segment manifest and resume bookkeeping (spec §5 Phase 2 item 3).+ *+ * A resumed render reuses encoded segments from a previous attempt, so a+ * wrong reuse silently corrupts the output rather than failing. Two things+ * guard that: the plan hash covers everything that determines segment bytes,+ * and every reused segment is re-validated on disk before it is skipped.+ */+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";++export interface SegmentManifestEntry {+ index: number;+ startFrame: number;+ endFrame: number;+ path: string;+ bytes: number;+ completedAt: string;+}++export interface SegmentManifest {+ version: 1;+ planHash: string;+ totalFrames: number;+ segmentFrames: number;+ completed: SegmentManifestEntry[];+}++export interface SegmentPlanHashInput {+ compositionHash: string;+ cliVersion: string;+ totalFrames: number;+ segmentFrames: number;+ fps: { num: number; den: number };+ width: number;+ height: number;+ codec: string;+ preset: string;+ quality: number | undefined;+ bitrate: string | undefined;+ pixelFormat: string | undefined;+ imageFormat: string;+}++const MANIFEST_FILENAME = "segments.json";++/** Everything that determines segment bytes. Key order is fixed by construction. */+export function computeSegmentPlanHash(input: SegmentPlanHashInput): string {+ const ordered = [+ input.compositionHash,+ input.cliVersion,+ String(input.totalFrames),+ String(input.segmentFrames),+ `${input.fps.num}/${input.fps.den}`,+ `${input.width}x${input.height}`,+ input.codec,+ input.preset,+ input.quality === undefined ? "" : String(input.quality),+ input.bitrate ?? "",+ input.pixelFormat ?? "",+ input.imageFormat,+ ].join(" ");+ return createHash("sha256").update(ordered).digest("hex").slice(0, 16);+}++export function segmentDirFor(projectRendersDir: string, planHash: string): string {+ return join(projectRendersDir, ".hf-segments", planHash);+}++function hasNumber(value: object, key: string): boolean {+ return key in value && typeof Reflect.get(value, key) === "number";+}++function hasString(value: object, key: string): boolean {+ return key in value && typeof Reflect.get(value, key) === "string";+}++function isEntry(value: unknown): value is SegmentManifestEntry {+ if (typeof value !== "object" || value === null) return false;+ return (+ hasNumber(value, "index") &&+ hasNumber(value, "startFrame") &&+ hasNumber(value, "endFrame") &&+ hasString(value, "path") &&+ hasNumber(value, "bytes") &&+ hasString(value, "completedAt")+ );+}++function isManifest(value: unknown): value is SegmentManifest {+ if (typeof value !== "object" || value === null) return false;+ const completed: unknown = Reflect.get(value, "completed");+ return (+ Reflect.get(value, "version") === 1 &&+ hasString(value, "planHash") &&+ hasNumber(value, "totalFrames") &&+ hasNumber(value, "segmentFrames") &&+ Array.isArray(completed) &&+ completed.every(isEntry)+ );+}++export function readSegmentManifest(segmentDir: string): SegmentManifest | null {+ const path = join(segmentDir, MANIFEST_FILENAME);+ if (!existsSync(path)) return null;+ try {+ const parsed: unknown = JSON.parse(readFileSync(path, "utf-8"));+ return isManifest(parsed) ? parsed : null;+ } catch {+ // A truncated or hand-edited manifest means "no resume", never a crash:+ // the render still has every frame it needs to capture from scratch.+ return null;+ }+}++/** Atomic: write to a temp name, then rename over the manifest. */+export function writeSegmentManifest(segmentDir: string, manifest: SegmentManifest): void {+ mkdirSync(segmentDir, { recursive: true });+ const tmp = join(segmentDir, `${MANIFEST_FILENAME}.${process.pid}.tmp`);+ writeFileSync(tmp, JSON.stringify(manifest, null, 2), "utf-8");+ renameSync(tmp, join(segmentDir, MANIFEST_FILENAME));+}++/**+ * Indices safe to skip on resume. A segment counts only if the hash matches,+ * the file exists at the recorded size, and its frame count equals the slice+ * length. Anything else re-captures — the cost of re-capturing a good segment+ * is minutes; the cost of reusing a bad one is a silently wrong video.+ */+export async function validateCompletedSegments(+ manifest: SegmentManifest,+ expectedHash: string,+ probeFrames: (path: string) => Promise<number | null>,+): Promise<Set<number>> {+ const ok = new Set<number>();+ if (manifest.planHash !== expectedHash) return ok;+ for (const entry of manifest.completed) {+ if (!existsSync(entry.path)) continue;+ const size = statSync(entry.path).size;+ if (size <= 0 || size !== entry.bytes) continue;+ const frames = await probeFrames(entry.path);+ if (frames !== entry.endFrame - entry.startFrame) continue;+ ok.add(entry.index);+ }+ return ok;+}