Search by

sugarcraft / candy-vcr

detain

Record and replay sugar-core Program sessions into cassettes, render VHS .tape scripts to GIFs — bug-repro / regression / fuzzing.

Package info

github.com/sugarcraft/candy-vcr

Documentation

pkg:composer/sugarcraft/candy-vcr

Statistics

Installs: 1 101

Dependents: 5

Suggesters: 0

Stars: 0

Open Issues: 0

dev-master 2026-11-18 21:16 UTC

This package is auto-updated.

Last update: 2026-11-20 01:04:02 UTC


README

Cassette recorder / replayer for sugar-core Programs, and a .tape → .gif terminal-demo renderer for PHP 8.3+ — .tape is the terminal-recording DSL from VHS. The Program/Msg model being recorded lives in sugar-core; the renderer pairs with sugar-vterm — every frame fed to the GIF encoder is a SugarCraft\Vterm\Snapshot taken off sugar-vterm's Terminal.

Records every Msg fed into a sugar-core Program and every frame emitted by view(), with timing, into a cassette file. Replays cassettes by feeding the recorded Msgs back at recorded cadence and asserting frames match (cell-grid equality via sugar-vterm, with byte-equality fallback).

Contents

Status

🟢 v1 ready — cassette recording, replay assertions, tape compilation, frame rendering, rasterization and GIF encoding all ship in the library.

Start with Quickstart for the shortest end-to-end path, or jump straight to CLI if you only want the candy-vcr binary.

Use cases

  • Bug repro — user runs candy-vcr record --output bug.cas -- <cmd>, ships the cassette, maintainer replays locally with candy-vcr replay bug.cas.
  • Regression tests — record a known-good session, replay in CI, diff against expected screen state.
  • Demo capture — alternative to VHS (the Go terminal-GIF recorder) for headless / scriptable recordings (no Docker; runs in a PHP unit-test process).
  • Fuzzing seeds — mutate recorded Msgs slightly, replay to find edge cases.

Install

composer require sugarcraft/candy-vcr

Examples in this README invoke the binary as vendor/bin/candy-vcr; inside a checkout of this repo (the Examples tour, which runs from the candy-vcr/ directory) the same program sits at bin/candy-vcr; with a PHAR install or a composer global install it is simply candy-vcr on PATH. The library itself hard-requires ext-mbstring. Rendering needs ext-gd (or --backend=imagick with ext-imagick) and, for the default encoder, ffmpeg on PATH; PhpGifEncoder is the pure-PHP fallback that needs no external binaries. YamlFormat additionally suggests symfony/yaml.

Nothing to record yet? Two commands play with the cassette that ships in this repo:

bin/candy-vcr inspect examples/cassettes/counter.cas
bin/candy-vcr stats   examples/cassettes/counter.cas

Quickstart

Record a session:

use SugarCraft\Core\Program;
use SugarCraft\Vcr\Recorder;

// $model — any sugar-core Model; examples/record.php ships a tiny CounterModel.
$program = new Program($model);
$program->setRecorder(Recorder::open('/tmp/session.cas'));  // void — statement form
$program->run();
// cassette is closed automatically when the run loop ends
// (final recordQuit rides only a QuitMsg exit; a crash still flushes)

Read a recorded cassette back:

use SugarCraft\Vcr\Format\JsonlFormat;

$cassette = (new JsonlFormat())->read('/tmp/session.cas');
foreach ($cassette->events as $event) {
    echo $event->kind->value, ' @ ', $event->t, "\n";
}

Cassette format

Full schema reference: docs/CASSETTE.md — includes dual-timestamp (t + tRaw) format, all event kinds, and the header structure.

{"v":1,"created":"2026-05-07T10:00:00Z","cols":80,"rows":24,"runtime":"sugarcraft/candy-vcr@record"}
{"t":0.000,"k":"resize","cols":80,"rows":24}
{"t":0.001,"k":"output","b":"�[2J�[H..."}
{"t":0.450,"k":"input","msg":{"@type":"KeyMsg","key":"j"}}
{"t":1.201,"k":"quit"}
  • Line 1 is the header (carries v).
  • Subsequent lines are events keyed by k — all seven EventKind cases (resize, input, output, quit, snapshot, hide, show) with kind-specific payload fields; see docs/CASSETTE.md.
  • t is seconds since cassette start (ms precision).

Cassette formats

candy-vcr ships five cassette codecs, each tuned for a different trade-off between human-readability, file size, and toolchain interop. All five produce the same Cassette value object, but only four of them implement the Format interface (JsonlFormat, CompressedJsonlFormat, RelativeFormat, YamlFormat) and can be dropped into a Format slot. AsciinemaFormat is an importer: it exposes read() only, never write()/encode(), and is not a Format.

