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
fix: fourth audit -- dry-run side files, SMPTE in every tool, pad time grammar, cut --segments input guard (#183)
claude[bot]ff19afe1d553
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 747c6af..9264816 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,11 @@## Unreleased- README gains a "Gotchas and best practices" section for human readers: VFR, keyframe snapping, HDR, loudness targets, caption order, 9:16 crops, fonts, silence threshold, sync confidence, plans; every flag named is checked against the scripts' `--help`.+- `--dry-run` writes no side files either: `silence.py --edl`, `scenes.py --edl` and the `.ass` that `caption.py --animate/--karaoke` generates were written while stderr said "would write". The contract's note for these tools was right; the code was not.+- SMPTE `hh:mm:ss:ff` times resolve with the input's fps in every tool that takes a time (`overlay`, `graphics`, `look`, `insert`, `background`, `fit`, `loop`), and a bad time is a `kind: input` failure document naming the flag instead of a traceback (`time_arg()` in `_common.py`; `cut`/`freeze` already did this).+- `pad.py --start/--end` accept the shared time grammar (`1:30`) like every other tool; junk is a `kind: input` refusal, not an argparse exit 2 without JSON.+- `cut.py --segments` refuses an output that is the same file as its input. The run() guard compares each ffmpeg command's `-i` with its output, and the final concat's only `-i` is the temp list file, so `-o in.mp4` replaced the source with the join (fourth review, P0); the single-segment path already refused.+- The dry-run exception list in SKILL.md and `docs/contract.md` names `silence`, `loudness` and `stabilize` again; the pinning test now checks the sentence that states the exception in all three docs, not "the name appears somewhere in the file", which is how the list drifted twice.## 1.4.8diff --git a/SKILL.md b/SKILL.mdindex c684ac1..87bb69a 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` may still run ffmpeg/ffprobe to measure or analyse — they just don't write their final artifact; `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). 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.mdindex da039d4..be65f8e 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -156,9 +156,10 @@ with `--dry-run` behind a fake `ffmpeg` that records any call, and asserts thatcall happened and no file appeared. Under `--dry-run` a tool prints the command linesit would run, reports `dry_run: true`, and never reports an output probe. Theexceptions are stated per tool in the contract's `dry_run` field: `probe` and `check` are-read-only (ffprobe still runs), `sync`, `multicam`, `scenes`, `cropdetect` and `report` still-run their ffmpeg/ffprobe measurements (the analysis is the tool's job; only the artifact is-skipped), and `verify` does not support dry-run (its steps run). `SKILL.md` and+read-only (ffprobe still runs); `sync`, `multicam`, `scenes`, `cropdetect`, `report`, `silence`,+`loudness` and `stabilize` still run their ffmpeg/ffprobe measurements (the analysis is the+tool's job; only the artifact is skipped, including side files such as `--edl`, `--sheet` or a+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.### Repeatabilitydiff --git a/scripts/_common.py b/scripts/_common.pyindex a2c89c2..a1b2076 100755--- a/scripts/_common.py+++ b/scripts/_common.py@@ -356,6 +356,26 @@ def _check_no_overwrite_input(cmd: Sequence[str]) -> None:continue+def refuse_output_is_input(output: str, *inputs: str) -> None:+ """Tool-level twin of the run() guard, for tools whose final ffmpeg command does not name+ the user's input at all. `cut.py --segments` cuts each part into a temp dir and then concats+ a list file: the last command's only `-i` is that list, so `-o` equal to the input sailed+ through _check_no_overwrite_input() and replaced the source with the join (fourth audit,+ P0). Call it once the output path is known, before any part of the input is consumed."""+ try:+ out_real = os.path.realpath(output)+ except OSError:+ return+ for inp in inputs:+ try:+ same = os.path.realpath(inp) == out_real+ except OSError:+ continue+ if same:+ die(f"refusing to run: output {output!r} is the same file as input {inp!r} "+ f"(the result would replace the source) -- choose a different --output/-o path", kind="input")++def _check_existing_output(cmd: Sequence[str]) -> None:"""An output path that already exists is someone's file: a previous result, a source theagent mis-named, a deliverable from another run. ffmpeg's -y (which every command carries so@@ -954,6 +974,19 @@ def parse_time(value: str, fps: Optional[float] = None) -> float:return total+def time_arg(value: str, flag: str, fps: Optional[float] = None) -> float:+ """parse_time() for a command-line flag: SMPTE hh:mm:ss:ff resolves with the input's fps when+ the caller has one, and every parse failure is a `kind: input` refusal naming the flag (so+ `--json` callers get a failure document, never a traceback)."""+ try:+ return parse_time(value, fps)+ except MissingFpsError as e:+ die(f"{flag} {value!r}: {e}")+ except ValueError as e:+ die(f"{flag} {value!r}: {e} (use seconds, mm:ss, hh:mm:ss.ms or, with a known fps, hh:mm:ss:ff)")+ return 0.0 # unreachable++def fmt_srt_time(seconds: float) -> str:if seconds < 0:seconds = 0.0diff --git a/scripts/background.py b/scripts/background.pyindex 5632e40..0775024 100644--- a/scripts/background.py+++ b/scripts/background.py@@ -14,7 +14,7 @@ import argparseimport mathimport sys-from _common import add_common, apply_common, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS+from _common import add_common, apply_common, die, emit, ffmpeg_base, info, parse_time, probe, run, validate_color, video_args, X264_PRESETS, time_argdef main() -> int:@@ -34,7 +34,7 @@ def main() -> int:args = ap.parse_args()apply_common(args)- target = parse_time(args.duration)+ target = time_arg(args.duration, "--duration", args.fps)if target <= 0:die("--duration must be > 0")if args.fps <= 0:diff --git a/scripts/caption.py b/scripts/caption.pyindex ff1f6ea..8616980 100755--- a/scripts/caption.py+++ b/scripts/caption.py@@ -200,7 +200,10 @@ def parse_srt(path: str) -> List[Tuple[float, float, str]]:if times:a, b = times.split("-->")text = "\n".join(block[block.index(times) + 1:]).strip()- cues.append((parse_time(a), parse_time(b), text))+ try:+ cues.append((parse_time(a), parse_time(b), text))+ except ValueError as e: # includes MissingFpsError: SRT timings are hh:mm:ss,ms, never frames+ die(f"{path}: cannot read the timing line {times.strip()!r}: {e}")block = []if not cues:die(f"no cues found in {path}")@@ -531,12 +534,16 @@ def main() -> int:w, h = meta["video"]["width"], meta["video"]["height"]if meta["video"].get("rotation") in (90, -90, 270, -270):w, h = h, w- write_ass(cues_for_ass, ass_path, args, w, h, video=args.input if meta.get("audio") else None)+ if not STATE.dry_run: # the generated ASS is an artifact of this run: a plan writes nothing+ write_ass(cues_for_ass, ass_path, args, w, h, video=args.input if meta.get("audio") else None)info(f"wrote {ass_path} ({len(cues_for_ass)} cues, animate={args.animate}, karaoke={args.karaoke})")args.ass = ass_path+ generated_ass = True+ else:+ generated_ass = Falseif args.ass:- if not os.path.exists(args.ass):+ if not generated_ass and not os.path.exists(args.ass):die(f"ASS file not found: {args.ass}")vf = f"ass={escape_filter_path(args.ass)}"if args.fonts_dir:diff --git a/scripts/cut.py b/scripts/cut.pyindex 137132f..e046cfb 100755--- a/scripts/cut.py+++ b/scripts/cut.py@@ -30,7 +30,7 @@ import sysimport tempfilefrom typing import List, Tuple-from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near, MissingFpsError, concat_list_line+from _common import video_args, STATE, add_common, apply_common, audio_codec_for, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, is_audio_output, parse_time, probe, run, X264_PRESETS, keyframes_near, MissingFpsError, concat_list_line, refuse_output_is_input# keyframe timestamps found next to a requested cut that the tolerance turned into a re-encode# (reported so the caller can choose a lossless cut at one of them next time)@@ -192,6 +192,7 @@ def main() -> int:segments = [(s, min(e, total) if total else e) for s, e in segments]output = args.output or default_output(args.input, "cut")+ refuse_output_is_input(output, args.input)ext = os.path.splitext(output)[1] or ".mp4"reencoded = Falsediff --git a/scripts/fit.py b/scripts/fit.pyindex 8ead7fa..2aced2a 100755--- a/scripts/fit.py+++ b/scripts/fit.py@@ -38,7 +38,7 @@ import sysfrom fractions import Fractionfrom typing import List-from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args, X264_PRESETS+from _common import video_args, STATE, add_common, apply_common, emit, aac_args, cfr_args, default_output, die, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, pad_filters, add_pad_fill_args, X264_PRESETS, time_argASPECT_PRESETS = {"16:9": Fraction(16, 9), "9:16": Fraction(9, 16), "1:1": Fraction(1, 1), "4:5": Fraction(4, 5), "4:3": Fraction(4, 3), "21:9": Fraction(21, 9)}@@ -155,7 +155,7 @@ def main() -> int:# ---- durationif args.duration:- target = parse_time(args.duration)+ target = time_arg(args.duration, "--duration", meta["video"].get("fps") if meta.get("video") else None)if target <= 0:die("target duration must be > 0")if args.method == "speed":diff --git a/scripts/graphics.py b/scripts/graphics.pyindex c16f99e..8fd2443 100755--- a/scripts/graphics.py+++ b/scripts/graphics.py@@ -21,7 +21,7 @@ import argparseimport sysfrom typing import List, Optional-from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_font_file, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args, drawtext_boxborderw, X264_PRESETS+from _common import aac_args, add_common, apply_common, cfr_args, color_hex, default_font_file, default_output, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, load_brand, parse_time, probe, run, run_keeping_subtitles, video_args, drawtext_boxborderw, X264_PRESETS, time_argTEMPLATES = ["lower-third", "title", "chapter", "progress", "countdown", "bug"]@@ -86,8 +86,9 @@ def main() -> int:if meta["video"].get("rotation") in (90, -90, 270, -270):W, H = H, Wdur = meta.get("duration") or 0.0- s = parse_time(args.start) if args.start else 0.0- e = parse_time(args.end) if args.end else dur+ fps = meta["video"].get("fps")+ s = time_arg(args.start, "--start", fps) if args.start else 0.0+ e = time_arg(args.end, "--end", fps) if args.end else durif e <= s:die("--end must be after --start")en = f"enable='between(t,{s:.3f},{e:.3f})'"diff --git a/scripts/insert.py b/scripts/insert.pyindex fdf34f3..abb040b 100644--- a/scripts/insert.py+++ b/scripts/insert.py@@ -27,7 +27,7 @@ import argparseimport mathimport sys-from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS+from _common import add_common, apply_common, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS, time_argdef even(n: float) -> int:@@ -52,7 +52,7 @@ def main() -> int:args = ap.parse_args()apply_common(args)- target = parse_time(args.duration)+ target = time_arg(args.duration, "--duration", args.fps)if target <= 0:die("--duration must be > 0")if args.fps <= 0:diff --git a/scripts/look.py b/scripts/look.pyindex 6c18c73..4ef163f 100755--- a/scripts/look.py+++ b/scripts/look.py@@ -15,7 +15,7 @@ import sysfrom pathlib import Pathfrom typing import List-from _common import add_common, apply_common, default_font_file, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run+from _common import add_common, apply_common, default_font_file, die, emit, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, time_argFONT = "fontcolor=white:fontsize=h/18:box=1:[email protected]:boxborderw=6:x=8:y=8"@@ -69,7 +69,7 @@ def main() -> int:die("--compare needs --at TIME")probe(args.compare)for t in args.at:- sec = parse_time(t)+ sec = time_arg(t, "--at", meta["video"].get("fps") if meta.get("video") else None)out = args.output or os.path.join(outdir, f"{stem}_vs_{Path(args.compare).stem}_{sec:.3f}s.png")half = args.width // 2stamp = "" if args.no_timecode else f",drawtext=text='{escape_drawtext(fmt_hms(sec))}':{font_prefix}{FONT}"@@ -82,7 +82,7 @@ def main() -> int:outputs.append(out)elif args.at:for t in args.at:- sec = parse_time(t)+ sec = time_arg(t, "--at", meta["video"].get("fps") if meta.get("video") else None)if dur and sec > dur:die(f"--at {t} is beyond the duration ({dur:.2f}s)")if args.output and len(args.at) == 1 and Path(args.output).suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"):diff --git a/scripts/loop.py b/scripts/loop.pyindex 29acb18..dafc8de 100644--- a/scripts/loop.py+++ b/scripts/loop.py@@ -18,7 +18,7 @@ import argparseimport mathimport sys-from _common import add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS+from _common import add_common, aac_args, apply_common, cfr_args, default_output, die, emit, ffmpeg_base, info, parse_time, probe, run, video_args, X264_PRESETS, time_argdef main() -> int:@@ -49,7 +49,7 @@ def main() -> int:target = Nonestream_loop = args.times - 1else:- target = parse_time(args.duration)+ target = time_arg(args.duration, "--duration", meta["video"].get("fps") if meta.get("video") else None)if target <= src_dur:die(f"--duration ({target:g}s) must be longer than the source ({src_dur:.3f}s) -- use cut.py to trim instead")stream_loop = math.ceil(target / src_dur) - 1diff --git a/scripts/metadata.py b/scripts/metadata.pyindex 19ca1f9..ef3f3fc 100755--- a/scripts/metadata.py+++ b/scripts/metadata.py@@ -48,7 +48,7 @@ def parse_chapters(path: str, duration: float) -> List[Dict[str, Any]]:parts = line.split(None, 1)try:start = parse_time(parts[0])- except ValueError:+ except ValueError: # MissingFpsError is a ValueError: chapter files carry no fpsdie(f"{path}:{n}: cannot read the time in {line!r} (use seconds, mm:ss or hh:mm:ss.ms)")title = parts[1].strip() if len(parts) > 1 else f"Chapter {len(entries) + 1}"if entries and start <= entries[-1]["start"]:diff --git a/scripts/overlay.py b/scripts/overlay.pyindex f749274..bddf092 100755--- a/scripts/overlay.py+++ b/scripts/overlay.py@@ -24,7 +24,7 @@ import argparseimport sysfrom typing import List, Optional-from _common import STATE, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, X264_PRESETS+from _common import STATE, load_brand, video_args, add_common, apply_common, default_font_file, emit, aac_args, cfr_args, default_output, die, escape_drawtext, escape_filter_path, ffmpeg_base, info, parse_time, probe, run, run_keeping_subtitles, validate_color, x264_args, X264_PRESETS, time_argPOS = {"top-left": ("{m}", "{m}"),@@ -155,8 +155,9 @@ def main() -> int:if args.audio_stream and not audio_streams:die("--audio-stream needs an input with audio streams")vw = meta["video"]["width"]- start = parse_time(args.start) if args.start else None- end = parse_time(args.end) if args.end else None+ fps = meta["video"].get("fps")+ start = time_arg(args.start, "--start", fps) if args.start else None+ end = time_arg(args.end, "--end", fps) if args.end else Noneif start is not None and end is not None and end <= start:die("--end must be after --start")if not 0 <= args.opacity <= 1:diff --git a/scripts/pad.py b/scripts/pad.pyindex f27ff0a..a767c76 100644--- a/scripts/pad.py+++ b/scripts/pad.py@@ -16,15 +16,15 @@ Examples:import argparseimport sys-from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS+from _common import add_common, apply_common, aac_args, cfr_args, default_output, die, emit, ffmpeg_base, info, probe, run_keeping_subtitles, validate_color, video_args, X264_PRESETS, time_argdef main() -> int:ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)ap.add_argument("input")ap.add_argument("-o", "--output", help="output file (default: <name>_pad.<ext>)")- ap.add_argument("--start", type=float, default=0.0, help="seconds of padding to add before the clip (default 0)")- ap.add_argument("--end", type=float, default=0.0, help="seconds of padding to add after the clip (default 0)")+ ap.add_argument("--start", default="0", help="padding to add before the clip: seconds or mm:ss (default 0)")+ ap.add_argument("--end", default="0", help="padding to add after the clip: seconds or mm:ss (default 0)")ap.add_argument("--color", default="black", help="padding colour (default black)")ap.add_argument("--crf", type=int, default=18, help="x264 CRF (default 18)")ap.add_argument("--preset", default="medium", choices=X264_PRESETS, help="x264 preset")@@ -32,6 +32,8 @@ def main() -> int:args = ap.parse_args()apply_common(args)+ args.start = time_arg(args.start, "--start")+ args.end = time_arg(args.end, "--end")if args.start < 0 or args.end < 0:die(f"--start/--end must be >= 0, got start={args.start:g} end={args.end:g}")if args.start == 0 and args.end == 0:diff --git a/scripts/scenes.py b/scripts/scenes.pyindex 6fb8caf..b0dad10 100755--- a/scripts/scenes.py+++ b/scripts/scenes.py@@ -24,7 +24,7 @@ import reimport sysfrom typing import Dict, List, Tuple-from _common import add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, require_tool, run, run_analysis, decode_pcm_mono, rms_envelope+from _common import STATE, add_common, apply_common, default_font_file, die, emit, escape_filter_path, ffmpeg_base, info, print_json, probe, require_tool, run, run_analysis, decode_pcm_mono, rms_envelopeSCORE_RE = re.compile(r"frame:(\d+)\s+pts:\d+\s+pts_time:([0-9.]+)")@@ -168,9 +168,10 @@ def main() -> int:result["highlights_rank_by"] = args.rank_byinfo(f"proposed {len(picks)} highlight ranges totalling {result['highlights_total']:.1f}s")if args.edl:- with open(args.edl, "w", encoding="utf-8") as fh:- for s, e in picks:- fh.write(f"{s:.2f}-{e:.2f}\n")+ if not STATE.dry_run: # the contract says --edl is not written under --dry-run+ with open(args.edl, "w", encoding="utf-8") as fh:+ for s, e in picks:+ fh.write(f"{s:.2f}-{e:.2f}\n")info(f"wrote {args.edl}")if args.sheet:diff --git a/scripts/silence.py b/scripts/silence.pyindex c6ab7a7..511eacb 100755--- a/scripts/silence.py+++ b/scripts/silence.py@@ -104,9 +104,10 @@ def main() -> int:info("hint: " + summary["hint"])if args.edl:- with open(args.edl, "w", encoding="utf-8") as fh:- for s, e in keeps:- fh.write(f"{s:.3f}-{e:.3f}\n")+ if not STATE.dry_run: # the EDL is an artifact like the cut itself: a plan writes nothing+ with open(args.edl, "w", encoding="utf-8") as fh:+ for s, e in keeps:+ fh.write(f"{s:.3f}-{e:.3f}\n")info(f"wrote {args.edl}")if args.list:diff --git a/tests/test_all.py b/tests/test_all.pyindex 23923d0..f52a4fd 100644--- a/tests/test_all.py+++ b/tests/test_all.py@@ -2110,7 +2110,7 @@ class FFmpegSkillTests(unittest.TestCase):(force_style) path."""hostile_font = "Arial,Bold:evil"ass_out = OUT / "font_inject.ass"- script("caption.py", self.src, "--text", self.cues, "--font", hostile_font, "--animate", "fade", "--write-ass", ass_out, "--dry-run")+ script("caption.py", self.src, "--text", self.cues, "--font", hostile_font, "--animate", "fade", "--write-ass", ass_out, "--fast", "-o", OUT / "font_inject.mp4")style_line = next(l for l in ass_out.read_text(encoding="utf-8").splitlines() if l.startswith("Style: Default,"))self.assertNotIn(",Arial,Bold:evil,", style_line, "raw hostile font must not appear -- it would shift every later field")fields = style_line.split(",")@@ -2130,7 +2130,8 @@ class FFmpegSkillTests(unittest.TestCase):hostile_cues = OUT / "brace_inject_cues.txt"hostile_cues.write_text("00:00:00 --> 00:00:03 hi {\\pos(0,0)\\fscx500}INJECTED\n", encoding="utf-8")ass_out = OUT / "brace_inject.ass"- script("caption.py", self.src, "--text", hostile_cues, "--animate", "fade", "--write-ass", ass_out, "--dry-run")+ # a real (fast) burn: since 1.4.9 --dry-run writes no side files, the generated ASS included+ script("caption.py", self.src, "--text", hostile_cues, "--animate", "fade", "--write-ass", ass_out, "--fast", "-o", OUT / "brace_inject.mp4")dialogue = next(l for l in ass_out.read_text(encoding="utf-8").splitlines() if l.startswith("Dialogue: "))# --animate fade legitimately prepends its own "{\fad(200,200)}" override block; only the# cue-text-derived braces from the hostile payload must be gone.diff --git a/tests/test_contract.py b/tests/test_contract.pyindex 8cbda17..be2ef2e 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -506,13 +506,18 @@ class ContractTests(unittest.TestCase):analysis_tools = set(_contract.DRY_RUN_ANALYSIS.keys())self.assertEqual(analysis_tools, {"sync", "multicam", "scenes", "report", "cropdetect", "silence", "loudness", "check", "stabilize"},"the analysis-only dry-run tool set changed -- update SKILL.md/references/scripts.md's exception list to match")- skill = (ROOT / "SKILL.md").read_text(encoding="utf-8")- scripts_ref = (ROOT / "references" / "scripts.md").read_text(encoding="utf-8")- for name in analysis_tools:- self.assertIn(name, skill, f"SKILL.md's dry-run exception note is missing {name!r}")- self.assertIn(name, scripts_ref, f"references/scripts.md's dry-run exception note is missing {name!r}")- self.assertIn("verify", skill)- self.assertIn("verify", scripts_ref)+ # "the name appears somewhere in the file" was too weak: every tool name is in SKILL.md's+ # request table anyway, so the list drifted twice (#176 -> #179) with this test green.+ # Pin the sentence that states the exception: the one naming `verify` and `--dry-run`.+ docs = {"SKILL.md": ROOT / "SKILL.md", "references/scripts.md": ROOT / "references" / "scripts.md",+ "docs/contract.md": ROOT / "docs" / "contract.md"}+ for label, path in docs.items():+ text = path.read_text(encoding="utf-8")+ paragraphs = [p for p in text.split("\n\n") if "verify" in p and "dry-run" in p and "multicam" in p]+ self.assertTrue(paragraphs, f"{label}: no paragraph states the dry-run exceptions (names verify, multicam and dry-run)")+ for name in analysis_tools:+ self.assertTrue(any(f"`{name}`" in p for p in paragraphs),+ f"{label}'s dry-run exception sentence is missing `{name}`")def test_skill_workflow_mentions_doctor_and_contract(self):"""SKILL.md's Workflow section (the first thing an agent reads) used to never mention@@ -1365,6 +1370,71 @@ class ContractTests(unittest.TestCase):self.assertEqual(json.loads((ROOT / "package.json").read_text())["files"].count("docs/contract.md"), 1)self.assertIn("'docs'", (ROOT / "bin" / "install.js").read_text())+ def test_fourth_audit_regressions(self):+ """Pins from the fourth audit (1.4.8). N01: --dry-run used to skip only ffmpeg, so+ silence --edl, scenes --edl and caption's generated .ass were written while stderr said+ "would write". N02: overlay/graphics/look/insert/background/fit/loop called parse_time()+ without the input's fps, so an hh:mm:ss:ff time was a MissingFpsError traceback with no+ --json failure document (cut/freeze had been fixed, the rest had not). N03: pad --start/--end+ were argparse floats, so the mm:ss grammar every other tool accepts exited 2 without JSON."""+ # N01 -- a dry run writes no side files either+ edl = self.out("dry_silence.edl")+ proc = tool("silence", self.src, "--dry-run", "--edl", edl, "--json")+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ self.assertFalse(edl.exists(), "silence --dry-run wrote --edl")+ edl2 = self.out("dry_scenes.edl")+ proc = tool("scenes", self.src, "--dry-run", "--highlights", "2", "--edl", edl2, "--json")+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ self.assertFalse(edl2.exists(), "scenes --dry-run wrote --edl")+ cues = self.out("dry_cues.txt")+ cues.write_text("0:00 hello\n0:02 world\n", encoding="utf-8")+ cap = self.out("dry_cap.mp4")+ proc = tool("caption", self.src, "--text", cues, "--animate", "pop", "--dry-run", "--json", "-o", cap)+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ self.assertFalse(cap.with_suffix(".ass").exists(), "caption --dry-run wrote the generated .ass")+ self.assertFalse(cap.exists())+ # N02 -- SMPTE resolves with the input's fps; a bad timecode is a kind: input document+ proc = tool("overlay", self.src, "--text", "hi", "--start", "00:00:01:15", "--dry-run", "--json", "-o", self.out("smpte_ov.mp4"))+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ self.assertNotIn("Traceback", proc.stderr)+ proc = tool("look", self.src, "--at", "00:00:01:15", "--dry-run", "--json", "-o", self.out("smpte_look.png"))+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ self.assertIn("1.500", " ".join(map(str, json.loads(proc.stdout)["commands"])))+ proc = tool("overlay", self.src, "--text", "hi", "--start", "00:00:01:99", "--json", "-o", self.out("smpte_ov_bad.mp4"), check=False)+ self.assertNotEqual(proc.returncode, 0)+ self.assertNotIn("Traceback", proc.stderr)+ doc = json.loads(proc.stdout)+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("--start", doc["error"]["message"])+ proc = tool("fit", self.src, "--duration", "00:00:01:15", "--dry-run", "--json", "-o", self.out("smpte_fit.mp4"))+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ proc = tool("background", "--duration", "00:00:01:15", "--fps", "30", "--width", "64", "--height", "64", "--dry-run", "--json", "-o", self.out("smpte_bg.mp4"))+ self.assertIn("1.500", " ".join(map(str, json.loads(proc.stdout)["commands"])))+ # N03 -- pad speaks the shared time grammar and refuses junk as kind: input+ proc = tool("pad", self.src, "--start", "1:30", "--dry-run", "--json", "-o", self.out("pad_mmss.mp4"))+ self.assertEqual(proc.returncode, 0, proc.stderr[-300:])+ self.assertIn("start_duration=90.000", " ".join(map(str, json.loads(proc.stdout)["commands"])))+ proc = tool("pad", self.src, "--start", "abc", "--json", "-o", self.out("pad_bad.mp4"), check=False)+ self.assertEqual(json.loads(proc.stdout)["error"]["kind"], "input")++ def test_cut_segments_refuses_output_equal_to_input(self):+ """Fourth review, P0: `cut.py in.mp4 --segments 0-1,2-3 -o in.mp4` replaced the source+ with the 2 s join. The run() guard compares the ffmpeg command's -i paths with its output,+ and the final concat command's only -i is the temp list file, so it never fired; the+ single-segment path (whose -i is the input) refused correctly. Pin the tool-level guard+ with both spellings of the same file, and that the source is untouched."""+ victim = self.out("victim_segments.mp4")+ shutil.copyfile(self.src, victim)+ before = victim.read_bytes()+ for spelling in (str(victim), os.path.join(str(victim.parent), ".", victim.name)):+ proc = tool("cut", victim, "--segments", "0-1,2-3", "--json", "-o", spelling, check=False)+ self.assertNotEqual(proc.returncode, 0, spelling)+ doc = json.loads(proc.stdout)+ self.assertEqual(doc["status"], "failed")+ self.assertEqual(doc["error"]["kind"], "input")+ self.assertIn("same file as input", doc["error"]["message"])+ self.assertEqual(victim.read_bytes(), before, "the source was modified")+def test_failed_run_never_deletes_an_output_that_predates_it(self):"""The partial-output cleanup (#78) removed the output path after every failed ffmpeg runwithout asking whether the file had been there before: a bad filter argument aimed at an