carlos / platform Public

plans: media conversion plans 1-3 (spike, console, engine), draft

Plan 1 is the Paul-gated dev spike that fixes task sizes, per-file
maximums and the activation proofs. Plan 2 is the console side (one-row
lifecycle with its simulation, door, provenance, refusal gate, caps,
retirement, store uploads) against a fake engine. Plan 3 is the engine
image, AWS adapters, the media-engine module and the rollout. Not yet
reviewed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 99398b7d4f202cbaef7a5cf0ba16e043d7dfa1aa parent c58c28e
3 files changed, +968 −0
  • docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md +114 −0
  • docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md +519 −0
  • docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md +335 −0

Intent

Human

<task-notification> <task-id>afb34e431dff63a6f</task-id> <tool-use-id>toolu_0165M2HRHJezWsyuPePUdwxJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/8509ad95-d983-414c-9679-b3ef222618ef/tasks/afb34e431dff63a6f.output</output-file> <status>completed</status> <summary>Agent "Opus drafts three conversion plans" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I've written the three plans. They aren't committed or pushed, and I made no scratch files, ran no builds, tests or AWS calls, and didn't touch the image-resize worktree. ## Files - `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-video-conversion/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md` (114 lines) - `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-video-conversion/docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md` (519 lines) - `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-video-conversion/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md` (335 lines) ## Tasks **Plan 1, the spike (Paul-gated):** 1. Prepare with no AWS calls: the scratch `mediaspike` driver and probe, a scratch tofu root that copies plan 3's module, and the scope request. 2. Paul's approval and his files. 3. Stand it up, build the image on an arm64 builder, save fixtures for plan 3. 4. Isolation, credentials, the four endpoints, non-reuse, override size, idempotency, retention, clock, the timer drills, and the two store behaviours. 5. Encode matrix, x264 preset choice, tone-mapping (Paul judges it on his iPhone), the rule that sets the maximums, and cost. 6. The 30 GiB source, and expiry ending in exit 75. 7. The playback matrix, served the way production serves. 8. Report, fixtures, spec amendments, cleanup. **Plan 2, the console** (one branch with plan 3, one merge): - 0. Copy deck and UX pass. - 1. Shared types (`internal/media`), the job API, and the simulation with I1..I7 verbatim plus I8 for the allowance sentence. It is left red on purpose, so nothing is pushed until Task 2 makes it pass. - 2. **[Astra]** The `media_jobs` table and its transitions, including classes, capacity, fairness and reservations. Reviewed together with Task 1. - 3. **[Astra]** Store provenance, incarnation and verification (`internal/storecfg`). - 4. **[Astra]** The refusal gate. - 5. **[Astra]** The door, POST and GET. - 6. **[Astra]** `media_minutes_month`, the pack and the cap. - 7. **[Astra]** Retirement at every store teardown. - 8. **[Astra]** The pass worker and `GET /api/cli/system/media`. - 9. **[Astra]** `carlos store uploads`, bucket CORS and the multipart actions. - 10. `carlos media` and `carlos system media status`. - 11. Docs. - 12. The two censuses (root-read and record-write). **Plan 3, the engine:** - 1. **[Astra]** The deadline container. - 2. **[Astra]** Download with resume, `If-Match` and exit 75. - 3. Sniff, probe and child-process cleanup, with fuzzing. - 4. The encodes, with the byte-range playlist written in Go rather than by ffmpeg. - 5. Loudness (ceiling first) and the waveform peaks. - 6. **[Astra]** Collecting outputs through a held directory descriptor, upload, and the result object. - 7. The hostile-input corpus, `selftest` and `drill`. - 8. A reproducible image built without a container runtime (`cmd/mediaimage`). - 9. **[Astra]** The ECS, STS and S3 adapters, plus a MinIO test. - 10. Console wiring. - 11. **[Astra]** `infra/modules/media-engine`. - 12. **[Astra]** The region-host `store_conversion` switch. - 13. The local runner and the import guard that keeps the AWS SDK out of core. - 14. Census, whole-branch review and merge. - Then rollout R1 to R5: release, dev infra, dev drills (attacks first), playback, flagship. ## Spec gaps and contradictions 1. **Module name:** the spec says `infra/modules/media-engine` and your brief said `media-host`. I used the spec's. 2. **§10 vs bucket names:** §10 says the task never sees an account or app name, but minted bucket names are `&lt;prefix&gt;&lt;account&gt;-&lt;app&gt;` and appear in every transfer's host. Plan 3 notes it for Paul. 3. **§9 adoption drill vs §5.2:** the drill says a store adopted under the minted name is refused `store_unverified`. Under §5.2's checks, a clean bucket like that passes verification. The drill now gives the bucket a foreign policy, so it's still refused, and then passes once that's removed. 4. **Done-job charging can be forged:** a done job is charged by the duration in the result object. §6 assumes a compromised ffmpeg can hold the result transfer, so it could forge a short duration. That's a ruling, so it's reported, not changed. Separately, the plan records the converted output's duration as `source_ms`, which closes the honest-but-lying-header case. 5. **Refusal table additions:** the table lacks an unknown-class row, a dot-segment key rule, and placement for the repeat POST and `engine_misconfigured`. I added `unknown_class`, refused `.` and `..` segments under `bad_key`, and placed a repeat POST (answers 200, skipping the later checks) and then `engine_misconfigured` after the 413 check. An explicit `short` above the size threshold becomes `long`. 6. **Peak ceiling vs AAC:** AAC overshoot makes "never above -1.5 dBTP" unreachable without headroom. The gain targets the ceiling less a codec headroom of 0.5 dB, which the spike measures. 7. **Pack price:** the media pack has no price in the spec; R5 asks Paul. 8. **Interpretations I chose:** - Capacity classes count across both presets. - The door's 402 counts settled charges only, not reservations. - The 90-day prune also applies to retired rows. - A crash between dispatch and `RunTask` charges the full bound. That's per the spec, but harsh. - There are four task definitions regardless of whether per-run sizing works; ephemeral storage is a per-run override, with a fallback. - Media is refused on host-claim consoles, so `claim_purge.go` is exempt from the retirement guard. 9. **Image build:** amadan CI has no container runtime, per `.amadan/README.md`. So the image is assembled from pinned Debian packages, and the spike decides how the weekly refresh runs. ## Values that wait on the spike All are named constants or settings in the plans, with the provisional value in brackets: - Per-file maximums: `video_max` (2 h), `video_max_hi` (30 min), `video_bytes` (40 GiB), `audio_max` (8 h), `audio_bytes` (10 GiB). - Class sizes, CPU and memory per row, and whether 16 vCPU arm64 is available. - Short-class granted durations (10 min video, 2 h audio). - `x264Preset` (veryfast) and `x264CRF` (23). - The HDR tone-map chain and `refuseDolbyVision5` (false). - `codecHeadroomDB` (0.5). - `EngineRecordRetention` (1 h). - `MaxOverrideBytes` (8,192) and the worst-case token length (1,400). - Whether `ephemeralStorage` and task size can be set per run. - Platform version (1.4.0) and clock skew. - The playback fallback, and the acceptance time (expected under 2 minutes). - How the weekly image refresh runs. - Cost figures.</result> <usage><subagent_tokens>508653</subagent_tokens><tool_uses>120</tool_uses><duration_ms>2573744</duration_ms></usage> </task-notification>