Format File extension When to pick it Trade-offs
JsonlFormat (default) .cas, .jsonl, .cassette Tests, version control, day-to-day recording. One JSON document per line, absolute timestamps (t). Human-readable, diff-friendly, no compression.
CompressedJsonlFormat .cas.gz Long recordings, CI artifact storage. Gzipped JSONL. 5–10× smaller on disk; a batch write of a complete Cassette (the gzip pump is incremental inside write(), but the cassette object must exist first — live recording rides plain JSONL). Loses git-diff friendliness.
RelativeFormat .cas (with dt field) Deterministic replay; cassettes meant to be edited by hand. Delta timestamps (interval since previous event). Easier to reason about edits — no need to re-shift downstream t values.
YamlFormat .yaml, .yml Test fixtures where the cassette is hand-authored. Human-editable, indented. Largest on disk; slowest to parse. Lowest priority for production recordings.
AsciinemaFormat .cast Importing existing asciinema recordings. Read-only importer (not a Format): accepts cast v2 (asciinema's own output, top-level width/height) and the v3 header that nests them under term. Stdin events become raw-byte inputs; unknown event types are skipped. Never writes .cast.

Auto-detection. Player::loadAny() and the CLI commands (inspect, replay, diff, stats) accept either a cassette or a .tape source and pick the right loader via SugarCraft\Vcr\Format\CassetteLoader: extension first, then content sniff (first non-blank non-comment line — { is JSON, a known tape directive keyword is a tape source). .cas/.jsonl files dispatch on the first event line (line 2 of the file; line 1 is the header): a dt field selects RelativeFormat, anything else selects JsonlFormat. Anything else throws \InvalidArgumentException.

Tape vs cassette. A .tape file (the VHS DSL) is compiled through the Lexer → Parser → Compiler pipeline before it becomes a Cassette — the on-disk format is source code, not serialized events. CassetteLoader::isTape() exposes the sniff for callers that want to short-circuit on it themselves.

Timestamp modes

Cassettes support two timestamp modes:

Mode Field Use case
absolute (default) t = seconds since cassette start Playback timing
relative interval since previous event (like asciinema v3) — spelled dt by RelativeFormat, or carried in re-based t values by a relative-mode JsonlFormat file (see docs/CASSETTE.md) Deterministic replay; easier manual editing

Select the mode at record time via the header you pass Recorder::open():

use SugarCraft\Vcr\CassetteHeader;
use SugarCraft\Vcr\Recorder;

// Relative timestamps (delta between events) — the mode rides the header.
// Recorder::withFormat(new RelativeFormat()) does NOT flip modes: it only
// confirms the header already matches the format and throws RuntimeException
// on a mismatch. Recorder::defaultHeader() (what open() uses without a
// header) is always absolute — it has no timestampMode knob.
$recorder = Recorder::open('/tmp/session.cas', new CassetteHeader(
    version: CassetteHeader::CURRENT_VERSION,
    createdAt: gmdate('Y-m-d\TH:i:s\Z'),
    cols: 80,
    rows: 24,
    runtime: 'sugarcraft/candy-vcr@dev',
    timestampMode: CassetteHeader::TIMESTAMP_MODE_RELATIVE,
));

$program = new Program($model);
$program->setRecorder($recorder);   // withRecorder() is the deprecated chain form
$program->run();

The Player::open() factory auto-detects which format a cassette uses: a name ending in .gz is handed straight to CompressedJsonlFormat (gzipped JSONL) without any sniffing, every other name is decided by examining the first event line — dt field means RelativeFormat, t field means JsonlFormat. No format parameter needed on replay; for extension-routed loading (.tape sources, .cast imports) use Player::loadAny().

Absolute mode example:

{"t":0.000,"k":"output","b":"$ "}
{"t":0.500,"k":"output","b":"ls\r\n"}
{"t":0.502,"k":"output","b":"file1.txt file2.txt\r\n"}

Relative mode example (same events):

{"dt":0.000,"k":"output","b":"$ "}
{"dt":0.500,"k":"output","b":"ls\r\n"}
{"dt":0.002,"k":"output","b":"file1.txt file2.txt\r\n"}

The header carries timestampMode so the format is self-describing. Backwards compatibility is preserved — cassettes without a timestampMode key default to absolute.

Gzip compression

Cassettes can be gzip-compressed by using the .gz extension or by using CompressedJsonlFormat directly:

use SugarCraft\Vcr\Format\CompressedJsonlFormat;

$format = new CompressedJsonlFormat();

// Write compressed cassette
$format->write($cassette, '/tmp/session.cas.gz');

// Read compressed cassette (auto-detects .gz extension)
$cassette = $format->read('/tmp/session.cas.gz');

Compressed cassettes are typically 5–10× smaller than plain JSONL, making them suitable for CI storage and git repositories. Compression is a batch operation: CompressedJsonlFormat::write() receives a complete Cassette value object, so gzip happens once the recording exists, not as events are recorded — live streaming with coalesced flush doors is the plain-JSONL Recorder's domain. Reading materializes the whole tape in memory too (see Limitations).

Asciinema import

Import asciinema cast files as candy-vcr Cassettes for replay. Both cast shapes are accepted: v2 (what asciinema rec writes, with the terminal size at the top level) and the v3 header that nests it under term:

use SugarCraft\Vcr\Format\AsciinemaFormat;

$cassette = (new AsciinemaFormat())->read('/path/to/session.cast');
$player = new Player($cassette);
$result = $player->play(programFactory: $factory, speed: Player::SPEED_REALTIME);

Event lines carry delta-accumulated (relative) timestamps in both versions — each line records the seconds since the previous event, which the importer re-accumulates into absolute t values. The importer converts o (stdout) events to output events, i (stdin) events to input events, and x (exit) events to quit events.

PHP API

The core types in SugarCraft\Vcr\:

Class Role
Cassette Immutable container: readonly header: CassetteHeader and events: list<Event> properties. Methods eventCount(), duration(). (header() still exists but is @deprecated — read $header.)
CassetteHeader Schema metadata — $version, $createdAt, $cols, $rows, $runtime, $theme, $typingSpeed, $env, $timestampMode, $playbackSpeed, $fontSize, $fontFamily, $widthPx, $heightPx. Constants CURRENT_VERSION (1 — the version writers stamp; MAX_READABLE_VERSION is 2, so readers accept v1 and v2 today and refuse anything newer — v2 exists as the migration target only), PLAYBACK_SPEED_DEFAULT (1.0), TIMESTAMP_MODE_ABSOLUTE, TIMESTAMP_MODE_RELATIVE. (The wire key is created; the DTO property is $createdAt.)
Event One recorded line. Fields: t: float, kind: EventKind, payload array.
EventKind Enum: Resize, Input, Output, Quit, Snapshot, Hide, Show.
Recorder Record-side. Construct via Recorder::open($path, ?CassetteHeader $header = null) — the cassette file is created and tightened to 0600 (owner-only) because cassettes can embed secrets; the header's timestampMode decides absolute vs relative. Methods: withFormat(Format) (confirms only — throws when the header is not relative), withHook(Hook), withIdleTrim($threshold, $compressedMax=0.5), recordResize($cols, $rows), recordInputBytes($bytes), recordOutput($bytes), recordQuit(), close(), captureWriteErrors(): int (count of failed write/flush attempts — a non-zero total means the cassette is silently incomplete). Helpers defaultHeader($cols, $rows, $runtime), hooks(): HookRegistry — hookErrors(): list<string> reports the afterCapture() hooks that threw during capture (recorded, never swallowed; the record command prints them as warnings). Env filtering is RecordCommand::filteredHostEnv() — see the record options.
Player Replay-side. Factories: Player::open($path) (a .gz name is routed straight to CompressedJsonlFormat without sniffing; any other name content-sniffs the first event line (line 2 of the file; line 1 is the header) — a dt field selects RelativeFormat, otherwise JsonlFormat, so for non-.gz names the extension is not consulted), Player::loadAny($path) (extension + content sniff via CassetteLoader, accepts .tape sources). Methods: withIdleTrim(?float), play(programFactory, ?assertion, speed, ?serializerRegistry, ?timeoutSeconds, skipFirstResize, ?matcher, ?idleThresholdSeconds, useRawTimestamps). Constants SPEED_INSTANT, SPEED_REALTIME, INSTANT_YIELD_SECONDS.
Format\Format (interface) write(Cassette, $path), read($path): Cassette, encode(Cassette): string, decode(string): Cassette. Implementations: JsonlFormat (default), CompressedJsonlFormat, RelativeFormat, YamlFormat. AsciinemaFormat is a read-only importer with read() only and implements nothing.
Format\CassetteLoader load($path): Cassette — auto-detects cassette vs tape source. isTape($path): bool — exposes the sniff.
ReplayResult DTO returned by Player::play(). $ok: bool, $diff: string (empty when ok; the assertion diff otherwise), $eventCount, $inputCount, $resizeCount, $outputCount, $quitCount, $programQuitCleanly: bool, $undecodedInputCount (input events whose msg envelope had no registered decoder and were skipped — diffSummary() prints it when non-zero); helper diffSummary(): string.

CLI

vendor/bin/candy-vcr record       --output session.cas -- bash -c 'echo hi'  # capture a real PTY session
vendor/bin/candy-vcr inspect      session.cas                                # list events
vendor/bin/candy-vcr replay       session.cas --speed=realtime               # stream output to stdout
vendor/bin/candy-vcr replay       session.cas --idle-trim=1.0                # clamp long gaps to 1s during replay
vendor/bin/candy-vcr diff         a.cas b.cas                                # structural diff
vendor/bin/candy-vcr stats        session.cas                                # show cassette statistics
vendor/bin/candy-vcr migrate      session.cas upgraded.cas                   # rewrite a v1 cassette as v2 (--dry-run to validate)
vendor/bin/candy-vcr render-tape demo.tape                                 # render .tape to .gif
vendor/bin/candy-vcr render-batch demos/                                     # render all .tape files in directory

record runs the given command under a fresh master/slave PTY. It drops the host stdin into raw mode, pumps bytes through sugar-pty with a Recorder teed onto every stdin and master-output chunk, and writes a session-<timestamp>.cas cassette (override with --output PATH). The CLI is defensive about that file:

  • An existing target is never silently truncated. Two doors guard it: an advisory existence check — without --force, record exits 2 with refusing to overwrite existing cassette {path} — pass --force to replace — and, once that passes, an exclusive flock taken before the file is touched, so a second recorder racing for the same path refuses by name instead of clobbering it.
  • A --output ending in .gz is refused outright (exit 2), because the CLI records plain JSONL bytes only; gzip cassettes are the API's job (CompressedJsonlFormat, see Gzip compression).
  • The recorded child gets a controlling terminal by default so Ctrl+C reaches it (use --no-ctty to disable); the host termios is restored on every exit path including thrown exceptions.

The cassette can then be replayed via vendor/bin/candy-vcr replay … or loaded by tests through Player::play().

A finished replay prints one summary line to stderr — events streamed, output bytes and virtual time — so a silent terminal is never ambiguous about whether anything played; stdout keeps carrying only the recorded bytes, which is what makes candy-vcr replay x.cas | cmp - expected a valid test. render-tape likewise announces what it is rendering, and reports every 100 frames while it works, so a multi-minute render is not indistinguishable from a hang. Every verb responds to -h / --help with its own usage block on stdout and exit 0; --version / -V is handled before verb dispatch — it prints candy-vcr <version> on stdout and exits 0 (a dev stamp in any composer checkout or install — the honest composer-mode answer from Application::versionString(); only a PHAR build carries a release stamp from its manifest).

Localization

The CLI prose is translated into the fleet's 16 locales (ar cs de en es fr it ja ko nl pl pt pt-br ru tr zh-cn, lang/*.php, namespace vcr through SugarCraft\Vcr\Lang). bin/candy-vcr picks the locale from LC_ALL → LC_MESSAGES → LANG (T::setLocale(T::detect())); an unset, C/POSIX or unshipped locale gives English, byte-identical to what this README quotes. Translated: the usage and --help prose, per-verb summaries, Symfony option descriptions of render-tape/render-batch, diagnostics, and the success/summary lines. Deliberately not translated, because scripts and tests match them or they are data: flag spellings, the header.* / event[N] field labels in diff output, the t=… kind event rows and time<TAB>cursor<TAB>hash frame rows of inspect, the OK/FAIL status tokens, JSONL from --dry-run, and messages raised by the library layer below the CLI (cassette loading, the tape lexer/parser, the renderers). Placeholders are bound by name, so a translation may reorder them; LocaleParityTest pins key sets and placeholder names across all 16 files, and LangUsageTest fails on a Lang::t key missing from en.php, a dead en.php key, or a re-introduced candy-vcr <verb>: … literal in src/Cli/.

inspect shows each event's timestamp, kind, and a short payload summary (with --since=<seconds> / --until=<seconds> filters). replay streams the cassette's recorded output bytes to stdout — --speed=realtime honours the recorded cadence (use it for visual demos), --speed=instant (the default when the flag is omitted) flushes everything as fast as the kernel will accept it; the header's playbackSpeed multiplier scales rendered output (render-tape/render-batch), not live replay. diff compares headers + per-event payloads and exits non-zero on any difference — event timestamps compare with a 2 ms tolerance, and the _id/_enc migration-metadata keys are stripped from both sides before payload comparison so a migrated cassette diffs clean against its original; pass --strict to keep those keys in the comparison. stats prints event tallies by kind, total duration, input message type breakdown, and output byte counts with per-event averages.

Recording commands

vendor/bin/candy-vcr record -- vim /tmp/scratch
vendor/bin/candy-vcr record --output bash-session.cas --cols 132 --rows 40 -- bash -l
vendor/bin/candy-vcr record --no-ctty -- /bin/echo 'hello, world'   # non-interactive child, no Ctrl+C wiring
vendor/bin/candy-vcr record --shell                                  # spawn $SHELL -l (or /bin/sh -l)
vendor/bin/candy-vcr record --env -- bash -c 'echo hi'              # capture filtered host env into cassette header
vendor/bin/candy-vcr record --idle-trim 1.0 -- bash demo.sh         # compress idle gaps > 1s (asciinema-style trim)
vendor/bin/candy-vcr replay  --no-trim session.cas --speed=realtime # restore real cadence on a trimmed cassette

Comparable to asciinema rec, but writes the candy-vcr JSONL cassette so the existing inspect / replay / diff / stats commands and the Player::play() API work without conversion. record is a PTY feature like exec-mode rendering — it needs sugar-pty's master/slave layer, so it is POSIX-only at the pump (native Windows records through ConPTY, see below) — and the signal half of its TTY safety net needs pcntl: the handlers are installed only where pcntl_signal() and pcntl_async_signals() exist, and without them the net degrades to the in-band finally plus the shutdown function. --cols/--rows set the child PTY size when the recording starts (80×24 when omitted) and are written into the header; the recorder does not track SIGWINCH, so resizing your own terminal mid-recording leaves the program laid out for the size you started with — pick the geometry up front. --idle-trim and the host-termios safety net (register_shutdown_function + signal handlers) are covered under their own headings below.

Native Windows (PHP 8.4+ with FFI) records through ConPTY with its own polling loop instead of the POSIX pump. Keystrokes from a console are read as console input records in VT input mode, so arrows and Ctrl keys reach the child as the same bytes a POSIX terminal sends. A piped or redirected stdin is forwarded as-is. Host console resizes are forwarded and recorded, because Windows has no SIGWINCH. The child gets the Windows system variables it needs to start (SystemRoot, ComSpec, PATHEXT, …), and --ctty has no meaning there: the pseudo console delivers Ctrl+C itself.

--shell

Spawn the user's $SHELL -l (falling back to /bin/sh -l when $SHELL is empty or non-executable; on Windows the fallback is %ComSpec%, i.e. cmd.exe, which takes no -l) instead of an explicit positional command. Useful for "capture what my prompt does" demos without enumerating the shell binary every time. Mutually exclusive with positional <cmd>.

--env and --env-regex=PATTERN

Env capture is opt-in — --env snapshots the host environment into the cassette header. By default, keys matching the conservative secret-name regex /(PASS|SECRET|TOKEN|KEY|PASSWORD|API|CRED|AUTH|PRIV)/i are stripped before they hit disk (SSH_PASSPHRASE falls to the PASS arm). A second screen inspects the VALUE: any variable whose value embeds URL credentials (scheme://user:pass@host) is stripped too, so a clean-looking DATABASE_URL cannot smuggle a password under a benign name. The bias is "rather strip-too-much than leak" — KEYBOARD_LAYOUT is stripped because it contains KEY. Override the regex with --env-regex=PATTERN when you need a narrower (or wider) filter; passing --env-regex implies --env. An empty --env-regex= is rejected — it can no longer be used to silently disable filtering (that footgun previously recorded every secret).

--env-all (formerly --env-allow-secrets)

DANGEROUS — for trusted, isolated environments only. When this flag is set, secret-key filtering is disabled entirely and the cassette will contain the full host environment with credential values verbatim (API tokens, passwords, private keys, etc.). Because that is a footgun, capturing everything now requires this explicit flag, and every captured variable name is printed to stderr as a warning so you can see exactly what landed in the cassette. Only use it when recording in a fully isolated environment and you understand that the resulting cassette must never be shared or stored in an untrusted location. --env-allow-secrets remains as a legacy alias. The cassette file itself is created 0600 (owner read/write only) by Recorder::open() even under the default umask — but file permissions are hygiene, not confidentiality: an --env-all cassette still contains every credential in plaintext, so store it accordingly and delete it when done.

vendor/bin/candy-vcr record --env-all -- bash -c 'echo $GITHUB_TOKEN'
# GITHUB_TOKEN value is now in the cassette in plain text, and stderr prints:
# candy-vcr record: WARNING --env-all captured the full host environment WITHOUT secret filtering (N vars): ..., GITHUB_TOKEN, ...

Captured env lands on the cassette header as a JSON object:

{"v":1,"created":"...","cols":80,"rows":24,"runtime":"sugarcraft/candy-vcr@record","env":{"HOME":"/home/me","LANG":"en_US.UTF-8","PATH":"/usr/bin:/bin","TERM":"xterm-256color"}}

RecordCommand::filteredHostEnv(?string $regex = null, bool $captureAll = false): array<string,string> is the public helper invoked under the hood; tests can drive it directly without spawning a child. An empty/null $regex falls back to the default secret filter — the full env is captured only when $captureAll is true.

--idle-trim N and replay --no-trim

Borrowed from asciinema, idle-trim compresses long inter-event gaps so a 30-second make build doesn't take 30 seconds to replay. When the gap between consecutive events exceeds N seconds, the recorder writes the event with both t (the compressed timestamp) and tRaw (the original wall-clock timestamp). The compressed gap defaults to 0.5 s (or N, whichever is smaller). Flag grammar is per-verb: on replay, --idle-trim and --speed are the two dual-form value flags (both --flag=N and --flag N accepted) — --no-trim is a plain boolean and every other --flag spelling is reported as unknown option and exits 2. record --idle-trim and inspect --fps accept both forms too; inspect --since/--until are equals-form only, where a bare space form falls to the unknown option door.

{"v":1,"created":"...","cols":80,"rows":24,"runtime":"sugarcraft/candy-vcr@record"}
{"t":0,"k":"output","b":"pre\r\n"}
{"t":0.5,"k":"output","b":"post\r\n","tRaw":1.234}
{"t":0.515,"k":"quit","tRaw":1.249}

Replay defaults to the compressed timeline. Pass --no-trim to replay to honour tRaw instead — useful when the original cadence matters (demos, race-condition repros). Events without tRaw (older cassettes, or untrimmed events) replay using t, so the format stays backward-compatible. The Player::play(... useRawTimestamps: true) flag exposes the same behaviour to PHP callers.

Host TTY safety net

record puts the host stdin into raw mode while the recorded program runs. The in-band finally restores it on every PHP-controlled exit path (clean exit, exception). For exits that bypass finally — SIGTERM, SIGHUP, SIGINT, fatal errors — the command installs:

  • register_shutdown_function([RecordCommand::class, 'rescueRestore']) — fires on every PHP run shutdown, including fatal errors.
  • pcntl_signal(SIGTERM/SIGHUP/SIGINT, [RecordCommand::class, 'handleRescueSignal']) with pcntl_async_signals(true) — restores then re-raises the signal with the default handler so the process still dies with the right status.

SIGKILL cannot be intercepted by anything. As a mitigation, while recording is in flight the command drops a marker file at sys_get_temp_dir() . '/candy-vcr-rescue.' . getmypid() . '.' . bin2hex(random_bytes(8)) — the 16-hex suffix makes the name unguessable and collision-proof against a recycled PID, and it is created with fopen($path, 'xb') (O_CREAT|O_EXCL: a pre-existing path, including a symlink planted on a shared /tmp, is refused rather than followed). The file carries tty= (the host TTY's device path, resolved via posix_ttyname(STDIN)), pid= and started= lines. If a hard kill leaves your terminal stuck in raw mode, run stty sane < /path/to/your/tty (you'll find the path in the marker file, which is cleaned up on every clean exit).

The static handlers are signal-safe (no allocation, no logging) and idempotent; calling rescueRestore() twice in a row is a no-op.

Recording overhead

The PosixPump recorder tap is a single conditional recorder->recordOutput($bytes) call per master-read chunk — no extra syscalls on the hot path, no per-chunk serialization beyond appending a JSON line to the open cassette stream.

Benchmark (tests/Integration/ShirleyOverheadTest.php: one warmup iteration, then 6 timed interleaved iterations per scenario — two rounds of ROUNDS = 3 without/with pairs — reduced to a trimmed mean (min and max discarded, middle four averaged), time bash -c 'seq 100000'):

Scenario Trimmed-mean wallclock (illustrative single run)
Pump WITHOUT recorder ~47 ms
Pump WITH recorder ~40 ms
Measured overhead within noise

Figures are one trimmed-mean reading from a quiet dedicated host, printed to show the shape of the result — they are an illustrative single run, not a guarantee; on shared CI runners the without/with pair wanders by a few ms per direction, which is why the table's headline is a verdict ("within noise") and not a delta. The assertion budget below is what carries the signal.

The assertion budget is 8 % to absorb shared-runner jitter while still catching the regression class this test exists to flag (a real serialization-per-chunk regression would land at dozens of percent). The original performance survey's 2 % acceptance target is reported by the test but not asserted.

Hook system

Hooks intercept and transform events during recording, enabling sanitization, metadata injection, and custom logging:

use SugarCraft\Vcr\Recorder;
use SugarCraft\Vcr\Hook\SanitizingHook;
use SugarCraft\Vcr\Hook\MetadataHook;

$recorder = Recorder::open('/tmp/session.cas');

// Remove sensitive keys from all events
$recorder->withHook(new SanitizingHook(
    removeKeys: ['API_KEY', 'SECRET_TOKEN'],
));

// Add CI metadata to the first output event
$recorder->withHook(new MetadataHook([
    'CI_RUN_ID' => getenv('GITHUB_RUN_ID'),
    'test_name' => 'MyTest::testViewOutput',
]));

$program = new Program($model);
$program->setRecorder($recorder);
$program->run();

Available hooks:

  • SanitizingHook — removes keys or replaces patterns via regex
  • MetadataHook — injects metadata into the first output event
  • Custom hooks implement SugarCraft\Vcr\Hook\Hook (beforeSave($event): ?Event + afterCapture($event): void)

Hooks are managed by Hook\HookRegistry (addHook, beforeSave, afterCapture, count, clear). An afterCapture() hook that throws is recorded — never silently swallowed: Recorder::hookErrors() lists the failures, and the record command prints each one as a warning on stderr after the session.

Redaction is opt-in wiring. Nothing attaches a hook automatically: a record run stores exactly what the terminal sent, so scrubbing typed secrets is a call-site decision — attach SanitizingHook on the recorder yourself. The --env flags filter header environment names only, never event payload bytes (see Limitations). Recorder::withHook() appends to its private registry; returning null from beforeSave() drops the event entirely.

Matcher classes — replay-side flexibility

SugarCraft\Vcr\Matcher\EventMatcher controls when a replayed event "matches" the recorded one. Use cases: timing-tolerant replays (CI that drifts a few ms), content-only diffs (ignore wall-clock drift entirely).

Class Semantics
PassthroughMatcher Every event matches — equivalent to omitting matcher: entirely (Player::play() defaults it to null, which skips matcher filtering); pairs with ByteAssertion for the actual diff.
ContentMatcher Matches on (kind, payload); ignores t. Useful when replay timing isn't deterministic.
TimingTolerantMatcher Matches when |t_actual - t_recorded| ≤ timingTolerance. Construct with timingTolerance: (float seconds, default 0.1); negative values throw InvalidArgumentException.
use SugarCraft\Vcr\Matcher\TimingTolerantMatcher;
$matcher = new TimingTolerantMatcher(timingTolerance: 0.05);  // ±50 ms (default 0.1)
$matcher->matches($recordedEvent, $actualEvent);  // bool

Custom matchers implement EventMatcher::matches(Event $recorded, Event $actual): bool.

Rendering .tape files to GIF

The render-tape and render-batch commands convert .tape files to animated GIFs. They use the TapeToGif pipeline: Lexer → Parser → Compiler → Player → Terminal → Renderer → FrameStream → FrameDedup → Rasterizer → GifEncoder. .tape is the only renderable input — a recorded cassette cannot be exported to GIF, and no command seeks or window-crops a tape (see Limitations).

⚠ Security — a .tape file is a program. The Set Shell directive, --shell=<sh>, or --exec put the renderer into exec mode: every typed keystroke is written to a real PTY-hosted shell and executed. Rendering a third-party tape is therefore arbitrary code execution on your machine — treat untrusted .tape files the way you would treat an unfamiliar Makefile or package.json and review them before rendering. See Exec mode below.

# Try it now — render the smoke tape this repo ships (from the candy-vcr/ directory)
vendor/bin/candy-vcr render-tape .vhs/smoke.tape

# Render a single .tape file
vendor/bin/candy-vcr render-tape demo.tape

# Custom output path
vendor/bin/candy-vcr render-tape .vhs/smoke.tape -o output.gif

# Specify theme and fps
vendor/bin/candy-vcr render-tape demo.tape --theme Dracula --fps 20

# Use imagick backend instead of gd
vendor/bin/candy-vcr render-tape demo.tape --backend imagick

# Use pure-PHP encoder (fallback when ffmpeg unavailable)
vendor/bin/candy-vcr render-tape demo.tape --encoder php

# Strict mode — fail on unknown directives
vendor/bin/candy-vcr render-tape demo.tape --strict

# Exec mode — actually RUN the typed commands and capture the program's
# output into the GIF (real vhs-style program demos, not just keystrokes).
# Opt in via `Set Shell "bash"` inside the tape, or on the CLI:
vendor/bin/candy-vcr render-tape demo.tape --shell sh
vendor/bin/candy-vcr render-tape demo.tape --exec        # default shell ($SHELL/sh)

# Batch render all .tape files in a directory
vendor/bin/candy-vcr render-batch demos/

# Batch render recursively
vendor/bin/candy-vcr render-batch demos/ --recursive

# Custom output directory for batch
vendor/bin/candy-vcr render-batch demos/ -o output-gifs/

render-tape options

Option Short Description
--output -o Output .gif path (default: same as input with .gif extension)
--font -f TTF font family name (default: JetBrainsMono)
--theme -t Theme name (default: TokyoNight). Options: TokyoNight, TokyoNightLight, TokyoNightStorm, Dracula, SolarizedDark
--fps Frames per second (default: 30)
--backend -b Rasterizer backend: gd (default) or imagick
--encoder -e GIF encoder: ffmpeg (default) or php
--strict Error on unknown directives instead of skipping
--shell Execute the typed commands in this shell under a real PTY and capture the program's output (exec mode). Overrides the tape's Set Shell.
--exec Enable exec mode with a default shell ($SHELL or /bin/sh) when the tape sets no Set Shell
--dry-run Print the compiled event stream as JSONL to stdout; no GIF is written

Exec mode — rendering program output (Set Shell)

By default render-tape rasterizes the keystrokes a tape types — it never runs them, so it cannot render a demo of a program's output. Exec mode changes that: the tape's Type/Enter/Ctrl+… input is written to a real PTY-hosted shell, and the program's output is captured back into the frames on the tape clock (a Sleep Ns after Enter becomes the real read window during which output streams in) — the same model the .tape format prescribes. This makes candy-vcr a drop-in renderer for program-output demos.

Timing caveat: that read window is derived from tape-clock deltas divided by Set PlaybackSpeed, so a 2× render halves the real seconds the live shell gets to answer each command, and a command at the very end of the tape drains for a single frame interval. Keep speed at 1 (or pad the final Sleep) for output-heavy exec tapes — see Limitations.

Enable it three ways, in precedence order: the CLI --shell=<sh> (operator override) → the tape's own Set Shell "<sh>" directive → --exec (default shell). Absence of all three keeps the byte-identical echo path — tapes with no shell render exactly as before. A tape's shell name is validated against upstream vhs's nine-name set (bash, zsh, fish, powershell, pwsh, cmd, nu, osh, xonsh — plain sh is not one of them, upstream included); an unknown name is refused at the compile door — a warning and the tape stays on the echo path, or a hard error under --strict. The CLI --shell flag is your own invocation and skips the roster.

Set Shell "bash"
Type "php examples/spinner.php"
Enter
Sleep 3s

Exec mode needs a working PTY layer (ext-ffi + a readable/writable /dev/ptmx on POSIX; PHP 8.4+ FFI for ConPTY on Windows, where a bare Set Shell name is found through PATH/PATHEXT and cmd.exe is the fallback). When a shell is requested but the PTY layer is unavailable, the render logs a warning and transparently falls back to echo mode instead of failing — so FFI-less hosts still render shell-less tapes. The spawned shell is interactive (-i) but not a login shell, so renders stay reproducible (no host-specific profile/MOTD noise).

--dry-run runs Lexer → Parser → Compiler but skips the Renderer → Rasterizer → Encoder. The first stdout line is the compiled header tagged with "_header"; subsequent lines are one event per line as {"t":…, "kind":…, "payload":…}. Useful for diffing two tape files' event streams or inspecting what Type "..." compiles into without spending the GIF render cost. The -o flag (if also passed) is ignored in dry-run mode.

vendor/bin/candy-vcr render-tape demo.tape --dry-run | head -5

inspect --frames

inspect <cassette|.tape> --frames walks the cassette through a Renderer and Terminal at the configured fps (default 30; set it with --fps=<n> or the space form --fps <n> — both spellings are accepted, validated once, and a non-positive or non-numeric value exits 2), printing one line per snapshot:

time<TAB>cursor_row,cursor_col<TAB>grid_sha1

grid_sha1 is a deterministic digest of every (row, col, char, fg, bg, attrs, fgTruecolor, bgTruecolor, rendition) cell tuple plus the cursor state. Two snapshots that would rasterize to identical pixels share the same hash. The footer reports frames: <total> unique: <n> deduped: <n>, where uniqueness is decided by consecutive Snapshot::equals() comparison — the same rule FrameDedup applies on the render path — handy for sizing the GIF-encoding job before committing to a full render.

vendor/bin/candy-vcr inspect demo.tape --frames --fps 60

render-batch options

render-batch <dir> takes its own option set — the render flags below, but no --shell, --exec or --dry-run (those are single-tape only: a batch never spawns a shell, and dry-run has no meaning across a directory).

Option Short Description
--output-dir -o Output directory for .gif files (default: same as source dir)
--font -f TTF font family name (default: JetBrainsMono)
--theme -t Theme name (default: TokyoNight)
--backend -b Rasterizer backend `gd
--encoder -e GIF encoder `ffmpeg
--fps Frames per second (default: 30)
--recursive -r Search recursively for .tape files
--strict Error on unknown directives instead of skipping

GIF encoding pipeline

The TapeToGif class wires together the full render pipeline:

  1. Parsing — Lexer tokenizes the .tape source, Parser produces an AST
  2. Compilation — Compiler converts the AST into a Cassette with timed events
  3. Rendering — Player drives the cassette events into a Terminal, Renderer produces frames via FrameStream
  4. Deduplication — FrameDedup collapses visually identical adjacent frames
  5. Rasterization — Rasterizer converts each Snapshot to a PNG using glyph tiles
  6. Encoding — FfmpegGifEncoder produces the final GIF (or PhpGifEncoder as fallback)

Frame hold durations are tracked through the dedup stage and passed to the encoder for accurate VFR (variable frame rate) timing.

Cassette migration

Cassette format versions evolve over time. The migrate command upgrades cassettes automatically: migrate reads and writes plain JSONL only — YAML, tape and gzip inputs are refused by name rather than fed to the JSON parser, and an output path ending in .gz is rejected too; for a .cas.gz cassette the workflow is gunzip, migrate, re-gzip.

# Migrate in-place (creates session.cas.bak backup)
vendor/bin/candy-vcr migrate session.cas

# Migrate to a new file
vendor/bin/candy-vcr migrate session.cas upgraded.cas

# Replace an existing output file (it is refused without --force)
vendor/bin/candy-vcr migrate session.cas upgraded.cas --force

# Dry-run — validate without writing
vendor/bin/candy-vcr migrate session.cas --dry-run

# Show registered migrators
vendor/bin/candy-vcr migrate --info

The migration system is pluggable via SugarCraft\Vcr\Migration\CassetteMigrator. V1ToV2Migrator upgrades v1 cassettes by adding sequential event IDs, explicit encoding metadata on output events, and other structural improvements. Future version migrators slot in without modifying the core infrastructure.

Tape compiler

candy-vcr ships a SugarCraft\Vcr\Tape layer that parses .tape files (the VHS DSL) into a Cassette that the existing Player can replay. This decouples the render pipeline from the tape format.

use SugarCraft\Vcr\Tape\Compiler;

$source = file_get_contents('demo.tape');
$result = Compiler::parseSource($source);

if (!empty($result['errors'])) {
    foreach ($result['errors'] as $error) {
        echo $error->getLine(), ': ', $error->getMessage(), "\n";
    }
    exit(1);
}

$cassette = (new Compiler())->compile($result['ast'], 'demo.tape');
// Feed to Player::play() for replay...

Supported directives:

Directive Supported Notes
Type "..." ✅ Each char emits an Input event at TypingSpeed cadence. UTF-8 string literals preserved byte-for-byte.
Enter ✅ Raw byte \r.
Tab ✅ Raw byte \t.
Backspace ✅ Raw byte \x7f.
Space ✅ Raw byte ' '.
Escape ✅ Raw byte \x1b.
Up / Down / Left / Right ✅ CSI cursor: \x1b[A / [B / [D / [C.
Ctrl+<letter> ✅ Control character via ord($letter) & 0x1F; round-trips as upper-case Ctrl+C.
Sleep <duration> ✅ Advances virtual clock only; suffixes ms/s/m accepted.
Set <key> <value> ✅ Key allowlist below.
Env KEY "value" ✅ Adds to cassette header env map.
Output <path> ✅ Accepted (stored on the OutputDirective AST node for the render step; not encoded as a Cassette event).
Hide, Show ✅ Suppresses/resumes cursor rendering in output GIF from this point.
Wait <duration> ✅ Advances the virtual clock (like Sleep); emits no output event.
Wait /pattern/ ⚠️ CONDITION wait — upstream blocks until output matches; the record-side compiler has no live stream to poll, so it emits no event, advances no clock, and reports the mismatch through the compiler's problem channel — a warning by default, a hard error under --strict.
Screenshot <path> ✅ Captures current frame to PNG path during render.
Source <path> ✅ Inlines and compiles another .tape file at this point.
Key <name> ✅ Named-key byte roster (finding 005); a name outside the roster is reported through the problem channel.
Modifier <key> ✅ Latches Alt (or Shift) so the following key event carries it.
Copy "text" ✅ Emits an OSC 52 clipboard-set sequence (ESC ]52;c;<base64> BEL) — the bytes upstream's clipboard copy produces, on the wire.
Paste ⚠️ Needs a clipboard to read from; the record-side compiler emits no bytes — reported through the problem channel (warning, hard error under --strict).
Require <module> ⚠️ Upstream's precondition loader; candy-vcr emits no bytes for it — reported the same way.
Screen <arg> — Candy-only keyword with no upstream counterpart: it lexes (so it never falls to UNKNOWN's door) and the Parser discards it — accepted and ignored, not ported.

Upstream delta. Upstream-legal tapes cannot fail silently. The twelve upstream command keywords the original port never lexed (Key / Modifier / Copy / Paste / Require family arms) carry dedicated lexer arms; the 60-name keyword roster is pinned by KeywordRosterParityTest against candy-code's VhsTapeContractTest, and any unclassifiable line becomes a ParseError — a warning without --strict, an abort with it. What remains accepted-but-inert is exactly the Paste / Require pair above (no clipboard to read, no module loader during a compile-only pass) and the candy-only Screen keyword.

The Set directive's key parameter is validated against an allowlist; unknown keys raise a ParseError:

Set key Effect
Theme Theme name (TokyoNight, TokyoNightLight, TokyoNightStorm, Dracula, SolarizedDark). Stored on CassetteHeader::$theme.
FontSize Default rasterizer font size in pixels (tape-path default: Compiler::DEFAULT_FONT_SIZE = 22; the standalone GdRasterizer constructor default is 14).
Width / Height Output IMAGE size in PIXELS (VHS semantics; defaults 1200 / 600). Stored on CassetteHeader::$widthPx / $heightPx; the terminal cols / rows are DERIVED from these via the font cell size.
TypingSpeed Inter-character delay for Type runs. Accepts <n>ms / <n>s / <n>m.
FontFamily TTF family name (resolved by FontLoader).
Padding / Margin Reserved for the rasterizer; accepted but not yet enforced.
PlaybackSpeed Speed multiplier (e.g. 2.0 = 2x speed, 0.5 = half speed). Applied in FrameStream during rendering.
Shell Opt into exec mode: run the typed commands in this shell under a real PTY and capture the program output into the frames (see Exec mode). Surfaced via Compiler::shell(); absence keeps the byte-identical echo path.
// AST nodes (under SugarCraft\Vcr\Tape\Ast):
// TypeDirective · EnterDirective · TabDirective · BackspaceDirective ·
// SpaceDirective · EscapeDirective · ArrowDirective · CtrlDirective ·
// SleepDirective · SetDirective · EnvDirective · OutputDirective ·
// HideDirective · ShowDirective · WaitDirective · ScreenshotDirective ·
// SourceDirective · ParseError

The Compiler::compile() method produces a Cassette with a CassetteHeader carrying the configured cols/rows/theme/env and a list of Event objects typed as EventKind::Input with raw bytes (['b' => string]) payloads. Sleep directives advance the virtual clock without emitting events, so inter-event timing is preserved for the Player.

Corpus coverage: Every .tape file in the monorepo parses without error and compiles to a valid Cassette (verified by TapeCorpusTest, which walks the tree for .tape files rather than a pinned count).

Decompiler — Cassette → tape source

SugarCraft\Vcr\Tape\Decompiler is the reverse of the Compiler: it walks a Cassette's events back into tape source text, serving as the round-trip safety net for the Tape compiler (parse → compile → decompile → re-parse should be stable for canonical inputs).

use SugarCraft\Vcr\Tape\Compiler;
use SugarCraft\Vcr\Tape\Decompiler;

$result = Compiler::parseSource(file_get_contents('demo.tape'));
$cassette = (new Compiler())->compile($result['ast'], 'demo.tape');

$source = (new Decompiler())->decompile($cassette);
file_put_contents('demo-roundtripped.tape', $source);

Heuristics:

  • Sleep threshold — gaps over 100ms between adjacent Input events emit an explicit Sleep <n>ms directive. Smaller gaps are absorbed as the implicit TypingSpeed cadence between Type chars.
  • Space heuristic — a lone space byte sandwiched between printable bytes folds into the current Type "..." group; a solitary space gets its own Space line.
  • Type grouping — runs of printable input bytes merge into one Type "..." line and break on any control byte, non-input event, or Sleep-worthy gap.

Limitations:

  • Hide and Show directives emit events into the Cassette but the Decompiler does not yet reconstruct them on round-trip (v2).
  • Wait is parsed but emits no events (deferred to v2).
  • Screenshot and Output are render-side only and leave no Cassette trace.
  • Non-printable single bytes that don't map to a known directive become # unprintable byte 0x.. dropped comments — they can't be expressed in tape source.
  • Ctrl+letter is reconstructed from raw control bytes 1..26, normalised to upper-case (so Ctrl+c in source round-trips as Ctrl+C).

tests/Tape/RoundTripTest.php covers Type "hello", Enter, Sleep, Set Theme, Ctrl+C, all four arrows, Backspace, Tab, Escape, Env, plus a combined multi-directive tape. For each: Lexer → Parser → Compiler → Cassette → Decompiler → Lexer → Parser → Compiler → Cassette2 and asserts the two event streams match timestamp-for-timestamp.

Frame renderer

candy-vcr ships a SugarCraft\Vcr\Render layer that converts a compiled Cassette into a stream of terminal Snapshot frames at configurable fps, with optional deduplication of identical adjacent frames:

use SugarCraft\Vcr\Player;
use SugarCraft\Vcr\Render\Renderer;
use SugarCraft\Vcr\Render\FrameDedup;
use SugarCraft\Vterm\Terminal;

// Open a cassette (from tape compiler or direct record)
$player = Player::open('demo.cas');

// Create terminal emulator and renderer
$terminal = Terminal::new(80, 24);
$renderer = new Renderer();

// Get frame stream and optionally dedup identical frames
$stream = $renderer->render($player, $terminal, 30.0);
$deduped = FrameDedup::dedup($stream);

foreach ($deduped as $index => $snapshot) {
    // $snapshot is a SugarCraft\Vterm\Snapshot with grid + cursor + time
    printf("Frame %d at t=%.3f\n", $index, $snapshot->time);
}

Key classes:

Class Role
Renderer Orchestrates Player + Terminal; produces FrameStream
FrameStream \IteratorAggregate yielding Snapshot at fps cadence
FrameDedup Static filter collapsing identical adjacent frames

Frame dedup: Typical terminal recordings have 80–95% identical frames (e.g., cursor blink, idle time between keystrokes). FrameDedup::dedup() collapses consecutive identical frames into a single frame, reducing downstream GIF encoder work significantly. The holdMax parameter (default 300) caps how many identical frames can be collapsed to prevent pathological cases.

Snapshot equality: Two Snapshot objects are equal when their grid and cursor state match, regardless of capture time. This enables frame dedup across different virtual timestamps. The equalsWithTime() method compares all three fields (grid, cursor, time) for exact reproducibility checks.

Performance note: Cell equality comparison is O(cols × rows) per frame — for a typical 80×24 terminal that's 1920 cell comparisons. At 30fps with dedup disabled, that's ~57,600 cell comparisons per second. This is acceptable for typical frame grids; cell-comparison cost is the known optimization target.

Frame rasterizer

The SugarCraft\Vcr\Raster namespace converts terminal Snapshot frames into PNG images for GIF encoding:

use SugarCraft\Vcr\Raster\GdRasterizer;
use SugarCraft\Vcr\Raster\FontLoader;

$rasterizer = new GdRasterizer(fontSize: 14, fontFamily: 'DejaVuSansMono');

$image = $rasterizer->rasterize($snapshot, cellW: 8, cellH: 28); // \GdImage

imagepng($image, 'frame.png');
imagedestroy($image);

Cell metrics. Compiler::cellMetrics() derives the cell box from the font size: cellW = floor(fontSize * 0.6), cellH = fontSize * 2 (both clamped to ≥ 1).

  FontSize 22 → cellW = 13px, cellH = 44px
  80×24 terminal → 1040×1056 px
  120×40 terminal → 1560×1760 px
  1200×600 px canvas fits a 92×13 terminal

Architecture:

Class Role
FontLoader Resolves TTF font paths from fonts/ bundle + system dirs
Glyphs Per-(char, fg, bg, bold, italic, underline, ±truecolor override) tile cache — the performance key
Rasterizer Interface: rasterize(Snapshot, cellW, cellH, ?FontLoader): GdImage|Imagick
GdRasterizer Default ext-gd backend; blits tiles + renders cursor
ImagickRasterizer ext-imagick alternative; better anti-aliasing

Bundled fonts: fonts/JetBrainsMono-{Regular,Bold,Italic,BoldItalic}.ttf (default family) plus DejaVuSansMono.ttf and DejaVuSansMono-Bold.ttf as a fallback. FontLoader tries the fonts/ dir first, then system font directories (/usr/share/fonts/, ~/.fonts/, etc.). See the Fonts section under Development for licensing and override details.

Glyphs cache: Typical terminal frames have thousands of cells but only ~50 unique (char, attrs) combinations. The tile cache makes rasterization O(unique tiles) instead of O(cells). Cache key: "$char|$fg|$bg|$bold|$italic|$underline", plus a |tc<fgRgb>,<bgRgb> tail whenever either ?int truecolor override is supplied to tile()/tileWide() — a truecolor cell can never reuse a palette-keyed tile, while pure-palette cells keep keys byte-identical to the pre-truecolor cache.

Wide chars: CJK and fullwidth characters get a 2×-wide tile; the rasterizer advances 2 columns after blitting. The grid is the oracle: a head cell is wide exactly when its right neighbour carries Cell::continuation(), and a continuation cell paints nothing (it advances one column, covered by its head's tile). The former mb_strwidth($char) > 1 width-table oracle is retired — it drifted from the emulator in both directions (Glyphs::measure()'s font-metrics helper is a separate surface, not the paint path).

Cursor shapes:

  • Block (shape=1): glyph rendered in reverse-video (fg/bg swapped)
  • Underline (shape=2): filled rect at y = cellH × 0.75
  • Bar (shape=3): narrow filled rect at left edge

FontLoader API. new FontLoader($fontDirs = []) resolves TTF paths. load($family, $size, $style = 'regular') returns the resolved path (throws if missing); resolve($family, $style) returns ?string; lastResolvedPath() returns the most recent hit. Search order: bundled candy-vcr/fonts/ → $fontDirs overrides → /usr/share/fonts/truetype/ → /usr/share/fonts/opentype/ → /usr/share/fonts/X11/Type1/ → /usr/share/fonts/X11/TTF/ → /usr/local/share/fonts/ → ~/.fonts/ → ~/.local/share/fonts/.

Glyphs API. new Glyphs($cellW, $cellH, $fonts, $fontFamily = 'JetBrainsMono', $fontSize = 14, $theme = null) ($fonts is a FontLoader) builds a per-(char, fg, bg, attrs) tile cache. Accessors: cellWidth(), cellHeight(), fontFamily(), fontSize(), theme(), cacheStats(): array{hits: int, misses: int, evictions: int}, tile($char, $fg, $bg, $bold, $italic, $underline, ?int $fgRgb = null, ?int $bgRgb = null): GdImage ($fgRgb/$bgRgb are exact 24-bit 0xRRGGBB truecolor overrides), tileWide(...) (same tail, 2× width for CJK / fullwidth), measure($char): array{cellW, cellH}. The instance is hoisted onto the rasterizer as a property so the cache survives across every snapshot in one tape render — a (cellW, cellH, fontFamily, fontSize, theme) fingerprint invalidates and rebuilds when any of those change. There is no public DEFAULT_FONT_FAMILY constant: JetBrainsMono is the constructor default on both Glyphs and GdRasterizer (whose DEFAULT_FONT_FAMILY is private).

GIF encoder

The SugarCraft\Vcr\Encode namespace converts a stream of rasterized PNG frames into an animated GIF:

use SugarCraft\Vcr\Encode\FfmpegGifEncoder;
use SugarCraft\Vcr\Encode\TapeToGif;

$tapeToGif = TapeToGif::new(['encoder' => 'ffmpeg']);
$tapeToGif->render('demo.tape', 'demo.gif');

Pipeline: .tape → Lexer → Parser → Compiler → Cassette → Player → Terminal → Renderer → FrameStream → FrameDedup → Rasterizer → FfmpegGifEncoder → .gif

Encoders:

Encoder Description
FfmpegGifEncoder Default; uses ffmpeg with two-pass palette generation. CFR via -framerate; VFR via a concat demuxer list file passed as -i (no shell process substitution).
PhpGifEncoder Pure-PHP fallback: rasterizes frames with GD and hand-assembles the animated GIF byte stream (header, NETSCAPE looping extension, per-frame LZW) in PHP. Roughly 5–10× slower than ffmpeg, but requires no external binaries.

TapeToGif options:

$tapeToGif->render($tapePath, $outputPath, [
    'fps'       => 30.0,        // frames per second
    'theme'    => 'TokyoNight', // theme name
    'fontSize'  => 14,           // terminal font size in pixels
    'fontFamily' => 'JetBrainsMono', // TTF font family name
    'backend'  => 'gd',        // 'gd' (default) or 'imagick'
    'encoder'  => 'ffmpeg',   // 'ffmpeg' (default) or 'php'
]);

VFR (Variable Frame Rate): When frameHolds differ between frames, FfmpegGifEncoder writes a concat demuxer list to concat.txt in its temp dir and passes that file as ffmpeg's -i input (nothing is piped on stdin):

file 'frame00000.png'
duration 0.033
file 'frame00001.png'
duration 0.100
...
file 'frame00004.png'
duration 0.033
file 'frame00004.png'

The last frame is listed twice to give it a display duration (the entry before it carries the duration). This produces accurate per-frame timing without re-encoding artifacts.

Two-pass palette: palettegen=stats_mode=diff computes an optimal 256-color palette by analysing frame-to-frame pixel differences. paletteuse=dither=bayer:bayer_scale=5 applies the palette with ordered dithering. This produces significantly better quality than single-pass GIF encoding.

Requirements: ffmpeg must be in $PATH for FfmpegGifEncoder. The symfony/process package is required as a runtime dependency.

Limitations

Honest capability boundaries, each with what closing it would take:

  • Reading loads the whole tape. The plain-JSONL write side streams (the Recorder appends event lines with coalesced flush doors), but every read() path materializes the cassette fully before the first event is returned — raw string, per-line array, Event list, and the Cassette copy stack, so peak RSS is a small multiple of the file size and a multi-gigabyte cassette runs out of memory before validation even starts. Closing it needs lazy, generator-based readers that the Player and CLI consume without re-buffering.
  • No seek or windowed export. Replay and render always run a cassette from t=0; inspect --since/--until can view a slice but nothing writes a trimmed cassette back out, so cutting a demo out of a long recording means hand-editing JSONL. Closing it needs a time-window filter that rewrites a slice with rebased timestamps through the format writers.
  • A recording can't become a shareable clip. render-tape accepts only hand-authored .tape DSL files, and the Asciinema importer has no writer, so there is no cassette → GIF path today. Closing it needs a cassette → tape translation (or a direct cassette renderer) feeding the same TapeToGif pipeline.
  • Exec-mode timing scales with playback speed. The live shell's read window per command is tape-clock deltas divided by Set PlaybackSpeed, so 2× playback halves every command's real time and the final command drains for one frame interval. Closing it needs speed-independent command holds scaled after the fact (VFR-style), not a shrunken window.
  • Secrets stay raw unless you redact. Cassettes store the exact keystrokes typed; SanitizingHook exists but is wired to nothing on the record path, and the record --env machinery filters environment names only. Closing it needs a decision on which default redaction set ships enabled, then wiring into the CLI record path.
  • Upstream's operational modes are not ported. charmbracelet/vhs's record/replay modes (RecordOnly / ReplayOnly / Passthrough) are deliberately absent — the Recorder/Player API split subsumes them. The concepts that carry state across that split — hooks, matchers and redaction filters — did port (SanitizingHook, the Matcher\ classes); the mode-flag surface did not.

Examples

examples/record.php and examples/replay.php are runnable scripts built on a tiny CounterModel; examples/inspect.php is a plain cassette reader that runs no model. The examples/cassettes/counter.cas fixture is a real recording you can play with:

bin/candy-vcr inspect examples/cassettes/counter.cas
bin/candy-vcr stats   examples/cassettes/counter.cas
bin/candy-vcr replay  examples/cassettes/counter.cas --speed=realtime
php examples/replay.php examples/cassettes/counter.cas

To record your own run, point record.php at a scratch path — it opens its target through Recorder::open, which locks the file and replaces an existing unlocked one, so never let it write over the tracked fixture (with no argument it defaults to examples/cassettes/recorded.cas):

php examples/record.php /tmp/session.cas
bin/candy-vcr inspect /tmp/session.cas
bin/candy-vcr replay  /tmp/session.cas --speed=realtime

Note that examples/replay.php judges whatever cassette it is given against an 80×24 ScreenAssertion (replay.php:69) — replaying a freshly recorded live run diffs the counter's expected frames against your terminal's, which will not match unless you recorded the same 80×24 session.

Replay

use SugarCraft\Vcr\Player;
use SugarCraft\Vcr\Assert\ByteAssertion;

$player = Player::open('/tmp/session.cas');
$result = $player->play(
    programFactory: fn ($input, $output, $loop) => new Program(
        new MyModel(),
        new ProgramOptions(
            useAltScreen: false, catchInterrupts: false, hideCursor: false,
            input: $input, output: $output, loop: $loop,
        ),
    ),
    assertion: new ByteAssertion(),
    speed: Player::SPEED_INSTANT,  // or SPEED_REALTIME for demo replay
);

if (!$result->ok) {
    echo $result->diffSummary();
    exit(1);
}

Player::play walks the cassette and feeds each event into the program: resize → WindowSizeMsg, input bytes → re-parsed via InputReader and dispatched, input msg envelope → decoded via the serializer registry, quit → program->quit(). Output events accumulate into the expected byte buffer; the program's actual output stream is captured and compared via the supplied assertion.

Replay is verbatim, not sanitized. A cassette never executes a program, but the bytes it carries are written to the replay terminal as recorded — OSC 8 hyperlinks, OSC 52 clipboard writes, window-title sequences and the private-use image markers all reach your emulator. Replaying a third-party cassette is therefore like opening a third-party web page: harmless-looking data whose display you are trusting. Cassettes are also faithful: an input event stores the raw keystrokes you typed, so secrets entered during a recording are in the file whether or not --env captured them.

Replay is environment-blind. Playback honours the header's cols/rows and its own theme, not your terminal: it does not read NO_COLOR, does not degrade for TERM=dumb, and does not follow a window resize mid-replay. Byte assertions against a captured output stream are unaffected; watching a replay on a differently sized terminal is cosmetic drift, not corruption.

Idle time trimming: In SPEED_REALTIME mode, long pauses between events can slow down CI tests. Set idleThresholdSeconds: 0.5 (or withIdleTrim(0.5) on the Player) to clamp pauses longer than 500 ms to 500 ms, making tests run faster while still honoring shorter pauses. The fluent withIdleTrim() form is useful when the threshold is configured once at the call site:

$result = $player->withIdleTrim(0.5)->play(
    programFactory: $factory,
    speed: Player::SPEED_REALTIME,
);
// Or pass it explicitly to play():
$result = $player->play(
    programFactory: $factory,
    speed: Player::SPEED_REALTIME,
    idleThresholdSeconds: 0.5,  // Skip long pauses in CI
);

Mouse replay encodings (DEC 1000–1016)

Mouse reporting is not one protocol: the bytes a terminal sends for the same click depend on which DEC private modes the program had enabled at record time, and only the SGR form is self-identifying. The Player therefore feeds every recorded output chunk through Input\MouseModeTracker (a sugar-ansi-parser Parser handler that records CSI ? h/l for the mouse modes), and the raw-input path runs Input\MouseReplayDecoder before falling back to InputReader, so a byte sequence is decoded in the mode that produced it instead of being assumed to be SGR:

Mode Encoding Replay behaviour
1000 / 1002 / 1003 X10 ESC [ M + 3 raw bytes (coord = byte − 32) decoded when any is on and 1005 is off
1005 X10 lead, UTF-8-encoded coordinates decoded when on
1006 SGR CSI < b ; x ; y M/m self-identifying — handled by InputReader exactly as before
1015 urxvt CSI b ; x ; y M decoded only while 1015 is on (shape alone is ambiguous)
1016 SGR + pixel coordinates (…; x ; y ; z) dropped, by design — see Known limits

Known limits

  • 1016 pixel reports are dropped. MouseMsg carries 1-based cell coordinates and has no pixel fields, so a faithful decode is impossible; discarding them (the pre-existing behaviour) beats inventing a cell mapping the program never asked for.
  • A legacy mouse payload must be exactly one sequence. Multi-mode DECSET/DECRST (CSI ? 1000 ; 1006 h) is tracked per mode, but a recorded input chunk that coalesces an X10/1015 event with other bytes falls through to InputReader unchanged — same as before, no mis-decode.
  • Mode state follows output order. If a cassette enables mouse reporting only via bytes the tracker never saw (e.g. replaying with the Output branch filtered out by a custom EventMatcher), legacy sequences stay gated off and defer to the fallback, never guessed.

Engine parity tests

ScreenAssertion grids come from sugar-vterm's full emulator (SugarCraft\Vterm\Terminal\Terminal), while Render\Renderer frames ride the renderer-path class (SugarCraft\Vterm\Terminal). tests/VtParityTest.php feeds curated + seeded-random escape streams through both engines and asserts identical normalised cell grids, so the two candy-vcr surfaces cannot drift silently. The renderer-path parity pass (deferred DECAWM wrap, absolute CUP clamping, IL/DL cursor homing, correct DECTCEM, 4;3 vs 4:3 via Parser::subparams(), SGR 29/58/59 + triplet consumption) and sugar-vterm's PR #1417 emulator fixes graduated the former divergences into parity assertions. What remains catalogued are representation/adapter limits — truecolor VALUES (the renderer Cell has no RGB slot), the stored underline colour, emulator ED/EL erasing with the active background (BCE), renderer-only REP, and the explicit CSI 0 L/M count no-op that sugar-ansi-parser's HandlerAdapter clamps to 1 before the renderer sees it — each pinned as an explicit tripwire case with a fix pointer rather than left to surface as a mystery assertion failure.

Assertion classes

ByteAssertion is the strict baseline — exact byte equality with a hex-and-printable diff window on failure. ScreenAssertion (cell-grid equality via sugar-vterm) is the recommended choice for round-trip tests:

use SugarCraft\Vcr\Assert\ScreenAssertion;

$result = $player->play(
    programFactory: $factory,
    assertion: new ScreenAssertion(cols: 80, rows: 24),
);

It feeds both expected and actual byte streams into separate SugarCraft\Vterm\Terminal\Terminal instances and compares the resulting cell grids. ANSI-level reorderings — redundant SGR re-emission, equivalent cursor moves, partial vs full repaints — collapse to the same grapheme grid, so a recording → replay round trip passes even when the byte streams differ. Failure messages list the first 5 differing cells with (row,col) coordinates and the expected vs actual graphemes.

ContainsAssertion provides flexible partial matching — it passes when the expected substring is found anywhere within the actual output:

use SugarCraft\Vcr\Assert\ContainsAssertion;

$result = $player->play(
    programFactory: $factory,
    assertion: new ContainsAssertion(),
);
// Passes if actual output contains "Ready." anywhere
// even if the full byte stream differs from expected
$this->assertTrue($result->ok);

This is useful when you only care about specific content appearing in the output (e.g. a status message, prompt, or error keyword) without requiring exact formatting. The comparison is case-sensitive; empty substring always matches.

RegexAssertion accepts a PCRE pattern (with delimiters) and supports multiline / case-insensitive / dot-all flags on the constructor:

use SugarCraft\Vcr\Assert\RegexAssertion;

$result = $player->play(
    programFactory: $factory,
    assertion: new RegexAssertion(
        pattern: '/Ready in \\d+ms\\./',
        multiline: true,
        caseInsensitive: false,
        dotAll: false,
    ),
);

Invalid PCRE patterns throw \InvalidArgumentException at construction.

Assertion class summary:

Class Use when
ByteAssertion Strict byte-equality; the safest baseline.
ScreenAssertion Cell-grid equality through sugar-vterm; collapses ANSI re-orderings. Default for round-trip tests.
ContainsAssertion Substring check; expected must appear anywhere in actual.
RegexAssertion PCRE regex match; supports multiline / caseInsensitive / dotAll.
Assertion (interface) compare(string $expected, string $actual): array{ok: bool, diff: string} — implement for custom assertions.

Msg serializers

SugarCraft\Vcr\Msg\Registry::new() is preloaded with:

  • BuiltinSerializer — covers 17 Msgs: KeyMsg, MouseClickMsg / MotionMsg / WheelMsg / ReleaseMsg, WindowSizeMsg, FocusGainedMsg / FocusLostMsg / BlurMsg, FocusInMsg / FocusOutMsg, PasteStartMsg, PasteEndMsg, PasteMsg, BackgroundColorMsg, ForegroundColorMsg, CursorPositionMsg. Tag is the unqualified class name.
  • JsonableSerializer — catch-all for any Msg implementing \JsonSerializable. Tag is the FQCN; data is the jsonSerialize() result. Round-trip works when the constructor's parameter names match the keys returned by jsonSerialize(). Encoding is unconditional; DECODING is allow-listed — a cassette names a class in your process, so the catch-all only instantiates classes the host opted in with $registry->allow(MyMsg::class) (and even then only after data keys are validated against the real constructor signature). Un-allowed envelopes decode to null.
use SugarCraft\Vcr\Msg\Registry;
$registry = Registry::new();
$registry->allow(MyUserMsg::class);  // opt user classes in for decoding
$envelope = $registry->encode($msg);  // ['@type' => 'KeyMsg', …] or null
$decoded  = $registry->decode($envelope);  // Msg|null

Custom serializers slot in via $registry->register(new MyOne()), which appends them at the lowest priority. Because JsonableSerializer is a catch-all, a codec that must handle a \JsonSerializable Msg instead goes in with $registry->registerFirst(new MyOne()).

Visual regression goldens

candy-vcr/tests/golden/tapes/ holds 10 curated .tape files (TokyoNight, Dracula, plain Type+Enter, sleep-heavy, Ctrl-sequence, arrow keys, wide CJK, Set Width/Height, multi-frame animation, idle-rich) and their committed .gif baselines under both encoders (<name>.php.gif + <name>.ffmpeg.gif one level up in candy-vcr/tests/golden/, 20 GIFs, 302 KB total — measured: 309,363 bytes summed over the committed .gif files).

tests/Encode/VisualRegressionTest.php re-renders each tape and compares to the golden via:

  • SHA-256 byte hash for PhpGifEncoder (deterministic encoder).
  • SSIM ≥ 0.95 via ffmpeg's ssim filter (-filter_complex '[0:v][1:v]ssim', the All: score parsed from the filter's stderr line) for FfmpegGifEncoder (auto-skipped when command -v ffmpeg is empty); pixel-diff fallback when the SSIM filter is unavailable.

To regenerate goldens intentionally (after an encoder change or a theme palette tweak):

php candy-vcr/scripts/refresh-goldens.php           # safe — warns + exits 2 if >3 tapes drift
php candy-vcr/scripts/refresh-goldens.php --dry-run # preview the drift list, change nothing
php candy-vcr/scripts/refresh-goldens.php --force   # commit the new baseline

The manifest lives at candy-vcr/tests/golden/MANIFEST.md.

Committed-GIF exception: the repo-wide rule is that rendered GIFs are regenerated by CI and never committed. These golden GIFs are the deliberate exception: VisualRegressionTest compares fresh renders against the committed bytes, so the baselines are test fixtures and must live in git alongside the .tape inputs. Demo GIFs rendered through the monorepo-root workflow .github/workflows/vhs.yml (a repo-root path, not a candy-vcr/ one) still follow the no-commit rule.

Development

composer install
vendor/bin/phpunit                                          # test suite
vendor/bin/phpstan analyze                                  # static analysis (level: max)
vendor/bin/php-cs-fixer fix --config=../.php-cs-fixer.dist.php  # lint + auto-fix style

Code style is enforced by php-cs-fixer via the root .php-cs-fixer.dist.php (PSR-12 + declare_strict_types + strict_param + short array syntax). Append --dry-run --diff to preview without writing.

Fonts

candy-vcr/fonts/ ships JetBrainsMono (Regular, Bold, Italic, BoldItalic) as the default rasterizer font family. JetBrainsMono is distributed under the SIL Open Font License, version 1.1 — the full license text is bundled alongside the TTFs. The bundled DejaVuSansMono faces are DejaVu Fonts, derived from the Bitstream Vera fonts (the DejaVu changes are in the public domain) and distributed under the Bitstream Vera license — its full text is bundled in the same fonts/LICENSE, below the OFL. The default family is JetBrainsMono (the fontFamily: constructor default on both Glyphs and GdRasterizer). DejaVuSansMono (Regular + Bold, also bundled) is a second selectable family — and the first candidate in Glyphs' fallback chain: if the requested family cannot be resolved, FontLoader::load() throws RuntimeException and Glyphs then probes DejaVuSansMono, then the system-installed FreeMono and NotoSansMono. To use a different family pass it to the Glyphs constructor or call GdRasterizer::withFont($family, $fontSize) (the rasterizer has no font_family property); FontLoader searches the bundled fonts/ dir first, then /usr/share/fonts/truetype/, /usr/share/fonts/opentype/, /usr/share/fonts/X11/Type1/, /usr/share/fonts/X11/TTF/, /usr/local/share/fonts/, ~/.fonts/, and ~/.local/share/fonts/.

CI integration

render-batch is the CI entry point:

php candy-vcr/bin/candy-vcr render-batch <lib>/.vhs/ --encoder ffmpeg

The vhs-candy-vcr job in the repo-root .github/workflows/vhs.yml renders its matrix via that command — but the matrix is still the soak seed, the vhs-candy-vcr job's strategy.matrix.lib: [sugar-core] entry, whose inline comment allows expansion only in a follow-up PR after the soak window passes without visual drift. The soak has not closed: candy-vcr's own tapes are not rendered by this job (the seed renders sugar-core's .vhs/*.tape set). The job smoke-checks that every produced GIF is non-empty and that file recognises it as a GIF image, and uploads them as vhs-candy-vcr-<lib> workflow artifacts with 7-day retention. The job is advisory (continue-on-error: true); the legacy render job remains the blocking renderer — its hand-maintained matrix (~49 libs, candy-vcr included; sugar-dashboard is excluded there and rendered by a dedicated job) is gated by the changed job's per-lib diff output, whose all=(...) force-render selector fires only on manual dispatch or a vhs.yml change. Reverting the vhs-candy-vcr job stanza is the rollback. candy-vcr ships one smoke tape (.vhs/smoke.tape); the rendered GIF is a CI artifact, not a committed file.

The job runs on ubuntu-latest with PHP 8.3 via shivammathur/setup-php (ext-gd, ext-curl, ext-ssh2 among others) and ffmpeg from apt. A matching prebaked container — ghcr.io/detain/sugarcraft-vhs-runner-php (same PHP 8.3 extensions, ffmpeg and the bundled JetBrainsMono fonts; Dockerfile at the monorepo-root scripts/Dockerfile.vhs-runner — again a repo-root path, not the lib's candy-vcr/scripts/ — rebuilt by .github/workflows/vhs-runner-php-image.yml when the Dockerfile or the workflow changes) — is published for local renders and a future containerised CI job.

Snapshot tests

Render output is covered by golden-file snapshot tests. Fixture files live in tests/fixtures/ with a .golden extension and are compared against actual ANSI byte output via SugarCraft\Testing\Snapshot\Assertions::assertGoldenAnsi().

assertGoldenAnsi() is create-only: a missing golden is written and the assertion passes; an existing golden is only ever compared. There is no in-place re-record switch — after an intentional output change, delete the stale golden and re-run the test, then review the regenerated file:

rm tests/fixtures/session.roundtrip.golden
vendor/bin/phpunit --filter session.roundtrip
git diff tests/fixtures/session.roundtrip.golden

For the tape corpus the same rule applies in bulk, with a drift guard:

php candy-vcr/scripts/refresh-goldens.php   # safe — warns + exits 2 if >3 tapes drift
                                            # (--dry-run previews the drift list; --force refreshes)

License

MIT

Support: issue tracker · trust-boundary notes and disclosure policy: SECURITY.md.

Credits & inspiration

Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project.