summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDrew Ritter <drew@ritter.dev>2026-09-11 17:16:38 -0700
committerGitHub <noreply@github.com>2026-09-11 17:16:38 -0700
commitc3116b22c6b30bda7135828c4b62f3049808ec5d (patch)
tree5c472ab0077e5a4d7350ea03b6dfc6e6a009fab5
parentf6617db1517488d4a8b66925519d5ffbeef965b3 (diff)
parent9fe81b48a2d9599d0a39cca0a1e5329f3905cae4 (diff)
Merge pull request #2275 from obra/feat/movie-os-compatibilityimport/proving-it-works-skill
feat(movie): support native Windows PowerShell and Git Bash
-rw-r--r--docs/superpowers/plans/2026-09-11-movie-review-fixes.md60
-rw-r--r--docs/superpowers/specs/2026-09-09-proof-movie-windows-completion-design.md72
-rw-r--r--skills/proving-it-works-with-a-movie/SKILL.md6
-rw-r--r--skills/proving-it-works-with-a-movie/assembling.md66
-rw-r--r--skills/proving-it-works-with-a-movie/examples/film-terminal.py531
-rw-r--r--skills/proving-it-works-with-a-movie/narrating.md10
-rw-r--r--skills/proving-it-works-with-a-movie/recording-a-terminal.md135
-rw-r--r--skills/proving-it-works-with-a-movie/recording-motion.md23
-rwxr-xr-xskills/proving-it-works-with-a-movie/scripts/assemble85
-rw-r--r--skills/proving-it-works-with-a-movie/scripts/browser_tools.py127
-rwxr-xr-xskills/proving-it-works-with-a-movie/scripts/burn-subtitles35
-rwxr-xr-xskills/proving-it-works-with-a-movie/scripts/check-movie11
-rwxr-xr-xskills/proving-it-works-with-a-movie/scripts/make-subtitles9
-rw-r--r--skills/proving-it-works-with-a-movie/scripts/media_paths.py24
-rwxr-xr-xskills/proving-it-works-with-a-movie/scripts/narrate115
-rw-r--r--tests/proving-it-works-with-a-movie/README.md24
-rw-r--r--tests/proving-it-works-with-a-movie/fixtures.py298
-rw-r--r--tests/proving-it-works-with-a-movie/fixtures/terminal_app.py41
-rw-r--r--tests/proving-it-works-with-a-movie/run-tests.py63
-rwxr-xr-xtests/proving-it-works-with-a-movie/test-assemble.sh88
-rwxr-xr-xtests/proving-it-works-with-a-movie/test-check-movie.sh105
-rwxr-xr-xtests/proving-it-works-with-a-movie/test-narrate.sh54
-rw-r--r--tests/proving-it-works-with-a-movie/test_assembly.py399
-rw-r--r--tests/proving-it-works-with-a-movie/test_browser.py73
-rw-r--r--tests/proving-it-works-with-a-movie/test_checker.py95
-rw-r--r--tests/proving-it-works-with-a-movie/test_narration.py199
-rw-r--r--tests/proving-it-works-with-a-movie/test_paths.py104
-rw-r--r--tests/proving-it-works-with-a-movie/test_subtitles.py106
-rw-r--r--tests/proving-it-works-with-a-movie/test_terminal.py307
29 files changed, 2910 insertions, 355 deletions
diff --git a/docs/superpowers/plans/2026-09-11-movie-review-fixes.md b/docs/superpowers/plans/2026-09-11-movie-review-fixes.md
new file mode 100644
index 0000000..e0f2fc8
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-11-movie-review-fixes.md
@@ -0,0 +1,60 @@
+# Movie review fixes implementation plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
+
+**Goal:** Repair the reproduced findings on #2214/#2275 while retaining the existing movie workflow.
+
+**Architecture:** Keep the recorder and five media tools. Refuse reused take directories before sending input; publish only accepted narration in the manifest. Correct the Windows recipes and missing-capability test handling.
+
+**Tech Stack:** Python, unittest, uv, ttyd, Chromium, PowerShell and Git Bash.
+
+**Spec:** `docs/superpowers/specs/2026-09-09-proof-movie-windows-completion-design.md`
+
+## Global constraints
+
+- Native Windows 11 x64: PowerShell 5.1, PowerShell 7, Git Bash; invoking and recorded shells match.
+- Preserve the Unix recipe, existing CLI interfaces, media formats, and verification policy.
+- Drew approved the necessary third-party dependencies on 2026-09-11: "those deps are normal and fine". Remove only the unused `websockets` test dependency.
+- Drew personally watches the movies for final acceptance. Do not run movie checkers, audio transcription, or image inspection for this repair pass. Mock external media boundaries in code-contract tests.
+- Preserve old takes and failed audio as evidence. Do not delete user output directories.
+- No new framework, backwards compatibility layer, merge, or external review comment.
+
+### Task 1: Repair reusable output and missing-capability contracts
+
+**Files:**
+- Modify `skills/proving-it-works-with-a-movie/examples/film-terminal.py` and `scripts/narrate`.
+- Modify `tests/proving-it-works-with-a-movie/test_terminal.py`, `test_narration.py`, `test_subtitles.py`, and `run-tests.py`.
+
+**Interfaces:** Existing recorder `film`, `run`, `key`, `watch`, and `main`; existing narration manifest; existing unittest runner.
+
+- [x] Add regressions that execute real cache/filesystem behavior with fake external synthesis/capture. Two rejected `openai-chat --verify off` invocations must both return 1 and regenerate, with failed scenes absent from the manifest; an accepted scene still caches. A cached clip rejected by strict ASR must be removed from the manifest. No actual ASR or media inspection.
+- [x] Add a frame-directory regression with existing PNGs plus a sentinel file: recording must fail before capture and preserve every byte. Test CLI refusal before connecting or typing, for run/key/watch. Keep empty/new directories valid.
+- [x] Run focused tests to observe the known failures.
+- [x] Implement the smallest guards. Before manifest append: `if sid in failures: continue`. Share a small nonempty-directory guard between the CLI preflight and direct `film()` path; use `any(out.iterdir())` only after checking existence. Report a clear error instructing the caller to use a new take directory. Guard before run/key side effects, not only inside `film`.
+- [x] Mock `module.shutil.which` in subtitle unit tests. In the real subtitle integration test call `fixtures.missing_executables("uv", "ffmpeg")` and skip before invoking `has_libass` if missing. Preserve strict runner rejection of skipped capabilities.
+- [x] Remove only `websockets` from the runner's inline dependency list.
+- [x] Run narration and recorder unit tests. Run subtitle tests with an isolated PATH containing uv and no FFmpeg; ordinary mode must pass with a capability skip, strict mode must fail because of that skip. Do not run media integration tests with FFmpeg available.
+- [x] Self-review and commit only owned files. Report commands, results, commits, and any concerns.
+
+### Task 2: Make Windows recipes executable from a fresh directory
+
+**Files:** Modify `skills/proving-it-works-with-a-movie/recording-a-terminal.md`; record local before/after instruction evidence separately from shipped guidance.
+
+**Interfaces:** Existing serve/run/key/watch/close CLI, readiness JSON, exit codes 0/1/2.
+
+- [x] Preserve current docs as the baseline. Have fresh readers identify and exercise setup and invocation for each shell without consulting recorder source. Record outcomes against the unchanged recipe. The actual PowerShell recipe creates the cwd indirectly and passes; the missing-cwd review finding is not reproduced.
+- [x] Add `[System.IO.Directory]::CreateDirectory($work) | Out-Null` before PowerShell serve. Use literal-path checks for readiness because the sample directory contains brackets.
+- [x] Replace the Git Bash shorthand with a complete Bash block: `skill=$(cygpath -m /c/path/to/skills/proving-it-works-with-a-movie)`, `work=$(cygpath -m "$HOME/movie O'Brien λ & [take]")`, `mkdir -p "$work"`, `film="$skill/examples/film-terminal.py"`, then `uv run --script "$film" ...` with `--shell gitbash`. Explain the harness-owned background serve lifetime and readiness before commands.
+- [x] Explain that each take needs an empty/new directory; return code 2 means the command remains active and should continue through key/watch. Include cleanup and keep the Unix section untouched.
+- [x] Use fresh readers for corrected-doc trials on native Windows. Verify shell startup, cwd, persistent state, status handling, and close; do not grade media. Record exact commands, docs revision, and limitations. Cover PowerShell 5.1 and 7 plus Git Bash without a cross-product matrix.
+- [x] Commit the corrected recipe. Review the complete repair diff against the reproduced comments; keep final media acceptance with Drew.
+
+## Results
+
+- Code repair: `4d4ede29`; 10 narration tests, 8 recorder unit tests, and 4 subtitle tests passed. The FFmpeg-dependent integration test was skipped; strict mode rejected that skip.
+- Fresh-reader baseline: Git Bash failed on the copied PowerShell call operator; PowerShell 7 passed the nested session/cwd recipe.
+- Corrected recipes passed on native Windows PowerShell 5.1, PowerShell 7, and Git Bash: echo, persistent state, interactive key, long-command watch, and close. PowerShell quoted-command arguments were checked in both versions.
+- An initial PowerShell 5.1 candidate exposed native argument quote loss. Final examples use Read-Host/Start-Sleep, with verified version-specific quoting guidance. PowerShell can retain a true success flag after a parse error; the guidance now states that limitation.
+- These are bounded instruction trials, not proof of automatic skill discovery or a full adversarial evaluation of the imported skill. Drew retains movie acceptance.
+- The worker accidentally ran one integration test that checked temporary test frames before restricting subsequent execution to unit tests. Drew was informed; that run is excluded from acceptance evidence.
+- Detailed local reports, command logs, and preserved failures are under `.superpowers/sdd/2026-09-11-movie-review-fixes/`.
diff --git a/docs/superpowers/specs/2026-09-09-proof-movie-windows-completion-design.md b/docs/superpowers/specs/2026-09-09-proof-movie-windows-completion-design.md
new file mode 100644
index 0000000..84b2aaa
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-09-proof-movie-windows-completion-design.md
@@ -0,0 +1,72 @@
+# Finish Windows support for the movie skill
+
+## Goal and limits
+
+An agent on native Windows can use the existing movie skill from **PowerShell 5.1, PowerShell 7, or Git Bash** to capture real software, generate local narration, assemble the movie, add subtitles, and apply the existing movie verification gate.
+
+- Both the invoking shell and the recorded shell must work. The acceptance rows pair each invoking shell with the same recorded shell; a nine-combination shell matrix is unnecessary.
+- PowerShell does not require Git Bash. Native Windows does not require WSL, tmux, Docker, administrator rights, a cloud key, or changes to machine settings.
+- Reuse native Python/uv, FFmpeg/ffprobe, Chromium-family browsers, ttyd, and the existing local voice/transcription dependencies. First use may download prerequisites and models; document that setup separately from recording.
+- Keep the existing five tool CLIs, scene kinds, narration manifest, offsets, SRT files, and checker behavior. Preserve the existing Unix terminal recipe and macOS/Linux behavior.
+- Validated on native Windows 11 x64. Support for other Windows releases or architectures is not inferred.
+
+This is a Windows port. It does not deliver a general process-management framework, a cross-platform recorder rewrite, a new eval harness, or a new OS/architecture certification matrix. Existing Linux, Mac, WSL, Rosetta, and offline-isolation setup may be reused when useful; extending that setup is not a deliverable.
+
+## 1. Finish the existing media tools
+
+| Area | Required resulting behavior |
+| --- | --- |
+| Invocation | All five extensionless scripts work with `uv run --script <path> ...` from each Windows shell. Documentation uses each shell's own quoting and environment syntax. Existing Unix shebang execution remains usable. |
+| Browser and cards | Discover installed Chrome or Edge in standard Windows user/machine locations and on PATH; keep existing Mac/Linux discovery. An explicit `--browser` is authoritative: an unusable value reports an error. Render local HTML using `Path.resolve().as_uri()`, an owned temporary browser profile, and a bounded timeout. Verify the screenshot exists. Release the browser processes launched by this render on success/failure without touching the user's browser. |
+| Subtitle paths | For hard subtitles, copy the SRT to a safe fixed basename in a temporary directory and run FFmpeg there, using absolute movie/output paths. This avoids interpreting drive letters, apostrophes, and backslashes as filter syntax. Preserve explicit soft-subtitle mode and the existing no-libass fallback, with accurate diagnostics. A burn failure must not be reported as missing libass. |
+| Text | Read/write YAML, JSON, HTML, SRT, and transcription text with explicit UTF-8, accepting UTF-8 BOM where shell-generated input requires it. CRLF input is valid. Unicode paths/content must survive native Windows defaults, including PowerShell 5.1. Machine-readable helper results must not depend on the console code page. |
+| Local transcription | Replace the failing nested `python3` launch with a Windows-compatible uv-managed Python invocation isolated from the project being filmed. Return transcript data separately from library stdout diagnostics. Under `--verify on`, transcribe both newly generated and reused cached WAVs: an unchanged manifest or a prior `--verify off` run does not establish verification. Missing, malformed, or failed transcription is nonzero under `on`; `auto` may report verification unavailable, and `off` remains explicit. Preserve existing drift thresholds. |
+
+The narration change addresses observed failures: native Windows could synthesize audio but silently skip requested transcription, and a native-library stdout warning could be mistaken for transcript text. Do not change the checker's general acceptance policy as part of this fix.
+
+## 2. Provide a usable Windows terminal example
+
+Windows has no tmux, so `examples/film-terminal.py` stands in for it, keeping
+the Unix route's shape: ttyd serves the shell, a headless Chrome or Edge page
+renders it, screenshots are the frames. `serve` starts both, keeps them alive
+in a harness-owned background task, and appends the raw terminal output to a
+log. `run`, `key`, `watch`, and `close` are one-shot CDP calls against that
+browser, so the shell, its variables, and its cwd persist across separate
+tool calls with no daemon protocol.
+
+- The installed prompt reports a counter, the shell's success flag, the last
+ native exit code, and the cwd through the window title, which the picture
+ never shows. `run` types a command, waits for the next prompt, and prints
+ that status as JSON; it exits 1 when the command failed and 2 when it is
+ still running after `--seconds`.
+- Capture is bounded `Page.captureScreenshot` at 5 fps in a fixed 1600×900
+ viewport. Frames sit on the 0.2-second grid and a slow screenshot repeats
+ the previous frame, so every `--record` directory is a `kind: frames` scene
+ at `rate: 5` for the assembler.
+- `serve` refuses a blank canvas at readiness and exits nonzero if the
+ browser or ttyd connection drops. `close` kills ttyd, the browser, and
+ their descendants (`taskkill /T` on Windows) and removes the browser
+ profile.
+- The script does not check which OS it runs on, which is how its session
+ tests run on macOS too; the Unix route stays the tmux recipe.
+
+## 3. Update only the Windows-facing guidance
+
+Update the existing skill/route documents where Unix-only commands block Windows use. Keep their existing evidence standards and terminology.
+
+- Provide complete PowerShell and Git Bash command sequences for the five tools and terminal example. Record how PowerShell 5.1 writes UTF-8 files and how both shells preserve producer exit status when logging.
+- Explain the distinct choices of invoking shell and recorded shell, foreground lifetime, take boundaries, fixed viewport, and cleanup.
+- Include a Windows FFmpeg `gdigrab` desktop preflight alongside the existing macOS recipe, using a scratch output directory. Verify it in the available ordinary-user interactive desktop session. Document unavailable/locked-desktop capture honestly: a log reel proves a run, not uncaptured GUI behavior.
+- Retain browser-driven motion, stills, existing movie segments, and log reels as existing routes through the same media tools. No new scene language or browser automation framework is needed.
+- Correct the current dangling terminal-example reference so Unix and Windows instructions point to what actually exists.
+
+## 4. Validation
+
+Each of PowerShell 5.1, PowerShell 7, and Git Bash on Windows 11 x64 produced
+a complete narrated, hard-subtitled movie from a title card, a still, real
+browser clicks, two terminal takes across separate tool calls, and a source
+movie segment, using local Piper narration verified by local transcription,
+with the checker passing. The recorder's session tests pass on Windows 11 for
+all three shells and on macOS against a real ttyd; the media suites were also
+run on Linux during development. Full-desktop `gdigrab` capture returned only
+wallpaper on the test host; window-title capture worked.
diff --git a/skills/proving-it-works-with-a-movie/SKILL.md b/skills/proving-it-works-with-a-movie/SKILL.md
index 58353f2..78c7d5c 100644
--- a/skills/proving-it-works-with-a-movie/SKILL.md
+++ b/skills/proving-it-works-with-a-movie/SKILL.md
@@ -33,6 +33,12 @@ that quietly fakes one beat is worthless as evidence for any beat.
## The gate — every route, before you hand anything over
+On native Windows, use the complete PowerShell or Git Bash sequence in
+assembling.md and the native example in recording-a-terminal.md. Invoke all
+five tools with `uv run --script`; Windows does not execute their Unix shebangs.
+
+The Unix sequence:
+
```bash
# $SKILL_DIR is this skill's own directory - the "Base directory for this
# skill" path printed when it loads. Installed as a plugin that is
diff --git a/skills/proving-it-works-with-a-movie/assembling.md b/skills/proving-it-works-with-a-movie/assembling.md
index a11d0dc..e6da417 100644
--- a/skills/proving-it-works-with-a-movie/assembling.md
+++ b/skills/proving-it-works-with-a-movie/assembling.md
@@ -102,3 +102,69 @@ the repo. Scratch directories are cleaned by the OS between sessions; losing
the assembler mid-production means reconstructing it from prose before you
can re-cut a single scene. Ask before committing large media; the *pipeline*
is small and always worth committing.
+
+## Native Windows: the five tools
+
+Use native `uv`, FFmpeg and ffprobe on the test process's PATH. Hard subtitles
+require FFmpeg's `subtitles` filter (libass). Install Chrome or Edge for cards.
+The tools' Python environments are managed by uv and need Python 3.10+.
+First use can
+download Python, script dependencies, the local Piper voice, and the local
+transcription model. Do that setup before recording. No cloud key is required.
+PowerShell needs neither Git Bash nor WSL, tmux, Docker, or administrator rights.
+
+Keep the whole skill directory together: the scripts import their adjacent
+helpers. Set `skill` to the skill's loaded base directory, and write a scene
+file in `work`. Scene kinds remain `card`, `image`, `frames`, and `movie`;
+`kind: movie` retains the source clip's own audio. Other scenes can have
+`narration`. Use the measured assembly offsets for subtitles.
+
+PowerShell 5.1 and 7 (each native exit code is checked before continuing):
+
+```powershell
+$skill = 'C:/path/to/skills/proving-it-works-with-a-movie'
+$work = "$HOME/movie O'Brien λ & [take]"
+[IO.Directory]::CreateDirectory($work) | Out-Null
+& uv run --script "$skill/scripts/narrate" "$work/scenes.yaml" "$work/narration" --engine piper --verify on
+if ($LASTEXITCODE -ne 0) { throw 'narrate failed' }
+& uv run --script "$skill/scripts/assemble" "$work/scenes.yaml" "$work/cut.mp4" --narration "$work/narration" --work "$work/assembly work"
+if ($LASTEXITCODE -ne 0) { throw 'assemble failed' }
+& uv run --script "$skill/scripts/make-subtitles" "$work/narration/manifest.json" "$work/movie.srt" --offsets-json "$work/assembly work/offsets.json"
+if ($LASTEXITCODE -ne 0) { throw 'make-subtitles failed' }
+& uv run --script "$skill/scripts/burn-subtitles" "$work/cut.mp4" "$work/movie.srt" "$work/movie.mp4"
+if ($LASTEXITCODE -ne 0) { throw 'burn-subtitles failed' }
+& uv run --script "$skill/scripts/check-movie" "$work/movie.mp4" --out "$work/evidence" --json
+if ($LASTEXITCODE -ne 0) { throw 'check-movie failed' }
+```
+
+Git Bash: convert paths to native Windows form before passing them to native
+uv/Python/FFmpeg. In particular, Python can interpret `/c/...` as `C:\c\...`.
+Keep each path quoted; an apostrophe is literal inside Bash double quotes.
+
+```bash
+set -euo pipefail
+skill=$(cygpath -m '/c/path/to/skills/proving-it-works-with-a-movie')
+work=$(cygpath -m "$HOME/movie O'Brien λ & [take]")
+mkdir -p "$work"
+uv run --script "$skill/scripts/narrate" "$work/scenes.yaml" "$work/narration" --engine piper --verify on
+uv run --script "$skill/scripts/assemble" "$work/scenes.yaml" "$work/cut.mp4" --narration "$work/narration" --work "$work/assembly work"
+uv run --script "$skill/scripts/make-subtitles" "$work/narration/manifest.json" "$work/movie.srt" --offsets-json "$work/assembly work/offsets.json"
+uv run --script "$skill/scripts/burn-subtitles" "$work/cut.mp4" "$work/movie.srt" "$work/movie.mp4"
+uv run --script "$skill/scripts/check-movie" "$work/movie.mp4" --out "$work/evidence" --json
+```
+
+Keep `movie.srt` beside `movie.mp4`: the checker discovers that basename.
+Inspect the finished contact sheet and hard captions, then transcribe the
+rendered audio as described in narrating.md. A successful soft-subtitle
+fallback is not proof that captions were burned into the picture.
+
+PowerShell 5.1's `Out-File` defaults to UTF-16. For scene YAML/JSON, request
+JSON, HTML, and SRT, write UTF-8 explicitly:
+
+```powershell
+[IO.File]::WriteAllText($path, $json, [Text.UTF8Encoding]::new($false))
+```
+
+Use `-LiteralPath` for PowerShell file operations on paths containing brackets.
+BOM-bearing UTF-8 and CRLF scene input are supported; a console's displayed
+encoding is not a reliable way to check the bytes in a JSON file.
diff --git a/skills/proving-it-works-with-a-movie/examples/film-terminal.py b/skills/proving-it-works-with-a-movie/examples/film-terminal.py
new file mode 100644
index 0000000..3cc80de
--- /dev/null
+++ b/skills/proving-it-works-with-a-movie/examples/film-terminal.py
@@ -0,0 +1,531 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.10"
+# dependencies = ["websocket-client==1.9.0", "pillow"]
+# ///
+"""Film a shell on native Windows, where there is no tmux.
+
+ttyd serves the shell over HTTP and a headless Chrome or Edge page renders
+it: the same picture the Unix route in recording-a-terminal.md gets. `serve`
+stands in for tmux: it holds the only ttyd client open so the shell survives
+between tool calls, and appends the raw terminal output to
+SESSION/terminal.log. Every other verb is one short CDP call against that
+browser.
+
+ serve SESSION --shell powershell51|powershell7|gitbash [--cwd DIR]
+ hold the session open; run it in a background task
+ run SESSION 'command' [--record OUT] [--seconds 60] [--hold 1.5]
+ type the command, film until the prompt returns, print its status
+ key SESSION Enter|Escape|Tab|Ctrl-C|ArrowDown|q [--record OUT]
+ press one key
+ watch SESSION --record OUT [--seconds 30]
+ film without typing: a TUI after a key, or the tail of long work
+ close SESSION
+ kill ttyd, the browser, and everything they started
+
+The prompt `serve` installs reports each command's status through the
+window title, which the picture never shows, so `run` can print it.
+"""
+import argparse
+import base64
+import io
+import json
+import os
+import re
+import shutil
+import socket
+import subprocess
+import sys
+import time
+import urllib.request
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
+from browser_tools import find_browser, kill_process_tree # noqa: E402
+
+FPS = 5
+WIDTH, HEIGHT = 1600, 900
+# Title set by the installed prompt: MOVIE;<count>;<ok>;<native exit>;<cwd>
+MARKER = re.compile(rb"\x1b\][012];MOVIE;(\d+);([01]);(-?\d*);([^\x07\x1b]*)(?:\x07|\x1b\\)")
+SHELLS = {
+ "powershell51": (["-NoLogo", "-NoProfile", "-NoExit"], "powershell"),
+ "powershell7": (["-NoLogo", "-NoProfile", "-NoExit"], "pwsh"),
+ "gitbash": (["--noprofile", "--norc", "-i"], "bash"),
+ "bash": (["--noprofile", "--norc", "-i"], "bash"),
+}
+PROMPTS = {
+ "powershell": r'''$global:MovieN = 0
+function global:prompt {
+ $ok = $?; $native = $global:LASTEXITCODE; $global:MovieN++
+ $Host.UI.RawUI.WindowTitle = "MOVIE;$global:MovieN;$([int]$ok);$native;$PWD"
+ "PS $PWD> "
+}
+Clear-Host''',
+ "bash": r'''MOVIE_N=0
+movie_prompt() { local s=$?; MOVIE_N=$((MOVIE_N + 1)); printf '\033]0;MOVIE;%s;%s;%s;%s\a' "$MOVIE_N" "$((s == 0))" "$s" "$PWD"; }
+PROMPT_COMMAND=movie_prompt
+PS1='\w \$ '
+clear''',
+}
+KEYS = {
+ "Enter": dict(key="Enter", code="Enter", windowsVirtualKeyCode=13, text="\r"),
+ "Escape": dict(key="Escape", code="Escape", windowsVirtualKeyCode=27),
+ "Tab": dict(key="Tab", code="Tab", windowsVirtualKeyCode=9, text="\t"),
+ "ArrowLeft": dict(key="ArrowLeft", code="ArrowLeft", windowsVirtualKeyCode=37),
+ "ArrowUp": dict(key="ArrowUp", code="ArrowUp", windowsVirtualKeyCode=38),
+ "ArrowRight": dict(key="ArrowRight", code="ArrowRight", windowsVirtualKeyCode=39),
+ "ArrowDown": dict(key="ArrowDown", code="ArrowDown", windowsVirtualKeyCode=40),
+ "Ctrl-C": dict(key="c", code="KeyC", windowsVirtualKeyCode=67, modifiers=2),
+}
+
+
+def shell_family(kind):
+ return "bash" if kind in ("bash", "gitbash") else "powershell"
+
+
+def shell_argv(kind, explicit=None):
+ flags, default = SHELLS[kind]
+ exe = explicit
+ if not exe and kind == "gitbash":
+ # PATH may hold WSL's bash.exe; only Git's is a native Windows shell.
+ for root in (os.environ.get("ProgramFiles"), os.environ.get("ProgramW6432")):
+ if root and (Path(root) / "Git/bin/bash.exe").is_file():
+ exe = str(Path(root) / "Git/bin/bash.exe")
+ exe = exe or shutil.which(default)
+ if not exe:
+ raise SystemExit(f"cannot find the {kind} executable; pass --shell-exe")
+ return [str(Path(exe).resolve()), *flags]
+
+
+def prompt_script(kind, cwd):
+ """Enter the cwd (ttyd's own -w is unreliable), install the status prompt, clear."""
+ if shell_family(kind) == "bash":
+ quoted = "'" + str(cwd).replace("\\", "/").replace("'", "'\\''") + "'"
+ return f"cd -- {quoted}\n" + PROMPTS["bash"]
+ quoted = "'" + str(cwd).replace("'", "''") + "'"
+ return f"Set-Location -LiteralPath {quoted}\n" + PROMPTS["powershell"]
+
+
+def prompt_command(kind, cwd):
+ """One typed line that runs prompt_script without any quoting hazards."""
+ encoded = base64.b64encode(prompt_script(kind, cwd).encode("utf-8")).decode()
+ if shell_family(kind) == "bash":
+ return f'eval "$(printf %s {encoded} | base64 -d)"'
+ return (". ([scriptblock]::Create([Text.Encoding]::UTF8.GetString("
+ f"[Convert]::FromBase64String('{encoded}'))))")
+
+
+VISIBLE = re.compile(rb"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\\\)|\x1b\[[0-?]*[ -/]*[@-~]|\r")
+
+
+def at_prompt(log):
+ """True when the visible text so far ends in a shell prompt (`$` or `>`)."""
+ return VISIBLE.sub(b"", log).rstrip(b" \t\n").endswith((b"$", b">"))
+
+
+def prompts(log):
+ """Every status the installed prompt has reported in these bytes, oldest first."""
+ return [dict(n=int(m[1]), ok=m[2] == b"1", exit_code=int(m[3]) if m[3] else None,
+ cwd=m[4].decode("utf-8", "replace")) for m in MARKER.finditer(log)]
+
+
+def key_params(key):
+ if key in KEYS:
+ return dict(KEYS[key])
+ if len(key) == 1 and key.isprintable():
+ return dict(key=key, text=key)
+ raise SystemExit(f"unknown key {key!r}: use one character or one of {', '.join(KEYS)}")
+
+
+def require_empty_take(out):
+ if out.exists() and any(out.iterdir()):
+ raise SystemExit(f"{out} is not empty: use a new take directory")
+
+
+def film(out, seconds, hold, capture, finished, clock=time.monotonic, sleep=time.sleep):
+ """Write PNG frames on the FPS grid until `finished()` plus `hold` seconds,
+ or `seconds` in all. A slow capture repeats the previous frame, so the
+ directory plays back at exactly FPS. Returns the frame count."""
+ require_empty_take(out)
+ out.mkdir(parents=True, exist_ok=True)
+ start, index, last, stop = clock(), -1, None, None
+ while True:
+ now = clock()
+ if stop is None and finished():
+ stop = now + hold
+ if now - start >= seconds or (stop is not None and now >= stop):
+ return index + 1
+ slot = int((now - start) * FPS)
+ if slot > index:
+ png = capture()
+ for missed in range(index + 1, slot):
+ (out / f"f{missed:05d}.png").write_bytes(last or png)
+ (out / f"f{slot:05d}.png").write_bytes(png)
+ index, last = slot, png
+ sleep(0.02)
+
+
+class CDP:
+ def __init__(self, url):
+ import websocket
+
+ self.ws = websocket.create_connection(url, timeout=5, suppress_origin=True)
+ self.count, self.on_event = 0, None
+
+ def recv(self, timeout):
+ import websocket
+
+ self.ws.settimeout(timeout)
+ try:
+ raw = self.ws.recv()
+ except websocket.WebSocketTimeoutException:
+ return None
+ if not raw:
+ raise ConnectionError("browser connection closed")
+ message = json.loads(raw)
+ if "id" not in message and self.on_event:
+ self.on_event(message)
+ return message
+
+ def call(self, method, params=None, timeout=10):
+ self.count += 1
+ self.ws.send(json.dumps({"id": self.count, "method": method, "params": params or {}}))
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ message = self.recv(0.05)
+ if message and message.get("id") == self.count:
+ if "error" in message:
+ raise RuntimeError(f"{method}: {message['error']}")
+ return message.get("result", {})
+ raise TimeoutError(f"{method} took longer than {timeout:g}s")
+
+
+def free_port():
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
+def page_url(debug_port):
+ with urllib.request.urlopen(f"http://127.0.0.1:{debug_port}/json/list", timeout=2) as response:
+ pages = json.load(response)
+ return next(page["webSocketDebuggerUrl"] for page in pages if page["type"] == "page")
+
+
+def connect(session):
+ return CDP(page_url(session["debug_port"]))
+
+
+def type_text(cdp, text):
+ cdp.call("Runtime.evaluate", {"expression": "document.querySelector('.xterm-helper-textarea').focus()"})
+ cdp.call("Input.insertText", {"text": text})
+
+
+def press(cdp, key):
+ params = key_params(key)
+ cdp.call("Input.dispatchKeyEvent", dict(type="keyDown", **params))
+ cdp.call("Input.dispatchKeyEvent", dict(type="keyUp", **{k: v for k, v in params.items() if k != "text"}))
+
+
+def screenshot(cdp):
+ return base64.b64decode(cdp.call("Page.captureScreenshot", {"format": "png"}, timeout=5)["data"])
+
+
+def tail(path, size=262144):
+ with path.open("rb") as handle:
+ handle.seek(max(0, handle.seek(0, os.SEEK_END) - size))
+ return handle.read()
+
+
+def read_json(path):
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def write_json(path, value):
+ path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
+def load_session(directory):
+ if not (directory / "ready.json").is_file():
+ raise SystemExit(f"{directory} has no ready.json: is `serve` running there?")
+ return read_json(directory / "session.json")
+
+
+def lit_fraction(png):
+ from PIL import Image
+
+ image = Image.open(io.BytesIO(png)).convert("L")
+ return sum(image.histogram()[91:]) / (image.width * image.height)
+
+
+def serve(args):
+ directory = args.session
+ if directory.exists() and any(directory.iterdir()):
+ raise SystemExit(f"{directory} is not empty: use a new session directory")
+ directory.mkdir(parents=True, exist_ok=True)
+ cwd = Path(args.cwd or os.getcwd()).resolve()
+ if not cwd.is_dir():
+ raise SystemExit(f"--cwd is not a directory: {cwd}")
+ shell = shell_argv(args.shell, args.shell_exe)
+ ttyd = args.ttyd or shutil.which("ttyd")
+ if not ttyd:
+ raise SystemExit("ttyd is not on PATH; pass --ttyd")
+ browser = find_browser(args.browser)
+ if not browser:
+ raise SystemExit("no Chrome or Edge found; pass --browser")
+ port, debug_port = free_port(), free_port()
+ unix = os.name != "nt"
+ # ttyd 1.7 on Windows needs -w but decodes it in the ANSI code page, so
+ # pass "." and let the shell inherit this process's Unicode cwd; the
+ # installed prompt script then cds there explicitly and reports back.
+ ttyd_argv = [ttyd, "-i", "127.0.0.1", "-p", str(port), "-W", "-m", "1", "-w", ".",
+ "-t", "fontSize=17", *shell]
+ # Software GL: without it a GPU-less session paints the xterm canvas empty.
+ browser_argv = [browser, "--headless=new", "--no-first-run", "--no-default-browser-check",
+ "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader",
+ "--disable-background-networking", "--remote-debugging-address=127.0.0.1",
+ f"--remote-debugging-port={debug_port}", f"--user-data-dir={directory / 'profile'}",
+ f"--window-size={WIDTH},{HEIGHT}", "--hide-scrollbars", "about:blank"]
+ logs = [(directory / "ttyd.log").open("ab"), (directory / "browser.log").open("ab")]
+ processes = [
+ subprocess.Popen(ttyd_argv, cwd=cwd, stdin=subprocess.DEVNULL, stdout=logs[0],
+ stderr=subprocess.STDOUT, start_new_session=unix),
+ subprocess.Popen(browser_argv, cwd=directory, stdin=subprocess.DEVNULL, stdout=logs[1],
+ stderr=subprocess.STDOUT, start_new_session=unix),
+ ]
+ session = dict(shell=args.shell, cwd=str(cwd), terminal_url=f"http://127.0.0.1:{port}/",
+ debug_port=debug_port, pids=[process.pid for process in processes])
+ write_json(directory / "session.json", session)
+ output = (directory / "terminal.log").open("ab")
+ state = {"closed": False}
+
+ def on_event(event):
+ if event["method"] == "Network.webSocketFrameReceived":
+ frame = event["params"]["response"]
+ raw = base64.b64decode(frame["payloadData"]) if frame["opcode"] == 2 else frame["payloadData"].encode()
+ if raw[:1] == b"0": # ttyd frame type 0 is terminal output
+ output.write(raw[1:])
+ output.flush()
+ elif event["method"] == "Network.webSocketClosed":
+ state["closed"] = True
+
+ def pump_until(condition, timeout, failure):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ cdp.recv(0.05)
+ if state["closed"]:
+ raise ConnectionError("the terminal connection closed")
+ if condition():
+ return
+ (directory / "timeout.png").write_bytes(screenshot(cdp))
+ raise TimeoutError(f"{failure}; terminal output so far: {tail(directory / 'terminal.log')[-300:]!r}")
+
+ def pump_while_output_flows(quiet):
+ # A shell's banner and first prompt can trickle out; type only once
+ # it has been silent for `quiet` seconds.
+ deadline, seen = time.monotonic() + quiet, output.tell()
+ while time.monotonic() < deadline:
+ cdp.recv(0.05)
+ if state["closed"]:
+ raise ConnectionError("the terminal connection closed")
+ if output.tell() != seen:
+ deadline, seen = time.monotonic() + quiet, output.tell()
+
+ code = 1
+ try:
+ deadline = time.monotonic() + 20
+ while True:
+ try:
+ cdp = CDP(page_url(debug_port))
+ break
+ except (OSError, StopIteration) as error:
+ if time.monotonic() > deadline:
+ raise TimeoutError(f"browser did not start: {error}") from None
+ time.sleep(0.1)
+ cdp.on_event = on_event
+ cdp.call("Network.enable") # before navigation, or the terminal socket is never reported
+ cdp.call("Page.enable")
+ cdp.call("Emulation.setDeviceMetricsOverride",
+ {"width": WIDTH, "height": HEIGHT, "deviceScaleFactor": 1, "mobile": False})
+ cdp.call("Page.navigate", {"url": session["terminal_url"]})
+ # Type only once the shell is reading input: its own prompt is on
+ # screen and nothing more has arrived for a moment.
+ pump_until(lambda: at_prompt(tail(directory / "terminal.log")), 20, "the shell never showed a prompt")
+ pump_while_output_flows(0.5)
+ # Git Bash under ConPTY can lose the first keystroke of a session.
+ # Spend it on a bare Enter, which only repaints the prompt.
+ press(cdp, "Enter")
+ pump_while_output_flows(0.5)
+ type_text(cdp, prompt_command(args.shell, cwd))
+ press(cdp, "Enter")
+ pump_until(lambda: prompts(tail(directory / "terminal.log")), 15,
+ "the shell never showed the installed prompt")
+ prompt = prompts(tail(directory / "terminal.log"))[-1]
+ if shell_family(args.shell) == "powershell":
+ entered = os.path.normcase(os.path.normpath(prompt["cwd"])) == os.path.normcase(str(cwd))
+ else: # Git Bash reports /c/... paths, so compare the leaf directory
+ entered = Path(prompt["cwd"]).name == cwd.name
+ if not entered:
+ raise RuntimeError(f"the shell is in {prompt['cwd']!r}, not {str(cwd)!r}")
+
+ def typed(text): # type one line and wait for the prompt after it
+ before = prompts(tail(directory / "terminal.log"))[-1]["n"]
+ type_text(cdp, text)
+ press(cdp, "Enter")
+ pump_until(lambda: prompts(tail(directory / "terminal.log"))[-1]["n"] > before, 15,
+ f"no prompt after typing {text[:24]!r}")
+
+ # Preflight as the Unix route does: print something dense, refuse a blank canvas.
+ typed("echo '" + "#" * 120 + "'")
+ time.sleep(0.3)
+ png = screenshot(cdp)
+ (directory / "ready.png").write_bytes(png)
+ lit = lit_fraction(png)
+ if lit < 0.002:
+ raise RuntimeError(f"the terminal renders blank ({lit:.4%} lit pixels); see ready.png")
+ typed("clear")
+ time.sleep(0.3)
+ prompt = prompts(tail(directory / "terminal.log"))[-1]
+ write_json(directory / "ready.json", dict(session, prompt=prompt, lit=round(lit, 4)))
+ print(json.dumps({"ready": True, "session": str(directory), "cwd": prompt["cwd"]},
+ ensure_ascii=False), flush=True)
+ while not (directory / "stop").exists():
+ cdp.recv(0.2)
+ if state["closed"]:
+ raise ConnectionError("the terminal connection closed")
+ code = 0
+ except KeyboardInterrupt:
+ code = 0
+ except Exception as error: # noqa: BLE001 - report, then clean up below
+ print(f"serve: {error}", file=sys.stderr)
+ code = 0 if (directory / "stop").exists() else 1
+ finally:
+ for process in processes:
+ kill_process_tree(process.pid)
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
+ for handle in (output, *logs):
+ handle.close()
+ return code
+
+
+def observe(args, cdp, n0):
+ """Film or wait until the prompt after `n0` appears; print the status."""
+ log = args.session / "terminal.log"
+
+ def latest():
+ return next((p for p in reversed(prompts(tail(log))) if p["n"] > n0), None)
+
+ frames = 0
+ if args.record:
+ frames = film(args.record, args.seconds, args.hold, lambda: screenshot(cdp), lambda: latest() is not None)
+ else:
+ deadline = time.monotonic() + args.seconds
+ while latest() is None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ prompt = latest()
+ result = {"outcome": "completed" if prompt else "running"}
+ if prompt:
+ result.update(ok=prompt["ok"], exit_code=prompt["exit_code"], cwd=prompt["cwd"])
+ if args.record:
+ result["frames"] = frames
+ result["scene"] = {"kind": "frames", "src": str(args.record.resolve()), "rate": FPS}
+ write_json(args.record / "take.json", result)
+ print(json.dumps(result, ensure_ascii=False))
+ return 2 if not prompt else 0 if prompt["ok"] else 1
+
+
+def last_prompt_number(directory):
+ reported = prompts(tail(directory / "terminal.log"))
+ return reported[-1]["n"] if reported else 0
+
+
+def run(args):
+ session = load_session(args.session)
+ n0 = last_prompt_number(args.session)
+ cdp = connect(session)
+ type_text(cdp, args.command)
+ press(cdp, "Enter")
+ write_json(args.session / "mark.json", {"n": n0})
+ return observe(args, cdp, n0)
+
+
+def key(args):
+ session = load_session(args.session)
+ n0 = last_prompt_number(args.session)
+ cdp = connect(session)
+ cdp.call("Runtime.evaluate", {"expression": "document.querySelector('.xterm-helper-textarea').focus()"})
+ press(cdp, args.key)
+ write_json(args.session / "mark.json", {"n": n0})
+ return observe(args, cdp, n0)
+
+
+def watch(args):
+ session = load_session(args.session)
+ # Wait for the prompt after the last run/key, even if it already returned.
+ mark = args.session / "mark.json"
+ n0 = read_json(mark)["n"] if mark.exists() else last_prompt_number(args.session)
+ return observe(args, connect(session), n0)
+
+
+def close(args):
+ session = read_json(args.session / "session.json")
+ (args.session / "stop").write_text("")
+ for pid in session["pids"]:
+ kill_process_tree(pid)
+ for _ in range(50): # the browser releases its profile shortly after dying
+ try:
+ shutil.rmtree(args.session / "profile")
+ break
+ except FileNotFoundError:
+ break
+ except OSError:
+ time.sleep(0.1)
+ print(json.dumps({"closed": True}))
+ return 0
+
+
+def main():
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(errors="backslashreplace")
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ verbs = parser.add_subparsers(dest="verb", required=True)
+
+ def filming(sub, seconds):
+ sub.add_argument("--record", type=Path, help="write PNG frames here at 5 fps")
+ sub.add_argument("--seconds", type=float, default=seconds, help="give up waiting after this long")
+ sub.add_argument("--hold", type=float, default=1.5, help="keep filming this long after the prompt returns")
+
+ sub = verbs.add_parser("serve")
+ sub.add_argument("session", type=Path)
+ sub.add_argument("--shell", choices=list(SHELLS), required=True)
+ sub.add_argument("--cwd", type=Path)
+ sub.add_argument("--shell-exe")
+ sub.add_argument("--ttyd")
+ sub.add_argument("--browser")
+ sub = verbs.add_parser("run")
+ sub.add_argument("session", type=Path)
+ sub.add_argument("command")
+ filming(sub, 60)
+ sub = verbs.add_parser("key")
+ sub.add_argument("session", type=Path)
+ sub.add_argument("key")
+ filming(sub, 30)
+ sub = verbs.add_parser("watch")
+ sub.add_argument("session", type=Path)
+ filming(sub, 30)
+ sub = verbs.add_parser("close")
+ sub.add_argument("session", type=Path)
+ args = parser.parse_args()
+ if args.verb == "watch" and not args.record:
+ parser.error("watch needs --record")
+ if getattr(args, "record", None):
+ require_empty_take(args.record)
+ return {"serve": serve, "run": run, "key": key, "watch": watch, "close": close}[args.verb](args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/proving-it-works-with-a-movie/narrating.md b/skills/proving-it-works-with-a-movie/narrating.md
index accfa21..8d5720c 100644
--- a/skills/proving-it-works-with-a-movie/narrating.md
+++ b/skills/proving-it-works-with-a-movie/narrating.md
@@ -88,3 +88,13 @@ Check the sample for your own jargon before committing to a voice. If a good
voice mangles one term, spell it phonetically **in the TTS input only**
("S M evals"), never in the script file a human reads. Keep that
substitution in the narrate step so the source text stays clean.
+
+## Native Windows local voice
+
+Use `--engine piper --verify on` with the commands in assembling.md. The
+first run downloads the Piper voice and the transcription model; later runs
+reuse those caches. `--verify on` transcribes every clip, including cached
+WAVs from an earlier run, and treats an unavailable transcriber as a failure
+rather than a pass. Afterwards, transcribe the finished movie's audio and
+compare each narrated interval with its script. A `kind: movie` segment
+keeps its own sound and is checked against its source, not a script.
diff --git a/skills/proving-it-works-with-a-movie/recording-a-terminal.md b/skills/proving-it-works-with-a-movie/recording-a-terminal.md
index 7f521bc..c78ba43 100644
--- a/skills/proving-it-works-with-a-movie/recording-a-terminal.md
+++ b/skills/proving-it-works-with-a-movie/recording-a-terminal.md
@@ -4,11 +4,142 @@ CLIs, TUIs, installs, test runs, agents at work — a large share of what is
worth proving happens in a terminal, and none of it is visible to a browser
recorder or an OS screen capture you probably can't get permission for.
+## Native Windows: `examples/film-terminal.py` stands in for tmux
+
+Windows has no tmux, so the example script holds the session instead. `serve`
+starts ttyd on the shell you name and a headless Chrome or Edge page showing
+it, keeps both alive, and appends the raw terminal output to
+`SESSION/terminal.log`. Every other verb is one short call against that
+browser. Run `serve` in a background task your harness keeps alive, the way
+the visual companion server runs; a one-shot shell that kills its children
+on return ends the session.
+
+It needs uv, ttyd, and Chrome or Edge on PATH, or `--ttyd` and `--browser`.
+`--shell powershell51|powershell7|gitbash` picks the filmed shell; the shell
+you type these commands into is a separate choice. Replace the sample
+commands below with the software you are proving.
+
+### PowerShell
+
+Run this block in a background terminal/task your harness keeps alive.
+For PowerShell 5.1 use `--shell powershell51`; for PowerShell 7 use
+`--shell powershell7`.
+
+```powershell
+$skill = 'C:/path/to/skills/proving-it-works-with-a-movie'
+$work = "$HOME/movie O'Brien λ & [take]"
+$film = "$skill/examples/film-terminal.py"
+[System.IO.Directory]::CreateDirectory($work) | Out-Null
+& uv run --script $film serve "$work/session" --shell powershell7 --cwd $work
+```
+
+In a second terminal/task, define the same paths and wait for readiness.
+Repeat these three variable definitions in each tool call if your harness
+starts a fresh shell for every call. `-LiteralPath` keeps the brackets in
+the sample directory name from being interpreted as wildcards.
+
+```powershell
+$skill = 'C:/path/to/skills/proving-it-works-with-a-movie'
+$work = "$HOME/movie O'Brien λ & [take]"
+$film = "$skill/examples/film-terminal.py"
+$deadline = (Get-Date).AddSeconds(60)
+while (-not (Test-Path -LiteralPath "$work/session/ready.json")) {
+ if ((Get-Date) -gt $deadline) { throw 'Recorder not ready; inspect the serve task output.' }
+ Start-Sleep -Milliseconds 200
+}
+& uv run --script $film run "$work/session" 'echo hello' --record "$work/take-one"
+& uv run --script $film run "$work/session" 'Read-Host' --record "$work/take-two" --seconds 2
+# Exit 2 means Read-Host is still waiting. Press Enter to finish it in a new take:
+& uv run --script $film key "$work/session" Enter --record "$work/take-three"
+# A long command can continue across calls; exit 2 here is expected too:
+& uv run --script $film run "$work/session" 'Start-Sleep -Seconds 5' --record "$work/take-four" --seconds 1
+& uv run --script $film watch "$work/session" --record "$work/take-five" --seconds 10
+& uv run --script $film close "$work/session"
+```
+
+Read `$LASTEXITCODE` immediately after each invocation. Stop on exit 1;
+exit 2 is expected while the interactive command is waiting for input.
+Always call `close` when finished, including after a failed command.
+
+When invoking from PowerShell 5.1, escape embedded double quotes with a
+backslash before passing a command to native uv: use the command argument
+`'python -c \"print(123)\"'`. PowerShell 7 preserves the quotes in
+`'python -c "print(123)"'` directly. This depends on the invoking shell,
+regardless of which shell you record.
+
+### Git Bash
+
+Convert paths passed to native uv/Python with `cygpath -m`. Run this block
+in a background terminal/task your harness keeps alive:
+
+```bash
+skill=$(cygpath -m /c/path/to/skills/proving-it-works-with-a-movie)
+work=$(cygpath -m "$HOME/movie O'Brien λ & [take]")
+film="$skill/examples/film-terminal.py"
+mkdir -p "$work"
+uv run --script "$film" serve "$work/session" --shell gitbash --cwd "$work"
+```
+
+In a second terminal/task, use the same paths. Repeat the three variable
+definitions in each tool call if it starts a fresh shell. Keep `set -e`
+off for these interactive calls so expected exit 2 does not end the script.
+
+```bash
+skill=$(cygpath -m /c/path/to/skills/proving-it-works-with-a-movie)
+work=$(cygpath -m "$HOME/movie O'Brien λ & [take]")
+film="$skill/examples/film-terminal.py"
+deadline=$((SECONDS + 60))
+until [[ -f "$work/session/ready.json" ]]; do
+ if (( SECONDS >= deadline )); then
+ printf '%s\n' 'Recorder not ready; inspect the serve task output.' >&2
+ exit 1
+ fi
+ sleep 0.2
+done
+uv run --script "$film" run "$work/session" 'echo hello' --record "$work/take-one"
+uv run --script "$film" run "$work/session" 'read -r answer' --record "$work/take-two" --seconds 2
+# Exit 2 means read is still waiting. Press Enter to finish it in a new take:
+uv run --script "$film" key "$work/session" Enter --record "$work/take-three"
+# A long command can continue across calls; exit 2 here is expected too:
+uv run --script "$film" run "$work/session" 'sleep 5' --record "$work/take-four" --seconds 1
+uv run --script "$film" watch "$work/session" --record "$work/take-five" --seconds 10
+uv run --script "$film" close "$work/session"
+```
+
+Read `$?` immediately after each invocation. Stop on exit 1; exit 2 means
+the command remains active. Always call `close` when finished, including
+after a failed command. The original `serve` task exits after `close`.
+
+`run` types the command and films at 5 fps into `--record` until the prompt
+comes back, holds 1.5 s so the result stays readable, and prints the status
+as JSON: `ok` is the shell's own success flag and `exit_code` the last native
+program's exit code, which PowerShell keeps from an earlier program when the
+command was a cmdlet. PowerShell can also leave its success flag true after
+a parse error, so check the terminal output when a command returns without
+doing the expected work. The recorder exits 1 when the shell reports failure
+and 2 when it is still running after `--seconds`. `key` presses one key and `watch` films
+without typing; both wait for the prompt the same way. Every `--record`
+directory is a `kind: frames` scene at `rate: 5`; a slow screenshot repeats
+the previous frame so the timing stays honest. Use a new or empty directory
+for every take, including retakes. A nonempty `--record` directory is refused
+before input is sent, preserving the earlier take.
+
+Long work spans takes exactly as on Unix: film the command being issued with
+a short `--seconds`, do other things, then `watch` the result as a new take.
+The shell, its variables and its cwd persist across calls until `close`,
+which kills ttyd, the browser and everything they started.
+
+The viewport is fixed at 1600×900 with a 17 px font. Look at
+`SESSION/ready.png` before filming; `serve` refuses a blank canvas, the same
+preflight as below.
+
+## Unix: tmux and ttyd
+
The technique: serve the terminal over HTTP with **ttyd**, attach it to a
**tmux** session, screenshot the page from a browser, and drive the session
with `tmux send-keys` from outside. Real characters from a real shell, in a
-window you fully control. `examples/film-terminal.py` is a working
-implementation of everything below.
+window you fully control. The commands below are the Unix recipe.
+`examples/film-terminal.py` implements the separate native Windows route.
```bash
# inside the machine/container being filmed
diff --git a/skills/proving-it-works-with-a-movie/recording-motion.md b/skills/proving-it-works-with-a-movie/recording-motion.md
index e8ccbeb..4570953 100644
--- a/skills/proving-it-works-with-a-movie/recording-motion.md
+++ b/skills/proving-it-works-with-a-movie/recording-motion.md
@@ -116,3 +116,26 @@ scene depends on a job outliving the process that started it.
only; tagging every navigation forces reloads and breaks hash routing.
- **Typed fields with parsers**: a value like `Yes`/`No`/`On`/`Off` in a
YAML-backed form field saves as a boolean and can crash the app on camera.
+
+## Native Windows desktop capture
+
+FFmpeg's `gdigrab` captures one window by its exact title, or the whole
+desktop with `-i desktop`. From an ordinary-user interactive desktop:
+
+```powershell
+$check = "$HOME/movie capture check"
+[IO.Directory]::CreateDirectory($check) | Out-Null
+$arguments = @('-nostdin','-y','-f','gdigrab','-framerate','5','-i',
+ 'title=Your application window title','-t','2',"$check/window-check.mp4")
+& ffmpeg @arguments
+if ($LASTEXITCODE -ne 0) { throw 'Window capture unavailable' }
+$arguments = @('-nostdin','-y','-i',"$check/window-check.mp4",
+ '-frames:v','1',"$check/window-check.png")
+& ffmpeg @arguments
+```
+
+Look at the PNG. A zero exit with wallpaper or a blank window is not a
+capture; only visible application pixels are. On the host this was tested
+on, the window-title form captured the app and `-i desktop` returned only
+wallpaper. If neither shows the app, use the browser route and say what
+remains unproven.
diff --git a/skills/proving-it-works-with-a-movie/scripts/assemble b/skills/proving-it-works-with-a-movie/scripts/assemble
index 690c6f9..aa8491d 100755
--- a/skills/proving-it-works-with-a-movie/scripts/assemble
+++ b/skills/proving-it-works-with-a-movie/scripts/assemble
@@ -30,16 +30,12 @@ import os
import shutil
import subprocess
import sys
-import urllib.parse
+import tempfile
from pathlib import Path
import yaml
-
-BROWSERS = [
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
- "chromium", "chromium-browser", "google-chrome", "google-chrome-stable",
-]
+from browser_tools import find_browser, render_card
+from media_paths import ffconcat_entry, stage_frames
CARD_HTML = """<!doctype html><meta charset="utf-8">
<style>
@@ -59,8 +55,9 @@ def die(msg):
sys.exit(1)
-def run(cmd):
- r = subprocess.run(cmd, capture_output=True, text=True)
+def run(cmd, *, cwd=None):
+ r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True,
+ encoding="utf-8", errors="replace")
if r.returncode != 0:
die(f"{' '.join(map(str, cmd))}\n{r.stderr.strip()[:500]}")
return r
@@ -72,18 +69,6 @@ def dur(path):
return float(r.stdout.strip())
-def find_browser(explicit):
- for cand in ([explicit] if explicit else []) + BROWSERS:
- if not cand:
- continue
- if os.path.sep in cand and Path(cand).exists():
- return cand
- found = shutil.which(cand)
- if found:
- return found
- return None
-
-
def make_card(scene, png, w, h, browser):
if not browser:
die("a `card` scene needs a browser (Chrome/Chromium) to render text; "
@@ -94,13 +79,17 @@ def make_card(scene, png, w, h, browser):
sub=scene.get("subtitle_size", max(16, h // 32)),
TITLE=scene.get("title", ""), SUB=scene.get("subtitle", ""))
tmp = png.with_suffix(".html")
- tmp.write_text(html)
- run([browser, "--headless=new", "--disable-gpu", "--hide-scrollbars",
- f"--screenshot={png}", f"--window-size={w},{h}",
- "--force-device-scale-factor=1", "file://" + urllib.parse.quote(str(tmp))])
+ tmp.write_text(html, encoding="utf-8")
+ try:
+ render_card(tmp, png, browser=browser, width=w, height=h)
+ finally:
+ tmp.unlink(missing_ok=True)
def main():
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(errors="backslashreplace")
ap = argparse.ArgumentParser()
ap.add_argument("scenes", type=Path)
ap.add_argument("out", type=Path)
@@ -113,7 +102,7 @@ def main():
if not shutil.which(tool):
die(f"{tool} not on PATH")
- doc = yaml.safe_load(args.scenes.read_text())
+ doc = yaml.safe_load(args.scenes.read_text(encoding="utf-8-sig"))
base = args.scenes.parent
res = doc.get("resolution", {}) or {}
W, H = int(res.get("width", 1920)), int(res.get("height", 1080))
@@ -146,16 +135,28 @@ def main():
"-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-ar", "44100", "-ac", "2", str(seg)])
else:
+ frame_staging = None
if kind == "frames":
src = base / sc["src"]
- n = len(list(Path(src).glob("*.png")))
- if not n:
- die(f"scene {sid}: no PNGs in {src}")
rate = float(sc.get("rate", FPS))
+ frame_staging = tempfile.TemporaryDirectory(
+ prefix=f"frames-{sid}-", dir=work
+ )
+ try:
+ staged = stage_frames(
+ src, Path(frame_staging.name) / "sequence"
+ )
+ except ValueError as error:
+ frame_staging.cleanup()
+ die(f"scene {sid}: {error}")
+ except BaseException:
+ frame_staging.cleanup()
+ raise
+ n = len(staged)
vis = n / rate
target = max(nard, vis)
- vin = ["-framerate", str(rate), "-pattern_type", "glob",
- "-i", str(Path(src) / "*.png")]
+ vin = ["-framerate", str(rate), "-start_number", "0",
+ "-i", str(staged[0].parent / "frame-%08d.png")]
# freeze the last frame when narration outlasts the action
vf = fit + f",tpad=stop_mode=clone:stop_duration={max(0.0, target - vis):.3f}"
else:
@@ -174,11 +175,15 @@ def main():
ain = (["-i", str(nar)] if nar.exists()
else ["-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo"])
- run(["ffmpeg", "-nostdin", "-y", "-v", "error", *vin, *ain,
- "-vf", vf, "-af", "apad", "-r", str(FPS), "-t", f"{target:.3f}",
- "-map", "0:v:0", "-map", "1:a:0",
- "-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p",
- "-c:a", "aac", "-ar", "44100", "-ac", "2", str(seg)])
+ try:
+ run(["ffmpeg", "-nostdin", "-y", "-v", "error", *vin, *ain,
+ "-vf", vf, "-af", "apad", "-r", str(FPS), "-t", f"{target:.3f}",
+ "-map", "0:v:0", "-map", "1:a:0",
+ "-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p",
+ "-c:a", "aac", "-ar", "44100", "-ac", "2", str(seg)])
+ finally:
+ if frame_staging is not None:
+ frame_staging.cleanup()
actual = dur(seg)
# only scenes that speak get a subtitle offset; a movie played as
@@ -186,14 +191,16 @@ def main():
if nar.exists() and kind != "movie":
offsets[sid] = round(clock, 3)
clock += actual
- concat_lines.append(f"file '{seg.resolve()}'")
+ concat_lines.append(ffconcat_entry(seg))
print(f"{sid}: {actual:.1f}s{' (own audio)' if kind == 'movie' else ''}")
listing = work / "concat.txt"
- listing.write_text("\n".join(concat_lines) + "\n")
+ listing.write_text("".join(concat_lines), encoding="utf-8")
run(["ffmpeg", "-nostdin", "-y", "-v", "error", "-f", "concat", "-safe", "0",
"-i", str(listing), "-c", "copy", str(args.out)])
- (work / "offsets.json").write_text(json.dumps(offsets, indent=2))
+ (work / "offsets.json").write_text(
+ json.dumps(offsets, indent=2), encoding="utf-8"
+ )
print(f"\nassembled {args.out} ({dur(args.out):.1f}s)")
print(f"scene offsets -> {work / 'offsets.json'} "
f"(feed to make-subtitles --offsets-json)")
diff --git a/skills/proving-it-works-with-a-movie/scripts/browser_tools.py b/skills/proving-it-works-with-a-movie/scripts/browser_tools.py
new file mode 100644
index 0000000..7559939
--- /dev/null
+++ b/skills/proving-it-works-with-a-movie/scripts/browser_tools.py
@@ -0,0 +1,127 @@
+"""Headless browser discovery, bounded card screenshots, and process-tree cleanup."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+
+UNIX_BROWSERS = [
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
+ "chromium", "chromium-browser", "google-chrome", "google-chrome-stable",
+]
+
+
+def _windows_browsers() -> list[Path]:
+ locations = []
+ for variable in ("LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMW6432"):
+ value = os.environ.get(variable)
+ if value:
+ root = Path(value)
+ locations.extend([
+ root / "Google/Chrome/Application/chrome.exe",
+ root / "Microsoft/Edge/Application/msedge.exe",
+ ])
+ return locations
+
+
+def _resolve(candidate: str | Path) -> str | None:
+ path = Path(candidate).expanduser()
+ if path.is_file() and (sys.platform == "win32" or os.access(path, os.X_OK)):
+ return str(path.resolve())
+ return shutil.which(str(candidate))
+
+
+def find_browser(explicit: str | None) -> str | None:
+ """Return a usable Chrome-family executable, honoring explicit values."""
+ if explicit:
+ found = _resolve(explicit)
+ if found:
+ return found
+ raise FileNotFoundError(f"explicit browser is not usable: {explicit}")
+ candidates: list[str | Path] = (
+ _windows_browsers() + ["chrome.exe", "msedge.exe"]
+ if sys.platform == "win32" else UNIX_BROWSERS
+ )
+ for candidate in candidates:
+ found = _resolve(candidate)
+ if found:
+ return found
+ return None
+
+
+def _descendants(pid: int) -> list[int]:
+ pids, index = [pid], 0
+ while index < len(pids):
+ listed = subprocess.run(["pgrep", "-P", str(pids[index])], capture_output=True, text=True).stdout
+ pids.extend(int(child) for child in listed.split())
+ index += 1
+ return pids
+
+
+def kill_process_tree(pid: int) -> None:
+ """Kill a process this tool started and everything it spawned. A browser
+ or ttyd leaves helpers behind otherwise, and on Unix a pty child starts
+ its own session, so a process group is not enough."""
+ if sys.platform == "win32":
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(pid)], capture_output=True)
+ return
+ for victim in reversed(_descendants(pid)):
+ try:
+ os.kill(victim, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+
+
+def render_card(html: Path, png: Path, *, browser: str, width: int,
+ height: int, timeout: float = 20) -> None:
+ """Render one local HTML page and release every process it launched."""
+ html = Path(html).resolve()
+ png = Path(png).resolve()
+ if not html.is_file():
+ raise FileNotFoundError(f"card HTML does not exist: {html}")
+ png.parent.mkdir(parents=True, exist_ok=True)
+ png.unlink(missing_ok=True)
+ with tempfile.TemporaryDirectory(prefix="movie-browser-", ignore_cleanup_errors=True) as profile:
+ profile_path = Path(profile)
+ log = profile_path / "browser.log"
+ argv = [
+ str(Path(browser).resolve()) if Path(browser).is_file() else browser,
+ "--headless=new", "--disable-gpu", "--hide-scrollbars",
+ "--no-first-run", "--no-default-browser-check",
+ f"--user-data-dir={profile_path}", f"--screenshot={png}",
+ f"--window-size={width},{height}", "--force-device-scale-factor=1",
+ html.as_uri(),
+ ]
+ with log.open("wb") as output:
+ process = subprocess.Popen(argv, cwd=profile_path, stdin=subprocess.DEVNULL,
+ stdout=output, stderr=subprocess.STDOUT,
+ start_new_session=sys.platform != "win32")
+ try:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ # A fresh profile may keep background services alive after
+ # taking the screenshot. A complete PNG is the render result.
+ if png.is_file():
+ data = png.read_bytes()
+ if data.startswith(b"\x89PNG\r\n\x1a\n") and data.endswith(b"IEND\xaeB`\x82"):
+ return
+ elif process.poll() is not None:
+ detail = log.read_text(encoding="utf-8", errors="replace")[-1000:]
+ raise RuntimeError(f"Browser exited with status {process.returncode} "
+ f"without a complete PNG: {detail}")
+ time.sleep(0.05)
+ raise TimeoutError(f"Browser exceeded {timeout:g}s")
+ finally:
+ kill_process_tree(process.pid)
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
diff --git a/skills/proving-it-works-with-a-movie/scripts/burn-subtitles b/skills/proving-it-works-with-a-movie/scripts/burn-subtitles
index edfcb0e..d88b5e4 100755
--- a/skills/proving-it-works-with-a-movie/scripts/burn-subtitles
+++ b/skills/proving-it-works-with-a-movie/scripts/burn-subtitles
@@ -20,18 +20,19 @@ import argparse
import shutil
import subprocess
import sys
+import tempfile
from pathlib import Path
def has_libass():
out = subprocess.run(["ffmpeg", "-hide_banner", "-filters"],
- capture_output=True, text=True)
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
return any(line.split()[1:2] == ["subtitles"]
for line in out.stdout.splitlines() if line.strip())
-def run(cmd):
- r = subprocess.run(cmd, capture_output=True, text=True)
+def run(cmd, *, cwd=None):
+ r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace")
if r.returncode != 0:
print(" ".join(map(str, cmd)), file=sys.stderr)
print(r.stderr.strip()[:600], file=sys.stderr)
@@ -39,6 +40,9 @@ def run(cmd):
def main():
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(errors="backslashreplace")
ap = argparse.ArgumentParser()
ap.add_argument("movie", type=Path)
ap.add_argument("subs", type=Path)
@@ -56,7 +60,10 @@ def main():
if not f.exists():
sys.exit(f"no such file: {f}")
- if not args.soft and has_libass():
+ args.movie, args.subs, args.out = (path.resolve() for path in
+ (args.movie, args.subs, args.out))
+ libass = has_libass() if not args.soft else False
+ if not args.soft and libass:
# ffmpeg 8 dropped positional filter options, so name it explicitly:
# `subtitles=movie.srt` parses on 5.x and fails on 8.x, but
# `subtitles=filename=movie.srt` works on both
@@ -67,14 +74,16 @@ def main():
f"BorderStyle=3,Outline=1,Shadow=0,MarginV={args.margin},"
f"PrimaryColour=&H00FFFFFF&,OutlineColour=&HB0101014&,"
f"BackColour=&HB0101014&")
- # run from the subtitle's directory: the filter treats ':' and '\' in
- # paths as its own syntax, and quoting around that is a losing game
- ok = run(["ffmpeg", "-nostdin", "-y", "-v", "error",
- "-i", str(args.movie.resolve()),
- "-vf", f"subtitles=filename={args.subs.name}:"
- f"force_style='{style}'",
- "-c:a", "copy", "-c:v", "libx264", "-preset", "medium",
- "-pix_fmt", "yuv420p", str(args.out.resolve())])
+ # Only the safe basename enters filter syntax; media paths stay absolute.
+ with tempfile.TemporaryDirectory(prefix="movie-subtitles-") as temporary:
+ directory = Path(temporary)
+ shutil.copyfile(args.subs, directory / "captions.srt")
+ ok = run(["ffmpeg", "-nostdin", "-y", "-v", "error",
+ "-i", str(args.movie),
+ "-vf", "subtitles=filename=captions.srt:"
+ f"force_style='{style}'",
+ "-c:a", "copy", "-c:v", "libx264", "-preset", "medium",
+ "-pix_fmt", "yuv420p", str(args.out)], cwd=directory)
if ok:
print(f"burned into the picture -> {args.out}")
return 0
@@ -87,7 +96,7 @@ def main():
if not ok:
return 1
print(f"embedded a soft subtitle track -> {args.out}")
- if not args.soft:
+ if not args.soft and not libass:
print("NOTE: this ffmpeg has no libass, so the subtitles are a track a "
"player must choose to show, not pixels. Anything that autoplays "
"without subtitle UI (Slack, PR previews) will show none. Install "
diff --git a/skills/proving-it-works-with-a-movie/scripts/check-movie b/skills/proving-it-works-with-a-movie/scripts/check-movie
index ad4cf05..1d82cda 100755
--- a/skills/proving-it-works-with-a-movie/scripts/check-movie
+++ b/skills/proving-it-works-with-a-movie/scripts/check-movie
@@ -64,7 +64,7 @@ def sample_picture(movie, workdir):
out = subprocess.run(
["ffmpeg", "-nostdin", "-v", "error", "-i", str(movie),
"-vf", f"fps=1,scale={THUMB_W}:-1", "-f", "image2", str(frames / "s%05d.png")],
- capture_output=True, text=True)
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
if out.returncode != 0:
die(f"frame sampling failed: {out.stderr.strip()[:200]}")
paths = sorted(frames.glob("s*.png"))
@@ -122,6 +122,9 @@ def contact_sheet(paths, out_path, count=12):
def main():
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(errors="backslashreplace")
ap = argparse.ArgumentParser()
ap.add_argument("movie", type=Path)
ap.add_argument("--out", type=Path, default=None)
@@ -146,7 +149,7 @@ def main():
meta = subprocess.run(
["ffprobe", "-v", "error", "-print_format", "json",
"-show_format", "-show_streams", str(args.movie)],
- capture_output=True, text=True)
+ capture_output=True, text=True, encoding="utf-8", errors="replace")
if meta.returncode != 0:
die(f"ffprobe failed: {meta.stderr.strip()[:200]}")
info = json.loads(meta.stdout)
@@ -186,7 +189,7 @@ def main():
embedded = any(s["codec_type"] == "subtitle" for s in info["streams"])
if srt.exists():
last = 0.0
- for line in srt.read_text(errors="replace").splitlines():
+ for line in srt.read_text(encoding="utf-8-sig", errors="replace").splitlines():
if "-->" in line:
end = line.split("-->")[1].strip().split()[0]
hh, mm, rest = end.split(":")
@@ -246,7 +249,7 @@ def main():
(workdir / "check.json").write_text(json.dumps(
{"duration": duration, "change_seconds": changes,
"talk_seconds": talking, "failures": failures,
- "warnings": warnings}, indent=2))
+ "warnings": warnings}, indent=2), encoding="utf-8")
if failures:
print("\nNOT SHIPPABLE. Fix, regenerate, re-run.")
diff --git a/skills/proving-it-works-with-a-movie/scripts/make-subtitles b/skills/proving-it-works-with-a-movie/scripts/make-subtitles
index 7c73473..02a5b45 100755
--- a/skills/proving-it-works-with-a-movie/scripts/make-subtitles
+++ b/skills/proving-it-works-with-a-movie/scripts/make-subtitles
@@ -71,6 +71,9 @@ def ts(seconds):
def main():
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(errors="backslashreplace")
ap = argparse.ArgumentParser()
ap.add_argument("manifest", type=Path)
ap.add_argument("out", type=Path)
@@ -84,11 +87,11 @@ def main():
ap.add_argument("--max-secs", type=float, default=MAX_SECS)
args = ap.parse_args()
- manifest = json.loads(args.manifest.read_text())
+ manifest = json.loads(args.manifest.read_text(encoding="utf-8-sig"))
overrides = {}
if args.offsets_json:
overrides.update({k: float(v) for k, v in
- json.loads(args.offsets_json.read_text()).items()})
+ json.loads(args.offsets_json.read_text(encoding="utf-8-sig")).items()})
for spec in args.offsets:
k, _, v = spec.partition("=")
overrides[k] = float(v)
@@ -116,7 +119,7 @@ def main():
if b <= a:
b = a + MIN_SECS
lines += [str(i), f"{ts(a)} --> {ts(b)}", text, ""]
- args.out.write_text("\n".join(lines))
+ args.out.write_text("\n".join(lines), encoding="utf-8")
print(f"{len(cues)} cues, ends at {ts(cues[-1][1])} -> {args.out}")
return 0
diff --git a/skills/proving-it-works-with-a-movie/scripts/media_paths.py b/skills/proving-it-works-with-a-movie/scripts/media_paths.py
new file mode 100644
index 0000000..5c13592
--- /dev/null
+++ b/skills/proving-it-works-with-a-movie/scripts/media_paths.py
@@ -0,0 +1,24 @@
+"""Portable media path preparation for the movie assembly tools."""
+
+import shutil
+from pathlib import Path
+
+
+def stage_frames(source: Path, destination: Path) -> list[Path]:
+ files = sorted(source.glob("*.png"))
+ if not files:
+ raise ValueError(f"no PNG frames in {source}")
+ destination.mkdir(parents=True, exist_ok=False)
+ result = []
+ for index, frame in enumerate(files):
+ target = destination / f"frame-{index:08d}.png"
+ shutil.copyfile(frame, target)
+ result.append(target)
+ return result
+
+
+def ffconcat_entry(path: Path) -> str:
+ value = path.resolve().as_posix()
+ if "\n" in value or "\r" in value:
+ raise ValueError("FFconcat paths cannot contain line breaks")
+ return "file '" + value.replace("'", "'\\''") + "'\n"
diff --git a/skills/proving-it-works-with-a-movie/scripts/narrate b/skills/proving-it-works-with-a-movie/scripts/narrate
index 5f99e21..a6b3a5e 100755
--- a/skills/proving-it-works-with-a-movie/scripts/narrate
+++ b/skills/proving-it-works-with-a-movie/scripts/narrate
@@ -28,6 +28,7 @@ import os
import re
import subprocess
import sys
+import tempfile
import urllib.request
import wave
from pathlib import Path
@@ -67,7 +68,9 @@ import sys
from faster_whisper import WhisperModel
m = WhisperModel(sys.argv[2], device="cpu", compute_type="int8")
segs, _ = m.transcribe(sys.argv[1])
-print(" ".join(s.text.strip() for s in segs))
+from pathlib import Path
+import json
+Path(sys.argv[3]).write_text(json.dumps({"text": " ".join(s.text.strip() for s in segs)}), encoding="utf-8")
"""
@@ -75,13 +78,26 @@ def transcribe_local(wav, model="base.en"):
"""Transcribe with a local ASR, in its own uv env so narrate stays light.
Returns None when faster-whisper isn't available."""
try:
- out = subprocess.run(
- ["uv", "run", "--quiet", "--with", "faster-whisper", "python3",
- "-c", ASR_SNIPPET, str(wav), model],
- capture_output=True, text=True, timeout=900)
- except Exception: # noqa: BLE001 - no uv, no network: gate simply unavailable
+ with tempfile.TemporaryDirectory(prefix="movie-asr-") as temporary:
+ result_path = Path(temporary) / "transcript.json"
+ out = subprocess.run(
+ ["uv", "run", "--no-config", "--no-project", "--isolated",
+ "--python", sys.executable, "--with", "faster-whisper", "python",
+ "-c", ASR_SNIPPET, str(wav.resolve()), model, str(result_path)],
+ cwd=temporary, capture_output=True, text=True,
+ encoding="utf-8", errors="replace", timeout=900)
+ for diagnostic in (out.stdout, out.stderr):
+ if diagnostic.strip():
+ print(f"local ASR: {diagnostic.strip()[-600:]}", file=sys.stderr)
+ if out.returncode != 0:
+ print(f"local ASR exited with status {out.returncode}", file=sys.stderr)
+ return None
+ data = json.loads(result_path.read_text(encoding="utf-8"))
+ text = data.get("text") if isinstance(data, dict) else None
+ return text.strip() if isinstance(text, str) and text.strip() else None
+ except (OSError, ValueError, subprocess.SubprocessError) as error:
+ print(f"local ASR unavailable: {error}", file=sys.stderr)
return None
- return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else None
def structural_drift(text, heard):
@@ -153,14 +169,17 @@ def say_piper(text, out_wav, voice):
def duration(path):
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
- "-of", "csv=p=0", str(path)], capture_output=True, text=True)
+ "-of", "csv=p=0", str(path)], capture_output=True, text=True, encoding="utf-8", errors="replace")
return round(float(out.stdout.strip()), 3)
def main():
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(errors="backslashreplace")
if len(sys.argv) == 4 and sys.argv[1] == "--drift-check":
- script = Path(sys.argv[2]).read_text()
- heard = Path(sys.argv[3]).read_text()
+ script = Path(sys.argv[2]).read_text(encoding="utf-8-sig")
+ heard = Path(sys.argv[3]).read_text(encoding="utf-8-sig")
delta, worst = structural_drift(script, heard)
bad = delta > 0.15 or worst >= 4
print(f"length change {delta:.0%}, worst run {worst} -> "
@@ -181,7 +200,7 @@ def main():
ap.add_argument("--asr-model", default="base.en")
args = ap.parse_args()
- doc = yaml.safe_load(args.scenes.read_text())
+ doc = yaml.safe_load(args.scenes.read_text(encoding="utf-8-sig"))
scenes = [s for s in doc.get("scenes", []) if (s.get("narration") or "").strip()]
if not scenes:
die("no scenes with narration")
@@ -207,7 +226,7 @@ def main():
if prior_path.exists():
try:
prior = {e["id"]: e.get("text", "") for e in
- json.loads(prior_path.read_text())}
+ json.loads(prior_path.read_text(encoding="utf-8-sig"))}
except Exception: # noqa: BLE001 - a corrupt manifest just means no cache
prior = {}
manifest, failures = [], []
@@ -216,13 +235,14 @@ def main():
sid = sc["id"]
text = " ".join((sc["narration"] or "").split())
wav = args.outdir / f"{sid}.wav"
- if wav.exists() and not args.force and prior.get(sid) == text:
+ cached = wav.exists() and not args.force and prior.get(sid) == text
+ if cached:
print(f"{sid}: cached")
elif wav.exists() and not args.force and sid in prior:
print(f"{sid}: text changed since this clip was rendered - redoing")
- args.force = True
- else:
- for attempt in (1, 2):
+ for attempt in ((1,) if cached else (1, 2)):
+ claimed = None
+ if not cached:
if engine == "openai":
claimed = say_openai(key, text, wav, args.voice)
elif engine == "openai-chat":
@@ -230,42 +250,43 @@ def main():
else:
claimed = say_piper(text, wav, args.voice)
- # a chat model reports what it said: hold it to that exactly,
- # because "Sure, here it is:" is the failure it introduces
- if claimed is not None:
- want, got = norm(text), norm(claimed)
- drift = abs(len(want) - len(got)) + sum(
- 1 for a, b in zip(want, got) if a != b)
- if drift > max(2, len(want) // 25):
- print(f"{sid}: engine ad-libbed (attempt {attempt}, "
- f"drift {drift})")
- continue
-
- # every engine: listen back. An ASR mangles unusual names, so
- # only missing or invented CONTENT counts as a failure here.
- if verify:
- heard = transcribe_local(wav, args.asr_model)
- if heard is None:
- print(f"{sid}: ok (no local ASR available - gate skipped)")
- break
- delta, worst = structural_drift(text, heard)
- if delta > 0.15 or worst >= 4:
- print(f"{sid}: what came out does not match the script "
- f"(attempt {attempt}: {delta:.0%} length change, "
- f"{worst} words in a row wrong)")
- print(f" heard: {heard[:120]}")
- continue
- print(f"{sid}: ok (verified by ear: {delta:.0%} length "
- f"change, worst run {worst})")
+ # Preserve the engine transcript gate and the ASR drift thresholds.
+ if claimed is not None:
+ want, got = norm(text), norm(claimed)
+ drift = abs(len(want) - len(got)) + sum(
+ 1 for a, b in zip(want, got) if a != b)
+ if drift > max(2, len(want) // 25):
+ print(f"{sid}: engine ad-libbed (attempt {attempt}, drift {drift})")
+ continue
+ if verify:
+ heard = transcribe_local(wav, args.asr_model)
+ if heard is None:
+ if args.verify == "on":
+ print(f"{sid}: required verification unavailable", file=sys.stderr)
+ failures.append(sid)
+ else:
+ print(f"{sid}: verification unavailable (no local ASR)")
break
- print(f"{sid}: ok")
+ delta, worst = structural_drift(text, heard)
+ if delta > 0.15 or worst >= 4:
+ print(f"{sid}: what came out does not match the script "
+ f"(attempt {attempt}: {delta:.0%} length change, "
+ f"{worst} words in a row wrong)")
+ print(f" heard: {heard[:120]}")
+ continue
+ print(f"{sid}: ok (verified by ear: {delta:.0%} length "
+ f"change, worst run {worst})")
break
- else:
- failures.append(sid)
+ print(f"{sid}: ok")
+ break
+ else:
+ failures.append(sid)
+ if sid in failures:
+ continue
manifest.append({"id": sid, "text": text, "wav": wav.name,
"duration": duration(wav)})
- (args.outdir / "manifest.json").write_text(json.dumps(manifest, indent=2))
+ (args.outdir / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
total = sum(m["duration"] for m in manifest)
print(f"\n{len(manifest)} clips, {total:.1f}s total -> {args.outdir}/manifest.json")
if engine == "piper":
diff --git a/tests/proving-it-works-with-a-movie/README.md b/tests/proving-it-works-with-a-movie/README.md
new file mode 100644
index 0000000..3c3f4fc
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/README.md
@@ -0,0 +1,24 @@
+# Portable movie regressions
+
+Run a suite from the repository root:
+
+```sh
+uv run --script tests/proving-it-works-with-a-movie/run-tests.py --suite assembly
+uv run --script tests/proving-it-works-with-a-movie/run-tests.py --suite checker
+uv run --script tests/proving-it-works-with-a-movie/run-tests.py --suite narration
+uv run --script tests/proving-it-works-with-a-movie/run-tests.py --suite all
+```
+
+By default, unavailable external capabilities are reported as skips. Add
+`--require-capabilities` when the selected environment is required to provide
+them; any skip then makes the run fail.
+
+The assembly sine wave is only a synthetic timing fixture. The narration drift
+inputs exercise text comparison only. Neither is speech/ASR acceptance.
+
+The `terminal` suite starts a real ttyd session and skips where ttyd or a
+Chrome-family browser is missing. It films `bash` by default on Unix and
+`powershell51` on Windows; set `MOVIE_TEST_SHELL` to `powershell51`,
+`powershell7`, `gitbash`, or `bash`, and `MOVIE_TEST_SHELL_EXE`,
+`MOVIE_TEST_TTYD`, or `MOVIE_TEST_BROWSER` when those executables are not on
+PATH.
diff --git a/tests/proving-it-works-with-a-movie/fixtures.py b/tests/proving-it-works-with-a-movie/fixtures.py
new file mode 100644
index 0000000..30fa073
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/fixtures.py
@@ -0,0 +1,298 @@
+"""Portable fixtures for the imported movie regression suites."""
+
+import json
+import importlib.util
+import importlib.machinery
+import shutil
+import subprocess
+import types
+import sys
+from pathlib import Path
+
+
+TIMEOUT_SECONDS = 900
+
+
+def missing_executables(*names: str) -> list[str]:
+ """Return executable names that cannot be resolved on PATH."""
+ return [name for name in names if shutil.which(name) is None]
+
+
+def output_text(result: subprocess.CompletedProcess[bytes]) -> str:
+ """Decode a captured command's combined output as UTF-8 evidence."""
+ return (result.stdout + result.stderr).decode("utf-8", errors="replace")
+
+
+def run_tool(
+ name: str,
+ args: list[str],
+ *,
+ cwd: Path,
+ env: dict[str, str] | None = None,
+) -> subprocess.CompletedProcess[bytes]:
+ """Invoke one extensionless movie tool through its PEP 723 environment."""
+ uv = shutil.which("uv")
+ if uv is None:
+ raise RuntimeError("uv is required for movie tool tests")
+ script = (
+ Path(__file__).resolve().parents[2]
+ / "skills/proving-it-works-with-a-movie/scripts"
+ / name
+ )
+ return subprocess.run(
+ [uv, "run", "--script", str(script), *args],
+ cwd=cwd,
+ env=env,
+ capture_output=True,
+ timeout=TIMEOUT_SECONDS,
+ )
+
+
+def load_script(name: str) -> types.ModuleType:
+ """Load an extensionless movie tool as a test module."""
+ script = (
+ Path(__file__).resolve().parents[2]
+ / "skills/proving-it-works-with-a-movie/scripts"
+ / name
+ )
+ if not script.exists():
+ script = script.with_suffix(".py")
+ sys.path.insert(0, str(script.parent))
+ loader = importlib.machinery.SourceFileLoader(f"movie_tool_{name}", str(script))
+ spec = importlib.util.spec_from_loader(loader.name, loader)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"cannot load movie tool {name!r}")
+ module = importlib.util.module_from_spec(spec)
+ try:
+ spec.loader.exec_module(module)
+ finally:
+ sys.path.pop(0)
+ return module
+
+
+def duration(path: Path) -> float:
+ """Measure a media file's container duration with ffprobe."""
+ ffprobe = shutil.which("ffprobe")
+ if ffprobe is None:
+ raise RuntimeError("ffprobe is required for movie tool tests")
+ result = subprocess.run(
+ [
+ ffprobe,
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration",
+ "-of",
+ "csv=p=0",
+ str(path),
+ ],
+ capture_output=True,
+ timeout=TIMEOUT_SECONDS,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"ffprobe failed for {path}: {output_text(result)}")
+ return float(result.stdout.decode("utf-8").strip())
+
+
+def _run_ffmpeg(args: list[str], *, cwd: Path) -> None:
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg is None:
+ raise RuntimeError("ffmpeg is required for movie tool tests")
+ result = subprocess.run(
+ [ffmpeg, "-nostdin", "-y", "-v", "error", *args],
+ cwd=cwd,
+ capture_output=True,
+ timeout=TIMEOUT_SECONDS,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"ffmpeg fixture generation failed: {output_text(result)}")
+
+
+def assembly_fixture(work: Path) -> Path:
+ """Write the imported image/frames/synthetic-timing-audio assembly case."""
+ shots = work / "shots"
+ shots.mkdir(parents=True)
+ for index in range(1, 5):
+ _run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ f"color=c=0x{index}0{index}0{index}0:size=320x180:d=0.1",
+ "-frames:v",
+ "1",
+ str(shots / f"s0{index}.png"),
+ ],
+ cwd=work,
+ )
+
+ narration = work / "narration"
+ narration.mkdir()
+ wav = narration / "body.wav"
+ _run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=300:duration=6",
+ str(wav),
+ ],
+ cwd=work,
+ )
+ manifest = [
+ {
+ "id": "body",
+ "text": "one two three four five six seven eight nine ten",
+ "wav": "body.wav",
+ "duration": duration(wav),
+ }
+ ]
+ (narration / "manifest.json").write_text(
+ json.dumps(manifest), encoding="utf-8"
+ )
+
+ scenes = work / "scenes.yaml"
+ scenes.write_text(
+ """resolution: { width: 640, height: 360 }
+fps: 30
+scenes:
+ - id: opener
+ kind: image
+ src: shots/s01.png
+ duration: 2
+ - id: body
+ kind: frames
+ src: shots
+ rate: 1.0
+""",
+ encoding="utf-8",
+ )
+ return scenes
+
+
+def checker_fixture(work: Path) -> dict[str, Path]:
+ """Create the four imported checker movies and their subtitle sidecars."""
+ front_loaded = work / "front-loaded.mp4"
+ _run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=320x240:rate=10:d=2",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=navy:size=320x240:rate=10:d=20",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=300:duration=22",
+ "-filter_complex",
+ "[0:v][1:v]concat=n=2:v=1:a=0[v]",
+ "-map",
+ "[v]",
+ "-map",
+ "2:a",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-shortest",
+ str(front_loaded),
+ ],
+ cwd=work,
+ )
+
+ paced = work / "paced.mp4"
+ _run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=320x240:rate=10:d=22",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=300:duration=22",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-shortest",
+ str(paced),
+ ],
+ cwd=work,
+ )
+
+ still = work / "still.mp4"
+ _run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=navy:size=320x240:rate=10:d=12",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=300:duration=12",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-shortest",
+ str(still),
+ ],
+ cwd=work,
+ )
+
+ silent = work / "silent.mp4"
+ _run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ "testsrc2=size=320x240:rate=10:d=12",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ str(silent),
+ ],
+ cwd=work,
+ )
+
+ subtitles = """1
+00:00:00,000 --> 00:00:07,000
+A narrated movie needs subtitles:
+plenty of people watch muted.
+
+2
+00:00:07,000 --> 00:00:14,000
+The checker treats their absence
+as a defect, not a nicety.
+
+3
+00:00:14,000 --> 00:00:21,500
+And it notices when they stop
+before the narration does.
+"""
+ (work / "paced.srt").write_text(subtitles, encoding="utf-8")
+ (work / "short.srt").write_text(
+ "\n".join(subtitles.splitlines()[:8]) + "\n", encoding="utf-8"
+ )
+ short = work / "short.mp4"
+ shutil.copyfile(paced, short)
+
+ return {
+ "front-loaded": front_loaded,
+ "paced": paced,
+ "still": still,
+ "silent": silent,
+ "short": short,
+ }
diff --git a/tests/proving-it-works-with-a-movie/fixtures/terminal_app.py b/tests/proving-it-works-with-a-movie/fixtures/terminal_app.py
new file mode 100644
index 0000000..0b197d9
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/fixtures/terminal_app.py
@@ -0,0 +1,41 @@
+"""TUI fixture: three timed colour states, then wait for `q`.
+`tree DIR` instead leaves a three-deep process tree running for cleanup tests."""
+import json, os, subprocess, sys, time
+from pathlib import Path
+
+
+def getch():
+ if os.name == "nt":
+ import msvcrt
+ return msvcrt.getwch()
+ import termios, tty
+ fd = sys.stdin.fileno()
+ old = termios.tcgetattr(fd)
+ try:
+ tty.setcbreak(fd)
+ return sys.stdin.read(1)
+ finally:
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
+
+
+if len(sys.argv) > 1 and sys.argv[1] == "tree":
+ directory = Path(sys.argv[2])
+ directory.mkdir(exist_ok=True)
+ level = int(sys.argv[3]) if len(sys.argv) > 3 else 0
+ if level < 2:
+ subprocess.Popen([sys.executable, __file__, "tree", str(directory), str(level + 1)])
+ (directory / f"{level}.json").write_text(json.dumps(dict(pid=os.getpid(), level=level)))
+ while True:
+ time.sleep(1)
+
+print("WRAPPING OUTPUT " + ("0123456789 wrap proof " * 60), flush=True)
+time.sleep(1.4)
+states = []
+for label, color in [("STATE ONE RED", 41), ("STATE TWO GREEN", 42), ("STATE THREE BLUE", 44)]:
+ print("\x1b[2J\x1b[H" + f"\x1b[{color}m" + (label + " " * 60 + "\n") * 12 + "\x1b[0m", end="", flush=True)
+ states.append(dict(label=label, time=time.monotonic()))
+ Path("states.json").write_text(json.dumps(states))
+ time.sleep(1.5)
+while getch() != "q":
+ pass
+print("\nAUTOMATIC GATE COMPLETE", flush=True)
diff --git a/tests/proving-it-works-with-a-movie/run-tests.py b/tests/proving-it-works-with-a-movie/run-tests.py
new file mode 100644
index 0000000..02f0d17
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/run-tests.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.10"
+# dependencies = ["pyyaml", "pillow", "websocket-client==1.9.0"]
+# ///
+"""Run the proving-it-works-with-a-movie regression suites portably."""
+
+import argparse
+import sys
+import unittest
+from pathlib import Path
+
+
+IMPLEMENTED_SUITES = {
+ "assembly": "test_assembly.py",
+ "browser": "test_browser.py",
+ "checker": "test_checker.py",
+ "narration": "test_narration.py",
+ "paths": "test_paths.py",
+ "subtitles": "test_subtitles.py",
+ "terminal": "test_terminal.py",
+}
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--suite",
+ required=True,
+ choices=[*IMPLEMENTED_SUITES, "all"],
+ )
+ parser.add_argument("--require-capabilities", action="store_true")
+ return parser.parse_args()
+
+
+def main() -> int:
+ args = parse_args()
+ patterns = (
+ list(IMPLEMENTED_SUITES.values())
+ if args.suite == "all"
+ else [IMPLEMENTED_SUITES[args.suite]]
+ )
+ test_directory = Path(__file__).resolve().parent
+ loader = unittest.TestLoader()
+ suite = unittest.TestSuite(
+ loader.discover(
+ str(test_directory),
+ pattern=pattern,
+ top_level_dir=str(test_directory),
+ )
+ for pattern in patterns
+ )
+ result = unittest.TextTestRunner(verbosity=2).run(suite)
+ if args.require_capabilities and result.skipped:
+ print(
+ f"required capabilities unavailable: {len(result.skipped)} "
+ "selected test(s) skipped",
+ file=sys.stderr,
+ )
+ return 1
+ return 0 if result.wasSuccessful() else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/proving-it-works-with-a-movie/test-assemble.sh b/tests/proving-it-works-with-a-movie/test-assemble.sh
deleted file mode 100755
index c5eca66..0000000
--- a/tests/proving-it-works-with-a-movie/test-assemble.sh
+++ /dev/null
@@ -1,88 +0,0 @@
-#!/usr/bin/env bash
-# Regression tests for scripts/assemble and scripts/make-subtitles.
-#
-# The property that matters: a segment lasts max(narration, visuals), and
-# the scene offsets written for the subtitler match where scenes actually
-# start in the finished cut. Hand-computed offsets silently mistime every
-# cue after an inserted scene, which is why assemble emits them.
-#
-# Usage: tests/proving-it-works-with-a-movie/test-assemble.sh
-set -uo pipefail
-
-HERE="$(cd "$(dirname "$0")" && pwd)"
-SCRIPTS="$HERE/../../skills/proving-it-works-with-a-movie/scripts"
-WORK="$(mktemp -d)"
-trap 'rm -rf "$WORK"' EXIT
-pass=0; fail=0
-
-for tool in ffmpeg ffprobe uv; do
- command -v "$tool" >/dev/null || { echo "SKIP: $tool not on PATH"; exit 0; }
-done
-
-ok() { echo "ok $1"; pass=$((pass + 1)); }
-no() { echo "FAIL $1"; fail=$((fail + 1)); }
-dur() { ffprobe -v error -show_entries format=duration -of csv=p=0 "$1"; }
-about() { # about <actual> <expected> <tolerance>
- awk -v a="$1" -v b="$2" -v t="$3" 'BEGIN{exit !(a-b<t && b-a<t)}'
-}
-
-mkdir -p "$WORK/shots"
-for i in 1 2 3 4; do
- ffmpeg -nostdin -y -v error -f lavfi \
- -i "color=c=0x${i}0${i}0${i}0:size=320x180:d=0.1" -frames:v 1 \
- "$WORK/shots/s0$i.png"
-done
-# a 6-second narration stand-in, so the 4s of pictures must be padded to it
-mkdir -p "$WORK/narration"
-ffmpeg -nostdin -y -v error -f lavfi -i "sine=frequency=300:duration=6" \
- "$WORK/narration/body.wav"
-python3 - "$WORK" <<'PY'
-import json, sys, subprocess
-w = sys.argv[1]
-d = float(subprocess.run(["ffprobe","-v","error","-show_entries","format=duration",
- "-of","csv=p=0",f"{w}/narration/body.wav"],capture_output=True,text=True).stdout)
-json.dump([{"id":"body","text":"one two three four five six seven eight nine ten",
- "wav":"body.wav","duration":d}], open(f"{w}/narration/manifest.json","w"))
-PY
-
-cat > "$WORK/scenes.yaml" <<'YAML'
-resolution: { width: 640, height: 360 }
-fps: 30
-scenes:
- - id: opener
- kind: image
- src: shots/s01.png
- duration: 2
- - id: body
- kind: frames
- src: shots
- rate: 1.0
-YAML
-
-out="$WORK/out.mp4"
-if "$SCRIPTS/assemble" "$WORK/scenes.yaml" "$out" >"$WORK/log" 2>&1; then
- ok "assemble runs"
-else
- no "assemble runs"; sed 's/^/ /' "$WORK/log"
-fi
-
-# opener 2s + body max(4s pictures, 6s narration) = 8s
-total="$(dur "$out")"
-if about "$total" 8 0.4; then ok "segment = max(narration, visuals)"
-else no "segment = max(narration, visuals): got ${total}s, wanted ~8"; fi
-
-offset="$(python3 -c "import json;print(json.load(open('$WORK/segments/offsets.json'))['body'])" 2>/dev/null)"
-if about "${offset:-0}" 2 0.3; then ok "offsets.json places the narrated scene"
-else no "offsets.json places the narrated scene: got ${offset:-none}, wanted ~2"; fi
-
-if "$SCRIPTS/make-subtitles" "$WORK/narration/manifest.json" "$WORK/out.srt" \
- --offsets-json "$WORK/segments/offsets.json" >/dev/null 2>&1 \
- && grep -q "00:00:0[2-9]" "$WORK/out.srt"; then
- ok "cues start at the scene's real offset, not zero"
-else
- no "cues start at the scene's real offset, not zero"
-fi
-
-echo
-echo "$pass passed, $fail failed"
-[ "$fail" -eq 0 ]
diff --git a/tests/proving-it-works-with-a-movie/test-check-movie.sh b/tests/proving-it-works-with-a-movie/test-check-movie.sh
deleted file mode 100755
index 05242da..0000000
--- a/tests/proving-it-works-with-a-movie/test-check-movie.sh
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/env bash
-# Regression tests for scripts/check-movie.
-#
-# Synthesizes movies with known defects using ffmpeg's lavfi sources - no
-# fixtures committed, nothing downloaded - and asserts the checker's verdict
-# on each. The front-loaded case reproduces the real failure this skill
-# exists to prevent: a movie whose action finishes in the first seconds
-# while narration keeps talking over a frozen picture.
-#
-# Usage: tests/proving-it-works-with-a-movie/test-check-movie.sh
-set -uo pipefail
-
-HERE="$(cd "$(dirname "$0")" && pwd)"
-CHECKER="$HERE/../../skills/proving-it-works-with-a-movie/scripts/check-movie"
-WORK="$(mktemp -d)"
-trap 'rm -rf "$WORK"' EXIT
-
-pass=0
-fail=0
-
-for tool in ffmpeg ffprobe uv; do
- command -v "$tool" >/dev/null || { echo "SKIP: $tool not on PATH"; exit 0; }
-done
-[ -x "$CHECKER" ] || { echo "FAIL: $CHECKER is not executable"; exit 1; }
-
-# --- fixtures -------------------------------------------------------------
-# action for 2s, then a frozen picture for 20s, narration (tone) throughout
-ffmpeg -nostdin -y -v error \
- -f lavfi -i "testsrc2=size=320x240:rate=10:d=2" \
- -f lavfi -i "color=c=navy:size=320x240:rate=10:d=20" \
- -f lavfi -i "sine=frequency=300:duration=22" \
- -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" \
- -map "[v]" -map 2:a -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest \
- "$WORK/front-loaded.mp4"
-
-# picture changing throughout, narration throughout
-ffmpeg -nostdin -y -v error \
- -f lavfi -i "testsrc2=size=320x240:rate=10:d=22" \
- -f lavfi -i "sine=frequency=300:duration=22" \
- -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest "$WORK/paced.mp4"
-
-# one static frame for the whole runtime, narration throughout
-ffmpeg -nostdin -y -v error \
- -f lavfi -i "color=c=navy:size=320x240:rate=10:d=12" \
- -f lavfi -i "sine=frequency=300:duration=12" \
- -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest "$WORK/still.mp4"
-
-# motion, but no audio track at all
-ffmpeg -nostdin -y -v error \
- -f lavfi -i "testsrc2=size=320x240:rate=10:d=12" \
- -c:v libx264 -pix_fmt yuv420p "$WORK/silent.mp4"
-
-# subtitles: one covering the whole runtime, one that gives up early
-cat > "$WORK/paced.srt" <<'SRT'
-1
-00:00:00,000 --> 00:00:07,000
-A narrated movie needs subtitles:
-plenty of people watch muted.
-
-2
-00:00:07,000 --> 00:00:14,000
-The checker treats their absence
-as a defect, not a nicety.
-
-3
-00:00:14,000 --> 00:00:21,500
-And it notices when they stop
-before the narration does.
-SRT
-head -8 "$WORK/paced.srt" > "$WORK/short.srt"
-cp "$WORK/paced.mp4" "$WORK/short.mp4"
-
-# --- assertions -----------------------------------------------------------
-check() { # check <label> <expected-exit> <must-contain> <movie> [extra args...]
- local label="$1" want="$2" needle="$3" movie="$4"; shift 4
- local out rc
- out="$("$CHECKER" "$movie" --out "$WORK/$(basename "$movie" .mp4)-check" "$@" 2>&1)"
- rc=$?
- if [ "$rc" -ne "$want" ]; then
- echo "FAIL $label: exit $rc, wanted $want"
- echo "$out" | sed 's/^/ /'
- fail=$((fail + 1)); return
- fi
- if ! printf '%s' "$out" | grep -qi -- "$needle"; then
- echo "FAIL $label: output missing '$needle'"
- echo "$out" | sed 's/^/ /'
- fail=$((fail + 1)); return
- fi
- echo "ok $label"
- pass=$((pass + 1))
-}
-
-check "front-loaded action is rejected" 1 "every visible change happens in the first" "$WORK/front-loaded.mp4"
-check "paced + subtitles is accepted" 0 "Mechanical checks pass" "$WORK/paced.mp4"
-check "narrated without subtitles rejected" 1 "no subtitles" "$WORK/paced.mp4" --subs "$WORK/nope.srt"
-check "subtitles that stop early rejected" 1 "subtitles stop at" "$WORK/short.mp4"
-check "subtitle check is opt-outable" 0 "Mechanical checks pass" "$WORK/paced.mp4" --subs "$WORK/nope.srt" --no-expect-subtitles
-check "a still with audio is rejected" 1 "never reaches a new state" "$WORK/still.mp4"
-check "missing narration is rejected" 1 "no audio stream" "$WORK/silent.mp4"
-check "silent movie passes when unnarrated" 0 "Mechanical checks pass" "$WORK/silent.mp4" --no-expect-audio
-check "a contact sheet is always written" 0 "contact-sheet.png" "$WORK/paced.mp4"
-
-echo
-echo "$pass passed, $fail failed"
-[ "$fail" -eq 0 ]
diff --git a/tests/proving-it-works-with-a-movie/test-narrate.sh b/tests/proving-it-works-with-a-movie/test-narrate.sh
deleted file mode 100755
index 36f4be7..0000000
--- a/tests/proving-it-works-with-a-movie/test-narrate.sh
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/usr/bin/env bash
-# Regression tests for the narration gate's drift rule.
-#
-# The rule has to survive a real asymmetry: an ASR mangles unusual names, so
-# exact word-matching produces false alarms — and, worse, a *dropped* word
-# scores as more similar than two mispronounced ones. So the gate measures
-# missing/invented CONTENT, and these tests pin that distinction.
-#
-# Usage: tests/proving-it-works-with-a-movie/test-narrate.sh
-set -uo pipefail
-
-HERE="$(cd "$(dirname "$0")" && pwd)"
-NARRATE="$HERE/../../skills/proving-it-works-with-a-movie/scripts/narrate"
-WORK="$(mktemp -d)"
-trap 'rm -rf "$WORK"' EXIT
-pass=0; fail=0
-
-command -v uv >/dev/null || { echo "SKIP: uv not on PATH"; exit 0; }
-
-drift() { # drift <label> <expect-exit> <script> <heard>
- local label="$1" want="$2"
- printf '%s' "$3" > "$WORK/script.txt"
- printf '%s' "$4" > "$WORK/heard.txt"
- local out rc
- out="$("$NARRATE" --drift-check "$WORK/script.txt" "$WORK/heard.txt" 2>&1)"; rc=$?
- if [ "$rc" -eq "$want" ]; then
- echo "ok $label ($out)"; pass=$((pass + 1))
- else
- echo "FAIL $label: exit $rc wanted $want ($out)"; fail=$((fail + 1))
- fi
-}
-
-SCRIPT="This is smevals studio. Every eval on the shelf is a folder of tasks and graders."
-
-# the ASR mangles jargon on a perfectly good clip - must NOT fail
-drift "mispronounced jargon passes" 0 "$SCRIPT" \
- "This is Mevil studio. Every Yvel on the shelf is a folder of tasks and graders."
-
-# identical - must pass
-drift "exact transcript passes" 0 "$SCRIPT" "$SCRIPT"
-
-# the voice skipped a whole clause - must fail
-drift "a dropped clause fails" 1 "$SCRIPT" "This is smevals studio."
-
-# a chat model prepended a preamble - must fail
-drift "an invented preamble fails" 1 "$SCRIPT" \
- "Sure, here it is, happy to help with that. This is smevals studio. Every eval on the shelf is a folder of tasks and graders."
-
-# a silent/garbage clip - must fail
-drift "an empty clip fails" 1 "$SCRIPT" "you"
-
-echo
-echo "$pass passed, $fail failed"
-[ "$fail" -eq 0 ]
diff --git a/tests/proving-it-works-with-a-movie/test_assembly.py b/tests/proving-it-works-with-a-movie/test_assembly.py
new file mode 100644
index 0000000..20c78d5
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_assembly.py
@@ -0,0 +1,399 @@
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+import fixtures
+from PIL import Image
+
+
+def run_ffmpeg(args: list[str], *, cwd: Path) -> subprocess.CompletedProcess[bytes]:
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg is None:
+ raise RuntimeError("ffmpeg is required for assembly fixtures")
+ result = subprocess.run(
+ [ffmpeg, "-nostdin", "-y", "-v", "error", *args],
+ cwd=cwd,
+ capture_output=True,
+ timeout=fixtures.TIMEOUT_SECONDS,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(
+ f"ffmpeg fixture generation failed: {fixtures.output_text(result)}"
+ )
+ return result
+
+
+def make_tone(path: Path, duration: float, frequency: int, *, cwd: Path) -> None:
+ run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ f"sine=frequency={frequency}:sample_rate=8000:duration={duration}",
+ "-c:a",
+ "pcm_s16le",
+ str(path),
+ ],
+ cwd=cwd,
+ )
+
+
+def make_movie(path: Path, duration: float, frequency: int, *, cwd: Path) -> None:
+ run_ffmpeg(
+ [
+ "-f",
+ "lavfi",
+ "-i",
+ f"color=c=green:size=160x90:rate=10:duration={duration}",
+ "-f",
+ "lavfi",
+ "-i",
+ f"sine=frequency={frequency}:sample_rate=8000:duration={duration}",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-shortest",
+ str(path),
+ ],
+ cwd=cwd,
+ )
+
+
+def decoded_pixel(path: Path, timestamp: float, *, cwd: Path) -> tuple[int, int, int]:
+ result = run_ffmpeg(
+ [
+ "-ss",
+ str(timestamp),
+ "-i",
+ str(path),
+ "-frames:v",
+ "1",
+ "-vf",
+ "scale=1:1",
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgb24",
+ "-",
+ ],
+ cwd=cwd,
+ )
+ if len(result.stdout) < 3:
+ raise AssertionError(f"no decoded pixel from {path}")
+ return tuple(result.stdout[:3])
+
+
+def decoded_frequency(path: Path, *, cwd: Path) -> float:
+ sample_rate = 8000
+ result = run_ffmpeg(
+ [
+ "-ss",
+ "0.1",
+ "-t",
+ "0.5",
+ "-i",
+ str(path),
+ "-map",
+ "0:a:0",
+ "-f",
+ "s16le",
+ "-acodec",
+ "pcm_s16le",
+ "-ac",
+ "1",
+ "-ar",
+ str(sample_rate),
+ "-",
+ ],
+ cwd=cwd,
+ )
+ samples = [
+ int.from_bytes(result.stdout[index:index + 2], "little", signed=True)
+ for index in range(0, len(result.stdout) - 1, 2)
+ ]
+ nonzero = [sample for sample in samples if sample]
+ crossings = sum(
+ (left < 0 <= right) or (left > 0 >= right)
+ for left, right in zip(nonzero, nonzero[1:])
+ )
+ seconds = len(samples) / sample_rate
+ return crossings / (2 * seconds)
+
+
+def available_browser() -> str | None:
+ return fixtures.load_script("browser_tools").find_browser(os.environ.get("MOVIE_BROWSER"))
+
+
+class AssemblyRegression(unittest.TestCase):
+ def test_narration_padding_and_offsets(self):
+ missing = fixtures.missing_executables("uv", "ffmpeg", "ffprobe")
+ if missing:
+ self.skipTest(f"required executable(s) not on PATH: {', '.join(missing)}")
+
+ with tempfile.TemporaryDirectory() as directory:
+ work = Path(directory)
+ scenes = fixtures.assembly_fixture(work)
+ result = fixtures.run_tool(
+ "assemble", [str(scenes), str(work / "out.mp4")], cwd=work
+ )
+ self.assertEqual(result.returncode, 0, fixtures.output_text(result))
+ self.assertAlmostEqual(
+ fixtures.duration(work / "out.mp4"), 8, delta=0.4
+ )
+ offsets = json.loads(
+ (work / "segments/offsets.json").read_text(encoding="utf-8")
+ )
+ self.assertAlmostEqual(offsets["body"], 2, delta=0.3)
+
+ subtitles = fixtures.run_tool(
+ "make-subtitles",
+ [
+ str(work / "narration/manifest.json"),
+ str(work / "out.srt"),
+ "--offsets-json",
+ str(work / "segments/offsets.json"),
+ ],
+ cwd=work,
+ )
+ self.assertEqual(
+ subtitles.returncode, 0, fixtures.output_text(subtitles)
+ )
+ srt = (work / "out.srt").read_text(encoding="utf-8")
+ timing_line = next(line for line in srt.splitlines() if "-->" in line)
+ start = timing_line.partition("-->")[0].strip()
+ hours, minutes, seconds_millis = start.split(":")
+ seconds, millis = seconds_millis.split(",")
+ first_cue_start = (
+ int(hours) * 3600
+ + int(minutes) * 60
+ + int(seconds)
+ + int(millis) / 1000
+ )
+ self.assertAlmostEqual(
+ first_cue_start,
+ offsets["body"],
+ delta=0.001,
+ )
+
+ def test_image_frames_and_movie_paths_timing_order_and_cleanup(self):
+ missing = fixtures.missing_executables("uv", "ffmpeg", "ffprobe")
+ if missing:
+ self.skipTest(f"required executable(s) not on PATH: {', '.join(missing)}")
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ launch = root / "launch"
+ launch.mkdir()
+ project = root / "movie O'Brien λ & [take]"
+ assets = project / "assets"
+ frames = assets / "frames"
+ subtitles = assets / "subtitles" / "nested"
+ narration = project / "narration"
+ frames.mkdir(parents=True)
+ subtitles.mkdir(parents=True)
+ narration.mkdir()
+
+ still = assets / "still image.png"
+ Image.new("RGB", (160, 90), (230, 230, 230)).save(still)
+ Image.new("RGB", (160, 90), (255, 0, 0)).save(frames / "a.png")
+ Image.new("RGB", (160, 90), (0, 0, 255)).save(frames / "b.png")
+ source_pngs = {
+ path: path.read_bytes() for path in [still, *sorted(frames.glob("*.png"))]
+ }
+
+ source_movie = assets / "source movie.mp4"
+ make_movie(source_movie, 0.8, 440, cwd=launch)
+ make_tone(narration / "image.wav", 0.8, 660, cwd=launch)
+ make_tone(narration / "frames.wav", 1.4, 770, cwd=launch)
+ make_tone(narration / "movie.wav", 1.6, 880, cwd=launch)
+
+ nested_srt = subtitles / "captions.srt"
+ nested_srt.write_bytes(
+ b"1\r\n00:00:00,000 --> 00:00:00,500\r\nPortable paths\r\n"
+ )
+ scenes = project / "scenes.yaml"
+ yaml_text = f"""resolution: {{ width: 160, height: 90 }}
+fps: 10
+scenes:
+ - id: image
+ kind: image
+ src: assets/still image.png
+ duration: 0.3
+ - id: frames
+ kind: frames
+ src: {frames.resolve().as_posix()}
+ rate: 2.0
+ - id: movie
+ kind: movie
+ src: assets/source movie.mp4
+"""
+ scenes.write_bytes(yaml_text.replace("\n", "\r\n").encode("utf-8"))
+
+ work = root / "generated outside launch"
+ output = project / "assembled output.mp4"
+ result = fixtures.run_tool(
+ "assemble",
+ [
+ os.path.relpath(scenes, launch),
+ os.path.relpath(output, launch),
+ "--narration",
+ str(narration.resolve()),
+ "--work",
+ str(work.resolve()),
+ ],
+ cwd=launch,
+ )
+ self.assertEqual(result.returncode, 0, fixtures.output_text(result))
+
+ image_duration = fixtures.duration(work / "image.mp4")
+ frames_duration = fixtures.duration(work / "frames.mp4")
+ movie_duration = fixtures.duration(work / "movie.mp4")
+ self.assertAlmostEqual(
+ image_duration,
+ max(fixtures.duration(narration / "image.wav"), 0.3),
+ delta=0.25,
+ )
+ self.assertAlmostEqual(
+ frames_duration,
+ max(fixtures.duration(narration / "frames.wav"), 1.0),
+ delta=0.25,
+ )
+ self.assertAlmostEqual(
+ movie_duration,
+ fixtures.duration(source_movie),
+ delta=0.25,
+ )
+ self.assertLess(movie_duration, fixtures.duration(narration / "movie.wav") - 0.4)
+ self.assertAlmostEqual(
+ decoded_frequency(work / "movie.mp4", cwd=launch),
+ 440,
+ delta=15,
+ )
+
+ offsets = json.loads(
+ (work / "offsets.json").read_text(encoding="utf-8")
+ )
+ self.assertAlmostEqual(offsets["image"], 0.0, delta=0.001)
+ self.assertAlmostEqual(offsets["frames"], image_duration, delta=0.001)
+ self.assertNotIn("movie", offsets)
+
+ first = decoded_pixel(work / "frames.mp4", 0.2, cwd=launch)
+ second = decoded_pixel(work / "frames.mp4", 0.7, cwd=launch)
+ self.assertGreater(first[0], first[2] + 100)
+ self.assertGreater(second[2], second[0] + 100)
+ self.assertEqual(
+ {path: path.read_bytes() for path in source_pngs},
+ source_pngs,
+ )
+ self.assertEqual(list(work.glob("frames-frames-*")), [])
+
+ subtitled = project / "subtitled output.mp4"
+ subtitle_result = fixtures.run_tool(
+ "burn-subtitles",
+ [
+ str(output.resolve()),
+ os.path.relpath(nested_srt, launch),
+ str(subtitled.resolve()),
+ "--soft",
+ ],
+ cwd=launch,
+ )
+ self.assertEqual(
+ subtitle_result.returncode,
+ 0,
+ fixtures.output_text(subtitle_result),
+ )
+ self.assertTrue(subtitled.is_file())
+
+ def test_card_uses_longer_narration_duration(self):
+ missing = fixtures.missing_executables("uv", "ffmpeg", "ffprobe")
+ if missing:
+ self.skipTest(f"required executable(s) not on PATH: {', '.join(missing)}")
+ browser = available_browser()
+ if browser is None:
+ self.skipTest("required browser unavailable for card assembly")
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ narration = root / "narration"
+ narration.mkdir()
+ make_tone(narration / "card.wav", 0.8, 550, cwd=root)
+ scenes = root / "scenes.yaml"
+ scenes.write_bytes(
+ b"\xef\xbb\xbfresolution: { width: 160, height: 90 }\r\n"
+ b"fps: 10\r\n"
+ b"scenes:\r\n"
+ b" - id: card\r\n"
+ b" kind: card\r\n"
+ b" title: Portable\r\n"
+ b" subtitle: paths\r\n"
+ b" duration: 0.3\r\n"
+ )
+ work = root / "work"
+ result = fixtures.run_tool(
+ "assemble",
+ [
+ str(scenes),
+ str(root / "out.mp4"),
+ "--work",
+ str(work),
+ "--browser",
+ browser,
+ ],
+ cwd=root,
+ )
+ self.assertEqual(result.returncode, 0, fixtures.output_text(result))
+ self.assertAlmostEqual(
+ fixtures.duration(work / "card.mp4"),
+ max(fixtures.duration(narration / "card.wav"), 0.3),
+ delta=0.25,
+ )
+ offsets = json.loads(
+ (work / "offsets.json").read_text(encoding="utf-8")
+ )
+ self.assertAlmostEqual(offsets["card"], 0.0, delta=0.001)
+
+ def test_frame_sources_survive_failed_assembly_cleanup(self):
+ missing = fixtures.missing_executables("uv", "ffmpeg", "ffprobe")
+ if missing:
+ self.skipTest(f"required executable(s) not on PATH: {', '.join(missing)}")
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source = root / "movie O'Brien λ & [take]" / "frames"
+ source.mkdir(parents=True)
+ bad_frame = source / "a.png"
+ bad_frame.write_bytes(b"not a PNG")
+ scenes = root / "scenes.yaml"
+ scenes.write_text(
+ f"""resolution: {{ width: 160, height: 90 }}
+fps: 10
+scenes:
+ - id: broken
+ kind: frames
+ src: {source.resolve().as_posix()}
+ rate: 1.0
+""",
+ encoding="utf-8",
+ )
+ work = root / "work"
+ result = fixtures.run_tool(
+ "assemble",
+ [str(scenes), str(root / "out.mp4"), "--work", str(work)],
+ cwd=root,
+ )
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(bad_frame.read_bytes(), b"not a PNG")
+ self.assertEqual(list(work.glob("frames-broken-*")), [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/proving-it-works-with-a-movie/test_browser.py b/tests/proving-it-works-with-a-movie/test_browser.py
new file mode 100644
index 0000000..e14e37b
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_browser.py
@@ -0,0 +1,73 @@
+import os
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from PIL import Image
+import fixtures
+
+
+class BrowserToolsRegression(unittest.TestCase):
+ def test_explicit_unusable_browser_fails_authoritatively(self):
+ module = fixtures.load_script("browser_tools")
+ with self.assertRaises(FileNotFoundError):
+ module.find_browser("this-browser-does-not-exist")
+ if os.name != "nt":
+ with tempfile.NamedTemporaryFile() as file:
+ with self.assertRaises(FileNotFoundError):
+ module.find_browser(file.name)
+
+ def test_windows_chrome_edge_discovery(self):
+ module = fixtures.load_script("browser_tools")
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ for relative in ("Google/Chrome/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe"):
+ browser = root / relative
+ browser.parent.mkdir(parents=True)
+ browser.touch()
+ with patch.object(module.sys, "platform", "win32"), patch.dict(os.environ, {"LOCALAPPDATA": str(root)}, clear=True), patch.object(module.shutil, "which", return_value=None):
+ self.assertEqual(module.find_browser(None), str(browser.resolve()))
+ browser.unlink()
+ with patch.object(module.sys, "platform", "win32"), patch.dict(os.environ, {}, clear=True), patch.object(module.shutil, "which", side_effect=lambda name: "C:/Edge/msedge.exe" if name == "msedge.exe" else None):
+ self.assertEqual(module.find_browser(None), "C:/Edge/msedge.exe")
+
+ def browser(self, module):
+ browser = module.find_browser(os.environ.get("MOVIE_BROWSER"))
+ if not browser:
+ self.skipTest("Chrome/Edge is required")
+ return browser
+
+ def test_render_card_special_path_is_a_real_png(self):
+ module = fixtures.load_script("browser_tools")
+ browser = self.browser(module)
+ with tempfile.TemporaryDirectory() as directory:
+ work = Path(directory) / "special path O'Brien λ # %"
+ work.mkdir()
+ html, png = work / "card page.html", work / "card.png"
+ html.write_text("<meta charset='utf-8'><style>body{margin:0;background:rgb(255,0,0)}</style><p>λ</p>", encoding="utf-8")
+ module.render_card(html, png, browser=browser, width=640, height=360)
+ with Image.open(png) as image:
+ self.assertEqual(image.size, (640, 360))
+ self.assertEqual(image.convert("RGB").getpixel((500, 200)), (255, 0, 0))
+
+ def test_render_card_timeout_preserves_unrelated_process(self):
+ module = fixtures.load_script("browser_tools")
+ browser = self.browser(module)
+ sentinel = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ with tempfile.TemporaryDirectory() as directory:
+ work = Path(directory)
+ html = work / "card.html"
+ html.write_text("<p>timeout</p>", encoding="utf-8")
+ start = time.monotonic()
+ with self.assertRaises(TimeoutError):
+ module.render_card(html, work / "card.png", browser=browser, width=640, height=360, timeout=0)
+ self.assertLess(time.monotonic() - start, 10)
+ self.assertIsNone(sentinel.poll())
+ finally:
+ sentinel.terminate()
+ sentinel.wait(timeout=10)
diff --git a/tests/proving-it-works-with-a-movie/test_checker.py b/tests/proving-it-works-with-a-movie/test_checker.py
new file mode 100644
index 0000000..dd5ad82
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_checker.py
@@ -0,0 +1,95 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from PIL import Image
+
+import fixtures
+
+
+class CheckerRegression(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ missing = fixtures.missing_executables("uv", "ffmpeg", "ffprobe")
+ if missing:
+ raise unittest.SkipTest(
+ f"required executable(s) not on PATH: {', '.join(missing)}"
+ )
+ cls._temporary_directory = tempfile.TemporaryDirectory()
+ cls.addClassCleanup(cls._temporary_directory.cleanup)
+ cls.work = Path(cls._temporary_directory.name)
+ cls.movies = fixtures.checker_fixture(cls.work)
+
+ def check(
+ self, expected_exit: int, needle: str, movie: Path, *extra_args: str
+ ) -> Path:
+ output_directory = self.work / f"{movie.stem}-check"
+ result = fixtures.run_tool(
+ "check-movie",
+ [str(movie), "--out", str(output_directory), *extra_args],
+ cwd=self.work,
+ )
+ output = fixtures.output_text(result)
+ self.assertEqual(result.returncode, expected_exit, output)
+ self.assertIn(needle.casefold(), output.casefold())
+ return output_directory
+
+ def test_front_loaded_action_is_rejected(self):
+ self.check(
+ 1,
+ "every visible change happens in the first",
+ self.movies["front-loaded"],
+ )
+
+ def test_paced_with_subtitles_is_accepted(self):
+ self.check(0, "Mechanical checks pass", self.movies["paced"])
+
+ def test_narrated_without_subtitles_is_rejected(self):
+ self.check(
+ 1,
+ "no subtitles",
+ self.movies["paced"],
+ "--subs",
+ str(self.work / "nope.srt"),
+ )
+
+ def test_subtitles_that_stop_early_are_rejected(self):
+ self.check(1, "subtitles stop at", self.movies["short"])
+
+ def test_subtitle_check_is_opt_outable(self):
+ self.check(
+ 0,
+ "Mechanical checks pass",
+ self.movies["paced"],
+ "--subs",
+ str(self.work / "nope.srt"),
+ "--no-expect-subtitles",
+ )
+
+ def test_still_with_audio_is_rejected(self):
+ self.check(1, "never reaches a new state", self.movies["still"])
+
+ def test_missing_narration_is_rejected(self):
+ self.check(1, "no audio stream", self.movies["silent"])
+
+ def test_silent_movie_passes_when_unnarrated(self):
+ self.check(
+ 0,
+ "Mechanical checks pass",
+ self.movies["silent"],
+ "--no-expect-audio",
+ )
+
+ def test_contact_sheet_is_always_written(self):
+ output_directory = self.check(
+ 0, "contact-sheet.png", self.movies["paced"]
+ )
+ sheet = output_directory / "contact-sheet.png"
+ self.assertTrue(sheet.is_file(), f"missing contact sheet: {sheet}")
+ with Image.open(sheet) as image:
+ image.load()
+ self.assertEqual(image.format, "PNG")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/proving-it-works-with-a-movie/test_narration.py b/tests/proving-it-works-with-a-movie/test_narration.py
new file mode 100644
index 0000000..c4c6884
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_narration.py
@@ -0,0 +1,199 @@
+import io
+import tempfile
+from contextlib import redirect_stderr, redirect_stdout
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import fixtures
+
+
+SCRIPT = (
+ "This is smevals studio. Every eval on the shelf is a folder of tasks and "
+ "graders."
+)
+
+
+class NarrationDriftRegression(unittest.TestCase):
+ def drift(self, expected_exit: int, heard: str) -> None:
+ missing = fixtures.missing_executables("uv")
+ if missing:
+ self.skipTest(
+ f"required executable(s) not on PATH: {', '.join(missing)}"
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ work = Path(directory)
+ script_path = work / "script.txt"
+ heard_path = work / "heard.txt"
+ script_path.write_text(SCRIPT, encoding="utf-8")
+ heard_path.write_text(heard, encoding="utf-8")
+ result = fixtures.run_tool(
+ "narrate",
+ ["--drift-check", str(script_path), str(heard_path)],
+ cwd=work,
+ )
+ self.assertEqual(
+ result.returncode, expected_exit, fixtures.output_text(result)
+ )
+
+ def test_mispronounced_jargon_passes(self):
+ self.drift(
+ 0,
+ "This is Mevil studio. Every Yvel on the shelf is a folder of tasks "
+ "and graders.",
+ )
+
+ def test_exact_transcript_passes(self):
+ self.drift(0, SCRIPT)
+
+ def test_dropped_clause_fails(self):
+ self.drift(1, "This is smevals studio.")
+
+ def test_invented_preamble_fails(self):
+ self.drift(
+ 1,
+ "Sure, here it is, happy to help with that. This is smevals studio. "
+ "Every eval on the shelf is a folder of tasks and graders.",
+ )
+
+ def test_empty_clip_fails(self):
+ self.drift(1, "you")
+
+ def test_cached_audio_requires_requested_verification(self):
+ import json
+ import sys
+ module = fixtures.load_script("narrate")
+ with tempfile.TemporaryDirectory() as tmp:
+ work = Path(tmp)
+ output = work / "voice"
+ output.mkdir()
+ (output / "clip.wav").write_bytes(b"cached audio fixture")
+ (output / "manifest.json").write_text(json.dumps([
+ {"id": "clip", "text": "Read this sentence.", "wav": "clip.wav",
+ "duration": 1.0}
+ ]), encoding="utf-8")
+ scenes = work / "scenes.yaml"
+ scenes.write_text(json.dumps({"scenes": [
+ {"id": "clip", "narration": "Read this sentence."}
+ ]}), encoding="utf-8")
+ argv = ["narrate", str(scenes), str(output),
+ "--engine", "piper", "--verify", "on"]
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with patch.object(sys, "argv", argv), \
+ patch.object(module, "openai_key", return_value=None), \
+ patch.object(module, "duration", return_value=1.0), \
+ patch.object(module, "transcribe_local", return_value=None), \
+ redirect_stdout(stdout), redirect_stderr(stderr):
+ self.assertNotEqual(module.main(), 0)
+ self.assertIn("clip: required verification unavailable", stderr.getvalue())
+ self.assertIn("FAILED verbatim delivery: ['clip']", stderr.getvalue())
+ self.assertEqual(
+ json.loads((output / "manifest.json").read_text(encoding="utf-8")),
+ [],
+ )
+ self.assertEqual((output / "clip.wav").read_bytes(), b"cached audio fixture")
+
+ def test_rejected_chat_audio_is_never_cached_but_accepted_audio_is(self):
+ import json
+ import sys
+ module = fixtures.load_script("narrate")
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ scenes = root / "scenes.yaml"
+ scenes.write_text(json.dumps({"scenes": [
+ {"id": "accepted", "narration": "Read this sentence exactly."},
+ {"id": "rejected", "narration": "Keep this evidence out of the manifest."},
+ ]}), encoding="utf-8")
+ output = root / "voice"
+ calls = []
+
+ def synthesize(key, text, wav, voice):
+ calls.append(text)
+ wav.write_bytes(f"render {len(calls)}".encode())
+ if text.startswith("Keep"):
+ return "Unrelated invented preamble with entirely different words here."
+ return text
+
+ argv = ["narrate", str(scenes), str(output), "--engine", "openai-chat",
+ "--verify", "off"]
+ rejected_renders = []
+ with patch.object(sys, "argv", argv), \
+ patch.object(module, "openai_key", return_value="test-key"), \
+ patch.object(module, "say_openai_chat", side_effect=synthesize), \
+ patch.object(module, "duration", return_value=1.0):
+ for _ in range(2):
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ self.assertEqual(module.main(), 1)
+ manifest = json.loads(
+ (output / "manifest.json").read_text(encoding="utf-8")
+ )
+ self.assertEqual([entry["id"] for entry in manifest], ["accepted"])
+ rejected_renders.append((output / "rejected.wav").read_bytes())
+
+ self.assertEqual(calls.count("Read this sentence exactly."), 1)
+ self.assertEqual(calls.count("Keep this evidence out of the manifest."), 4)
+ self.assertNotEqual(rejected_renders[0], rejected_renders[1])
+
+class TranscriptionProtocolRegression(unittest.TestCase):
+ def test_owned_json_is_used_instead_of_library_stdout(self):
+ import json
+ import subprocess
+ import sys
+ import io
+ module = fixtures.load_script("narrate")
+ def child(argv, **kwargs):
+ self.assertIn("--isolated", argv)
+ self.assertIn("--no-project", argv)
+ self.assertIn("--no-config", argv)
+ self.assertEqual(argv[argv.index("--python") + 1], sys.executable)
+ self.assertNotEqual(Path(kwargs["cwd"]), Path.cwd())
+ Path(argv[-1]).write_text(json.dumps({"text": "Correct λ transcript"}), encoding="utf-8")
+ return subprocess.CompletedProcess(argv, 0, "native library warning", "diagnostic")
+ diagnostics = io.StringIO()
+ with patch.object(module.subprocess, "run", side_effect=child), redirect_stderr(diagnostics):
+ self.assertEqual(module.transcribe_local(Path("clip.wav")), "Correct λ transcript")
+ self.assertIn("native library warning", diagnostics.getvalue())
+ self.assertIn("diagnostic", diagnostics.getvalue())
+
+ def test_failed_absent_and_malformed_child_results_are_unavailable(self):
+ import subprocess
+ module = fixtures.load_script("narrate")
+ for payload, code in ((None, 0), ("garbage", 0), ('{"text": 7}', 0), ('{"text": ""}', 0), ('{"text": "words"}', 1)):
+ with self.subTest(payload=payload, code=code):
+ def child(argv, **kwargs):
+ if payload is not None and "--isolated" in argv:
+ Path(argv[-1]).write_text(payload, encoding="utf-8")
+ return subprocess.CompletedProcess(argv, code, "misleading stdout", "error")
+ diagnostics = io.StringIO()
+ with patch.object(module.subprocess, "run", side_effect=child), \
+ redirect_stderr(diagnostics):
+ self.assertIsNone(module.transcribe_local(Path("clip.wav")))
+ self.assertIn("local ASR", diagnostics.getvalue())
+
+ def test_fresh_and_off_then_on_clips_require_asr(self):
+ import json
+ import sys
+ module = fixtures.load_script("narrate")
+ for cached in (False, True):
+ with self.subTest(cached=cached), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ scenes = root / "scenes.yaml"
+ scenes.write_text(json.dumps({"scenes": [{"id": "clip", "narration": "Read this sentence."}]}), encoding="utf-8-sig")
+ output = root / "voice"
+ def synthesize(text, wav, voice):
+ wav.write_bytes(b"branch policy fixture")
+ argv = ["narrate", str(scenes), str(output), "--engine", "piper", "--verify"]
+ with patch.object(module, "openai_key", return_value=None), patch.object(module, "say_piper", side_effect=synthesize), patch.object(module, "duration", return_value=1.0), patch.object(module, "transcribe_local", return_value=None):
+ if cached:
+ with patch.object(sys, "argv", [*argv, "off"]), \
+ redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
+ self.assertEqual(module.main(), 0)
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with patch.object(sys, "argv", [*argv, "on"]), \
+ redirect_stdout(stdout), redirect_stderr(stderr):
+ self.assertNotEqual(module.main(), 0)
+ self.assertIn("clip: required verification unavailable", stderr.getvalue())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/proving-it-works-with-a-movie/test_paths.py b/tests/proving-it-works-with-a-movie/test_paths.py
new file mode 100644
index 0000000..ed1cb50
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_paths.py
@@ -0,0 +1,104 @@
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+import wave
+from pathlib import Path
+
+
+SCRIPTS = (
+ Path(__file__).resolve().parents[2]
+ / "skills/proving-it-works-with-a-movie/scripts"
+)
+sys.path.insert(0, str(SCRIPTS))
+
+import media_paths
+
+
+class MediaPathRegression(unittest.TestCase):
+ def test_frame_staging_uses_ordinary_ordered_files(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source = root / "movie O'Brien λ & [take]"
+ source.mkdir()
+ (source / "b.png").write_bytes(b"second")
+ (source / "a.png").write_bytes(b"first")
+
+ staged = media_paths.stage_frames(source, root / "staged")
+
+ self.assertEqual(
+ [path.read_bytes() for path in staged],
+ [b"first", b"second"],
+ )
+ self.assertTrue(all(not path.is_symlink() for path in staged))
+ self.assertEqual(len(list(source.iterdir())), 2)
+
+ def test_frame_staging_rejects_an_empty_source(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ source = root / "empty"
+ source.mkdir()
+
+ with self.assertRaisesRegex(ValueError, "no PNG frames"):
+ media_paths.stage_frames(source, root / "staged")
+
+ self.assertFalse((root / "staged").exists())
+
+ def test_ffconcat_entry_is_accepted_by_ffmpeg(self):
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg is None:
+ self.skipTest("required executable not on PATH: ffmpeg")
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory) / "movie O'Brien λ & [take]"
+ nested = root / "subtitles" / "nested"
+ nested.mkdir(parents=True)
+ audio = nested / "tone.wav"
+ with wave.open(str(audio), "wb") as output:
+ output.setnchannels(1)
+ output.setsampwidth(2)
+ output.setframerate(8000)
+ output.writeframes(b"\x00\x00" * 800)
+
+ if sys.platform == "win32":
+ self.assertRegex(str(audio.resolve()), r"^[A-Za-z]:\\")
+
+ listing = root / "concat.txt"
+ listing.write_text(
+ "ffconcat version 1.0\n" + media_paths.ffconcat_entry(audio),
+ encoding="utf-8",
+ )
+ result = subprocess.run(
+ [
+ ffmpeg,
+ "-nostdin",
+ "-v",
+ "error",
+ "-f",
+ "concat",
+ "-safe",
+ "0",
+ "-i",
+ str(listing),
+ "-f",
+ "null",
+ "-",
+ ],
+ cwd=Path(directory),
+ capture_output=True,
+ timeout=30,
+ )
+ self.assertEqual(
+ result.returncode,
+ 0,
+ (result.stdout + result.stderr).decode("utf-8", errors="replace"),
+ )
+
+ def test_ffconcat_entry_rejects_line_breaks(self):
+ with self.assertRaisesRegex(ValueError, "cannot contain line breaks"):
+ media_paths.ffconcat_entry(Path("bad\nname.wav"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/proving-it-works-with-a-movie/test_subtitles.py b/tests/proving-it-works-with-a-movie/test_subtitles.py
new file mode 100644
index 0000000..21c37d1
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_subtitles.py
@@ -0,0 +1,106 @@
+import tempfile
+import sys
+import io
+from contextlib import redirect_stderr, redirect_stdout
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import fixtures
+
+
+class SubtitlePathRegression(unittest.TestCase):
+ def test_hard_burn_runs_from_safe_directory_with_absolute_media(self):
+ module = fixtures.load_script("burn-subtitles")
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory) / "movie O'Brien λ"
+ root.mkdir()
+ movie, subs, output = root / "in.mp4", root / "nested" / "captions.srt", root / "out.mp4"
+ subs.parent.mkdir()
+ movie.write_bytes(b"movie")
+ subs.write_bytes("\ufeff1\r\n00:00:00,000 --> 00:00:01,000\r\nλ\r\n".encode("utf-8"))
+ calls = []
+
+ def fake_run(cmd, *, cwd=None):
+ calls.append((cmd, cwd))
+ if cwd is not None:
+ self.assertEqual((cwd / "captions.srt").read_bytes(), subs.read_bytes())
+ return True
+
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with patch.object(sys, "argv", ["burn-subtitles", str(movie), str(subs), str(output)]), patch.object(module.shutil, "which", return_value="ffmpeg"), patch.object(module, "has_libass", return_value=True), patch.object(module, "run", side_effect=fake_run), redirect_stdout(stdout), redirect_stderr(stderr):
+ self.assertEqual(module.main(), 0)
+ self.assertIn("burned into the picture", stdout.getvalue())
+ command, cwd = calls[0]
+ self.assertEqual(cwd.name.startswith("movie-subtitles-"), True)
+ self.assertIn(str(movie.resolve()), command)
+ self.assertIn(str(output.resolve()), command)
+ self.assertTrue(any(value.startswith("subtitles=filename=captions.srt") for value in command))
+ self.assertFalse(cwd.exists())
+
+ def test_burn_failure_is_reported_separately_from_missing_libass(self):
+ module = fixtures.load_script("burn-subtitles")
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ movie, subs, output = root / "in.mp4", root / "captions.srt", root / "out.mp4"
+ movie.write_bytes(b"movie")
+ subs.write_text("1\n00:00:00,000 --> 00:00:01,000\ncaption\n", encoding="utf-8")
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with patch.object(sys, "argv", ["burn-subtitles", str(movie), str(subs), str(output)]), patch.object(module.shutil, "which", return_value="ffmpeg"), patch.object(module, "has_libass", return_value=True), patch.object(module, "run", return_value=False), redirect_stdout(stdout), redirect_stderr(stderr):
+ self.assertEqual(module.main(), 1)
+ self.assertIn("burn failed", stderr.getvalue())
+
+class SubtitleIntegrationRegression(unittest.TestCase):
+ def test_bom_manifest_and_offsets_write_utf8_under_legacy_console(self):
+ import json
+ import os
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ manifest, offsets, out = root / "manifest.json", root / "offsets.json", root / "λ.srt"
+ manifest.write_bytes(('\ufeff' + json.dumps([{"id": "clip", "text": "Unicode λ café", "duration": 1}], ensure_ascii=False) + '\r\n').encode('utf-8'))
+ offsets.write_text('{"clip": 2}', encoding="utf-8-sig")
+ env = dict(os.environ, PYTHONIOENCODING="cp1252", PYTHONUTF8="0")
+ result = fixtures.run_tool("make-subtitles", [str(manifest), str(out), "--offsets-json", str(offsets)], cwd=root, env=env)
+ self.assertEqual(result.returncode, 0, fixtures.output_text(result))
+ text = out.read_text(encoding="utf-8")
+ self.assertIn("Unicode λ café", text)
+ self.assertIn("00:00:02,000 --> 00:00:03,000", text)
+ self.assertFalse(out.read_bytes().startswith(b'\xef\xbb\xbf'))
+
+ def test_hard_subtitles_are_pixels_in_nested_special_path(self):
+ import subprocess
+ missing = fixtures.missing_executables("uv", "ffmpeg")
+ if missing:
+ self.skipTest(f"required executable(s) not on PATH: {', '.join(missing)}")
+ module = fixtures.load_script("burn-subtitles")
+ if not module.has_libass():
+ self.skipTest("libass FFmpeg is required for hard subtitle pixels")
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory) / "O'Brien λ # %"
+ root.mkdir()
+ movie, subs, output = root / "in.mp4", root / "nested" / "O'Brien.srt", root / "out.mp4"
+ subs.parent.mkdir()
+ subs.write_bytes("\ufeff1\r\n00:00:00,000 --> 00:00:01,000\r\nVisible caption\r\n".encode("utf-8"))
+ fixtures._run_ffmpeg(["-f", "lavfi", "-i", "color=c=black:s=640x360:d=1", "-c:v", "libx264", str(movie)], cwd=root)
+ result = fixtures.run_tool("burn-subtitles", [str(movie), str(subs), str(output)], cwd=Path(directory))
+ self.assertEqual(result.returncode, 0, fixtures.output_text(result))
+ self.assertIn("burned into the picture", fixtures.output_text(result))
+ frame = subprocess.run(["ffmpeg", "-v", "error", "-ss", "0.5", "-i", str(output), "-frames:v", "1", "-pix_fmt", "gray", "-f", "rawvideo", "-"], capture_output=True, check=True).stdout
+ self.assertGreater(sum(value > 180 for value in frame), 50)
+
+ def test_burn_failure_fallback_does_not_claim_missing_libass(self):
+ module = fixtures.load_script("burn-subtitles")
+ for libass in (True, False):
+ with self.subTest(libass=libass), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ movie, subs = root / "in.mp4", root / "in.srt"
+ movie.touch(); subs.touch()
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with patch.object(sys, "argv", ["burn-subtitles", str(movie), str(subs), str(root / "out.mp4")]), patch.object(module.shutil, "which", return_value="ffmpeg"), patch.object(module, "has_libass", return_value=libass), patch.object(module, "run", side_effect=[False, True] if libass else [True]), redirect_stdout(stdout), redirect_stderr(stderr):
+ self.assertEqual(module.main(), 0)
+ self.assertEqual("no libass" in stdout.getvalue(), not libass)
+ self.assertEqual("burn failed" in stderr.getvalue(), libass)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/proving-it-works-with-a-movie/test_terminal.py b/tests/proving-it-works-with-a-movie/test_terminal.py
new file mode 100644
index 0000000..93301b4
--- /dev/null
+++ b/tests/proving-it-works-with-a-movie/test_terminal.py
@@ -0,0 +1,307 @@
+"""The terminal recorder: prompt parsing and the frame grid anywhere; a real
+ttyd session wherever ttyd and a Chrome-family browser exist."""
+import importlib.util
+import json
+import os
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+import fixtures
+
+SCRIPT = Path(__file__).resolve().parents[2] / "skills/proving-it-works-with-a-movie/examples/film-terminal.py"
+FIXTURE = Path(__file__).resolve().with_name("fixtures") / "terminal_app.py"
+TTYD = os.environ.get("MOVIE_TEST_TTYD") or shutil.which("ttyd")
+BROWSER = fixtures.load_script("browser_tools").find_browser(os.environ.get("MOVIE_TEST_BROWSER"))
+SHELL = os.environ.get("MOVIE_TEST_SHELL") or ("powershell51" if os.name == "nt" else "bash")
+BASH = SHELL in ("bash", "gitbash")
+
+
+def recorder():
+ spec = importlib.util.spec_from_file_location("film_terminal", SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def gone(pid, timeout=5):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if os.name == "nt":
+ listed = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"],
+ capture_output=True, text=True).stdout
+ if str(pid) not in listed:
+ return True
+ else:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return True
+ time.sleep(0.1)
+ return False
+
+
+class PromptTests(unittest.TestCase):
+ def test_prompts_parse_both_terminators_and_paths_with_semicolons(self):
+ module = recorder()
+ log = (b"noise\x1b]0;MOVIE;1;1;;C:\\a;b\x07\x1b[0m"
+ b"\x1b]2;MOVIE;2;0;7;/c/x\x1b\\tail"
+ b"\x1b]0;MOVIE;3;1;0;/home/me\x07")
+ self.assertEqual(module.prompts(log), [
+ dict(n=1, ok=True, exit_code=None, cwd="C:\\a;b"),
+ dict(n=2, ok=False, exit_code=7, cwd="/c/x"),
+ dict(n=3, ok=True, exit_code=0, cwd="/home/me"),
+ ])
+ self.assertEqual(module.prompts(b"\x1b]0;something else\x07"), [])
+
+ def test_prompt_install_is_one_typed_line_per_shell(self):
+ module = recorder()
+ cwd = Path("C:/Users/x/movie O'Brien λ")
+ for kind in module.SHELLS:
+ line = module.prompt_command(kind, cwd)
+ self.assertEqual(len(line.splitlines()), 1, kind)
+ self.assertNotIn("MOVIE;", line, "the marker text must not be echoed by the install line")
+ self.assertIn("Brien λ", module.prompt_script(kind, cwd), "the script enters the cwd")
+
+ def test_keys_are_named_or_single_characters(self):
+ module = recorder()
+ self.assertEqual(module.key_params("Ctrl-C")["modifiers"], 2)
+ self.assertEqual(module.key_params("Enter")["text"], "\r")
+ self.assertEqual(module.key_params("q"), dict(key="q", text="q"))
+ with self.assertRaises(SystemExit):
+ module.key_params("Bogus")
+
+
+class FilmGridTests(unittest.TestCase):
+ def test_filming_refuses_a_nonempty_take_without_changing_its_contents(self):
+ module = recorder()
+ with tempfile.TemporaryDirectory() as directory:
+ out = Path(directory) / "take"
+ out.mkdir()
+ (out / "f00000.png").write_bytes(b"old frame")
+ (out / "notes.txt").write_bytes(b"sentinel evidence")
+ before = {path.name: path.read_bytes() for path in out.iterdir()}
+ captures = []
+
+ with self.assertRaisesRegex(SystemExit, "not empty.*new take directory"):
+ module.film(out, seconds=1, hold=0,
+ capture=lambda: captures.append(True) or b"new frame",
+ finished=lambda: True)
+
+ self.assertEqual(captures, [])
+ self.assertEqual(
+ {path.name: path.read_bytes() for path in out.iterdir()}, before
+ )
+
+ def test_a_slow_capture_repeats_the_previous_frame_and_filming_holds_after_the_prompt(self):
+ module = recorder()
+ clock = {"now": 0.0}
+ shots = []
+
+ def capture():
+ shots.append(len(shots) + 1)
+ clock["now"] += 0.5 if len(shots) == 2 else 0.01 # the second screenshot stalls
+ return bytes([len(shots)])
+
+ with tempfile.TemporaryDirectory() as directory:
+ out = Path(directory) / "take"
+ frames = module.film(out, seconds=10, hold=0.4, capture=capture,
+ finished=lambda: clock["now"] >= 1.0,
+ clock=lambda: clock["now"],
+ sleep=lambda s: clock.__setitem__("now", clock["now"] + s))
+ files = sorted(out.glob("f*.png"))
+ self.assertEqual([f.name for f in files], [f"f{i:05d}.png" for i in range(frames)])
+ self.assertEqual(files[2].read_bytes(), files[1].read_bytes(), "missed slot repeats the last frame")
+ self.assertNotEqual(files[3].read_bytes(), files[2].read_bytes())
+ self.assertEqual(frames, 7, "1.0 s to the prompt plus 0.4 s hold at 5 fps")
+
+ def test_filming_stops_at_the_deadline_while_the_command_runs(self):
+ module = recorder()
+ clock = {"now": 0.0}
+ with tempfile.TemporaryDirectory() as directory:
+ frames = module.film(Path(directory), seconds=1.0, hold=5, capture=lambda: b"png",
+ finished=lambda: False, clock=lambda: clock["now"],
+ sleep=lambda s: clock.__setitem__("now", clock["now"] + s))
+ self.assertEqual(frames, 5)
+
+
+class ServeArgumentTests(unittest.TestCase):
+ def test_serve_refuses_a_missing_cwd_before_launching_anything(self):
+ with tempfile.TemporaryDirectory() as directory:
+ result = subprocess.run([sys.executable, str(SCRIPT), "serve", str(Path(directory) / "session"),
+ "--shell", "bash", "--cwd", str(Path(directory) / "missing")],
+ capture_output=True, text=True, timeout=60)
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("--cwd is not a directory", result.stderr)
+ self.assertFalse((Path(directory) / "session" / "session.json").exists())
+
+ def test_recording_verbs_refuse_a_nonempty_take_before_session_side_effects(self):
+ module = recorder()
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ session = root / "session"
+ session.mkdir()
+ (session / "ready.json").write_text("{}", encoding="utf-8")
+ (session / "session.json").write_text(
+ json.dumps({"debug_port": 1}), encoding="utf-8"
+ )
+ (session / "terminal.log").write_bytes(
+ b"\x1b]0;MOVIE;1;1;0;/tmp\x07"
+ )
+ for verb, positional in (("run", ["echo hello"]),
+ ("key", ["Enter"]),
+ ("watch", [])):
+ with self.subTest(verb=verb):
+ take = root / verb
+ take.mkdir()
+ (take / "f00000.png").write_bytes(b"old frame")
+ (take / "sentinel.txt").write_bytes(b"keep me")
+ before = {path.name: path.read_bytes() for path in take.iterdir()}
+ argv = ["film-terminal", verb, str(session), *positional,
+ "--record", str(take)]
+ with patch.object(sys, "argv", argv), \
+ patch.object(module, "connect",
+ side_effect=AssertionError("connected")), \
+ patch.object(module, "type_text",
+ side_effect=AssertionError("typed")), \
+ patch.object(module, "press",
+ side_effect=AssertionError("pressed")), \
+ self.assertRaisesRegex(SystemExit,
+ "not empty.*new take directory"):
+ module.main()
+ self.assertEqual(
+ {path.name: path.read_bytes() for path in take.iterdir()}, before
+ )
+
+
+@unittest.skipUnless(TTYD and BROWSER, "ttyd and a Chrome-family browser are required")
+class SessionTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(prefix="movie-terminal-", ignore_cleanup_errors=True)
+ self.addCleanup(self.tmp.cleanup)
+ self.work = Path(self.tmp.name) / "movie O'Brien λ"
+ self.work.mkdir()
+ self.session = Path(self.tmp.name) / "session"
+ self.log = (Path(self.tmp.name) / "serve.log").open("wb")
+ self.addCleanup(self.log.close)
+ argv = [sys.executable, str(SCRIPT), "serve", str(self.session), "--shell", SHELL,
+ "--cwd", str(self.work), "--ttyd", TTYD, "--browser", BROWSER]
+ if os.environ.get("MOVIE_TEST_SHELL_EXE"):
+ argv += ["--shell-exe", os.environ["MOVIE_TEST_SHELL_EXE"]]
+ self.serve = subprocess.Popen(argv, stdout=self.log, stderr=subprocess.STDOUT)
+ deadline = time.monotonic() + 45
+ while not (self.session / "ready.json").exists() and self.serve.poll() is None \
+ and time.monotonic() < deadline:
+ time.sleep(0.1)
+ if not (self.session / "ready.json").exists():
+ report = "".join(f"--- {name}\n" + path.read_text(errors="replace") if path.exists() else ""
+ for name, path in (("serve.log", Path(self.tmp.name) / "serve.log"),
+ ("ttyd.log", self.session / "ttyd.log"),
+ ("browser.log", self.session / "browser.log")))
+ self.fail(report)
+
+ def tearDown(self):
+ if self.serve.poll() is None:
+ self.cli("close", str(self.session))
+ try:
+ self.serve.wait(15)
+ except subprocess.TimeoutExpired:
+ self.serve.kill()
+ self.serve.wait()
+ for pid in json.loads((self.session / "session.json").read_text(encoding="utf-8"))["pids"]:
+ self.assertTrue(gone(pid), f"pid {pid} survived close")
+
+ def cli(self, *args, timeout=120):
+ result = subprocess.run([sys.executable, str(SCRIPT), *args], capture_output=True, timeout=timeout)
+ return result.returncode, result.stdout.decode("utf-8", "replace"), result.stderr.decode("utf-8", "replace")
+
+ def run_command(self, command, *extra):
+ code, out, err = self.cli("run", str(self.session), command, *extra)
+ self.assertTrue(out.strip(), err)
+ return code, json.loads(out.strip().splitlines()[-1])
+
+ def quoted(self, *words):
+ if BASH:
+ return " ".join(shlex.quote(w.replace("\\", "/")) for w in words)
+ return "& " + " ".join("'" + w.replace("'", "''") + "'" for w in words)
+
+ def native(self, code):
+ return self.quoted(sys.executable) + f' -c "{code}"'
+
+ def test_commands_report_status_and_the_shell_persists_between_calls(self):
+ code, result = self.run_command("echo hello")
+ self.assertEqual((code, result["outcome"], result["ok"]), (0, "completed", True), result)
+ self.assertTrue(result["cwd"].endswith("movie O'Brien λ"), result["cwd"])
+ if BASH:
+ set_value, check_value, failing = "MOVIE_VALUE=kept", 'test "$MOVIE_VALUE" = kept', "false"
+ else:
+ set_value = "$global:MovieValue = 'kept'"
+ check_value = "if ($global:MovieValue -ne 'kept') { throw 'lost' }"
+ failing = "Get-Item 'Z:\\nowhere'"
+ self.assertEqual(self.run_command(set_value)[0], 0)
+ self.assertEqual(self.run_command(check_value)[0], 0, "state must survive separate calls")
+ code, result = self.run_command(failing)
+ self.assertEqual((code, result["ok"]), (1, False), result)
+ code, result = self.run_command(self.native("import sys; sys.exit(7)"))
+ self.assertEqual((code, result["ok"], result["exit_code"]), (1, False, 7), result)
+
+ def test_a_tui_is_filmed_across_two_takes_and_a_long_command_across_calls(self):
+ from PIL import Image
+
+ take_one, take_two, take_three = (self.work / name for name in ("take-one", "take-two", "take-three"))
+ code, result = self.run_command(self.quoted(sys.executable, str(FIXTURE)),
+ "--record", str(take_one), "--seconds", "7")
+ self.assertEqual((code, result["outcome"]), (2, "running"), result)
+ frames = sorted(take_one.glob("f*.png"))
+ self.assertGreaterEqual(len(frames), 30, "7 s at 5 fps")
+ seen = []
+ for frame in frames:
+ with Image.open(frame) as image:
+ r, g, b = image.convert("RGB").getpixel((300, 120))
+ color = ("red" if r > 150 and g < 100 and b < 100 else
+ "green" if g > 120 and r < 100 and b < 140 else
+ "blue" if b > 150 and r < 100 and g < 140 else None)
+ if color and (not seen or seen[-1] != color):
+ seen.append(color)
+ self.assertEqual(seen, ["red", "green", "blue"], "the three TUI states, in order, in the automatic frames")
+ code, out, err = self.cli("key", str(self.session), "q", "--record", str(take_two), "--seconds", "10")
+ result = json.loads(out.strip().splitlines()[-1])
+ self.assertEqual((code, result["outcome"], result["ok"]), (0, "completed", True), (result, err))
+ self.assertGreaterEqual(result["frames"], 7, "the exit plus the 1.5 s hold")
+ self.assertEqual(len(json.loads((self.work / "states.json").read_text())), 3)
+
+ code, result = self.run_command(self.native("import time; time.sleep(3)"), "--seconds", "1")
+ self.assertEqual(result["outcome"], "running")
+ code, out, err = self.cli("watch", str(self.session), "--record", str(take_three), "--seconds", "15")
+ result = json.loads(out.strip().splitlines()[-1])
+ self.assertEqual((code, result["outcome"], result["ok"]), (0, "completed", True), (result, err))
+ self.assertGreaterEqual(result["frames"], 10, "about 2 s of waiting plus the hold")
+ self.assertEqual(result["scene"], {"kind": "frames", "src": str(take_three.resolve()), "rate": 5})
+
+ def test_close_kills_the_shell_tree_and_spares_unrelated_processes(self):
+ sentinel = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
+ self.addCleanup(sentinel.kill)
+ tree = self.work / "tree"
+ code, result = self.run_command(self.quoted(sys.executable, str(FIXTURE), "tree", str(tree)), "--seconds", "2")
+ self.assertEqual(result["outcome"], "running")
+ deadline = time.monotonic() + 20
+ while len(list(tree.glob("*.json"))) < 3 and time.monotonic() < deadline:
+ time.sleep(0.1)
+ pids = [json.loads(path.read_text())["pid"] for path in tree.glob("*.json")]
+ self.assertEqual(len(pids), 3)
+ code, out, err = self.cli("close", str(self.session))
+ self.assertEqual(code, 0, err)
+ self.assertEqual(self.serve.wait(15), 0)
+ for pid in pids:
+ self.assertTrue(gone(pid), f"descendant {pid} survived close")
+ self.assertIsNone(sentinel.poll(), "an unrelated process must survive")
+
+
+if __name__ == "__main__":
+ unittest.main()