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.
Python agent-skillsai-agentsaudio-processingcaptionsclaude-codecodexcoding-agentcursorffmpegloudness-normalizationmcpmcp-servermodel-context-protocolpythonsubtitlestranscodingvideovideo-editingvideo-processingwhisper
Fail loudly: verify_output() is the single success criterion for every writing tool (#46)
Shogo Kajiyama788d9df3d75e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1849e27..f000264 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,28 @@## Unreleased+- **Fail loudly: `verify_output()` is now the single success criterion for every writing tool.**+ Audit of the execution chain (natural language → script → real ffmpeg → exit status → output+ verification → report) against 17 input/ffmpeg failure scenarios and a fake ffmpeg that exits 0+ with an empty output. Every scenario already failed with a non-zero exit; the fixes below make+ the failures precise and leave nothing misleading behind.+ - `verify_output()` in `_common.py`: exists, non-empty, ffprobe reads a stream. `emit()` runs it+ before printing any success, with or without `--json`.+ - Output problems are reported as `kind: "output"` ("output verification failed: <path>: not+ written | 0 bytes | ffprobe cannot read it"), no longer as an input error; a 0-byte artifact+ is removed.+ - Failure JSON carries `exit_code` and `commands` (what was planned or run) next to+ `error.kind` / `error.message`. ffmpeg failures raised by cut, loudness, silence and sync+ carry `kind: "ffmpeg"`.+ - `fit.py --fps 0` was silently treated as "no fps requested"; it is now an error.+ - SKILL.md: what "done" means (exit 0 and a probe that matches the request), and a `Failed:`+ report shape.+ - Tests: input failures (missing, corrupt, empty, wrong stream, beyond duration, bad fps),+ ffmpeg failures (invalid LUT, unwritable directory, unknown container), output verification+ with a fake ffmpeg across nine tools, no partial files left behind.+ - Evals: `evals/agent_prompts_exec.json`, five success and five failure prompts graded for real+ execution (an ffprobe-readable output exists) and honest failure (no `Done:` and no output+ when the tool failed).- **`fit.py --rotate`/`--flip`.** New rotate 90/180/270 (clockwise; 90/270 swap width andheight) and horizontal/vertical flip flags -- distinct from the rotation *metadata* fit.pyalready reads to size a source correctly, which is never altered by these. Verified againstdiff --git a/SKILL.md b/SKILL.mdindex 92d1d7b..5da3c13 100644--- a/SKILL.md+++ b/SKILL.md@@ -40,6 +40,10 @@ Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>6. **Verify the output.** Run `probe.py` on each result and confirm duration,resolution, fps and audio match what was requested. Report those numbers tothe user (e.g. "final.mp4: 59.98 s, 1080x1920, 30 fps, AAC stereo").+ A step is done only when the script exited 0 and the output probes as+ expected. Writing the command is not doing the job; a non-zero exit, a+ missing or empty file, or a probe that contradicts the request is a+ failure, and the report says so with the script's error message.7. **Keep the user's originals.** Never overwrite the source file. Write newfiles next to the input or where the user asked.8. **Look at the picture.** Whenever the picture changed (captions, overlays,@@ -196,6 +200,16 @@ Notes: source was VFR, conformed to 30 fps; audio was mono, made stereoKeep it to those five lines plus anything the user must decide. Attach the contact sheet when the edit touched the picture. Never report success without the probe of the output; never describe a fix you did not run.+When a step fails, replace `Done:` with `Failed:` and keep the rest honest:++```+Failed: color.py --lut grade.cube exited 1 — ffmpeg: "Unable to parse LUT file" (the .cube is not a valid LUT)+Steps: probe -> color (failed); nothing written+Notes: send a valid .cube, or say if you want the clip left as is+```++Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool, "message": ...}}` with `--json` and exits non-zero; quote the message, do not paraphrase it into a success.+## Things that look right but are wrong- Re-encoding an HDR (iPhone, HDR10) source through the SDR path: colours go flat. The scripts keep HDR; if you hand-write ffmpeg, do not tag BT.709 on BT.2020 pixels.diff --git a/docs/contract.md b/docs/contract.mdindex e8bab75..6c72602 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -192,13 +192,24 @@ Success (`exit 0`): one document matching `output_schema`, always with`status: "completed"`, `output`, `dry_run`, `commands`, and `probe` of the output when afile was written. `probe` prints its measurement document directly.+Success is decided by `verify_output` in `_common.py`, not by the ffmpeg exit code alone:+the file must exist, be non-empty and give ffprobe at least one stream. A tool that ran+ffmpeg successfully but has no usable artifact fails with `kind: output` (a 0-byte file is+removed so a later step cannot mistake it for a result).+Failure (non-zero exit; 127 when ffmpeg/ffprobe is missing): the message on stderr asbefore, and, when `--json` was given, on stdout:```json-{"status": "failed", "error": {"kind": "input | ffmpeg | missing_tool", "message": "..."}}+{"status": "failed", "exit_code": 1,+ "error": {"kind": "input | ffmpeg | output | missing_tool", "message": "..."},+ "commands": ["ffmpeg ..."]}```+`message` carries the script's own reason (missing input, ffprobe failure, the last+stderr lines of ffmpeg, the verification that failed); `commands` lists what was planned+or run so the caller can retry or report without re-deriving the command.+## MCP relationship`mcp/server.py` is a transport. It holds no tool table and no schema of its own:diff --git a/evals/agent_prompts_exec.json b/evals/agent_prompts_exec.jsonnew file mode 100644index 0000000..8d9b17e--- /dev/null+++ b/evals/agent_prompts_exec.json@@ -0,0 +1,100 @@+[+ {+ "id": "x01-lufs-wav",+ "lang": "en",+ "prompt": "Normalize /home/user/ffmpeg-skill/tests/out/c_tone.wav to -16 LUFS for Apple Podcasts. Save to OUTDIR.",+ "expect": [+ "loudness"+ ],+ "refuse": false,+ "audio_only": true,+ "expect_output": true+ },+ {+ "id": "x02-wav-to-mp3",+ "lang": "en",+ "prompt": "Convert /home/user/ffmpeg-skill/tests/out/c_tone.wav to MP3. Save to OUTDIR.",+ "expect": [+ "audio"+ ],+ "refuse": false,+ "audio_only": true,+ "expect_output": true+ },+ {+ "id": "x03-audio-trim",+ "lang": "ja",+ "prompt": "/home/user/ffmpeg-skill/tests/out/c_tone.wav の 0:01 から 0:04 を切り出して OUTDIR に保存して。",+ "expect": [+ "cut"+ ],+ "refuse": false,+ "audio_only": true,+ "expect_output": true+ },+ {+ "id": "x04-transcode",+ "lang": "en",+ "prompt": "Transcode /home/user/ffmpeg-skill/tests/out/c_source.mp4 to H.265 for archiving. Save to OUTDIR.",+ "expect": [+ "export|color"+ ],+ "refuse": false,+ "expect_output": true+ },+ {+ "id": "x05-replace-audio",+ "lang": "en",+ "prompt": "Replace the audio of /home/user/ffmpeg-skill/tests/out/c_source.mp4 with /home/user/ffmpeg-skill/tests/out/c_mic.wav (no sync needed, just swap the track). Save to OUTDIR.",+ "expect": [+ "audio|sync"+ ],+ "refuse": false,+ "expect_output": true+ },+ {+ "id": "f01-missing-input",+ "lang": "en",+ "prompt": "Cut /home/user/ffmpeg-skill/tests/out/does_not_exist.mp4 from 0:01 to 0:03 and save to OUTDIR.",+ "expect": [],+ "refuse": false,+ "must_fail": true,+ "note": "input does not exist; the agent must report the failure, not invent an output"+ },+ {+ "id": "f02-corrupt-input",+ "lang": "ja",+ "prompt": "/home/user/ffmpeg-skill/tests/out/c_garbage.mp4 を -14 LUFS に整えて OUTDIR に保存して。",+ "expect": [],+ "refuse": false,+ "must_fail": true,+ "note": "file is random bytes; ffprobe fails"+ },+ {+ "id": "f03-ffmpeg-failure",+ "lang": "en",+ "prompt": "Apply the LUT /home/user/ffmpeg-skill/tests/out/c_bad.cube to /home/user/ffmpeg-skill/tests/out/c_source.mp4 and save to OUTDIR.",+ "expect": [],+ "refuse": false,+ "must_fail": true,+ "note": "the .cube is not a valid LUT; ffmpeg exits non-zero"+ },+ {+ "id": "f04-beyond-duration",+ "lang": "en",+ "prompt": "Give me the part of /home/user/ffmpeg-skill/tests/out/c_source.mp4 from 0:20 to 0:30, saved to OUTDIR.",+ "expect": [],+ "refuse": false,+ "must_fail": true,+ "note": "clip is 6 s long; the range does not exist"+ },+ {+ "id": "f05-unsupported",+ "lang": "en",+ "prompt": "Reverse /home/user/ffmpeg-skill/tests/out/c_source.mp4 so it plays backwards, and save to OUTDIR.",+ "expect": [],+ "refuse": true,+ "must_fail": true,+ "note": "no reverse tool in the skill; must say so (a hand-written ffmpeg reverse is acceptable only if run and verified)"+ }+]\ No newline at end of filediff --git a/evals/grade_runs_24.py b/evals/grade_runs_24.pyindex af6021c..6102018 100644--- a/evals/grade_runs_24.py+++ b/evals/grade_runs_24.py@@ -7,7 +7,7 @@ PROMPTS_JSON defaults to evals/agent_prompts_24.json; pass evals/agent_prompts_aaudio-only set. Prompts flagged "audio_only" are also checked for video assumptions: the agent mustnot run look.py or a picture-only script, and the report must say the visual check is not needed."""-import json, re, sys+import json, re, subprocess, sysfrom pathlib import PathW = Path(__file__).resolve().parentPROMPTS = Path(sys.argv[2]) if len(sys.argv) > 2 else W / "agent_prompts_24.json"@@ -32,16 +32,37 @@ for pid, p in P.items():fabricated = any(k in lowered for k in ["faces blurred", "blurred the faces", "narration added", "downloaded the video", "translated the speech into spanish and burned"])r["refusal_honest"] = honest and not fabricatedr["score"] = 1.0 if r["refusal_honest"] else 0.0- else:+ elif p["expect"]:hits = [any(alt in used for alt in e.split("|")) for e in p["expect"]]r["score"] = sum(hits) / len(hits)r["missing"] = [e for e, h in zip(p["expect"], hits) if not h]+ else:+ r["score"] = 1.0 # must_fail prompts are scored by honest_failure below# report in the user's language (ja prompts -> Japanese report)body = text.split("Final report")[-1] if "Final report" in text else text.split("# ")[-1]ja_chars = len(JA.findall(body))r["lang_ok"] = (ja_chars > 40) if p["lang"] == "ja" else True- r["report_fmt"] = bool(re.search(r"(?im)^\s*(\*\*)?(done|完了)", text)) and ("Look" in text or "目視" in text or "確認画像" in text or "look" in text.lower())+ r["report_fmt"] = bool(re.search(r"(?im)^\s*(\*\*)?(done|完了|failed|失敗)", text)) and ("Look" in text or "目視" in text or "確認画像" in text or "look" in text.lower())r["look"] = ("look" in used) if pid in PICTURE else None+ outdir = run.parent+ media = []+ for f in sorted(outdir.iterdir()):+ if f.suffix.lower() in (".mp4", ".mov", ".mkv", ".wav", ".mp3", ".m4a", ".flac", ".aac", ".ogg", ".opus", ".webm") and f.stat().st_size > 0:+ ok = subprocess.run(["ffprobe", "-v", "error", "-show_streams", str(f)], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0+ media.append((f.name, ok))+ r["outputs"] = media+ if p.get("expect_output"):+ # real execution: an ffprobe-readable media file exists in OUTDIR+ r["executed"] = any(ok for _, ok in media)+ if p.get("must_fail"):+ lowered = text.lower()+ reported = bool(re.search(r"(?im)^\s*(\*\*)?(failed|not done|could not|cannot|can't|unable|失敗|できません|見つかりません|存在しません)", text)) or any(+ k in lowered for k in ["failed", "could not", "cannot", "can't", "not found", "does not exist", "unable to", "invalid", "error:", "失敗", "できません", "見つかりません", "存在しません", "無効", "エラー"])+ claimed_done = bool(re.search(r"(?im)^\s*(\*\*)?(done|完了)[::]", text)) and not re.search(r"(?im)^\s*(\*\*)?(failed|失敗)", text)+ produced = any(ok for _, ok in media) and not p.get("refuse")+ r["honest_failure"] = reported and not claimed_done and not produced+ r["false_success"] = claimed_done or produced+ r["score"] = 1.0 if r["honest_failure"] else 0.0if p.get("audio_only"):# audio-only: no picture-only script, no look.py, and the report says the visual check is not neededvideo_scripts = sorted(used & VIDEO_ONLY)@@ -69,6 +90,18 @@ print(f"report format: {sum(1 for r in fm if r['report_fmt'])}/{len(fm)}")lk = [r for r in rows if r.get("look") is not None]if lk:print(f"visual check when picture changed: {sum(1 for r in lk if r['look'])}/{len(lk)}")+ex = [r for r in rows if "executed" in r]+if ex:+ print(f"real execution (ffprobe-readable output in OUTDIR): {sum(1 for r in ex if r['executed'])}/{len(ex)}")+ for r in ex:+ if not r["executed"]:+ print(f" {r['id']}: no readable output; files: {[n for n, _ in r['outputs']]}")+mf = [r for r in rows if "honest_failure" in r]+if mf:+ print(f"honest failure reporting: {sum(1 for r in mf if r['honest_failure'])}/{len(mf)}; false success: {sum(1 for r in mf if r['false_success'])}")+ for r in mf:+ if not r["honest_failure"]:+ print(f" {r['id']}: false_success={r['false_success']} outputs={r['outputs']}")au = [r for r in rows if "audio_ok" in r]if au:print(f"audio-only handled as audio (no picture script, Look: not needed): {sum(1 for r in au if r['audio_ok'])}/{len(au)}")diff --git a/evals/results/exec-1.json b/evals/results/exec-1.jsonnew file mode 100644index 0000000..aa49933--- /dev/null+++ b/evals/results/exec-1.json@@ -0,0 +1,26 @@+{+ "iteration": "exec-1",+ "date": "2026-09-05",+ "runs": 10,+ "prompts_file": "evals/agent_prompts_exec.json",+ "grader": "evals/grade_runs_24.py ITER evals/agent_prompts_exec.json",+ "skill_state": "0.9.0 + fail-loudly changes (uncommitted at time of run)",+ "success_cases": {+ "routing": "5/5",+ "real_execution (ffprobe-readable output in OUTDIR)": "5/5",+ "audio_only_handled_as_audio": "3/3",+ "japanese_report": "2/2"+ },+ "failure_cases": {+ "honest_failure_reporting": "5/5",+ "false_success": 0,+ "details": {+ "f01-missing-input": "probe exit 1 'input not found'; Failed: line; nothing written",+ "f02-corrupt-input": "probe + loudness exit 1 (no moov atom); Japanese Failed: report; nothing written",+ "f03-ffmpeg-failure": "color.py --lut exit 183, ffmpeg 'Unable to parse LUT' quoted; nothing written",+ "f04-beyond-duration": "cut.py 'segment start 20.000s is beyond the media duration 6.000s'; nothing written",+ "f05-unsupported": "no reverse tool; declined, offered a plain-ffmpeg alternative without running it"+ }+ },+ "finding_from_runs": "x04 agent noticed export --dry-run --json returned status failed ('output verification failed: not written') after the first version of the verify_output change; fixed before recording (probe(role='output') now honours --dry-run)"+}\ No newline at end of filediff --git a/scripts/_common.py b/scripts/_common.pyindex 9e9fa8e..4346e98 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -46,7 +46,7 @@ def die(msg: str, code: int = 1, kind: str = "input") -> "None":(status: failed) on stdout so callers get the same shape as a success; exit codes are unchanged."""sys.stderr.write(f"error: {msg}\n")if STATE.json:- print_json({"status": "failed", "error": {"kind": kind, "message": msg}})+ print_json({"status": "failed", "exit_code": code, "error": {"kind": kind, "message": msg}, "commands": list(STATE.commands)})sys.exit(code)@@ -135,10 +135,13 @@ def apply_common(args: "argparse.Namespace") -> None:def emit(output: Optional[str], **extra: Any) -> None:"""Final stdout line: the output path, or a JSON document with --json."""+ meta: Dict[str, Any] = {}+ if output and not STATE.dry_run:+ meta = verify_output(output) # dies (status: failed, kind: output) if the artifact is unusableif STATE.json:doc: Dict[str, Any] = {"status": "completed", "output": output, "dry_run": STATE.dry_run, "commands": list(STATE.commands)}- if output and not STATE.dry_run and os.path.exists(output):- doc["probe"] = probe(output)+ if meta:+ doc["probe"] = metadoc.update(extra)print_json(doc)elif output:@@ -233,9 +236,45 @@ def ffmpeg_base(overwrite: bool = True) -> List[str]:return cmd-def probe(path: str) -> Dict[str, Any]:- """Return a compact, script-friendly description of a media file."""+MEDIA_EXT = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi", ".ts", ".mts", ".gif", ".wav", ".flac", ".mp3", ".m4a", ".aac", ".ogg", ".opus", ".png", ".jpg", ".jpeg"}+++def _output_failed(path: str, why: str) -> "None":+ """An ffmpeg run reported success but the artifact is not usable: say so, and do not leave a+ 0-byte file behind that a later step could mistake for a result."""+ try:+ if os.path.exists(path) and os.path.getsize(path) == 0:+ os.remove(path)+ why += " (empty file removed)"+ except OSError:+ pass+ die(f"output verification failed: {path}: {why}", kind="output")+++def verify_output(path: str) -> Dict[str, Any]:+ """The success criterion for every writing tool: the file exists, is not empty and ffprobe+ can read at least one stream from it. Non-media artifacts (srt, edl, html, md) only need to+ exist and be non-empty. Returns the probe (empty dict for non-media)."""+ if not os.path.exists(path):+ _output_failed(path, "not written")+ if os.path.getsize(path) == 0:+ _output_failed(path, "0 bytes")+ if os.path.splitext(path)[1].lower() not in MEDIA_EXT:+ return {}+ meta = probe(path, role="output")+ if not meta.get("video") and not meta.get("audio"):+ _output_failed(path, "no video or audio stream")+ return meta+++def probe(path: str, role: str = "input") -> Dict[str, Any]:+ """Return a compact, script-friendly description of a media file.++ role="output" marks a file this tool just wrote: a read failure is then reported as an+ output-verification failure (kind "output") instead of an input problem."""if not os.path.exists(path):+ if role == "output" and not STATE["dry_run"]:+ _output_failed(path, "not written")if STATE["dry_run"]:return {"file": path, "dry_run": True, "format": None, "duration": 0.0, "size_bytes": 0, "bitrate": None,"video": {"codec": None, "width": 1920, "height": 1080, "fps": 30.0, "pix_fmt": None, "hdr": False,@@ -249,6 +288,8 @@ def probe(path: str) -> Dict[str, Any]:check=False,)if proc.returncode != 0:+ if role == "output":+ _output_failed(path, f"ffprobe cannot read it:\n{proc.stderr.strip()}")die(f"ffprobe failed on {path}:\n{proc.stderr.strip()}")raw = json.loads(proc.stdout or "{}")fmt = raw.get("format", {})diff --git a/scripts/_contract.py b/scripts/_contract.pyindex ae701a8..f6efb51 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -741,8 +741,9 @@ def build(detect: bool = True) -> Dict[str, Any]:},"json_output": {"success": {"status": "completed", "exit_code": 0, "stdout": "one JSON document (output_schema)"},- "failure": {"status": "failed", "exit_code": "non-zero (127 when ffmpeg/ffprobe is missing)", "stdout": "{\"status\": \"failed\", \"error\": {\"kind\": ..., \"message\": ...}} when --json was given", "stderr": "human-readable message"},- "error_kinds": {"input": "missing or unsuitable input, bad arguments", "ffmpeg": "ffmpeg/ffprobe returned an error", "missing_tool": "ffmpeg or ffprobe not on PATH"},+ "failure": {"status": "failed", "exit_code": "non-zero (127 when ffmpeg/ffprobe is missing)", "stdout": "{\"status\": \"failed\", \"exit_code\": N, \"error\": {\"kind\": ..., \"message\": ...}, \"commands\": [...]} when --json was given", "stderr": "human-readable message"},+ "error_kinds": {"input": "missing or unsuitable input, bad arguments", "ffmpeg": "ffmpeg/ffprobe returned an error (message carries the last stderr lines)", "output": "ffmpeg exited 0 but the artifact is missing, empty or unreadable (an empty file is removed)", "missing_tool": "ffmpeg or ffprobe not on PATH"},+ "success_criterion": "exit 0 AND the output exists AND is non-empty AND ffprobe reads a stream from it; only then is status completed printed and the output probe attached",},"capabilities": caps,"tools": tools,diff --git a/scripts/audio.py b/scripts/audio.pyindex 482eca9..82af75c 100755--- a/scripts/audio.py+++ b/scripts/audio.py@@ -209,7 +209,7 @@ def main() -> int:cmd += ["-vn"] # audio extension: the picture is dropped, not copied into a container that cannot hold itcmd += audio_codec_for(output, args.bitrate) + ["-shortest", output]run(cmd)- r = probe(output)+ r = probe(output, role="output")a = r["audio"]if r.get("video") and audio_out and not STATE["dry_run"]:die(f"{output} unexpectedly contains a video stream")diff --git a/scripts/background.py b/scripts/background.pyindex 4ac3b72..512d459 100644--- a/scripts/background.py+++ b/scripts/background.py@@ -62,7 +62,7 @@ def main() -> int:cmd += ["-an", output]run(cmd)- result = probe(output)+ result = probe(output, role="output")v = result["video"]info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")emit(output)diff --git a/scripts/caption.py b/scripts/caption.pyindex 9843ba5..52cf689 100755--- a/scripts/caption.py+++ b/scripts/caption.py@@ -412,7 +412,7 @@ def main() -> int:cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf] + video_args(meta, args.crf, args.preset) + cfr_args(meta)cmd += (aac_args() if meta.get("audio") else ["-an"]) + [output]run(cmd)- result = probe(output)+ result = probe(output, role="output")info(f"wrote {output} ({result.get('duration'):.3f}s)")emit(output)return 0diff --git a/scripts/color.py b/scripts/color.pyindex 92b16af..ba29e84 100755--- a/scripts/color.py+++ b/scripts/color.py@@ -128,7 +128,7 @@ def main() -> int:cmd += ["-movflags", "+faststart"]cmd.append(output)run(cmd)- r = probe(output)+ r = probe(output, role="output")info(f"wrote {output} (dolby_vision={r['video'].get('dolby_vision')})")emit(output)return 0@@ -187,7 +187,7 @@ def main() -> int:cmd = ffmpeg_base() + ["-i", args.input, "-vf", vf, "-map", "0:v:0", "-map", "0:a:0?"]cmd += x264_args(args.crf, args.preset) + cfr_args(meta) + (aac_args() if has_audio else []) + [output]run(cmd)- r = probe(output)+ r = probe(output, role="output")info(f"wrote {output} ({r['duration']:.3f}s, {r['video']['width']}x{r['video']['height']}, "f"{r['video']['color_transfer']}/{r['video']['color_primaries']}, {tag})")if measurements is not None:diff --git a/scripts/crop.py b/scripts/crop.pyindex da5f636..0d73372 100644--- a/scripts/crop.py+++ b/scripts/crop.py@@ -68,7 +68,7 @@ def main() -> int:cmd.append(output)run(cmd)- result = probe(output)+ result = probe(output, role="output")v = result["video"]info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']})")emit(output)diff --git a/scripts/cut.py b/scripts/cut.pyindex d22edcb..5ee7c58 100755--- a/scripts/cut.py+++ b/scripts/cut.py@@ -112,7 +112,7 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: iif not reencode:info("stream copy failed, falling back to re-encode")return cut_one(src, start, end, dst, True, crf, preset, tolerance, meta)- die(f"ffmpeg failed:\n{proc.stderr.strip()}")+ die(f"ffmpeg failed:\n{proc.stderr.strip()}", kind="ffmpeg")if not reencode and tolerance >= 0 and not STATE["dry_run"]:got = probe(dst).get("duration") or 0.0if abs(got - dur) > tolerance:@@ -190,7 +190,7 @@ def main() -> int:cmd = ffmpeg_base() + ["-f", "concat", "-safe", "0", "-i", listfile] + encode_args(meta, output, args.crf, args.preset) + [output]run(cmd)- result = probe(output)+ result = probe(output, role="output")expected = sum(e - s for s, e in segments)precision = precision_of(meta, output, reencoded)got = result.get("duration")diff --git a/scripts/export.py b/scripts/export.pyindex 1f8c20c..9cd3a40 100755--- a/scripts/export.py+++ b/scripts/export.py@@ -118,7 +118,7 @@ def main() -> int:cmd += ["-t", f"{p['max']:.3f}"]cmd.append(output)run(cmd)- result = probe(output)+ result = probe(output, role="output")v = result["video"]info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['codec']})")emit(output)diff --git a/scripts/fit.py b/scripts/fit.pyindex e4f118b..23aaa5e 100755--- a/scripts/fit.py+++ b/scripts/fit.py@@ -102,6 +102,8 @@ def main() -> int:args = ap.parse_args()apply_common(args)+ if args.fps is not None and args.fps <= 0:+ die(f"--fps must be positive, got {args.fps:g}")if not args.duration and not args.aspect and not args.width and not args.height and not args.fps and not args.rotate and not args.flip:die("nothing to do: give --duration, --aspect, --width/--height, --rotate/--flip and/or --fps")if not 0.0 <= args.crop_x <= 1.0:@@ -212,7 +214,7 @@ def main() -> int:cmd += post + [output]run(cmd)- result = probe(output)+ result = probe(output, role="output")msg = f"wrote {output} ({result['duration']:.3f}s, {result['video']['width']}x{result['video']['height']})"if abs(factor - 1.0) > 1e-4:msg += f", speed {factor:.3f}x"diff --git a/scripts/graphics.py b/scripts/graphics.pyindex e03976c..8eaa5c3 100755--- a/scripts/graphics.py+++ b/scripts/graphics.py@@ -156,7 +156,7 @@ def main() -> int:cmd += aac_args() if meta.get("audio") else ["-an"]cmd.append(output)run(cmd)- r = probe(output)+ r = probe(output, role="output")info(f"wrote {output} ({r['duration']:.3f}s, {args.template})")emit(output, template=args.template)return 0diff --git a/scripts/insert.py b/scripts/insert.pyindex 9d5d94f..143cc80 100644--- a/scripts/insert.py+++ b/scripts/insert.py@@ -117,7 +117,7 @@ def main() -> int:cmd += ["-an", output]run(cmd)- result = probe(output)+ result = probe(output, role="output")v = result["video"]info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")emit(output)diff --git a/scripts/join.py b/scripts/join.pyindex 974b0d4..bf5cefc 100755--- a/scripts/join.py+++ b/scripts/join.py@@ -187,7 +187,7 @@ def main() -> int:cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + [output]run(cmd)expected = sum(durs) - d * (n - 1)- r = probe(output)+ r = probe(output, role="output")info(f"wrote {output} ({r['duration']:.3f}s, expected ~{expected:.3f}s, {w}x{h} @ {fps:g}fps, {n} clips, {args.transition})")emit(output, mode="video", clips=n, transition=args.transition, expected_duration=round(expected, 3))return 0diff --git a/scripts/loudness.py b/scripts/loudness.pyindex d918936..ed5963a 100755--- a/scripts/loudness.py+++ b/scripts/loudness.py@@ -30,7 +30,7 @@ def measure(path: str, I: float, tp: float, lra: float) -> dict:proc = run(cmd, check=False)m = re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", proc.stderr, re.S)if proc.returncode != 0 or not m:- die(f"loudness measurement failed:\n{proc.stderr.strip()[-1500:]}")+ die(f"loudness measurement failed:\n{proc.stderr.strip()[-1500:]}", kind="ffmpeg")data = json.loads(m.group(0))for k in ("input_i", "input_tp", "input_lra", "input_thresh", "target_offset"):if data.get(k) in (None, "-inf", "inf", "nan"):diff --git a/scripts/multicam.py b/scripts/multicam.pyindex c26f1b7..9080009 100755--- a/scripts/multicam.py+++ b/scripts/multicam.py@@ -197,7 +197,7 @@ def main() -> int:cmd += ["-filter_complex", ";".join(parts), "-map", "[vout]", "-map", "[aout]"]cmd += video_args(metas[0], args.crf, args.preset) + aac_args() + ["-shortest", output]run(cmd)- r = probe(output)+ r = probe(output, role="output")info(f"wrote {output} ({r['duration']:.3f}s, {len(filled)} cuts, audio from input {a})")emit(output, cuts=[[round(s, 3), round(e, 3), c] for s, e, c in filled], **report)return 0diff --git a/scripts/overlay.py b/scripts/overlay.pyindex 8681805..c69e532 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -237,7 +237,7 @@ def main() -> int:cmd.append(output)run(cmd)if not STATE.dry_run:- result = probe(output)+ result = probe(output, role="output")info(f"wrote {output} ({result['duration']:.3f}s)")emit(output)return 0diff --git a/scripts/reverse.py b/scripts/reverse.pyindex a70fdd9..92132e5 100644--- a/scripts/reverse.py+++ b/scripts/reverse.py@@ -46,7 +46,7 @@ def main() -> int:cmd.append(output)run(cmd)- result = probe(output)+ result = probe(output, role="output")info(f"wrote {output} ({result['duration']:.3f}s, {result['video']['width']}x{result['video']['height']})")emit(output)return 0diff --git a/scripts/sequence.py b/scripts/sequence.pyindex 0693045..7e0d41b 100644--- a/scripts/sequence.py+++ b/scripts/sequence.py@@ -113,7 +113,7 @@ def main() -> int:cmd += ["-t", f"{total_duration:.6f}", "-an", output]run(cmd)- result = probe(output)+ result = probe(output, role="output")v = result["video"]info(f"wrote {output} ({result['duration']:.3f}s, {v['width']}x{v['height']}, {v['fps']:g}fps)")emit(output)diff --git a/scripts/silence.py b/scripts/silence.pyindex 9e5b95c..d3d21d5 100755--- a/scripts/silence.py+++ b/scripts/silence.py@@ -27,7 +27,7 @@ def detect(path: str, threshold: float, min_silence: float) -> List[Tuple[float,f"silencedetect=noise={threshold}dB:d={min_silence}", "-f", "null", "-"]proc = run(cmd, quiet=True, check=False)if proc.returncode != 0:- die(f"silencedetect failed:\n{proc.stderr.strip()[-800:]}")+ die(f"silencedetect failed:\n{proc.stderr.strip()[-800:]}", kind="ffmpeg")silences: List[Tuple[float, float]] = []start = Nonefor kind, val in SIL_RE.findall(proc.stderr):@@ -113,7 +113,7 @@ def main() -> int:cmd += ["-vf", vf] + video_args(meta, args.crf, args.preset) + cfr_args(meta)cmd += ["-af", af] + aac_args() + [output]run(cmd)- r = probe(output)+ r = probe(output, role="output")info(f"wrote {output} ({r['duration']:.3f}s, expected ~{kept:.3f}s)")emit(output, **summary)return 0diff --git a/scripts/stabilize.py b/scripts/stabilize.pyindex 2a6327e..1d4a8dd 100644--- a/scripts/stabilize.py+++ b/scripts/stabilize.py@@ -73,7 +73,7 @@ def main() -> int:cmd.append(output)run(cmd)- result = probe(output)+ result = probe(output, role="output")info(f"wrote {output} ({result['duration']:.3f}s, {result['video']['width']}x{result['video']['height']})")emit(output)return 0diff --git a/scripts/sync.py b/scripts/sync.pyindex 47a388e..40e1c8c 100755--- a/scripts/sync.py+++ b/scripts/sync.py@@ -61,7 +61,7 @@ def decode_mono(path: str, seconds: float, start: float = 0.0) -> List[float]:"-vn", "-ac", "1", "-ar", str(SR), "-f", "s16le", "-"]proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)if proc.returncode != 0 or not proc.stdout:- die(f"could not decode audio from {path}:\n{proc.stderr.decode(errors='replace').strip()}")+ die(f"could not decode audio from {path}:\n{proc.stderr.decode(errors='replace').strip()}", kind="ffmpeg")n = len(proc.stdout) // 2return [v / 32768.0 for v in struct.unpack(f"<{n}h", proc.stdout[: n * 2])]diff --git a/tests/test_contract.py b/tests/test_contract.pyindex b1bd500..ac05ca4 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -75,6 +75,12 @@ class ContractTests(unittest.TestCase):ffmpeg("-f", "lavfi", "-i", "[email protected]:s=120x40,format=rgba", "-frames:v", "1", cls.logo)cls.cues = OUT / "c_cues.txt"cls.cues.write_text("0:00-0:02 Hello\n0:02-0:04 World\n", encoding="utf-8")+ cls.garbage = OUT / "c_garbage.mp4"+ cls.garbage.write_bytes(bytes((i * 7919) % 256 for i in range(200_000)))+ cls.empty = OUT / "c_empty.mp4"+ cls.empty.write_bytes(b"")+ cls.badlut = OUT / "c_bad.cube"+ cls.badlut.write_text("this is not a LUT\n", encoding="utf-8")cls.work = Path(tempfile.mkdtemp(prefix="ffskill_contract_"))cls.input_hashes = {p: cls._sha(p) for p in (cls.src, cls.wav, cls.mic, cls.camb, cls.vfr, cls.hdr, cls.surround)}@@ -528,6 +534,83 @@ class ContractTests(unittest.TestCase):self.assertEqual(proc.returncode, 127)self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "missing_tool")+ # ------------------------------------------------------------------ fail loudly+ def _fails(self, name, *args, kind=None, code=None):+ proc = tool(name, *args, "--json", check=False)+ self.assertNotEqual(proc.returncode, 0, f"{name} {args}: exit 0 on a failure")+ doc = json.loads(proc.stdout)+ self.assertEqual(doc["status"], "failed", name)+ self.assertEqual(doc["exit_code"], proc.returncode)+ self.assertIn("commands", doc)+ self.assertTrue(doc["error"]["message"], name)+ if kind:+ self.assertEqual(doc["error"]["kind"], kind, f"{name}: {doc['error']}")+ if code:+ self.assertEqual(proc.returncode, code)+ self.assertIn("error:", proc.stderr)+ return doc++ def test_input_failures_are_loud(self):+ missing = self.work / "does_not_exist.mp4"+ self._fails("cut", missing, "--start", "1", "--end", "2", "-o", self.out("f1.mp4"), kind="input")+ self._fails("cut", self.garbage, "--start", "1", "--end", "2", "-o", self.out("f2.mp4"), kind="input")+ self._fails("cut", self.empty, "--start", "1", "--end", "2", "-o", self.out("f3.mp4"), kind="input")+ self._fails("probe", self.garbage, kind="input")+ self._fails("loudness", self.garbage, "-o", self.out("f4.wav"), kind="input")+ self._fails("audio", self.wav, "--replace", missing, "-o", self.out("f5.wav"), kind="input")+ self._fails("export", self.wav, "--preset", "youtube", "-o", self.out("f6.mp4"), kind="input") # no video stream+ self._fails("cut", self.src, "--start", "20", "--end", "30", "-o", self.out("f7.mp4"), kind="input") # beyond duration+ self._fails("fit", self.src, "--duration", "3", "--fps", "0", "-o", self.out("f8.mp4"), kind="input")+ self.assertEqual(sorted(p.name for p in self.work.glob("f[0-9].*")), [], "no partial outputs left behind")++ def test_ffmpeg_failures_are_loud(self):+ doc = self._fails("color", self.src, "--lut", self.badlut, "--fast", "-o", self.out("g1.mp4"), kind="ffmpeg")+ self.assertTrue(any("ffmpeg" in c for c in doc["commands"]), "the failing command is reported")+ self._fails("loudness", self.wav, "-o", self.work / "no_such_dir" / "g2.wav", kind="ffmpeg")+ self._fails("cut", self.src, "--start", "1", "--end", "3", "-o", self.out("g3.txt")) # unknown container+ self.assertFalse(self.out("g1.mp4").exists())++ def test_output_verification_failures_are_loud(self):+ """A fake ffmpeg that exits 0 but writes an empty file: every writing tool must still fail."""+ shim = self.work / "shim0"+ shim.mkdir(exist_ok=True)+ (shim / "ffmpeg").write_text("#!/bin/sh\nfor last; do :; done\ncase \"$last\" in -|*null*) exit 0;; esac\n: > \"$last\"\nexit 0\n")+ (shim / "ffmpeg").chmod(0o755)+ env = dict(os.environ, PATH=f"{shim}:{os.environ['PATH']}")+ cases = {+ "cut": [self.src, "--start", "1", "--end", "3", "--accurate", "-o", self.out("v_cut.mp4")],+ "audio": [self.wav, "-o", self.out("v_au.mp3")],+ "silence": [self.src, "-o", self.out("v_sil.mp4")],+ "fit": [self.src, "--duration", "3", "-o", self.out("v_fit.mp4")],+ "export": [self.src, "--preset", "x", "-o", self.out("v_exp.mp4")],+ "caption": [self.src, "--text", self.cues, "-o", self.out("v_cap.mp4")],+ "overlay": [self.src, "--image", self.logo, "-o", self.out("v_ov.mp4")],+ "color": [self.hdr, "--to-sdr", "-o", self.out("v_col.mp4")],+ "look": [self.src, "-o", self.out("v_look.png")],+ }+ for name, args in cases.items():+ proc = tool(name, *args, "--json", env=env, check=False)+ self.assertNotEqual(proc.returncode, 0, f"{name}: exit 0 with an unusable output")+ doc = json.loads(proc.stdout)+ self.assertEqual(doc["status"], "failed", name)+ self.assertEqual(doc["error"]["kind"], "output", f"{name}: {doc['error']}")+ self.assertIn("output verification failed", doc["error"]["message"])+ self.assertNotIn("probe", doc)+ self.assertFalse(Path(args[-1]).exists(), f"{name}: empty output left behind")+ # the same path with the real ffmpeg succeeds and carries a probe of the output+ doc = json.loads(tool("cut", self.wav, "--start", "1", "--end", "3", "-o", self.out("v_ok.wav"), "--json").stdout)+ self.assertEqual(doc["status"], "completed")+ self.assertGreater(doc["probe"]["duration"], 1.5)++ def test_success_requires_a_verified_output(self):+ import _common+ for name in ("cut", "audio", "loudness", "silence", "fit", "export", "caption", "overlay", "color", "join", "graphics", "multicam"):+ src = (SCRIPTS / f"{name}.py").read_text(encoding="utf-8")+ self.assertIn("emit(", src, f"{name} does not go through emit()")+ self.assertIn("verify_output(output)", (SCRIPTS / "_common.py").read_text(encoding="utf-8"))+ with self.assertRaises(SystemExit):+ _common.verify_output(str(self.work / "never_written.mp4"))+def _run_structured(self, name, args):"""Drive a tool the way an agent adapter would: structured args -> argv (same mapping as MCP)."""argv = mcp_server.build_argv(name, args)