Skip to content

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

Add curated dev skills from wdm0006/python-skills (concurrent-branches, CI, git hygiene, release, MCP, more) (#43)

Shogo Kajiyama24c1610abffc
diff --git a/.claude/skills/build-artifacts/SKILL.md b/.claude/skills/build-artifacts/SKILL.md
new file mode 100644
index 0000000..0c5c6c3
--- /dev/null
+++ b/.claude/skills/build-artifacts/SKILL.md
@@ -0,0 +1,182 @@
+---
+name: shipping-build-artifacts
+description: Make the build step a real gate on what you actually distribute — build scripts that warn and exit 0 on a missing input, size checks with only an upper bound, hand-maintained file lists that drift from the entrypoints they must cover, committed bundles that go stale when only the source changes, GNU-only shell in release scripts that aborts on the other OS, and verification that runs against the source tree instead of the artifact. Use when writing or reviewing a build/package script, a `dist/` copy step, a release workflow that uploads a zip or installer, or a committed compiled asset.
+---
+
+# Shipping Build Artifacts
+
+Lint, type-check, and tests run against the source tree. What users install is a
+*different* set of bytes — assembled by a script that most gates never look at,
+then uploaded by a workflow that trusts whatever the script left behind. Every
+failure below ships a broken or stale artifact under fully green CI.
+
+## A script that warns and exits 0 is not a gate
+
+The shape is universal: a declared list of inputs, a copy loop, a friendly
+warning when one is missing.
+
+```js
+for (const f of DIST_FILES) {
+ if (!fs.existsSync(f)) {
+ console.warn(`Warning: ${f} not found, skipping`); // build "succeeds"
+ continue;
+ }
+ fs.copyFileSync(f, path.join("dist", f));
+}
+```
+
+Move one required file aside and the script prints a line nobody reads, exits 0,
+and produces a `dist/` without it. Nothing downstream notices: the test job ran
+against the source tree, and the release job zips `dist/` and attaches it to a
+public release. The artifact is wholly non-functional — the entrypoint imports a
+file that isn't there — and the failure is discovered by users.
+
+```js
+const missing = DIST_FILES.filter((f) => !fs.existsSync(f));
+if (missing.length) {
+ console.error(`Missing build inputs: ${missing.join(", ")}`);
+ process.exit(1);
+}
+```
+
+The rule: inside a build script, `warn` may only describe something the artifact
+survives without. If you cannot say what still works when that file is absent, it
+is an error and the process must exit non-zero.
+
+## Bound the artifact size on *both* sides
+
+A packaging check with only a ceiling — "fail if the zip exceeds 500 KB" — is a
+cost guard, not a correctness one. A build that silently dropped half its files
+is *smaller*, so it passes the only check that exists.
+
+```js
+assert(bytes < 500 * 1024, "package too large");
+assert(bytes > 20 * 1024, "package suspiciously small — inputs likely missing");
+assert(entries.length === DIST_FILES.length, "package entry count mismatch");
+```
+
+Better still, assert on contents rather than a proxy: list the archive's entries
+and compare against the set the entrypoints require.
+
+## Derive the file list, or check it against the entrypoints
+
+`DIST_FILES` — like a build backend's `only-include`, or a hand-written
+`package_data` — is a *second* copy of "what this app is made of." The first copy
+is the manifest, the entry HTML, and the import graph. They drift in one
+direction: someone adds `utils.js`, references it from the popup, and forgets the
+copy list. The build stays green and the feature is dead in the packaged app.
+
+Either derive the list (bundle from the real entrypoints), or add a check that
+every path referenced by the manifest and by `<script src>` / `importScripts`
+exists in `dist/` after the build. A hand-maintained allowlist with no such check
+is a bug scheduled for a future commit.
+
+The same rule covers any place dependency or asset metadata is restated by hand —
+a standalone launcher script whose inline dependency header duplicates the
+project manifest's `dependencies`, for instance. If duplication is unavoidable,
+add a test that normalizes both lists and compares them, so drift fails in CI
+instead of at a user's install.
+
+## Committed build outputs go stale silently
+
+When a compiled or minified bundle is committed and served directly, *the bundle
+is the program* and its source is a comment until someone rebuilds. Editing only
+the source ships nothing; the page keeps serving the previous bundle, and no test
+or linter says a word.
+
+- Rebuild in CI and `diff` against the committed output; fail on drift.
+- Pin the builder to an exact version — the diff is only meaningful if the output
+ is byte-deterministic.
+- Confirm that determinism once across the environments people actually use
+ (native toolchain vs. container image), so the check is runnable locally too.
+
+```bash
+npx -y [email protected] src/app.jsx --jsx=transform --minify --outfile=/tmp/app.js
+diff /tmp/app.js web/app.js
+```
+
+Rebuild and commit the output in the **same commit** as the source change. A
+"rebuild bundles" follow-up commit means every commit in between shipped code
+that does not match its source.
+
+## Release scripts run on an OS you didn't write them on
+
+Build scripts are written on a developer machine and executed on the runner.
+GNU-only tooling is the usual break, and `set -e` turns it into a total abort on
+a line that merely reads a version number:
+
+```bash
+# Breaks under BSD grep (macOS): -P / lookbehind are GNU extensions.
+VERSION=$(grep -Po '(?<=^version = ")[^"]+' pyproject.toml)
+```
+
+Read structured metadata with a parser instead of a regex, and prefer a runtime
+you already depend on:
+
+```bash
+VERSION=$(python -c 'import tomllib;print(tomllib.load(open("pyproject.toml","rb"))["project"]["version"])')
+VERSION=$(jq -r .version package.json)
+```
+
+Then pin it with a test: the version the build script extracts must equal the
+version declared in the project manifest. Without that, the failure mode is a
+release tagged `v1.4.0` whose artifact reports `1.3.2`, and nothing in the
+pipeline disagrees.
+
+## Verify the artifact, then publish — in that order, in that job
+
+Attaching a file to a public release, pushing a tag, or uploading to a registry
+are the least reversible steps in the project. The verification must sit between
+the build and the upload, in the same job. A separate green "test" job proves
+nothing about the artifact: it ran against the source tree.
+
+Minimum ordering:
+
+1. Build.
+2. List every entry in the artifact and assert the entrypoints are present.
+3. Install or load it **from a directory the source tree is not on the load path
+ of**, and exercise one real symbol or command — not merely that a top-level
+ name resolves.
+4. Only then upload.
+
+Step 3 is the one that gets skipped, and it is the only step that distinguishes
+"the archive has files in it" from "the thing runs." Run it somewhere else on
+disk, or it passes against the sources and proves nothing.
+
+## Checklist
+
+```
+Build script:
+- [ ] Missing declared input → non-zero exit, not a warning
+- [ ] Size assertions have a floor as well as a ceiling
+- [ ] File list is derived, or checked against manifest/entry-HTML references
+- [ ] Duplicated dependency metadata has a drift test
+- [ ] No GNU-only flags (grep -P, sed -i'' semantics) in scripts CI also runs
+- [ ] Version extracted with a parser, and asserted equal to the declared version
+
+Committed build outputs:
+- [ ] CI rebuilds and diffs; drift fails
+- [ ] Builder pinned to an exact version; output confirmed deterministic
+- [ ] Output committed alongside the source change, not in a follow-up
+
+Release:
+- [ ] Artifact contents listed and asserted before upload
+- [ ] Artifact installed/loaded from outside the repo and exercised
+- [ ] Verification runs in the same job as the upload, before it
+```
+
+## Note for this repository (ffmpeg-skill)
+
+`package.json`'s `"files"` list is the equivalent of `DIST_FILES` here — it must
+list exactly what ships (`bin/`, `scripts/`, `mcp/`, `references/`, `SKILL.md`,
+`README.md`, `LICENSE`), and `.claude/` (this file included) must NEVER appear
+in it. `npm publish --dry-run` is the "list every entry and assert the
+entrypoints are present" step (step 2 above) — run it before every publish, and
+watch for stray `__pycache__`/`.pyc` files sneaking into the tarball from a
+local test run (this actually happened once this session and was caught by
+exactly this check). There is no separate "install from outside the repo and
+exercise a symbol" step in this repo's release process today (`node
+bin/install.js --dir /tmp/skills` from README's Development section is the
+closest equivalent) — worth doing before a real publish, not just a dry-run.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/concurrent-branches/SKILL.md b/.claude/skills/concurrent-branches/SKILL.md
new file mode 100644
index 0000000..f349376
--- /dev/null
+++ b/.claude/skills/concurrent-branches/SKILL.md
@@ -0,0 +1,244 @@
+---
+name: concurrent-branches
+description: Resolve conflicts and merges when several branches are open against one repo at the same time — the hotspot files every change must touch (registry manifests, a single version field, shared tool config, one aggregated test module, tracked build output), union-vs-recompute-vs-rebuild as three different correct resolutions, generated artifacts that must never be merged, non-deterministic serialization that makes every branch conflict, renumbered identifiers that git cannot show you, and why a clean auto-merge is not a passing test. Use when rebasing or merging a long-lived branch, resolving conflict markers, reviewing a merge commit, deciding what a repo should commit vs generate, or setting up a repo that will take parallel contributions.
+---
+
+# Merging Concurrent Branches
+
+When several branches are open against the same repo at once, the conflicts do
+not land in the code you were thinking about. They land in a small, predictable
+set of **hotspot** files that nearly every change has to touch — a registry
+manifest, a version field, shared tool config, one aggregated test module, a
+tracked build output.
+
+Each hotspot has exactly one correct resolution, and they are not the same rule.
+"Take ours" / "take theirs" is right for almost none of them. Worse, getting one
+wrong is silent: the dropped entry, the collided version, the stale bundle all
+merge green and are found later by someone who cannot reproduce them.
+
+## Find the hotspots before you need to resolve them
+
+Files touched by nearly every commit are the files your branch will conflict on.
+
+```bash
+# the 15 files most commits touch — your hotspot list
+git log --format= --name-only -n 200 | sort | uniq -c | sort -rn | head -15
+```
+
+Write the resolution rule for each one into the contributing docs. Under
+conflict pressure, with a stale branch and a red CI run, nobody re-derives
+"the version field is recomputed, not merged" correctly.
+
+## Additive registries: union both sides, never choose one
+
+A manifest that lists every component — plugin entries, module paths, exported
+names, a feature list. Two branches each append an entry, and the conflict spans
+both additions:
+
+```jsonc
+<<<<<<< HEAD
+ "./components/exporter",
+ "./components/importer" // theirs, already merged to main
+=======
+ "./components/exporter",
+ "./components/validator" // yours
+>>>>>>> feature/validator
+```
+
+Both sides are correct and neither is a substitute for the other. Resolve by
+keeping **every** entry from both sides. Taking a side deletes a component that
+is still fully present in the tree — the code compiles, the tests pass, and the
+component is simply never registered or installed.
+
+Nothing catches that unless you check the registry against the filesystem:
+
+```bash
+# every registered path exists
+jq -r '.plugins[].components[]' manifest.json | while read -r p; do
+ [ -e "${p#./}" ] || echo "registered but missing: $p"
+done
+# every component on disk is registered
+for d in components/*/; do
+ grep -q "\"./${d%/}\"" manifest.json || echo "present but unregistered: $d"
+done
+```
+
+Run it as a repo test, not as a merge-day ritual. It is the only thing standing
+between a mis-resolved conflict and a component that quietly does not ship.
+
+## Single-value counters: recompute from the integration branch
+
+A version field, a sequence number, a "latest migration" pointer. Both branches
+bumped `2.17.0` to `2.18.0`; both are wrong now, because a third branch already
+merged and main is at `2.18.0` too.
+
+Union is meaningless here and picking a side reintroduces a collision. The rule
+is **recompute from the current integration branch**, not from either side of
+the conflict — every change that merged since you branched consumed one
+increment:
+
+```bash
+git fetch origin main
+git show origin/main:manifest.json | jq -r '.metadata.version' # -> 2.18.0
+# your branch takes 2.19.0, regardless of what your branch said before
+```
+
+Do this as the *last* step before pushing, not during the merge. If another
+branch lands while you resolve, you redo only one line.
+
+## Generated artifacts: rebuild, never merge
+
+A committed minified bundle, a built PDF, a compiled schema, a checked-in
+snapshot. Git will happily produce a merge for the text ones and force a
+binary choice for the rest — and **every** such result is wrong, because a
+derived file's only correct content is whatever the merged sources generate.
+
+Resolve the sources, then regenerate:
+
+```bash
+git checkout --merge -- src/ ui/app.jsx # resolve the real inputs first
+make build # regenerate the artifact
+git add dist/bundle.js docs/handbook.pdf
+```
+
+Two things make this reviewable rather than a leap of faith:
+
+- **Pin the generator version.** If the bundler or typesetter is pinned, its
+ output is byte-identical anywhere, and a reviewer can regenerate and `diff` to
+ confirm the artifact matches the source. Unpinned, the artifact diff is a mix
+ of your change and a tool upgrade, and nobody can tell them apart.
+- **Verify only the expected regions moved.** A rebuilt document reflows: a
+ one-paragraph edit typically spreads across two or three consecutive pages.
+ Raster-diff or `diff` the rebuilt artifact against one built from the base
+ commit in the same environment, and say in the PR which regions changed and
+ why. Anything else that moved is your merge, not your edit.
+
+## Non-deterministic serialization turns every branch into a conflict
+
+If a tracked file is written by iterating a map, set, or dict whose order is not
+stable, the whole file is rewritten on every run. Then every branch conflicts on
+every line, diffs are unreviewable, and real conflicts hide inside the churn.
+
+Sort before writing:
+
+```python
+# BAD — map iteration order; the file is rewritten differently every time
+records = [to_record(k, v) for k, v in index.items()]
+
+# GOOD — a stable key. ISO-8601 dates sort chronologically as plain strings,
+# so no date parsing is needed to get a deterministic, reviewable file.
+records = sorted((to_record(k, v) for k, v in index.items()), key=lambda r: r["date"])
+```
+
+This applies to *any* code path that rebuilds a committed file from an unordered
+collection, including the ones added later. Once one path forgets, the file is
+churny again.
+
+## Shared tool config: take the base file, re-apply your delta
+
+`pyproject.toml`, `package.json`, lint config, a CI workflow — files where your
+branch added three lines and four other branches added their own. Reconciling
+hunks by hand is where dev-dependency pins and tool sections get silently
+dropped.
+
+Take the integration branch's copy wholesale — it already carries everything
+that landed while you were away — then re-add only the lines your branch
+introduced:
+
+```bash
+git checkout origin/main -- pyproject.toml
+# re-add just your delta, then confirm nothing else moved
+git diff origin/main -- pyproject.toml
+```
+
+That last `git diff` should show your addition and nothing else. If it shows a
+pin reverting or a tool section disappearing, you took a side by accident.
+
+## Aggregated test modules: keep both suites, then check for shadowing
+
+Two branches append cases to the same test file. Union them — but a union can
+produce two tests with the same name, and in Python and JavaScript the later
+definition simply replaces the earlier one. The file looks longer, the suite
+count looks plausible, and one branch's case never runs.
+
+```bash
+grep -oE '^\s*(def test_[A-Za-z0-9_]+|it\(.[^,]*|test\(.[^,]*)' tests/test_thing.py \
+ | sort | uniq -d
+```
+
+The same shape bites production code: two branches independently add the same
+module-level helper, the resolution keeps both, and the second shadows the
+first.
+
+## Append; never renumber a shared identifier
+
+Repos that carry stable identifiers cited from elsewhere — claim IDs in a source
+ledger, migration numbers, fixture keys, snapshot names — break in a way conflict
+markers cannot show you. Renumbering `C7`-`C12` to make room is a clean,
+conflict-free edit that invalidates every citation of those IDs in files your
+merge never touched.
+
+Add new identifiers by continuing the numbering past the highest one that exists
+anywhere, and never reuse or renumber one. If two branches both claimed `C17`,
+renumber **yours** and fix your own references; do not renumber the side that
+already merged.
+
+## A clean auto-merge is not verification
+
+Two branches editing far-apart regions of one large file merge cleanly and can
+still be semantically wrong: one side's change depends on a helper the other
+removed, or both added equivalent logic under different names, or one side's
+edit now sits inside a branch the other made unreachable.
+
+After any non-trivial merge, confirm both sides survived — grep the merged tree
+for a distinctive string from each:
+
+```bash
+git grep -n "computes the retry budget" # a phrase only their change added
+git grep -n "REDACTION_PLACEHOLDER" # a symbol only yours added
+```
+
+Present and consistent, not just present. Then read the two regions together.
+
+## Match the repo's integration style, and re-run the real gate
+
+```bash
+git log --graph --oneline -20 # merge commits, or a linear rebased history?
+```
+
+Follow whichever the history already uses. Then run the repo's actual CI
+commands locally before pushing: **a resolved merge is code that has never
+existed anywhere before**, and neither branch's CI run covered it. A green check
+on your branch and a green check on main say nothing about their union. See
+**reproducing-ci-locally** for deriving the commands the runner actually uses.
+
+## Checklist
+
+- [ ] Hotspot files identified from `git log --name-only` before branching
+- [ ] Registry/manifest conflicts resolved by union; every entry from both sides kept
+- [ ] Registry checked against the filesystem in both directions, in CI
+- [ ] Version/counter fields recomputed from `origin/main`, not taken from either side
+- [ ] Generated artifacts rebuilt from merged sources, never text- or binary-merged
+- [ ] Generator version pinned so a reviewer can regenerate and diff
+- [ ] Files serialized from maps/sets sorted by a stable key
+- [ ] Shared tool config taken from base, delta re-applied, `git diff` shows only your lines
+- [ ] Merged test modules checked for duplicate test names
+- [ ] New shared identifiers appended; none reused or renumbered
+- [ ] A distinctive string from each side found in the merged tree
+- [ ] Repo's real CI gate run locally on the merged result before pushing
+
+## Note for this repository (ffmpeg-skill)
+
+This is exactly the pattern seen across the PR #28-#37 merge cascade for the
+0.10.0 release: `CHANGELOG.md` was the hotspot file nearly every PR touched,
+and the correct resolution every time was "union both sides, never choose
+one" (keep every bullet, verify no leftover conflict markers). `package.json`'s
+`version` field is the single-value-counter case: it should be recomputed
+once, after all merges land, not carried through each individual merge.
+
+## Learn More
+
+- **reproducing-ci-locally** (also added to this repo's `.claude/skills/`) —
+ running the runner's real commands on the merged tree
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/cross-surface-changes/SKILL.md b/.claude/skills/cross-surface-changes/SKILL.md
new file mode 100644
index 0000000..04e4f3b
--- /dev/null
+++ b/.claude/skills/cross-surface-changes/SKILL.md
@@ -0,0 +1,227 @@
+---
+name: shipping-across-surfaces
+description: Land a change everywhere the same fact is stated — enumerating the full surface inventory (landing copy, docs, machine-readable summaries, changelog badges repeated across every page, sitemap, README, descriptions embedded in code, and untyped frontend consumers of typed responses), generating a surface instead of restating it, drift tests where you cannot generate, never hand-maintaining a copy of a surface another codebase owns, shipping a paired PR when you change a format a different codebase decodes, and keeping overloaded product words apart. Use when adding or renaming a user-facing feature, editing product/marketing copy or docs, renaming a serialized response field, changing a serialization or share-link format, wiring one repo's output into another's checks, or reviewing a PR that touched only one place a fact appears.
+---
+
+# Shipping Across Surfaces
+
+Most product facts are stated more than once. The feature exists in code, is
+described on a landing page, summarized for agents, listed in a changelog,
+repeated in a nav badge, restated in a README, and embedded again in the
+description string of every tool or endpoint that exposes it. Each copy drifts
+independently, and none of them are covered by tests.
+
+The failure is never loud. Nothing goes red; the product simply describes itself
+inaccurately in the four places you didn't edit, and the one place a reader
+happened to look is the stale one.
+
+## Enumerate the surface inventory once, in the repo
+
+"I'll remember the other places" does not survive the second feature. Write the
+list down — in `CONTRIBUTING.md`, a PR template, or the skill/guide the project
+already keeps — and treat it as the definition of done for a user-facing change.
+A realistic inventory for a product with a public site:
+
+- Landing page: hero, section ledes, the feature cards, the free/paid list
+- `<meta>` / OG / Twitter tags, and the structured data (`SoftwareApplication`
+ description, `FAQPage` entries) — search engines read the copy you forgot
+- Docs page, and any machine-readable summary for agents (`llms.txt`)
+- Changelog entry **and** the version badge repeated in the nav of every page
+- Sitemap, and the footer product column present on every page
+- README, comparison pages, onboarding/skill files
+- **The descriptions embedded in code** — every tool, command, or endpoint
+ description, not just the primary one
+
+That last bullet is the one that gets missed. A rename lands in the tool it was
+named after and stays wrong in the three sibling tools that mention it in
+passing. Grep for the old string across the whole tree, not just the docs
+directory, before calling the change done.
+
+All of these ship in the **same PR**. A follow-up "update docs" commit means the
+interval between them shipped a product that contradicted itself.
+
+## Prefer a generated surface to a restated one
+
+The surfaces above are drudgery precisely because they're copies. Delete the copy
+where you can:
+
+- An API reference rendered from the live schema self-syncs and needs no hand
+ edit when the API changes. That page is *free* forever.
+- A version badge repeated across forty pages belongs in a template/partial or a
+ build-time injection, not in forty files.
+- A "supported features" list is better derived from the registry it describes
+ than typed a second time.
+
+Where generation isn't practical, make drift fail a test rather than a review.
+
+```python
+def test_readme_documents_every_registered_tool():
+ registered = {t.name for t in get_registered_tools()}
+ documented = parse_tool_names(README.read_text())
+ assert documented == registered # fails on add, remove, and rename
+```
+
+Compare against the *live* registry, not a second hand-written list — a test that
+compares two hand-maintained lists only proves you updated both copies of the
+same mistake. The same rule covers duplicated dependency metadata and committed
+build outputs; see **build-artifacts** (also in this repo's `.claude/skills/`).
+
+## A response model is only half the contract
+
+A typed backend and an untyped frontend can disagree without either side
+failing. Renaming a Pydantic field updates serialization and keeps every Python
+test green, while a Jinja template's inline JavaScript still reads the old name
+inside a template literal. The browser then renders `undefined`: valid
+JavaScript, no exception, no backend failure.
+
+Treat every serialized field rename as a producer-and-consumer change:
+
+```bash
+# Search the whole tree, not just Python call sites. Templates and committed
+# JavaScript bundles are consumers too.
+rg 'old_field|new_field' .
+```
+
+Then pin the boundary with a test that uses the real serialized response and the
+real consumer. A browser test is ideal when available. A cheaper contract test
+can still make the hidden dependency explicit:
+
+```python
+def test_dashboard_consumes_the_audit_response_contract():
+ payload = AuditResponse.example().model_dump()
+ template = Path("templates/dashboard.html").read_text()
+
+ for field in ("summary", "recommendations"):
+ assert field in payload
+ assert f"result.{field}" in template
+```
+
+This test is deliberately narrow: it does not claim to execute JavaScript. It
+makes a field rename fail in the same change that alters the response model,
+instead of relying on someone to notice `undefined` in a rendered page. Prefer
+generating a typed client or shared schema when the frontend architecture allows
+it; otherwise keep this boundary test beside the producer's contract tests.
+
+## Don't hand-maintain a copy of a surface you don't own
+
+The tempting shortcut when validating against another system — another service's
+tool names, another team's enum, a partner API's status codes — is to paste the
+current values into a constant and check against it.
+
+```python
+# Anti-pattern: a private snapshot of someone else's public surface.
+KNOWN_TOOLS = {"search", "create", "archive"} # correct until they ship
+```
+
+It is stale the moment the owner ships, and the staleness surfaces as *your*
+validator rejecting valid input. Worse, nothing in your repo can detect it: you
+have no reference to compare against.
+
+Truth flows **outward from whoever owns it**. The owning codebase publishes a
+generated, versioned artifact — a committed `tools.json` carrying the source
+version and commit — and the consumer reads that file. Ask "who owns this fact,
+and which direction is it moving?" before writing the check. A design where your
+repo reaches into theirs to scrape the truth is the wrong direction and will
+break on access, auth, or refactor; a design where they publish and you consume
+is stable.
+
+Checks that need **no** external truth are fine to land standalone: a denylist of
+known-bad legacy patterns, a structural schema check, a "this field is required"
+assertion. Those describe your own expectations, not their surface.
+
+## A format change needs its consumer's PR in the same breath
+
+When one codebase encodes and a different one decodes — a share-link payload, an
+export file, a cache key, a webhook body — the format is a contract between two
+repos, and half a contract is an outage.
+
+- Open the paired PR in the consumer repo at the same time, proactively. Don't
+ land the producer side and file an issue for the other end.
+- Version the payload so an old decoder can *detect* a new format instead of
+ misparsing it into plausible garbage.
+- Where the two are on different release cadences (an app store review vs. a
+ static site deploy), ship the decoder first and the encoder second.
+
+If the counterpart repo is private and this one is public, refer to it by what it
+does — "the site that serves the share links" — never by slug, path, or URL.
+Naming the public product a piece of content is *about* is expected; leaking the
+name of a private repository is not. That distinction is worth a CI check in any
+public repo that has a private counterpart.
+
+## Keep overloaded words apart
+
+Products accumulate words that name two different things. One system may have a
+per-feed, unsigned POST configured on a resource *and* an account-wide, signed,
+retried event stream with a delivery log — and call both a "webhook." Once copy
+uses the bare word, every sentence about either becomes ambiguous and support
+questions stop being answerable.
+
+Write the two definitions down with a canonical label for each, put them
+somewhere new copy is written against, and never let the bare overloaded word
+stand alone in user-facing text. This applies to nav labels and tool descriptions
+as much as to prose — the label is the surface most people read.
+
+## Make factual claims traceable
+
+Copy that asserts things about behavior ("processes N per second", "caps
+withdrawals per settlement") drifts from the code faster than any other surface,
+because nothing recompiles when it becomes false.
+
+Keep a claim ledger with stable identifiers, cite the identifier inline from the
+copy, and record provenance in the ledger rather than repeating it in the prose.
+Two rules make it survive:
+
+- **Append, never renumber.** A new claim continues the numbering; reusing or
+ renumbering an identifier silently repoints every existing citation.
+- **When two ledgers cover the same fact, cite the more rigorously derived one** —
+ a measured benchmark row over a read-the-source row — so the weaker claim can't
+ outlive its replacement.
+
+A repo-level check that every factual sentence carries a citation turns this from
+a habit into a gate.
+
+## Checklist
+
+```
+Before calling a user-facing change done:
+- [ ] Surface inventory exists in the repo and was walked, not recalled
+- [ ] Old strings grepped for across the whole tree, including code descriptions
+- [ ] Serialized field renames grepped through templates and frontend code
+- [ ] Untyped response consumers covered by a boundary contract test
+- [ ] Every sibling tool/endpoint description mentioning the feature updated
+- [ ] Changelog entry added and the repeated version badge bumped everywhere
+- [ ] All surfaces in ONE PR, not a docs follow-up
+
+Reducing the surface count:
+- [ ] Anything renderable from a live schema/registry is generated, not typed
+- [ ] Repeated fragments live in a template/partial, not N files
+- [ ] Unavoidable duplication has a drift test against the live source
+
+Across repo boundaries:
+- [ ] No hand-maintained snapshot of a surface another codebase owns
+- [ ] Truth flows outward from the owner as a versioned, generated artifact
+- [ ] Format changes ship a paired consumer PR; payload is versioned
+- [ ] Decoder deploys before encoder when cadences differ
+- [ ] Public content names no private repo slug, path, or URL
+
+Wording:
+- [ ] Overloaded product terms have written definitions and canonical labels
+- [ ] Factual claims cite a stable ledger identifier; identifiers are append-only
+```
+
+## Note for this repository (ffmpeg-skill)
+
+The "22 tools" count (and the per-category tool tables) in README.md and
+SKILL.md is exactly this kind of restated surface — it drifted to "21" more
+than once this session when a tool was added and only the code was updated.
+`tests/test_contract.py`'s `test_mcp_tools_match_contract` and
+`test_mcp_schema_drift_follows_the_scripts` are the "generated surface" /
+"drift test" answer for the MCP tool list specifically (MCP's `tools/list` is
+derived from the contract, never hand-written) — the same rigor doesn't yet
+exist for the README/SKILL.md tool-count prose, which is still grepped and
+hand-edited. `docs/contract.md`'s `capability_map`/`provides` sections are the
+other real example: they explicitly promise "says nothing tools[] doesn't
+already say," i.e. they are declared to be a re-index, not a second source of
+truth — exactly the "truth flows outward from whoever owns it" principle.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/defect-reports/SKILL.md b/.claude/skills/defect-reports/SKILL.md
new file mode 100644
index 0000000..23f2b8c
--- /dev/null
+++ b/.claude/skills/defect-reports/SKILL.md
@@ -0,0 +1,222 @@
+---
+name: writing-defect-reports
+description: Establish a finding before you publish it, and correct it after — headlines that overstate what actually reproduces at the layer a user sees, reporting code that no entry point can reach or that is already dead, filing a caveat the project's own records already answered, re-verifying your prior notes against the tree instead of against the note, choosing the narrowest injection point that reproduces a failure without breaking the run first, capturing probe output a harness swallows, and withdrawing a published claim in the thread where you published it. Use when filing an issue, writing the body of a PR or code review that asserts a defect, triaging someone else's report, or deciding whether a suspicious observation is reportable at all.
+---
+
+# Writing Defect Reports
+
+A report is a claim, and it is read by people who will not re-derive it. The cost
+of an overstated one is not embarrassment — it is a maintainer spending an
+afternoon on a premise that does not hold, or a "fix" landing for a failure mode
+that never occurred. The techniques for *finding* a defect live in
+**verifying-external-behavior** (also in this repo's `.claude/skills/`). This
+skill is about the step between finding one and publishing it.
+
+The rule underneath all of it: **publish the claim you actually measured, at the
+layer you measured it.**
+
+## The anomaly is real; the headline may not be
+
+The common failure is not a fabricated bug. It is a genuine internal oddity
+promoted one layer too far.
+
+You notice that a helper returns a degenerate value for a small sample, trace it
+into a scoring path, and write the report as *"short inputs are wrongly flagged."*
+Then you run real short inputs through the public entry point and the flag never
+sets — a downstream threshold absorbs the degenerate value, and the only visible
+effect is noise in a secondary per-feature list. The internal oddity is worth
+fixing; the headline was false, and a reviewer who tests it will say so.
+
+**Before writing the title, run the reproduction at the outermost layer the title
+names.** Then choose one of three honest framings:
+
+| what you measured | how to file it |
+| ------------------------------------------ | ------------------------------------------- |
+| reproduces end to end | file it as the user-visible symptom |
+| reproduces internally, absorbed downstream | file the internal defect, state the absorption |
+| does not reproduce at all | do not file; record the probe and move on |
+
+The second row is a good report, not a weak one. "This helper returns a value it
+should not; today a threshold happens to mask it, so there is no user-visible
+symptom yet" tells a maintainer exactly how to prioritize. Silently keeping the
+dramatic title because the underlying issue is real is what burns credibility.
+
+## Check the code is reachable before calling it broken
+
+Three shapes look like defects and are not — or are, but not the one you were
+about to describe:
+
+**A branch that cannot execute.** An early return guarding a lookup that already
+returns the same value on the missing case; a condition a preceding gate already
+implies. This is dead code, and "dead code" is the accurate report. Filing it as a
+correctness bug, or naming a test as though it exercises that branch, misleads
+everyone downstream — confirm liveness by deleting the line and watching the
+suite, not by reading it.
+
+**A guard whose pattern only matches your fixture.** A validity check written
+against a hand-typed sample can be structurally unable to fire against the real
+input: a single-line pattern against a generator that wraps its output across
+indented lines, an exact-string check against a source that varies whitespace.
+Verify the guard against a captured real input, not the fixture. The consequence
+matters for the fix, too: replacing synthetic fixtures with real captures deletes
+that guard's only coverage, so the fix and the fixture change belong in one
+change, not two.
+
+**A file nothing invokes.** Repos accumulate scripts that reference paths the
+repo does not contain and toolchains it does not depend on. Before reporting one
+as broken, find the caller — the task runner, the workflow, the entry point. If
+there is none, the report is "this is dead, delete it," which is cheap and
+uncontroversial, rather than "the build is broken," which is wrong.
+
+## Search the project's own records before filing a caveat
+
+The most avoidable report is the one the project already answered. Two measured
+figures that look inconsistent are usually inconsistent *definitions*, and the
+definition is usually written down: a claim ledger row, a docstring, a design
+note, a closed issue.
+
+Grep for the term before writing "these two numbers do not appear to compute the
+same quantity." If a record pins the definition, cite it — the caveat you were
+about to publish reads as an open question the project already closed, and a
+maintainer has to re-close it.
+
+The same discipline applies to numbers you are *quoting*. Figures in an older
+issue may not reproduce, because a dependency the value depends on is unpinned
+and the installed version has changed. Re-measure before restating, and record it
+with the command, output, and date — see **verifying-external-behavior** for why
+an undated measurement cannot be re-checked, and **cross-surface-changes** for
+choosing between two records that cover the same fact.
+
+**Quote the protocol next to the figure**, not only in whatever artifact produced
+it: the split, the warmup, the seed, the version. Two documents quoting the same
+metric under different protocols read as a regression to anyone comparing them,
+and the reader has no way to tell that they are not comparable.
+
+## Your earlier note is a claim, not evidence
+
+Working notes, scratch findings, and a prior comment on the same issue are
+secondary sources — including your own. They were true about a tree that has
+since moved, or they were wrong when written.
+
+When a note and the code disagree, the code settles it. Re-derive from the
+integration branch directly rather than from a checkout that may be behind:
+
+```bash
+git show origin/main:path/to/file.py | grep -n 'the_symbol'
+```
+
+If two notes contradict each other, do not average them and do not pick the more
+recent — re-check the tree and then correct the wrong note in place, saying that
+it was wrong. A knowledge base that records both readings without resolving them
+is worse than one that records neither, because the next reader will pick one at
+random.
+
+## Pick the narrowest injection point that reproduces the failure
+
+To exercise a failure path by hand you need to break something. Break the
+smallest possible thing, or the run dies before reaching the path you care about.
+
+The classic miss is a blanket hook or a global monkeypatch:
+
+```bash
+# Too broad — rejects EVERY commit, including the unrelated bookkeeping commit
+# the process makes first. The run fails earlier than the path under test, and
+# you have reproduced a different bug.
+echo 'exit 1' > .git/hooks/pre-commit
+
+# Narrow — fails exactly the operation whose failure you want to observe.
+cat > .git/hooks/commit-msg <<'EOF'
+grep -q 'sync from source-b' "$1" && exit 1
+exit 0
+EOF
+```
+
+The same rule holds elsewhere: fail one HTTP host rather than the network; make
+one file unreadable rather than the directory; raise from one call rather than
+patching the module. **After the run, confirm it failed where you intended** —
+otherwise you have measured your instrumentation.
+
+**Check where your probe's output actually goes.** Test harnesses commonly
+replace the global logger or console object at setup, and verbosity flags do not
+undo that. If a probe prints nothing, append to a file outside the harness's
+reach and read it afterwards, rather than concluding the code path did not run.
+
+## Report the checks that model a real regression
+
+When you back a report with mutation evidence, include only mutations that (a)
+plausibly model how an implementation would actually regress and (b) demonstrably
+turn a named test red. A mutation that nothing catches is worth reporting as a
+coverage gap; a mutation nobody would ever write is noise that makes the rest of
+the report look padded.
+
+State which test each mutation trips, and which assertion inside it — a guard
+often turns out to be load-bearing at a different layer than the report assumed,
+and the assertion name is what reveals it.
+
+## A red gate is not an aside
+
+Whether a red check is pre-existing is answered by running it on the base commit
+— see **reproducing-ci-locally** (also in this repo's `.claude/skills/`). What
+belongs here is where that answer goes in the write-up. A red check is never a
+parenthetical under a "done" claim: give it its own statement naming what is red,
+what makes it red, and whether you fixed it. And **confirm green after the run
+finishes** rather than writing "should be green" — a prediction stated as an
+outcome is the same defect as an overstated headline, one artifact over.
+
+## Withdraw published claims where you published them
+
+A wrong claim that has been read does not become unwritten when you stop
+repeating it. If a caveat, a number, or a framing you published turns out to be
+wrong or already-answered:
+
+- Say so in the same thread, naming what was wrong and what is true instead.
+- Do not quietly delete it and re-file a corrected version elsewhere; readers who
+ saw the first one are never routed to the second.
+- Keep it to the correction. A retraction is one or two sentences — what you
+ claimed, what is actually the case, what changes as a result.
+
+The same applies to a claim you inherited. If you repeat someone else's figure and
+it fails to reproduce, correcting it is part of your report, not a separate errand.
+
+## Checklist
+
+```
+Before publishing a defect report:
+- [ ] Reproduction run at the outermost layer the title names; title matches
+ what reproduced there, not what you found internally
+- [ ] Absorbed-downstream findings filed as internal defects, with the absorption
+ stated — not promoted to a user-visible symptom
+- [ ] The code is reachable: an entry point calls it, and the branch is live
+ (checked by deletion, not by reading)
+- [ ] Guards verified against a captured real input, not the fixture that was
+ written alongside them
+- [ ] Project records (ledger, docstrings, design notes, closed issues) searched
+ for a definition that already resolves the discrepancy
+- [ ] Every quoted number re-measured, with version, command, and date; protocol
+ stated next to the figure
+- [ ] Prior notes re-verified against the integration branch, and any wrong note
+ corrected in place
+- [ ] Failure injected at the narrowest point; run confirmed to have failed where
+ intended
+- [ ] Mutation evidence limited to plausible regressions, each attributed to a
+ named test and assertion
+- [ ] No red check described as pre-existing under a "done" claim; green
+ confirmed after the run finished, not predicted
+- [ ] Any earlier wrong claim withdrawn in the thread where it was published
+```
+
+## Note for this repository (ffmpeg-skill)
+
+This is the same discipline behind this repo's 0.9.1/0.10.0 "honesty fix"
+pattern: `cut.py`'s `mode`/`keyframe_snapped`/`duration_delta_seconds` fields,
+`check.py`'s `reason` field, and `render.py`'s check-stage exit code were all
+added because a prior report ("the cut is lossless," "the check passed," "the
+render succeeded") was true at one layer and silently false at the layer a
+caller actually reads results from — exactly the "genuine internal oddity
+promoted one layer too far" pattern this skill describes, just discovered
+after shipping rather than before. When investigating a new claim about this
+codebase, reproduce it with real media via `tests/test_all.py`'s fixtures
+before reporting it, the same way `test_cut_copy_keyframe_snap_reports_a_real_nonzero_delta`
+measured an actual 1.24s divergence rather than assuming one.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/destructive-operations/SKILL.md b/.claude/skills/destructive-operations/SKILL.md
new file mode 100644
index 0000000..e9c5af2
--- /dev/null
+++ b/.claude/skills/destructive-operations/SKILL.md
@@ -0,0 +1,211 @@
+---
+name: guarding-destructive-operations
+description: Add and review preconditions on operations that delete, overwrite, rewrite history, or resolve a caller-supplied name to a filesystem path — refusing instead of warning, placing the guard ahead of the first mutation, structural classification rather than string-prefix matching, name validation plus resolved-path containment as two independent checks, why a guard on the destructive path is invisible to the dry-run, and mutation-testing each half separately. Use when writing or reviewing a `--rebuild`/`--reset`/`--purge` command, a bulk delete, a history rewrite, an `rm -rf`-shaped step, or any code that turns an argument into a file path.
+---
+
+# Guarding Destructive Operations
+
+Some operations have no undo: an orphan-branch rewrite, a recursive delete of
+every tracked file, an overwrite of a stored artifact, a `DROP`/`purge` path. The
+implementation is usually short and usually correct *for the setup its author had
+in mind*. The bug is never the deletion itself — it is that nothing checked
+whether the target was the thing the author imagined.
+
+Two shapes recur, and they take the same fix:
+
+- **Blast radius.** The operation is correct only in a dedicated, single-purpose
+ target and is catastrophic in a mixed one.
+- **Boundary escape.** A caller-supplied name is joined onto a base directory and
+ lands outside it.
+
+## Refuse; don't warn, and don't add an override
+
+A destructive operation that discovers its precondition is violated should return
+an error and change nothing. A warning is read by nobody, and a `--force` escape
+hatch turns the guard into documentation.
+
+```go
+// A rebuild that recreates history does `checkout --orphan` then
+// `rm -rf --ignore-unmatch .`, keeping only the state files it rewrites.
+// That is correct in a dedicated mirror repository whose ONLY tracked content
+// is `.state/`. Run it where source code also lives and the new branch loses
+// the source code.
+func (e *Engine) rebuild() error {
+ if err := e.ensureDedicatedRepo(); err != nil {
+ return err // nothing mutated yet
+ }
+ ...
+}
+```
+
+The honest justification for having no override flag: there is no situation where
+the operator wants this command to delete unrelated tracked files. If a real one
+appears later, that is a separate, differently-named command — not a boolean on
+this one.
+
+## Put the guard ahead of the first mutation
+
+"Refuses" is only true if the refusal happens before anything has changed.
+Walk the function and find the *first* statement with an effect — it is often not
+the obvious deletion. In-memory state clearing, a branch checkout, and a
+read-then-rewrite of the very files you are preserving all count.
+
+```go
+// Order that makes the refusal safe:
+// 1. reject detached HEAD / ambiguous state
+// 2. ensureDedicatedRepo() <-- the new guard, nothing mutated yet
+// 3. read the state files to preserve
+// 4. CheckoutOrphan()
+// 5. RemoveAllTrackedFiles()
+// 6. ClearAllProgressCounts()
+```
+
+Steps 3-6 are all mutations of something (3 is not, but it is where the "what to
+preserve" snapshot is taken, and a guard after it has already committed you to a
+shape). Land the guard at 2 and a rejected run leaves the working tree byte-identical.
+
+Also refuse *ambiguous* state before rewriting it. A history rewrite that assumes
+a named branch should reject detached HEAD up front rather than silently
+recreating the wrong ref.
+
+## Classify structurally, not by string prefix
+
+The guard needs to answer "is every tracked path inside the directory this
+command owns?". A `HasPrefix`/`startswith` on the bare directory name is the
+wrong answer and looks right in every test you would think to write.
+
+```go
+// Bad — admits `.state-backup/notes.md` and `.stateful.txt`, so a repository
+// full of unrelated content passes the guard and gets deleted.
+func owned(path string) bool {
+ return strings.HasPrefix(path, ".state")
+}
+
+// Good — the directory itself, or something genuinely under it.
+func owned(path string) bool {
+ return path == ".state" || strings.HasPrefix(path, ".state/")
+}
+```
+
+The same distinction in Python is `Path(p) == base or base in Path(p).parents`,
+not `p.startswith(str(base))`. Any time a check compares paths as strings, ask
+what a sibling with a longer name does to it.
+
+## Name validation and resolved containment are two checks, not one
+
+When a public argument selects a file — a baseline name, a template id, a report
+slug — do both, in this order:
+
+```python
+NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
+
+def _validate_name(name: str) -> str:
+ if ".." in name or not NAME_RE.match(name):
+ raise ValueError(f"invalid name: {name!r}")
+ return name
+
+def _resolve(name: str, base: Path) -> Path:
+ candidate = (base / f"{_validate_name(name)}.json").resolve()
+ if not candidate.is_relative_to(base.resolve()):
+ raise ValueError(f"name escapes {base}: {name!r}")
+ return candidate
+```
+
+The containment half is **not** redundant with the regex. The regex stops `..`
+segments and absolute paths; only the `resolve()` + containment check stops a
+*symlink placed inside the directory* that points out of it — a name matching
+`^[A-Za-z0-9]` all the way through can still resolve anywhere. Route every entry
+point through both: the loader, the saver, and any path-building helper a public
+method still calls directly. A single unrouted helper reinstates the whole hole.
+
+Without this, an implicit suffix (`name + ".json"`) plus an absolute-path
+argument reads any file on disk whose name happens to end in that suffix.
+
+## A guard on the destructive path is invisible to the preview
+
+If the real run reaches the guard but `--dry-run` short-circuits earlier, the
+preview cheerfully describes an operation the real run will refuse. That is a
+defensible design — the destructive path is the one that must be safe — but be
+explicit about it:
+
+- The preview will show a full rebuild in a repository where the rebuild is
+ forbidden. Only the real invocation errors.
+- Anything meant to warn the operator *earlier* has to live in the preview stage
+ or the CLI argument-validation layer, duplicated deliberately, not moved.
+
+Say which one you chose in the PR description; a reviewer cannot tell from the
+diff whether the dry-run gap is intentional.
+
+## Know what the caller does with your refusal
+
+Tightening validation only helps if the new error reaches somebody. A broad
+`except Exception` two frames up will turn a hard refusal into an ordinary
+result shape:
+
+```python
+try:
+ features = self._load(baseline)
+except Exception as e: # already there, catches your ValueError
+ return {"error": f"Analysis failed: {e}", "features": {}, "flags": {...}}
+```
+
+This is often *fine* — an API boundary that never raises is a real contract, and
+the refusal surfaces as a normal error-shaped response rather than a protocol
+error. But check it deliberately: if that shape is what your caller sees, the
+integration test asserts on `result["error"]`, not on `pytest.raises`.
+
+## Testing
+
+- **Mutate each half separately.** Neuter only the regex and confirm a `..`
+ fixture fails; neuter only the containment check and confirm a *symlink*
+ fixture fails. One combined test passes with either half deleted and proves
+ neither.
+- **Write the sibling-name fixture explicitly.** A test whose repository tracks
+ `.state/data.json` passes against `HasPrefix(path, ".state")` too. The test
+ that separates the implementations tracks `.state-backup/old.json` and asserts
+ the operation is refused.
+- **Assert nothing was mutated on refusal**, not just that an error came back:
+ the branch is unchanged, the tracked file list is unchanged, the in-memory
+ progress counters are unchanged. That is the actual claim.
+- **Existing fixtures become the rejected shape.** Older tests for the
+ destructive path were often built loosely — a repository tracking `app.txt`
+ alongside the state directory, because nothing cared. After the guard, such a
+ test no longer reaches the code it was written to cover; it now exercises the
+ refusal. Tighten those fixtures to the allowed shape and add the refusal case
+ as a *new* test, or you silently lose coverage of the destructive path.
+- **Reproduce the failure with the narrowest hook.** When you need one specific
+ operation to fail in order to test the recovery path, target it precisely — a
+ blanket hook that rejects every operation of that kind aborts the run earlier
+ than the path you were trying to reach, and the test proves something else.
+
+## Checklist
+
+- [ ] Every irreversible operation states its precondition in code, not in a doc
+- [ ] Violation returns an error; no `--force`, no warn-and-continue
+- [ ] The guard runs before the first statement with an effect
+- [ ] Ambiguous state (detached HEAD, missing target, multiple candidates) rejected up front
+- [ ] Path/ownership classification is structural, never a bare string prefix
+- [ ] Caller-supplied names are validated *and* resolved-path contained
+- [ ] Every entry point routes through both checks, including internal helpers
+- [ ] The dry-run/preview gap is intentional and stated
+- [ ] Tests mutate each half of the guard independently
+- [ ] A sibling-name (`x-backup/`) and a symlink fixture both exist
+- [ ] Refusal tests assert the target is unchanged, not just that an error was raised
+
+## Note for this repository (ffmpeg-skill)
+
+This repo's actual exposure is much narrower than the examples above — there is
+no `--rebuild`/`--purge`-shaped command, no history rewriting, and "Keep
+originals" is already a stated design principle (`README.md` design principle
+#9: no tool overwrites its input; a test hashes every input after every run,
+see `tests/test_all.py`/`tests/test_contract.py`'s input-hash checks). The
+closest analogue is `-o`/output-path handling: every tool takes a
+caller-supplied output path and `ffmpeg_base()` always passes `-y` (overwrite
+without prompting) — there is no confirmation step before an existing file at
+that path is silently replaced. Since this is a local CLI a human or agent
+invokes directly (not a server resolving untrusted network input against a
+base directory), the "boundary escape" half of this skill is low-stakes here;
+the "refuse before the first mutation" and "existing input-hash tests still
+prove nothing was touched" halves are the parts that actually apply.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/git-hygiene/SKILL.md b/.claude/skills/git-hygiene/SKILL.md
new file mode 100644
index 0000000..827b225
--- /dev/null
+++ b/.claude/skills/git-hygiene/SKILL.md
@@ -0,0 +1,216 @@
+---
+name: keeping-git-repos-clean
+description: Prevents, detects, and remediates files that should never be committed — secrets (.env, API tokens, hardcoded credentials) and dev artifacts (build output, scratch databases, editor/OS files). Covers .gitignore (and why it does not untrack), git rm --cached, auditing tracked files, history scrubbing, and credential rotation. Use when a repo has committed secrets or junk, when setting up a new repo's ignore rules, or when reviewing what a repo actually tracks.
+---
+
+# Keeping Git Repos Clean
+
+Two classes of files keep ending up in repos: **secrets** and **dev artifacts**.
+Both are cheap to prevent and expensive to clean up after the fact, because git
+history is forever and public repos publish everything.
+
+## The one rule everyone forgets
+
+**`.gitignore` does NOT untrack files that are already committed.** Adding a path
+to `.gitignore` only prevents *future untracked* files from being staged. A file
+git is already tracking keeps getting committed regardless. This bites repeatedly:
+a `.env` is listed in `.gitignore` but was committed before the rule existed, so
+it keeps shipping.
+
+To actually stop tracking a file while keeping your local copy:
+
+```bash
+git rm --cached path/to/file # untrack, leave working-tree copy in place
+git rm -r --cached some/dir/ # for a directory
+echo "path/to/file" >> .gitignore # then ignore it so it doesn't come back
+git commit -m "Stop tracking <file>; add to .gitignore"
+```
+
+`--cached` is the important flag — plain `git rm` deletes the working copy too.
+
+## Audit what a repo actually tracks
+
+Don't trust `.gitignore` to tell you what's clean — read the index directly:
+
+```bash
+git ls-files | grep -iE '\.(env|pem|key|p12|profraw|log|bak|db|sqlite3?)$'
+git ls-files | grep -iE '(^|/)(\.DS_Store|~\$|todo\.db|node_modules/|__pycache__/)'
+git ls-files '*.db' '*.sqlite*' # scratch databases
+git ls-files | xargs -I{} du -h {} | sort -rh | head # surprisingly large tracked files
+```
+
+Usual suspects seen across real repos:
+
+- **Secrets:** `.env` with a live token, hardcoded `AWS_*`/DB creds in a settings
+ module, `SECRET_KEY = "CHANGEME"`/`"foobar"` placeholders shipped to prod.
+- **Build artifacts:** LaTeX `.aux/.toc/.log/.synctex.gz/.pdf`, LLVM `*.profraw`,
+ compiled binaries, `htmlcov/`, `dist/`, `*.egg-info/`.
+- **Scratch / personal artifacts:** `todo.db` and other tool-local SQLite scratch
+ DBs, editor backups (`*.backup`, `*.bak`, `~$*.docx` Word lock files), stray
+ `*.log`.
+- **OS noise:** `.DS_Store`, `Thumbs.db`.
+
+## Secrets need more than `git rm`
+
+Removing a secret from `HEAD` does **not** remove it from history — `git log -p`
+and the commit that introduced it still expose it. Three things must happen, in
+order, and the first is the only one that actually protects you:
+
+1. **Rotate the credential.** Treat any secret that ever touched a remote as
+ compromised. Issue a new token/key/password and revoke the old one. Do this
+ first — the leaked value is public the moment it was pushed.
+2. **Untrack going forward** (`git rm --cached` + `.gitignore` + `.env.example`
+ documenting which vars are needed, with placeholder values only).
+3. **Scrub history** if required (`git filter-repo --invert-paths --path .env`,
+ or BFG) and force-push. This rewrites SHAs and disrupts collaborators, so it's
+ usually a deliberate maintainer step done after rotation — not an automated PR.
+
+A PR that does (2) and (3) but skips (1) gives false comfort: the value is still
+valid and still in history clones/forks. Always call out rotation as the required
+human follow-up.
+
+## "Committed" means "published"
+
+For public repos — and especially static sites deployed with `path: '.'`
+(GitHub Pages uploads the entire repo) — every tracked file is fetchable at a
+public URL. A scratch `todo.db` at the repo root of a brochure site is served at
+`/todo.db`. Before committing to any public repo, assume anyone can download it.
+
+## Prevent it: global ignore + a secret scanner
+
+Per-developer noise (editor files, OS files, tool scratch DBs like `todo.db`)
+should be ignored **globally**, not in every project's `.gitignore` — that way it
+never lands anywhere:
+
+```bash
+git config --global core.excludesFile ~/.gitignore_global
+printf '%s\n' '.DS_Store' '*.swp' 'todo.db' '*.profraw' >> ~/.gitignore_global
+```
+
+Block secrets at commit time with a pre-commit hook so they never reach history:
+
+```yaml
+# .pre-commit-config.yaml
+repos:
+ - repo: https://github.com/gitleaks/gitleaks
+ rev: v8.18.0
+ hooks: [{id: gitleaks}]
+ - repo: https://github.com/Yelp/detect-secrets
+ rev: v1.5.0
+ hooks: [{id: detect-secrets, args: ["--baseline", ".secrets.baseline"]}]
+```
+
+A starter project `.gitignore` (commit this):
+
+```gitignore
+# Secrets / local config
+.env
+.env.*
+!.env.example
+*.pem
+*.key
+
+# Python build/test artifacts
+__pycache__/
+*.py[cod]
+build/
+dist/
+*.egg-info/
+.coverage
+htmlcov/
+.pytest_cache/
+
+# Scratch / OS / editor
+*.db
+*.sqlite
+*.sqlite3
+*.profraw
+*.log
+*.bak
+*.backup
+.DS_Store
+~$*
+```
+
+## Verification can dirty the tree
+
+Compilers, test runners, and asset pipelines often write into the checkout even
+when the command is only meant to verify a change. They may create unignored
+cache files or regenerate a tracked distributable such as a PDF or compiled CSS.
+A green command does not mean the working tree still contains only your change.
+
+Bracket verification with status checks and stage only reviewed paths:
+
+```bash
+git status --short
+make test # or the project's real build command
+git status --short
+git diff -- path/you/changed
+git add path/you/changed # never sweep in generated files with git add -A
+git diff --cached --check
+git diff --cached --stat
+```
+
+If a tool necessarily produces noisy output, run it in a disposable copy of the
+checkout. This preserves a real build while keeping generated files away from
+the patch:
+
+```bash
+scratch_dir=$(mktemp -d)
+rsync -a --exclude .git ./ "$scratch_dir/"
+(cd "$scratch_dir" && make build)
+```
+
+When verification modifies a tracked generated output that is intentionally out
+of scope, restore **that exact path only after reviewing its diff**:
+
+```bash
+git diff -- docs/manual.pdf
+git restore -- docs/manual.pdf
+```
+
+Do not use a broad restore/reset to clean up: the checkout may already contain
+someone else's work. Also do not rely on `git stash` as cleanup for untracked
+artifacts; ordinary stashes omit them, and even `--include-untracked` can collide
+with files regenerated before `stash pop`. Prevent or remove known generated
+paths explicitly instead.
+
+## Checklist
+
+```
+Audit:
+- [ ] `git ls-files` reviewed for secrets, build output, scratch DBs, OS files
+- [ ] No live credentials in tracked source or .env
+- [ ] No surprisingly large/binary tracked files
+
+Remediate (if dirty):
+- [ ] Secret rotated/revoked FIRST (history is public the moment it was pushed)
+- [ ] `git rm --cached` + .gitignore entry for each offending file
+- [ ] .env.example documents required vars with placeholder values only
+- [ ] History scrub flagged as a maintainer follow-up if the secret is in history
+
+Prevent:
+- [ ] Project .gitignore covers secrets, build artifacts, OS/editor noise
+- [ ] Global core.excludesFile catches per-developer scratch files
+- [ ] gitleaks / detect-secrets pre-commit hook installed
+- [ ] Verification bracketed by `git status --short`; only reviewed paths staged
+```
+
+For scanning source code for vulnerabilities and hardcoded-secret *patterns*
+rather than what git tracks, use the `/security-review` skill already available
+in this session.
+
+## Note for this repository (ffmpeg-skill)
+
+`.gitignore` already covers `__pycache__/`, and `package.json`'s `"files"` list
+is the actual publish gate — but this session hit exactly the "verification can
+dirty the tree" case: running `python3 scripts/proxy.py` and the test suites
+locally created `__pycache__/*.pyc` files that then showed up in an `npm
+publish --dry-run` listing before they were deleted. The `git status --short`
+bracket-and-check habit above (or, cheaper here, just re-running the dry-run
+after deleting stray `__pycache__/` directories) is the concrete fix. There
+are no secrets or `.env`-shaped files in this repo (no cloud/API keys by
+design), so the credential-rotation half of this skill does not currently
+apply — the dev-artifact half is the one worth watching.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/github-actions/SKILL.md b/.claude/skills/github-actions/SKILL.md
new file mode 100644
index 0000000..869e6be
--- /dev/null
+++ b/.claude/skills/github-actions/SKILL.md
@@ -0,0 +1,317 @@
+---
+name: running-github-actions-efficiently
+description: Cut GitHub Actions minutes and wall-clock time without losing coverage — the OS billing multiplier (macOS 10x / Windows 2x / Linux 1x), trigger hygiene that stops push+pull_request double-firing, concurrency that cancels superseded runs, dependency caching keyed on lockfiles, matrix discipline, and auditing scheduled crons that bill 24/7. Use when CI is burning included minutes, when runs feel slow, when setting up a new repo's workflows, or when reviewing an existing workflow for waste.
+---
+
+# Running GitHub Actions Efficiently
+
+Actions minutes on **private** repos bill against a monthly included quota; public
+repos are free. So cost concentrates in private repos, and a handful of workflows
+usually dominate the bill. This skill is the checklist for finding and fixing that
+waste. Every fix below preserves what CI actually verifies — none of them trade
+away coverage.
+
+## First, know the one number that dominates everything
+
+Minutes are billed **per job**, rounded up to the minute, times a **runner-OS
+multiplier**:
+
+| Runner | Multiplier |
+|--------|-----------|
+| Linux (`ubuntu-*`) | **1x** |
+| Windows (`windows-*`) | **2x** |
+| macOS (`macos-*`) | **10x** |
+
+A one-minute macOS job costs the same as ten Linux minutes. This single fact
+reorders every optimization: **a repo with a few macOS jobs can outspend a repo
+with ten times as many Linux jobs.** Before anything else, find your macOS jobs
+and ask of each: does this step genuinely need macOS?
+
+- Xcode / Apple-platform builds and tests (`xcodebuild`): yes, macOS is required.
+- Linters and formatters (even Swift ones like SwiftLint/SwiftFormat), pure
+ unit tests with no Apple frameworks, packaging, doc builds: usually **no** —
+ move them to `ubuntu-latest` and cut that job's cost ~10x.
+
+Split the must-be-macOS work into its own job and push everything else to Linux.
+If a single macOS job does both (e.g. runs SwiftLint *and* an Xcode build), split
+it: a cheap Linux `lint` job plus the macOS `build` job. The tools only parse
+source, so the Linux job just checks out and runs them — no toolchain build.
+
+SwiftLint and SwiftFormat both ship self-contained prebuilt Linux binaries, so
+"Swift means macOS" is a myth for the linting half of the pipeline:
+
+```yaml
+ lint:
+ runs-on: ubuntu-latest # 1x, not 10x
+ steps:
+ - uses: actions/checkout@v4
+ - name: Install SwiftLint & SwiftFormat (Linux)
+ run: |
+ set -euxo pipefail
+ curl -fsSL -o /tmp/sl.zip https://github.com/realm/SwiftLint/releases/download/0.65.0/swiftlint_linux_amd64.zip
+ unzip -oq /tmp/sl.zip -d /tmp/sl
+ sudo install -m0755 /tmp/sl/swiftlint-static /usr/local/bin/swiftlint
+ curl -fsSL -o /tmp/sf.zip https://github.com/nicklockwood/SwiftFormat/releases/download/0.62.1/swiftformat_linux.zip
+ unzip -oq /tmp/sf.zip -d /tmp/sf
+ sudo install -m0755 /tmp/sf/swiftformat_linux /usr/local/bin/swiftformat
+ - run: swiftlint lint
+ - run: swiftformat . --lint
+```
+
+Use SwiftLint's **`swiftlint-static`** (not the dynamically linked `swiftlint`,
+which needs a Swift runtime the bare runner lacks) and SwiftFormat's
+`swiftformat_linux` — both are statically linked and run on plain `ubuntu-latest`.
+Pin versions in the URL, `curl -f` to fail on a bad download, and reference the
+exact binary names rather than a fragile `find`.
+
+**What genuinely can't move.** A SwiftPM target only builds on Linux if its code
+and its dependencies do. Two reliable signals it's macOS-pinned: the package
+declares `platforms: [.macOS(...)]` only, or it depends on an Apple-focused
+library (e.g. `SQLite.swift`, anything importing `AppKit`/`SwiftUI`/`CloudKit`).
+Don't gamble a repo's only build job on a Linux move — if `swift build` there
+depends on such a package, keep it on macOS. `grep -rE 'import (AppKit|SwiftUI|
+Cocoa|CloudKit|CoreData)'` over the target's sources is a fast pre-check.
+
+## Trigger hygiene: stop paying for the same commit twice
+
+The most common silent waste is a workflow that runs **twice on every change**:
+
+```yaml
+on:
+ push: # ← no branch filter: fires on EVERY push to EVERY branch
+ pull_request: # ← also fires for the PR built from those same commits
+```
+
+When you push a feature branch that has an open PR, the `push` event and the
+`pull_request` event both fire a full run of the same commit. On a 10x macOS
+runner that doubles the most expensive thing you have.
+
+**Fix — scope `push` to the branches you actually gate on:**
+
+```yaml
+on:
+ push:
+ branches: [main] # only post-merge commits to main
+ pull_request: # all pre-merge validation happens here
+```
+
+Now branch work is validated once (by the PR) and `main` is validated once
+(post-merge). No commit is ever built twice for the same reason.
+
+Add **path filters** so unrelated changes don't spin a runner at all:
+
+```yaml
+on:
+ pull_request:
+ paths-ignore: ['**.md', 'docs/**', '.github/ISSUE_TEMPLATE/**']
+```
+
+(Note: a required status check gated on `paths` can block PRs that legitimately
+change nothing in-scope — prefer `paths-ignore` for docs, or make the check
+non-required, rather than `paths` on a required job.)
+
+## Concurrency: kill superseded runs automatically
+
+Without a `concurrency` block, pushing three commits in quick succession starts
+three full runs and lets all three finish. You only care about the last one.
+
+```yaml
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+```
+
+This cancels any in-progress run on the same ref when a newer one starts. It is
+the single highest-leverage line for anyone who pushes iteratively or force-pushes
+during review. Put it at the top level of every workflow.
+
+One caveat: don't set `cancel-in-progress: true` on workflows that must run to
+completion once started — deploys, releases, anything that writes external state.
+Scope those with a distinct group and leave cancellation off (or queue them).
+
+## Cache dependencies — keyed on the lockfile
+
+Re-downloading and re-resolving dependencies on every run is pure waste. Cache the
+dependency directory, keyed on the **lockfile** so the cache invalidates exactly
+when dependencies change, with a `restore-keys` fallback for partial hits.
+
+Most `setup-*` actions have caching built in — prefer it over hand-rolled
+`actions/cache` where it exists:
+
+```yaml
+# Python (uv)
+- uses: astral-sh/setup-uv@v6
+ with:
+ enable-cache: true
+ cache-dependency-glob: "uv.lock"
+
+# Python (pip)
+- uses: actions/setup-python@v5
+ with: { python-version: '3.12', cache: 'pip' }
+
+# Node
+- uses: actions/setup-node@v4
+ with: { node-version: '20', cache: 'npm' }
+
+# Go
+- uses: actions/setup-go@v5
+ with: { go-version: '1.22', cache: true } # caches modules + build cache
+```
+
+For ecosystems without built-in caching, use `actions/cache` directly:
+
+```yaml
+# Rust (cargo registry + build)
+- uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ target
+ key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }}
+ restore-keys: ${{ runner.os }}-cargo-
+
+# SwiftPM (build + package repository cache)
+- uses: actions/cache@v4
+ with:
+ path: |
+ .build
+ ~/Library/Caches/org.swift.swiftpm
+ key: ${{ runner.os }}-spm-${{ hashFiles('Package.resolved') }}
+ restore-keys: ${{ runner.os }}-spm-
+
+# Docker layers (buildx / build-push-action)
+- uses: docker/build-push-action@v6
+ with:
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+```
+
+Cache the **dependency graph** (downloaded/resolved packages), not fragile
+machine-specific build state. Caching compiler-derived artifacts with absolute
+paths (e.g. all of Xcode's `DerivedData`) can produce flaky or wrong builds — the
+dependency cache is the safe, high-ROI target.
+
+Two speed wins on macOS runners specifically:
+
+```yaml
+# Skip the multi-minute `brew update` when you just need a couple of tools
+- run: brew install swiftlint swiftformat
+ env:
+ HOMEBREW_NO_AUTO_UPDATE: "1"
+ HOMEBREW_NO_INSTALL_CLEANUP: "1"
+```
+
+## Matrix discipline
+
+A matrix multiplies job count: `os: [ubuntu, macos, windows] × python: [3.10, 3.11,
+3.12, 3.13]` is **12 jobs per run**, and the macOS/Windows cells carry the 10x/2x
+multipliers. Test broadly, but deliberately:
+
+- Run the **full matrix** on `main` / nightly, and a **minimal matrix** (one OS,
+ min+max version) on PRs. `if: github.event_name == 'push'` gates the expensive
+ cells.
+- `fail-fast: true` (the default) stops the whole matrix on the first failure —
+ keep it unless you specifically need every cell's result.
+- Test the versions you actually support. Dropping an EOL runtime is free minutes.
+- Prefer Linux cells; add macOS/Windows cells only for genuinely OS-specific code.
+
+## Scheduled workflows bill around the clock
+
+A `schedule:` cron runs whether or not anyone touched the repo — so it bills
+continuously, forever, and is the easiest thing to forget. Audit every one:
+
+```yaml
+on:
+ schedule:
+ - cron: '*/15 * * * *' # every 15 min = ~2,880 runs/month. Almost never worth it on Actions.
+```
+
+- **Uptime / health checks** do not belong on Actions — a `*/5` or `*/15` cron is
+ a runaway meter. Use a purpose-built external monitor (many have free tiers).
+- **Daily rebuilds of static content that hasn't changed** (e.g. redeploying a
+ site on a timer) are wasted runs — deploy on push instead, and keep a
+ `workflow_dispatch:` for manual rebuilds.
+- **DST/timezone hacks** that register two crons and gate one out still pay the
+ runner spin-up (checkout + toolchain setup) for the run that no-ops. Gate
+ *before* the setup steps, or compute the schedule so only one fires.
+- Genuinely periodic jobs (a real nightly build) are fine — just right-size the
+ frequency to how often the input actually changes.
+
+Find them all across a repo:
+
+```bash
+grep -rl "schedule:" .github/workflows/
+```
+
+## Failures and long runs still bill
+
+- A job that fails at minute 9 of 10 bills all 9. Order steps cheap-to-expensive
+ and lint/typecheck **before** the long build, so bad commits die fast.
+- Add a `timeout-minutes:` to every job so a hung step can't burn the max 6-hour
+ runner allotment.
+- Flaky tests that auto-retry the whole workflow multiply cost — fix the flake
+ rather than papering over it with reruns.
+
+## Measure before and after
+
+Don't guess which workflow is expensive — measure:
+
+- **Repo/org billing:** Settings → Billing → this month's Actions minutes, and
+ the per-repo breakdown.
+- **Per-run breakdown (API):** `/repos/{owner}/{repo}/actions/runs/{id}/timing`
+ returns billable milliseconds split by OS multiplier.
+- **What runs most (API):** `/repos/{owner}/{repo}/actions/runs?created=>=YYYY-MM-DD`
+ — count runs per workflow and note the triggering `event`. A workflow with far
+ more runs than you have merges is double-firing or over-scheduled.
+
+Fix the top one or two offenders first; the distribution is almost always
+long-tailed.
+
+## Checklist
+
+```
+Audit:
+- [ ] Identified every macOS/Windows job (10x/2x) — each justified, or moved to Linux
+- [ ] Listed every schedule: cron and confirmed each is worth running 24/7
+- [ ] Compared runs-per-workflow to merge frequency (excess = double-fire/over-schedule)
+
+Triggers:
+- [ ] push scoped to gated branches (e.g. [main]); pull_request handles pre-merge
+- [ ] No workflow builds the same commit on both push and pull_request
+- [ ] paths-ignore excludes docs/markdown-only changes
+
+Concurrency:
+- [ ] concurrency + cancel-in-progress on CI workflows
+- [ ] Deploy/release workflows use a distinct group and do NOT cancel mid-run
+
+Caching & speed:
+- [ ] Dependencies cached, keyed on the lockfile, with restore-keys
+- [ ] setup-* built-in caching used where available
+- [ ] Cheap checks (lint/typecheck) run before the long build; jobs have timeout-minutes
+- [ ] macOS brew steps skip auto-update (HOMEBREW_NO_AUTO_UPDATE)
+
+Matrix:
+- [ ] Full matrix on main/nightly; reduced matrix on PRs
+- [ ] Only supported runtime versions; only necessary OSes
+```
+
+## Note for this repository (ffmpeg-skill)
+
+`.github/workflows/ci.yml` already gets the trigger-hygiene rule right —
+`push: branches: [main]` plus an unscoped `pull_request:` means no commit is
+built twice for the same reason. It has no Python dependency install step to
+cache (stdlib only, nothing to resolve), so the caching section mostly doesn't
+apply here.
+
+Two things this skill's checklist would flag as genuinely missing, verified by
+reading the file directly (not assumed): **no `concurrency:` block** — pushing
+several commits to an open PR in quick succession runs the full 3-OS matrix
+every time with nothing cancelling the superseded ones, and macOS is the 10x
+runner in that matrix — and **no `timeout-minutes:`** on the job, so a hung
+`ffmpeg`/`choco`/`brew` step would run to the platform's multi-hour default
+before failing instead of failing fast. Neither has been added as part of
+adding this skill; they're noted here as a real, verified finding for whoever
+next touches the workflow file to decide on.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/mcp-server-design/SKILL.md b/.claude/skills/mcp-server-design/SKILL.md
new file mode 100644
index 0000000..d7938c1
--- /dev/null
+++ b/.claude/skills/mcp-server-design/SKILL.md
@@ -0,0 +1,286 @@
+---
+name: building-python-mcp-servers
+description: Builds robust Python MCP (Model Context Protocol) servers with FastMCP — tool design, error contracts, event-loop-safe blocking work, subprocess/CLI wrapping, single-file vs packaged distribution, global-state-free testing, and prompt-injection awareness. Use when writing an MCP server, exposing a tool or CLI to an LLM client, debugging tool registration/packaging, or testing MCP tools.
+---
+
+# Building Python MCP Servers
+
+MCP servers expose tools to an LLM client (Claude Desktop, Claude Code, etc.).
+The LLM is the caller, so the failure modes differ from a normal library: errors
+must be machine-readable, every input is untrusted, and a green test suite often
+proves nothing about whether the tools actually work. This skill encodes the
+patterns that recur when these go wrong.
+
+## Quick Start (FastMCP)
+
+```python
+from mcp.server.fastmcp import FastMCP
+
+mcp = FastMCP("my-server")
+
+def read_config(path: str) -> dict:
+ """Read a config file. `path` must be absolute."""
+ p = Path(path)
+ if not p.is_absolute():
+ return {"error": "path must be absolute"}
+ if not p.exists():
+ return {"error": f"no such file: {path}"}
+ return {"data": p.read_text()}
+
+if __name__ == "__main__":
+ mcp.run()
+```
+
+## Error Contract: return, don't raise — and stay consistent
+
+An uncaught exception surfaces to the LLM as an opaque protocol error it can't
+reason about. Return a structured result with a predictable shape instead, and
+make callers check for it.
+
+- **Pick one error shape and use it everywhere.** A dict with an `"error"` key is
+ the common convention. Document that callers must check for it.
+- **Batch tools must report skips, not swallow them.** The most common
+ inconsistency: a single-item tool collects per-item errors, but a sibling
+ "do this across a directory" tool silently `continue`s past files that fail to
+ load. For automation that is invisible data loss. Every batch tool should
+ return both results and a per-item `skipped`/`errors` list.
+
+```python
+def validate_dir(path: str) -> dict:
+ results, skipped = {}, []
+ for f in Path(path).glob("*.md"):
+ try:
+ results[f.name] = _validate(f)
+ except Exception as e:
+ skipped.append({"file": f.name, "error": str(e)}) # never silently continue
+ return {"results": results, "skipped": skipped}
+```
+
+> Type footgun: YAML auto-parses an unquoted ISO date (`date: 2025-06-15`) into a
+> `datetime.date`, **not** a `str` or `datetime.datetime`. A validator that
+> handles only `str`/`datetime` will false-positive on native YAML dates. When
+> validating parsed values, enumerate every type the parser can actually produce.
+
+## Wrapping a subprocess / CLI
+
+A huge share of MCP servers shell out to another tool. Three failures recur:
+
+**1. Don't discard stdout on a non-zero exit.** Many CLIs exit non-zero *by
+design* (a linter/mutation-tester reporting findings) and write their real
+output to **stdout** with an empty stderr. A wrapper that returns
+`f"Error: {result.stderr}"` whenever `returncode != 0` reports a successful run
+to the LLM as an empty `"Error: "`.
+
+```python
+def run_tool(args: list[str]) -> dict:
+ r = subprocess.run(args, capture_output=True, text=True)
+ return { # hand BOTH streams to the model; let it judge
+ "returncode": r.returncode,
+ "stdout": r.stdout,
+ "stderr": r.stderr,
+ }
+```
+
+**2. Pin to the version you actually wrap, and verify subcommands exist.** A
+server written against a tool's 2.x CLI while the project pins 3.x will call
+subcommands and flags that no longer exist — every wrapped tool breaks at
+runtime. Check the *installed* version's `--help`, not your memory of it.
+
+**3. Parse args safely.** Splitting an extra-args string with `str.split()`
+breaks quoted, space-containing arguments — use `shlex.split()`. Never
+interpolate a client-supplied string into a shell command; pass an argv list to
+`subprocess.run` (no `shell=True`). When a tool accepts a target/path, remember
+the LLM (or content it read) chose it — validate it.
+
+## No module-level global state (it makes the server untestable)
+
+Parsing CLI args at import time and stashing them in module globals
+(`WORKING_DIR`, `MAKEFILE_PATH`, caches…) forces every test to
+`del sys.modules["server"]` and re-import under a patched `sys.argv` just to
+reset state — brittle and easy to get wrong. Keep configuration in an object or
+pass it through; construct tools from a factory.
+
+```python
+def build_server(config: Config) -> FastMCP:
+ mcp = FastMCP("my-server")
+
+ @mcp.tool()
+ def do_thing(x: str) -> dict:
+ return {"result": _work(x, config)} # config captured, not global
+
+ return mcp
+```
+
+This also avoids **double registration**: a module-level "create all tools" loop
+*plus* the same loop inside `main()` registers every tool twice when the file is
+run directly (`uv run server.py`, as Claude Desktop does) versus via a console
+entry point. Register in exactly one place.
+
+## Keep blocking work off the protocol event loop
+
+Do not assume a framework moves synchronous tool functions to a worker thread.
+Some FastMCP runtimes invoke them inline on the protocol event loop. A SQLite
+query, filesystem walk, dependency traversal, or synchronous HTTP call that takes
+five seconds can therefore block pings and every unrelated request for the same
+five seconds.
+
+Make the tool async and move only the blocking boundary to a thread:
+
+```python
+import asyncio
+
+async def find_dependents(item_id: int) -> dict:
+ rows = await asyncio.to_thread(repository.find_dependents, item_id)
+ return {"items": [row.to_dict() for row in rows]}
+```
+
+Keep connection ownership in mind. Do not create a SQLite connection on the
+event-loop thread and hand that connection to the worker. Open and close it
+inside `repository.find_dependents`, or use a pool/driver whose concurrency
+contract explicitly permits the handoff. A thread wrapper around a shared,
+thread-affine connection merely trades event-loop starvation for intermittent
+database errors.
+
+Test responsiveness, not just the slow tool's result. Start a deliberately
+blocked repository call, invoke a lightweight tool (or protocol ping) before
+releasing it, and require the lightweight request to finish first:
+
+```python
+slow = asyncio.create_task(call_tool("find_dependents", {"item_id": 42}))
+await entered_worker.wait()
+
+healthy = await asyncio.wait_for(call_tool("health", {}), timeout=0.2)
+assert healthy == {"ok": True}
+
+release_worker.set()
+await slow
+```
+
+A timing assertion on the slow call alone cannot detect event-loop starvation;
+the regression is that independent protocol traffic stops making progress.
+
+## Sampling is an optional client capability — contain failures in the tool
+
+`ctx.sample(...)` is not guaranteed to work just because the tool itself was
+called successfully. The connected client may not support sampling, or its
+sampling handler may raise while processing the request. Those are different
+failure modes at the framework layer, but they are the same tool-level outcome:
+the requested analysis could not be produced.
+
+Catch the exception around the sampling boundary **inside the tool** and convert
+it to the server's normal error shape. Do not rely on the framework's outer
+exception wrapper; by then the caller receives an opaque protocol/tool error
+instead of your documented contract.
+
+```python
+async def sample_or_error(ctx: Context, prompt: str) -> dict:
+ try:
+ response = await ctx.sample(prompt)
+ except Exception as exc:
+ return {"error": f"sampling failed: {exc}"}
+ return {"result": response.text or ""}
+```
+
+Keep the `try` block narrow so unrelated programming errors are not mislabeled as
+sampling failures. Test both boundaries explicitly: a client with no sampling
+support, and a configured sampling handler that raises. Also test an empty
+sampling response if the tool promises an empty-string or other fallback.
+
+## Distribution: single-file vs packaged
+
+MCP servers are often launched as a single file (`uv run server.py`), so two
+packaging traps are easy to ship without noticing:
+
+- **Module/package name collision.** Having both a top-level `server.py` *and* a
+ `server/` package directory means `import server` resolves to the package
+ (shadowing the module), so a console entry point like `server:main` finds no
+ `main` and fails. Only running the file directly works. Pick one name.
+- **Over-narrow build includes.** A build config like
+ `only-include = ["server.py"]` produces a wheel containing just that file —
+ `import server.analyzers` raises `ModuleNotFoundError` for anyone who
+ `pip install`s it, even though `uv run server.py` works locally. If you ship a
+ package, include the package and its data files.
+
+For a PEP 723 single-file server, pin explicit versions in the inline
+`# /// script` header **and** keep them in sync with `pyproject.toml`; a
+transitive-only dependency (imported but never declared) breaks the moment the
+intermediary drops it.
+
+## Testing: prove the tools actually work
+
+Mocking the subprocess/transport layer and asserting that argv contains certain
+tokens locks in commands that may not exist in the wrapped tool — the suite stays
+green while every tool is broken at runtime. A passing CI here does **not** mean
+the server works.
+
+- Keep at least one **integration test that invokes the real wrapped tool** (or
+ a real sample file) end to end.
+- A bare `import server` smoke test is meaningless under a name collision (it can
+ import an empty package). Assert a tool *runs and returns expected output*.
+- Test the error contract: malformed input returns your `"error"` shape, batch
+ tools populate `skipped`.
+
+## Treat all tool I/O as untrusted (prompt injection)
+
+Tool inputs, file contents, and especially **other tools' descriptions** can be
+attacker-influenced and flow into the model's context. A server that feeds such
+text back into a second LLM call is itself a prompt-injection surface — its
+output is advisory, not authoritative. Don't grant a tool more filesystem/network
+reach than it needs, validate paths, and never let tool output be treated as a
+trusted instruction.
+
+## MCP Server Checklist
+
+```
+Contract:
+- [ ] One consistent error shape; documented that callers check it
+- [ ] Batch tools return a per-item skipped/errors list (never silent continue)
+- [ ] Inputs validated (absolute paths, allowed types) before use
+- [ ] Sampling failures (unsupported client and handler exception) normalized inside the tool
+
+Subprocess:
+- [ ] Both stdout and stderr returned; non-zero exit not assumed to be failure
+- [ ] Pinned to the wrapped tool's actual version; subcommands verified
+- [ ] shlex.split for arg strings; argv list (no shell=True)
+
+Structure:
+- [ ] No module-level CLI parsing / global state
+- [ ] Tools registered in exactly one place
+- [ ] Blocking database/filesystem/network work moved off the protocol event loop
+- [ ] Concurrency test proves a lightweight request completes while a slow tool is blocked
+
+Distribution & tests:
+- [ ] No server.py / server/ name collision; build includes the whole package
+- [ ] PEP 723 header deps pinned and synced with pyproject
+- [ ] An integration test exercises a real tool (not just mocked argv)
+```
+
+## Note for this repository (ffmpeg-skill)
+
+`mcp/server.py` here is a hand-rolled stdio JSON-RPC server, NOT FastMCP — the
+`@mcp.tool()` decorator examples above don't apply directly. But most of the
+*principles* transfer almost exactly, because this server's entire job is
+wrapping 22 subprocess-based CLI tools:
+
+- The subprocess-wrapping section (stdout/stderr handling, argv-list-only, no
+ `shell=True`) matches `mcp/server.py`'s actual design: `execution.shell:
+ false` and `arbitrary_executables: false` are load-bearing guarantees in
+ `contract --json`, not just documentation.
+- "No module-level global state" and "tools registered in exactly one place"
+ are already true by construction here: `tools/list` is derived from
+ `scripts/_contract.py` at call time, not from a hand-written table (see
+ `tests/test_contract.py`'s `test_mcp_tools_match_contract` and
+ `test_mcp_schema_drift_follows_the_scripts`).
+- "Testing: prove the tools actually work" is already the norm —
+ `test_mcp_tool_call_round_trip` and the contract tests build real JSON-RPC
+ requests and check real tool output, not mocked argv.
+- The event-loop/blocking-work section does not apply: this server is
+ synchronous stdio, not an async framework moving work onto a shared loop.
+- The prompt-injection section is worth taking seriously as-is: any tool
+ whose input includes a caller-supplied path (nearly all of them) should be
+ read with the same wariness this section describes.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/release-management/SKILL.md b/.claude/skills/release-management/SKILL.md
new file mode 100644
index 0000000..449b13b
--- /dev/null
+++ b/.claude/skills/release-management/SKILL.md
@@ -0,0 +1,147 @@
+---
+name: managing-python-releases
+description: Manages Python library releases including semantic versioning, changelog maintenance (Keep a Changelog format), release automation with GitHub Actions, and deprecation workflows. Use when planning releases, writing changelogs, automating release pipelines, or communicating breaking changes.
+---
+
+# Release Management
+
+## Semantic Versioning
+
+```
+MAJOR.MINOR.PATCH (e.g., 1.2.3)
+
+PATCH: Bug fixes, no API changes
+MINOR: New features, backward compatible
+MAJOR: Breaking changes
+```
+
+## Changelog Format (Keep a Changelog)
+
+```markdown
+# Changelog
+
+## [Unreleased]
+### Added
+- New `batch_encode()` function
+
+## [1.2.0] - 2024-03-15
+### Added
+- Support for custom formats (#123)
+
+### Fixed
+- Edge case at -180 longitude (#145)
+
+### Deprecated
+- `old_function()` - use `new_function()` instead
+
+[Unreleased]: https://github.com/user/repo/compare/v1.2.0...HEAD
+[1.2.0]: https://github.com/user/repo/releases/tag/v1.2.0
+```
+
+**Categories:** Added, Changed, Deprecated, Removed, Fixed, Security
+
+## Version in Code
+
+```python
+# src/package/__init__.py
+__version__ = "1.2.3"
+
+# Or use importlib.metadata
+from importlib.metadata import version
+__version__ = version("my-package")
+```
+
+## GitHub Actions Release (PyPI example)
+
+A tag-triggered workflow builds and publishes to a registry via trusted
+publishing (no stored token) is the general shape — swap the publish step for
+whatever registry the project actually uses (PyPI, npm, crates.io, ...):
+
+```yaml
+# .github/workflows/release.yml
+on:
+ push:
+ tags: ['v*']
+
+jobs:
+ release:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write # create the GitHub release
+ id-token: write # trusted publishing (no token)
+ steps:
+ - uses: actions/checkout@v4
+ - uses: astral-sh/setup-uv@v5
+ - run: uv build
+ - uses: softprops/action-gh-release@v2
+ with:
+ files: dist/*
+ - uses: pypa/gh-action-pypi-publish@release/v1
+```
+
+## Deprecation Process
+
+Warn with `stacklevel=2` so the message points at the caller.
+
+```python
+import warnings
+
+def old_function():
+ """Deprecated: Use new_function() instead."""
+ warnings.warn(
+ "old_function() deprecated, will be removed in 2.0.0",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return new_function()
+```
+
+## Release Process
+
+```bash
+# 1. Update CHANGELOG.md (move Unreleased to version)
+# 2. Bump version in the project manifest
+# 3. Commit and tag
+git commit -am "Release v1.2.0"
+git tag -a v1.2.0 -m "Release v1.2.0"
+git push origin main --tags
+# 4. CI publishes automatically (if automated) or publish manually
+```
+
+## Checklist
+
+```
+Before Release:
+- [ ] All tests pass
+- [ ] CHANGELOG updated
+- [ ] Version bumped
+- [ ] Documentation current
+
+After Release:
+- [ ] Registry shows new version
+- [ ] A fresh install actually works (not just that the tag/publish succeeded)
+- [ ] GitHub release created
+- [ ] Docs updated
+```
+
+## Note for this repository (ffmpeg-skill)
+
+`CHANGELOG.md` here already follows Keep a Changelog's dated-section format
+(`## 0.10.0 — 2026-09-06 — ...`), so the format guidance above matches this
+repo exactly. Two real differences from the generic PyPI example:
+
+- **No automated release workflow exists.** There is no
+ `.github/workflows/release.yml` — the 0.10.0 release this session did every
+ step by hand: bump `package.json`'s `version`, convert the CHANGELOG's
+ `## Unreleased` into a dated section, `git tag`, create the GitHub Release,
+ then `npm publish` separately. This is exactly the gap `managing-python-releases`
+ is meant to close with automation — worth considering if releases become
+ frequent enough that a manual miss (like 0.9.2 sitting un-published to npm
+ for a while, discovered this session) becomes a recurring problem.
+- **The registry is npm, not PyPI**, and there is no `__version__` in code —
+ `scripts/_contract.py`'s `skill_version()` and `doctor`'s `version` field
+ both read `package.json` directly (see this repo's own `concurrent-branches`
+ and `build-artifacts` skill notes for the related merge-conflict and
+ publish-verification patterns this touches).
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/reproducing-ci-locally/SKILL.md b/.claude/skills/reproducing-ci-locally/SKILL.md
new file mode 100644
index 0000000..da68faf
--- /dev/null
+++ b/.claude/skills/reproducing-ci-locally/SKILL.md
@@ -0,0 +1,250 @@
+---
+name: reproducing-ci-locally
+description: Run the CI gate on your machine so it agrees with the runner — deriving the exact command, paths, markers, and env from the workflow file instead of the Makefile, unblocking gate steps that short-circuit and hide the next failure, pinning the linter version CI resolves, building the interpreter/toolchain environment the runner builds, and confirming the run is green instead of explaining a red job away. Use when a check passes locally but fails in CI (or the reverse), when a lint/format job goes red on an untouched file, when setting up a local dev loop for an unfamiliar repo, or before pushing a branch you expect to merge.
+---
+
+# Reproducing CI Locally
+
+A local check is only useful if it runs the same thing the runner runs. Most
+"green locally, red in CI" failures are not bugs in the code — they are a
+difference between two commands: different paths, different test markers,
+different env, a different linter version, or a different interpreter.
+
+The fix is mechanical: **derive the local command from the workflow file**, not
+from the Makefile, not from habit, not from what the last repo used.
+
+## Read the workflow before you run anything
+
+The workflow is the contract. The Makefile is a convenience that drifts from it.
+
+```bash
+# What the gate actually is, in order
+sed -n '/jobs:/,$p' .github/workflows/ci.yml
+
+# Every command CI runs, across all workflows
+grep -rn "run:" .github/workflows/
+```
+
+Copy out four things, verbatim:
+
+1. **The commands and their order.**
+2. **The paths each command is scoped to** (`ruff check app tests scripts` is not
+ `ruff check .`).
+3. **Test selection** — marker expressions, `-k` filters, which suites are excluded.
+4. **The `env:` block**, and the runtime/toolchain versions in `setup-*` steps.
+
+Each of those four is a distinct way to get a wrong answer locally.
+
+**Paths.** If CI lints `app tests scripts` and you run `ruff check .`, you get
+findings from directories CI never looks at — a red that isn't a merge blocker
+and shouldn't be "fixed" in an unrelated PR. Run it the narrow way to reproduce
+the gate; run it the wide way only when you're deliberately auditing.
+
+**Markers.** A suite-wide `make test` that excludes one marker is not the CI
+gate if CI excludes six. Live-credential integration tests deselected in CI will
+run locally, hit a fake key, and fail in a way that looks like a regression:
+
+```bash
+# Wrong: local shorthand — pulls in suites CI never runs
+pytest -m "not browser"
+
+# Right: the full expression, copied from the workflow
+pytest -m "not browser and not slow and not load and not integration"
+```
+
+**Env.** Config objects instantiated at import time (a settings singleton at
+module scope, an engine built when the module loads) make *collection* fail
+without the workflow's variables — a wall of "Field required" errors that looks
+like a broken suite. Mirror the `env:` block, including the *shape* of values:
+if CI passes a Postgres URL and the module builds a pooled engine, a local
+SQLite URL raises on arguments that dialect rejects before a single test runs.
+
+Keep those values in a gitignored `.env.ci` copied from the workflow's `env:`
+block, so the local command is the workflow command plus one `set -a`:
+
+```bash
+set -a; . ./.env.ci; set +a
+pytest -m "not browser and not slow and not load and not integration"
+```
+
+## A short-circuiting gate hides the next failure
+
+Gate steps run in order and the job stops at the first red. So the CI log shows
+you *one* failure even when three are waiting:
+
+```yaml
+- run: ruff check . # fails here …
+- run: ruff format --check . # … so this never runs, and you never see it
+```
+
+You fix the lint error, push, and get an immediate second red for formatting.
+Same shape everywhere: `cargo fmt --all -- --check` before `cargo clippy
+--all-targets -- -D warnings` before `cargo test` means a formatting failure
+tells you nothing about whether clippy or the tests pass.
+
+**Run every gate step locally, even after one fails.** Don't `&&`-chain them
+while diagnosing — run them separately and collect the whole set:
+
+```bash
+ruff check app tests scripts; echo "lint: $?"
+ruff format --check app tests; echo "format: $?"
+pytest -m "not integration"; echo "tests: $?"
+```
+
+The corollary: after a red job, never report "only X is broken." Everything
+downstream of X is unmeasured until you run it.
+
+## Pin what gates the build, and reproduce the version CI resolves
+
+An unpinned gating tool means the gate changes without a commit. A range like
+`ruff>=0.4.0` resolves to whatever shipped this morning, and a release that
+*widens file coverage* — a formatter that starts formatting code blocks inside
+Markdown, a linter that promotes a rule to default — turns every open PR red on
+files nobody touched.
+
+Two habits:
+
+- **Pin the linter, formatter, and toolchain** in the manifest, and bump them in
+ a dedicated PR where the reformat is the whole diff.
+- **Reproduce with the version CI resolves**, not the one you happen to have:
+
+```bash
+uvx [email protected] format --check . # exactly what the runner would install
+
+# Node: CI does `npm ci` then `npx prettier --check web` — that's the LOCKFILE's
+# prettier. A bare `npx prettier` fetches the latest and flags files CI is fine
+# with. Read the pinned version, then ask for it.
+grep -m1 -A2 '"node_modules/prettier"' package-lock.json
+npx -y [email protected] --check web
+```
+
+Formatting a file CI never complained about is not a fix — it's an unrelated
+diff caused by using a different tool than the gate.
+
+## Build the environment the runner builds
+
+Package managers will happily invent an environment for you, and the one they
+invent is not CI's.
+
+- **A fresh clone or worktree has no virtualenv.** `uv run <tool>` silently
+ creates a bare one *without* your dev extras, then fails with `Failed to
+ spawn: ruff` — which reads like a missing dependency rather than a missing
+ environment.
+- **`uv run` re-syncs from the lockfile** against your *host* interpreter. On a
+ Python newer than CI's matrix, a pinned dependency with no wheel for that
+ version gets built from source and fails on a compiler error that has nothing
+ to do with your change.
+- **Extras differ.** If CI installs `[dev,web]` and `make install` installs
+ `[dev]`, the full suite errors at collection locally on an import CI has.
+
+Build it explicitly, at CI's interpreter version, with CI's extras:
+
+```bash
+uv venv .venv --python 3.12 --seed
+uv pip install --python "$PWD/.venv/bin/python" -e ".[dev,web]"
+.venv/bin/python -m ruff check app tests scripts
+.venv/bin/python -m pytest -m "not integration"
+```
+
+Driving the tools as `.venv/bin/python -m <tool>` sidesteps the re-sync entirely.
+If you prefer `uv run`, pass `--no-sync`. And prefix with `env -u VIRTUAL_ENV`
+when a shell profile exports one — otherwise the run is silently redirected into
+an unrelated environment and its results mean nothing.
+
+## Fix divergence in shared config, not in the workflow
+
+When you find a difference, ask where the fix belongs. A flag added to the
+workflow YAML fixes CI and leaves every local run diverging — so the next person
+hits the same confusion.
+
+Prefer the file both sides read:
+
+- Test-runner flags → `addopts` in `pyproject.toml`, not the workflow's `run:`.
+ (Import-mode is the classic one: a source directory on `sys.path` shadowing an
+ installed compiled package is a *config* problem, and pinning
+ `--import-mode=importlib` in `addopts` fixes local and CI together.)
+- Marker definitions, coverage thresholds, lint rules and target version → the
+ project manifest.
+- Keep `requires-python` and the linter's `target-version` in sync; a mismatch
+ means the linter applies rules for a runtime you don't support.
+
+The workflow should read as `make lint` / `make test` plus the environment. When
+it contains flags the local target doesn't, that's the divergence.
+
+## Know which checks are actually gates
+
+Not every command in the repo is a merge blocker, and treating them as equal
+wastes PRs.
+
+```bash
+# Which jobs are required is a repo setting, not a file — check it
+gh api repos/OWNER/REPO/branches/main/protection --jq '.required_status_checks.contexts'
+```
+
+If CI runs the linter but not the type checker, then a pre-existing type error in
+an untouched module is not blocking your PR — don't fold a speculative fix for it
+into an unrelated change, and don't claim CI verifies types. The inverse matters
+too: a helper target like `make quality-check` that runs *more* than CI will show
+you reds that no one is gating on.
+
+## Finish by confirming the run, not by explaining it
+
+"Passes locally" is a prediction. Wait for the real result:
+
+```bash
+gh pr checks --watch
+gh run view --log-failed # the failing step's output, not the summary
+```
+
+When a job is red, fix it in the same PR if the fix is feasible. If you believe
+it's pre-existing, **prove it**: check out the base commit and run the same
+command there. An unverified "pre-existing / out of scope" is how a base branch
+becomes permanently red.
+
+Two traps in the log itself:
+
+- A step gated on an event (`if: github.event.action == 'opened'`) is skipped
+ when you re-run by pushing a commit. Green-on-rerun can mean *not run*.
+- A permissions failure at the last step (an HTTP 403 posting a comment) shows
+ every build/test step green with a red X on the job — read which step failed
+ before concluding the code is broken.
+
+## Checklist
+
+```
+Before running anything:
+- [ ] Read .github/workflows/*.yml — commands, order, paths, markers, env, versions
+- [ ] Local command uses CI's paths (not `.`) and CI's full marker expression
+- [ ] Workflow env: block mirrored, including value shape (DB URL dialect, etc.)
+
+Environment:
+- [ ] venv created explicitly at CI's runtime version, with CI's extras
+- [ ] Tools driven from that venv (`.venv/bin/python -m …` or `--no-sync`)
+- [ ] `env -u VIRTUAL_ENV` when a shell profile exports one
+- [ ] Gating linter/formatter/toolchain pinned; local run uses the pinned version
+
+Running:
+- [ ] Every gate step run separately — a first failure hides the rest
+- [ ] Formatter check run even when the linter passed (they are different tools)
+
+Fixing:
+- [ ] Divergence fixed in shared config (manifest/addopts), not only in the workflow
+- [ ] Checked which jobs are actually required before treating a red as blocking
+- [ ] Waited for the real run; any red either fixed here or proven on the base commit
+```
+
+## Note for this repository (ffmpeg-skill)
+
+This repo's gate is `.github/workflows/ci.yml`: install ffmpeg per-OS (apt /
+`brew install ffmpeg-full` / `choco install ffmpeg`), then `python
+tests/test_all.py` and `python tests/test_contract.py` (unittest, not pytest —
+there is no marker expression to copy, but there IS an OS-conditional: a
+handful of `test_contract.py` tests are `skipIf`'d on Windows because they
+depend on a POSIX shell shim, not on CI's own `if:` gating). Read the actual
+workflow file before assuming a local `npm test` run matches — `npm test` runs
+both files with no OS-conditional skip logic layered on top, so on a
+non-Windows machine it is already a faithful local reproduction; the gap only
+shows up when debugging a Windows-specific CI failure, where the fix is to
+read what `skipIf` actually excludes before assuming a fix applies everywhere.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).
diff --git a/.claude/skills/verifying-external-behavior/SKILL.md b/.claude/skills/verifying-external-behavior/SKILL.md
new file mode 100644
index 0000000..5d684a8
--- /dev/null
+++ b/.claude/skills/verifying-external-behavior/SKILL.md
@@ -0,0 +1,217 @@
+---
+name: verifying-external-behavior
+description: Confirms what a third-party library, remote API, build backend, or scraped document actually does before writing code that depends on it — throwaway probes that run in seconds, permissive clients that forward wrong arguments instead of rejecting them, per-endpoint docs that don't generalize, response shapes that make a "fast path" always-false, fakes that encode your assumption rather than the service's behavior, and dry-runs that skip the step that fails. Use when integrating a new dependency or endpoint, writing a tolerated-status or error branch, choosing a client argument name, testing against a fake, or reviewing code that asserts an upstream contract.
+---
+
+# Verifying External Behavior
+
+Most integration bugs are not coding errors. They are a belief about someone
+else's system — a status code, a parameter name, a response shape, a build
+backend's scoping rule — that was never checked and turned out to be wrong. The
+code is written correctly against a contract that does not exist.
+
+The fix is not more care. It is a **probe**: a throwaway command that asks the
+real system the exact question, before the code is written. Probes cost seconds.
+The bugs they prevent are silent, ship green, and are found months later.
+
+## Probe the exact call you are about to write
+
+Not a similar call, not the documented example — the same endpoint form, the same
+library version, the same argument spelling.
+
+```bash
+# A library's real defaults / return shapes, with no venv to create or clean up
+uv run --no-project --with somelib python -c "import somelib; print(somelib.Thing())"
+
+# The exact URL, including the collection-vs-item distinction
+curl -s -o /dev/null -w '%{http_code}\n' https://api.example.com/v1/things
+curl -s -o /dev/null -w '%{http_code}\n' https://api.example.com/v1/things/1
+
+# What a build backend actually put in the artifact
+uv build && unzip -l dist/*.whl
+
+# A real service instead of a fake, for one minute
+docker run --rm -p 6390:6379 redis:7-alpine
+```
+
+Two rules make probes worth the minute they cost:
+
+- **Probe before you design around the answer.** A probe that confirms a
+ parameter tweak "should" fix a discrepancy is worth more than the tweak.
+- **Paste the probe command and its output into the PR, comment, or test.** A
+ finding with no reproduction decays into folklore, and the next person re-derives
+ it — or, worse, trusts it after it has gone stale.
+
+## Permissive clients don't reject wrong arguments — they ignore them
+
+This is the highest-severity class, because the failure returns *plausible data*.
+Many HTTP client wrappers forward keyword arguments verbatim into the query
+string without validating them against their own documented parameter list. The
+remote service then drops the unknown parameter and applies its default — often
+"the authenticated user". A misspelled selector (`owner=` for `owner_screen_name=`,
+`id_=` for `id=`) does not raise; it silently returns *someone else's* records.
+
+Never infer "the library would have rejected that" from the library's declared
+parameter list. Read the bytes that leave the process:
+
+```python
+# Probe: intercept the transport and print the outbound request, then stop.
+import requests
+
+sent = {}
+def spy(self, method, url, **kw):
+ sent["url"], sent["params"] = url, kw.get("params")
+ raise RuntimeError("probe: request intercepted")
+
+requests.Session.request = spy
+try:
+ client.favorites(id_=12345) # the call you were about to ship
+except RuntimeError:
+ pass
+print(sent) # {'url': '.../favorites/list.json', 'params': {'id_': 12345}}
+```
+
+If the parameter you passed is not in `params` under the name the service
+documents, the call is wrong no matter how healthy the response looks.
+
+Two corollaries:
+
+- **Pass every selector by keyword.** Clients that bind positional arguments in a
+ per-endpoint order will happily accept `get_thing(owner, slug)` and send `slug`
+ as `owner_id`, while a neighbouring method with the same-looking signature is
+ correct by luck.
+- **Check that the parameter exists at all.** Some endpoints have no equivalent of
+ the selector you want. "Forward it under the right name" is not a fix when the
+ right name does not exist — the feature has to be built differently.
+
+## Per-endpoint docs do not generalize across sibling endpoints
+
+A status code documented for the single-item form frequently does not apply to
+the collection form of the same resource. Verified live against a large public
+REST API: `GET /repos/{repo}/issues` on a repository with issues disabled returns
+**200 with an empty array**, while `GET /repos/{repo}/issues/1` returns **410
+Gone**. Code written to "tolerate 410 when issues are disabled" therefore has a
+branch that never fires, and the real path — an empty 200 — falls through to
+whatever the generic handler does.
+
+Probe the exact URL before writing a tolerated-status branch. If you keep a
+defensive branch for a status you could not reproduce, label it as defensive and
+name the path you *did* observe, so the next reader does not mistake it for
+verified behaviour.
+
+```python
+# Observed: issues-disabled repos return 200 with []. The 410 branch is
+# defensive — the item endpoint documents it, the list endpoint never sent it.
+if resp.status_code == 410:
+ return []
+```
+
+## The response *shape* is part of the contract
+
+List endpoints commonly embed a **summary** object — a handful of identity fields —
+rather than the full entity. A "we already have the data" fast path written
+against the full entity is then always false:
+
+```python
+# This check is intended to skip a per-item fetch. Against summary objects that
+# carry only {login, id, avatar_url}, it is False for every item — so the
+# "fallback" enrichment fetch is the common path, and the loop is N+1.
+if all(k in user for k in ("name", "company", "location", "followers")):
+ return user
+return fetch_user(user["login"]) # runs every time
+```
+
+Before optimizing around a response, print one real element and compare its keys
+to what your code reads. The same probe settles range and boundary assumptions
+that otherwise get "handled" defensively forever: if a per-year query provably
+returns exactly that year's days, the dedup pass guarding against adjacent-year
+leakage is dead code, and saying so in the PR is more valuable than the code.
+
+## A fake proves your code calls the fake
+
+Fakes are written by the same person as the code, from the same beliefs, so they
+agree with each other by construction. Stand the real thing up **once** and re-run
+the same assertions against it — a container is a minute, and it is the only thing
+that validates the semantics the fake asserts: TTL and expiry sentinels, whether a
+client factory is awaitable, key eviction, ordering, which exception type a
+failure raises.
+
+Simulate the outage deterministically instead of mocking the error, so the code
+takes the same path production would:
+
+```python
+# A dead port is a real, instant, deterministic connection failure.
+client = redis.asyncio.from_url("redis://localhost:1")
+```
+
+The same reasoning applies to documents you parse. A hand-written fixture encodes
+your reading of the markup; the live page may render the same tokens across
+indented lines, so a regex requiring single spaces matches every fixture and never
+matches production. Capture one real sample, commit it, and point the parser's
+test at it. Prefer a machine-readable attribute (`data-date="2024-01-01"`) over a
+human-readable string when the source offers both — it survives markup and locale
+changes that a prose regex does not.
+
+## Dry-runs skip the step that fails
+
+Resolve-only and plan-only modes are not verification of anything the *real* run
+does after resolution. A dependency resolver's `--dry-run` reports success for a
+requirement whose presence makes the actual build hard-fail, because the dry run
+never builds. A build script's `--check` may never invoke the platform-specific
+tool that breaks.
+
+Run the real operation once, on the platform that matters:
+
+```bash
+uv pip install --dry-run . # resolves; does NOT build → misses build-time errors
+uv build # actually builds → catches them
+```
+
+More generally: if a mode exists specifically to be cheap, ask which step it
+bought that discount by skipping, and whether your bug lives there.
+
+## Some verified behaviour is not yours to fix
+
+A probe sometimes proves the upstream system is simply wrong, or surprising, for
+your use case. Resist reaching for a configuration knob to make the number look
+right — if the underlying model or endpoint produces that output across parameter
+settings, tuning a parameter buries the finding instead of recording it. Write
+down what was observed, at which version, with the command, and choose a different
+approach.
+
+Record findings with three things or they will not survive: **the command**, **the
+observed output**, and **the date**. External behaviour changes; an undated claim
+cannot be re-checked.
+
+## Checklist
+
+```
+Before shipping code that depends on an external system:
+- [ ] The exact call/endpoint/version was probed, not a similar one
+- [ ] Outbound request parameters inspected — names match what the service documents
+- [ ] Selectors passed by keyword, never positionally
+- [ ] Collection and item forms probed separately for status-code branches
+- [ ] One real response element printed and compared against the fields the code reads
+- [ ] Fakes validated against the real service at least once
+- [ ] Failure paths exercised against a real failure (dead port, revoked token), not a mock
+- [ ] Verified with the real build/install, not a dry-run
+- [ ] Every tolerated-status or defensive branch is either reproduced or labelled defensive
+- [ ] Findings recorded with command, output, and date
+```
+
+## Note for this repository (ffmpeg-skill)
+
+`ffmpeg`/`ffprobe` are exactly the "third-party system" this skill is about —
+their real behavior across versions and flags is the whole reason `doctor`
+exists, and this session repeatedly needed to probe ffmpeg directly rather
+than reason about it from documentation. The clearest example: `cut.py`'s
+copy-mode `-ss` (before `-i`) seeks to the nearest preceding keyframe, and it
+was tempting to assume the output duration would still equal the requested
+`-t` regardless of where the seek landed. Running the actual command against
+a real fixture (`--start 1.13 --end 5.71 --tolerance 2.0`) showed a real
+1.24s divergence between `requested_duration` and `output_duration` — the
+kind of finding this skill says to record with the command, the output, and
+the date, which is exactly how `test_cut_copy_keyframe_snap_reports_a_real_nonzero_delta`
+in `tests/test_all.py` was derived, rather than calculated from first principles.
+
+Source: [wdm0006/python-skills](https://github.com/wdm0006/python-skills) (MIT).