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: 1.17.1 — fit-size reachable from templates, SKILL.md routes the 1.17 features, UTF-8 child output (#234) (#237)
claude[bot]9848f372eb09
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5c0502f..4d4474a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,47 @@## Unreleased-(nothing yet)+### Fixed++- **The caption size is fitted on the template path too.** `render.py --template NAME` fills the+ caption `size` from the delivery table and forwarded it as an explicit `--size`, which is how+ `caption.py` is told "a human chose this size" — so `--fit-size auto` never ran and a long cue+ was split across two consecutive cues on every template run (eval 18 cw1/dl1/dl3/dl4), the one+ path a "make this a TikTok" request takes. A template's filled project now states+ `"fit_size": "on"`; a template file that states its own `fit_size`, and a brand file that+ actually states `caption.size`, still win — `--brand` on its own is not a stated size, so a+ brand of colours or a font keeps the fit — and `"fit_size": "off"` reproduces 1.17.0's captions+ byte for byte.+- **`render.py` project captions accept `fit_size`, `min_size` and `fit_size_scope`** (eval 18+ cs1: the keys were refused as unknown, so the fit policy could not be stated in a project at+ all and the four stages had to be run by hand). `render.py`'s result also carries the caption+ stage's own block as `caption`.+- **SKILL.md routes the 1.17 features.** Filler words → `silence.py --filler --words`, cutting to+ the music → `scenes.py --beats` then `cut.py --snap beats`, a folder and the cores →+ `batch.py --jobs auto`, one stage changed → `render.py --cache DIR`. None of them appeared in+ the routing table, so runs rebuilt them by hand or reported the feature does not exist (eval 18+ bt2/fw1/fw3/rc1). Paid for with duplicated wording elsewhere: the file is still under the+ 30,000-byte budget.+- **One label for a partial result.** SKILL.md now states it: a partial result is `Done:` with the+ shortfall in `Notes:`, never a third label like `Done (partially):`.+- **`caption.py` says when the text is unchanged**: `caption text unchanged` in the summary and+ `text_unchanged: true` in the result when the drawn text equals the cues that were handed in —+ nothing transcribed, no cue dropped, no cue split across two cues and no glyph stripped by+ `--emoji none`. Wrapping, line breaks and timing do not count as a change; the key is burn mode+ only (`--mode mux` never touches the text and omits it).+- **#234: child-process output is decoded as UTF-8, never as the machine's code page.** On a+ Windows cp932 locale `text=True` decoded ffprobe's UTF-8 JSON with the console code page, the+ reader thread raised `UnicodeDecodeError`, `communicate()` returned an empty stdout and+ `probe.py` printed `?s | no video | no audio` and exited 0 — an unmeasured file reported as+ measured. Every child capture in `scripts/` (ffmpeg, ffprobe, fc-list/fc-match, whisper, the+ sibling tools render.py and batch.py run) now passes `encoding="utf-8", errors="replace"` --+ including `run_analysis()`, the capture every ffmpeg *measurement* goes through, and the two+ captures in `evals/` -- and+ a probe whose ffprobe printed nothing refuses with `kind: input` naming the unreadable output+ instead of returning a document of nulls.+- **evals**: `write_fixtures.py` stages a batch recipe's `output_dir` absolute under the prompt's+ own directory — a relative `"out"` resolved against the caller's cwd, so the staged recipe wrote+ outside the prompt folder and had to be rewritten before the prompt could be answered.## 1.17.0diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 7da0010..3066f88 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -85,6 +85,9 @@ would have caught the original bug isn't done yet.asserts it. The only exception is a tool whose entire output is a table, a JSONdocument or an HTML file: add it to `INSPECTION` in `demos/build.py` instead andit gets a command and a sentence in the gallery's Inspection section.+- A release PR moves `docs/roadmap.md`'s "the released version today is ..." line in the **same+ PR as the version bump**, so the roadmap never describes a version that is already out as+ planned.## Reporting issuesdiff --git a/README.md b/README.mdindex 8d1e6e2..41a5bc7 100644--- a/README.md+++ b/README.md@@ -117,7 +117,11 @@ python3 $S/render.py talk.mp4 --template tiktok --cues cues.txtThat fills the shipped `templates/tiktok.json`: 9:16 crop, captions popped word by word *above*TikTok's description bar and clear of its like column, −14 LUFS, the `tiktok` export preset, and-a `check.py --platform tiktok` on the file it wrote. Templates ship for `tiktok`, `reels`,+a `check.py --platform tiktok` on the file it wrote. The caption size comes from the delivery+table, so since 1.17.1 the filled project also states `"fit_size": "on"`: a size nobody asked for+shrinks to fit the cue instead of splitting the sentence across two cues. A template that states+its own `fit_size`, and a `--brand` that states a caption size, still win, and a project with+`"fit_size": "off"` renders the captions 1.17.0 rendered. Templates ship for `tiktok`, `reels`,`shorts`, `youtube-shorts`, `youtube`, `x`, `linkedin`, `facebook` and `podcast`;`--template all` (or a comma-separated list) renders every destination from the same edit andwrites a `<name>_pack.md` table of what each one produced. Files land next to the input unless@@ -179,7 +183,8 @@ These are the rules the skill file gives the agent and the code enforces.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.7. **Unknown is not missing.** When a listing cannot be read (a layout the parser does not know, ffmpeg exiting non-zero) the affected capabilities are `unknown`: never `missing`, never silently `available`. An installed filter is not reported absent; a failed detection is not a pass.8. **Verify the result.** The output is probed, and when the picture changed (captions, overlays, crops, colour, transitions) the agent runs `look.py` and inspects the PNG. The report is not finished until its `Look:` line names that image; audio-only jobs say `Look: not needed`. **"Inspects" means the calling agent's own vision, not a feature of this skill:** `look.py` only renders a PNG; nothing in this repository detects faces, products, subjects, or "the interesting part" of a frame or a scene. When a crop or reframe needs to keep a specific part of the frame (`fit.py --fit crop --crop-x/-y`, see [Tools](#tools)), it is the multimodal agent looking at that PNG and choosing the anchor — a non-visual caller (a script, a CLI user without eyes on the sheet) has to supply that decision itself, and the default is a plain centre crop. Likewise `scenes.py --highlights` ranks candidate scenes by a measured proxy (`--rank-by audio` or `--rank-by duration`), never by content; it is the agent that turns a look at the sheet into a judgement.-9. **Keep originals.** No tool overwrites its input. Outputs are new files named `<input>_<operation>.<ext>` unless told otherwise, and a test hashes every input after the run.+9. **One label per report.** A finished job is `Done:`, a failure or a refusal is `Failed:`, and a partial result is `Done:` with the shortfall named in `Notes:` — never a third label such as `Done (partially):`.+10. **Keep originals.** No tool overwrites its input. Outputs are new files named `<input>_<operation>.<ext>` unless told otherwise, and a test hashes every input after the run.## Tools@@ -234,7 +239,7 @@ These are the rules the skill file gives the agent and the code enforces.| Tool | What it does ||---|---|-| `caption.py` | Burn SRT/ASS with font, size, colour, outline, position; build SRT from timed plain text; wraps to the safe area with a phrase-aware breaker (`--wrap phrase|measured`) and `--max-lines`/`--min-duration`/`--offset`; `--mode mux` takes a repeated `--srt file:lang` for several language-tagged, toggleable tracks in one file; picks a font by script for non-Latin text (`--lang`); animated and word-by-word karaoke timed to the speech energy or real word timings; `--fit-size` shrinks the size until a cue fits `--max-lines` instead of splitting the sentence; optional local transcription |+| `caption.py` | Burn SRT/ASS with font, size, colour, outline, position; build SRT from timed plain text; wraps to the safe area with a phrase-aware breaker (`--wrap phrase|measured`) and `--max-lines`/`--min-duration`/`--offset`; `--mode mux` takes a repeated `--srt file:lang` for several language-tagged, toggleable tracks in one file; picks a font by script for non-Latin text (`--lang`); animated and word-by-word karaoke timed to the speech energy or real word timings; `--fit-size` shrinks the size until a cue fits `--max-lines` instead of splitting the sentence (on by default on the delivery-template path since 1.17.1, where the size comes from the platform table); says `caption text unchanged` when it burned the cues exactly as given; optional local transcription || `overlay.py` | Logos, watermarks and titles with position, time range, opacity, fades; `--platform NAME` keeps them clear of that destination's UI; `--video` for picture-in-picture, `--chromakey` for green-screen compositing || `graphics.py` | Lower-thirds, title cards, chapter chips, progress bars, countdowns, corner bugs, social stickers, opening hook cards and meme captions drawn by FFmpeg from a brand kit; `--platform NAME` keeps them inside that destination's safe zone; `--text-render` routes shaping scripts through libass and `--emoji-assets` composites colour emoji || `color.py` | HDR10 / HLG / Dolby Vision → SDR BT.709 tone mapping, DV layer stripping, 3D LUT (.cube), colour-tag rewriting, typed primary correction (exposure/contrast/saturation/gamma/white balance/lift-gain/levels/curves) |@@ -252,7 +257,7 @@ These are the rules the skill file gives the agent and the code enforces.| Tool | What it does ||---|---|-| `render.py` | Render a whole edit from a declarative `project.json` (clips, transitions, captions, overlays including the social sticker/hook/meme graphics, music and stem levels, loudness, export, chapter markers, check); `--init`, `--dry-run`, `--stop-after`, `--cache DIR`/`--from STAGE` (reuse the stages that did not change); `--template NAME INPUT` renders a shipped delivery template (`--template all` writes the whole social pack plus its table) |+| `render.py` | Render a whole edit from a declarative `project.json` (clips, transitions, captions, overlays including the social sticker/hook/meme graphics, music and stem levels, loudness, export, chapter markers, check); `--init`, `--dry-run`, `--stop-after`, `--cache DIR`/`--from STAGE` (reuse the stages that did not change); the captions block takes the fit-size policy (`fit_size`, `min_size`, `fit_size_scope`) and the run reports the caption stage's counts as `caption`; `--template NAME INPUT` renders a shipped delivery template (`--template all` writes the whole social pack plus its table) || `batch.py` | Apply a step recipe or a project to a folder with a content-hash cache; `--watch`; `--jobs N` processes several files at once under one shared `--timeout` || `multicam.py` | Align any number of cameras and recorders by audio (with drift correction) and cut between them from a switch list || `verify.py` | Run the toolchain on real device files and report PASS / FAIL per step |@@ -362,7 +367,7 @@ The short list for humans. The agent-facing version, with the reasoning, is the- **Frame changes first, text second.** Captions and overlays burned before a crop or resize end up off-frame. Reframe, then caption.- **Cropping 16:9 to 9:16 discards 70 % of the width.** `fit.py --fit crop` centres by default; pass `--crop-x`/`--crop-y` toward the subject, or pad with `--fit pad --pad-fill blur`. Look at the contact sheet before deciding.- **Phrase-aware caption breaking (1.16).** `caption.py`/`graphics.py --wrap phrase` (the default) never breaks inside a word or on the wrong side of a hyphen, never leaves a lone digit, kana or punctuation pair on a line, prefers Japanese sentence ends and particles over a mid-word break, and never ends a line on an article or preposition. All four are penalties over break positions that already fit, so no line is widened and the line count never changes; `--wrap measured` restores 1.15's width-only wrap. The text itself is never rewritten or shortened. Since 1.16.1 a Thai run and a katakana word are never broken inside (Thai writes no space inside a phrase and there is no dictionary: the break goes where you put a space or `|`), and a line wider than the safe width is reported as `overlong` with the fix named.-- **Caption size fitted to the cue (1.17).** At a platform caption size a line holds about six em, so an ordinary sentence needs four lines and `--max-lines 2` used to cut it into consecutive cues — half the sentence arriving late. `caption.py --fit-size` (default `auto`) now walks the size down until every cue fits, *before* laying the cues out, with a legibility floor of 4.5 % of the frame height (`--min-size`, default 13 ASS units). `--fit-size off` is 1.16 byte for byte, an explicit `--size` or a `brand.json` size is never overridden, and the caption text is still never rewritten to make it fit.+- **Caption size fitted to the cue (1.17, reachable from the templates since 1.17.1).** At a platform caption size a line holds about six em, so an ordinary sentence needs four lines and `--max-lines 2` used to cut it into consecutive cues — half the sentence arriving late. `caption.py --fit-size` (default `auto`) walks the size down until every cue fits, *before* laying the cues out, with a legibility floor of 4.5 % of the frame height (`--min-size`, default 13 ASS units). An explicit `--size` or a `brand.json` size is a statement about the look and is never overridden — which in 1.17.0 also silenced the fitter on every `render.py --template` run, since a template fills the size from the platform table; 1.17.1 marks that size as the default it is (`"fit_size": "on"` in the filled project), so the type shrinks and no cue is split. `--fit-size off` restores that earlier behaviour byte for byte, and the caption text is still never rewritten to make it fit.- **Beat-synced cuts (1.17).** `scenes.py --beats` reports the measured grid — tempo, beat times, and a confidence built from how far the winning autocorrelation lag stands above the others and how many onsets land on it. `cut.py --snap beats` (and a `"snap"` block in a `render.py` project) moves in/out points to the nearest beat within `--snap-tolerance` — and only onto the grid points a measured onset actually marks, never onto the regular grid's continuation through a passage with no music in it. Below `--min-confidence` it **refuses**: a cut point may move to a measured beat and may not appear from one, so speech and ambience get an honest "no steady pulse here" instead of an invented grid.- **Filler words (1.17).** `silence.py --filler --words transcript.json` removes "um" and "uh" through the same cut graph the silences use. Never without measured word timings — there is no heuristic that finds an "um" without them that would not also cut real speech — and `like`, `tipo` and `cioè` are deliberately not in the built-in lists, because a discourse marker is a content word. Whisper stays optional: `--transcribe` with no engine installed refuses and names the three installs.- **Throughput (1.17).** `batch.py --jobs N` runs several files at once, capped at `min(N, cpu_count, 8)` and sharing one `--timeout` budget rather than one per item; the per-item table keeps its order. `render.py --cache DIR` reuses stages whose inputs and arguments did not change, so swapping an export preset re-runs export only. The cache is opt-in with no default directory, and the ffmpeg, skill and contract versions are part of every key, so a cache is never reused across them.diff --git a/SKILL.md b/SKILL.mdindex 86c2cd3..4d0fa0c 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`, and delivery templates in `templates/`. This file is enough to do a job: the table below routes the request and `--help` on the one script you are about to run is the cheapest full flag list. The reference files cost as much to read as this file does, so open one only when it answers a question you actually have: `references/scripts.md` (every flag of all 42 scripts), `references/devices.md` (iPhone HDR, GoPro, DJI, screen recordings, Zoom), `references/gotchas.md` (the long form of the one-line rules at the end).+Scripts live in `scripts/` next to this file; run them with `python3 <skill-dir>/scripts/<name>.py`, and delivery templates in `templates/`. This file is enough to do a job: the table below routes the request, and `--help` on the script you are about to run is the cheapest full flag list. A reference file costs as much to read as this file, so open one only when it answers a question you have: `references/scripts.md` (every flag of all 42 scripts), `references/devices.md` (iPhone HDR, GoPro, DJI, screen recordings, Zoom), `references/gotchas.md` (the long form of the one-line rules at the end).Shared flags, on every script: `--dry-run`; `--json` (output path, a probe of the output, the commands run); `--json-brief` (the same trimmed to status/output/verified plus a `summary` — prefer it on writing steps); `--fast` (preview quality); `--progress`; `--timeout SECONDS` (`kind: timeout`, default 1800); `--overwrite` (step 7); `--plan FILE` (the dry run as a plan `render.py FILE` runs later, refusing if an input changed). Every re-encoding tool also takes `--codec h264|hevc|av1|prores` and `--quality N` (CRF scale, replaces the deprecated `--crf`): unset, SDR is x264 and HDR is x265 Main10; `prores` needs an explicit `-o NAME.mov`, `h264` refuses an HDR source (`color.py --to-sdr` first).@@ -13,11 +13,11 @@ Writing tools run nothing under `--dry-run`; the measuring tools (`probe`, `chec## Workflow (always follow this order)-0. **Environment, only on failure.** Never start a job with `doctor`: a broken machine fails on its own with `kind: missing_tool` or an ffmpeg error naming the filter/encoder (`No such filter: 'subtitles'`). Run `python3 <skill-dir>/scripts/_contract.py doctor` (also `npx ffmpeg-skill doctor`) after such a failure, or when the user asks what the machine can do: read `ok` and the tool's `usable`, and report the missing capability (usually `libass`, `zscale` or an encoder) rather than rediscovering it at runtime. `contract --json`'s tool schema is for a *planning* agent choosing a tool from an abstract goal, not for this workflow.+0. **Environment, only on failure.** Never start a job with `doctor`: a broken machine fails on its own with `kind: missing_tool` or an ffmpeg error naming the filter/encoder (`No such filter: 'subtitles'`). Run `python3 <skill-dir>/scripts/_contract.py doctor` (or `npx ffmpeg-skill doctor`) after such a failure, or when asked what the machine can do: read `ok` and the tool's `usable`, and report the missing capability (usually `libass`, `zscale` or an encoder). `contract --json`'s tool schema is for a *planning* agent, not this workflow.1. **Probe what you must plan from.** Run `probe.py` on each input you plan the edit from — duration, fps, resolution, codecs, channels, `variable_frame_rate_suspected` — and whenever the user asks about a file. No separate probe before every edit: every writing tool's `--json` already carries its input and a probe of the output. Plan from real numbers, never assumptions.2. **Prefer lossless.** If the request can be met without re-encoding (plain cuts on keyframes, remuxing, audio-only changes), do not re-encode. `cut.py` and `loudness.py` stream-copy video by default; `--accurate` on `cut.py` only for frame-exact cuts.3. **Plan with `--dry-run --json`, then execute.** Trust `--json`, not a dry run's summary line, for any number in the plan (dimensions there can be a placeholder — `docs/contract.md`). Use it before long encodes and to report exact facts. `--fast` is preview quality (x264 veryfast), `--progress` prints percent/ETA on stderr. Never point `-o` at a file you did not create in this job unless the user asked for it to be replaced; pass `--overwrite` only then.-4. **Chain in a sensible order.** A delivery request with no other editing ("make this a TikTok") is one template run — `render.py --template NAME INPUT`, not a hand-built chain. Otherwise: colour (HDR→SDR / LUT) → cut → join → silence → fit → caption/overlay → sync → audio → loudness → export. Frame changes before captions and overlays, so text is sized for the final frame. Re-encode as few times as possible: intermediates at CRF 18, `export.py` only last. **Three or more steps: `render.py` with a project.json** — one call, one JSON, one place for the user to change a number.+4. **Chain in a sensible order.** A delivery request with no other editing is one template run (`render.py --template NAME INPUT`), not a hand-built chain. Otherwise: colour (HDR→SDR / LUT) → cut → join → silence → fit → caption/overlay → sync → audio → loudness → export. Frame changes before captions and overlays, so text is sized for the final frame. Re-encode as few times as possible: intermediates at CRF 18, `export.py` only last. **Three or more steps: `render.py` with a project.json** — one call, one JSON, one number for the user to change.5. **Check the deliverable.** Before reporting, run `check.py OUTPUT --platform X` for the destination the user named (a template run already does). Format rows (codec, pixel format, size, true peak, colour tags, VFR) are safe to fix mechanically. Judgement rows change the content: duration (cut loses material), aspect (crop loses edges), fps (drops motion), loudness (ambience must not be boosted) — fix those only when the request implies the answer, otherwise state the choice and its cost in one line. Mention WARNs; do not chase them.6. **Verify the output.** Confirm duration, resolution, fps and audio match the request — from the writing tool's own `--json`/`--json-brief` probe, or `probe.py` — and report those numbers ("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: a non-zero exit, a missing or empty file, or a probe that contradicts the request is a failure reported with the script's error message.7. **Keep the user's originals.** Never overwrite the source; write new files next to the input or where the user asked. Set `FFMPEG_SKILL_NO_OVERWRITE=1` in the environment you run these scripts in: an existing output path is then refused (`kind: input`) instead of warned about, with `--overwrite` the one way to say "yes, replace it". It is the recommended agent setting, and 2.0's default.@@ -98,29 +98,32 @@ Timestamp flags (`--start`, `--end`, `--at`, `--from`, `--duration`, `--offset`,| "a title for the first 4 seconds" | `overlay.py input.mp4 --text "Title" --position top --start 0 --end 4 --fade 0.4` || "webcam clip in the corner", "picture-in-picture" | `overlay.py input.mp4 --video webcam.mp4 --position bottom-right --scale 480` || "remove the green screen" | `overlay.py bg.mp4 --video greenscreen.mp4 --chromakey 0x00ff00` |-| "turn this podcast into a video", "audiogram" | `render.py --template audiogram ep.m4a --image cover.png` — waveform over a still or colour plate; give an image or a colour, nothing is fetched |+| "turn this podcast into a video", "audiogram" | `render.py --template audiogram ep.m4a --image cover.png` — waveform over a still or colour plate; give an image or colour, nothing is fetched || "sync the lav mic", "line up two cameras" | `sync.py camera.mp4 mic.wav --replace-audio` / `sync.py camA.mp4 camB.mp4 --trim-second` || "fix the audio levels", "normalise to -14 LUFS" | `loudness.py input.mp4` (`-I -16 --tp -1.5` podcast, `-I -23` broadcast; `--lra N` for the range) || "cut this and make it HEVC / AV1 / ProRes" (output codec named) | `cut.py input.mp4 --start 0:10 --end 0:40 --codec hevc` (`--codec`/`--quality` on any re-encoding tool; ProRes needs `-o NAME.mov`) |-| "make this a TikTok / Reel / Short / YouTube / X / LinkedIn / podcast" | `render.py --template tiktok\|reels\|shorts\|youtube-shorts\|youtube\|x\|linkedin\|facebook\|podcast input.mp4 [--cues cues.txt\|--srt subs.srt] [--title "..."] [--logo logo.png] [--brand brand.json]` — frame, captions inside the safe area, loudness, export and that platform's check in one command (`--list-templates`, `--write-project` to edit first) |-| "post it everywhere", "one edit for every platform" | `render.py --template all input.mp4 --cues cues.txt` (or a comma list) → one file per destination plus `<name>_pack.md`; `report.py --pack <name>_pack.md` for the HTML |+| "make this a TikTok / Reel / Short / YouTube / X / LinkedIn / podcast" | `render.py --template tiktok\|reels\|shorts\|youtube-shorts\|youtube\|x\|linkedin\|facebook\|podcast input.mp4 [--cues cues.txt\|--srt subs.srt] [--title "..."] [--logo logo.png] [--brand brand.json]` — frame, captions in the safe area, loudness, export and that platform's check in one command (`--list-templates`, `--write-project` to edit first) |+| "post it everywhere", "one edit for every platform" | `render.py --template all input.mp4 --cues cues.txt` (or a comma list) → one file per destination plus `<name>_pack.md` (`report.py --pack` renders the HTML) || "export for YouTube / Reels / X", "a ProRes master" | `export.py input.mp4 --preset youtube\|reels\|tiktok\|shorts\|linkedin\|facebook\|x\|prores\|h265` (`--normalize` hits the loudness spec in the same call; `youtube-hdr` keeps HDR, `youtube-av1` writes AV1) || "make a GIF preview" | `export.py input.mp4 --preset gif` |-| "a small proxy / cheap preview file" | `proxy.py input.mp4 [--width 640 --no-audio]` — not a delivery preset (those are `export.py`) |+| "a small proxy / cheap preview file" | `proxy.py input.mp4 [--width 640 --no-audio]` — not a delivery preset (that is `export.py`) || "cut out the pauses", "jump cuts" | `silence.py input.mp4 [--threshold -40 --min-silence 0.8]` |+| "cut the ums and uhs", "remove the filler words" | `silence.py input.mp4 --filler --words words.json` (measured word timings; `--transcribe` makes them) || "stitch these clips", "add a crossfade" | `join.py a.mp4 b.mp4 c.mp4 --transition fade --duration 0.5` |-| "show me what it looks like", "are the captions readable" | `look.py output.mp4 --tiles 3x2` then view the PNG |+| "show me what it looks like", "are the captions readable" | `look.py output.mp4 --tiles 3x2`, then view the PNG || "what would you run?", "don't render yet" | any script with `--dry-run` || "a 60 s highlight from this hour" | `scenes.py long.mp4 --highlights 6 --target 60 --edl picks.txt` → `cut.py --segments` |+| "cut on the beat", "edit it to the music" | `scenes.py track.mp4 --beats --json > beats.json`, then `cut.py input.mp4 --segments ... --snap beats --snap-source beats.json` (`--snap-source` carries the measured grid over) || "is this OK to upload?" | `check.py final.mp4 --platform reels` || "a podcast episode with chapters" | `loudness.py ep.wav -I -16 --tp -1.5` → `metadata.py ep.m4a --chapters chapters.txt` → `check.py ep.m4a --platform podcast` (chapters and channels rows) || "several changes to the same edit", 3+ steps | `render.py --init project.json`, edit, `render.py project.json` |+| "I changed one stage, don't redo the rest" | `render.py project.json --cache DIR` — identical stages come from the cache (`--from STAGE` starts there) || "a lower third with my name", "countdown intro", "progress bar" | `graphics.py input.mp4 --template lower-third --name "..." --title "..." --start 2 --end 8` || "a sticker", "a hook card for the first 3 s", "meme text" | `graphics.py input.mp4 --template sticker --text "NEW" --platform tiktok` / `--template hook --title "..." --duration 3` / `--template meme --top "..." --bottom "..."` |-| "blurred background instead of black bars" | `fit.py input.mp4 --aspect 9:16 --fit blur` (whole picture kept, borders are a blurred, darkened copy) |+| "blurred background instead of black bars" | `fit.py input.mp4 --aspect 9:16 --fit blur` (whole picture kept, borders a blurred, darkened copy) || "use our brand fonts/colours/logo" | `--brand brand.json` on caption/overlay/graphics, or `"brand"` in project.json || "send me a summary of what you did" | `report.py --before raw.mov --after final.mp4 --platform youtube -o report.html` |-| "do this to every file in the folder" | `batch.py FOLDER --recipe batch.json` (steps or a render project; cached) |+| "do this to every file in the folder", "use all the cores" | `batch.py FOLDER --recipe batch.json --jobs auto` (steps or a render project; cached) || "transcribe it and caption it" | `caption.py input.mp4 --transcribe --animate pop --karaoke` (needs a local whisper; else `--text`) || "three cameras, cut between them" | `multicam.py camA.mp4 camB.mp4 camC.mp4 --switch "0-20:0,20-40:1,40-60:2"` || "iPhone Dolby Vision clip looks wrong" | `color.py clip.mov --to-sdr` or `--strip-dovi` (keep HDR, drop the DV layer) |@@ -146,12 +149,12 @@ Timestamp flags (`--start`, `--end`, `--at`, `--from`, `--duration`, `--offset`,## Audio-only files-Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`, `audio.py`, `sync.py`, `check.py --platform podcast` and `render.py --template podcast` take WAV, FLAC, MP3, M4A/AAC, OGG and Opus, and the output extension picks the format. `Look: not needed` in the report; `Check:` still applies. Scripts that need a picture (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" — say so instead of forcing a video wrapper. Audio recipes, packet vs sample precision, joining and extracting one track: `references/gotchas.md#audio-only-files`.+Audio is a first-class input: `probe.py`, `cut.py`, `silence.py`, `loudness.py`, `audio.py`, `sync.py`, `check.py --platform podcast` and `render.py --template podcast` take WAV, FLAC, MP3, M4A/AAC, OGG and Opus; the output extension picks the format. `Check:` still applies. Scripts that need a picture (`fit`, `caption`, `overlay`, `graphics`, `color`, `export`, `scenes`, `look`) refuse an audio file with "input has no video stream" — say so, do not force a video wrapper. Audio recipes, packet vs sample precision, joining, extracting a track: `references/gotchas.md#audio-only-files`.## Report format-Reply in the language the request itself is written in — the user's own sentences, not a language the request talks about (a request for subtitles in another language is still answered in the language it was written in). Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read like log fields across languages. The *lines* they head are not: `Done:`, `Steps:` and `Check:` carry the user's language just as `Look:` and `Notes:` do — a Spanish prompt answered with English `Done:`/`Steps:` sentences is an English report. Everything around them — the sentences, any question, any explanation of a judgement call — is in the user's language. Never default to English because the tool names are English, and never drift because the job was short or the report is a failure: a one-line "file does not exist" is in the request's language too. A mid-conversation switch follows the user's latest message.+Reply in the language the request itself is written in — the user's own sentences, not a language the request merely talks about (subtitles in another language are still reported in the request's language). Keep the field labels (`Done:`, `Steps:`, `Check:`, `Look:`, `Notes:`) in English: they read as log fields in any language. Everything else is the user's language — the lines those labels head, any question, any judgement call explained. Never drift because the job was short or the report is a failure: even a one-line "file does not exist". A mid-conversation switch follows the user's latest message.Finish every job with this shape (numbers from `--json` or `probe.py`/`check.py`, not memory):@@ -185,7 +188,10 @@ Look: not neededNotes: send a valid .cube, or say if you want the clip left as is```-A refusal (a judgement this skill does not make, or something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run, `Look: not needed`. The shortest failure still gets all five labels, never prose headings. A refusal that still delivers something is `Failed:`, never a third label like `Done (partially):` — the label answers the request as asked; the alternative goes in `Notes:`. When a failure JSON carries `error.hint`, quote it in `Notes:`: it is the flag change that makes a retry meaningful.+Those filler lines are sentences, not labels: the same report for a Japanese request ends+`Check: 検証するものなし` / `Look: 不要`.++A refusal (a judgement this skill does not make, or something outside its scope) uses the same shape: `Failed:` names what was refused and why, `Steps:` lists what did run, `Look: not needed`. The shortest failure gets all five labels, never prose headings. A partial result is `Done:` with the shortfall in `Notes:`, and a refusal that still delivers something is `Failed:` — never a third label like `Done (partially):`. When a failure JSON carries `error.hint`, quote it in `Notes:`: it is the flag change that makes a retry meaningful.Every script prints `{"status": "failed", "error": {"kind": input | ffmpeg | output | missing_tool | timeout | verification | interrupted, "message": ...}}` with `--json` and exits non-zero; quote the message, never paraphrase it.@@ -201,10 +207,9 @@ One line each; open the linked `references/gotchas.md` section when the job is i- "Normalised" audio can still clip (check true peak), and ambience at -40 LUFS or below must never be raised to a speech target. Details: [#loudness-and-ambience](references/gotchas.md#loudness-and-ambience)- Captions burned before a crop/resize land off-frame, and burned small then upscaled by `export.py` they come out soft. Details: [#captions-fonts-and-text-order](references/gotchas.md#captions-fonts-and-text-order)- Emoji need `--emoji-assets DIR` (a PNG per glyph) to render in colour; without it they come out monochrome and the run says so. Details: [#emoji](references/gotchas.md#emoji)-- `graphics.py` renders Devanagari, Bengali, Tamil and Thai through libass automatically — drawtext cannot shape them.-- Non-Latin text picks a font by script since 1.12; `doctor --json` `fonts.scripts` says which languages this machine renders; no font = failed job. Details: [#fonts-by-script](references/gotchas.md#fonts-by-script)-- `--fit crop` 16:9 → 9:16 throws away 70 % of the width, 60→30 fps halves the motion, and "60 seconds" by speed or by trim are different answers — say which and why. Details: [#reframing-fps-and-duration](references/gotchas.md#reframing-fps-and-duration)-- TikTok/Reels cover the bottom fifth and the right column with their own UI — templates keep text out of those zones; `look.py --safe tiktok` shows them. Details: [#platform-safe-zones](references/gotchas.md#platform-safe-zones)+- Non-Latin text picks a font by script (`graphics.py` shapes Devanagari, Bengali, Tamil and Thai through libass; drawtext cannot); no font = failed job. Details: [#fonts-by-script](references/gotchas.md#fonts-by-script)- `yuv420p` needs even dimensions and phone rotation tags are honoured, both automatically. Details: [#dimensions-and-rotation](references/gotchas.md#dimensions-and-rotation)+- `--fit crop` 16:9 → 9:16 throws away 70 % of the width, and "60 seconds" by speed or by trim are different answers — say which and why. Details: [#reframing-fps-and-duration](references/gotchas.md#reframing-fps-and-duration)+- TikTok/Reels cover the bottom fifth and the right column with their own UI — templates keep text out of those zones; `look.py --safe tiktok` shows them. Details: [#platform-safe-zones](references/gotchas.md#platform-safe-zones)- `scenes.py --highlights` ranks by loudness (or duration), never by meaning: check the sheet before treating picks as final. Details: [#highlights](references/gotchas.md#highlights)-- Three hand-chained re-encodes should be one `render.py` project; re-encodes use x264 `medium`. Details: [#chaining-and-speed](references/gotchas.md#chaining-and-speed)+- Re-encodes use x264 `medium`; three chained ones belong in one `render.py` project. Details: [#chaining-and-speed](references/gotchas.md#chaining-and-speed)diff --git a/docs/contract.md b/docs/contract.mdindex 359480e..a73a89d 100644--- a/docs/contract.md+++ b/docs/contract.md@@ -450,6 +450,13 @@ Per-tool keys added in 1.17, all additive:| `jobs`, `jobs_requested`, `wall_seconds`, `item_seconds_total`, `timed_out` | `batch.py` | the parallelism actually applied and the number asked for, the batch's wall clock, the sum of the per-item times (so the speed-up can be quoted), and whether the shared timeout budget ran out. A timed-out item carries `"skipped": "timeout"` in its result row || `cache` | `render.py --cache` | `{dir, ffmpeg, hits, misses, saved_seconds, entries}`, plus `would_hit` under `--dry-run`. The ffmpeg build banner, the skill version, the contract version, the forwarded flags (`--fast`, `--codec`, …) and the output's extension are all part of every key, so a cache is never reused across any of them — a `--fast` draft is never served to a run that did not ask for one |+Per-tool keys added in 1.17.1, all additive:++| key | tool | what it holds |+|---|---|---|+| `caption` | `render.py` | the caption stage's own block, forwarded verbatim from `caption.py` (the cue-layout counts plus the fit-size keys above), so a template run can be read for `split` and `size_used` without re-running the stage. `null` when the project has no captions stage — and also when the captions stage came from the `--cache` (a cache hit carries no stage document, so a second `render.py … --cache DIR` run reports `caption: null` while `stages_done` still lists `captions`). `caption.py --mode mux` writes no `caption` block at all |+| `text_unchanged` | `caption.py` | a sibling inside the `caption` block, **burn mode only** (`--mode mux` never touches the text and omits the key): `true` when the drawn text equals the cues that were handed in — nothing transcribed, no cue dropped, no cue **split** across two consecutive cues and no glyph stripped (`--emoji none`). Wrapping, line breaks and timing do not count: the words are the same. This tool never rewrites, shortens or translates a cue, so the key is a statement of what happened, not a judgement of the text |+`check.py` also gains an informational `subtitles` row on **every** platform:`PASS` when every soft subtitle stream carries a language tag, `WARN` when onediff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex fd15d5c..637bd14 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -162,6 +162,51 @@ exists. When a decision changes, edit the entry in the same PR.change, hence major); tools that only call those keep working with a one-line change. Rejected:thread-locals (hides the dependency the reviews keep asking about). Code: `_common.Context`.+## External review, 2026-09-14 (1.17.0)++An outside review of the repository at 1.17.0, alongside eval 18. What it raised, and what was+decided. Recorded here so none of it is re-proposed from scratch.++- **P0-1 — run eval 18 before any further feature work.** Accepted, and **done before this+ patch**: eval 18 ran on 1.17.0 (100 prompts, independent grading) and its findings are what+ 1.17.1 fixes — the delivery templates never reached `--fit-size`, the project schema refused+ the fit keys, and SKILL.md routed none of the 1.17 features.+- **P0-2 — issue #234, `probe.py` reports `?s | no video | no audio` on a cp932 Windows box.**+ Accepted and **fixed in 1.17.1**: every child capture in `scripts/` passes+ `encoding="utf-8", errors="replace"` instead of decoding with the machine's code page, and a+ probe whose ffprobe printed nothing refuses (`kind: input`) rather than returning a document of+ nulls with exit 0. A source-level test keeps `text=True` without an encoding out of the tree.+- **P0-3 — the roadmap's "released version today" line lagged the bump.** Accepted; the checklist+ half landed in the eval-18 docs PR (`CONTRIBUTING.md`'s release checklist now says to move that+ line in the same PR as the version bump) but the line itself still read 1.16.0 against a+ `package.json` of 1.17.0 until review 17 caught it; **done in 1.17.1**.+- **P1-4 — `scripts/_common/text.py` is the next module too large to review in one pass.**+ Accepted, and deliberately **not mixed into 1.17.1**: it is a behaviour-free split, so it gets+ the same treatment `_common.py` got — its own no-change release after 1.17.1, with the contract+ snapshot, the MCP surface and every `--help` byte-identical.+- **P1-5 — reports copy the English boilerplate lines into non-English answers.** Accepted:+ SKILL.md's failure example now shows the Japanese rendering of `Check:`/`Look:`'s filler lines,+ so the rule ("these are sentences, not labels") has an example next to it.+- **P1-6 — eval prompt `ml2` tested a refusal, not the mux.** Accepted: `ml2` now ships a German+ SRT and a video and expects `caption|render`.+- **P1-7 — the 42-tool MCP `tools/list` is paid for by every session.** Accepted, and moved+ **ahead of the optical-flow work into 1.18.0**: the default listing becomes the core 12, the+ rest stay reachable through the contract, which still describes all 42.+- **P1-8 — at least one routing run on a non-Claude model.** Accepted as an `evals/run.py` task:+ the harness reads transcripts and files and is not Claude-specific; the routing/refusal set is+ what a Cursor or Codex run would publish.+- **P2-9 — issue #143 (real-device corpus) has no acceptance criteria.** Accepted as written in+ the issue: the corpus run is the criterion, one row per device family.+- **P2-10 — `--cache` has no failure-path tests.** Accepted and **closed in this patch**: the+ existing tests cover hit, miss, invalidation (stage args, ffmpeg build, skill and contract+ version, `--fast`, container) and the atomic cache write; what was missing — a failed stage+ must cache nothing and leave no work directory — is now a test.+- **P2-11 — no accuracy numbers for the beat grid and filler removal.** Accepted: those wait for+ eval-19 data rather than being asserted from the implementation.+- **P2-12 — reorganise SKILL.md's table by intent.** Accepted, and it **stays 1.20.0**: 1.17.1+ spends its byte budget on the missing routing rows, which is the same finding at a smaller+ scale.+## External review, 2026-09-13An outside review of the repository at 1.13.0 (eval 14). What it raised, and what was decided.diff --git a/docs/roadmap.md b/docs/roadmap.mdindex ebeb292..85945d5 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -21,7 +21,7 @@ The released version today is **1.17.0**, shipped and evaluated: **eval 18**(`evals/results/iteration-18.json`) graded it on the 100-prompt set, the 87 carried over plusthirteen written for the 1.17 features. It found the size fitter is unreachable on the templatepath and that SKILL.md routes none of the 1.17 features (see the 1.17.0 section); **1.17.1 below-is the patch and is planned**. Everything after 1.17.1 is planned.+is the patch and is planned for release** — implemented, not tagged yet. Everything after 1.17.1 is planned.| version | state | evidence ||---|---|---|@@ -37,7 +37,7 @@ is the patch and is planned**. Everything after 1.17.1 is planned.| 1.16.0 | shipped + evaluated | eval 17 at 1.16.0 (`iteration-17.json`); contract and MCP snapshots additive only; tool count still 42 || 1.16.1 | shipped + evaluated | caption-break patch from eval 17: a Thai run and a katakana word are never broken inside, `caption.py` reports `overlong` lines; eval 18 graded the tree that carries it and reported no wrapping defect || 1.17.0 | shipped, evaluated (eval 18) | eval 18 at 1.17.0 (`iteration-18.json`); tool count still 42; contract and MCP snapshots additive only. Two findings: `render.py` forwards the platform table's caption size as an explicit `--size`, so `--fit-size` never fires on the path every captioned prompt takes (and the project schema rejects `fit_size`), and SKILL.md names none of the 1.17 features, so beats, filler and `--cache` were each used in one run at most. 1.17.1 is the patch |-| 1.17.1 | planned | `render.py` forwards `--fit-size on` (or omits `--size`) when the size came from the platform table, and the project `captions` block accepts `fit_size`/`min_size`/`fit_size_scope`; SKILL.md routing lines for filler, beats, `batch.py --jobs` and `render.py --cache`; the cs2 disclosure line; eval 19 |+| 1.17.1 | planned | patch from eval 18: the template path fits the caption size, project captions take the fit keys, SKILL.md routes filler/beats/`--jobs`/`--cache`; tool count still 42, contract additive only; not tagged yet, eval 19 after the release || 1.18.0 → 1.21.0, 2.0.0 | planned | — |## 1.8.0 — one-call delivery, quieter checks, encoder flags (shipped + evaluated, eval 8)@@ -341,28 +341,26 @@ came out byte-identical, as did `--help` for all 42 tools.skill has no beat detection and cut at the literal timestamps, and two rebuilt filler removalby hand with `cut.py --segments` (leaving the output VFR). 1.17.1 is the patch.-## 1.17.1 — make 1.17 reachable (planned)--- **`render.py` forwards `--fit-size on`** — or simply omits `--size` — when the caption size came- from the platform table rather than from the user or the template author, with an e2e over the- `tiktok` template on the `cw1` cues asserting `split == 0` and `size_used < 24`.-- **The project `captions` block accepts `fit_size`, `min_size` and `fit_size_scope`**, so the- fitter is reachable declaratively and not only from a hand-run `caption.py`.-- **SKILL.md routing lines**, one each: filler / "ums and uhs" → `silence.py --filler --words`,- beat / "on the beat" → `cut.py --snap beats` and `scenes.py --beats`, a folder of files →- `batch.py --jobs`, "I only changed the preset" → `render.py --cache`. Paid for with cuts- elsewhere in the 30,000-byte budget; four of eval 18's six routing misses are pure- discoverability. With it, a line telling an agent to quote a measured low confidence rather- than deny the capability.-- **One report line for the `cs2` shape**: when the skill declines to change the user's text, the- report must say the text is unchanged, not merely leave it unchanged.-- **A sanctioned form for a partial result.** `Done (partially):` and `Failed (partially, …):`- are the only two format defects in eval 18's 100 runs and the only one in eval 17's 90; either- bless `Done:` with the shortfall named in `Notes:`, or the rule keeps losing to the truth.-- **Eval 19** re-runs the `cw`/`dl`/`cs`/`bt`/`fw`/`rc` prompts and checks that `size_used` and- `shrunk` appear on the template path, that the beat, filler and cache prompts route on the- first try, and that no third label appears. The `bp1`/`bp2` `batch.json` fixture (its- `output_dir` escapes OUTDIR) is fixed first.+## 1.17.1 — the eval-18 patch (implemented, not tagged yet, eval 19 pending)++- **Done. The template path fits the caption size.** 1.17.0's fitter was unreachable from+ `render.py --template`: the template fills the caption size from the delivery table and+ forwarded it as an explicit `--size`, which is the signal `caption.py` reads as "a human chose+ this", so `--fit-size auto` stood down and the cue was split instead (eval 18 cw1/dl1/dl3/dl4).+ The filled project states `"fit_size": "on"`; a template's own `fit_size` and a `--brand`+ caption size still win, and `"fit_size": "off"` is 1.17.0 byte for byte.+- **Done. Project captions take `fit_size`, `min_size`, `fit_size_scope`** (eval 18 cs1 could not+ state the policy in a project and hand-ran the four stages), and `render.py` reports the caption+ stage's block as `caption`.+- **Done. SKILL.md routes the 1.17 features** — filler, beats, `--jobs auto`, `--cache` — after+ eval 18 found none of them in the routing table (bt2 even reported the skill has no beat+ detection). Paid for with duplicated wording, inside the 30,000-byte budget.+- **Done. One label for a partial result**: `Done:` with the shortfall in `Notes:`.+- **Done. `caption.py` reports `text_unchanged`** and says "caption text unchanged" in its summary+ when it burned the cues exactly as given.+- **Done. Eval fixtures** stage a batch recipe's `output_dir` absolute (eval 18 bp1/bp2).+- **Eval 19** reruns cw1/cw2, dl1/dl3/dl4, cs1-3, bt1-3, fw1-3, bp1-2 and rc1-2 plus the trigger+ set; the full 100 waits for 1.18.0.## 1.18.0 — measured analysis and multicam at scale (still no judgement) (planned)diff --git a/evals/agent_prompts_24.json b/evals/agent_prompts_24.jsonindex 4a616a8..03aab52 100644--- a/evals/agent_prompts_24.json+++ b/evals/agent_prompts_24.json@@ -784,12 +784,14 @@{"id": "ml2","lang": "de",- "prompt": "Häng die deutschen Untertitel an /home/user/ffmpeg-skill/tests/out/source.mp4 dran — übersetz die englischen aus OUTDIR/en.srt einfach. Alles nach OUTDIR.",- "expect": [],- "refuse": true,- "note": "no translation engine (same rule as r04); the refusal is in German, labels included",+ "prompt": "Häng die deutschen Untertitel aus OUTDIR/de.srt an /home/user/ffmpeg-skill/tests/out/source.mp4 dran, als umschaltbare Spur. Alles nach OUTDIR.",+ "expect": [+ "caption|render"+ ],+ "refuse": false,+ "note": "the mux, not a translation: caption.py --mode mux --srt de.srt:de on the given video; the German subtitles are supplied, so nothing has to be translated (report in German)","fixtures": {- "en.srt": "1\n00:00:00,000 --> 00:00:03,000\nHello world\n"+ "de.srt": "1\n00:00:00,000 --> 00:00:03,000\nHallo Welt\n"}},{diff --git a/evals/contract/check.py b/evals/contract/check.pyindex ee1dd02..cfd3c90 100644--- a/evals/contract/check.py+++ b/evals/contract/check.py@@ -20,7 +20,7 @@ QUESTIONS = json.loads((HERE / "questions.json").read_text(encoding="utf-8"))def contract():- out = subprocess.run([sys.executable, str(ROOT / "scripts" / "_contract.py"), "--json", "--static"], stdout=subprocess.PIPE, text=True, check=True).stdout+ out = subprocess.run([sys.executable, str(ROOT / "scripts" / "_contract.py"), "--json", "--static"], stdout=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", check=True).stdoutreturn json.loads(out)diff --git a/evals/grade_runs_24.py b/evals/grade_runs_24.pyindex d410766..b39fa18 100644--- a/evals/grade_runs_24.py+++ b/evals/grade_runs_24.py@@ -125,7 +125,7 @@ def emoji_mode_here():mode = Nonetry:out = subprocess.run([sys.executable, str(W.parent / "scripts" / "_contract.py"), "doctor", "--json"],- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=120)+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=120)mode = (json.loads(out.stdout).get("fonts") or {}).get("emoji", {}).get("mode")except Exception:mode = Nonediff --git a/evals/write_fixtures.py b/evals/write_fixtures.pyindex 54c58b4..19fe7ed 100644--- a/evals/write_fixtures.py+++ b/evals/write_fixtures.py@@ -10,12 +10,37 @@ never committed, so the repo stays free of generated media and generated fixtureare overwritten. Prompts without a "fixtures" key write nothing."""import json+import ntpath+import os+import posixpathimport sysfrom pathlib import PathHERE = Path(__file__).resolve().parent+def absolute_output_dir(text: str, name: str, outdir: Path) -> str:+ """A batch recipe's "output_dir" is resolved against the CALLER's cwd, not against the folder+ of inputs, so a relative "out" in a staged fixture wrote somewhere the run never looked and+ the agent had to rewrite the recipe (eval 18 bp1/bp2). Stage it absolute, under OUTDIR.+ """+ if not name.endswith(".json"):+ return text+ try:+ doc = json.loads(text)+ except ValueError:+ return text+ if not isinstance(doc, dict) or not isinstance(doc.get("output_dir"), str):+ return text+ # ntpath/posixpath rather than Path: on Windows `Path("/srv/out").is_absolute()` is False, so+ # a posix-absolute output_dir would be rewritten under OUTDIR there (review 17 finding 9).+ stated = os.path.normpath(doc["output_dir"]).replace("\\", "/")+ if posixpath.isabs(stated) or ntpath.isabs(doc["output_dir"]):+ return text+ doc["output_dir"] = str((outdir / doc["output_dir"]).resolve())+ return json.dumps(doc, indent=2, ensure_ascii=False) + "\n"++def write(outdir: Path, prompt: dict) -> list:written = []for name, text in (prompt.get("fixtures") or {}).items():@@ -23,6 +48,7 @@ def write(outdir: Path, prompt: dict) -> list:raise SystemExit(f"fixture name must be a plain file name: {name!r}")outdir.mkdir(parents=True, exist_ok=True)target = outdir / name+ text = absolute_output_dir(text, name, outdir)target.write_text(text, encoding="utf-8")written.append(target)# 1.15: a prompt may ask for a directory of emoji PNGs. The repo ships NO emoji art -- Twemojidiff --git a/references/scripts.md b/references/scripts.mdindex 596ef48..23b0588 100644--- a/references/scripts.md+++ b/references/scripts.md@@ -601,6 +601,10 @@ hardlinks the artifact into the work directory, or copies it where thefilesystem will not link — never moves it, since the cache has to outlive therun's own cleanup. Any mismatch is a silent miss.+A stage whose flags changed misses the cache, so editing the captions block (for+example to `"fit_size": "off"`) re-runs captions and everything after it and+serves the earlier stages from the cache.+`stages_done` is unchanged: a cached stage is still a stage that happened.Nothing is written under `--dry-run`, which instead reports `cache.would_hit`.Result: `cache.dir`, `cache.ffmpeg`, `cache.hits`, `cache.misses`,@@ -645,6 +649,17 @@ Alias spellings are accepted everywhere one name is: `youtube-shorts`/`yt-shorts(`check.py --platform`, `export.py --preset`, `caption.py`/`graphics.py`/`overlay.py--platform`, `look.py --safe`, `render.py --template`).+**Caption size on the template path (1.17.1).** A template's caption `size` and+`margin` come from the delivery table, not from a literal in the JSON, so the+filled project also states `"fit_size": "on"`: a size nobody asked for must not+switch off the size fitter the way a stated `--size` does (before 1.17.1 a long+cue was split across two consecutive cues on every `--template` run). A template+file that states its own `fit_size`, and a `--brand` whose caption block states a+size, both win. A project may state the policy itself — `"captions": {"fit_size":+"auto"|"on"|"off", "min_size": N, "fit_size_scope": "file"|"cue"}` — and+`"fit_size": "off"` renders the captions 1.17.0 rendered, byte for byte. The+render result carries the caption stage's own block as `caption`.+Under `--dry-run` a pack prints every child's planned commands and its table reads `planned`with no size or duration: nothing was encoded, so nothing is reported as verified. `--chapters`reaches a pack's audio destination like it does the single-template form.@@ -973,6 +988,15 @@ Results, alongside the existing caption stats:`shrunk`, `fit_scope`, `fit_exhausted`, and `size_source` (`input` or`platform-frame`).+**"caption text unchanged" (1.17.1).** When the drawn text equals the cues that+were handed in — nothing transcribed, no cue dropped, no cue *split* across two+consecutive cues and no glyph stripped by `--emoji none` — the summary says+`caption text unchanged: the cues were burned exactly as given (line breaks,+timing and type size only)` and the result carries `text_unchanged: true`. It is+the honest sentence for a report, made automatic: only the line breaks, the+timing and the type size ever move, and those do not count as a change. The key+is burn mode only; `--mode mux` never touches the text and omits it.+Under `--dry-run`/`--plan` on an input that does not exist yet there is nogeometry to measure. With `--platform` the destination's own frame is used —that frame *is* what the real run will have, so the planned `FontSize` is thediff --git a/scripts/_common/asr.py b/scripts/_common/asr.pyindex fc45453..ba51689 100644--- a/scripts/_common/asr.py+++ b/scripts/_common/asr.py@@ -84,7 +84,7 @@ def _asr_run(cmd: List[str], subprocess, name: str) -> "subprocess.CompletedProcfrom _common import STATE, dielimit = STATE.timeout or Nonetry:- return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=limit)+ return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=limit)except subprocess.TimeoutExpired:die(f"{name} exceeded the {limit:.0f} s time limit and was killed; raise --timeout for a long recording",code=124, kind="timeout")diff --git a/scripts/_common/probe.py b/scripts/_common/probe.pyindex 3ac3eeb..aa1559f 100644--- a/scripts/_common/probe.py+++ b/scripts/_common/probe.py@@ -137,6 +137,20 @@ def probe(path: str, role: str = "input") -> Dict[str, Any]: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()}")+ if not (proc.stdout or "").strip():+ # ffprobe exited 0 and printed nothing we could read. Before 1.17.1 that produced a+ # SUCCESS document of nulls -- "?s | no video | no audio", exit 0 -- which is how #234+ # showed up on a Windows cp932 machine: the capture decoded ffprobe's UTF-8 JSON with the+ # locale code page, the reader thread raised UnicodeDecodeError and stdout came back+ # empty. Every child capture is decoded as UTF-8 with errors="replace" now; if a document+ # still does not arrive, refuse rather than report an unmeasured file as measured.+ msg = (f"ffprobe printed no output for {path}: its JSON could not be read (a decoding or "+ "pipe failure, not a measurement)")+ if proc.stderr.strip():+ msg += f"\n{proc.stderr.strip()}"+ if role == "output":+ _output_failed(path, msg)+ die(msg, kind="input")try:raw = json.loads(proc.stdout or "{}")except ValueError as e:diff --git a/scripts/_common/runner.py b/scripts/_common/runner.pyindex bf38bbc..1829941 100644--- a/scripts/_common/runner.py+++ b/scripts/_common/runner.py@@ -100,7 +100,7 @@ def ffmpeg_version() -> "Tuple[int, int]":if _FFMPEG_VERSION is None:_FFMPEG_VERSION = (0, 0)try:- out = subprocess.run(["ffprobe", "-version"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,+ out = subprocess.run(["ffprobe", "-version"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace",timeout=PROBE_TIMEOUT).stdoutm = re.search(r"ffprobe version\s+n?(\d+)\.(\d+)", out)if m:@@ -708,7 +708,11 @@ def run_analysis(cmd: Sequence[str], *, check: bool = True, text: bool = True, rSTATE.commands.append(_cmdline(cmd))limit = _limit_for(cmd)try:- proc = subprocess.run(list(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, timeout=limit)+ # #234: decode as UTF-8, never as the machine's locale code page -- ffmpeg echoes the+ # input filename on stderr, and loudness/check parse the loudnorm JSON out of it. The+ # encoding kwargs are rejected with text=False, so they are only passed for text mode.+ text_kw = {"encoding": "utf-8", "errors": "replace"} if text else {}+ proc = subprocess.run(list(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=text, **text_kw, timeout=limit)except subprocess.TimeoutExpired:_timed_out(cmd, limit or 0)if check and proc.returncode != 0:@@ -744,7 +748,7 @@ def run_tool(argv: Sequence[str], *, per_call: Optional[float] = None) -> subprodocument (kind timeout, exit 124), so callers that parse the child's --json see a timeoutexactly as they would from the child itself."""limit = child_limit(per_call)- child = subprocess.Popen([sys.executable] + list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ child = subprocess.Popen([sys.executable] + list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")_watch(child, []) # a sibling script removes its own partial output; there is none of ours to cleantry:out, err = child.communicate(timeout=limit)@@ -804,7 +808,7 @@ def _limit_for(cmd: Sequence[str]) -> Optional[float]:def _run_captured(cmd: List[str], check: bool) -> subprocess.CompletedProcess:"""Plain run with stdout/stderr captured."""limit = _limit_for(cmd)- child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")_watch(child, cmd)try:out, err = child.communicate(timeout=limit)@@ -854,7 +858,7 @@ def _run_with_progress(cmd: List[str], check: bool) -> subprocess.CompletedProcefull = cmd[:1] + ["-progress", "pipe:1", "-nostats"] + cmd[1:]t0 = time.time()limit = _limit_for(cmd)- proc = subprocess.Popen(full, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ proc = subprocess.Popen(full, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")_watch(proc, cmd)assert proc.stdout is not None and proc.stderr is not Nonelines: "queue.Queue[Optional[str]]" = queue.Queue()@@ -1022,7 +1026,7 @@ def ffmpeg_encoders() -> set:_ENCODERS = set()try:out = subprocess.run([shutil.which("ffmpeg") or "ffmpeg", "-hide_banner", "-encoders"], stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL, text=True, timeout=PROBE_TIMEOUT).stdout+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=PROBE_TIMEOUT).stdout_ENCODERS = set(re.findall(r"^\s*[VAS][.\w]{5}\s+(\S+)", out, re.M))except (OSError, subprocess.SubprocessError):passdiff --git a/scripts/_common/text.py b/scripts/_common/text.pyindex d6486ef..2e9648c 100644--- a/scripts/_common/text.py+++ b/scripts/_common/text.py@@ -72,7 +72,7 @@ def default_font_file(font_name: str) -> Optional[str]:if not exe:return Nonetry:- proc = subprocess.run([exe, "--format=%{file}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=5)+ proc = subprocess.run([exe, "--format=%{file}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=5)except (subprocess.TimeoutExpired, OSError):return Noneif proc.returncode != 0:@@ -319,7 +319,7 @@ def _emoji_color_font() -> "Tuple[Optional[str], Optional[str], bool]":for family in _EMOJI_COLOR_FAMILIES:try:proc = subprocess.run([exe, f":family={family}", "file"], stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL, text=True, timeout=10)+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)except (subprocess.TimeoutExpired, OSError):return None, None, Falseif proc.returncode != 0:@@ -618,7 +618,7 @@ def drawtext_shaping() -> "Dict[str, bool]":for flag in ("-buildconf", "-version"):try:proc = subprocess.run([exe, "-hide_banner", flag], stdout=subprocess.PIPE,- stderr=subprocess.STDOUT, text=True, timeout=10)+ stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", timeout=10)except (subprocess.TimeoutExpired, OSError):breakif proc.returncode == 0 and proc.stdout.strip():@@ -645,7 +645,7 @@ def font_family_of_file(path: str) -> "Optional[str]":if exe:try:proc = subprocess.run([exe, "--format", "%{family[0]}", path], stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL, text=True, timeout=10)+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)if proc.returncode == 0 and proc.stdout.strip():return proc.stdout.strip().splitlines()[0].strip()except (subprocess.TimeoutExpired, OSError):@@ -717,7 +717,7 @@ def _fc_list_fonts(fc_lang: str) -> "Optional[List[Tuple[str, List[str]]]]":return Nonetry:proc = subprocess.run([exe, f":lang={fc_lang}", "file", "family"],- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=10)+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)except (subprocess.TimeoutExpired, OSError):return Noneif proc.returncode != 0:@@ -832,7 +832,7 @@ def font_covers_script(font_name: str, script: str) -> bool:return Truetry:proc = subprocess.run([exe, f":lang={FC_LANG[script]}:family={font_name}", "file"],- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=10)+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)except (subprocess.TimeoutExpired, OSError):return Trueif proc.returncode != 0:@@ -866,7 +866,7 @@ def fonts_dir_covers_script(fonts_dir: str, script: str) -> "Optional[bool]":return Nonetry:proc = subprocess.run([exe, "--format", "%{lang}\n", fonts_dir],- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=10)+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=10)except (subprocess.TimeoutExpired, OSError):return Noneif proc.returncode != 0:diff --git a/scripts/_contract.py b/scripts/_contract.pyindex 8299bb3..42dea62 100644--- a/scripts/_contract.py+++ b/scripts/_contract.py@@ -532,7 +532,7 @@ def _ff_listing(binary: str, flag: str) -> Dict[str, Any]:if not exe:return {"names": [], "status": "missing", "detail": f"{binary} not on PATH"}try:- proc = subprocess.run([exe, "-hide_banner", flag], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=_DETECT_TIMEOUT)+ proc = subprocess.run([exe, "-hide_banner", flag], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=_DETECT_TIMEOUT)except subprocess.TimeoutExpired:return {"names": [], "status": "failed", "detail": f"{binary} {flag} did not exit within {_DETECT_TIMEOUT}s"}except OSError as e:@@ -578,7 +578,7 @@ def _version_line(binary: str) -> Optional[str]:if not exe:return Nonetry:- proc = subprocess.run([exe, "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=_DETECT_TIMEOUT)+ proc = subprocess.run([exe, "-version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=_DETECT_TIMEOUT)except subprocess.TimeoutExpired:return Nonefirst = (proc.stdout or proc.stderr).splitlines()[:1]@@ -623,7 +623,7 @@ def _drawtext_probe() -> Dict[str, Any]:proc = subprocess.run([exe, "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:d=1","-vf", "drawtext=text=x", "-frames:v", "1", "-f", "null", "-"],- stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=_DETECT_TIMEOUT,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=_DETECT_TIMEOUT,)except subprocess.TimeoutExpired:return {"status": "unknown", "detail": f"drawtext probe did not exit within {_DETECT_TIMEOUT}s"}@@ -657,7 +657,7 @@ def _font_available(font_name: str) -> Dict[str, Any]:if not exe:return {"status": "unknown", "detail": "fc-match not on PATH; drawtext succeeding proves nothing (fontconfig substitutes silently), so availability cannot be verified"}try:- proc = subprocess.run([exe, "--format=%{family}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=_DETECT_TIMEOUT)+ proc = subprocess.run([exe, "--format=%{family}\n", font_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=_DETECT_TIMEOUT)except subprocess.TimeoutExpired:return {"status": "unknown", "detail": f"fc-match did not exit within {_DETECT_TIMEOUT}s"}except OSError as e:diff --git a/scripts/caption.py b/scripts/caption.pyindex 3d2a569..22965cc 100755--- a/scripts/caption.py+++ b/scripts/caption.py@@ -1272,6 +1272,21 @@ def main() -> int:result = probe(output, role="output")info(f"wrote {output} ({fmt_secs(result.get('duration'))})")extra = {"notes": side_notes} if side_notes else {}+ # 1.17.1: say so when the words on screen are the words that were handed in. This tool never+ # rewrites, shortens or translates a cue -- only line breaks, timing and type size move -- so+ # the honest sentence in a report ("the text is yours, unchanged") needs no extra judgement.+ # Review 17 finding 5: a cue SPLIT across two consecutive cues, a dropped cue, transcription+ # and `--emoji none` (which str.replace()s glyphs out of the drawn text) all change what the+ # viewer reads, so none of them may be reported as unchanged. Wrapping, line breaks and+ # timing do not count -- the words are the same.+ caption_stats["text_unchanged"] = bool(+ not args.transcribe+ and not caption_stats.get("dropped")+ and not caption_stats.get("split")+ and (emoji_plan or {}).get("mode") != "none")+ if caption_stats["text_unchanged"]:+ info("caption text unchanged: the cues were burned exactly as given (line breaks, timing "+ "and type size only)")extra["caption"] = dict(caption_stats)if emoji_plan:notes = list(extra.get("notes") or [])diff --git a/scripts/render.py b/scripts/render.pyindex 92fbce3..3a7d86f 100755--- a/scripts/render.py+++ b/scripts/render.py@@ -64,7 +64,7 @@ from typing import Any, Dict, List, Optional, Sequencefrom export import PRESETS, PLATFORM_OFfrom _platforms import PLATFORMS, caption_defaults, resolve as resolve_platform-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, ffmpeg_version+from _common import STATE, add_common, brand_caption_style, load_brand, apply_common, child_args, die, emit, info, probe, run_tool, place_output, refuse_output_is_input, fingerprint, PLAN_VERSION, ffmpeg_versionimport subprocessfrom _contract import CONTRACT_VERSIONfrom batch import file_key@@ -126,9 +126,12 @@ OBJECT_KEYS: Dict[str, frozenset] = {# 1.16: the picture an audio-only source gets before the rest of the chain can work on it"audiogram": frozenset({"image", "image_fit", "style", "position", "vis_height", "opacity","platform", "title", "color", "background", "width", "height", "fps"}),+ # 1.17.1: fit_size / min_size / fit_size_scope, so a project can state the fit policy the+ # templates now default to (eval 18 cs1 hit "unknown key 'fit_size'" and hand-ran the stages)."captions": frozenset({"text", "srt", "ass", "font", "size", "color", "position", "margin","animate", "highlight_color", "outline", "karaoke", "bold", "box",- "lang", "offset", "max_lines", "min_duration"}),+ "lang", "offset", "max_lines", "min_duration",+ "fit_size", "min_size", "fit_size_scope"}),# the 1.14 social templates (sticker/hook/meme) take their own text and timing, so a# graphics[] entry can carry them too -- a template that only works from the CLI is not# "usable inside a render.py graphics[] entry" (review 12)@@ -201,6 +204,23 @@ def fill_template(node: Any, values: Dict[str, Any]) -> "tuple":return node, True+def brand_states_caption_size(path: Optional[str]) -> bool:+ """True only when a brand file actually names a caption size. `--brand` alone says nothing+ about type size -- brand_caption_style() applies no defaults -- so the presence of the flag+ must not switch caption.py's `--fit-size auto` off (review 17 finding 1)."""+ if not path or not os.path.isfile(path):+ return False+ try:+ stated = load_brand(path).get("_stated") or {}+ except SystemExit:+ raise+ except Exception:+ return False+ # BRAND_DEFAULTS always supplies caption.size, so only what the FILE said can answer this+ # (the same reason brand_states_font() exists).+ return brand_caption_style(stated).get("size") is not None++def template_project(name: str, args) -> Dict[str, Any]:"""One template plus the run's arguments as a ready-to-render project."""tpl = load_template(name)@@ -216,6 +236,14 @@ def template_project(name: str, args) -> Dict[str, Any]:tpl["captions"]["margin"] = defaults["margin"]for key in ("position", "animate", "outline"):tpl["captions"].setdefault(key, defaults[key])+ # 1.17.1: that size is the table's default, not a size anyone asked for, so it must not+ # switch off caption.py's `--fit-size auto` the way a stated --size does -- eval 18 saw a+ # long cue split across two consecutive cues instead of the type shrinking to fit. A+ # template that states "fit_size" wins, and so does a brand file that STATES a caption+ # size (that size is a statement about the look). A brand of colours or a font alone+ # states no size, so it must not stand the fitter down: review 17 finding 1.+ if not brand_states_caption_size(args.brand):+ tpl["captions"].setdefault("fit_size", "on")output = args.output or str(template_output(args.input, name, dest))values = {"$INPUT": os.path.abspath(args.input),@@ -510,7 +538,7 @@ def ffmpeg_banner() -> str:"""try:out = subprocess.run(["ffprobe", "-version"], stdout=subprocess.PIPE,- stderr=subprocess.DEVNULL, text=True, timeout=20).stdout+ stderr=subprocess.DEVNULL, text=True, encoding="utf-8", errors="replace", timeout=20).stdoutfirst = (out or "").strip().splitlines()if first:return first[0].strip()@@ -820,6 +848,9 @@ def main() -> int:dest = str(((proj.get("check") or {}).get("platform") or "")) if proj.get("template") else ""platform_args: List[str] = ["--platform", dest] if dest in PLATFORMS and PLATFORMS[dest].get("frame") else []stages_done: List[str] = []+ # what the caption stage reported (wrapped/split counts and the fit-size keys), so a caller+ # reading render.py's JSON can see whether the type was shrunk to fit or a cue was split.+ caption_report: Optional[Dict[str, Any]] = NoneCACHE.clear()CACHE.update(_fresh_cache())@@ -995,13 +1026,16 @@ def main() -> int:argv += ["--ass", rel(cap["ass"])]else:die("captions needs text, srt or ass")- for k, flag in (("font", "--font"), ("size", "--size"), ("color", "--color"), ("position", "--position"), ("margin", "--margin"), ("animate", "--animate"), ("highlight_color", "--highlight-color"), ("outline", "--outline"), ("lang", "--lang"), ("offset", "--offset"), ("max_lines", "--max-lines"), ("min_duration", "--min-duration")):+ for k, flag in (("font", "--font"), ("size", "--size"), ("color", "--color"), ("position", "--position"), ("margin", "--margin"), ("animate", "--animate"), ("highlight_color", "--highlight-color"), ("outline", "--outline"), ("lang", "--lang"), ("offset", "--offset"), ("max_lines", "--max-lines"), ("min_duration", "--min-duration"),+ ("fit_size", "--fit-size"), ("min_size", "--min-size"), ("fit_size_scope", "--fit-size-scope")):if cap.get(k) is not None:argv += [flag, str(cap[k])]for k, flag in (("karaoke", "--karaoke"), ("bold", "--bold"), ("box", "--box")):if cap.get(k):argv.append(flag)sh("caption.py", *(argv + brand_args + platform_args), stage="captions")+ if isinstance(_LAST_DOC.get("caption"), dict):+ caption_report = dict(_LAST_DOC["caption"])current = nxtstages_done.append("captions")if args.stop_after == "captions":@@ -1202,6 +1236,7 @@ def main() -> int:snap_report = dict(snap_reports[0])snap_report["clips"] = snap_reportsemit(output, stages=stages_done, check=check_result, snap=snap_report, cache=cache_report,+ caption=caption_report,verification=[{"step": "check", "ok": True, "platform": ck["platform"]}] if check_result else [])return 0diff --git a/scripts/verify.py b/scripts/verify.pyindex 2649b7c..8048770 100755--- a/scripts/verify.py+++ b/scripts/verify.py@@ -81,7 +81,7 @@ def step(name: str, argv: List[str], timeout: float) -> Dict:STATE.json = was_jsonreturn {"step": name, "ok": ok, "seconds": round(time.time() - t0, 1), "error": err}try:- proc = subprocess.run([sys.executable, str(HERE / argv[0])] + argv[1:], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=timeout)+ proc = subprocess.run([sys.executable, str(HERE / argv[0])] + argv[1:], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", timeout=timeout)ok = proc.returncode == 0err = "" if ok else (proc.stderr.strip().splitlines() or ["?"])[-1][:200]except subprocess.TimeoutExpired:diff --git a/scripts/waveform.py b/scripts/waveform.pyindex 42c195c..a6db9c5 100644--- a/scripts/waveform.py+++ b/scripts/waveform.py@@ -274,8 +274,7 @@ def _child(script_name: str, argv: "list") -> None:if STATE.dry_run:cmd.append("--dry-run")info("-> " + " ".join(os.path.basename(c) if c.endswith(".py") else str(c) for c in cmd[1:]))- proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,- encoding="utf-8", errors="replace")+ proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")if proc.returncode != 0:die(f"{script_name} failed:\n{(proc.stderr or proc.stdout).strip()[-800:]}", kind="ffmpeg")diff --git a/tests/test_contract.py b/tests/test_contract.pyindex f54ff53..febe074 100644--- a/tests/test_contract.py+++ b/tests/test_contract.py@@ -2808,6 +2808,176 @@ class DoctorDetectionTests(unittest.TestCase):f"SKILL.md is {size} bytes, {size - 30_000} over the 30,000-byte budget -- ""trim a line rather than raising the limit (see CONTRIBUTING.md)")+ # ------------------------------------------------- #234: child output is decoded as UTF-8+ def test_every_child_text_capture_names_utf8(self):+ """#234: `text=True` decodes with the machine's locale code page. On a Windows cp932 box+ ffprobe's UTF-8 JSON then raises UnicodeDecodeError inside the reader thread,+ communicate() hands back an empty stdout, and probe.py reported `?s | no video | no+ audio` with exit 0. Every child capture in this repo states its encoding."""+ import ast++ def offending_calls(source, rel):+ """Every subprocess.run/Popen call that asks for text mode without naming UTF-8.+ The scan is over the parsed call, not over one line: review 17 finding 3 -- the+ line-matching version could not see `text=text` in runner.run_analysis(), which is+ exactly the capture that shipped undecorated."""+ found = []+ tree = ast.parse(source)+ funcs = [n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ name = getattr(node.func, "attr", None) or getattr(node.func, "id", None)+ if name not in ("run", "Popen", "check_output", "call"):+ continue+ kw = {k.arg: k.value for k in node.keywords if k.arg}+ if "text" not in kw and "universal_newlines" not in kw:+ continue+ flag = kw.get("text", kw.get("universal_newlines"))+ if isinstance(flag, ast.Constant) and flag.value is False:+ continue # bytes: encoding would be rejected+ if "encoding" in kw:+ continue+ if any(k.arg is None for k in node.keywords):+ # a **mapping of encoding kwargs, built in the enclosing function+ owner = [f for f in funcs if f.lineno <= node.lineno <= (f.end_lineno or node.lineno)]+ seg = "\n".join(ast.get_source_segment(source, f) or "" for f in owner)+ if '"encoding": "utf-8"' in seg or "'encoding': 'utf-8'" in seg:+ continue+ found.append(f"{rel}:{node.lineno}")+ return found++ offenders = []+ for root in ("scripts", "evals"):+ for path in sorted((ROOT / root).rglob("*.py")):+ offenders += offending_calls(path.read_text(encoding="utf-8"), path.relative_to(ROOT))+ self.assertEqual(offenders, [], "decode child output as UTF-8 (errors='replace'), never as the locale code page")+ # the scan must see the shapes the old line match missed+ self.assertEqual(offending_calls("subprocess.run(cmd, text=text)", "x.py"), ["x.py:1"])+ self.assertEqual(offending_calls("subprocess.run(cmd, universal_newlines=True)", "x.py"), ["x.py:1"])+ self.assertEqual(offending_calls("subprocess.run(cmd, text=False)", "x.py"), [])++ def _utf8_ffprobe_shim(self, body):+ shim = OUT / "utf8_shim"+ shim.mkdir(parents=True, exist_ok=True)+ (shim / "ffprobe").write_text("#!/bin/sh\n" + body, encoding="utf-8")+ (shim / "ffprobe").chmod(0o755)+ # LANG/LC_ALL=C with the UTF-8 modes off is this machine's stand-in for a cp932 Windows+ # console: Python's preferred encoding becomes ASCII, so a locale-decoded capture of the+ # UTF-8 JSON below fails exactly as it does there.+ env = dict(os.environ, PATH=f"{shim}:{os.environ['PATH']}", LANG="C", LC_ALL="C",+ PYTHONUTF8="0", PYTHONCOERCECLOCALE="0")+ env.pop("PYTHONIOENCODING", None)+ return env++ @unittest.skipIf(platform.system() == "Windows", "the fake ffprobe is a #!/bin/sh script")+ def test_probe_reads_non_ascii_ffprobe_json_under_a_non_utf8_locale(self):+ doc = ('{"format": {"filename": "\u65e5\u672c\u8a9e.mp4", "format_name": "mov,mp4", '+ '"duration": "12.0", "size": "1000", "tags": {"title": "\u65e5\u672c\u8a9e"}}, '+ '"streams": [{"codec_type": "video", "codec_name": "h264", "width": 1280, '+ '"height": 720, "r_frame_rate": "30/1", "pix_fmt": "yuv420p"}]}')+ env = self._utf8_ffprobe_shim("cat <<'JSON'\n" + doc + "\nJSON\n")+ target = OUT / "utf8_probe.mp4"+ target.write_bytes(b"not really a movie") # ffprobe is the shim; only the path must exist+ proc = sh(sys.executable, SCRIPTS / "probe.py", target, "--json", env=env)+ self.assertEqual(proc.returncode, 0, proc.stderr)+ d = json.loads(proc.stdout)+ self.assertEqual(d["duration"], 12.0)+ self.assertEqual(d["video"]["width"], 1280)+ # the non-ASCII text ffprobe printed survives the capture -- the #234 surface (the path+ # on argv is the filesystem encoding, a different axis, so it is not what is asserted)+ self.assertEqual(d["tags"]["title"], "\u65e5\u672c\u8a9e")++ @unittest.skipIf(platform.system() == "Windows", "the fake ffprobe is a #!/bin/sh script")+ def test_probe_refuses_when_ffprobe_prints_nothing(self):+ """The half of #234 that made it a silent defect: an empty stdout with exit 0 must never+ become a success document of nulls."""+ env = self._utf8_ffprobe_shim("exit 0\n")+ target = OUT / "empty_probe.mp4"+ target.write_bytes(b"not really a movie")+ # this module's own sh() (line 41), not tests/_fixtures.sh: check=False means "do not+ # raise on a non-zero exit", which is the point of the refusal being asserted below.+ proc = sh(sys.executable, SCRIPTS / "probe.py", target, "--json", env=env, check=False)+ self.assertNotEqual(proc.returncode, 0)+ err = json.loads(proc.stdout)+ self.assertEqual(err["status"], "failed")+ self.assertEqual(err["error"]["kind"], "input")+ self.assertIn("no output", err["error"]["message"])++ @unittest.skipIf(platform.system() == "Windows", "the fake ffmpeg is a #!/bin/sh script")+ def test_run_analysis_survives_non_utf8_locale_on_the_loudness_path(self):+ """Review 17 finding 2: run_analysis() is the capture every ffmpeg MEASUREMENT goes+ through -- loudness.py parses the loudnorm JSON out of its stderr. With the locale's+ codec it raised UnicodeDecodeError inside subprocess.run: an unhandled traceback, not a+ `status: failed` document."""+ shim = OUT / "utf8_ffmpeg_shim"+ shim.mkdir(parents=True, exist_ok=True)+ (shim / "ffmpeg").write_text(+ "#!/bin/sh\n"+ "printf 'Input #0, mov,mp4, from \\346\\227\\245\\346\\234\\254\\350\\252\\236.mp4:\\n' >&2\n"+ "cat >&2 <<'JSON'\n"+ '{ "input_i" : "-18.5", "input_tp" : "-2.0", "input_lra" : "7.0", '+ '"input_thresh" : "-28.7", "target_offset" : "0.5" }\n'+ "JSON\n", encoding="utf-8")+ (shim / "ffmpeg").chmod(0o755)+ env = dict(os.environ, PATH=f"{shim}:{os.environ['PATH']}", LANG="C", LC_ALL="C",+ PYTHONUTF8="0", PYTHONCOERCECLOCALE="0")+ env.pop("PYTHONIOENCODING", None)+ code = ("import json, sys; sys.path.insert(0, %r); import loudness; "+ "print(json.dumps(loudness.measure('x.wav', -14.0, -1.0, 11.0)))" % str(SCRIPTS))+ proc = sh(sys.executable, "-c", code, env=env)+ self.assertEqual(json.loads(proc.stdout)["input_i"], "-18.5")++ def test_skill_md_routes_the_1_17_features(self):+ """Eval 18: SKILL.md never mentioned filler, --snap beats, --jobs or --cache, so three+ runs rebuilt those features by hand and one asserted the skill has no beat detection.+ A feature nobody can find from the routing table does not exist."""+ table = (ROOT / "SKILL.md").read_text(encoding="utf-8").split("## Request \u2192 script", 1)[1]+ for feature, needles in (("filler words", ("silence.py", "--filler", "--words")),+ ("beat-synced cuts", ("scenes.py", "--beats", "--snap beats")),+ ("parallel batch", ("batch.py", "--jobs auto")),+ ("the stage cache", ("render.py", "--cache"))):+ for needle in needles:+ self.assertIn(needle, table, f"{feature}: the routing table never names {needle}")++ def test_skill_md_sanctions_one_label_for_a_partial_result(self):+ """1.17.1: a partial result is `Done:` with the shortfall in `Notes:`. Agents were+ inventing `Done (partially):` because the rule only said what not to write."""+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")+ self.assertIn("A partial result is `Done:` with the shortfall in `Notes:`", text)+ self.assertIn("Done (partially):", text, "the forbidden label is still named, as the counter-example")++ def test_eval_fixtures_stage_a_batch_recipe_with_an_absolute_output_dir(self):+ """eval 18 bp1/bp2: the staged batch.json said "output_dir": "out", which resolves+ against the caller's cwd, so the run wrote outside the prompt's folder and the agent had+ to rewrite the recipe before it could answer the prompt."""+ sys.path.insert(0, str(ROOT / "evals"))+ import importlib+ write_fixtures = importlib.import_module("write_fixtures")+ with tempfile.TemporaryDirectory() as tmp:+ outdir = Path(tmp) / "bp1"+ written = write_fixtures.write(outdir, {"fixtures": {+ "batch.json": json.dumps({"glob": "*.mp4", "output_dir": "out", "steps": []}),+ "cues.txt": "0:00-0:03 hello\n"}})+ recipe = json.loads((outdir / "batch.json").read_text(encoding="utf-8"))+ self.assertTrue(Path(recipe["output_dir"]).is_absolute())+ # the fixture resolves the path (macOS tempdirs live under a /var -> /private/var symlink)+ self.assertEqual(Path(recipe["output_dir"]), (outdir / "out").resolve())+ self.assertEqual((outdir / "cues.txt").read_text(encoding="utf-8"), "0:00-0:03 hello\n",+ "a non-JSON fixture is written exactly as the prompt states it")+ self.assertEqual(len(written), 2)+ # an absolute output_dir in the prompt is left alone -- on every OS. Path("/srv/out")+ # .is_absolute() is False on Windows, which used to rewrite a posix-absolute dir under+ # OUTDIR there (review 17 finding 9), so both spellings are asserted here.+ for stated in ("/srv/out", "C:\\srv\\out"):+ with tempfile.TemporaryDirectory() as tmp:+ outdir = Path(tmp) / "bp2"+ write_fixtures.write(outdir, {"fixtures": {"batch.json": json.dumps(+ {"glob": "*.mp4", "output_dir": stated})}})+ self.assertEqual(+ json.loads((outdir / "batch.json").read_text(encoding="utf-8"))["output_dir"],+ stated)+def test_font_fix_hint_names_the_language_and_how_to_install_one(self):hint = _contract._capability_fix_hint("font:ko")self.assertIn("Korean", hint)diff --git a/tests/test_orchestration.py b/tests/test_orchestration.pyindex 8dafe16..84cf0c8 100644--- a/tests/test_orchestration.py+++ b/tests/test_orchestration.py@@ -598,6 +598,105 @@ class OrchestrationTests(MediaFixtures):self.assertEqual(plan["status"], "completed")self.assertIn("export", plan["stages"])+ # --------------------------------------------- 1.17.1: the template path fits the caption size+ def _cw1_cues(self):+ cues = OUT / "cues_cw1.txt"+ cues.write_text("0:00-0:03 A third line the tool times for me\n"+ "0:03-0:06 Segunda l\u00ednea de subt\u00edtulos\n", encoding="utf-8")+ return cues++ def test_template_captions_shrink_instead_of_splitting(self):+ """1.17.0 filled the caption size from the platform table and forwarded it as an explicit+ --size, which switched off caption.py's --fit-size auto: on the template path -- the path+ every "make this a TikTok" request takes -- long cues were split across two consecutive+ cues instead of shrinking (eval 18 cw1). The template now states fit_size "on"."""+ out = OUT / "tpl_fit.mp4"+ doc = json.loads(script("render.py", self.src, "--template", "tiktok", "--fast",+ "--cues", self._cw1_cues(), "-o", out, "--json").stdout)+ cap = doc["caption"]+ self.assertEqual(cap["split"], 0, "no cue may be chopped in two on the template path")+ self.assertEqual(cap["fit_size"], "on")+ self.assertEqual(cap["size_requested"], 24) # the tiktok table's size+ self.assertLess(cap["size_used"], 24, "the size must come down to fit the cue")+ self.assertGreaterEqual(cap["size_used"], cap["size_floor"])+ self.assertGreaterEqual(cap["shrunk"], 1)+ self.assertFalse(cap["fit_exhausted"])+ # honest BECAUSE nothing was split: a split cue now makes text_unchanged false+ self.assertTrue(cap["text_unchanged"])+ self.assertTrue(Path(out).exists())++ def test_template_captions_fit_under_a_brand_that_states_no_size(self):+ """Review 17 finding 1: `--brand` alone is not a stated caption size. A brand file of+ colours states nothing about type, so the platform table's 24 is still the skill's own+ choice and must stay fittable; a brand that names caption.size does state one."""+ brand = OUT / "brand_colours_only.json"+ brand.write_text(json.dumps({"colors": {"text": "FFFFFF"}}), encoding="utf-8")+ proj = OUT / "tpl_brand_colours.json"+ script("render.py", self.src, "--template", "tiktok", "--cues", self._cw1_cues(),+ "--brand", brand, "--write-project", proj, "-o", OUT / "tpl_brand_colours.mp4")+ self.assertEqual(json.loads(proj.read_text(encoding="utf-8"))["captions"]["fit_size"], "on")+ doc = json.loads(script("render.py", self.src, "--template", "tiktok", "--fast",+ "--cues", self._cw1_cues(), "--brand", brand,+ "-o", OUT / "tpl_brand_colours.mp4", "--json").stdout)+ cap = doc["caption"]+ self.assertEqual(cap["fit_size"], "on")+ self.assertEqual(cap["split"], 0, "a colours-only brand must not stand the fitter down")+ self.assertLess(cap["size_used"], 24)++ sized = OUT / "brand_with_size.json"+ sized.write_text(json.dumps({"colors": {"text": "FFFFFF"}, "caption": {"size": 22}}),+ encoding="utf-8")+ proj2 = OUT / "tpl_brand_sized.json"+ script("render.py", self.src, "--template", "tiktok", "--cues", self._cw1_cues(),+ "--brand", sized, "--write-project", proj2, "-o", OUT / "tpl_brand_sized.mp4")+ self.assertNotIn("fit_size", json.loads(proj2.read_text(encoding="utf-8"))["captions"],+ "a brand-stated caption size is an explicit size: leave it alone")++ def test_project_fit_size_off_renders_1_17_0s_captions(self):+ """The stability answer: a project that states "fit_size": "off" gets exactly the ASS+ 1.17.0 wrote -- which is what a project written before 1.17.1 (no fit_size key at all,+ so an explicit --size and no fit) still produces, byte for byte."""+ proj = OUT / "fitoff_project.json"+ script("render.py", self.src, "--template", "tiktok", "--cues", self._cw1_cues(),+ "--write-project", proj, "-o", OUT / "fitoff.mp4")+ loaded = json.loads(proj.read_text(encoding="utf-8"))+ self.assertEqual(loaded["captions"]["fit_size"], "on",+ "a template-written project states the fit policy it renders with")++ def render_ass(captions, tag):+ work = OUT / f"fitoff_work_{tag}"+ shutil.rmtree(work, ignore_errors=True)+ doc = dict(loaded)+ doc["captions"] = captions+ doc["output"] = str(OUT / f"fitoff_{tag}.mp4")+ path = OUT / f"fitoff_{tag}.json"+ path.write_text(json.dumps(doc), encoding="utf-8")+ script("render.py", path, "--fast", "--stop-after", "captions", "--work", work, "--keep")+ return (work / "captioned.ass").read_bytes()++ stated_off = dict(loaded["captions"], fit_size="off")+ legacy = {k: v for k, v in loaded["captions"].items() if k != "fit_size"}+ self.assertEqual(render_ass(stated_off, "off"), render_ass(legacy, "legacy"),+ '"fit_size": "off" must reproduce the pre-1.17.1 captions byte for byte')+ self.assertNotEqual(render_ass(stated_off, "off2"), render_ass(loaded["captions"], "on"),+ "the new default has to actually change the ASS, or it fixes nothing")++ def test_project_captions_accept_the_fit_keys(self):+ """eval 18 cs1: a project could not state the fit policy at all ("unknown key+ 'fit_size'"), so the agent hand-ran the four stages instead of using render.py."""+ proj = OUT / "fitkeys.json"+ proj.write_text(json.dumps({+ "output": str(OUT / "fitkeys.mp4"),+ "clips": [{"src": str(self.src.resolve()), "in": 0, "out": 4}],+ "captions": {"text": str(self._cw1_cues()), "size": 24, "max_lines": 2,+ "fit_size": "on", "min_size": 15, "fit_size_scope": "cue"},+ }), encoding="utf-8")+ doc = json.loads(script("render.py", proj, "--fast", "--json").stdout)+ cap = doc["caption"]+ self.assertEqual((cap["fit_size"], cap["size_floor"], cap["fit_scope"]), ("on", 15, "cue"))+ self.assertGreaterEqual(cap["size_used"], 15)+ self.assertEqual(cap["split"], 0)+def test_project_graphics_entry_renders_a_sticker_and_a_meme(self):"""The three social graphics templates are advertised as usable inside a render.pygraphics[] entry, and until review 12 the project validator refused their own keys@@ -967,6 +1066,25 @@ class OrchestrationTests(MediaFixtures):self.assertEqual(sorted(p.name for p in cdir.iterdir()), [])self.assertIn("cache", data)+ def test_render_failure_with_a_cache_leaves_no_work_dir_and_caches_nothing(self):+ """The failure path of --cache, which the happy-path tests do not reach: a stage that+ fails must not leave its work directory behind, and must never put the partial artifact+ in the cache where a later run would be served it as a finished stage."""+ cdir = OUT / "rcache_fail"+ shutil.rmtree(cdir, ignore_errors=True)+ proj = self._cache_project("cache_fail")+ r = script("render.py", proj, "--cache", cdir, "--timeout", "0.05", "--json", expect_fail=True)+ self.assertEqual(json.loads(r.stdout)["error"]["kind"], "timeout")+ self.assertEqual(sorted(p.name for p in cdir.iterdir()), [],+ "a failed stage must not be cached")+ self.assertEqual([p.name for p in OUT.glob("cache_fail_out*_work_*")], [],+ "the work directory is removed on the failure path too")+ self.assertFalse((OUT / "cache_fail_out.mp4").exists())+ # and the cache is still usable afterwards: the next (untimed) run fills it normally+ ok = json.loads(script("render.py", proj, "--cache", cdir, "--json").stdout)+ self.assertEqual(ok["cache"]["hits"], [])+ self.assertTrue(list(cdir.glob("*.json")))+def test_render_from_without_a_cache_refuses(self):r = script("render.py", self._cache_project("cache_from"), "--from", "captions","--json", expect_fail=True)diff --git a/tests/test_picture.py b/tests/test_picture.pyindex 83fb321..88328c7 100644--- a/tests/test_picture.py+++ b/tests/test_picture.py@@ -1756,6 +1756,43 @@ class PictureTests(MediaFixtures):pinned = Path(__file__).resolve().parent / "fixtures" / "caption_1_16_1_fitsize_off.ass"self.assertEqual(ass.read_bytes(), pinned.read_bytes())+ def test_caption_says_when_the_text_is_unchanged(self):+ """1.17.1: the report sentence "the text is yours, unchanged" should not be a judgement+ the agent has to make -- the run states it (eval 18 cs2/cs3, where one run rewrote the+ user's cue text)."""+ vert, cues = self._vertical(), self._fit_cues()+ proc = script("caption.py", vert, "--text", cues, "--platform", "tiktok", "--max-lines", "2",+ "--font", "DejaVu Sans", "-o", OUT / "cap_unchanged.mp4", "--json")+ data = json.loads(proc.stdout)["caption"]+ self.assertEqual(data["split"], 0)+ self.assertTrue(data["text_unchanged"])+ self.assertIn("caption text unchanged", proc.stderr)++ def test_caption_text_is_not_unchanged_when_a_cue_was_split(self):+ """Review 17 finding 5: a cue the layout chopped into two consecutive cues is not the+ text that was handed in -- and it is the exact defect 1.17.1 exists to fix, so the tool+ must not claim honesty on precisely the runs that are still wrong."""+ vert, cues = self._vertical(), self._fit_cues()+ proc = script("caption.py", vert, "--text", cues, "--platform", "tiktok", "--max-lines", "2",+ "--size", "24", "--fit-size", "off", "--font", "DejaVu Sans",+ "-o", OUT / "cap_split.mp4", "--json")+ cap = json.loads(proc.stdout)["caption"]+ self.assertGreater(cap["split"], 0, "this run is the one that splits a cue")+ self.assertFalse(cap["text_unchanged"])+ self.assertNotIn("caption text unchanged", proc.stderr)++ def test_caption_text_is_not_unchanged_when_emoji_none_strips_glyphs(self):+ """--emoji none str.replace()s the clusters out of the drawn text: the viewer reads+ something other than the cue that was handed in (review 17 finding 5)."""+ cues = OUT / "cues_emoji_strip.txt"+ cues.write_text("0:00-0:03 Ship it \U0001F680\n", encoding="utf-8")+ proc = script("caption.py", self._vertical(), "--text", cues, "--platform", "tiktok",+ "--emoji", "none", "--font", "DejaVu Sans",+ "-o", OUT / "cap_emoji_none.mp4", "--json")+ cap = json.loads(proc.stdout)["caption"]+ self.assertFalse(cap["text_unchanged"])+ self.assertNotIn("caption text unchanged", proc.stderr)+def test_caption_fit_size_auto_leaves_an_explicit_size_alone(self):vert, cues = self._vertical(), self._fit_cues()data = json.loads(script("caption.py", vert, "--text", cues, "--platform", "tiktok",