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.

chore: attribute-only Context; ship only the agent-facing references in the npm package (#177)

Shogo Kajiyama8e8c82f49faa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7fc77bd..d5a0cf4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
## Unreleased
- Docs: README no longer claims media ffmpeg calls have no timeout; tool counts read 42 everywhere (the count test now catches the "all N by" / "same N names" phrasings); `docs/contract.md` lists every dry-run exception; the error-kind list is identical in SKILL.md, README and the contract; SKILL.md states the dry-run exceptions once and moves the Windows drawtext story to `references/ci-platform-pitfalls.md`; CODE_OF_CONDUCT.md added.
+- The npm package ships `references/scripts.md`, `devices.md` and `ci-platform-pitfalls.md` only; the maintainer diary `process-pitfalls.md` stays in the repository. Internal: the `Context` dict-style shims are gone, every call site uses attributes.
## 1.4.5
diff --git a/package.json b/package.json
index b4f0a3f..8c7c5ce 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,9 @@
"bin/",
"scripts/",
"mcp/",
- "references/",
+ "references/scripts.md",
+ "references/devices.md",
+ "references/ci-platform-pitfalls.md",
"SKILL.md",
"README.md",
"LICENSE"
diff --git a/scripts/_common.py b/scripts/_common.py
index 64f4f3e..820dfd9 100755
--- a/scripts/_common.py
+++ b/scripts/_common.py
@@ -207,12 +207,11 @@ class Context:
"""Per-process settings that the shared flags (--dry-run, --json, --progress, --fast) set once.
Scripts read it as attributes (``STATE.dry_run``) or, for older call sites, like a dict
- (``STATE["dry_run"]``). Keeping it a single explicit object rather than module globals makes
+ (``STATE.dry_run``). Keeping it a single explicit object rather than module globals 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")
- _KEYS = ("dry_run", "json", "progress", "fast", "duration_hint", "commands", "timeout", "overwrite", "written", "preexisting")
def __init__(self) -> None:
self.reset()
@@ -229,19 +228,6 @@ class Context:
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
- # mapping-style access kept for backwards compatibility
- def __getitem__(self, key: str) -> Any:
- if key not in self._KEYS:
- raise KeyError(key)
- return getattr(self, key)
-
- def __setitem__(self, key: str, value: Any) -> None:
- if key not in self._KEYS:
- raise KeyError(key)
- setattr(self, key, value)
-
- def get(self, key: str, default: Any = None) -> Any:
- return getattr(self, key, default) if key in self._KEYS else default
STATE = Context()
@@ -689,9 +675,9 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]:
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"]:
+ if role == "output" and not STATE.dry_run:
_output_failed(path, "not written")
- if STATE["dry_run"]:
+ if STATE.dry_run:
# width/height/fps are honestly 0/0/0.0 -- "not measured", matching duration/size_bytes
# below -- because this is a dry run: the file doesn't exist yet, so there is nothing to
# probe. Earlier this stub used plausible-looking placeholders (1920x1080x30.0) instead,
@@ -728,8 +714,8 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]:
duration = _to_float(video.get("duration"))
if duration is None and audio:
duration = _to_float(audio.get("duration"))
- if duration and STATE.get("duration_hint") is None:
- STATE["duration_hint"] = duration
+ if duration and STATE.duration_hint is None:
+ STATE.duration_hint = duration
out: Dict[str, Any] = {
"file": path,
diff --git a/scripts/audio.py b/scripts/audio.py
index 9d6a8a3..87816de 100755
--- a/scripts/audio.py
+++ b/scripts/audio.py
@@ -131,9 +131,9 @@ def main() -> int:
output = args.output or default_output(args.input, "audio")
audio_out = is_audio_output(output)
streams = meta.get("audio_streams") or []
- if streams and not (0 <= args.audio_stream < len(streams)) and not STATE["dry_run"]:
+ if streams and not (0 <= args.audio_stream < len(streams)) and not STATE.dry_run:
die(f"--audio-stream {args.audio_stream}: input has {len(streams)} audio stream(s), 0..{len(streams) - 1}")
- if args.audio_stream and not streams and not STATE["dry_run"]:
+ if args.audio_stream and not streams and not STATE.dry_run:
die("--audio-stream needs an input with audio streams")
inputs: List[str] = ["-i", args.input]
@@ -222,7 +222,7 @@ def main() -> int:
run(cmd)
r = probe(output, role="output")
a = r["audio"]
- if r.get("video") and audio_out and not STATE["dry_run"]:
+ if r.get("video") and audio_out and not STATE.dry_run:
die(f"{output} unexpectedly contains a video stream")
info(f"wrote {output} ({r['duration']:.3f}s, audio {a['codec']} {a['channels']}ch {a['sample_rate']}Hz"
+ (", video stream-copied" if has_video and not audio_out else ", video dropped" if has_video else "") + ")")
diff --git a/scripts/batch.py b/scripts/batch.py
index 17db9a5..de85924 100755
--- a/scripts/batch.py
+++ b/scripts/batch.py
@@ -191,7 +191,7 @@ def main() -> int:
info(f"=== {src.name}")
r = process(src, recipe, outdir, work)
results.append(r)
- if r["ok"] and not STATE["dry_run"]:
+ if r["ok"] and not STATE.dry_run:
cache[key] = r
# write_text isn't atomic -- a process killed mid-write (or a --watch loop racing
# a concurrent manual run) could leave a truncated file that json.loads() above
diff --git a/scripts/broll.py b/scripts/broll.py
index 6fb4bfb..4bfd1f1 100755
--- a/scripts/broll.py
+++ b/scripts/broll.py
@@ -83,7 +83,7 @@ def main() -> int:
if dur_a and at + length > dur_a + 0.01:
die(f"cutaway {i + 1}: {at:g}s + {length:g}s runs past the end of the A-roll ({dur_a:.3f}s)")
dur_b = meta_b.get("duration") or 0.0
- if dur_b and start_b + length > dur_b + 0.01 and not STATE["dry_run"]:
+ if dur_b and start_b + length > dur_b + 0.01 and not STATE.dry_run:
die(f"cutaway {i + 1}: {path} has only {dur_b - start_b:.3f}s from {start_b:g}s, {length:g}s asked for")
if cutaways and at < cutaways[-1]["at"] + cutaways[-1]["length"]:
die(f"cutaway {i + 1} at {at:g}s overlaps the previous one (ends {cutaways[-1]['at'] + cutaways[-1]['length']:g}s)")
@@ -142,7 +142,7 @@ def main() -> int:
run(cmd)
result = probe(output, role="output")
- if not STATE["dry_run"] and dur_a and abs((result.get("duration") or 0.0) - dur_a) > max(0.1, 1.5 / fps):
+ if not STATE.dry_run and dur_a and abs((result.get("duration") or 0.0) - dur_a) > max(0.1, 1.5 / fps):
die(f"output is {result.get('duration'):.3f}s but the A-roll is {dur_a:.3f}s -- a cutaway must not change the length", kind="output")
info(f"wrote {output} ({result.get('duration', 0):.3f}s, {len(cutaways)} cutaway(s), audio={args.audio})")
emit(output, cutaways=[{"insert": c["path"], "at": c["at"], "end": c["at"] + c["length"], "from": c["from"]} for c in cutaways], audio=args.audio)
diff --git a/scripts/cut.py b/scripts/cut.py
index 72b0896..6f78218 100755
--- a/scripts/cut.py
+++ b/scripts/cut.py
@@ -117,7 +117,7 @@ def cut_one(src: str, start: float, end: float, dst: str, reencode: bool, crf: i
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()}", kind="ffmpeg")
- if not reencode and tolerance >= 0 and not STATE["dry_run"]:
+ if not reencode and tolerance >= 0 and not STATE.dry_run:
got = probe(dst).get("duration") or 0.0
if abs(got - dur) > tolerance:
near = keyframes_near(src, start)
@@ -209,7 +209,7 @@ def main() -> int:
expected = sum(e - s for s, e in segments)
precision = precision_of(meta, output, reencoded)
got = result.get("duration")
- error_ms = round((got - expected) * 1000, 3) if got is not None and not STATE["dry_run"] else None
+ error_ms = round((got - expected) * 1000, 3) if got is not None and not STATE.dry_run else None
# mode: "copy" (untouched lossless), "accurate" (--accurate was asked for), "hybrid" (asked for
# lossless but the keyframe snap exceeded --tolerance so this segment silently re-encoded instead)
mode = "copy" if not reencoded else ("accurate" if args.accurate else "hybrid")
diff --git a/scripts/export.py b/scripts/export.py
index a2e52ff..a05cd17 100755
--- a/scripts/export.py
+++ b/scripts/export.py
@@ -100,7 +100,7 @@ def main() -> int:
video = list(p["video"])
if args.crf is not None and "-crf" in video:
video[video.index("-crf") + 1] = str(args.crf)
- if STATE["fast"] and "-preset" in video:
+ if STATE.fast and "-preset" in video:
video[video.index("-preset") + 1] = "veryfast"
cmd += video
if args.preset != "copy":
diff --git a/scripts/fit.py b/scripts/fit.py
index 2e474d1..8ead7fa 100755
--- a/scripts/fit.py
+++ b/scripts/fit.py
@@ -159,7 +159,7 @@ def main() -> int:
if target <= 0:
die("target duration must be > 0")
if args.method == "speed":
- if src_dur <= 0 and STATE["dry_run"]:
+ if src_dur <= 0 and STATE.dry_run:
src_dur = target # planning against an intermediate that does not exist yet
factor = src_dur / target # >1 = speed up
if factor > args.max_speed or factor < 1 / args.max_speed:
@@ -175,7 +175,7 @@ def main() -> int:
if has_audio:
af.append(atempo_chain(factor))
post += ["-t", f"{target:.3f}"]
- STATE["duration_hint"] = target
+ STATE.duration_hint = target
else:
if target < src_dur:
start = (src_dur - target) / 2 if args.from_center else 0.0
diff --git a/scripts/join.py b/scripts/join.py
index 657b8b7..8de4388 100755
--- a/scripts/join.py
+++ b/scripts/join.py
@@ -36,7 +36,7 @@ def join_audio(args: argparse.Namespace, metas: List[dict]) -> int:
durs = [m.get("duration") or 0.0 for m in metas]
d = args.duration if args.transition != "none" else 0.0
for p, dur in zip(args.inputs, durs):
- if d and dur <= d * 2 and not STATE["dry_run"]:
+ if d and dur <= d * 2 and not STATE.dry_run:
die(f"{p} is only {dur:.2f}s, too short for a {d:.2f}s crossfade; shorten --duration")
rates = [m["audio"].get("sample_rate") or 48000 for m in metas]
chans = [m["audio"].get("channels") or 2 for m in metas]
@@ -70,7 +70,7 @@ def join_audio(args: argparse.Namespace, metas: List[dict]) -> int:
expected = sum(durs) - d * (n - 1)
r = probe(output)
a = r.get("audio") or {}
- if not STATE["dry_run"]:
+ if not STATE.dry_run:
if r.get("video"):
die(f"{output} unexpectedly contains a video stream")
if a.get("sample_rate") != rate or a.get("channels") != channels:
@@ -137,7 +137,7 @@ def main() -> int:
durs = [m.get("duration") or 0.0 for m in metas]
d = args.duration if args.transition != "none" else 0.0
for p, dur in zip(args.inputs, durs):
- if d and dur <= d * 2 and not STATE["dry_run"]:
+ if d and dur <= d * 2 and not STATE.dry_run:
die(f"{p} is only {dur:.2f}s, too short for a {d:.2f}s transition; shorten --duration")
cmd = ffmpeg_base()
diff --git a/scripts/loudness.py b/scripts/loudness.py
index 80f50fb..94ff866 100755
--- a/scripts/loudness.py
+++ b/scripts/loudness.py
@@ -23,7 +23,7 @@ from _common import STATE, add_common, apply_common, emit, AUDIO_CODECS, audio_c
def measure(path: str, I: float, tp: float, lra: float) -> dict:
- if STATE["dry_run"]:
+ if STATE.dry_run:
return {"input_i": "-20.0", "input_tp": "-3.0", "input_lra": "8.0", "input_thresh": "-30.0", "target_offset": "0.0", "silent": False}
ffmpeg = require_tool("ffmpeg")
cmd = [ffmpeg, "-hide_banner", "-nostdin", "-i", path, "-vn", "-af", f"loudnorm=I={I}:TP={tp}:LRA={lra}:print_format=json", "-f", "null", "-"]
diff --git a/scripts/metadata.py b/scripts/metadata.py
index fa55de9..19ca1f9 100755
--- a/scripts/metadata.py
+++ b/scripts/metadata.py
@@ -136,9 +136,9 @@ def main() -> int:
result = probe(output, role="output")
written = result.get("chapters") or []
- if chapters is not None and not STATE["dry_run"] and len(written) != len(chapters):
+ if chapters is not None and not STATE.dry_run and len(written) != len(chapters):
die(f"wrote {len(written)} chapters but {len(chapters)} were asked for", kind="output")
- if args.clear_chapters and not STATE["dry_run"] and written:
+ if args.clear_chapters and not STATE.dry_run and written:
die(f"{len(written)} chapters survived --clear-chapters", kind="output")
info(f"wrote {output} ({len(written)} chapters, tags: {', '.join(sorted(tags)) or 'unchanged'}, streams copied)")
emit(output, chapters=written, tags=result.get("tags") or {}, streams_copied=True)
diff --git a/scripts/render.py b/scripts/render.py
index aeea2cd..b780a17 100755
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -85,7 +85,7 @@ def sh(script: str, *argv: Any, extra: List[str] = None) -> str:
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for line in proc.stderr.splitlines():
if line.startswith("$ ") or line.startswith("[dry-run]"):
- STATE["commands"].append(line[2:] if line.startswith("$ ") else line)
+ STATE.commands.append(line[2:] if line.startswith("$ ") else line)
elif line.strip():
info(" " + line)
try:
@@ -152,7 +152,7 @@ def main() -> int:
parts: List[str] = []
for i, c in enumerate(clips):
src = rel(c["src"])
- if not STATE["dry_run"]:
+ if not STATE.dry_run:
probe(src)
needs_cut = c.get("in") is not None or c.get("out") is not None
part = str(work / f"clip{i:02d}.mp4")
@@ -167,7 +167,7 @@ def main() -> int:
part = src
if c.get("speed"):
spd = float(c["speed"])
- dur = (probe(part).get("duration") or 0.0) if not STATE["dry_run"] else 10.0
+ dur = (probe(part).get("duration") or 0.0) if not STATE.dry_run else 10.0
fitted = str(work / f"clip{i:02d}_speed.mp4")
sh("fit.py", part, "--duration", f"{dur / spd:.3f}", "-o", fitted)
part = fitted
@@ -348,7 +348,7 @@ def main() -> int:
sh("export.py", *argv)
stages_done.append("export")
else:
- if not STATE["dry_run"]:
+ if not STATE.dry_run:
import shutil
shutil.copyfile(current, output)
info(f"copied final stage to {output}")
@@ -358,7 +358,7 @@ def main() -> int:
ck = proj.get("check")
check_result = None
exit_code = 0
- if ck and ck.get("platform") and not STATE["dry_run"]:
+ if ck and ck.get("platform") and not STATE.dry_run:
proc = subprocess.run([sys.executable, str(HERE / "check.py"), output, "--platform", ck["platform"], "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
check_result = json.loads(proc.stdout)
diff --git a/scripts/stabilize.py b/scripts/stabilize.py
index 4fbbc9d..03b2596 100644
--- a/scripts/stabilize.py
+++ b/scripts/stabilize.py
@@ -62,7 +62,7 @@ def main() -> int:
trf = str(Path(tmp) / "transforms.trf")
trf_arg = escape_filter_path(trf)
- if not STATE["dry_run"]:
+ if not STATE.dry_run:
ffmpeg = require_tool("ffmpeg")
detect_vf = f"vidstabdetect=shakiness={args.shakiness}:result={trf_arg}"
if args.tripod:
diff --git a/tests/test_all.py b/tests/test_all.py
index 95dd6d7..23923d0 100644
--- a/tests/test_all.py
+++ b/tests/test_all.py
@@ -2832,17 +2832,20 @@ class FFmpegSkillTests(unittest.TestCase):
self.assertNotIn("\nwrote ", proc.stderr, "dry-run must not claim a file was written")
# ---------------------------------------------------------------- _common
- def test_context_attribute_and_mapping_access_agree(self):
+ def test_context_is_attribute_only_and_resets(self):
+ """Context once carried dict-style shims for older call sites; every site uses attributes
+ now and the shims are gone, so a stray STATE["x"] is a TypeError at the call site rather
+ than a second, silently-diverging access path. __slots__ also refuses unknown names."""
from _common import Context
ctx = Context()
- ctx["dry_run"] = True
- self.assertTrue(ctx.dry_run)
+ ctx.dry_run = True
ctx.fast = True
- self.assertTrue(ctx["fast"])
- self.assertIsNone(ctx.get("duration_hint"))
- self.assertIsNone(ctx.get("nonexistent"))
- with self.assertRaises(KeyError):
- ctx["nonexistent"] = 1
+ self.assertTrue(ctx.dry_run and ctx.fast)
+ self.assertIsNone(ctx.duration_hint)
+ with self.assertRaises(TypeError):
+ ctx["dry_run"] # noqa: B018 -- the mapping shim is gone on purpose
+ with self.assertRaises(AttributeError):
+ ctx.nonexistent = 1
ctx.commands.append("x")
ctx.reset()
self.assertEqual((ctx.dry_run, ctx.fast, ctx.commands), (False, False, []))
diff --git a/tests/test_contract.py b/tests/test_contract.py
index 713781b..c795b7f 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -410,11 +410,11 @@ class ContractTests(unittest.TestCase):
reporting the honest "not measured" 0/0/0.0 instead of a fabricated 1920x1080/30fps that
looked like a real computed preview in a tool's human-readable dry-run summary line."""
import _common
- _common.STATE["dry_run"] = True
+ _common.STATE.dry_run = True
try:
meta = _common.probe(str(self.out("does_not_exist_and_never_will.mp4")))
finally:
- _common.STATE["dry_run"] = False
+ _common.STATE.dry_run = False
self.assertEqual(meta["video"]["width"], 0)
self.assertEqual(meta["video"]["height"], 0)
self.assertEqual(meta["video"]["fps"], 0.0)