diff --git a/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md b/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md
new file mode 100644
index 000000000..dc9146695
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md
@@ -0,0 +1,114 @@
+# Media conversion, plan 1 (the dev spike) 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 (`- [ ]`) syntax for tracking.
+
+**Goal:** Measure and prove, on a throwaway dev cluster with Paul's real files, every claim the spec marks (unverified) or (estimate) and assigns to the spike, and commit a report whose exact figures plans 2 and 3 read, with a spec amendment for every proof that fails.
+**Architecture:** A scratch OpenTofu root builds the engine's network, endpoints, DNS firewall, roles, cluster and reaper as plan 3 Task 11 specifies, around a scratch image (Debian 13, its ffmpeg, and one scratch Go program, `mediaspike`). `mediaspike` is both the driver on docs-t1 (assume, presign, run, watch, time) and the probe inside the task (credentials, DNS, network, timer attacks, encodes). Nothing is committed but the report and its fixtures; everything is destroyed at the end.
+**Tech Stack:** Go 1.26 (scratch module), OpenTofu, `aws` CLI with profile `kass`, podman on an arm64 builder, Debian 13 `ffmpeg`, Safari (iOS and macOS), Chrome, Firefox, hls.js.
+**Spec:** docs/superpowers/specs/2026-11-16-video-conversion-design.md (rev 8, approved)
+
+## Global Constraints
+
+- Paul-gated (spec decision 1). No AWS resource is created, and no AWS call other than read-only `describe`/`get`/`list` is made, before Paul's one scoped approval in Task 2. Ask again if the work grows past it.
+- Dev account only, profile `kass`, region `eu-west-1`. Nothing in the flagship account, nothing on a tenant's store, the dev console untouched.
+- Scratch: `$TMPDIR/mediaspike/` on docs-t1 (source, tofu root and state, builds), `~/.cache/mediaspike/inbox/` for Paul's files, `/var/tmp/mediaspike` on the builder. Each removed by its exact path at the end, never by glob. Paul's files never enter git, a log or the report; only `ffprobe` facts with every `tags` object removed do.
+- The scratch root mirrors plan 3 Task 11 resource for resource (the network, the four endpoint policies, the DNS allow list, the roles, the task shape), so a proof here is a proof of that module. Where the spike deviates (its own image, the conversion role trusting the operator's principal instead of a console role, extra drill task definitions), the report says so.
+- Class rows to measure (§7.1): video short 4 vCPU/8 GB, video long 16 vCPU/32 GB, audio short 1 vCPU/2 GB, audio long 2 vCPU/4 GB, ARM64, Fargate platform 1.4.0.
+- Encoding arguments are plan 3 Task 4's and Task 5's exactly, with `-preset` varied over `veryfast`, `faster`, `medium` and `-crf 23`.
+- Copy voice for the report: plain, no em dashes. Neutral names in anything committed.
+
+## Review Focus
+
+1. **Start time measured on a toy image.** Fargate pulls the whole image for every task; the start figure must come from an image the size of the real one (Debian 13 slim plus the ffmpeg closure). Test: Task 3 Step 3 records the image size; Task 5 Step 1 times starts on that image only.
+2. **iPhone HDR is Dolby Vision 8.4 over HLG.** Numbers cannot show washed-out or blown colours; Paul judges the poster and a 10 s clip against the source on a real iPhone. Test: Task 5 Step 3.
+3. **Safari plays what is served the way production serves it.** A file that plays from a local disk can fail behind a presigned redirect or a proxied playlist. Test: Task 7 serves through both paths only.
+4. **The session token's length varies.** One AssumeRole sample understates the override size. Test: Task 4 Step 5 takes the longest of 20.
+5. **ECS's stopped-task retention varies.** One sample overstates it. Test: Task 4 Step 7 measures three tasks and the report uses the shortest.
+
+---
+
+### Task 1: Prepare, with no AWS calls
+
+**Files (scratch, never committed):**
+- Create: `$TMPDIR/mediaspike/src/` (module `mediaspike`, stdlib plus `aws-sdk-go-v2` `sts`, `s3`, `ecs` from the module cache, `GOFLAGS=-mod=mod`), `$TMPDIR/mediaspike/tofu/` (`main.tf`, `variables.tf`, `outputs.tf`), `$TMPDIR/mediaspike/image/Containerfile`, `$TMPDIR/mediaspike/page/index.html`, `$TMPDIR/mediaspike/scope.md`
+
+**Interfaces (scratch):** `mediaspike` subcommands. Driver: `grant --bucket <b> --key <k> --etag <e> --session <minutes>` (AssumeRole of the spike conversion role with plan 3 Task 9's session policy, prints the five transfers in plan 2 Task 1's `media.Transfers` JSON, its struct copied into the scratch module since plan 2 is not built yet, and the token length); `run --class <preset/class> [--command …] [--env K=V]… [--storage <GiB>] [--cpu <units> --memory <MiB>] [--token <t>]` (RunTask as plan 3 Task 9 builds it; prints the ARN and the override byte length); `watch <arn>` (DescribeTasks every 5 s; prints created, pull start/stop, started, each container's start from the codec's metadata log, stopped, stop code, exits); `retention <arn>…` (DescribeTasks every 5 min until `MISSING`). Probe (in the task): `creds`, `dns <name>…`, `net <host:port>…`, `foreign`, `marker`, `hostile-timer`, `deadline` (plan 2's `media.DeadlineSleep` rule, copied), `clock`, `encode --preset <x264> --profile video|audio|poster|hdr` (downloads the transfer's source with resume, runs the plan 3 arguments, reads `memory.peak` of its cgroup, uploads, prints wall times per phase), `playlist <mp4>` (a scratch copy of plan 3's `readFMP4` and `writePlaylist`), `reconnect --cut-at <bytes> --pause-until <unix>`.
+
+- [ ] **Step 1:** Write `mediaspike`; `go vet` and `CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build`. Expected: clean.
+- [ ] **Step 2:** Write the tofu root (plan 3 Task 11's resources, `name = "mediaspike"`, the bucket `<dev store prefix>mediaspike-<6 hex>` with SSE-S3, versioning off, public access blocked; drill task definitions `late-deadline` (the deadline container on a separate image tag padded with a 2 GB layer), `no-deadline` (the deadline container on a digest that does not exist), `no-start-dep` and `stop-20`). `tofu init -backend=false && tofu validate`. Expected: valid. Read the dev store prefix from the dev root (read-only).
+- [ ] **Step 3:** Write the Containerfile: `FROM docker.io/library/debian:13-slim@sha256:<digest>`, `apt-get install --no-install-recommends ffmpeg`, `COPY mediaspike /usr/local/bin/`, `USER 65534:65534`, `ENTRYPOINT ["/usr/local/bin/mediaspike"]`. Record the digest.
+- [ ] **Step 4:** Write `scope.md`, the approval request, with: account and region; every resource of Step 2 by type and name, plus one throwaway `t4g.medium` Debian 13 arm64 builder (SSM only, no inbound, 40 GB gp3; or the existing dev root runner if one is up), one dev app `mediaspike` for the playback page, and in an unrelated account Paul names one IAM user with no policy and one access key; what each permits (the conversion role trusts only the operator's `kass` principal); traffic effects (none on tenants or the dev console); cost at most 100 US dollars (endpoints about 1 dollar a day, Fargate runs, the builder, about 150 GB of S3 for a week); duration at most 7 days; Task 8's cleanup and its verification. List the files needed from Paul (spec decision 1): 4K60 HDR in Dolby Vision or HLG, a portrait clip with rotation, a variable-frame-rate clip, an ordinary 1080p clip, an hour or more of video, a browser voice recording; and the Safari checks on his iPhone or the tito-studio Mac.
+
+---
+
+### Task 2: Paul's approval
+
+- [ ] **Step 1:** Send `scope.md` to Paul. Wait. Record his approval (verbatim, with the date) at the top of the report draft. Without it, stop here.
+- [ ] **Step 2:** Paul puts his files in `~/.cache/mediaspike/inbox/` on docs-t1 (or names where they are). Record each file's size and `ffprobe` stream summary (codecs, dimensions, rotation, frame rates, colour transfer, Dolby Vision profile, duration) in the draft, tags removed.
+
+---
+
+### Task 3: Stand it up, build the image, save the fixtures
+
+- [ ] **Step 1:** `tofu apply` the scratch root (`AWS_PROFILE=kass`). Expected: every resource created; `tofu output` gives the repository, cluster, subnets, groups, roles and bucket.
+- [ ] **Step 2:** Start (or reuse) the builder. Over SSM: install podman, copy in the Containerfile and the arm64 `mediaspike`, `podman build`, log in to the spike repository with `aws ecr get-login-password`, push; record the digest. Re-apply with that digest in the task definitions.
+- [ ] **Step 3:** Record the image's compressed size and `ffmpeg -version` (the Debian 13 package version). These are the start-time and version baselines (Review Focus 1).
+- [ ] **Step 4:** On the builder, with that ffmpeg and plan 3 Task 4's exact arguments on 10 s `lavfi` sources at 320x180 (`testsrc2` with a 440 Hz tone; the same without audio; the tone alone), make `video.mp4`, `video-noaudio.mp4`, `audio.mp4`, and save each one's `ffprobe -show_packets -of json` beside it. Save `ffprobe -show_streams -show_format -of json` of Paul's HDR, portrait, VFR and voice files with every `tags` object removed. Copy all of it to docs-t1 as `docs/superpowers/reviews/media-spike-fixtures/fmp4/` and `…/probe/`.
+- [ ] **Step 5:** Upload Paul's files to the spike bucket (`aws s3 cp`, multipart). On the builder, derive and upload: a 20-minute 4K cut and a 20-minute 4K HDR cut (`-stream_loop` with stream copy where the source is shorter), an 8-hour WAV and MP3 of the voice recording looped, and a 30 GiB MP4 of the hour-long video looped with stream copy.
+
+---
+
+### Task 4: Isolation, credentials, endpoints, the timer and the ECS behaviours (§7.4 items 3, 4, 5)
+
+Each step runs one or more tasks through `mediaspike run` and records the probe's `PASS`/`FAIL` lines and `watch`'s timeline in the report.
+
+- [ ] **Step 1: Credentials.** `--command creds` on each class. Expected: no `AWS_*` variable; no `AWS_CONTAINER_CREDENTIALS_*`; `169.254.170.2` serves no credential; `169.254.169.254` unreachable; the v4 task metadata answers but holds no credential.
+- [ ] **Step 2: Names and routes.** `dns` for the five allowed names and for `example.com`, `amazonaws.com`, `sts.eu-west-1.amazonaws.com`, `ecs.eu-west-1.amazonaws.com`; `net` to `1.1.1.1:443`, the dev console's private IP on 443 and another dev box's private IP on 22. Expected: only the allowed names resolve; every connection fails. An unsigned `GET` of a spike-bucket object and one signed by the foreign user: refused at the S3 endpoint.
+- [ ] **Step 3: Foreign credentials.** `--command foreign` with the foreign user's key in its environment (this task only): signed calls to S3, `ecr:GetAuthorizationToken`, an ECR Docker `HEAD` of a manifest, and `logs:PutLogEvents`. Expected: four refusals at the endpoint (the error names the VPC endpoint policy).
+- [ ] **Step 4: Non-reuse and isolation.** Two tasks in sequence and two side by side with `--command marker` (writes its task ARN under `/scratch` and `/tmp`, reads for any other ARN, lists `/proc` for foreign PIDs). Expected: each sees only itself; distinct task ARNs and ENIs.
+- [ ] **Step 5: Overrides, size, storage.** Twenty `grant` calls: record the longest token. A `run` with that token and a 512-byte key of 3-byte runes: record the override byte length and whether RunTask accepts it. `--storage 48`: accepted, and `df /scratch` in the task shows it. `--cpu 16384 --memory 32768` on the audio-short definition: accepted or refused (whether size can be set per run). A video-long run at 16 vCPU ARM64: placed, or the capacity error.
+- [ ] **Step 6: Idempotency.** RunTask twice with one `clientToken` and the same body: the same task ARN. The same token with a different environment value: record the error code.
+- [ ] **Step 7: Retention.** Stop three finished tasks; `retention` on all three. Record each time to `MISSING`; the report uses the shortest (Review Focus 5).
+- [ ] **Step 8: Clock.** `--command clock` on each class prints its `CLOCK_REALTIME` against the driver's (NTP on docs-t1) at a shared instant. Record the skew.
+- [ ] **Step 9: The timer (activation gates).** `late-deadline`: the codec's metadata log shows `codec` started after `deadline`. `no-deadline`: the task stops; `codec` has no start and no exit code. `no-start-dep` and `stop-20`: record that they run (the console's gate, not ECS, refuses them; plan 2 Task 4). Then, with no driver process running at all: `--command hostile-timer` and `CARLOS_MEDIA_DEADLINE_S=180`: record `startedAt` to `stoppedAt`. Expected: at most 210 s, the deadline container's exit 0, the codec's 137. Again with `CARLOS_MEDIA_GRANT_EXPIRY` 60 s ahead of start: stopped within 60 − 30 + 30 s.
+- [ ] **Step 10: Store behaviours (§5.4).** Tag a spike object `carlos-scan=infected` with the operator role; presign a GET and a HEAD through the assumed conversion role. Expected: 403 for both. Presign a PUT with signed `If-None-Match: *` for an existing key. Expected: 412.
+
+---
+
+### Task 5: Throughput, maximums and tone-mapping (§7.4 items 1, 2)
+
+- [ ] **Step 1: Encode matrix.** For each class row, `--command encode` at `veryfast`, `faster` and `medium` on: the ordinary 1080p clip, the portrait clip, the VFR clip, the hour of 1080p (long class), the 20-minute 4K and 4K HDR cuts (long class), and the 8-hour audio files (audio classes). Record per run: RunTask to `RUNNING`, image pull time, download throughput (MB/s), encode wall time and speed (media seconds per second), poster time, upload time, peak memory, and the output's bitrate and file size. Three runs per cell for the short class, one for the rest.
+- [ ] **Step 2: Choose the preset.** The slowest of the three whose long-class 1080p speed is at least 3 times real time. That is `x264Preset`.
+- [ ] **Step 3: Tone-mapping.** The HDR cut through plan 3's HDR chain on the long class: speed, and whether 30 minutes of it fits the rule in Step 4. Paul views `poster.jpg` and a 10-second excerpt beside the source on his iPhone and says whether the colours read right (Review Focus 2). If the chain does not fit or does not look right, the report proposes refusing HDR with `unsupported_hdr` (a spec amendment). Record the Dolby Vision profile of Paul's file; profile 5 is refused only if a profile 5 sample is tried and fails (`refuseDolbyVision5`).
+- [ ] **Step 4: Set the maximums.** With `t_start` the 95th-percentile start, `B` the 5th-percentile download throughput and `v` the 5th-percentile speed at the chosen preset: size maximum `S = min(spec value, B × 15 min)`, rounded down to 5 GiB; duration maximum `D = min(spec value, (40 min − t_start − S/B) × v)`, rounded down to 15 min; separately for video up to 1080p, video above 1080p, and audio. Short classes: the granted duration stays 10 min (video) and 2 h (audio) when `t_start + 1 GiB/B + granted/v` is at most 12 min (video) and 8 min (audio); otherwise the largest multiple of 5 min that fits. Loudness: measure each audio output's integrated loudness and true peak; `codecHeadroomDB` is the largest overshoot above the gain's target seen, rounded up to 0.1 dB, and at least 0.5.
+- [ ] **Step 5: Cost.** From the measured task seconds and that day's Fargate ARM64 prices for `eu-west-1` (vCPU-hour, GB-hour, ephemeral storage above 20 GiB) and the endpoints' hourly and per-GB charges: the cost of one minute of video per class, of one hour of audio, and the fixed monthly cost; and the engine cost per allowance minute against decision 6's "at most about 0.6 cents".
+
+---
+
+### Task 6: The 30 GiB source and the grant window (§7.4 item 6)
+
+- [ ] **Step 1:** The 30 GiB source on the long class with `--command encode` and `reconnect --cut-at 10GiB`: download resumed under `If-Match`, converted and uploaded inside the hour. Record each phase's time against the hour.
+- [ ] **Step 2:** A grant with `--session 15` (the shortest AssumeRole allows): `reconnect --cut-at 1GiB --pause-until <expiry + 60 s>`. Expected: the resumed GET is refused, the codec exits 75, no result object exists, ECS reports the run time. (The console's mapping to `failed grant_expired` and its cleanup are plan 2's tested code.)
+- [ ] **Step 3:** A task whose `CARLOS_MEDIA_GRANT_EXPIRY` is already in the past (the container's view of having waited in `PENDING` past its grant): the deadline container exits at once and the task stops; no output key exists in the bucket.
+
+---
+
+### Task 7: Playback (§7.4 item 7)
+
+- [ ] **Step 1:** Convert the ordinary 1080p clip cut to two minutes (video) and the voice recording (audio) with the chosen preset; write each playlist with `mediaspike playlist`.
+- [ ] **Step 2:** Deploy dev app `mediaspike` serving `index.html` and a small handler: `/media/v/video.m3u8` and `/media/a/audio.m3u8` proxied from the bucket with `Content-Type: application/vnd.apple.mpegurl`; `/media/v/video.mp4` and `/media/a/audio.mp4` answered with a 302 to a presigned GET (Review Focus 3). The page has a `<video>` on the MP4, a `<video>` on the playlist (native HLS), an hls.js player (vendored, pinned version recorded) on the playlist, and the same three for audio.
+- [ ] **Step 3:** In Safari on iOS (Paul's iPhone), Safari on macOS and Chrome and Firefox (tito-studio Mac): each player starts, seeks to 75 % and plays from there within 3 s, and plays to the end; native HLS only where the browser has it. Record a matrix of pass, fail and the error.
+- [ ] **Step 4:** Time a full round trip: browser upload of the clip, POST-equivalent `grant` and `run`, poll until done. This is the acceptance time R4 of plan 3 uses (spec: expected under two minutes).
+- [ ] **Step 5:** If progressive playback of the single MP4 fails anywhere, the report proposes the spec's fallback (a second, ordinary faststart MP4, G2 amended), with the failing cells.
+
+---
+
+### Task 8: Report, fixtures, amendments, cleanup
+
+**Files:**
+- Create: `docs/superpowers/reviews/2026-11-16-media-conversion-spike.md`, `docs/superpowers/reviews/media-spike-fixtures/fmp4/*`, `docs/superpowers/reviews/media-spike-fixtures/probe/*.json`
+
+- [ ] **Step 1: Also establish the image route.** Whether amadan CI runs on a schedule (amadan CLI help and `.amadan/README.md`); whether `snapshot.debian.org` is reachable from docs-t1 (`curl -sI`, with that host declared). Record which weekly refresh plan 3 Task 8 uses: an amadan schedule, or a Paseo schedule on docs-t1.
+- [ ] **Step 2: Write the report:** Paul's approval; environment and image; Paul's files' facts (tags removed); every Task 4 to 7 result as a table; then **Values for plans 2 and 3**, one row each with provisional and measured: `media.EngineRecordRetention` (1 h), `media.MaxOverrideBytes` (8,192) and the worst token length (1,400 in plan 2's test), `video_max` (2 h), `video_max_hi` (30 min), `video_bytes` (40 GiB), `audio_max` (8 h), `audio_bytes` (10 GiB), the four class rows' CPU and memory and whether 16 vCPU ARM64 places, the short classes' granted durations (10 min, 2 h), `x264Preset` (`veryfast`), `x264CRF` (23), the HDR chain and `refuseDolbyVision5` (false), `codecHeadroomDB` (0.5), whether `ephemeralStorage` and task size are accepted per run, platform version (1.4.0), clock skew, the playback matrix and the acceptance time, the weekly image refresh, and the cost table. Then **Spec amendments**: one per failed proof, with the evidence; or "none".
+- [ ] **Step 3:** Commit the report and fixtures on the design branch: `docs: media conversion spike report and fixtures`. Paul confirms the report before plan 3 Task 4 starts.
+- [ ] **Step 4: Clean up**, then verify each: `tofu destroy` (bucket emptied first) and an `aws resourcegroupstaggingapi get-resources` for the spike's tag showing nothing; the builder terminated (or the root runner's `/var/tmp/mediaspike` removed); the foreign user's key and user deleted (Paul, or with his credentials); dev app `mediaspike` deleted; `~/.cache/mediaspike/` and `$TMPDIR/mediaspike/` removed by exact path. Tell Paul it is done, with the report's path.
diff --git a/docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md b/docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md
new file mode 100644
index 000000000..5bedb677f
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md
@@ -0,0 +1,519 @@
+# Media conversion, plan 2 (the console side) 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 (`- [ ]`) syntax for tracking.
+
+**Goal:** Every app with a provisioned store and a Service credential can ask the console to convert a video or audio object, poll the job, and get its output keys, with the one-row lifecycle, store provenance, the allowance and the uploads verb all built and tested against fakes.
+**Architecture:** `internal/media` is a stdlib-only leaf holding every shared name: presets, classes, limits, the job id, the codec's payload and result schema, exit codes, error codes and the `Engine` and `Grants` interfaces (with fakes in `internal/media/mediatest`). `internal/mediajobs` owns the `media_jobs` table and every transition as one SQL transaction, driven by a single-goroutine pass; `internal/sim/mediajobs` runs it under randomized interleavings and checks I1 to I8. The console adds the door, the store-provenance check (`internal/storecfg`), retirement at every store teardown, the `media_minutes_month` cap, `carlos store uploads`, the CLI verbs and the docs; AWS adapters arrive in plan 3.
+**Tech Stack:** Go 1.26, `database/sql` over `modernc.org/sqlite` (the console store), `net/http`, the console's existing gates (`apiAccountApp`, `storeWalks`, plan caps), `clireg`.
+**Spec:** docs/superpowers/specs/2026-11-16-video-conversion-design.md (rev 8, approved)
+
+## Global Constraints
+
+- Door paths: `POST /api/cli/apps/{account}/{app}/media/conversions` and `GET /api/cli/apps/{account}/{app}/media/conversions/{id}`, both `svcrole.Allow(svcrole.Service)`, both resolved through `apiAccountApp`. `s.allowWrite` does not apply.
+- POST body is strict JSON, at most 4 KiB: `key` (required), `preset` (`video-720p` default, or `audio-aac`), `class` (`short` or `long`; absent: the source's size picks).
+- Job id: the first 32 hex characters of SHA-256 over `"v1"`, key, ETag (no quotes), preset and class, each followed by one zero byte.
+- Execution id: 32 hex characters from 16 bytes of `crypto/rand`. It is RunTask's `startedBy` and its idempotency token.
+- Output keys: `derived/<key>/<etag>/<preset>/<execution>/` + `video.mp4`, `video.m3u8`, `poster.jpg` (video) or `audio.mp4`, `audio.m3u8`, `peaks.json` (audio). Result object: `media-results/<execution>.json` in the deployment bucket, read bounded to 64 KiB.
+- Classes (§7.1): video short (picked up to 1 GiB): 4 vCPU, 8 GB, deadline 15 min, granted 10 min; video long: 16 vCPU, 32 GB, 50 min, the video maximum; audio short (up to 256 MiB): 1 vCPU, 2 GB, 10 min, 2 h; audio long: 2 vCPU, 4 GB, 50 min, the audio maximum. Ephemeral storage 20 GiB, or source size plus 8 GiB when more.
+- Provisional maximums (settings, `CARLOS_MEDIA_LIMITS`; plan 1's report may change them): video 2 h up to 1080p and 30 min above, 40 GiB; audio 8 h, 10 GiB; 3840x2160, 60 fps.
+- Fair use: 6 short and 2 long tasks in the deployment, 2 short and 1 long per account, counted as rows with a dispatched execution and `task_stopped` false; per account 20 queued or running (429) and 30 submissions a minute with a burst of 10 (429); deployment-wide 200 queued (503).
+- Stop grace 30 s. Full bound = `deadline_s` + 30 s. Grant lifetime 1 h. Deadline at most 50 min. Under 3 min of deadline: wait while the account has another execution running, else fail `allowance_exceeded` uncharged.
+- Weights: `video-720p` 1, `audio-aac` 0.1, held as tenths (10 and 1) so every allowance figure is an integer: units = milliseconds × weight-tenths.
+- Allowance: `media_minutes_month`, monthly, warning at the limit, 402 from `capMessage` at twice the limit, ops accounts exempt, 0 = no limit, `capID` `media`. No catalog: `account_minutes` from `CARLOS_MEDIA_LIMITS`.
+- One SQLite connection (`internal/console/store.go:122`): every query inside a transaction goes through its `*sql.Tx`, and no network call (engine, grants, storecfg) is ever made inside a transaction.
+- Lock order: the store walk lock (`storeWalks.lock(acct, app, "")`) before any transaction, never the reverse. `mediajobs.Retire` never takes the lock; its caller holds it.
+- Media conversion is refused on a host-claim console: `media_jobs` is gated with `Refuse`, the doors answer 503 `not_configured`, and plan 3's boot wiring refuses `CARLOS_MEDIA_ENGINE` with `CARLOS_HOST_CLAIM`.
+- Error bodies: `jsonErrorCode(w, status, code, msg)` (`{"error": msg, "code": code}`). Job errors in a job answer are `{"code", "message"}`, the message always from the copy deck by code, never from the result object.
+- Every user-facing string comes from the approved copy deck (Task 0). Copy voice: no em dashes; CLI and JSON errors lower case with no trailing full stop; neutral examples (`shop`, `shop.example.com`).
+- Local tests: targeted `go test ./internal/<pkg>/... -run 'TestX' -count=1` only. Never set `GOCACHE`. CGO stays off (`CGO_ENABLED=0` builds).
+- The root `carlos` package never imports `internal/media`, `internal/mediajobs` or `internal/storecfg` (it decodes answers into local structs), so none of them enters the root census scope.
+- Branch: `media-conversion`, cut from amadan `main` after the design branch merges. Plans 2 and 3 are one branch, one whole-branch review and one merge. Do not push between Task 1 and Task 2 (Task 1 leaves the simulation red).
+- Review budget: AGENTS.md stopping rules. Tasks marked **[Astra]** get their own review before the next task starts; everything else is covered by the whole-branch review.
+
+## Review Focus
+
+1. **Phone file names.** `uploads/IMG 0001 (1).MOV`, `uploads/vidéo.mov` (NFC and NFD), `a+b%20c.mov`, and `x/../derived/y.mov`: the first four convert with the exact key echoed back and correctly escaped transfers; the dot segment is `bad_key`. Test: Task 5 `TestDoorKeysPeopleActuallyUpload`, and Task 1 `TestTransfersURLEscapesKeys`.
+2. **Multipart ETags.** A source uploaded in parts has an ETag like `"9b2cf535f27731c974343645a3985328-12"`; the job id, the output prefix and the signed `If-Match` all use it unquoted and unchanged. Test: Task 1 `TestJobIDAndPrefixWithMultipartETag`.
+3. **An app that polls with POST.** Fifty repeat POSTs of the same key in a minute answer 200 with the same job, start nothing, charge nothing and never 429. Test: Task 5 `TestRepeatPostIsNotRateLimited`.
+4. **A job that ends after midnight on the last day of the month.** It is charged in the month it ended; its reservation counted in both months while it ran. Test: Task 2 `TestChargeLandsInTheMonthItEnded`.
+5. **The account goes write-denied after submitting.** A queued row fails `store_writes_denied` uncharged at dispatch; a running row finishes and commits. Test: Task 2 `TestWritesDeniedBetweenSubmitAndDispatch`.
+
+---
+
+### Task 0: Copy deck and UX pass
+
+**Files:**
+- Create: `docs/superpowers/notes/media-conversion-copy-deck.md`
+- Create: `docs/superpowers/notes/media-conversion-usage-mockup.html` (the kit, `docs/console-mockup-kit/shell.html`)
+
+The deck holds every string Tasks 3 to 11 write. Drafts below; implementers copy from the approved deck, never from this plan. `%s`/`%d` are filled by code.
+
+| Key | Draft |
+|---|---|
+| `media.not_configured` (503) | `media conversion is not set up on this deployment` |
+| `media.engine_misconfigured` (503) | `the conversion engine failed its safety checks, so no conversion starts. ask this deployment's operator` |
+| `media.bad_key` (400) | `name the source object, e.g. {"key": "uploads/a1b2.mov"}. a key is at most 512 bytes, has no control characters and no "." or ".." segment, and is not under derived/` |
+| `media.unknown_preset` (400) | `preset is video-720p or audio-aac` |
+| `media.unknown_class` (400) | `class is short or long` |
+| `media.no_store` (409) | `%s has no object store yet. create one with carlos store create --app %s` |
+| `media.store_unverified` (409) | `this store cannot be used for conversion: %s. fix that and submit again` |
+| `media.check.name` / `.owner` / `.region` / `.encryption` / `.versioning` / `.policy` / `.lifecycle` / `.cors` | `its bucket is not named the way this deployment names buckets` / `its bucket belongs to another AWS account` / `its bucket is in another region` / `its bucket uses SSE-KMS, and conversion needs SSE-S3` / `its bucket has versioning turned on` / `its bucket has a bucket policy this platform did not write` / `its bucket has a lifecycle rule this platform did not write` / `its bucket has a CORS rule this platform did not write` |
+| `media.no_engine_in_region` (409) | `conversion runs in %s, and this store is in %s` |
+| `media.store_writes_denied` (402) | `this store refuses new objects because the account is past its storage allowance, so conversion cannot write its outputs` |
+| `media.source_not_found` (404) | `there is no object at that key` |
+| `media.source_unreadable` (409) | `that object cannot be read for conversion. it may have been found infected` |
+| `media.source_too_large` (413) | `that object is %s. %s converts sources up to %s` |
+| `cli.cap.media_minutes` (402) | `this account has used %d media minutes this month, twice its monthly limit of %d. conversion starts again on the 1st of the UTC month, or move to a larger plan` |
+| `media.busy_account` (429) | `this account already has %d conversions waiting or running. wait for one to finish` |
+| `media.rate` (429) | `this account has asked for more than %d conversions in a minute. try again in a moment` |
+| `media.queue_full` (503) | `the conversion queue is full. try again in a minute` |
+| `media.job_not_found` (404) | `this app has no conversion with that id` |
+| `media.job.unsupported_container` | `the file is not a format conversion reads. video: MP4, MOV, 3GP, WebM or MKV; audio also MP3, WAV, FLAC or Ogg` |
+| `media.job.no_video` / `no_audio` | `the file has no video track. convert it with "preset": "audio-aac"` / `the file has no audio track` |
+| `media.job.unsupported_video_codec` / `unsupported_audio_codec` | `the video codec is not one conversion reads: H.264, HEVC, VP8, VP9 or AV1` / `the audio codec is not one conversion reads: AAC, Opus, Vorbis, MP3, FLAC or PCM` |
+| `media.job.source_dimensions` / `source_frame_rate` | `the video is larger than 3840x2160` / `the video is over 60 frames a second` |
+| `media.job.source_too_long` | `the file is longer than %s, the most this preset converts` |
+| `media.job.needs_long_class` | `the file is longer than %s, the most the short class converts. submit it again with "class": "long"` |
+| `media.job.allowance_exceeded` | `this account's media allowance for the month does not cover this file` |
+| `media.job.unreadable` | `the file could not be read. it may be damaged or cut short` |
+| `media.job.output_too_large` | `a converted file would be over 5 GB, the most one output can be` |
+| `media.job.unsupported_hdr` | `this kind of HDR video cannot be converted yet` |
+| `media.job.source_changed` / `source_unreadable` / `source_not_found` / `source_too_large` | `the object changed after it was submitted. submit it again` / door copy / door copy / door copy |
+| `media.job.grant_expired` / `deadline_exceeded` | `the conversion ran past its one-hour window` / `the conversion took longer than its time limit and was stopped` |
+| `media.job.engine_failed` / `engine_unavailable` / `engine_lost` | `the conversion engine failed on this file` / `the conversion engine could not start. upload the file again to try once more` / `the conversion engine lost track of this job. upload the file again to try once more` |
+| `media.job.store_changed` / `store_writes_denied` | `the store was replaced while this job waited` / door copy |
+| `media.retire_pending` (browser flash) | `Conversions for “%s” are still stopping. Try again in a minute.` |
+| `uploads.*` (CLI/JSON) | `uploads.not_configured` (503) `browser uploads are not set up on this deployment`; `uploads.bad_origin` (400) `%q is not an origin uploads accept. use https:// and a host, or http://localhost:<port>`; `uploads.too_many_origins` (400) `at most 8 origins`; `uploads.no_hosts` (409) `this app has no ready platform hostname yet. name the origins with --origin` |
+| CLI lines | `media convert`: `id %s` / `state %s` / `error %s (%s)` / `output %s %s %s`; `system media status`: `engine configured in %s` / `engine not configured` / `image %s, built %s, ffmpeg %s` / `warning the image is %d days old. rebuild it and roll it out` / `gate %s ok` / `gate %s refused: %s` / `queue %d short, %d long` / `running %d short, %d long` / `24 hours %d done, %d failed` ; `store uploads status`: `uploads on` / `uploads off` / `origins %s` / `bucket matches` / `bucket changed: %s` |
+| Usage | `usage.label.media` `Media minutes`; `limit.media` `%s media minutes a month`; `usage.media` `%d of %d media minutes this month`; `banner.media_refused` `This account has used twice its media allowance this month. New conversions are refused until the 1st of the UTC month, or until it moves to a larger plan.`; `cli.media_refused`, `cli.media_over`, `banner.media_over` as their PDF siblings with "media allowance" and "conversions" |
+
+- [ ] **Step 1: UX pass.** In the kit, mock the billing page's usage list with the new "Media minutes" row beside "PDFs" (warn and over states), at 390 px and desktop, light and dark. Write each CLI output above as an 80-column sample in the deck (`media convert --wait` done and failed, `system media status` healthy and with a stale image and a refused gate, `store uploads status` on, off and changed). Fix what reads badly before review.
+- [ ] **Step 2:** Write the deck file with the table above, the samples and the mockup link.
+- [ ] **Step 3:** Run the copy-review skill on it. Wait for Paul's edits. Apply them verbatim.
+- [ ] **Step 4:** Commit: `docs: media conversion copy deck, approved`.
+
+---
+
+### Task 1: Shared types, the job API, and the simulation (red)
+
+**Files:**
+- Create: `internal/media/media.go`, `internal/media/limits.go`, `internal/media/payload.go`, `internal/media/result.go`, `internal/media/engine.go`, `internal/media/media_test.go`, `internal/media/payload_test.go`
+- Create: `internal/media/mediatest/engine.go`, `internal/media/mediatest/grants.go`
+- Create: `internal/mediajobs/jobs.go` (declarations; every method body `return …, errNotImplemented`), `internal/mediajobs/schema.go`
+- Create: `internal/sim/mediajobs/sim_test.go`, `world_test.go`, `actions_test.go`, `invariants_test.go`, `witness_test.go`
+
+**Interfaces:**
+- Produces in `internal/media` (stdlib only):
+ - `const PresetVideo720p = "video-720p"`, `PresetAudioAAC = "audio-aac"`, `ClassShort = "short"`, `ClassLong = "long"`.
+ - `type ClassKey struct{ Preset, Class string }`, `func (k ClassKey) String() string` (`"video-720p/short"`).
+ - `type ClassSpec struct{ Key ClassKey; PickUpTo int64; CPU, MemoryMiB int; Deadline, Granted time.Duration }` (`Granted` 0 = the preset maximum) and `func Class(k ClassKey) (ClassSpec, bool)` with the four rows of Global Constraints.
+ - `func PickClass(preset, requested string, bytes int64) string`: `requested == "long"`, or bytes over the short row's `PickUpTo`, gives `long`; otherwise `short` (an explicit `short` above the threshold becomes `long`).
+ - `func WeightTenths(preset string) int64` (10, 1); `func OutputNames(preset string) []string`; `func ContentType(name string) string` (`video/mp4`, `application/vnd.apple.mpegurl`, `image/jpeg`, `audio/mp4`, `application/json`).
+ - `func JobID(key, etag, preset, class string) string`; `func NewExecutionID() (string, error)`; `func OutputPrefix(key, etag, preset, execution string) string`; `func ResultKey(execution string) string`; `func ValidKey(key string) bool` (non-empty, at most 512 bytes, valid UTF-8, no byte below 0x20 or 0x7f, no `.` or `..` segment, not prefixed `derived/`).
+ - `const (StopGrace = 30*time.Second; GrantLifetime = time.Hour; GrantMintSlack = 5*time.Minute; EngineRecordRetention = time.Hour; MinDeadline = 3*time.Minute; MaxDeadline = 50*time.Minute; PassEvery = 5*time.Second; FailedRetention = 90*24*time.Hour; MaxResultBytes = 64 << 10; MaxOverrideBytes = 8192; MaxPutBytes = 5 << 30; ScratchFloorGiB = 20; ScratchHeadroom = 8 << 30)`. `EngineRecordRetention` and `MaxOverrideBytes` are plan 1 measurements.
+ - `func DeadlineSleep(start time.Time, deadline time.Duration, expiry time.Time) time.Duration`: the earlier of `start+deadline` and `expiry−StopGrace`, minus `start` (may be ≤ 0). Plan 3's deadline container and local runner both use it.
+ - `func EphemeralGiB(sourceBytes int64) int`: 0 when `ceil((bytes+8 GiB)/GiB) <= 20`, else that figure (at most 200).
+ - `type Limits struct{ VideoMax, VideoMaxHi, AudioMax time.Duration; VideoBytes, AudioBytes int64; AccountMinutes int64; Short, Long, AccountShort, AccountLong, AccountActive, PerMinute, Burst, Queue int }` and `func ParseLimits(v string) (Limits, error)`: comma-separated `key=value`; keys `video_max`, `video_max_hi`, `video_bytes`, `audio_max`, `audio_bytes`, `account_minutes`, `short`, `long`, `account_short`, `account_long`, `account_active`, `per_minute`, `burst`, `queue`; durations in Go syntax, bytes as an integer or `<n>GiB`/`<n>MiB`; `""` gives `2h,30m,40GiB,8h,10GiB,0,6,2,2,1,20,30,10,200`; unknown, duplicate, negative or zero-count keys are errors; `account_minutes` may be 0.
+ - `func (l Limits) MaxBytes(preset string) int64`, `func (l Limits) Granted(k ClassKey) time.Duration` (the class figure, or the preset maximum for long).
+ - Error codes as `const Code… = "…"` for every code in the deck's `media.job.*` rows plus `CodeRetired = "retired"`; `var HandlerCodes map[string]bool` (the codes a result object may carry: every `media.job.*` code except `grant_expired`, `deadline_exceeded`, `engine_unavailable`, `engine_lost`, `retired`, `store_changed`, `store_writes_denied`).
+ - Exit codes: `ExitDone = 0`, `ExitFailed = 1`, `ExitGrantExpired = 75`, `DeadlineExitReached = 0`, `DeadlineExitBadInput = 3`, `DeadlineExitStopped = 143`; container names `ContainerCodec = "codec"`, `ContainerDeadline = "deadline"`; env names `PayloadEnv = "CARLOS_MEDIA_JOB"`, `DeadlineEnv = "CARLOS_MEDIA_DEADLINE_S"`, `ExpiryEnv = "CARLOS_MEDIA_GRANT_EXPIRY"`.
+ - `func ClassifyStop(resultErr string, codecExit, deadlineExit *int) string`: `resultErr` when it is in `HandlerCodes`; else `grant_expired` when codec exited 75; else `deadline_exceeded` when the deadline container exited `DeadlineExitReached`; else `engine_failed`.
+ - Payload (`payload.go`), the codec's whole input, one env var:
+ ```go
+ const PayloadVersion = 1
+ type Transfer struct {
+ URL string `json:"u,omitempty"` // scheme://host/escaped-path, no query; empty for outputs
+ Name string `json:"n,omitempty"` // output file name; its URL is Transfers.OutPrefix + Name
+ Method string `json:"m"`
+ Date string `json:"d"` // X-Amz-Date
+ SignedHeaders string `json:"sh"`
+ Signature string `json:"sg"`
+ Header map[string]string `json:"h,omitempty"` // the exact signed headers to send
+ }
+ type Transfers struct {
+ Algorithm string `json:"a"`
+ Credential string `json:"c"`
+ Token string `json:"t"` // X-Amz-Security-Token, sent once for all five
+ Expires int `json:"x"` // X-Amz-Expires
+ Source Transfer `json:"src"`
+ OutPrefix string `json:"op"`
+ Outputs []Transfer `json:"out"`
+ Result Transfer `json:"res"`
+ }
+ func (t Transfers) URL(x Transfer) string // base + "?" + the seven X-Amz-* query parameters, url.QueryEscape'd
+ type JobLimits struct {
+ SourceBytes int64 `json:"b"`
+ GrantedMS int64 `json:"g"`
+ GrantedBy string `json:"gb"` // "class" | "allowance"
+ MaxMS int64 `json:"d"`
+ MaxHiMS int64 `json:"dh"` // video sources above 1080p; 0 for audio
+ OutputBytes int64 `json:"o"`
+ }
+ type Payload struct {
+ V int `json:"v"`
+ Execution string `json:"x"`
+ Preset string `json:"p"`
+ Limits JobLimits `json:"l"`
+ Expiry int64 `json:"e"` // grant expiry, Unix seconds
+ Transfers Transfers `json:"tr"`
+ }
+ func (p Payload) Validate() error // version, 32-hex execution, known preset, 3 outputs named OutputNames(preset), GET source, PUT outputs and result
+ ```
+ - Result (`result.go`):
+ ```go
+ const ResultVersion = 1
+ type SourceFacts struct {
+ DurationMS int64 `json:"duration_ms"`
+ Width int `json:"width,omitempty"`
+ Height int `json:"height,omitempty"`
+ VideoCodec string `json:"video_codec,omitempty"`
+ AudioCodec string `json:"audio_codec,omitempty"`
+ }
+ type OutputFact struct {
+ Name string `json:"name"`
+ Bytes int64 `json:"bytes"`
+ ETag string `json:"etag"` // "" when an upload retry met 412 (plan 3 Task 6); the console takes HEAD's
+ ContentType string `json:"content_type"`
+ Width int `json:"width,omitempty"`
+ Height int `json:"height,omitempty"`
+ }
+ type Result struct {
+ V int `json:"v"`
+ Execution string `json:"execution"`
+ Error string `json:"error,omitempty"`
+ Source *SourceFacts `json:"source,omitempty"`
+ FFmpeg string `json:"ffmpeg,omitempty"`
+ Outputs []OutputFact `json:"outputs,omitempty"`
+ }
+ func ParseResult(b []byte, execution, preset string) (Result, error) // strict decode; version 1; execution matches; Error in HandlerCodes or empty; when empty: Source set, exactly OutputNames(preset), sizes in 1..MaxPutBytes
+ ```
+ - Engine and grants (`engine.go`):
+ ```go
+ type RunRequest struct {
+ Execution string
+ Class ClassKey
+ Payload []byte // JSON of Payload
+ DeadlineS int64
+ GrantExpiry time.Time
+ EphemeralGiB int
+ }
+ type Task struct {
+ ARN, StartedBy, StopCode string
+ Stopped bool
+ StartedAt, StoppedAt time.Time // zero when ECS has none
+ CodecExit, DeadlineExit *int
+ }
+ type Rejected struct{ Retryable bool; Reason string } // no task was created
+ func (r *Rejected) Error() string
+ type Misconfigured struct{ Revision, Check string }
+ func (m *Misconfigured) Error() string
+ type Engine interface {
+ Run(ctx context.Context, req RunRequest) (arn string, err error) // *Rejected, or any other error = ambiguous
+ Describe(ctx context.Context, arns []string) (found []Task, missing []string, err error)
+ ListByStartedBy(ctx context.Context, execution string) (Task, bool, error) // RUNNING and STOPPED lists, described, matched on startedBy
+ Stop(ctx context.Context, arn, reason string) error
+ CheckRevision(ctx context.Context, class ClassKey) error // nil or *Misconfigured
+ }
+ var ErrNotFound, ErrDenied, ErrResultTooLarge error
+ type ObjectHead struct{ Size int64; ETag string } // ETag unquoted
+ type OutputFile struct{ Name, ContentType string }
+ type GrantRequest struct {
+ Bucket, SourceKey, SourceETag, OutputPrefix, Execution string
+ Outputs []OutputFile
+ }
+ type Grants interface {
+ Head(ctx context.Context, bucket, key string) (ObjectHead, error) // conversion role; ErrNotFound, ErrDenied
+ Grant(ctx context.Context, r GrantRequest) (Transfers, time.Time, error) // conversion role; the expiry
+ ReadResult(ctx context.Context, execution string) ([]byte, error) // console role; ErrNotFound, ErrResultTooLarge
+ DeleteResult(ctx context.Context, execution string) error // absent is success
+ DeleteOutputs(ctx context.Context, bucket string, keys []string) error // console role; absent is success
+ }
+ type ImageInfo struct {
+ Digest string `json:"digest"`
+ BuiltAt string `json:"built_at"` // RFC 3339
+ FFmpeg string `json:"ffmpeg"`
+ }
+ ```
+- Produces in `internal/media/mediatest`: `FakeEngine` and `FakeGrants` implementing the two interfaces, safe for concurrent use, with `Now func() time.Time`:
+ - `FakeEngine.Script(outcomes ...RunOutcome)` queues the next `Run` answers: `RunOK`, `RunRejectedRetryable`, `RunRejectedFinal`, `RunAmbiguousCreated` (task created, error returned), `RunAmbiguousNotCreated`. Tasks stay `PENDING` until `Start(arn, at)`, then run until `Finish(arn, at, codecExit)`, `DeadlineFires(arn, at)` (deadline 0, codec 137) or `FailStart(arn, at)` (stopped, no start). `Expire(arn)` drops a stopped record. `Misconfigure(class, check)`. `Requests(execution) []media.RunRequest`.
+ - `FakeGrants.Objects` (bucket/key → size, ETag, infected), `Results` (execution → bytes), `Granted` (output key → executions ever granted a PUT on it), `Deleted` (keys). `Grant` returns transfers on `https://<bucket>.s3.test/` with expiry `Now()+GrantLifetime`; `Head` answers `ErrDenied` for an infected object.
+- Produces in `internal/mediajobs` (declared here, bodies in Task 2): `var Schema []string`; `type StoreGuard interface{ Lock(account, app string) (unlock func()); Current(ctx context.Context, account, app string) (StoreFacts, error) }`; `type StoreFacts struct{ Exists bool; Incarnation, Bucket, Region string; WritesDenied bool }`; `type Deps struct{ Engine media.Engine; Grants media.Grants; Stores StoreGuard; Allowance func(ctx context.Context, account string) (minutes int64, err error); Limits media.Limits; Logf func(string, ...any) }`; `func New(db *sql.DB, d Deps) *Jobs`; `type SubmitRequest struct{ Account, App, Incarnation, Bucket, Key, ETag, Preset, Class string; Bytes int64; Now time.Time }`; `type Job struct{ Account, App, Incarnation, ID, Key, ETag, Preset, Class, Bucket, State, Execution, TaskARN, ErrorCode string; Bytes, GrantedS, DeadlineS, ChargedMS, SourceMS int64; StartFailures int; TaskStopped, Settled bool; Result *media.Result; SubmittedAt, DispatchedAt, CleanupDue, RetiredAt, EndedAt time.Time }`; `func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error)`; `Lookup(ctx, account, app, incarnation, id string) (Job, bool, error)` (never a retired row); `Counts(ctx, account string) (accountActive, deploymentQueued int, err error)`; `ChargedMinutes(ctx, account string, monthStart time.Time) (int64, error)`; `type Usage struct{ Charged, Reserved int64 }` (units); `Usage(ctx, account string, monthStart time.Time) (Usage, error)`; `Pass(ctx, now)`, `Track(ctx, now)`, `Recover(ctx, now)`, `DispatchNext(ctx context.Context, class string, now time.Time) (*Launch, error)` (nil, nil when nothing is eligible), `Launch(ctx context.Context, l *Launch, now time.Time) error`, `Cleanup(ctx, now)`, `Prune(ctx, now)` (each `error`); `type Scope struct{ Account, App string }`; `Retire(ctx context.Context, s Scope, now time.Time) (pending int, err error)`; `type Summary struct{ Queued, Running map[string]int; Done24h, Failed24h int; FailedByCode map[string]int }`; `Summary(ctx, now time.Time) (Summary, error)`.
+
+The simulation's steps, verbatim from spec §5.3: submit, dispatch, launch rejection, an ambiguous launch error, task start failure, task stop, a crash after launch with the task finishing before recovery, task record expiry, console restart, cleanup, app purge, store destroy and recreate, and two accounts' audio and video jobs dispatched and settled concurrently, including runs that end exactly at the deadline and inside the stop grace. Its invariants, verbatim:
+
+- **I1. Discoverable.** Every job that is not terminal and settled is a `queued` or `running` row, and the pass finds work only by querying rows.
+- **I2. Charged exactly once.** `settled` goes from false to true in the transaction that writes `charged_ms` and the terminal state, and nothing writes `charged_ms` afterwards.
+- **I3. Never undercharged.** `charged_ms` is at least the time ECS reports the task ran, or the row's full bound when ECS cannot say.
+- **I4. Obligations retained.** A row that is unsettled, has `cleanup_due` set, or has `task_stopped` false is never deleted.
+- **I5. One execution.** A `done` row's outputs are the keys of its own `execution_id`, and no other execution ever held a request for them.
+- **I6. Capacity.** The number of rows with a dispatched execution and `task_stopped` false never exceeds the dispatch cap, whatever their state or retirement.
+- **I7. Store lifetime.** No row is admitted, dispatched or committed against a store incarnation other than its own, and a store is not destroyed while one of its rows has `task_stopped` false.
+- **I8. Allowance** (§5.3's last sentence): no account is ever reserved or charged past its allowance: for every account with a limit, charged plus reserved this UTC month never exceeds twice the limit, in units.
+
+- [ ] **Step 1: Write the type tests** (`internal/media`):
+ - `TestJobIDVector`: `JobID("uploads/a1b2.mov", "9b2cf535f27731c974343645a3985328", "video-720p", "short")` equals the hex of `sha256("v1\x00uploads/a1b2.mov\x009b2cf535f27731c974343645a3985328\x00video-720p\x00short\x00")[:16]` computed in the test, is 32 characters, and changes when only the class changes.
+ - `TestJobIDAndPrefixWithMultipartETag` (Review Focus 2): ETag `"9b2cf535f27731c974343645a3985328-12"` with quotes is refused by the door's normaliser test helper; unquoted, `OutputPrefix("uploads/x.mov", "9b2c…-12", "video-720p", e)` is `derived/uploads/x.mov/9b2c…-12/video-720p/<e>/`.
+ - `TestValidKey`: accepts `uploads/a1b2.mov`, `uploads/IMG 0001 (1).MOV`, `uploads/vidéo.mov`, `a+b%20c.mov`, a 512-byte key; refuses `""`, 513 bytes, `a\x00b`, `a\x7fb`, `derived/x`, `x/../y`, `./x`, `x/.`, invalid UTF-8.
+ - `TestPickClass`: video 1<<30 short, 1<<30+1 long, explicit long at 1 byte long, explicit short at 2 GiB long; audio 256<<20 short, +1 long.
+ - `TestParseLimits`: `""` gives the defaults; `video_max=1h,audio_bytes=5GiB` overrides two; `bogus=1`, `short=0`, `video_max=1h,video_max=2h`, `video_bytes=-1` are errors; `account_minutes=0` is fine.
+ - `TestEphemeralGiB`: 0 bytes 0; 12 GiB 0 (20 exactly); 12 GiB+1 21; 40 GiB 48.
+ - `TestDeadlineSleepTable`: start 12:00, deadline 50 min, expiry 13:00: 50 min; expiry 12:40: 39 min 30 s; expiry 12:00:20: −10 s; spec §5.5's PENDING case (grant at 12:00, timer starting 12:12, deadline 50 min): 47 min 30 s, so the task ends by 12:59:30.
+ - `TestClassifyStop`: table over (result error, codec exit, deadline exit): (`no_video`, 1, 143) `no_video`; (`bogus`, 1, 143) `engine_failed`; ("", 75, 143) `grant_expired`; ("", 137, 0) `deadline_exceeded`; ("", 2, 143) `engine_failed`; ("", nil, nil) `engine_failed`.
+ - `TestParseResult`: a success result round-trips; wrong execution, version 2, unknown error code, a missing or extra output name, a 0-byte or over-5-GiB output, and 64 KiB + 1 bytes are each refused.
+ - `TestTransfersURLEscapesKeys` (Review Focus 1, `payload_test.go`): a source URL built for key `uploads/IMG 0001 (1).MOV` ends `/uploads/IMG%200001%20%281%29.MOV?` and carries `X-Amz-Security-Token` once with `+`, `/` and `=` query-escaped.
+ - `TestPayloadCarriesNoJobID` (spec §10): a payload built by `mediatest.FakeGrants` for a known job holds neither the job id nor the strings `account` or `app` as keys; the bucket name in the hosts is the one exception (reported to Paul, see plan 3's rollout notes).
+ - `TestWorstCasePayloadFits`: a payload with a 512-byte key of 3-byte UTF-8 runes, a 1,400-character token and 64-hex signatures marshals, inside the RunTask override structure plan 3 builds (`{"containerOverrides":[{"name":"codec","environment":[{"name":"CARLOS_MEDIA_JOB","value":…}]},{"name":"deadline","environment":[…two values…]}],"ephemeralStorage":{"sizeInGiB":48}}`), to at most `MaxOverrideBytes`.
+- [ ] **Step 2:** Run `go test ./internal/media/... -count=1`. Expected: FAIL (undefined).
+- [ ] **Step 3:** Implement `internal/media` and `mediatest`. `JobID`: `hex.EncodeToString(sum[:16])`. Then declare `internal/mediajobs` with every body returning `errNotImplemented`, and run the Step 1 command. Expected: PASS.
+- [ ] **Step 4: Write the simulation** in `internal/sim/mediajobs` (model `internal/sim/regionha`'s shape: `runSeed(seed int64, trace bool) *world`, `MEDIASIM_SEEDS` (default 200) and `MEDIASIM_SEED=n` to replay one seed with its trace, `TestSeedDeterministic`). The world: an in-memory SQLite database per seed (`file:mediasim<seed>?mode=memory&cache=shared`, `SetMaxOpenConns(1)`, `mediajobs.Schema` applied), a fake clock starting 2026-11-16T00:00:00Z, a `FakeEngine`, `FakeGrants`, a fake `StoreGuard` over a map of store records (incarnation, writes-denied) with a real `sync.Mutex` per app, two accounts each with two apps, allowances drawn per seed from {0, 20, 30, 600} minutes, and a `*mediajobs.Jobs`. Each step picks one action by weight: submit (random preset, class, size from 1 KiB to 50 GiB, key from a pool of six, two of which are overwritten with a new ETag mid-run); `Track`; `Recover`; `DispatchNext` for a random class, holding the returned launch; `Launch` of a held launch; script a launch rejection (retryable or final) or an ambiguous error (created or not); engine start, start failure, finish with exit 0 (the fake writes the result object and three outputs for that execution, `source_ms` at most the granted duration), exit 1 with a handler error, exit 75 with no result; deadline fires exactly at `deadline_s` or at a random instant inside the 30 s grace; expire a stopped record older than retention; console restart (drop held launches, build a new `Jobs` on the same database); `Cleanup`; `Prune`; app purge (lock, `Retire(Scope{acct, app})`, stop tasks; refused while pending, the purge then retried later); store destroy (same, refused while pending) and recreate with a new incarnation; toggle writes-denied; advance the clock by 1 s to 2 h. After every step `check(w)` evaluates I1 to I8 from raw SQL rows and the fakes' records with its own arithmetic (never by calling `mediajobs.Usage`), keeping a snapshot to detect I2 and I4 across steps.
+- [ ] **Step 5: Write the witnesses** (`witness_test.go`):
+ - `TestCheckerCatchesEachInvariant`: for each of I1 to I8, a world brought to a clean state, then one direct SQL or fake write that violates exactly that invariant (a `running` row with `settled` 1 and no state change for I2, a deleted unsettled row for I4, a done row whose output key was also granted to another execution for I5, …); the checker reports that invariant's id and no other.
+ - Named interleavings, each a fixed action list: `TestWitnessCrashAfterLaunchTaskFinishesBeforeRecovery` (ambiguous-created, finish exit 0, restart, `Recover`, `Track`: `done`, charged ECS's time); `TestWitnessRejectedVersusAmbiguous` (a final rejection: `failed engine_unavailable` uncharged at once; a retryable one: back to `queued` once, `failed engine_unavailable` the second time; ambiguous-not-created: `engine_lost` charged the full bound after retention); `TestWitnessDeadlineExactAndInsideGrace`; `TestWitnessStoreDestroyRefusedWhileRunning`; `TestWitnessRestartStartsNoFifthTask` (with `short=4`, four running, restart: no fifth dispatch until one stops); `TestWitnessTwentyMinutesLeft` (§9: an account at 20 minutes left submits a long audio file and a video; never reserved or charged past 20).
+- [ ] **Step 6:** Run `go test ./internal/sim/mediajobs/ -count=1`. Expected: FAIL: `TestMediaJobs` and the named witnesses fail on `errNotImplemented`; `TestCheckerCatchesEachInvariant` and `TestSeedDeterministic` pass.
+- [ ] **Step 7:** Commit (local only; do not push until Task 2 is green): `media: shared types, job API and lifecycle simulation`.
+
+---
+
+### Task 2: The `media_jobs` table and its transitions **[Astra: billing, termination]**
+
+**Files:**
+- Modify: `internal/mediajobs/jobs.go`, `internal/mediajobs/schema.go`
+- Create: `internal/mediajobs/dispatch.go`, `track.go`, `retire.go`, `metering.go`, `jobs_test.go`
+
+**Interfaces:**
+- Consumes: Task 1's declarations and fakes.
+- Produces: Task 1's `mediajobs` API, implemented. Schema (`Schema`):
+ ```sql
+ CREATE TABLE IF NOT EXISTS media_jobs (
+ account TEXT NOT NULL, app TEXT NOT NULL, incarnation TEXT NOT NULL, job_id TEXT NOT NULL,
+ key TEXT NOT NULL, etag TEXT NOT NULL, bytes INTEGER NOT NULL, preset TEXT NOT NULL,
+ class TEXT NOT NULL, bucket TEXT NOT NULL, state TEXT NOT NULL, submitted_at INTEGER NOT NULL,
+ execution_id TEXT NOT NULL DEFAULT '', task_arn TEXT NOT NULL DEFAULT '',
+ dispatched_at INTEGER NOT NULL DEFAULT 0, granted_s INTEGER NOT NULL DEFAULT 0,
+ deadline_s INTEGER NOT NULL DEFAULT 0, task_stopped INTEGER NOT NULL DEFAULT 1,
+ start_failures INTEGER NOT NULL DEFAULT 0, charged_ms INTEGER NOT NULL DEFAULT 0,
+ settled INTEGER NOT NULL DEFAULT 0, source_ms INTEGER NOT NULL DEFAULT 0,
+ result TEXT NOT NULL DEFAULT '', error TEXT NOT NULL DEFAULT '',
+ cleanup_due INTEGER NOT NULL DEFAULT 0, retired_at INTEGER NOT NULL DEFAULT 0,
+ ended_at INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (account, app, incarnation, job_id));
+ CREATE INDEX IF NOT EXISTS media_jobs_live ON media_jobs (task_stopped, state);
+ CREATE INDEX IF NOT EXISTS media_jobs_by_account ON media_jobs (account, ended_at);
+ CREATE INDEX IF NOT EXISTS media_jobs_queue ON media_jobs (state, class, submitted_at);
+ ```
+ Times are Unix milliseconds; `task_stopped` starts 1 so a queued row never counts toward capacity.
+
+Rules the tests pin (spec §5.3, §7):
+- Every transition is one transaction whose `UPDATE` is guarded by the expected `state`, `execution_id` and `settled = 0`; a guard that matches no row is a dropped result, logged, not an error.
+- Dispatch, per class: deployment count of `execution_id != '' AND task_stopped = 0` for that class under its cap; candidates are non-retired `queued` rows of the class from accounts under their per-class cap, ordered by the account's `MAX(dispatched_at)` (never dispatched first), then `submitted_at`. Lock the row's app, `Stores.Current`: absent or another incarnation fails the row `store_changed`, `WritesDenied` fails it `store_writes_denied`, both uncharged and settled. Then in one transaction: recount capacity; compute `R = 2·limit·600000 − (charged + reserved)` units for the account this UTC month (no limit: unbounded); `granted_ms = min(class granted, R/w)`, `deadline_ms = min(class deadline, R/w − 30000)`, both floored to whole seconds; under `MinDeadline` the row waits when the account has another execution with `task_stopped = 0`, else fails `allowance_exceeded` uncharged; otherwise `running`, a new execution id, `dispatched_at`, `granted_s`, `deadline_s`, `task_stopped = 0`. `GrantedBy` is `class` when the class figure was the smaller or equal.
+- `Launch` (`type Launch struct` carries the dispatched `Job` and its `GrantedBy`, unexported; a restart drops it and the row goes to recovery): `Grants.Grant` (an error is a definitive rejection, retryable); build the payload with `JobLimits{SourceBytes: MaxBytes(preset), GrantedMS: granted_s·1000, GrantedBy, MaxMS: VideoMax or AudioMax, MaxHiMS: VideoMaxHi or 0, OutputBytes: MaxPutBytes}` and `Expiry` = the grant's; `Engine.Run` with `DeadlineS`, `GrantExpiry` and `EphemeralGiB(bytes)`. `*Rejected` or a grant error: in one transaction `task_stopped = 1`, `start_failures + 1`, then "never started" with the rejection's `Retryable`. Any other error: leave the row (recovery). Success: record `task_arn`.
+- Never started (from `Track`, always retryable; from `Launch`, as the rejection says): back to `queued` uncharged when retryable and `start_failures` is now 1; otherwise `failed engine_unavailable`, settled, `charged_ms = 0`, no cleanup.
+- `Track`: `Describe` every row with `task_stopped = 0` and an ARN; a retired row still running gets `Stop` (outside any transaction). Stopped with no start time: never started. Stopped with codec exit 0, not retired: `ReadResult`, `ParseResult`, `Head` each output (`size` equal; result ETag empty or equal), then `done`, `charged_ms = StoppedAt − StartedAt`, `source_ms = Result.Source.DurationMS`, `result` = the result JSON, settled, `task_stopped`, `cleanup_due = now`, `ended_at = now`. A read error other than `ErrNotFound` leaves the row for the next pass; after exit 0, a missing or unparseable result, an output `Head` of `ErrNotFound`, or a size or ETag mismatch is `failed engine_failed`, charged ECS's time. Any other stop, or a retired row: `failed` with `ClassifyStop` (`retired` for a retired row), charged ECS's time, settled, stopped, `cleanup_due = now`. Missing from `Describe` past `dispatched_at + deadline_s + 30 s + EngineRecordRetention`: `failed engine_lost`, `charged_ms = (deadline_s + 30) · 1000`, `cleanup_due = dispatched_at + GrantLifetime + GrantMintSlack`.
+- `Recover`: a `running` row with no ARN: `ListByStartedBy(execution)`; found: save the ARN in its own transaction, then nothing else this pass; not found past the same retention bound: "unknown" as above. Never `Run` again.
+- `Retire(scope)`: set `retired_at` on every non-retired row of the scope; a `queued` row becomes `failed retired`, settled, uncharged; then `Stop` every retired row with an ARN and `task_stopped = 0`; return the count of the scope's rows with `task_stopped = 0`. With a nil engine and such rows, return that count without stopping.
+- `Cleanup`: rows with `cleanup_due` in (0, now] and `task_stopped = 1`: `DeleteResult`, and for a non-`done` row `DeleteOutputs` of its three keys; then `cleanup_due = 0`.
+- `Prune`: delete rows `settled = 1 AND task_stopped = 1 AND cleanup_due = 0 AND (retired_at > 0 OR state = 'failed') AND ended_at < now − FailedRetention`.
+- Metering, units this UTC month: `done` ended this month: `w·source_ms`; other settled rows ended this month: `w·charged_ms`; `running` unsettled rows: `w·max(granted_s, deadline_s+30)·1000`. `ChargedMinutes` = ceiling of settled units ÷ 600000.
+
+- [ ] **Step 1: Write the failing tests** (`jobs_test.go`, fakes from Task 1, an in-memory database):
+ - `TestSubmitIsIdempotent`: two submits of one id answer the same job; the second `created == false`.
+ - `TestDispatchFitsTheReservation`: limit 30 (R = 60 min), a long video: `granted_s = 3600`, `deadline_s = 3000`, reservation 60 min; a second long video waits; after the first settles at 5 engine minutes, the second dispatches with `granted_s = 3300`.
+ - `TestDispatchUnderThreeMinutes`: R of 2 min with nothing running fails `allowance_exceeded` uncharged; with another execution running it stays `queued`.
+ - `TestClassesDispatchSeparately` (§9): both long places taken, an account's own long row waiting: its short row dispatches at once.
+ - `TestCapacityHeldUntilStopped`: a retired running row keeps its place until `Describe` reports it stopped.
+ - `TestLaunchRejectedThenUnavailable`, `TestNeverStartedRetriesOnce`, `TestAmbiguousLaunchRecovers`, `TestUnknownChargesFullBound`, `TestRetiredRowNeverCommitsDone`, `TestResultForAnotherExecutionDropped`, `TestOutputSizeMismatchFails`, `TestCleanupSkipsDoneOutputs`, `TestPruneKeepsObligations`.
+ - `TestChargeLandsInTheMonthItEnded` (Review Focus 4): dispatched 2026-11-30T23:58Z, finished 2026-12-01T00:03Z: `Usage` for November counts its reservation before the finish and nothing after; December counts its charge.
+ - `TestWritesDeniedBetweenSubmitAndDispatch` (Review Focus 5): writes-denied set after submit: `failed store_writes_denied`, uncharged; set while running: the row commits `done`.
+ - `TestAudioWeighsATenth`: a done 60-minute audio job is 6 charged minutes; a running long audio row reserves `max(8 h, 50.5 min)·0.1` = 48 minutes.
+- [ ] **Step 2:** Run `go test ./internal/mediajobs/ -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. Every transaction uses `BeginTx` and its `*sql.Tx` throughout; network calls happen between transactions.
+- [ ] **Step 4:** Run `go test ./internal/mediajobs/ ./internal/sim/mediajobs/ -count=1`. Expected: PASS, including `TestMediaJobs` at 200 seeds and every witness. Then once, `MEDIASIM_SEEDS=3000 go test ./internal/sim/mediajobs/ -run TestMediaJobs -count=1`, and record the seed count and time in the commit body.
+- [ ] **Step 5:** Commit: `media: the job table, its transitions and the pass`. Astra reviews Tasks 1 and 2 together (billing, termination; the brief names I1 to I8 and asks for an interleaving the sim does not reach).
+
+---
+
+### Task 3: Store provenance, incarnation and verification **[Astra: security gate, production storage]**
+
+**Files:**
+- Modify: `internal/objstore/objstore.go` (`Record`, :154-185; new `Conversion` block), `internal/objstore/walk.go` (first grant write, :280-286), `internal/objstore/walk_test.go`
+- Create: `internal/storecfg/storecfg.go`, `internal/storecfg/fake.go`, `internal/storecfg/storecfg_test.go`
+- Create: `internal/console/mediastore.go`, `internal/console/mediastore_test.go`
+
+**Interfaces:**
+- Produces in `internal/objstore`: `type Conversion struct{ Incarnation string \`json:"incarnation"\`; Minted bool \`json:"minted,omitempty"\`; VerifiedAt *time.Time \`json:"verified_at,omitempty"\`; Uploads *Uploads \`json:"uploads,omitempty"\` }`, `type Uploads struct{ Origins []string \`json:"origins"\`; CORSHash, LifecycleHash string; At time.Time; By string }` (json `cors_hash`, `lifecycle_hash`, `at`, `by`), field `Record.Conversion *Conversion \`json:"conversion,omitempty"\`` (additive; `release.PurgeApp`'s local struct ignores it, asserted by a new `TestPurgeGuardIgnoresConversionBlock`). `func NewIncarnation() (string, error)` (32 hex). `GrantInFor`'s first write sets `Conversion{Incarnation, Minted: true}` only when `adoptBucket == ""`; an adopted bucket, even under the minted name, never gets `Minted`.
+- Produces in `internal/storecfg` (stdlib and `internal/objstore` only):
+ - `type Facts struct{ Owner, Region, Encryption, Versioning string; HasPolicy bool; CORS, Lifecycle []byte }` (`Encryption` is the default rule's algorithm, `""`, `AES256` or `aws:kms`; `CORS` and `Lifecycle` the canonical JSON of what the bucket holds, nil when none).
+ - `type Buckets interface{ Inspect(ctx context.Context, bucket string) (Facts, error); PutUploads(ctx context.Context, bucket string, origins []string) error; DeleteUploads(ctx context.Context, bucket string) error }`.
+ - `func UploadsCORS(origins []string) []byte` and `func UploadsLifecycle() []byte`: the canonical JSON of the one rule each (CORS: methods `GET`, `HEAD`, `PUT`, headers `*`, expose `ETag`, max age 3600, the origins sorted; lifecycle: id `carlos-abort-multipart`, empty prefix, `AbortIncompleteMultipartUpload` after 1 day, enabled). `func Hash(b []byte) string` (hex SHA-256).
+ - `func Verify(f Facts, want Want) (check string)`: `""` or the first failing check of `name`, `owner`, `region`, `encryption`, `versioning`, `policy`, `lifecycle`, `cors`, where `type Want struct{ Bucket, MintedName, Account, Region string; Uploads *objstore.Uploads }`: name equals `MintedName`; owner equals `Account`; region equals; encryption `AES256`; versioning `""`; no policy; lifecycle nil or its hash equals `Uploads.LifecycleHash`; CORS nil or its hash equals `Uploads.CORSHash`.
+ - `type Fake struct{ Facts map[string]Facts; … }` implementing `Buckets`.
+- Produces in `internal/console`: `Config.StoreConversion bool` (`CARLOS_STORE_CONVERSION=1`), `Config.StoreBuckets storecfg.Buckets`, `Config.StoreAccountID string` (the deployment's AWS account id, set by plan 3), and `func (s *Server) mediaStoreEligible(ctx context.Context, acct *Account, app string) (rec *objstore.Record, code, check string, err error)`, called with the walk lock held: no record or no `Provisioned` → `no_store`; `Conversion` with `Minted` or `VerifiedAt` → eligible; otherwise `Inspect` and `Verify`; a pass writes `Conversion{Incarnation: NewIncarnation(), VerifiedAt: now}` (keeping any `Uploads`) through `objstore.PutIn` with the record's ETag; a failure answers `store_unverified` and the check, and writes nothing.
+
+- [ ] **Step 1: Write the failing tests:** `TestFirstGrantRecordsMinted`, `TestAdoptedUnderMintedNameIsNotMinted`, `TestPurgeGuardIgnoresConversionBlock` (objstore); `TestVerifyTable` (one passing `Facts` and one failure per check, in the order above; SSE-KMS → `encryption`; `Suspended` → `versioning`; a lifecycle equal to `UploadsLifecycle()` with a matching recorded hash passes, with no record fails `lifecycle`); `TestUploadsCORSIsCanonical` (origin order does not change the bytes); `TestEligibleVerifiesOnceAndRecords`, `TestEligibleRefusalWritesNothing`, `TestRecreatedStoreHasANewIncarnation` (console, with `storecfg.Fake`).
+- [ ] **Step 2:** Run `go test ./internal/objstore/ -run 'TestFirstGrantRecordsMinted|TestAdoptedUnderMintedName|TestPurgeGuardIgnoresConversion' -count=1 && go test ./internal/storecfg/ -count=1 && go test ./internal/console/ -run 'TestEligible|TestRecreatedStore' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun Step 2's command and `go test ./internal/objstore/ -run 'TestPurgeGuard|TestGrant' -count=1`. Expected: PASS.
+- [ ] **Step 5:** Commit: `objstore: store incarnation and conversion provenance`.
+
+---
+
+### Task 4: The refusal gate **[Astra: security gate]**
+
+**Files:**
+- Create: `internal/media/gate.go`, `internal/media/gate_test.go`
+
+**Interfaces:**
+- Produces: `type TaskDefinition struct{ ARN, TaskRoleARN, PIDMode, CPUArchitecture string; Containers []ContainerDef }`, `type ContainerDef struct{ Name, Image, User string; Essential, ReadOnlyRoot, DropsAll bool; StopTimeout *int; DependsOn []Dependency; Volumes []string }`, `type Dependency struct{ Container, Condition string }`, and `func CheckTaskDefinition(td TaskDefinition) error` returning `*Misconfigured{Revision: td.ARN, Check: …}` for the first failing check, in order: `containers` (exactly `deadline` and `codec`), `essential` (both), `depends_on` (`codec` depends on `deadline` with `START`; `deadline` depends on nothing), `stop_timeout` (both exactly 30), `task_role` (empty), `pid_mode` (empty), `shared_volume` (no volume name in both containers' lists), `image` (equal and containing `@sha256:`), `user` (both set and not `0`, `root` or `0:…`), `read_only` (both), `capabilities` (both drop `ALL`), `arm64` (`ARM64`). Plan 3's adapter fills `TaskDefinition` from `DescribeTaskDefinition` and caches the verdict per revision ARN.
+
+- [ ] **Step 1: Write the failing test** `TestCheckTaskDefinition`: the module's intended definition passes; one mutation per check fails with that check's name (no `dependsOn`; `condition: COMPLETE`; deadline also depending on codec; stop timeout 29 and nil; a task role; `pidMode: task`; a volume in both; `:latest` instead of a digest; two different digests; user `0`; writable root; capabilities not dropped; `X86_64`).
+- [ ] **Step 2:** Run `go test ./internal/media/ -run TestCheckTaskDefinition -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: refuse an engine task definition that loosens the deadline`.
+
+---
+
+### Task 5: The door **[Astra: security gate]**
+
+**Files:**
+- Create: `internal/console/apimedia.go`, `internal/console/media_copy.go`, `internal/console/medialimit.go`, `internal/console/mediawire.go`, `internal/console/apimedia_test.go`
+- Modify: `internal/console/routedecls.go` (after :1032), `internal/console/server.go` (Config beside `PDFEngine`, :812-814; `NewServer` defaults beside :1954-1958 and construction beside :2005), `internal/console/store.go` (append `mediajobs.Schema` after the `pdf_renders` statements, :378-393), `internal/console/store_gate.go` (beside :238), `internal/console/testdata/claim-routes.txt`, `internal/console/claim_invariant_fixtures_test.go`
+
+**Interfaces:**
+- Consumes: Tasks 1 to 4; `apiAccountApp` (`internal/console/apicli.go:47`), `storeWalks.lock`, `jsonErrorCode` (`authcli.go:631`), `readJSONStrictLimit`.
+- Produces: `Config.MediaEngine media.Engine`, `Config.MediaGrants media.Grants`, `Config.MediaLimits media.Limits`, `Config.MediaRegion string`, `Config.MediaImage media.ImageInfo`; `s.media *mediajobs.Jobs` (built in `NewServer` over `s.store.db` always; `Deps.Engine` nil when unconfigured); `func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request)`, `handleAPIMediaGet`; `type mediaJobAnswer struct` (the GET shape below); `func mediaText(key string, args ...any) string`; `func newMediaLimiter(l media.Limits) *mediaLimiter` with `acquire(account string, now time.Time) *mediaRefusal` (token bucket, PDF limiter's shape); `func (s *Server) mediaAllowance(ctx context.Context, account string) (int64, error)` (planExempt → 0; no catalog → `MediaLimits.AccountMinutes`; else `MediaMinutesMonth`, 0 when at least `sponsorMost`; Task 6 adds the field, this task reads it through a stub returning 0 until then); `type consoleStoreGuard struct{ s *Server }` implementing `mediajobs.StoreGuard` over `storeWalks` and `objstore.GetIn(…, "")`.
+- `store_gate.go`: `"media_jobs": {Sqid: "account", App: "app", Refuse: "media conversion requires claims mode off"}`.
+- POST checks, in order, each before any row is written (spec table, plus three this plan places): `MediaEngine == nil` or `HostClaim` → 503 `not_configured`; body not strict JSON → `readJSONStrictLimit`'s 400; `!ValidKey` → 400 `bad_key`; preset → 400 `unknown_preset`; class not `""`, `short`, `long` → 400 `unknown_class`; then under `storeWalks.lock(acct, app, "")`: `mediaStoreEligible` (`no_store` 409, `store_unverified` 409 with the check's phrase); `Provisioned.Region != MediaRegion` → 409 `no_engine_in_region`; `WritesDenied` → 402 `store_writes_denied`; `Grants.Head`: `ErrNotFound` 404 `source_not_found`, `ErrDenied` 409 `source_unreadable`; size 0 or over `MaxBytes(preset)` → 413 `source_too_large`; resolve the class (`PickClass`) and the job id; **an existing row → 200 with it** (no further check); `Engine.CheckRevision(class)` → 503 `engine_misconfigured`; plan cap: `ChargedMinutes` at least twice the allowance → 402 `plan_limit` with `capMessage("cli.cap.media_minutes", used, limit)`; `Counts`: account active at `AccountActive` → 429 `too_many_jobs` (`Retry-After: 30`); deployment queued at `Queue` → 503 `queue_full` (`Retry-After: 60`); limiter → 429 `rate_limited` (`Retry-After` = seconds to the next token); then `Submit` and 202.
+- GET: `apiAccountApp`, then the store record's current incarnation (no lock); `Lookup`; absent or retired → 404 `job_not_found`.
+- Answer (both doors): `{"id","state","key","preset","class","submitted_at"}`, plus on `failed` `"error": {"code","message"}` (message `mediaText("media.job."+code, …)`; `source_too_long` and `needs_long_class` filled with the limit as `2h0m`→`2 hours` by `mediaDuration`), plus on `done` `"source": {"duration_ms","width","height","video_codec","audio_codec"}`, `"ffmpeg"`, and `"outputs": [{"key","bytes","etag","content_type","width","height"}]` with `key` = `OutputPrefix(…) + name`.
+
+- [ ] **Step 1: Write the failing tests** (`apimedia_test.go`, `mediatest` fakes, `storecfg.Fake`, the PDF door tests' fixture shape):
+ - `TestDoorRefusalOrder`: one subtest per row, each set up so every earlier check passes; status, code and deck message asserted; `media_jobs` has zero rows after each.
+ - `TestDoorKeysPeopleActuallyUpload` (Review Focus 1): the four phone-style keys answer 202, echo the key byte for byte, and the fake engine's payload source URL fetches that object from `FakeGrants`; `x/../derived/y.mov` is 400 `bad_key`.
+ - `TestRepeatPostIsNotRateLimited` (Review Focus 3): 50 POSTs of one key within a second: one 202, 49 200s with the same id, one `Submit` row, zero 429s.
+ - `TestDoorOtherAppOrAccount`: a Service token bound to `shop` on `/apps/{acct}/blog/media/conversions` and an account-wide token of another account both get 404, and the fake grants see no `Head`.
+ - `TestDoorInfectedSourceWithEnforcementOff` (§9): the store record has no `Enforce`, the object is tagged infected in `FakeGrants`: 409 `source_unreadable`.
+ - `TestGetHidesRetiredAndOtherIncarnations`, `TestGetDoneAnswerShape`, `TestGetFailedMessageComesFromTheDeck` (a result whose error is `no_video`: the answer's message is the deck's, whatever text the result carried).
+ - `TestMediaDoorsRefuseOnHostClaim`: `HostClaim` true → 503 `not_configured`.
+- [ ] **Step 2:** Run `go test ./internal/console/ -run 'TestDoor|TestRepeatPost|TestGet|TestMediaDoors' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. Register `{Pattern: "POST /api/cli/apps/{account}/{app}/media/conversions", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIMediaSubmit}` and the GET with `{id}`. Add both to `claim-routes.txt` and fixture them `claimRead("media conversion is off on a host-claim console: the door answers 503 and writes nothing")`.
+- [ ] **Step 4:** Run Step 2's command plus `-run 'TestClaimConsoleRouteCensus|TestEveryCLIDoorNamesItsRoles|TestClaimSQL|TestStoreGate'`. Expected: PASS.
+- [ ] **Step 5:** Commit: `console: media conversion door`.
+
+---
+
+### Task 6: Allowance, metering and the plan cap **[Astra: billing]**
+
+**Files:**
+- Modify: `internal/plans/catalog.go` (`Limits` :53, `nonNegative` :364, `Effective` packs :425-439, `generous` :481), `internal/plans/catalog_test.go`
+- Modify: `internal/console/plangrace.go` (:18, :25, :66, :75, :86), `internal/console/plangracepass.go` (:329-336, :473-474), `internal/console/planmeasure.go` (:62-64), `internal/console/billingusage.go` (:24, :29, :87, :136, :195), `internal/console/billingpage.go` (:731), `internal/console/billingpage_copy.go`, `internal/console/plancaps_copy.go`, `internal/console/plansponsor.go` (:92), `deploy/billing/sponsored-unlimited.json`, `internal/console/planexempt_test.go` (`planExemptSites`, :305-309)
+- Create: `internal/console/planmedia.go`, `internal/console/planmedia_test.go`
+
+**Interfaces:**
+- Produces: `Limits.MediaMinutesMonth int \`json:"media_minutes_month,omitempty"\``; `Pack.Adds.MediaMinutesMonth` honoured in `Effective` through `addPack` and clamped by `ce.MediaMinutesMonth`; `const capMedia capID = "media"` (monthly, ceiling at 2x, `graceEnd` the 1st of next month, in `capOrder` after `capPDF`, in `usageCaps` with label `usage.label.media`); stage `media_refused` in `planStage` when `Used/2 >= MediaMinutesMonth`; `mediaAllowance` from Task 5 reading the real field; `measureCaps` puts `capMedia` with `ChargedMinutes` this month.
+
+- [ ] **Step 1: Write the failing tests:** `TestLimitsMediaMinutesMonth` (JSON name, `nonNegative` refuses -1, `generous` takes the larger, a pack with `adds.media_minutes_month: 1000` adds 1,000 per unit up to the ceiling); `TestMediaAllowance` (limit 600: 600; exempt ops account: 0; sponsored: 0; no catalog with `account_minutes=45`: 45); `TestMediaCapLevels` (warn at 480 of 600, over at 601, ceiling at 1200; period the UTC month); `TestMeasureCapsMedia`; `TestDoorRefusesAtTwiceTheLimit` (in `apimedia_test.go`: 1200 charged minutes on limit 600 → 402 `plan_limit` with the deck's `cli.cap.media_minutes`, no row); the usage page test beside the PDF one shows `Media minutes` and `%d of %d media minutes this month`; `TestPlanExempt*` passes with `mediaAllowance` added to `planExemptSites`.
+- [ ] **Step 2:** Run `go test ./internal/plans/ -run 'TestLimits|TestNewFieldsKeepOldIDs' -count=1 && go test ./internal/console/ -run 'TestMediaAllowance|TestMediaCap|TestMeasureCapsMedia|TestDoorRefusesAtTwice|TestPlanExempt|Usage' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. No catalog file changes here: the flagship's values (Free 30, Personal 600, Community 1,200, Business 12,000, the `media` pack of 1,000 minutes) are catalog data, set in plan 3's rollout with Paul's prices.
+- [ ] **Step 4:** Rerun Step 2's command. Expected: PASS.
+- [ ] **Step 5:** Commit: `plans: monthly media minutes, audio at a tenth`.
+
+---
+
+### Task 7: Retirement at every teardown **[Astra: termination, production storage]**
+
+**Files:**
+- Create: `internal/console/mediaretire.go`, `internal/console/mediaretire_test.go`
+- Modify: `internal/console/appsettings.go` (between the lock at :1585 and `TeardownIn` at :1638), `internal/console/ownership.go` (`purgeOneStore` after the lock at :870; `deleteAccountNow` before `DeleteAccount` at :213), `internal/console/seedfinish.go` (after the lock at :170, before `TeardownIn` at :179)
+
+**Interfaces:**
+- Produces: `func (s *Server) mediaStoreRetire(ctx context.Context, acct, app, env string) (refusal string, err error)`: `""` at once for `env != ""`; otherwise `s.media.Retire(ctx, mediajobs.Scope{Account: acct, App: app}, now)` and, when `pending > 0`, `mediaText("media.retire_pending", app)`. The caller holds the walk lock. `func (s *Server) mediaAccountRetire(ctx context.Context, acct string) (string, error)` for account deletion (no lock: the account has no apps left).
+- `claim_purge.go:719` stays as it is: media refuses claims mode, so no row exists there; the guard test lists it as exempt with that reason.
+
+- [ ] **Step 1: Write the failing tests:** `TestStoreDestroyRefusedWhileATaskRuns` (§9: a running row, the destroy page: refused with the deck flash, `TeardownIn` not called, the fake engine got `Stop`; after `FakeEngine.Finish` and `Track`, the destroy succeeds); `TestRecreatedStoreMakesANewJob` (destroy, recreate, same key and bytes: a new job id row under the new incarnation, the old row invisible); `TestAppPurgeRetiresQueuedAndRunning` (§9: one queued and one running; the queued row `failed retired` uncharged at once, the running one stopped, charged ECS's time and cleaned; a new app of that name sees neither through GET); `TestSeedFinishRetires`; `TestAccountDeletionRetires`; `TestEveryStoreTeardownRetiresMedia` (a source guard: every `objstore.TeardownIn(` call in non-test `internal/console/*.go` is preceded in its function by `mediaStoreRetire(`, except `claim_purge.go`, listed with its reason).
+- [ ] **Step 2:** Run `go test ./internal/console/ -run 'TestStoreDestroyRefused|TestRecreatedStore|TestAppPurgeRetires|TestSeedFinishRetires|TestAccountDeletionRetires|TestEveryStoreTeardownRetiresMedia' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. Each site refuses with its existing failure path (the flash `fail(…)`, `purgeOneStore`'s returned sentence, `finishSeedStore`'s error).
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `console: retire media jobs before any store teardown`.
+
+---
+
+### Task 8: The pass worker and `GET /api/cli/system/media` **[Astra: production storage (cleanup deletes tenant objects)]**
+
+**Files:**
+- Create: `internal/console/mediapass.go`, `internal/console/mediapass_test.go`
+- Modify: `internal/console/claim_workers.go` (map at :7-36), `internal/console/apisystem.go` (beside `handleAPISystemPDFGet`, :257), `internal/console/routedecls.go` (beside :1088), `internal/console/svcroutes_test.go` (`closedDoors` :115, count :1757 to 104), `testdata/claim-routes.txt`, `claim_invariant_fixtures_test.go`, `claim_invariant_probes_read_test.go` (:372)
+
+**Interfaces:**
+- Produces: `func (s *Server) StartMediaPass(ctx context.Context)`: returns at once when `MediaEngine == nil`; otherwise `s.media.Pass(ctx, time.Now())` through `s.jobs.Run(ctx, "StartMediaPass", …)` every `media.PassEvery`. Registered as worker `StartMediaPass`, fixtured `claimRead("off on a host-claim console: media conversion refuses claims mode and the worker returns at once")`.
+- Produces: `GET /api/cli/system/media`, `svcrole.Set{}`, handler `handleAPISystemMediaGet` starting with `apiSystemStatusReader` like the PDF one, answering `{"configured": bool, "region": string, "image": {"digest","built_at","ffmpeg","age_days"}, "gates": {"video-720p/short": "ok" | "refused: <check>", …}, "queued": {"short","long"}, "running": {"short","long"}, "done_24h", "failed_24h", "failed_by_code_24h": {code: n}}`; gates from `CheckRevision` with a 5 s timeout each.
+
+- [ ] **Step 1: Write the failing tests:** `TestMediaPassRunsTheLifecycle` (fakes: submit through the door, run the worker for three ticks with `FakeEngine.Start` and `Finish` between: GET says `done` with three outputs, the result object deleted, outputs kept); `TestMediaPassFailedCleansOutputs`; `TestSystemMediaStatus` (operator: shape and counts; non-operator person 403; Service token 404; unconfigured `configured:false`); the `closedDoors` equality test.
+- [ ] **Step 2:** Run `go test ./internal/console/ -run 'TestMediaPass|TestSystemMedia|TestEveryClosedDoor|TestClaim' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `console: media pass worker and system status`.
+
+---
+
+### Task 9: `carlos store uploads` **[Astra: production storage, security gate]**
+
+**Files:**
+- Create: `internal/console/apistoreuploads.go`, `internal/console/apistoreuploads_test.go`, `store_uploads.go` (root), `store_uploads_test.go`
+- Modify: `internal/objstore/aws.go` (`storePolicyJSON` object Allow, :195-198), `internal/objstore/aws_test.go`, `internal/console/routedecls.go` (beside :980-985), `internal/console/scandeliver.go` (new helper beside `scanCallbackHost`, :280), `store.go` (root `storeCommand` children, :118-127), `apimode.go`, `parity/parity.tsv`, `docs/parity.md` (generated), `internal/console/testdata/claim-routes.txt`, `claim_invariant_fixtures_test.go`
+
+**Interfaces:**
+- Produces: `POST /api/cli/apps/{account}/{app}/store/uploads` and `GET` the same, `svcrole.Allow(svcrole.Admin)`. POST body `{"enabled": bool, "origins": [string]}`. Answer `{"enabled": bool, "origins": [string], "bucket_matches": bool, "mismatch": "" | "cors" | "lifecycle"}`.
+- Enable, under the walk lock: `StoreConversion` false or `StoreBuckets` nil or `HostClaim` → 503 `uploads_not_configured`; origins: each `https://<host>` (lowercase host, no port, path, query or `*`) or `http://localhost:<1..65535>`, at most 8, deduplicated → 400 `bad_origin` / `too_many_origins`; none given → `s.appReadyPlatformHosts(ref)` as `https://` origins, 409 `no_hosts` when empty; `mediaStoreEligible` (409 `no_store` / `store_unverified`); `PutUploads`; record `Conversion.Uploads{Origins, CORSHash, LifecycleHash, At, By}`; re-run `objstore.GrantIn` for the store so its user's policy carries the two multipart actions. Disable: `DeleteUploads` only when `Inspect` shows the recorded hashes; clear `Uploads`. GET: `Inspect` and compare with the record.
+- Produces: `func (s *Server) appReadyPlatformHosts(ref objstore.AppRef) ([]string, error)` (every ready, platform, non-canary, non-sidecar route host of the app, sorted; `scanCallbackHost`'s filter).
+- `storePolicyJSON`: the object Allow gains `s3:AbortMultipartUpload` and `s3:ListMultipartUploadParts` for every store.
+- CLI: `carlos store uploads enable --app <a> [--origin <o>]...`, `carlos store uploads status --app <a>`, `carlos store uploads disable --app <a>`, a `clireg` node `uploads` with three `raw` leaves; parity row `store-uploads storage gap store uploads enable ; store uploads status ; store uploads disable wp-email-storage `.
+
+- [ ] **Step 1: Write the failing tests:** `TestUploadsOriginsTable` (accepts `https://shop.example.com`, `http://localhost:3000`; refuses `http://shop.example.com`, `https://*.example.com`, `https://shop.example.com/`, `https://shop.example.com:8443`, `http://localhost`, `http://localhost:0`, nine origins); `TestUploadsEnableWritesOneRuleEach`; `TestUploadsDefaultOriginsArePrinted`; `TestUploadsRefusesForeignCORS` (a foreign CORS rule: 409 `store_unverified` with the `cors` phrase, nothing written); `TestUploadsDisableLeavesForeignRules`; `TestStorePolicyGrantsMultipartCleanup` (objstore: both actions in the object Allow; the tag Denys unchanged); `TestStoreUploadsVerbs` (root: the three leaves call the doors and print the deck lines).
+- [ ] **Step 2:** Run `go test ./internal/console/ -run 'TestUploads' -count=1 && go test ./internal/objstore/ -run 'TestStorePolicy' -count=1 && go test . -run 'TestStoreUploadsVerbs' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. Run `make parity-doc`.
+- [ ] **Step 4:** Rerun Step 2's command and `go test . -run 'TestParity|TestCLIProjection' -count=1 && go test ./internal/parity/ -count=1`. Expected: PASS. (`TestDeliveredContractMinio` runs on CI's MinIO step and must stay green with the new actions.)
+- [ ] **Step 5:** Commit: `store: browser uploads verb, bucket CORS and multipart cleanup`.
+
+---
+
+### Task 10: `carlos media` and `carlos system media status`
+
+**Files:**
+- Create: `media_cli.go`, `media_cli_test.go` (root)
+- Modify: `commands.go` (add `mediaCommand()` beside `storeCommand()`, :130), `system.go` (`systemMediaCommand()` beside `systemPDFCommand`, :698-720; usage text), `apimode.go` (client methods beside `systemPDFStatus`, :2248), `parity/parity.tsv` (beside :216), `docs/parity.md` (generated), `docs/site/cli.md` (headings below)
+
+**Interfaces:**
+- Produces: `carlos media convert <key> --app <a> [--preset audio-aac] [--class long] [--wait] [--account …] [--console …]` and `carlos media status <id> --app <a>`; `--wait` polls GET every 3 s until `done` or `failed`. Local `type mediaJobAnswer struct` mirroring Task 5's answer (root never imports `internal/media`). `func (a *apiSession) mediaConvert(ctx, acct, app string, body map[string]string) (mediaJobAnswer, int, error)`, `mediaJob(ctx, acct, app, id string)`, `systemMediaStatus(ctx)`. Parity rows `media-convert apps cli-only media convert ; media status Apps call the conversion door; the CLI is how a person tries it.` and `op-system-media operator operator system media status The media conversion engine.`.
+- `docs/site/cli.md`: `### carlos media` (with `#### carlos media convert`, `#### carlos media status`) after `### carlos store`'s section, `#### carlos store uploads` after `#### carlos store scan` (:2005), `#### carlos system media status` after `#### carlos system pdf status` (:3173); each heading's text from the deck's docs rows (Task 11 drafts them; this task adds the headings with one approved sentence each).
+
+- [ ] **Step 1: Write the failing tests:** `TestMediaConvertPrintsTheJob`, `TestMediaConvertWaitPollsUntilDone` (an `httptest` console answering queued, running, done), `TestMediaStatusFailedPrintsCodeAndMessage`, `TestPrintSystemMedia` (deck lines exactly; the 30-day warning from `age_days` 31).
+- [ ] **Step 2:** Run `go test . -run 'TestMediaConvert|TestMediaStatus|TestPrintSystemMedia' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. `make parity-doc`.
+- [ ] **Step 4:** Rerun with `TestParity|TestCLIProjection`, then `go test ./internal/docsite/ ./internal/parity/ -count=1`. Expected: PASS.
+- [ ] **Step 5:** Commit: `cli: carlos media and carlos system media status`.
+
+---
+
+### Task 11: Docs: the media page, plans and residency
+
+**Files:**
+- Create: `docs/site/media-conversion.md`
+- Modify: `docs/site/nav.json` (Reference section, beside the `pdfs` entry at :42, slug `media-conversion`), `docs/site/plans.md` (allowance sentence beside :37, caps list beside :84, the month bullet at :93, a ceiling bullet beside :100), `README.md` (one residency sentence where the PDF service is mentioned, :1341), `docs/superpowers/notes/media-conversion-copy-deck.md` (the docs rows)
+
+The page, in order (spec §5.6, §5.7): what it does (G1, G2, the two presets and their outputs); the walkthrough for app `shop` on `shop.example.com`, verbatim from spec §5.7; the door, its body and the refusal table; job states and every job error; serving (proxy the playlist from the app's own origin, never redirect it; MP4 and poster by `Range` proxy or redirect to a presigned GET); browser uploads and the multipart recipe; deleting (`derived/<source key>/` with the source); limits and the allowance (classes, maximums, weights, twice the limit); the residency sentence: conversion happens in the store's region.
+
+- [ ] **Step 1:** Draft every paragraph as deck rows `docs.media.*`, `docs.plans.media.*`, `docs.readme.media`. Run the copy-review skill and apply edits verbatim.
+- [ ] **Step 2:** Write the files from the approved rows.
+- [ ] **Step 3:** Run `go test ./internal/docsite/ -count=1`. Expected: PASS (nav, links, fences naming only existing verbs).
+- [ ] **Step 4:** Commit: `docs: media conversion page, plans and residency`.
+
+---
+
+### Task 12: Census, record-write census and hand-off to plan 3
+
+- [ ] **Step 1:** `git fetch origin && git merge origin/main`.
+- [ ] **Step 2:** `make census-card`. Expected in-scope changes: `internal/objstore/objstore.go`, `walk.go`, `aws.go`; root `store.go`, `store_uploads.go`, `media_cli.go`, `commands.go`, `system.go`, `apimode.go`. Write `docs/superpowers/notes/census-claims-media-conversion.tsv` (each unit: what changed; no new root read) and run `make census-propose NAME=media-conversion CLAIMS=docs/superpowers/notes/census-claims-media-conversion.tsv`.
+- [ ] **Step 3:** Run `go test ./internal/provision/ -run 'TestPlan9B8RecordWriteCensus' -count=1`. For each re-fingerprinted unit (expected: `internal/console/server.go` `NewServer`, `plangrace.go` `const#1`, the routedecls unit, `objstore` grant walk units), add a replacement entry to a new `internal/provision/media_conversion_census_test.go` layered on the current head inventory (the shape of `usage_attribution_390_census_test.go`), say in its comment what changed and that no record write moved, and point `TestPlan9B8RecordWriteCensus` at it. Rerun. Expected: PASS.
+- [ ] **Step 4:** Run `go vet ./internal/media/... ./internal/mediajobs/... ./internal/storecfg/... ./internal/console/ ./internal/objstore/ ./internal/plans/` and `gofmt -l .`, and the cross-compiles `GOOS=darwin GOARCH=arm64 go build ./...` and `GOOS=windows GOARCH=amd64 go build ./...`. Expected: clean.
+- [ ] **Step 5:** Commit: `census: media conversion console side`. Plan 3 continues on the same branch; the census verdict and the whole-branch review come at plan 3's end.
diff --git a/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md b/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md
new file mode 100644
index 000000000..46e40c0e4
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md
@@ -0,0 +1,335 @@
+# Media conversion, plan 3 (the engine, its image and its infrastructure) 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 (`- [ ]`) syntax for tracking.
+
+**Goal:** Build the codec handler and deadline timer that run in one Fargate task per execution, the arm64 image that carries them, the AWS adapters behind plan 2's interfaces, the `media-engine` module and the `store_conversion` switch, and roll them out dev first, then flagship, each step on Paul's go.
+**Architecture:** One pure-Go binary, `cmd/carlos-media`, is the image's entrypoint: `deadline` sleeps and exits, `codec` runs `internal/mediahandler` (download, sniff, probe, ffmpeg, loudness, peaks, collect, upload, result), `selftest` and `drill` serve the rollout. `internal/mediaaws` implements plan 2's `media.Engine`, `media.Grants` and `storecfg.Buckets` with ECS, STS and S3; `internal/medialocal` runs the same handler as a local process, which is the provider boundary's non-AWS runner and the end-to-end harness. `infra/modules/media-engine` holds the cluster, four task definitions, the closed VPC, its endpoints and DNS firewall, the roles and the reaper.
+**Tech Stack:** Go 1.26 (`CGO_ENABLED=0`, linux/arm64 for the image), Debian 13 `ffmpeg`, `aws-sdk-go-v2` (`service/ecs` added, `sts`, `s3`), OpenTofu with `mock_provider` tests, Python 3 stdlib for the reaper.
+**Spec:** docs/superpowers/specs/2026-11-16-video-conversion-design.md (rev 8, approved)
+
+## Global Constraints
+
+- Plan 2's Global Constraints apply. This plan consumes `internal/media` exactly as plan 2 Task 1 declares it: `Payload`, `Transfers`, `Transfer`, `JobLimits`, `Result`, `SourceFacts`, `OutputFact`, `ParseResult`, the exit codes, `ContainerCodec`/`ContainerDeadline`, `PayloadEnv`/`DeadlineEnv`/`ExpiryEnv`, `OutputNames`, `ContentType`, `HandlerCodes`, `StopGrace`, `MaxPutBytes`, `MaxResultBytes`, `MaxOverrideBytes`, `TaskDefinition`, `CheckTaskDefinition`, `Engine`, `Grants`, `RunRequest`, `Task`, `Rejected`, `Misconfigured`, `ImageInfo`. No new shared name is defined here.
+- Plan 1's report (`docs/superpowers/reviews/2026-11-16-media-conversion-spike.md`) must be committed and Paul must have confirmed it before Task 4 starts. Its figures replace the provisional constants named "spike" below; if a proof failed, the spec amendment it lists lands first.
+- The task: two containers from one arm64 image pinned by digest, both essential, `stopTimeout` 30 each, `codec` `dependsOn` `deadline` `START`, no task role, no `pidMode`, no volume shared between them, user `65534:65534`, read-only root, every capability dropped, `enableExecuteCommand` false. `codec` alone mounts the volume `scratch` at `/scratch`.
+- Deadline container: sleep until the earlier of its start plus `CARLOS_MEDIA_DEADLINE_S` and `CARLOS_MEDIA_GRANT_EXPIRY` less 30 s; exit `DeadlineExitReached` (0) at once if that has passed; `DeadlineExitStopped` (143) on SIGTERM; `DeadlineExitBadInput` (3) on bad input, at once.
+- Handler: one GET of the source to `/scratch/in/source`, resumed with `Range` under the same signed `If-Match`, at most 20 resumes; byte cap enforced as it streams; no transfer begins at or after the grant expiry, and a refusal after expiry exits `ExitGrantExpired` (75) with no result object. Named errors write a result object and exit `ExitFailed` (1); success writes the result and exits `ExitDone` (0).
+- Sniff families: ISO BMFF (`ftyp` at offset 4) → demuxer `mov`, EBML (`1A 45 DF A3`) → `matroska`, both presets; `audio-aac` also MP3 (`ID3`, or an MPEG audio frame sync) → `mp3`, `RIFF`…`WAVE` → `wav`, `fLaC` → `flac`, `OggS` → `ogg`. Anything else: `unsupported_container`, and no ffmpeg runs.
+- Every ffmpeg and ffprobe run: `-nostdin` (ffmpeg), `-protocol_whitelist file`, `-f <sniffed demuxer>`, `-enable_drefs 0` for `mov`, `-codec_whitelist h264,hevc,vp8,vp9,av1,libdav1d,aac,opus,libopus,vorbis,libvorbis,mp3,mp3float,flac,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_f64be,pcm_alaw,pcm_mulaw`, input `/scratch/in/source`, only the chosen streams mapped, `-t` at the granted duration, `-map_metadata -1 -map_chapters -1`, outputs under `/scratch/out`. Probe timeout 60 s.
+- Video: H.264 High, `yuv420p`, at most 1280x720 in either orientation, never upscaled, rotation applied, at most 30 fps (`-fpsmax 30`), a keyframe every 2 s, CRF under a 2.5 Mbit/s ceiling (`-maxrate 2500k -bufsize 5000k`), HDR tone-mapped; audio AAC-LC stereo 48 kHz 128 kbit/s or none; one fragmented MP4 with 4 s fragments and an HLS version 7 byte-range playlist over it; one JPEG poster at output size, 1 s in, or the midpoint of a clip shorter than 2 s.
+- Audio: AAC-LC 48 kHz, mono 64 kbit/s for a mono source, else stereo 128 kbit/s; one linear gain = min(gain to -16 LUFS, gain to -1.5 dBTP less the codec headroom); no gain for a source with no measurable loudness; the same container and playlist; `peaks.json` `{"version": 1, "duration_ms": N, "peaks": [1,000 integers 0..255]}`.
+- Output bounds: `video.mp4`/`audio.mp4` at most `MaxPutBytes`, playlists 4 MiB, `poster.jpg` 16 MiB, `peaks.json` 64 KiB. Collected through a held directory descriptor, regular files with one link only.
+- The handler and the deadline timer never log a transfer, a URL, a header or the payload.
+- Provider boundary: `internal/media/...`, `internal/mediajobs`, `internal/mediahandler`, `internal/medialocal`, `internal/storecfg` and `cmd/carlos-media` import no `github.com/aws/...` package; only `internal/mediaaws` and `cmd/console` do.
+- Infrastructure, releases and rolls need Paul's scoped approval (AGENTS.md); dev first. AWS commands always name a profile (`kass` for dev, `keymail` for flagship).
+- Local tests targeted, as plan 2. Cross-compile gate: `GOOS=darwin GOARCH=arm64 go build ./...` and `GOOS=windows GOARCH=amd64 go build ./...` before every push; Linux-only code sits in `*_linux.go` with `*_other.go` stubs.
+
+## Review Focus
+
+1. **An iPhone portrait clip, HEVC with a -90 rotation and HLG or Dolby Vision 8.4.** A person expects an upright 720x1280 SDR video and poster. Test: Task 4 `TestVideoArgsPortraitHDR`.
+2. **A variable-frame-rate screen recording** whose `r_frame_rate` is `120/1` while it averages 29.97. A person expects it to convert; a true 120 fps source is still refused. Test: Task 3 `TestFrameRateUsesTheAverage`.
+3. **A Chrome voice recording** (Opus in WebM from `MediaRecorder`), whose header carries no duration. A person expects it to convert like any other file. Test: Task 3 `TestDurationFromPacketsWhenTheHeaderHasNone`.
+4. **An MP3 or M4A with cover art.** As `video-720p` it is `no_video`, not `unsupported_video_codec`; as `audio-aac` it converts and the picture is ignored. Test: Task 3 `TestAttachedPictureIsNotVideo`.
+5. **A screen recording with no audio track.** The video converts with one track and a valid playlist. Test: Task 4 `TestVideoWithoutAudio`.
+
+## Census impact
+
+Expected; `make census-card` decides. In scope: every new file under `infra/` (`infra/modules/media-engine/**`, `infra/modules/region-host/main.tf`, `variables.tf`, its new tftest), `go.mod`/`go.sum` (the root binary's module), and plan 2's objstore and root CLI units. Out of scope: `cmd/carlos-media`, `cmd/mediaimage`, `cmd/console`, `internal/media*`, `internal/storecfg`, `internal/console` (none is in `go list -deps .`; Task 13's guard keeps it so). One overlay for the branch: `make census-propose NAME=media-conversion CLAIMS=docs/superpowers/notes/census-claims-media-conversion.tsv` (extended in Task 14); Astra gives the verdicts; recorded on #280.
+
+---
+
+### Task 1: The deadline container **[Astra: termination]**
+
+**Files:**
+- Create: `cmd/carlos-media/main.go`, `cmd/carlos-media/deadline.go`, `cmd/carlos-media/deadline_test.go`
+
+**Interfaces:**
+- Consumes: `media.DeadlineSleep` (plan 2 Task 1, with its table test).
+- Produces: `func runDeadline(getenv func(string) string, now func() time.Time, stop <-chan os.Signal) int` (parses `DeadlineEnv` as an integer in 1..3000 and `ExpiryEnv` as a positive integer of Unix seconds; returns `DeadlineExitBadInput` on anything else; `DeadlineExitReached` at once when `media.DeadlineSleep(now(), …)` is ≤ 0; otherwise a `time.Timer` against `stop`). `main` dispatches `deadline`, `codec`, `selftest`, `drill`, `version`; `deadline` calls `signal.Notify(stop, syscall.SIGTERM)` and `os.Exit(runDeadline(os.Getenv, time.Now, stop))`. It prints nothing and listens on nothing.
+
+- [ ] **Step 1: Write the failing tests:** `TestDeadlineExitsAtOnceWhenExpired` (expiry in the past: returns 0 within 10 ms); `TestDeadlineBadInput` (empty, `0`, `3001`, `-5`, `1e3`, a non-number expiry: 3, at once); `TestDeadlineStopped` (SIGTERM on the channel: 143); `TestDeadlineReached` (deadline 1 s with a fake clock start: returns 0 after the timer).
+- [ ] **Step 2:** Run `go test ./cmd/carlos-media/ -run 'TestDeadline' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: the deadline container`.
+
+---
+
+### Task 2: Handler: payload, download, resume and exit 75 **[Astra: security gate]**
+
+**Files:**
+- Create: `internal/mediahandler/handler.go`, `download.go`, `download_test.go`, `s3test_test.go` (an `httptest` server that checks the presigned query and the signed headers, serves `Range`, honours `If-Match` and `If-None-Match`, and can cut a connection after N bytes or answer 403 after an instant)
+- Modify: `cmd/carlos-media/main.go` (`codec`)
+
+**Interfaces:**
+- Consumes: `media.Payload`, `Transfers.URL`, `Payload.Validate`, the exit codes.
+- Produces: `type Config struct{ FFmpeg, FFprobe, Scratch string; HTTP *http.Client; Now func() time.Time; Logf func(string, ...any) }` (defaults `/usr/bin/ffmpeg`, `/usr/bin/ffprobe`, `/scratch`); `func Run(ctx context.Context, cfg Config, payload string) int`; `type jobError struct{ code string }`; `var errGrantExpired`; `func download(ctx context.Context, cfg Config, p media.Payload, dst string) error`. `codec` reads `os.Getenv(media.PayloadEnv)`, creates `/scratch/in`, `/scratch/out`, `/scratch/tmp` (0700), and exits `Run`'s answer.
+- Download rules: send `Transfer.Header` exactly; 200 with `Content-Length` over `SourceBytes` → `source_too_large` before reading; 200/206 counted as it streams, over the cap → `source_too_large`; 404 `source_not_found`; 412 `source_changed`; 403 at or after `Expiry` → `errGrantExpired`, before it → `source_unreadable`; a broken body resumes with `Range: bytes=<written>-` (206 required, else `unreadable`) after `min(2^n s, 10 s)`; before every attempt, `now ≥ Expiry` → `errGrantExpired`; after 20 resumes → `unreadable`.
+
+- [ ] **Step 1: Write the failing tests:** `TestDownloadSendsTheSignedHeaders` (the server sees `If-Match` and nothing derived from the payload but the URL); `TestDownloadResumesUnderIfMatch` (cut at 1 MiB, 5 MiB: the file is whole, each resume carried `If-Match` and the right `Range`); `TestDownloadSourceChanged` (412 on a resume); `TestDownloadCapWhileStreaming` (no `Content-Length`, the body passes the cap: `source_too_large`, the scratch file removed); `TestDownloadAfterExpiryExits75` (`Run` returns 75 and the server saw no result PUT); `TestDownload403BeforeExpiryIsUnreadable`; `TestRunRejectsABadPayload` (bad JSON, version 2, a 31-hex execution: exit 1, no request made); `TestHandlerNeverLogsTransfers` (a `Logf` that records: no line contains the signature, the token or `X-Amz`).
+- [ ] **Step 2:** Run `go test ./internal/mediahandler/ -run 'TestDownload|TestRunRejects|TestHandlerNeverLogs' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: handler download with resume and the grant window`.
+
+---
+
+### Task 3: Handler: sniff and probe
+
+**Files:**
+- Create: `internal/mediahandler/sniff.go`, `probe.go`, `procs_linux.go`, `procs_other.go`, `sniff_test.go`, `probe_test.go`, `procs_test.go`, `fakeffmpeg_test.go` (the `TestHelperProcess` pattern: the test binary re-executed as `ffmpeg` or `ffprobe` with `MEDIA_FAKE=<scenario>`; this task adds `probe-<fixture>` scenarios that print a fixture, and Tasks 4 to 7 add theirs), `testdata/probe/*.json` (ffprobe answers, copied from plan 1's `docs/superpowers/reviews/media-spike-fixtures/probe/` where the spike saved them from Paul's files with every `tags` object removed: an iPhone HEVC HLG portrait, a Dolby Vision 8.4, a VFR screen recording, a Chrome WebM Opus without duration; and hand-written ones: a Dolby Vision 5, an MP3 with cover art, a 4K60 H.264, a 120 fps H.264, a 30000x30000 bomb, a lying 10 h duration, a WAV mono, a 6-channel AAC)
+
+**Interfaces:**
+- Produces: `func runChild(ctx context.Context, cfg Config, name string, args []string, dir string) (stderrTail []byte, err error)` (Linux: the handler sets `PR_SET_CHILD_SUBREAPER` at start; the child gets its own process group and `Pdeathsig: SIGKILL`; when it exits or the context ends, `kill(-pgid, SIGKILL)`, then repeatedly kill every process whose parent is the handler (from `/proc/*/stat`) and `wait4(-1, WNOHANG)` until `ECHILD`, at most 5 s, else `engine_failed`; nothing reads `/scratch/out` before it returns; a non-zero exit is `unreadable`; the last 64 KiB of stderr is kept for the task's log and never holds a transfer; `procs_other.go` returns an error, as the handler runs only on Linux); `func sniff(head []byte, preset string) (demuxer string, err error)`; `type probeFacts struct{ VideoIndex, AudioIndex int; Width, Height, Rotation int; FPS float64; HDR bool; DolbyVisionProfile int; VideoCodec, AudioCodec string; Channels int; DurationMS int64 }` (`-1` for an absent stream); `func probe(ctx context.Context, cfg Config, demuxer string) (probeFacts, error)`; `func parseProbe(b []byte) (probeFacts, error)`; `func check(f probeFacts, preset string, l media.JobLimits) error` (a `jobError` or nil).
+- Rules: streams with `disposition.attached_pic` 1 are skipped; the first remaining video and first audio stream are taken (`audio-aac`: audio only); rotation from the display matrix side data, else the `rotate` tag; FPS from `avg_frame_rate`, `r_frame_rate` only when the average is `0/0`; HDR when `color_transfer` is `smpte2084` or `arib-std-b67`, or Dolby Vision side data is present; duration from `format.duration`, else the longest stream duration, else a second ffprobe pass over the chosen stream's packets (`-show_entries packet=pts_time,duration_time -of csv=p=0`) taking the largest `pts+duration`, else `unreadable`. Checks in spec §6's order: `no_video`/`no_audio`; video codec not `h264`, `hevc`, `vp8`, `vp9`, `av1` → `unsupported_video_codec`; audio codec not `aac`, `opus`, `vorbis`, `mp3`, `flac` or `pcm_*` → `unsupported_audio_codec`; a side over 4096 or more than 3840·2160 pixels → `source_dimensions`; FPS over 60 → `source_frame_rate`; duration over `MaxHiMS` (video above 1080p: longer side over 1920 or shorter side over 1080) or `MaxMS` → `source_too_long`; over `GrantedMS` → `needs_long_class` when `GrantedBy` is `class`, else `allowance_exceeded`; Dolby Vision profile 5 → `unsupported_hdr` only when the spike report sets `refuseDolbyVision5 = true` (spike; default false: decoded as HEVC and tone-mapped); probe failure or timeout → `unreadable`.
+
+- [ ] **Step 1: Write the failing tests:** `TestSniffTable` (each family for each preset; `#EXTM3U`, `<?xml`, a PDF, 0 bytes and an MP3 under `video-720p` → `unsupported_container`); `FuzzSniff` (never panics; never answers a family whose magic is absent); `TestParseProbeFixtures` (each fixture's facts); `TestFrameRateUsesTheAverage` (Review Focus 2); `TestDurationFromPacketsWhenTheHeaderHasNone` (Review Focus 3, the second pass driven by a fake ffprobe from Task 7's helper); `TestAttachedPictureIsNotVideo` (Review Focus 4); `TestCheckOrder` (a source failing two checks reports the earlier); `TestLyingDurationIsTooLong`; `TestBombIsDimensions`; `FuzzParseProbe` (arbitrary bytes never panic and never yield facts that pass `check` with a negative size or duration); `TestRunChildKillsEscapedDescendants` (Linux: a helper child that forks a grandchild which calls `setsid` and sleeps: after `runChild` returns, neither process exists); `TestProbeTimeoutIsUnreadable` (a fake ffprobe that sleeps past a 100 ms test timeout).
+- [ ] **Step 2:** Run `go test ./internal/mediahandler/ -run 'TestSniff|TestParseProbe|TestFrameRate|TestDurationFromPackets|TestAttachedPicture|TestCheckOrder|TestLying|TestBomb|TestRunChild|TestProbeTimeout' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. `probe` runs ffprobe through `runChild` with a 60 s context and reads at most 1 MiB of its output.
+- [ ] **Step 4:** Rerun, and `go test ./internal/mediahandler/ -run '^$' -fuzz FuzzSniff -fuzztime 30s` and the same for `FuzzParseProbe`. Expected: PASS, no crashers.
+- [ ] **Step 5:** Commit: `media: sniff and probe before any encode`.
+
+---
+
+### Task 4: Handler: the encodes, the playlist and the child processes
+
+**Files:**
+- Create: `internal/mediahandler/ffmpeg.go`, `geometry.go`, `fmp4.go`, `playlist.go`, `ffmpeg_test.go`, `fmp4_test.go`, `testdata/fmp4/*` (copied from plan 1's `docs/superpowers/reviews/media-spike-fixtures/fmp4/`: `video.mp4`, `video-noaudio.mp4`, `audio.mp4`, each made by the spike with Debian 13's ffmpeg and this task's exact arguments, with ffprobe's packet times beside each; docs-t1 has no ffmpeg)
+
+**Interfaces:**
+- Produces: `func targetSize(w, h, rotation int) (ow, oh int)` (swap for ±90/270; box 1280x720 landscape or 720x1280 portrait; `scale = min(1, boxW/w, boxH/h)`; each side rounded down to even, at least 2); `func videoArgs(f probeFacts, p media.Payload, demuxer string) []string`; `func posterArgs(f probeFacts, p media.Payload, demuxer string) []string`; `func audioArgs(f probeFacts, p media.Payload, demuxer string, gainDB float64) []string`; `type fragment struct{ Offset, Length int64; DurationS float64 }`; `func readFMP4(r io.ReaderAt, size int64) (initLen int64, frags []fragment, durationMS int64, err error)` (top-level `ftyp`, `moov` then `moof`/`mdat` pairs; the timescale from the first video track's `mdhd`, else the first track's; each fragment's duration from consecutive `tfdt`, the last from its `trun` sample durations; any other box order, overlap, a size past the file or over 1,000,000 fragments is an error); `func writePlaylist(w io.Writer, name string, initLen int64, frags []fragment) error`. Every encode runs through Task 3's `runChild`.
+- `videoArgs` (in order): the Global Constraints input flags; `-map 0:<v>`, `-map 0:<a>` when there is audio; `-sn -dn -map_metadata -1 -map_chapters -1 -t <GrantedMS as seconds, 3 decimals>`; `-vf scale=<ow>:<oh>:flags=bicubic,format=yuv420p` for SDR, or `-vf scale=<ow>:<oh>:flags=bicubic,zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p` for HDR (spike: the chain and operator plan 1 confirms); `-c:v libx264 -profile:v high -preset <x264Preset> -crf <x264CRF> -maxrate 2500k -bufsize 5000k -pix_fmt yuv420p -fpsmax 30 -force_key_frames expr:gte(t,n_forced*2) -sc_threshold 0`; audio `-c:a aac -b:a 128k -ac 2 -ar 48000` or `-an`; `-f mp4 -movflags +frag_keyframe+empty_moov+default_base_moof -min_frag_duration 4000000 /scratch/out/video.mp4`. `x264Preset = "veryfast"` and `x264CRF = 23` (spike).
+- `posterArgs`: `-ss <1.000, or duration/2 when under 2 s>` before `-i`, the same input flags and video filter, `-frames:v 1 -q:v 3 /scratch/out/poster.jpg`.
+- `audioArgs`: `-map 0:<a> -vn -sn -dn -map_metadata -1 -map_chapters -1 -t <granted>`, `-af aformat=channel_layouts=<mono|stereo>:sample_rates=48000,volume=<gain>dB`, `-c:a aac -b:a <64k|128k>`, then the same `-f mp4 … /scratch/out/audio.mp4`.
+- Playlist: `#EXTM3U`, `#EXT-X-VERSION:7`, `#EXT-X-TARGETDURATION:<ceil(max)>`, `#EXT-X-PLAYLIST-TYPE:VOD`, `#EXT-X-INDEPENDENT-SEGMENTS`, `#EXT-X-MAP:URI="<name>",BYTERANGE="<initLen>@0"`, per fragment `#EXTINF:<3 decimals>,`, `#EXT-X-BYTERANGE:<len>@<off>`, `<name>`, then `#EXT-X-ENDLIST`. Written by Go, never by ffmpeg. `SourceFacts.DurationMS` is `readFMP4`'s duration (what was converted).
+- [ ] **Step 1: Write the failing tests:** `TestTargetSizeTable` (1920x1080 → 1280x720; 1080x1920 → 720x1280; rotation -90 on 1920x1080 → 720x1280; 640x360 unchanged; 1281x721 → 1280x720; 3840x2160 → 1280x720; 1000x3000 → 240x720; odd results rounded down to even); `TestVideoArgsPortraitHDR` (Review Focus 1); `TestVideoArgsSDRLandscape` (the exact argument list for a 1080p H.264 fixture with audio); `TestVideoWithoutAudio` (Review Focus 5: no `-map 0:a`, `-an` present, and `readFMP4` of `testdata/fmp4/video-noaudio.mp4` yields a valid playlist); `TestPosterTime` (5 s → 1.000; 1.5 s → 0.750); `TestAudioArgsMonoAndStereo`; `TestReadFMP4Fixtures` (init length, fragment count and offsets, durations within 1 ms of the packet times saved beside each fixture, 4 s fragments); `TestPlaylistGolden`; `FuzzReadFMP4` (never panics; any answer it accepts has contiguous, in-bounds ranges).
+- [ ] **Step 2:** Run `go test ./internal/mediahandler/ -run 'TestTargetSize|TestVideoArgs|TestVideoWithout|TestPosterTime|TestAudioArgs|TestReadFMP4|TestPlaylist' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun, and `-fuzz FuzzReadFMP4 -fuzztime 30s`. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: encodes, the byte-range playlist and child cleanup`.
+
+---
+
+### Task 5: Handler: loudness and the waveform
+
+**Files:**
+- Create: `internal/mediahandler/loudness.go`, `peaks.go`, `loudness_test.go`, `peaks_test.go`
+
+**Interfaces:**
+- Produces: `const targetLUFS = -16.0`, `ceilingDBTP = -1.5`, `codecHeadroomDB = 0.5` (spike); `func measureArgs(f probeFacts, p media.Payload, demuxer string, layout string) []string` (`-af aformat=channel_layouts=<layout>:sample_rates=48000,loudnorm=I=-16:TP=-1.5:LRA=11:print_format=json -f null -`); `func parseLoudnorm(stderr []byte) (inputI, inputTP float64, measurable bool, err error)` (the last JSON object in the tail; `-inf` or below -70 LUFS is not measurable); `func gainDB(inputI, inputTP float64, measurable bool) float64` (0 when not measurable, else `min(-16 − I, (-1.5 − 0.5) − TP)`); `func peaksArgs(…, gainDB float64) []string` (mono, 8000 Hz, `volume=<gain>dB`, `-f s16le -acodec pcm_s16le /scratch/tmp/peaks.raw`); `func computePeaks(r io.Reader, samples int64) ([1000]uint8, error)` (slice `i` covers samples `[i·N/1000, (i+1)·N/1000)`; value `min(255, (max|s|·255 + 16383)/32767)`; an empty slice is 0); `func writePeaks(w io.Writer, durationMS int64, p [1000]uint8) error` (exactly `{"version":1,"duration_ms":N,"peaks":[…]}`).
+
+- [ ] **Step 1: Write the failing tests:** `TestGainTable` (I -30, TP -3: +12.5 limited by the ceiling, quieter than -16; I -20, TP -10: +4; I -10, TP 0: -6; I -inf: 0; I -75: 0); `TestParseLoudnormTail` (a real loudnorm block in a noisy stderr tail; a truncated block is an error); `TestComputePeaksSlices` (a ramp, N = 999, N = 1000, N = 2,500,000, all-zero silence → 1,000 zeros, a -32768 sample → 255); `TestPeaksJSONShape` (exactly 1,000 integers, version 1, key order); `FuzzComputePeaks`.
+- [ ] **Step 2:** Run `go test ./internal/mediahandler/ -run 'TestGain|TestParseLoudnorm|TestComputePeaks|TestPeaksJSON' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: linear loudness gain, ceiling first, and peaks`.
+
+---
+
+### Task 6: Handler: collecting and uploading outputs, and the result **[Astra: security gate]**
+
+**Files:**
+- Create: `internal/mediahandler/collect_linux.go`, `collect_other.go`, `upload.go`, `result.go`, `collect_test.go`, `upload_test.go`, `run_test.go`
+
+**Interfaces:**
+- Produces: `type collected struct{ Name string; File *os.File; Size int64 }`; `func collect(dir string, names []string, bounds map[string]int64) ([]collected, error)`: `os.OpenRoot(dir)`; per name `Lstat` (regular, not a symlink), `OpenFile(name, O_RDONLY|O_NOFOLLOW|O_NONBLOCK)`, `Fstat` (regular, `Nlink == 1`, same device and inode as the `Lstat`, size 1..bound); any failure is `engine_failed` (an oversized video or audio file is `output_too_large`); `func upload(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, c collected) (etag string, err error)` (`PUT` with `Content-Length` and the signed headers from an `io.SectionReader`; 200 → the ETag unquoted; 412 on the first attempt → `engine_failed`; a transport error retries at most twice, and a 412 after a transport error is accepted with ETag `""`; `now ≥ Expiry` before an attempt or 403 after it → `errGrantExpired`); `func writeResult(ctx context.Context, cfg Config, p media.Payload, r media.Result) error` (PUT of the JSON to the result transfer); `Run`'s flow: download → sniff → probe → check → (audio: measure, gain) → encode → (video: poster; audio: peaks) → children dead → `readFMP4` + `writePlaylist` → collect → upload three → result → exit 0. A `jobError` anywhere: best-effort result with that code, exit 1. `errGrantExpired`: exit 75, no result. SIGTERM: kill the children, exit 143, no result.
+
+- [ ] **Step 1: Write the failing tests** (`collect_test.go` builds hostile directories; `run_test.go` drives `Run` against Task 2's server and Task 3's fake ffmpeg, adding scenarios `ok-video` and `ok-audio` that write the Task 4 fixtures under the output names):
+ - `TestCollectRefusesHostileOutputs`: under each expected name in turn, a symlink to `/etc/passwd`, a symlink to a sibling regular file, a hard link (`Nlink` 2), a FIFO, a directory, a socket, an empty file, and a file one byte over its bound: `collect` fails and opens nothing else; the server receives no PUT.
+ - `TestCollectAcceptsRegularFiles`.
+ - `TestUploadSecondPutRefused` (§9: the server already holds the key: first-attempt 412 → `engine_failed`).
+ - `TestUploadRetryAfterTransportError` (the first PUT is cut after commit: the retry's 412 is accepted, ETag `""`).
+ - `TestRunSuccessWritesResultLast` (order at the server: GET, three PUTs, then the result; the result parses with `media.ParseResult`).
+ - `TestRunNamedErrorWritesResultAndExits1` (`no_video`).
+ - `TestRunExpiryBeforeLastUploadExits75` (the clock passes `Expiry` after the second output: exit 75, no third PUT, no result).
+ - `TestRunSIGTERMKillsChildren`.
+- [ ] **Step 2:** Run `go test ./internal/mediahandler/ -run 'TestCollect|TestUpload|TestRun' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: collect outputs by descriptor, upload, report`.
+
+---
+
+### Task 7: Hostile inputs, fuzzing, `selftest` and `drill`
+
+**Files:**
+- Modify: `internal/mediahandler/fakeffmpeg_test.go` (Task 3's helper; the scenarios below)
+- Create: `internal/mediahandler/hostile_test.go`, `internal/mediahandler/selftest.go`, `cmd/carlos-media/drill.go`, `cmd/carlos-media/drill_test.go`, `internal/mediahandler/testdata/corpus/*` (playlist-style files naming `http://169.254.169.254/` and `file:///etc/passwd`, a truncated MP4, an MP4 whose `dref` names `/etc/passwd`, a 0-byte file, 4 KiB of random bytes, an HTML file, a ZIP)
+
+**Interfaces:**
+- Produces: fake-ffmpeg scenarios `fail`, `fill-scratch` (writes until `ENOSPC` on a small tmpfs, Linux only, skipped elsewhere), `many-files` (100,000 empty files in the output directory), `symlink-out`, `hardlink-out`, `fifo-out`, `oversize-out`, `fork-setsid`, `ignore-term`; `func Selftest(ctx context.Context, cfg Config) error` (generates inputs with the image's real ffmpeg via `lavfi` (`testsrc2` 1080p 10 s with a 440 Hz tone; the same at 1080x1920 with `-display_rotation 90`; a PQ-tagged 10-bit 4K 5 s; a `-live 1` WebM Opus voice clip; a silent mono WAV; an MP3 with an attached picture), serves them from an in-process presigned-style server, runs `Run` for each, and checks: exit 0, output sizes, `readFMP4` and the playlist, the video output size from `targetSize`, the voice clip's output loudness within 1 LU of -16 or its true peak at most -1.5 dBTP and never above, its loudness range at least the source's less 0.5 LU, 1,000 peaks, the silent file's peaks all 0); `carlos-media selftest` prints one `PASS`/`FAIL <case>: <reason>` line per case and exits 0 or 1; `carlos-media drill <name>` with `creds` (no `AWS_*` variable; `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` and `_FULL_URI` absent or answering no credential; `169.254.170.2/v2/credentials` and `169.254.169.254` unreachable; the v4 task metadata endpoint yields no credential), `dns` (only the allowed names resolve; `example.com`, `amazonaws.com`, `sts.eu-west-1.amazonaws.com` do not), `net` (TCP to 1.1.1.1:443 and to a private address given as an argument fails), `foreign <access-key-id> <secret>` (signed requests from that principal to S3, the ECR API, ECR Docker and Logs endpoints are each refused with 403), `hostile-timer` (ignores SIGTERM and SIGINT, sends `SIGKILL` to every PID it can see and to `-1`, then loops), `fill-scratch`, `many-files`, `bad-outputs` (creates the hostile files of Task 6 under the output names, then calls `collect` and `upload` with the payload from `CARLOS_MEDIA_JOB`; prints how many PUTs were attempted, expected 0); each prints `PASS`/`FAIL` lines and never prints a credential, a URL or a header.
+
+- [ ] **Step 1: Write the failing tests:** `TestCorpusEndsInNamedErrors` (each corpus file through `Run` with the fake ffprobe answering as the real one would for it: a named code from `HandlerCodes`, never a panic, never exit 0, and no request other than the source GET and the result PUT); `TestPlaylistStyleFileMakesNoRequest` (the `169.254.169.254` file: `unsupported_container`, ffmpeg never started, the test server saw one GET); `TestHostileChildrenFailOnlyTheirJob` (`fill-scratch`, `many-files`, `fork-setsid`, `ignore-term`: exit 1 with a named error within the test's 30 s, no stray process left); `TestBadOutputsUploadNothing`; `TestDrillCredsReportsAnEnvCredential` (a fake environment with `AWS_SECRET_ACCESS_KEY` set: `FAIL`); `TestDrillOutputHasNoSecrets`.
+- [ ] **Step 2:** Run `go test ./internal/mediahandler/ ./cmd/carlos-media/ -run 'TestCorpus|TestPlaylistStyle|TestHostileChildren|TestBadOutputs|TestDrill' -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS. Then each fuzz target for 60 s. Expected: no crashers; add any found input to `testdata/fuzz/`.
+- [ ] **Step 5:** Commit: `media: hostile-input corpus, fuzzing, selftest and drills`.
+
+---
+
+### Task 8: The image
+
+**Files:**
+- Create: `cmd/mediaimage/main.go`, `lock.go`, `build.go`, `push.go`, `oci.go`, `deb.go`, `mediaimage_test.go`
+- Create: `deploy/media-image/debs.lock` (generated by Step 3), `deploy/media-image/README.md`
+- Modify: `Makefile` (targets `media-image-lock`, `media-image`)
+
+**Interfaces:**
+- Produces: `mediaimage lock --snapshot <YYYYMMDDTHHMMSSZ> --base docker.io/library/debian@sha256:<digest> --out deploy/media-image/debs.lock`: reads the base image's arm64 manifest and `var/lib/dpkg/status` from its layers through the registry API (anonymous token), fetches `Packages.xz` for `trixie`, `trixie-updates` and `trixie-security` `main binary-arm64` from `snapshot.debian.org` at that timestamp (decompressed with `xz -dc`), resolves `ffmpeg`'s `Pre-Depends` and `Depends` closure (first available alternative; a virtual name resolves to the first package that `Provides` it; `Recommends` and `Suggests` ignored), drops what the base already holds at the same version, and writes `# snapshot <ts>`, `# base <ref>`, then `package<TAB>version<TAB>url<TAB>sha256<TAB>size`, sorted. `mediaimage build --lock <file> --binary <carlos-media linux/arm64> --created <RFC3339> --out dist/media-image`: the base layers by digest, one layer of every `.deb`'s `data.tar` (sha256 checked against the lock; owners 0, mtimes `--created`, entries sorted), one layer with `/usr/local/bin/carlos-media` (0755) and an empty `/scratch` (0755); an OCI layout with config `architecture arm64`, `os linux`, `Entrypoint ["/usr/local/bin/carlos-media"]`, `User "65534:65534"`, labels `org.opencontainers.image.created`, `io.carlosframework.ffmpeg` (the lock's `ffmpeg` version), `io.carlosframework.debs-lock` (the lock's sha256); and `dist/media-image/image.json` = `media.ImageInfo` with the manifest digest. `mediaimage push --layout dist/media-image --repo <registry>/<repo>`: registry v2 push with basic auth `AWS:$CARLOS_REGISTRY_PASSWORD`, prints the digest. `make media-image` = `CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -o dist/carlos-media ./cmd/carlos-media && go run ./cmd/mediaimage build …`.
+- Rebuild cadence: every platform release builds the image (the release recipe gains `make media-image` and the push to each deployment's repository at roll time); weekly, `make media-image-lock` with the current snapshot opens a branch `media-image-lock-<date>` carrying only `debs.lock`. Who runs the weekly step is what plan 1's report found: an amadan scheduled job if amadan CI has schedules, else a Paseo schedule on docs-t1 set up in R1 with Paul's go. `carlos system media status` warns at 30 days either way.
+
+- [ ] **Step 1: Write the failing tests:** `TestLockParsesAndSorts`; `TestResolveClosure` (a hand-written `Packages` fixture with alternatives, a virtual package, a `Pre-Depends`, a cycle and a package already in the base status); `TestBuildIsDeterministic` (two builds from fixture `.deb`s and a fixture base layout with the same `--created` give the same manifest digest); `TestBuildRefusesABadDebHash`; `TestImageConfig` (entrypoint, user, labels, arch).
+- [ ] **Step 2:** Run `go test ./cmd/mediaimage/ -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. Generate the real `debs.lock` on a Debian 13 host with `xz` (docs-t1), with the snapshot timestamp and base digest written in the commit body. Write the README: what the image holds, `make media-image`, pushing to a deployment's repository, pinning `image_digest`/`image_built_at`/`image_ffmpeg` in the root, rollback to the previous digest, the weekly lock refresh. The README is user-facing: copy-review it.
+- [ ] **Step 4:** Rerun Step 2's command. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: reproducible arm64 image from Debian 13 packages`.
+
+---
+
+### Task 9: The AWS adapters **[Astra: security gate, production storage]**
+
+**Files:**
+- Create: `internal/mediaaws/config.go`, `engine.go`, `grants.go`, `buckets.go`, `mediaaws_test.go`, `minio_test.go`
+- Modify: `go.mod`, `go.sum` (`github.com/aws/aws-sdk-go-v2/service/ecs`, the release compatible with `aws-sdk-go-v2 v1.44.0`), `.amadan/ci.d/30-minio-contract` (one block in the shape of the `TestDBForwardMinio` block, :525-546)
+
+**Interfaces:**
+- Consumes: `media.Engine`, `media.Grants`, `media.CheckTaskDefinition`, `storecfg.Buckets`, `storecfg.UploadsCORS`, `storecfg.UploadsLifecycle`.
+- Produces: `type Config struct{ V int \`json:"v"\`; Region string \`json:"region"\`; Cluster string \`json:"cluster"\`; TaskDefinitions map[string]string \`json:"task_definitions"\`; Subnets []string \`json:"subnets"\`; SecurityGroup string \`json:"security_group"\`; ConversionRole string \`json:"conversion_role"\`; ResultsBucket string \`json:"results_bucket"\`; StorePrefix string \`json:"store_prefix"\`; AccountID string \`json:"account_id"\`; Image media.ImageInfo \`json:"image"\` }` and `func ParseConfig(v string) (Config, error)` (strict; `v` 1; exactly the four `ClassKey.String()` keys, each a task-definition ARN with a revision; at least one subnet; `Image.Digest` `sha256:` + 64 hex). Narrow client interfaces `ECSAPI`, `STSAPI`, `S3API`. `func NewEngine(c Config, api ECSAPI) media.Engine`; `func NewGrants(c Config, assume func(ctx context.Context, sessionName, policy string) (aws.Credentials, error), console S3API) media.Grants`; `func NewBuckets(accountID string, api S3API) storecfg.Buckets`; `func New(ctx context.Context, c Config) (media.Engine, media.Grants, error)` (real clients from the console's default AWS config).
+- Engine: `Run` → `RunTask{Cluster, TaskDefinition: c.TaskDefinitions[class], LaunchType FARGATE, PlatformVersion "1.4.0", Count 1, StartedBy: execution, ClientToken: execution, EnableExecuteCommand: false, NetworkConfiguration awsvpc {Subnets, SecurityGroups [sg], AssignPublicIp DISABLED}, Overrides{ContainerOverrides: codec env [PayloadEnv], deadline env [DeadlineEnv, ExpiryEnv]; EphemeralStorage when EphemeralGiB > 0}}`. Answer: a task → its ARN; failures and no task → `*Rejected{Retryable: reason starts "RESOURCE:" or contains "Capacity"}`; a client-fault API error → `*Rejected{Retryable: code == "ThrottlingException"}`; a server fault, a timeout or a transport error → returned as is (ambiguous). `Describe` in batches of 100, `MISSING` failures → `missing`; container exit codes by name. `ListByStartedBy`: `ListTasks` with desired status `RUNNING`, then `STOPPED` (paginated), described, matched on `startedBy`. `Stop`: `StopTask`; an already-stopped or missing task is success. `CheckRevision`: `DescribeTaskDefinition` → `media.TaskDefinition` → `CheckTaskDefinition`, cached per revision ARN.
+- Grants: `Grant` assumes the conversion role (session `media-<execution>`, 3600 s, session policy: `GetObject` on `arn:aws:s3:::<bucket>/*`, `PutObject` on `arn:aws:s3:::<bucket>/derived/*` and on `arn:aws:s3:::<results bucket>/media-results/<execution>.json`), then presigns with those credentials, `X-Amz-Expires` 3600, path-style only when the bucket name has a dot: `GetObject` with `IfMatch: "\"<etag>\""`; three `PutObject` with `IfNoneMatch: "*"` and `ContentType: media.ContentType(name)`; the result `PutObject` with `IfNoneMatch: "*"` and `application/json`. It splits each presigned URL into base and the seven `X-Amz-*` parameters, requires `Algorithm`, `Credential`, `Expires` and `Security-Token` equal across all five (else presigns once more, then errors), takes `SignedHeader` (less `Host`) as `Header`, and requires every output base to equal `OutPrefix + name`. The expiry is the credentials' `Expires`. `Head` uses one session per bucket (`media-head`, `GetObject` on that bucket only), reused until 15 minutes before it expires; 404 → `ErrNotFound`, 403 → `ErrDenied`. `ReadResult`: `GetObject` with `Range: bytes=0-65536` on the console's own client; more than 65,536 bytes → `ErrResultTooLarge`; `NoSuchKey` → `ErrNotFound`. `DeleteResult`, `DeleteOutputs`: the console's own client, absent is success.
+- Buckets: `Inspect` = `HeadBucket` with `ExpectedBucketOwner` set to the account id (success → `Owner` is that id; 403 → `Owner` empty), `GetBucketLocation` (`""` means `us-east-1`), `GetBucketEncryption`, `GetBucketVersioning`, `GetBucketPolicy` (`NoSuchBucketPolicy` → none), `GetBucketLifecycleConfiguration` and `GetBucketCors` each turned into the same canonical JSON `storecfg` writes (absent → nil). `PutUploads` = `PutBucketCors` and `PutBucketLifecycleConfiguration` from that canonical JSON; `DeleteUploads` = `DeleteBucketCors`, `DeleteBucketLifecycle`.
+
+- [ ] **Step 1: Write the failing tests** (stub clients recording inputs): `TestParseConfig`; `TestRunTaskInput` (every field above; payload in the codec's environment only; deadline values in the deadline's only; `EnableExecuteCommand` false); `TestRunTaskOverrideFits` (the worst-case payload of plan 2's `TestWorstCasePayloadFits` with the real token length from plan 1's report: the marshalled overrides at most `MaxOverrideBytes`); `TestRunErrorsClassified` (failures with `RESOURCE:CPU`: retryable rejection; `InvalidParameterException`: final; `ThrottlingException`: retryable; `ServerException` and a timeout: ambiguous); `TestListByStartedByReadsBothLists`; `TestCheckRevisionCachesPerRevision`; `TestGrantSessionPolicy` (exact JSON); `TestGrantTransfersShareOneCredential`; `TestHeadClassifiesErrors`; `TestReadResultBounded` (65,537 bytes: `ErrResultTooLarge`); `TestBucketsCanonicalRoundTrip` (what `PutUploads` sends, echoed back by `Inspect`, hashes to `storecfg.Hash(UploadsCORS(o))` and `Hash(UploadsLifecycle())`). In `minio_test.go`, skipped without `CARLOS_MINIO_TEST`: `TestMediaTransfersMinio` (static credentials in place of `assume`: the presigned GET downloads with the right `If-Match` and gets 412 after the object is rewritten; a presigned output PUT succeeds once and gets 412 the second time; the handler's `download` and `upload` from plan 3 Tasks 2 and 6 run against those URLs).
+- [ ] **Step 2:** Run `go test ./internal/mediaaws/ -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement. Add the CI block: `CARLOS_MINIO_TEST=1 MINIO_ENDPOINT=… go test ./internal/mediaaws/ -run 'TestMediaTransfersMinio' -count=1 -v`, failing unless `--- PASS: TestMediaTransfersMinio (` appears.
+- [ ] **Step 4:** Rerun Step 2's command. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: ECS, STS and S3 adapters`.
+
+---
+
+### Task 10: Console wiring
+
+**Files:**
+- Modify: `cmd/console/main.go` (beside `CARLOS_PDF_LIMITS` at :392, the `Config` literal at :594-603, the store backend block at :1089-1124, and the workers at :826), `cmd/console/media_test.go` (create)
+
+**Interfaces:**
+- Produces: `func mediaFromEnv(getenv func(string) string, store storeEnv, hostClaim bool) (mediaWiring, error)` in `cmd/console`: `CARLOS_STORE_CONVERSION=1` requires `CARLOS_STORE_BACKEND`, calls `sts:GetCallerIdentity` once for `StoreAccountID`, and sets `StoreConversion` and `StoreBuckets` (`mediaaws.NewBuckets`); `CARLOS_MEDIA_LIMITS` → `media.ParseLimits`; `CARLOS_MEDIA_ENGINE` → `mediaaws.ParseConfig`, refused (`log.Fatalf`, a diagnostic, not deck copy) with `CARLOS_HOST_CLAIM`, without `CARLOS_STORE_CONVERSION=1`, with a region other than `CARLOS_STORE_REGION`, a store prefix other than `CARLOS_STORE_BUCKET_PREFIX`, or an account other than the caller's; then `mediaaws.New` → `MediaEngine`, `MediaGrants`, `MediaRegion`, `MediaImage`. `go srv.RunClaimWorker(context.Background(), "StartMediaPass")` beside `StartScanPass`.
+
+- [ ] **Step 1: Write the failing test** `TestMediaFromEnv`: unset → nothing configured; each refusal above → its error; a valid set → every field.
+- [ ] **Step 2:** Run `go test ./cmd/console/ -run TestMediaFromEnv -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `console: wire media conversion from the environment`.
+
+---
+
+### Task 11: `infra/modules/media-engine` **[Astra: production infrastructure, security gate]**
+
+**Files:**
+- Create: `infra/modules/media-engine/{main.tf,network.tf,iam.tf,ecs.tf,reaper.tf,variables.tf,outputs.tf,versions.tf,README.md}`, `infra/modules/media-engine/reaper/reaper.py`, `reaper/reaper_test.py`, `infra/modules/media-engine/tests/media_engine.tftest.hcl`
+- Modify: `infra/modules/README.md` (module list)
+
+**Interfaces:**
+- Variables (`pdf-host`'s style): `name`, `region`, `store_region`, `store_bucket_prefix`, `deployment_bucket_name`, `console_role_name`, `console_role_arn`, `image_digest` (default `""`), `image_built_at`, `image_ffmpeg`, `vpc_cidr` (default `10.98.0.0/24`), `logs` (default `true`), `log_retention_days` (default 14), `reaper_max_age_minutes` (default 70), `classes` (default: the four rows, each `{preset, class, cpu, memory}`: `video-720p/short` 4096/8192, `video-720p/long` 16384/32768, `audio-aac/short` 1024/2048, `audio-aac/long` 2048/4096; spike).
+- Outputs: `carlos_media_engine` (`""` while `image_digest` is `""`; else `jsonencode` of plan 3 Task 9's `Config` with `v = 1`), `repository_url`, `cluster_arn`, `conversion_role_arn`.
+- Resources: an ECR repository (`IMMUTABLE` tags, scan on push); the VPC with DNS support and hostnames, two private `/25` subnets in two zones, one route table with no default route, no internet gateway and no NAT; a tasks security group with no ingress and egress only TCP 443 to the S3 prefix list and to the endpoints' security group; the endpoints' group admitting TCP 443 from the tasks' group only; an S3 gateway endpoint and interface endpoints `ecr.api`, `ecr.dkr` and (when `logs`) `logs`, private DNS on; their policies (below); a Route 53 Resolver DNS Firewall with an allow list (`s3.<region>.amazonaws.com`, `*.s3.<region>.amazonaws.com`, `api.ecr.<region>.amazonaws.com`, `*.dkr.ecr.<region>.amazonaws.com`, `logs.<region>.amazonaws.com`) at priority 100 `ALLOW` and `*` at 200 `BLOCK` with `NXDOMAIN`, associated with the VPC with mutation protection on, and `firewall_fail_open` `DISABLED`; a log group; the task execution role (trust `ecs-tasks.amazonaws.com` with `aws:SourceAccount`; `ecr:GetAuthorizationToken` on `*`, the three pull actions on the repository, `logs:CreateLogStream` and `logs:PutLogEvents` on the log group); the conversion role (trust: `console_role_arn` only; Allow `s3:GetObject` on `arn:aws:s3:::<prefix>*/*`, `s3:PutObject` on `arn:aws:s3:::<prefix>*/derived/*` and on `arn:aws:s3:::<deployment bucket>/media-results/*`; Deny `s3:GetObject` on `arn:aws:s3:::<prefix>*/*` when `s3:ExistingObjectTag/carlos-scan` is `infected`; Deny `s3:PutObject` on `*` when `ForAnyValue:StringEquals s3:RequestObjectTagKeys` is any of `carlos-scan`, `carlos-scan-version`, `carlos-scan-at`, `carlos-scan-sig`; max session 3600 s); the cluster (Fargate only, Container Insights off); four task definitions (one per `classes` entry, family `<name>-<preset>-<class>`, the Global Constraints' container shape, `deadline` with 64 CPU units and 64 MiB, `codec` with the rest, `codec` env `TMPDIR=/scratch/tmp`, `awslogs` on `codec` only when `logs`, `runtime_platform` `LINUX`/`ARM64`, no `task_role_arn`, no `pid_mode`, volume `scratch` with no host path; if plan 1 reports that RunTask refuses `ephemeralStorage` per run, each definition instead sets `ephemeral_storage` to its class's largest need, 48 GiB for video long and the 20 GiB default elsewhere, and `EphemeralGiB` is never sent), created only when `image_digest` is set; a role policy on `console_role_name` (`sts:AssumeRole` on the conversion role; `ecs:RunTask` on `arn:aws:ecs:<region>:<acct>:task-definition/<name>-*:*` with `ArnEquals ecs:cluster`; `ecs:DescribeTasks` and `ecs:StopTask` on `arn:aws:ecs:<region>:<acct>:task/<cluster>/*`; `ecs:ListTasks` on `*` with `ArnEquals ecs:cluster`; `ecs:DescribeTaskDefinition` on `*`; `iam:PassRole` on the execution role with `iam:PassedToService` `ecs-tasks.amazonaws.com`); the reaper (a Python 3.13 arm64 Lambda from `reaper/reaper.py`, env `CLUSTER` and `MAX_AGE_MINUTES`, timeout 50 s, its own log group, a role with `ecs:ListTasks` under the cluster condition, `ecs:DescribeTasks` and `ecs:StopTask` on the cluster's tasks and logging to its own group only, an EventBridge rule `rate(1 minute)` targeting it); a precondition that `region == store_region`.
+- Endpoint policies: S3 gateway: Allow `s3:GetObject`, `s3:PutObject` on the store prefix and `media-results/*` for principal `*` with `StringEquals aws:PrincipalArn` = the conversion role ARN; Allow `s3:GetObject` on `arn:aws:s3:::prod-<region>-starport-layer-bucket/*` for `*`. ECR API and Docker: Allow `ecr:BatchGetImage`, `ecr:GetDownloadUrlForLayer`, `ecr:BatchCheckLayerAvailability` on the repository and `ecr:GetAuthorizationToken` on `*`, each with `aws:PrincipalArn` = the execution role. Logs: Allow `logs:CreateLogStream`, `logs:PutLogEvents` on the log group with `aws:PrincipalArn` = the execution role.
+- `reaper.py`: `handler(event, context)` lists `RUNNING` tasks (paginated), describes them in batches of 100, and stops each whose `createdAt` is older than `MAX_AGE_MINUTES` with reason `carlos media reaper: older than <n> minutes`; it reads no other input.
+
+- [ ] **Step 1: Write the failing tests.** `media_engine.tftest.hcl` with `mock_provider "aws" {}`, runs: `region_must_be_store_region` (`expect_failures`); `no_digest_creates_only_the_repository` (no task definitions, `carlos_media_engine == ""`); `task_definitions_pass_the_gate` (for each of four: `task_role_arn == null`, `pid_mode == null`, ARM64, and on `jsondecode(container_definitions)`: names, essential, `dependsOn` `deadline`/`START`, `stopTimeout` 30 both, read-only root, user, caps drop `ALL`, images equal `<repo>@<digest>`, `scratch` mounted in `codec` only, CPU and memory per class); `endpoint_policies_name_their_principals` (every statement of the three interface policies has the execution-role condition; the S3 policy's two statements exactly); `tasks_sg_has_no_ingress_and_only_https_egress`; `no_default_route`; `dns_firewall_allows_three_services_and_blocks_the_rest`; `conversion_role_policy_exact` (three Allows, two Denies, trust only the console role); `console_policy_exact`; `reaper_role_is_cluster_scoped`; `output_parses` (the output's JSON has `v` 1, the region, four task definitions and the image). `reaper_test.py` (stdlib `unittest`, a stub client): an old task is stopped, a young one is not, pagination across two pages, a describe failure stops nothing.
+- [ ] **Step 2:** Run `cd infra/modules/media-engine && tofu init -backend=false && tofu test` and `python3 -I -m unittest discover -s infra/modules/media-engine/reaper`. Expected: FAIL.
+- [ ] **Step 3:** Implement. `tofu fmt -check` and `tofu validate` clean. Write the README in `pdf-host`'s shape (what it is, the two-phase apply: repository first, then the digest; wiring `carlos_media_engine` → `CARLOS_MEDIA_ENGINE`; the region rule; the activation gates of spec §5.5; rollback by digest); copy-review it.
+- [ ] **Step 4:** Rerun Step 2's commands. Expected: PASS.
+- [ ] **Step 5:** Commit: `infra: media-engine module, one Fargate task per conversion`.
+
+---
+
+### Task 12: `region-host` `store_conversion` **[Astra: production infrastructure]**
+
+**Files:**
+- Modify: `infra/modules/region-host/variables.tf` (beside `store_scanning`, :297-301), `infra/modules/region-host/main.tf` (boundary statements :809-821; a new policy beside `host_store_scan`, :962-980), `infra/modules/region-host/README.md`
+- Create: `infra/modules/region-host/tests/store_conversion.tftest.hcl` (the shape of `store_scanning.tftest.hcl`)
+
+**Interfaces:**
+- Produces: `variable "store_conversion"` (bool, default false; set it with `CARLOS_STORE_CONVERSION=1` on the console); `aws_iam_role_policy.host_store_conversion` (count on the switch; precondition `store_bucket_prefix != ""`) allowing `s3:GetBucketPolicy`, `s3:GetEncryptionConfiguration`, `s3:GetBucketVersioning`, `s3:GetBucketCORS`, `s3:PutBucketCORS`, `s3:GetLifecycleConfiguration`, `s3:PutLifecycleConfiguration` on `arn:aws:s3:::<prefix>*`; the store boundary's object statement gains `s3:AbortMultipartUpload` and `s3:ListMultipartUploadParts` when the switch is on.
+
+- [ ] **Step 1: Write the failing tftest:** off by default creates nothing and leaves the boundary byte for byte; on grants exactly those seven actions on that resource; on adds the two multipart actions to the boundary and nothing else; on without a prefix fails its precondition.
+- [ ] **Step 2:** Run `cd infra/modules/region-host && tofu init -backend=false && tofu test -filter=tests/store_conversion.tftest.hcl`. Expected: FAIL.
+- [ ] **Step 3:** Implement; README paragraph beside `store_scanning`'s; copy-review it.
+- [ ] **Step 4:** Rerun, and `tofu test` for the module's other files. Expected: PASS.
+- [ ] **Step 5:** Commit: `infra: store_conversion switch for provenance and uploads`.
+
+---
+
+### Task 13: The provider boundary
+
+**Files:**
+- Create: `internal/medialocal/runner.go`, `runner_linux.go`, `runner_other.go`, `runner_test.go`, `internal/medialocal/minio_test.go`, `internal/media/boundary_test.go`
+- Modify: `.amadan/ci.d/30-minio-contract` (one more block, as Task 9's)
+
+**Interfaces:**
+- Produces: `func New(binary, scratchRoot string) *Runner` implementing `media.Engine` without any cloud API: `Run` makes a fresh `0700` scratch directory under `scratchRoot` per execution, starts `<binary> codec` with only `CARLOS_MEDIA_JOB`, `PATH` and `TMPDIR=<scratch>/tmp` in its environment, its own process group, and the runner's own timer standing in for the deadline container (`media.DeadlineSleep`; at the deadline `SIGTERM`, then `SIGKILL` after `StopGrace`); `Describe` reports `StartedAt`, `StoppedAt`, the codec's exit and `DeadlineExit` 0 when the timer fired, else 143; `ListByStartedBy` by execution; `Stop` as the timer does; `CheckRevision` nil; the scratch directory removed when the task is described stopped. It is not wired into the console: a MinIO deployment would run the image under systemd with `RuntimeMaxSec` (spec §8); this runner is that shape for tests.
+- `TestCoreLinksNoCloudSDK`: `go list -deps` (linux/amd64 and linux/arm64, `CGO_ENABLED=0`) of `./internal/media/...`, `./internal/mediajobs/...`, `./internal/mediahandler/...`, `./internal/medialocal/...`, `./internal/storecfg/...`, `./cmd/carlos-media`: no path under `github.com/aws/`, none under `internal/console`; and `go list -deps .` contains none of those packages (the root census scope stays as it was).
+
+- [ ] **Step 1: Write the failing tests:** `TestCoreLinksNoCloudSDK`; `TestRunnerDeadlineEndsAnIgnoringChild` (a fake codec that ignores SIGTERM: gone within deadline plus `StopGrace` plus 1 s, `DeadlineExit` 0); `TestRunnerScratchIsPerExecution`; `TestLocalEndToEndMinio` (skipped without `CARLOS_MINIO_TEST`: `mediajobs` with this runner (the `carlos-media` binary built once with the fake ffmpeg scenario `ok-video`), `mediaaws` grants with static credentials against MinIO, a submitted job goes to `done`; its three outputs are in the bucket under its execution's prefix, the result object is deleted by cleanup).
+- [ ] **Step 2:** Run `go test ./internal/media/ -run TestCoreLinksNoCloudSDK -count=1 && go test ./internal/medialocal/ -count=1`. Expected: FAIL.
+- [ ] **Step 3:** Implement; add the CI block for `TestLocalEndToEndMinio`.
+- [ ] **Step 4:** Rerun. Expected: PASS.
+- [ ] **Step 5:** Commit: `media: local runner and the provider boundary guard`.
+
+---
+
+### Task 14: Census, whole-branch review and merge
+
+- [ ] **Step 1:** `git fetch origin && git merge origin/main`; rerun plan 2 Task 12 Steps 2 to 4 with this plan's files (the claims file gains the `infra/` files and `go.mod`/`go.sum`: what each is, and that root never reads them at runtime).
+- [ ] **Step 2:** Run `go test ./internal/provision/ -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary|TestPlan9B8RecordWriteCensus' -count=1`, `go vet` on every new package, `gofmt -l .`, and the cross-compiles. Expected: PASS, clean.
+- [ ] **Step 3:** Push. Astra reviews the census card and the whole branch (plans 2 and 3), Fable the branch, within the round budget, briefed from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md` with the spec, these plans and plan 1's report; verdicts on #280.
+- [ ] **Step 4:** Green CI on the tip, then merge only on Paul's go: `amadan branch merge carlos/platform media-conversion -squash -expect <full sha> -message "<subject under 80 characters>"` with the body naming the spec and the census verdict.
+
+---
+
+## Rollout (controller tasks; each needs Paul's go)
+
+Ask each time with the account, region, resources, cost, duration, traffic effect and cleanup (AGENTS.md). Dev first.
+
+### R1: Release and image
+
+- [ ] Ask Paul. Cut a release carrying the branch (release recipe; push the tag to the GitHub mirror). `make media-image` from the release tag; record `image.json`. Set up the weekly lock refresh the spike report chose.
+
+### R2: Dev infrastructure
+
+- [ ] Ask Paul (profile `kass`, `eu-west-1`). In the dev root: `store_conversion = true` on the console's region-host; `media-engine` with `image_digest = ""`; apply. Push the image to the new repository (`mediaimage push`), set `image_digest`, `image_built_at`, `image_ffmpeg`; apply. Set `CARLOS_STORE_CONVERSION=1` and `CARLOS_MEDIA_ENGINE=<output>` on the dev console through the roll restart. Check `carlos system media status`: configured, four gates `ok`, image age.
+- [ ] Run `carlos-media selftest` once per class as a one-off task (`aws ecs run-task` with the class's task definition and `command ["selftest"]` on `codec`). Expected: every case `PASS`.
+
+### R3: Dev drills, attacks first (spec §9)
+
+Each drill names its tool; record every result in `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md`.
+
+- [ ] Infected source refused at the door with enforcement off; tagged between submission and dispatch: `failed source_unreadable` at the download.
+- [ ] Another app's token, another account's token, a `derived/` key: refused. Stores adopted under the minted name with a foreign bucket policy, with SSE-KMS, with a foreign lifecycle rule: each `store_unverified` with its check (the adopted one passes once its policy is removed).
+- [ ] `drill creds`, `drill dns`, `drill net <console private IP>` and `drill net <another box's private IP>` as one-off tasks: all `PASS`; an unsigned S3 request and `drill foreign <key> <secret>` with Paul's unrelated-account no-permission user: refused at all four endpoints.
+- [ ] The corpus files uploaded to a dev store and converted: each ends in its named error; the `169.254.169.254` playlist makes no request.
+- [ ] `drill fill-scratch`, `drill many-files`, `drill bad-outputs`: each fails its own task only; `bad-outputs` attempted 0 PUTs.
+- [ ] A source rewritten between submission and dispatch: `source_changed`. A second PUT to a committed output key with a leaked transfer: refused.
+- [ ] The console stopped while four tasks run: on restart no fifth starts until one is confirmed stopped; each completes and is charged ECS's times.
+- [ ] A task definition revision with a bad digest: fails to start twice, `engine_unavailable` uncharged. A `RunTask` rejected by the service (a deliberately invalid subnet in a test config) versus a transport error (the console's ECS endpoint pointed at a black hole for one dispatch): the first `engine_unavailable`, the second recovered.
+- [ ] Console stopped; a task running `drill hostile-timer` with a 3-minute deadline: gone within 3 min 30 s, `deadline_exceeded` after restart.
+- [ ] The console killed after `RunTask` and before the ARN is saved, the task finishing before restart: `done`, charged ECS's times.
+- [ ] Store destroy with a task running: refused until it stops; destroy and recreate: the same key and bytes make a new job.
+- [ ] App purge with one job queued and one running: both retired, the task stopped, charged and cleaned; a new app of that name sees neither.
+- [ ] A task definition revision with `deadline` made to start late (a `sleep 60` entrypoint wrapper revision): `codec` starts only after it; one whose `deadline` cannot start: `codec` never runs. Revisions without the `START` dependency or with `stopTimeout` 20: refused at dispatch, door 503 `engine_misconfigured`.
+- [ ] Allowance: 10 minutes left and a one-hour video: `allowance_exceeded` at the probe. 20 minutes left, a long audio file and a video together: never reserved or charged past 20. A source over the size maximum, one over the duration maximum, and an account at twice its limit: each refused.
+- [ ] A 20-minute video under 1 GiB without a class: `needs_long_class`; resubmitted with `"class": "long"`: converts as a new job. Both long places taken: a clip starts at once, also for an account whose own long job waits.
+- [ ] A 20 GiB source uploaded in parts converts inside the hour. A WebM voice recording, an MP3, a WAV and a video's audio track each convert with `audio-aac`, 1,000 peaks; loudness as the selftest checks; a silent file converts to silence.
+
+### R4: Dev playback
+
+- [ ] A two-minute 1080p phone clip uploaded from a browser on a dev app's origin (`carlos store uploads enable`), converted, played from `video.mp4` through a redirect to a presigned GET in Safari on iOS (Paul's iPhone or the tito-studio Mac's simulator), Chrome and Firefox, and from `video.m3u8` proxied on the app's origin in Safari and hls.js, inside the time plan 1's report set. A browser voice recording the same way with `audio.mp4` and `audio.m3u8`. A repeated submission returns the same job and converts nothing. Report to Paul.
+
+### R5: Flagship
+
+- [ ] Paul confirms the H.264/AAC licensing question (decision 11) before flagship charges for conversion.
+- [ ] Ask Paul (profile `keymail`). Bump `?ref=` to the release tag in `carloku-infrastructure`, read plan, apply R2's steps, run the attack drills of R3 and R4's playback once.
+- [ ] Ask Paul for the media pack's prices; write the next catalog and pricebook (`deploy/billing/`) with `media_minutes_month` Free 30, Personal 600, Community 1,200, Business 12,000 and the `media` pack (`adds.media_minutes_month: 1000`, `max_quantity` 20, offered on the paid plans), and apply them through the operator plan door. Tell Paul it is live.
+
+Report with R3: the spec says the task never sees an account or app name (§10), but a minted bucket name is `<prefix><account>-<app>` and every transfer's host carries it.