Skip to content

Local video editor for coding agents: 42 FFmpeg tools with a machine-readable contract and an MCP server, for Claude Code, Cursor and Codex. Cut, captions, reframe, loudness, platform exports. No cloud, no API keys.

feat: --plan FILE writes the dry run as a plan that render.py executes (#196)

claude[bot]cf579ac9fead
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f0fa201..c2b9b87 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@
## Unreleased
-(nothing yet)
+- `--plan FILE` on every tool: the dry run written as a plan (tool, argv, fingerprinted inputs, commands, expected output, verify steps) that `render.py FILE` executes later, refusing if an input changed since the plan was made and running the verify steps (probe, `check` for a platform) afterwards. "Plan → user confirms → execute" is one round trip (issue #189 C).
## 1.5.2
diff --git a/README.md b/README.md
index cf9c229..5eab6ee 100644
--- a/README.md
+++ b/README.md
@@ -143,7 +143,7 @@ These are the rules the skill file gives the agent and the code enforces. Togeth
1. **Probe first.** No tool decides from the file name. `probe.py` measures duration, fps (with variable-frame-rate detection), resolution, rotation, bit depth, HDR format including Dolby Vision, colour tags and every audio stream before anything is cut.
2. **Lossless when possible.** `cut.py`, `join.py` and `loudness.py` stream-copy what they do not need to touch. Re-encoding happens only when it must: frame-accurate cuts, filters, format changes, or a keyframe farther than the tolerance.
-3. **Plan before render.** Every tool takes `--dry-run` (print the ffmpeg command lines, write nothing), `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress` (percent and ETA), `--timeout` (a hung ffmpeg is killed and reported, never waited on forever; Ctrl-C or SIGTERM likewise stops the running ffmpeg, removes its partial output and reports `kind: interrupted`) and `--overwrite` (explicit consent before an existing output is replaced). A test runs every tool under `--dry-run` behind a fake ffmpeg and asserts that no ffmpeg call happened and no file appeared.
+3. **Plan before render.** Every tool takes `--dry-run` (print the ffmpeg command lines, write nothing), `--plan FILE` (the dry run saved as a plan with fingerprinted inputs that `render.py FILE` executes later, refusing if an input changed), `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress` (percent and ETA), `--timeout` (a hung ffmpeg is killed and reported, never waited on forever; Ctrl-C or SIGTERM likewise stops the running ffmpeg, removes its partial output and reports `kind: interrupted`) and `--overwrite` (explicit consent before an existing output is replaced). A test runs every tool under `--dry-run` behind a fake ffmpeg and asserts that no ffmpeg call happened and no file appeared.
4. **Machine-readable contract.** `contract --json` describes all 42 tools: input schema generated from the parser, output schema, role, required and conditional FFmpeg capabilities, dry-run support, the verification tools to run afterwards, whether a visual check is required, `mutates_input: false`. `provides` lists all 42 by a cross-repository Capability id (`ffmpeg-skill.cut`, `ffmpeg-skill.loudness`, ...) for [`kajisho5/AI-video-production-OS`](https://github.com/kajisho5/AI-video-production-OS)'s `CapabilityContract.provides` — see `docs/contract.md`.
5. **Contract-derived MCP.** `mcp/server.py` builds its `tools/list` from the contract. Tool names, order and `inputSchema` cannot drift from the scripts; a test keeps the two byte-identical.
6. **Capability detection.** `doctor` reads `ffmpeg -encoders / -filters / -bsfs` and reports which of the components the tools need are present on this build (libx264, libass, zscale, loudnorm, xfade, …), before a job fails inside ffmpeg.
diff --git a/SKILL.md b/SKILL.md
index 80024a9..201975c 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -5,7 +5,7 @@ description: 'Edit video and audio with local FFmpeg from natural-language reque
# ffmpeg-skill
-Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. Every script has `--help`, and all of them accept `--dry-run`, `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress`, `--timeout SECONDS` (a single ffmpeg run is killed past this and reported as `kind: timeout`; default 1800) and `--overwrite` (consent to replace an output that already exists; without it the tool warns today and refuses from 2.0). Writing tools run nothing under `--dry-run`; `probe`/`check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`). Details for every flag: `references/scripts.md`. Device-specific behaviour (iPhone HDR, GoPro, DJI, screen recordings, Zoom): `references/devices.md`.
+Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`. Every script has `--help`, and all of them accept `--dry-run`, `--json` (structured result with a probe of the output), `--fast` (preview quality), `--progress`, `--timeout SECONDS` (a single ffmpeg run is killed past this and reported as `kind: timeout`; default 1800) and `--overwrite` (consent to replace an output that already exists; without it the tool warns today and refuses from 2.0) and `--plan FILE` (a dry run written as a plan: fingerprinted inputs, commands, expected output, verify steps; `render.py FILE` executes it later and refuses if an input changed, so "plan → user confirms → execute" is one round trip). Writing tools run nothing under `--dry-run`; `probe`/`check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact (nor side files such as `--edl`, `--sheet` or a generated `.ass`); `verify` accepts the flag but ignores it. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`). Details for every flag: `references/scripts.md`. Device-specific behaviour (iPhone HDR, GoPro, DJI, screen recordings, Zoom): `references/devices.md`.
## Workflow (always follow this order)
diff --git a/docs/contract.md b/docs/contract.md
index abca184..41a8585 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -162,6 +162,14 @@ tool's job; only the artifact is skipped, including side files such as `--edl`,
generated `.ass`), and `verify` does not support dry-run (its steps run). `SKILL.md` and
`references/scripts.md` repeat the same list; the contract is the authority.
+`--plan FILE` (1.6) is a dry run that also writes a plan document: `{"plan_version": 1,
+"tool", "argv", "cwd", "inputs": [{"path", "size", "sha256_head_tail"}], "commands",
+"output", "verify": [{"tool": "probe"}, {"tool": "check", "platform"}], "notes"}`. It
+implies `--dry-run`, so the same execution rules apply. `render.py FILE` executes a plan:
+it refuses (`kind: input`) when an input's size or head/tail hash differs from the plan,
+runs the tool with the planned `argv`, then the verify steps, and reports `plan`, `tool`,
+`tool_result` and `check`. `plan_version` is bumped when the document's shape changes.
+
### Repeatability
No tool keeps state or uses randomness. `deterministic_inputs` is `false` only for
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index c352c7a..8b713d9 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -103,6 +103,13 @@ exists. When a decision changes, edit the entry in the same PR.
130/143 are reserved for timeout, missing tool and interrupts; passing the raw code through
made the process exit code depend on the ffmpeg build. The raw code is in the JSON failure
document as `ffmpeg_returncode`. Code: `_common._fail()`.
+- **A plan is a dry run plus fingerprints, executed only by `render.py`.** `--plan FILE` is
+ implemented once in `emit()` (every tool gets it, nothing per tool), inputs are found from the
+ `-i` arguments of the planned commands, and the fingerprint is size + sha256 of the first and
+ last 8 MiB rather than the whole file, so planning a multi-GB master stays instant while a
+ re-export or re-trim is still caught. Execution re-runs the *tool* with the planned argv, not
+ the recorded command lines: the tool's own guards, staging and verification stay in force.
+ Code: `_common.write_plan()`, `render.execute_plan()`.
- **The 2.0 success-document shape ships in 1.x as an opt-in parallel key.** `result_v2`
(`FFMPEG_SKILL_RESULT_V2=1`) is built once in `emit()` from what every tool already passes,
so no tool changes its own keys and 2.0 becomes "promote `result_v2` to the top level". Per
diff --git a/references/scripts.md b/references/scripts.md
index 673a1e6..8e677ca 100644
--- a/references/scripts.md
+++ b/references/scripts.md
@@ -1,6 +1,6 @@
# Script reference
-Every script prints the same information with `--help`; this file exists so the agent can read several at once. All scripts accept `--dry-run`, `--json`, `--fast`, `--progress`, `--timeout SECONDS`, `--overwrite`, `-o OUT` -- but `--dry-run` only guarantees nothing is written for writing tools: `probe` (read-only, `--dry-run` changes nothing) still runs ffprobe, `check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` still run their ffmpeg/ffprobe measurements (a dry-run plan rests on real numbers; they just don't write the final artifact), and `verify` accepts the flag but ignores it entirely. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).
+Every script prints the same information with `--help`; this file exists so the agent can read several at once. All scripts accept `--dry-run`, `--json`, `--fast`, `--progress`, `--timeout SECONDS`, `--overwrite`, `--plan FILE` (the dry run written as a plan document that `render.py FILE` executes later; see render.py), `-o OUT` -- but `--dry-run` only guarantees nothing is written for writing tools: `probe` (read-only, `--dry-run` changes nothing) still runs ffprobe, `check`/`sync`/`multicam`/`scenes`/`cropdetect`/`report`/`silence`/`loudness`/`stabilize` still run their ffmpeg/ffprobe measurements (a dry-run plan rests on real numbers; they just don't write the final artifact), and `verify` accepts the flag but ignores it entirely. Exact per-tool semantics: `contract --json`'s `dry_run` field (or `docs/contract.md`).
## Contents
- probe.py — inspect
@@ -375,7 +375,17 @@ output; the result says so with `dropped_non_av_streams: true`.
```
render.py --init project.json # starter file
render.py project.json [--fast] [--dry-run] [--stop-after STAGE] [--work DIR --keep]
+render.py plan.json # execute a plan written by <tool> --plan plan.json
```
+A plan is a single tool's dry run as an artifact: `cut.py in.mp4 --start 2 --end 8
+--plan cut.json` writes `{plan_version, tool, argv, inputs (path, size, sha256 of
+head+tail), commands, output, verify}` and runs nothing. `render.py cut.json`
+re-fingerprints the inputs (refusing, `kind: input`, if any changed since the
+plan), runs the tool with the planned argv, then the verify steps (probe; `check`
+for a `--platform` or a platform export preset), and reports `plan`, `tool`,
+`tool_result` and `check`. Show the plan to the user, get the yes, execute:
+one round trip instead of re-deriving the command.
+
Stages: clips (cut, optional speed) → join (transition) → silence → fit →
captions → graphics → overlays → audio → loudness → export → check. Keys mirror the
CLI flags of each script (see the docstring). Use it whenever an edit has
diff --git a/scripts/_common.py b/scripts/_common.py
index bd44393..0a7f87e 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -227,7 +227,7 @@ class Context:
makes it obvious what run()/emit() depend on and lets tests reset it with ``STATE.reset()``.
"""
- __slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written", "preexisting")
+ __slots__ = ("dry_run", "json", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written", "preexisting", "plan")
def __init__(self) -> None:
self.reset()
@@ -243,6 +243,7 @@ class Context:
self.overwrite = False # --overwrite: an existing output may be replaced
self.written: set = set() # output paths this process has written itself
self.preexisting: dict = {} # output path -> (size, mtime_ns) of a file that was there before we ran
+ self.plan: Optional[str] = None # --plan FILE: write the dry-run as a plan document (implies --dry-run)
@@ -261,10 +262,13 @@ def add_common(ap: "argparse.ArgumentParser") -> None:
help=f"kill an ffmpeg run past this many seconds, kind=timeout (default {DEFAULT_TIMEOUT:.0f}; 0 = no limit)")
g.add_argument("--overwrite", action="store_true",
help="allow replacing an existing output (warned today, refused from 2.0)")
+ g.add_argument("--plan", metavar="FILE",
+ help="write the dry run as a plan (inputs fingerprinted, commands, expected output, verify steps) that render.py FILE executes later; implies --dry-run")
def apply_common(args: "argparse.Namespace") -> None:
- STATE.dry_run = bool(getattr(args, "dry_run", False))
+ STATE.plan = getattr(args, "plan", None) or None
+ STATE.dry_run = bool(getattr(args, "dry_run", False)) or bool(STATE.plan)
STATE.json = bool(getattr(args, "json", False))
STATE.progress = bool(getattr(args, "progress", False))
STATE.fast = bool(getattr(args, "fast", False))
@@ -350,11 +354,102 @@ def emit(output: Optional[str], **extra: Any) -> None:
doc.update(extra)
if os.environ.get("FFMPEG_SKILL_RESULT_V2", "") not in ("", "0"):
doc["result_v2"] = _result_v2(output, meta, extra)
+ if STATE.plan:
+ doc["plan"] = write_plan(STATE.plan, output, extra)
print_json(doc)
+ elif STATE.plan:
+ print(write_plan(STATE.plan, output, extra))
elif output:
print(output)
+PLAN_VERSION = 1
+_PLAN_STRIP = ("--plan", "--dry-run", "--json")
+
+
+def fingerprint(path: str) -> Dict[str, Any]:
+ """Size plus a sha256 over the first and last 8 MiB: enough to notice a re-export, a re-trim
+ or a swapped file, cheap enough for a multi-GB source (hashing a whole master would make
+ planning slower than the edit)."""
+ import hashlib
+ st = os.stat(path)
+ h = hashlib.sha256()
+ chunk = 8 * 1024 * 1024
+ with open(path, "rb") as f:
+ h.update(f.read(chunk))
+ if st.st_size > 2 * chunk:
+ f.seek(-chunk, os.SEEK_END)
+ h.update(f.read(chunk))
+ elif st.st_size > chunk:
+ h.update(f.read())
+ return {"path": os.path.abspath(path), "size": st.st_size, "sha256_head_tail": h.hexdigest()}
+
+
+def _plan_inputs(commands: Sequence[str]) -> List[str]:
+ """Every existing file named by `-i` in the planned commands (shell-quoted lines)."""
+ import shlex
+ seen: List[str] = []
+ for line in commands:
+ try:
+ toks = shlex.split(line.split("] ", 1)[1] if line.startswith("[dry-run] ") else line)
+ except ValueError:
+ continue
+ for i, tok in enumerate(toks[:-1]):
+ if tok == "-i" and os.path.isfile(toks[i + 1]) and toks[i + 1] not in seen:
+ seen.append(toks[i + 1])
+ return seen
+
+
+def write_plan(path: str, output: Optional[str], extra: Dict[str, Any]) -> str:
+ """The dry run as an artifact: what will run, on which exact inputs, producing what, checked
+ how. `render.py PLAN` executes it after re-fingerprinting the inputs (issue #189 C)."""
+ import datetime
+ argv = [a for a in sys.argv[1:]]
+ cleaned: List[str] = []
+ skip = False
+ for a in argv:
+ if skip:
+ skip = False
+ continue
+ if a in _PLAN_STRIP:
+ skip = a == "--plan"
+ continue
+ if a.startswith("--plan="):
+ continue
+ cleaned.append(a)
+ tool = os.path.splitext(os.path.basename(sys.argv[0]))[0]
+ verify: List[Dict[str, Any]] = [{"tool": "probe"}] if output else []
+ platform = None
+ if "--platform" in cleaned:
+ platform = cleaned[cleaned.index("--platform") + 1]
+ elif tool == "export" and "--preset" in cleaned:
+ platform = {"youtube": "youtube", "youtube4k": "youtube", "reels": "reels", "x": "x"}.get(cleaned[cleaned.index("--preset") + 1])
+ if platform and output and tool != "check":
+ verify.append({"tool": "check", "platform": platform})
+ doc = {
+ "plan_version": PLAN_VERSION,
+ "created": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "tool": tool,
+ "argv": cleaned,
+ "cwd": os.getcwd(),
+ "inputs": [fingerprint(p) for p in _plan_inputs(STATE.commands)],
+ "commands": list(STATE.commands),
+ "output": os.path.abspath(output) if output else None,
+ "verify": verify,
+ "notes": list(extra.get("notes") or []),
+ }
+ try:
+ tmp = f"{path}.tmp{os.getpid()}"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(doc, f, indent=2, ensure_ascii=False)
+ f.write("\n")
+ os.replace(tmp, path)
+ except OSError as exc:
+ die(f"cannot write plan {path}: {exc}", kind="output")
+ info(f"plan written: {path} ({len(doc['commands'])} command(s), {len(doc['inputs'])} input(s)); run it with render.py {path}")
+ return path
+
+
_V2_HANDLED = ("result", "measured", "notes", "dropped_non_av_streams")
diff --git a/scripts/_contract.py b/scripts/_contract.py
index ebaad60..3e1376c 100644
--- a/scripts/_contract.py
+++ b/scripts/_contract.py
@@ -333,7 +333,7 @@ def input_schema(parser: argparse.ArgumentParser) -> Dict[str, Any]:
props: Dict[str, Any] = {}
required: List[str] = []
positional: List[str] = []
- common = {"dry_run", "json", "progress", "fast", "timeout", "overwrite"}
+ common = {"dry_run", "json", "progress", "fast", "timeout", "overwrite", "plan"}
for action in parser._actions:
if isinstance(action, argparse._HelpAction):
continue
@@ -386,7 +386,10 @@ def output_schema(name: str, meta: Dict[str, Any]) -> Dict[str, Any]:
elif name == "look":
extra = {"outputs": {"type": "array", "items": {"type": "string"}}}
elif name == "render":
- extra = {"stages": {"type": "array", "items": {"type": "string"}}, "check": {"type": ["object", "null"]}}
+ extra = {"stages": {"type": "array", "items": {"type": "string"}}, "check": {"type": ["object", "null"]},
+ "plan": {"type": "string", "description": "when the argument was a plan.json (written by <tool> --plan): its path"},
+ "tool": {"type": "string", "description": "plan execution: the tool the plan ran"},
+ "tool_result": {"type": "object", "description": "plan execution: the tool's own --json document"}}
elif name == "verify":
extra = {"report": {"type": ["string", "null"]}, "files": {"type": "array"}, "failed": {"type": "integer"}, "total": {"type": "integer"}}
elif name == "batch":
diff --git a/scripts/render.py b/scripts/render.py
index 5b9114a..51c3d1f 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -49,13 +49,14 @@ Examples:
python3 render.py project.json --fast # preview quality
"""
import argparse
+import re
import json
import os
import sys
from pathlib import Path
from typing import Any, Dict, List
-from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output, refuse_output_is_input
+from _common import STATE, add_common, apply_common, child_args, die, emit, info, probe, run_tool, place_output, refuse_output_is_input, fingerprint, PLAN_VERSION
HERE = Path(__file__).resolve().parent
@@ -101,9 +102,75 @@ def sh(script: str, *argv: Any, extra: List[str] = None) -> str:
return str(doc.get("output") or "")
+def execute_plan(plan: Dict[str, Any], path: str) -> int:
+ """Run a plan written by `<tool> --plan FILE`: refuse if any fingerprinted input changed since
+ the plan was made (the plan's commands would then describe a different edit), run the tool
+ with the planned argv, then the plan's verify steps. --dry-run prints the planned commands."""
+ if plan.get("plan_version") != PLAN_VERSION:
+ die(f"{path}: plan_version {plan.get('plan_version')!r} is not {PLAN_VERSION}")
+ tool = str(plan.get("tool") or "")
+ script = HERE / f"{tool}.py"
+ if not re.fullmatch(r"[a-z][a-z0-9_]*", tool) or not script.exists() or tool == "render":
+ die(f"{path}: unknown tool {tool!r}")
+ changed = []
+ for inp in plan.get("inputs") or []:
+ p = inp.get("path")
+ if not p or not os.path.isfile(p):
+ changed.append(f"{p}: missing")
+ continue
+ now = fingerprint(p)
+ if now["size"] != inp.get("size") or now["sha256_head_tail"] != inp.get("sha256_head_tail"):
+ changed.append(f"{p}: content changed since the plan was made")
+ if changed:
+ die("plan inputs differ from what was planned; re-run the tool with --plan to make a new plan:\n " + "\n ".join(changed),
+ hint="plans are bound to the exact input files they were made from")
+ if plan.get("cwd") and os.path.isdir(plan["cwd"]):
+ os.chdir(plan["cwd"])
+ argv = [str(a) for a in plan.get("argv") or []]
+ if STATE.dry_run:
+ for c in plan.get("commands") or []:
+ STATE.commands.append(c)
+ info("[dry-run] " + c)
+ emit(plan.get("output"), plan=path, tool=tool, stages=[tool], check=None)
+ return 0
+ info(f"executing plan {path}: {tool} " + " ".join(argv))
+ proc = run_tool([str(script)] + argv + child_args() + ["--json"])
+ for line in proc.stderr.splitlines():
+ if line.startswith("$ "):
+ STATE.commands.append(line[2:])
+ elif line.strip():
+ info(" " + line)
+ try:
+ doc = json.loads(proc.stdout.strip() or "{}")
+ except ValueError:
+ doc = {}
+ if proc.returncode != 0 or doc.get("status") != "completed":
+ err = doc.get("error") or {}
+ die(f"{tool} failed while executing the plan: {err.get('message') or proc.stderr.strip()[-300:]}",
+ kind=err.get("kind", "ffmpeg"), plan=path, tool=tool)
+ output = doc.get("output") or plan.get("output")
+ check_result = None
+ exit_code = 0
+ for step in plan.get("verify") or []:
+ if step.get("tool") == "check" and step.get("platform") and output:
+ cp = run_tool([str(HERE / "check.py"), output, "--platform", step["platform"], "--json"] + child_args())
+ try:
+ check_result = json.loads(cp.stdout)
+ except ValueError:
+ check_result = {"error": cp.stderr.strip()[-300:]}
+ if check_result.get("failed") or check_result.get("status") == "failed" or check_result.get("error"):
+ exit_code = 1
+ if exit_code:
+ die(f"plan executed but {output} does not meet the {[s.get('platform') for s in plan.get('verify') or [] if s.get('tool') == 'check'][0]} spec",
+ kind="verification", output=output, plan=path, tool=tool, stages=[tool, "check"], check=check_result)
+ info(f"plan done: {output}")
+ emit(output, plan=path, tool=tool, stages=[tool] + (["check"] if check_result else []), check=check_result, tool_result=doc)
+ return 0
+
+
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- ap.add_argument("project", nargs="?", help="project.json")
+ ap.add_argument("project", nargs="?", help="project.json, or a plan.json written by <tool> --plan")
ap.add_argument("--init", metavar="FILE", help="write a starter project file and exit")
ap.add_argument("--work", help="work directory for intermediates (default: <output>_work)")
ap.add_argument("--keep", action="store_true", help="keep intermediates (default: kept only when --work is given)")
@@ -123,6 +190,8 @@ def main() -> int:
proj: Dict[str, Any] = json.loads(Path(args.project).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
die(f"cannot read project: {exc}")
+ if isinstance(proj, dict) and "plan_version" in proj:
+ return execute_plan(proj, args.project)
base = Path(args.project).resolve().parent
def rel(p: Any) -> str:
diff --git a/tests/fixtures/mcp_tools.json b/tests/fixtures/mcp_tools.json
index 51b88db..758510e 100644
--- a/tests/fixtures/mcp_tools.json
+++ b/tests/fixtures/mcp_tools.json
@@ -42,6 +42,7 @@
"music_volume",
"output",
"overwrite",
+ "plan",
"progress",
"replace",
"stereo",
@@ -66,6 +67,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout",
@@ -83,6 +85,7 @@
"force",
"json",
"overwrite",
+ "plan",
"progress",
"recipe",
"timeout",
@@ -109,6 +112,7 @@
"output",
"overwrite",
"pad_color",
+ "plan",
"preset",
"progress",
"timeout"
@@ -147,6 +151,7 @@
"outline_color",
"output",
"overwrite",
+ "plan",
"position",
"preset",
"progress",
@@ -175,6 +180,7 @@
"max_mb",
"no_loudness",
"overwrite",
+ "plan",
"platform",
"progress",
"timeout",
@@ -210,6 +216,7 @@
"output",
"overwrite",
"peak",
+ "plan",
"preset",
"progress",
"retag",
@@ -236,6 +243,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout",
@@ -255,6 +263,7 @@
"json",
"limit",
"overwrite",
+ "plan",
"progress",
"round_to",
"samples",
@@ -277,6 +286,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"segments",
@@ -301,6 +311,7 @@
"output",
"overwrite",
"parity",
+ "plan",
"preset",
"progress",
"timeout"
@@ -324,6 +335,7 @@
"luma_temporal",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"strength",
@@ -349,6 +361,7 @@
"pad_blur",
"pad_color",
"pad_fill",
+ "plan",
"preset",
"progress",
"timeout"
@@ -381,6 +394,7 @@
"pad_blur",
"pad_color",
"pad_fill",
+ "plan",
"preset",
"progress",
"rotate",
@@ -404,6 +418,7 @@
"mode",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout"
@@ -428,6 +443,7 @@
"name",
"output",
"overwrite",
+ "plan",
"position",
"preset",
"primary",
@@ -465,6 +481,7 @@
"output",
"overwrite",
"pad",
+ "plan",
"preset",
"progress",
"rows",
@@ -487,6 +504,7 @@
"output",
"overwrite",
"pan",
+ "plan",
"preset",
"progress",
"timeout",
@@ -513,6 +531,7 @@
"output",
"overwrite",
"pad_color",
+ "plan",
"preset",
"progress",
"sample_rate",
@@ -535,6 +554,7 @@
"no_timecode",
"output",
"overwrite",
+ "plan",
"progress",
"tiles",
"timeout",
@@ -554,6 +574,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout",
@@ -575,6 +596,7 @@
"measure_only",
"output",
"overwrite",
+ "plan",
"progress",
"sample_rate",
"timeout",
@@ -599,6 +621,7 @@
"json",
"output",
"overwrite",
+ "plan",
"progress",
"timeout",
"title"
@@ -624,6 +647,7 @@
"offsets_only",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"switch",
@@ -662,6 +686,7 @@
"opacity",
"output",
"overwrite",
+ "plan",
"position",
"preset",
"progress",
@@ -687,6 +712,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"start",
@@ -706,6 +732,7 @@
"inputs",
"json",
"overwrite",
+ "plan",
"progress",
"timeout"
],
@@ -724,6 +751,7 @@
"no_audio",
"output",
"overwrite",
+ "plan",
"progress",
"scale",
"timeout",
@@ -748,6 +776,7 @@
"mode",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout",
@@ -767,6 +796,7 @@
"json",
"keep",
"overwrite",
+ "plan",
"progress",
"project",
"stop_after",
@@ -789,6 +819,7 @@
"notes",
"output",
"overwrite",
+ "plan",
"platform",
"progress",
"timeout",
@@ -808,6 +839,7 @@
"no_audio",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout"
@@ -828,6 +860,7 @@
"min_scene",
"no_timecode",
"overwrite",
+ "plan",
"progress",
"rank_by",
"ratio",
@@ -852,6 +885,7 @@
"output",
"overwrite",
"pattern",
+ "plan",
"preset",
"progress",
"start_number",
@@ -876,6 +910,7 @@
"min_silence",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"threshold",
@@ -894,6 +929,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"segments",
@@ -919,6 +955,7 @@
"output",
"overwrite",
"pitch",
+ "plan",
"preset",
"progress",
"roll",
@@ -942,6 +979,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"shakiness",
@@ -968,6 +1006,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"timeout"
@@ -989,6 +1028,7 @@
"max_offset",
"output",
"overwrite",
+ "plan",
"progress",
"reference",
"replace_audio",
@@ -1010,6 +1050,7 @@
"out",
"overwrite",
"paths",
+ "plan",
"progress",
"quick",
"report",
@@ -1034,6 +1075,7 @@
"json",
"output",
"overwrite",
+ "plan",
"preset",
"progress",
"split_channels",
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 83c8b43..ee00089 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -1743,6 +1743,39 @@ class ContractTests(unittest.TestCase):
doc = json.loads(tool("cut", self.src, "--start", "0", "--end", "2", "--json", "-o", self.out("e6_cut0.mp4")).stdout)
self.assertIsNone(doc["lossless_alternative"])
+ def test_plan_roundtrip(self):
+ """--plan writes a plan and runs nothing; render.py executes it, verifies, and refuses when
+ an input changed since the plan (issue #189 C)."""
+ import shutil
+ src = self.out("plan_src.mp4"); shutil.copy(self.src, src)
+ plan = self.out("plan_cut.json"); out = self.out("plan_cut.mp4")
+ doc = json.loads(tool("cut", src, "--start", "0", "--end", "1", "-o", out, "--plan", plan, "--json").stdout)
+ self.assertTrue(doc["dry_run"]); self.assertEqual(doc["plan"], str(plan)); self.assertFalse(out.exists())
+ p = json.loads(plan.read_text())
+ self.assertEqual((p["plan_version"], p["tool"], p["output"]), (1, "cut", str(out)))
+ self.assertEqual([i["path"] for i in p["inputs"]], [str(src)])
+ self.assertNotIn("--plan", p["argv"]); self.assertNotIn("--json", p["argv"]); self.assertNotIn("--dry-run", p["argv"])
+ self.assertEqual(p["verify"], [{"tool": "probe"}])
+ doc = json.loads(tool("render", plan, "--dry-run", "--json").stdout)
+ self.assertTrue(doc["dry_run"]); self.assertFalse(out.exists())
+ doc = json.loads(tool("render", plan, "--json").stdout)
+ self.assertEqual((doc["status"], doc["tool"], doc["output"]), ("completed", "cut", str(out)))
+ # a lossless cut lands on packet boundaries: FFmpeg 5.1.1 writes 1.23 s for this 1 s request
+ self.assertTrue(0.9 <= doc["probe"]["duration"] <= 1.6, doc["probe"]["duration"])
+ self.assertEqual(doc["tool_result"]["status"], "completed")
+ # an export plan carries the platform check and runs it
+ xplan = self.out("plan_x.json"); xout = self.out("plan_x.mp4")
+ tool("export", src, "--preset", "x", "--fast", "-o", xout, "--plan", xplan)
+ self.assertEqual(json.loads(xplan.read_text())["verify"], [{"tool": "probe"}, {"tool": "check", "platform": "x"}])
+ doc = json.loads(tool("render", xplan, "--json", check=False).stdout)
+ self.assertIn(doc["status"], ("completed", "failed"))
+ self.assertEqual(doc["check"]["platform"], "x")
+ # a changed input is refused
+ ffmpeg("-i", self.src, "-t", "0.5", "-c", "copy", "-y", src)
+ proc = tool("render", plan, "--json", "--overwrite", check=False)
+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")
+ self.assertIn("changed", json.loads(proc.stdout)["error"]["message"])
+
def test_fifth_review_regressions(self):
"""Review 5 (2026-09-12): render refuses an output that is one of its clip sources (it
overwrote the source and said completed); fit --method trim drops a subtitle track whose