tests/video-production.test.ts
import { describe, it, expect, vi } from "vitest";
import { readdirSync, readFileSync } from "node:fs";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import agentModule, { handleMcpMessage, makeContext, manifest, validateManifest, validateArgv } from "../src/index.js";
const agent: any = agentModule;
const SCRIPT = {
title: "Offline mode in 30 seconds",
duration_seconds: 30,
segments: [
{ start: 0, end: 3, text: "Lost signal on the train? Your notes still save.", kind: "hook" },
{ start: 3, end: 15, text: "Oakline Notes keeps a local copy of every note and syncs changes when you reconnect. Sync finishes 40% faster than last year.", kind: "body" },
{ start: 15, end: 24, text: "Conflicts are merged line by line, so nothing you typed offline is lost.", kind: "body" },
{ start: 24, end: 30, text: "Try it free at oakline.example.", kind: "cta" },
],
claims: [
{ text: "Sync finishes 40% faster than last year.", source_url: "https://www.oakline.example/blog/sync-speed", segment: 1 },
{ text: "An unmatched claim", source_url: "https://stats.example/report" },
],
};
describe("video-production: manifest and safety", () => {
it("passes validateManifest, is offline, and only render starts processes (without a shell)", async () => {
expect(validateManifest(manifest)).toEqual([]);
expect(manifest.id).toBe("agentrove.video-production");
expect(manifest.permissions).toMatchObject({ filesystem: "read_write", network: [], credentials: [] });
for (const t of manifest.tools) {
if (t.name === "render") expect(t).toMatchObject({ side_effects: "writes_local_files", requires_confirmation: true });
else expect(t, t.name).toMatchObject({ side_effects: "none", requires_confirmation: false });
}
const fetch = vi.fn();
await expect(makeContext(manifest, { fetch }).fetch("https://example.com/")).rejects.toMatchObject({ code: "network_denied" });
expect(fetch).not.toHaveBeenCalled();
const srcDir = new URL("../src/", import.meta.url);
for (const f of readdirSync(srcDir)) {
const code = readFileSync(new URL(f, srcDir), "utf8");
if (f === "run.js") {
// The render module: spawn with an argv array and shell: false; never exec/execSync or a shell.
expect(code).toMatch(/import \{ spawn \} from "node:child_process"/);
expect(code).toMatch(/shell: false/);
// Patterns are assembled from parts so this test file does not itself look like a shell call to scanners.
const forbidden = [new RegExp("(?<![.\\w])" + "exec" + "(Sync)?\\("), new RegExp("shell" + ":\\s*" + "true"), new RegExp("exec" + "File")];
for (const re of forbidden) expect(code).not.toMatch(re);
} else expect(code, f).not.toMatch(/child_process|\bspawn\(|\bexecFile\(|writeFile/);
}
});
});
describe("video-production: plan_production", () => {
it("builds shots, b-roll needs, on-screen text and a CMX3600 EDL from the script", async () => {
const out = await agent.call("plan_production", { script: SCRIPT });
expect(out).toMatchObject({ title: "Offline mode in 30 seconds", fps: 30, aspect_ratio: "9:16", duration_seconds: 30 });
expect(out.shots.map((s: any) => [s.id, s.segment, s.type, s.start, s.end, s.framing])).toEqual([
["S01", 0, "a_roll", 0, 3, "close-up"],
["S02", 1, "a_roll", 3, 9, "medium"],
["S03", 1, "b_roll", 9, 15, "cutaway"],
["S04", 2, "a_roll", 15, 19.5, "medium close-up"],
["S05", 2, "b_roll", 19.5, 24, "cutaway"],
["S06", 3, "a_roll", 24, 30, "medium"],
]);
expect(out.broll[0]).toMatchObject({ id: "B01", shot_id: "S03", source_url: "https://www.oakline.example/blog/sync-speed" });
expect(out.broll[0].rights_note).toMatch(/Do not copy video/);
expect(out.broll[1]).toMatchObject({ id: "B02", shot_id: "S05", keywords: ["line", "conflicts", "merged", "nothing"], need: "Footage that shows: line, conflicts, merged, nothing" });
expect(out.onscreen_text.map((t: any) => [t.role, t.text, t.start, t.end])).toEqual([
["hook_title", "Lost signal on the train? Your\u2026", 0, 3],
["key_number", "40%", 3, 15],
["source_credit", "Source: oakline.example", 3, 15],
["end_card", "Try it free at oakline.example.", 24, 30],
["sources_card", "Sources: stats.example", 24, 30],
]);
expect(out.shots[1].text_ids).toEqual(["T02", "T03"]);
expect(out.safe_area).toMatch(/bottom 20%/);
expect(out.warnings.join(" ")).toMatch(/1 sourced claim\(s\) did not match a segment/);
const lines = out.edl.text.split("\n");
expect(lines[0]).toBe("TITLE: Offline mode in 30 seconds");
expect(lines[1]).toBe("FCM: NON-DROP FRAME");
expect(lines[3]).toBe("001 AROLL AA/V C 00:00:00:00 00:00:03:00 00:00:00:00 00:00:03:00");
expect(lines[4]).toBe("* FROM CLIP NAME: a_roll.mp4");
expect(out.edl.events.map((e: any) => [e.event, e.reel, e.track])).toEqual([
[1, "AROLL", "AA/V"], [2, "AROLL", "AA/V"], [3, "AROLL", "AA"], [4, "BROLL", "V"], [5, "AROLL", "AA/V"], [6, "AROLL", "AA"], [7, "BROLL", "V"], [8, "AROLL", "AA/V"],
]);
expect(out.edl.events[3]).toMatchObject({ source_in: "00:00:00:00", source_out: "00:00:06:00", record_in: "00:00:09:00", record_out: "00:00:15:00" });
expect(out.edl.text).toContain("* B-ROLL NEEDED: Source card or screenshot showing the claim from oakline.example");
});
it("uses the frame rate for timecodes and handles edge cases", async () => {
const out = await agent.call("plan_production", { script: SCRIPT, fps: 25, max_shot_seconds: 30, a_roll_reel: "TAKE1", aspect_ratio: "16:9" });
expect(out.shots).toHaveLength(4);
expect(out.broll).toHaveLength(0);
const weird = await agent.call("plan_production", { script: { title: "Caf\u00e9 \u2014 <b>demo</b>", segments: [{ start: 0, end: 2.02, text: "Hi" }, { start: 1.5, end: 3, text: "Overlap" }, { start: 5, end: 6, text: "After a gap" }] } });
expect(weird.edl.text.split("\n")[0]).toBe("TITLE: Caf? ? demo");
expect(weird.warnings.join(" ")).toMatch(/overlap by 0\.52 s/);
expect(weird.warnings.join(" ")).toMatch(/Gap of 2 s before segment 2/);
expect(weird.warnings.join(" ")).toMatch(/No segment has kind "hook"/);
const fps25 = await agent.call("plan_production", { script: { segments: [{ start: 0, end: 19.5, text: "x" }] }, fps: 25, max_shot_seconds: 60 });
expect(fps25.edl.events[0].record_out).toBe("00:00:19:13");
});
it("shows real figures with units (not years or trailing commas) and keeps host names out of b-roll keywords", async () => {
const script = {
segments: [
{ start: 0, end: 3, text: "E-bikes are booming.", kind: "hook" },
{ start: 3, end: 15, text: "According to transport.example.org and news.example.com: e-bike sales in Canada rose 18 percent in 2025, and the average commute was 9.4 km each way.", kind: "body" },
{ start: 15, end: 27, text: "Provinces offer rebates of up to $1,500 on 3 models, said blog.example.net in 2026.", kind: "body" },
],
};
const out = await agent.call("plan_production", { script });
expect(out.onscreen_text.filter((t: any) => t.role === "key_number").map((t: any) => t.text)).toEqual(["18%", "9.4 km", "$1,500"]);
expect(out.broll[0].keywords).not.toEqual(expect.arrayContaining(["according", "transport", "example", "news"]));
expect(out.broll[0].keywords).toEqual(expect.arrayContaining(["e-bike", "sales"]));
});
it("rejects invalid input", async () => {
await expect(agent.call("plan_production", { script: { segments: [] } })).rejects.toMatchObject({ code: "invalid_input" });
await expect(agent.call("plan_production", { script: { segments: [{ start: 5, end: 5, text: "x" }] } })).rejects.toMatchObject({ code: "invalid_input" });
await expect(agent.call("plan_production", { script: SCRIPT, fps: 29.97 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(agent.call("plan_production", { script: SCRIPT, a_roll_reel: "lower case" })).rejects.toMatchObject({ code: "invalid_input" });
});
});
describe("video-production: export_captions", () => {
it("exports wrapped SRT and WebVTT cues inside each segment", async () => {
const out = await agent.call("export_captions", { script: SCRIPT });
expect(out.captions_vtt.startsWith("WEBVTT\n\n1\n00:00:00.000 --> ")).toBe(true);
expect(out.captions_srt.startsWith("1\n00:00:00,000 --> ")).toBe(true);
expect(out.cues.every((c: any) => c.lines.length <= 2 && c.lines.every((l: string) => l.length <= 42))).toBe(true);
const seg1 = out.cues.filter((c: any) => c.start >= 3 && c.end <= 15);
expect(seg1.length).toBeGreaterThanOrEqual(2);
expect(seg1[0].start).toBe(3);
expect(seg1[seg1.length - 1].end).toBe(15);
for (let k = 1; k < out.cues.length; k++) expect(out.cues[k].start).toBeGreaterThanOrEqual(out.cues[k - 1].end);
expect(out.captions_srt).toMatch(/\n\d+\n\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}\n/);
expect(out.cues[out.cues.length - 1]).toMatchObject({ end: 30, lines: ["Try it free at oakline.example."] });
});
it("strips markup, escapes VTT, fixes overlaps and applies offsets", async () => {
const script = { segments: [{ start: 0, end: 5, text: "<i>Hi</i> {\\an8}there --> now & then <script>x</script>" }, { start: 4, end: 8, text: "3 < 5 and 6 > 2" }, { start: 9, end: 10, text: " " }] };
const out = await agent.call("export_captions", { script, offset_seconds: -0.5, max_chars_per_line: 20, max_lines: 1 });
expect(out.cues[0]).toMatchObject({ start: 0 });
expect(out.cues.map((c: any) => c.lines.join(" ")).join(" | ")).toBe("Hi there -> | now & then x | 3 < 5 and 6 > 2");
expect(out.captions_vtt).toContain("Hi there ->\n");
expect(out.captions_vtt).toContain("now & then x\n");
expect(out.captions_vtt).toContain("3 < 5 and 6 > 2");
expect(out.captions_srt).not.toMatch(/<i>|<script>|\{\\an8\}/);
expect(out.cues[1].end).toBe(3.5);
const w = out.warnings.join(" ");
expect(w).toMatch(/overlapping cue/);
expect(w).toMatch(/markup, control characters or "-->" removed/);
expect(w).toMatch(/Segment 2 has no caption text/);
});
it("breaks cues at sentence and clause ends, balances lines and keeps every word in order", async () => {
const text = "According to transport.example.org and news.example.com: e-bike sales in Canada rose 18% in 2025, the national cycling retailers group said on Tuesday. Vancouver shops reported waiting lists.";
const out = await agent.call("export_captions", { script: { segments: [{ start: 0, end: 12, text }] } });
const cues = out.cues.map((c: any) => c.lines.join(" "));
expect(cues.join(" ")).toBe(text);
expect(cues).toEqual([
"According to transport.example.org and news.example.com:",
"e-bike sales in Canada rose 18% in 2025,",
"the national cycling retailers group said on Tuesday.",
"Vancouver shops reported waiting lists.",
]);
// Two balanced lines instead of a full line and a stub.
expect(out.cues[0].lines).toEqual(["According to transport.example.org", "and news.example.com:"]);
for (const c of out.cues) expect(c.lines.every((l: string) => l.length <= 42) && c.lines.length <= 2).toBe(true);
// A single unbreakable word longer than a cue still produces captions (greedy fallback).
const long = await agent.call("export_captions", { script: { segments: [{ start: 0, end: 4, text: "x".repeat(200) }] }, max_chars_per_line: 20, max_lines: 1 });
expect(long.cues.map((c: any) => c.lines.join("")).join("")).toBe("x".repeat(200));
});
});
describe("video-production: ffmpeg_commands (text only)", () => {
it("builds quoted trim, concat, caption burn-in and fit commands without running them", async () => {
const out = await agent.call("ffmpeg_commands", {
operations: [
{ op: "trim", input: "raw take.mp4", output: "hook.mp4", start: "00:00:01.5", end: 4 },
{ op: "concat", inputs: ["hook.mp4", "body.mp4", "/abs/cta.mp4"], output: "final.mp4" },
{ op: "concat", method: "filter", inputs: ["a.mp4", "b.mp4"], output: "joined.mp4" },
{ op: "burn_captions", input: "final.mp4", subtitles: "C:\\clips\\it's, [v1].srt", output: "final-captioned.mp4", font_size: 18 },
{ op: "fit", input: "wide.mp4", output: "vertical.mp4", width: 1080, height: 1920 },
],
});
expect(out.executed).toBe(false);
const [trim, concat, filterConcat, burn, fit] = out.commands;
expect(trim.argv).toEqual(["ffmpeg", "-hide_banner", "-nostdin", "-n", "-ss", "1.5", "-i", "raw take.mp4", "-t", "2.5", "-c", "copy", "hook.mp4"]);
expect(trim.command).toBe("ffmpeg -hide_banner -nostdin -n -ss 1.5 -i 'raw take.mp4' -t 2.5 -c copy hook.mp4");
expect(concat.files).toEqual([{ path: "concat-list.txt", content: "file 'hook.mp4'\nfile 'body.mp4'\nfile '/abs/cta.mp4'\n" }]);
expect(concat.argv).toContain("-safe");
expect(filterConcat.argv).toContain("[0:v][0:a][1:v][1:a]concat=n=2:v=1:a=1[v][a]");
// Two-level filtergraph escaping: level 1 escapes \ ' : in the value, level 2 escapes \ ' [ ] , ; in the arguments.
expect(burn.argv[burn.argv.indexOf("-vf") + 1]).toBe("subtitles=filename=C\\\\:/clips/it\\\\\\'s\\, \\[v1\\].srt:force_style=FontSize=18\\,Outline=2\\,MarginV=40\\,Alignment=2");
expect(burn.command).toContain("-vf 'subtitles=filename=C\\\\:/clips/it\\\\\\'\\''s\\, \\[v1\\].srt:");
expect(burn.notes.join(" ")).toMatch(/libass/);
expect(fit.argv[fit.argv.indexOf("-vf") + 1]).toBe("scale=w=1080:h=1920:force_original_aspect_ratio=decrease,pad=w=1080:h=1920:x=(ow-iw)/2:y=(oh-ih)/2,setsar=1");
expect(out.warnings.join(" ")).toMatch(/NOT run/);
expect(out.allowed_options).toContain("-vf");
});
it("quotes for PowerShell and honours overwrite and a custom ffmpeg path", async () => {
const out = await agent.call("ffmpeg_commands", { shell: "powershell", overwrite: true, ffmpeg_binary: "C:/Tools/ffmpeg/bin/ffmpeg.exe", operations: [{ op: "trim", input: "it's me.mp4", output: "out.mp4", duration: 3, reencode: true }] });
const c = out.commands[0];
expect(c.argv[3]).toBe("-y");
expect(c.command.startsWith("& 'C:/Tools/ffmpeg/bin/ffmpeg.exe' -hide_banner -nostdin -y -ss 0 -i 'it''s me.mp4' -t 3 '-c:v' libx264")).toBe(true);
await expect(agent.call("ffmpeg_commands", { ffmpeg_binary: "rm", operations: [{ op: "trim", input: "a.mp4", output: "b.mp4", duration: 1 }] })).rejects.toMatchObject({ code: "invalid_input" });
});
it("refuses unsafe paths and invalid operations", async () => {
const bad = (o: any) => agent.call("ffmpeg_commands", { operations: [o] });
await expect(bad({ op: "trim", input: "-filter_complex.mp4", output: "b.mp4", duration: 1 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "trim", input: "http://evil.example/a.mp4", output: "b.mp4", duration: 1 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "concat", inputs: ["concat:a.mp4|b.mp4", "c.mp4"], output: "d.mp4" })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "trim", input: "a.mp4\n-y", output: "b.mp4", duration: 1 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "trim", input: "a.mp4", output: "run.sh", duration: 1 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "trim", input: "a.mp4", output: "a.mp4", duration: 1 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "trim", input: "a.mp4", output: "b.mp4", start: 5, end: 2 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "trim", input: "a.mp4", output: "b.mp4", start: "1:75", end: 2 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "burn_captions", input: "a.mp4", subtitles: "subs.txt", output: "b.mp4" })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "fit", input: "a.mp4", output: "b.mp4", width: 1081, height: 1920 })).rejects.toMatchObject({ code: "invalid_input" });
await expect(bad({ op: "explode", input: "a.mp4", output: "b.mp4" })).rejects.toMatchObject({ code: "invalid_input" });
});
it("builds WebM (VP9/Opus) and transcode commands and refuses stream copy across containers", async () => {
const out = await agent.call("ffmpeg_commands", {
operations: [
{ op: "fit", input: "take.mp4", output: "wide.webm", width: 1920, height: 1080, preset: "ultrafast" },
{ op: "transcode", input: "take.mp4", output: "take.webm" },
{ op: "transcode", input: "take.webm", output: "take-h264.mp4" },
{ op: "trim", input: "take.mkv", output: "cut.mkv", duration: 2 },
{ op: "burn_captions", input: "take.mkv", subtitles: "subs.srt", output: "subbed.mkv" },
],
});
const [fit, toWebm, toMp4, trimMkv, burnMkv] = out.commands;
expect(fit.argv.slice(fit.argv.indexOf("-c:v"), -1)).toEqual(["-c:v", "libvpx-vp9", "-crf", "32", "-b:v", "0", "-deadline", "realtime", "-cpu-used", "8", "-row-mt", "1", "-pix_fmt", "yuv420p", "-c:a", "libopus", "-b:a", "128k"]);
expect(toWebm.argv).toEqual(expect.arrayContaining(["-deadline", "good", "-cpu-used", "3", "-c:a", "libopus"]));
expect(toWebm.argv).not.toContain("-movflags");
expect(toMp4.argv).toEqual(expect.arrayContaining(["-c:v", "libx264", "-c:a", "aac", "-movflags", "+faststart"]));
expect(trimMkv.argv).toEqual(expect.arrayContaining(["-c", "copy"]));
expect(burnMkv.argv).not.toContain("-movflags");
expect(burnMkv.argv).toEqual(expect.arrayContaining(["-c:a", "copy"]));
expect(fit.notes.join(" ")).toMatch(/VP9/);
const bad = (o: any) => agent.call("ffmpeg_commands", { operations: [o] });
await expect(bad({ op: "trim", input: "a.mp4", output: "b.webm", duration: 1 })).rejects.toThrow(/stream copy cannot/);
await expect(bad({ op: "concat", inputs: ["a.mp4", "b.mp4"], output: "c.webm" })).rejects.toThrow(/concat demuxer copies streams/);
expect((await bad({ op: "trim", input: "a.mp4", output: "b.webm", duration: 1, reencode: true })).commands[0].argv).toContain("libvpx-vp9");
});
it("validates argv against the option and filter allowlists", () => {
expect(validateArgv(["ffmpeg", "-n", "-i", "a.mp4", "-c", "copy", "b.mp4"])).toBe(true);
const code = (argv: string[]) => {
try {
validateArgv(argv);
return "ok";
} catch (e: any) {
return e.code;
}
};
expect(code(["ffmpeg", "-i", "a.mp4", "-filter_script", "x.txt", "b.mp4"])).toBe("invalid_command");
expect(code(["ffmpeg", "-f", "lavfi", "-i", "anullsrc", "b.mp4"])).toBe("invalid_command");
expect(code(["ffmpeg", "-i", "a.mp4", "-vf", "movie=secret.mp4,overlay", "b.mp4"])).toBe("invalid_command");
expect(code(["ffmpeg", "-i", "a.mp4", "-vf", "scale=w=10:h=10,drawtext=textfile=/etc/passwd", "b.mp4"])).toBe("invalid_command");
expect(code(["ffmpeg", "-i", "a.mp4", "-c:v", "libx264; rm -rf /", "b.mp4"])).toBe("invalid_command");
expect(code(["ffmpeg", "-i", "pipe:0", "b.mp4"])).toBe("invalid_input");
expect(code(["ffmpeg", "-i", "a.mp4", "-crf", "99", "b.mp4"])).toBe("invalid_command");
expect(code(["ffmpeg", "-i", "a.mp4", "-ss"])).toBe("invalid_command");
});
});
describe("video-production: MCP", () => {
it("lists and calls tools over JSON-RPC", async () => {
const list = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 1, method: "tools/list" });
expect(list.result.tools.map((t: any) => t.name)).toEqual(["plan_production", "ffmpeg_commands", "export_captions", "render"]);
const call = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "export_captions", arguments: { script: SCRIPT } } });
expect(call.result.isError).toBe(false);
expect(call.result.structuredContent.captions_vtt.startsWith("WEBVTT")).toBe(true);
const bad = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "ffmpeg_commands", arguments: { operations: [{ op: "trim", input: "http://x/a.mp4", output: "b.mp4", duration: 1 }] } } });
expect(bad.result.isError).toBe(true);
expect(bad.result.content[0].text).toMatch(/^invalid_input: /);
});
});