plans: media conversion plans, round 2 rulings applied
One shared endpoint drill with independent controls (restrictive, permissive, restored; no error-text assertions; door unset until it passes) run by the spike and rollout R3. Done jobs charged by bounded duration per spec A2; host-claim refusal cites spec A1; the spike deletes its foreign-account log group.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md+13 −5docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md+18 −9docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md+21 −7
Intent
<task-notification> <task-id>afb34e431dff63a6f</task-id> <tool-use-id>toolu_01Mcqg8TNCVz226DB6RgN9Kr</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>The round 3 edits are in all three plans, and each plan's review log has a round 2 section. Nothing is committed or pushed, and I left no scratch files. ## Line counts - `docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md`: 137 - `docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md`: 566 - `docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md`: 378 ## Per item - **R2-1 (endpoint proof):** the endpoint drill is now defined once, in plan 3 Task 7. - The foreign user's registry token and the presigned S3 GET are made outside the VPC and passed into the task. - One pass (`carlos-media drill endpoints`) makes the same four authenticated requests. It prints only `ok` or `refused <status>` per endpoint, with no error text. - `scripts/media-endpoint-drill.sh` runs that pass three times: under the real policies (must fail), under AWS's full-access policy (must succeed), and under the restored policies (must fail). `endpoints-verdict` passes only on that pattern, and the script restores the saved policies on every exit path. - Plan 1 Task 4 Step 3 and plan 3's R3 both run this drill, and the old `drill foreign` is gone. - The policy swap is now in R2's scope request as well as the spike's, and the door stays unset until the drill passes. - **R2-2 (charging):** a done job is charged `w × source_ms` again, per spec §11 A2, and `max(duration, runtime)` is removed everywhere. - The 0 to granted bound and the hostile-result witnesses stay. A duration far below runtime is now accepted and charged by its duration, with `charged_ms` still holding the runtime. - The test is renamed `TestDoneChargedByDuration`. The review log notes that A2 states the residual risk. - **R2-3 (host-claim):** the global constraint and both door checks (conversion and uploads) now cite spec §11 A1, and "Paul has to rule" is gone. - **R2-4 (log group):** plan 1 names the foreign account's log group `mediaspike-endpoint-drill`. Task 8 deletes it and checks it's gone, along with the user. Plan 3's R3 cleanup also deletes and verifies its own drill resources. Nothing new for Paul from this round.</result> <usage><subagent_tokens>615679</subagent_tokens><tool_uses>9</tool_uses><duration_ms>157923</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| index 9b1bd7251..cff9b666b 100644 |
| --- 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 |
| @@ -32,12 +32,12 @@ |
| **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>`. |
| +**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>…`, `endpoints` (and the driver's `endpoints-verdict`), built to plan 3 Task 7's definition of the endpoint drill and nothing else, `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 1:** Write `mediaspike`, and a scratch copy of `scripts/media-endpoint-drill.sh` to plan 3 Task 7's definition (the drill is defined only there; plan 3 builds the committed version); `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/`, `RUN mkdir /scratch && chown 65534:65534 /scratch && chmod 0700 /scratch`, `VOLUME ["/scratch"]` (plan 3's image does the same), `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; for the foreign-credential gate, in an unrelated account Paul names, one IAM user and access key whose identity policy allows `s3:GetObject` and `s3:PutObject` on the spike bucket, `ecr:GetAuthorizationToken` and the pull actions on the spike repository, and `logs:CreateLogStream`/`logs:PutLogEvents` on one log group in that account, plus that log group; a spike-bucket policy and a spike-repository policy admitting that user; and, for minutes inside Task 4 Step 3, each of the four endpoint policies replaced by AWS's default full-access policy as a positive control and then restored; 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. |
| +- [ ] **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; for the foreign-credential gate, in an unrelated account Paul names, one IAM user and access key whose identity policy allows `s3:GetObject` on one object of the spike bucket, `ecr:GetAuthorizationToken` and the pull actions on the spike repository, and `logs:CreateLogStream`/`logs:PutLogEvents` on one log group in that account, plus that log group, named `mediaspike-endpoint-drill` in `eu-west-1`; a spike-bucket policy and a spike-repository policy admitting that user; and, for minutes inside Task 4 Step 3, each of the four endpoint policies replaced by AWS's default full-access policy as a positive control and then restored; 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. |
| --- |
| @@ -64,7 +64,7 @@ Each step runs one or more tasks through `mediaspike run` and records the probe' |
| - [ ] **Step 1: Credentials.** `--command creds` on each class. Expected: none of the credential-bearing variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_SECURITY_TOKEN`, `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN`, `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`, `AWS_WEB_IDENTITY_TOKEN_FILE`, `AWS_ROLE_ARN`); `AWS_EXECUTION_ENV` and the region variables are recorded and allowed; `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: refused at the S3 endpoint. |
| -- [ ] **Step 3: Foreign credentials, with both controls.** The foreign user's five requests (`GetObject` and `PutObject` on the spike bucket, `ecr:GetAuthorizationToken`, a manifest `HEAD` on the spike repository, `logs:PutLogEvents` to its own log group) run three times. (a) From docs-t1, outside the engine VPC: all five succeed, so its credentials and the bucket and repository policies allow them. (b) `--command foreign` inside a task, with the four endpoint policies as plan 3 writes them: all five refused, each error naming the VPC endpoint policy. (c) The four endpoint policies swapped to AWS's default full-access policy for one more task: all five succeed, so (b)'s refusals came from the endpoint policies; then restore the policies, re-run (b) and expect it to refuse again. Record the policy swap's start and end times. |
| +- [ ] **Step 3: The endpoint drill.** Run the endpoint drill exactly as plan 3 Task 7 defines it (registry token minted outside the VPC and passed in; the same four authenticated requests under the restrictive policies, AWS's full-access policy, and the restored policies) with the foreign user, on the video-short task definition. Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and the saved policies are back. Record the table and the policy swap's start and end times. Causality comes from phase B, not from error text. |
| - [ ] **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; and the codec, as `65534`, can create `/scratch/in`, `/scratch/out` and `/scratch/tmp` on the bind mount (record `stat /scratch`: owner, mode). |
| - [ ] **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. |
| @@ -111,7 +111,7 @@ Each step runs one or more tasks through `mediaspike run` and records the probe' |
| - [ ] **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), the muxer flags and the top-level box sequence of the fixtures (plan 3 expects `ftyp`, `moov`, then `moof`/`mdat` pairs with `skip_trailer`), whether `/scratch` is writable by 65534, `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. |
| +- [ ] **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, and its log group `mediaspike-endpoint-drill` deleted (`aws logs delete-log-group`), each verified absent in that account (`aws iam get-user` answers `NoSuchEntity`; `aws logs describe-log-groups --log-group-name-prefix mediaspike-endpoint-drill` lists nothing), by 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. |
| --- |
| @@ -127,3 +127,11 @@ Round 1 of at most 3: Astra against `99398b7d` (`docs/superpowers/plans/CODEX-FI |
| | F10 P1 trailer and audio fragments (spike half) | Accepted. Task 3 Step 4 records the fixtures' box sequence and muxer flags, which plan 3's parser tests depend on. | |
| | F13 P2 `AWS_*` too broad | Accepted. Task 4 Step 1 checks the credential-bearing variables by name. | |
| | F3 to F8, F11, F12, F14 to F16 | Plans 2 and 3; nothing changes here. | |
| + |
| +Round 2: Astra (`docs/superpowers/plans/CODEX-FINDINGS-MEDIA-PLANS-R2.md`), revise. R2-1 hit stopping rule 2; Paul took Opus's pick on 2026-11-16. A narrow round 3 checks only the endpoint drill. |
| + |
| +| Finding | Handling in this plan | |
| +|---|---| |
| +| R2-1 P1 endpoint proof | Accepted, as Paul's pick: Task 4 Step 3 runs the one endpoint drill defined in plan 3 Task 7 (token minted outside the VPC; restrictive, permissive, restored; no error-text assertions). The scope request already holds the permissive swap. | |
| +| R2-4 P2 foreign log group cleanup | Accepted. The log group is named `mediaspike-endpoint-drill`; Task 8 deletes it and verifies its absence, with the user. | |
| +| R2-2, R2-3 | Plan 2. | |
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| index 6e8eaa314..d03b58225 100644 |
| --- 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 |
| @@ -22,8 +22,8 @@ |
| - 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. |
| -- Charging a `done` job (Opus, 2026-11-16, told to Paul): `w × min(max(source_ms, charged_ms), reservation_ms)`, where `reservation_ms = max(granted_s, deadline_s + 30)·1000`. ECS runtime, which the codec cannot forge, is the floor; the reservation is the ceiling. A reported duration below 0 or above `granted_s·1000` is invalid output (`engine_failed`). Failed rows are charged `w × charged_ms` as the spec says. |
| -- Host-claim consoles (`CARLOS_HOST_CLAIM`, still read on `main` at `cmd/console/main.go:2042`): media conversion and browser uploads are refused there with their own copy (`media.claims_console`, 503 `claims_console`), `media_jobs` is gated with `Refuse`, and plan 3's boot wiring refuses `CARLOS_MEDIA_ENGINE` with `CARLOS_HOST_CLAIM`. This is an exception to G1 that Paul has to rule on; the claims cleanup will remove it. |
| +- Charging a `done` job (spec §7.3 and §11 A2): `w × source_ms`. A reported duration below 0 or above `granted_s·1000` is invalid output (`engine_failed`, charged ECS's runtime), so a done charge never exceeds the reservation. A2 states the residual risk: a tenant who compromises the codec in their own job can under-report within that range. Failed rows are charged `w × charged_ms` as the spec says; `charged_ms` is always ECS's runtime (I3). |
| +- Host-claim consoles (`CARLOS_HOST_CLAIM`, still read on `main` at `cmd/console/main.go:2042`): media conversion and browser uploads are refused there with their own copy (`media.claims_console`, 503 `claims_console`), `media_jobs` is gated with `Refuse`, and plan 3's boot wiring refuses `CARLOS_MEDIA_ENGINE` with `CARLOS_HOST_CLAIM`. This is the exception spec §11 A1 authorises, until the claims cleanup removes that mode. |
| - 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). |
| @@ -271,7 +271,7 @@ The simulation's steps, verbatim from spec §5.3: submit, dispatch, launch rejec |
| - [ ] **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; one finish in five is hostile, reporting a duration of −1 ms, 0, the grant plus 1 ms, `math.MaxInt64`, or 1 ms against a long runtime; one in twenty writes a result over 64 KiB), exit 1 with a handler error, exit 75 with no result; misconfigure a class's revision (paired with a console restart, so queued rows meet the unsafe revision with no new POST); 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); `TestWitnessHostileResults` (one row per hostile duration: −1 and grant + 1 ms and `math.MaxInt64` end `failed engine_failed` charged ECS's runtime; 0 and 1 ms against a 9-minute runtime end `done` charged 9 minutes; none above its reservation); `TestWitnessUnsafeRevisionAfterRestart` (a queued row, a restart with the class's revision lacking the `START` dependency: no `Run`, the row stays `queued`, nothing reserved). |
| + - 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); `TestWitnessHostileResults` (one row per hostile duration: −1 and grant + 1 ms and `math.MaxInt64` end `failed engine_failed` charged ECS's runtime; 0 and 1 ms against a 9-minute runtime end `done` charged by their duration, 0 and 1 ms (A2), with `charged_ms` still the 9-minute runtime; none above its reservation); `TestWitnessUnsafeRevisionAfterRestart` (a queued row, a restart with the class's revision lacking the `START` dependency: no `Run`, the row stays `queued`, nothing reserved). |
| - [ ] **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`. |
| @@ -327,7 +327,7 @@ Rules the tests pin (spec §5.3, §7): |
| - `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·min(max(source_ms, charged_ms), max(granted_s, deadline_s+30)·1000)`; 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. |
| +- 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`. |
| @@ -338,8 +338,8 @@ Rules the tests pin (spec §5.3, §7): |
| - `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 with a 3-minute runtime is `0.1 · min(max(60, 3), 120) = 6` charged minutes (short class: reservation `max(7200, 600 + 30)` s = 120 min); a running long audio row reserves `0.1 · max(28800, 3000 + 30)` s = 2,880 s = 48 minutes. |
| - - `TestDoneChargeFloorAndCeiling` (F6): a done video reporting 2 min after a 9-minute runtime is charged 9 min; one whose runtime overran to `deadline_s + 90` s is charged its reservation, while `charged_ms` keeps the raw runtime (I3). |
| + - `TestAudioWeighsATenth`: a done 60-minute audio job with a 3-minute runtime is `0.1 · 60 = 6` charged minutes; a running long audio row reserves `0.1 · max(28800, 3000 + 30)` s = 2,880 s = 48 minutes. |
| + - `TestDoneChargedByDuration` (F6, A2): a done video reporting 2 min after a 9-minute runtime is charged 2 min, and its `charged_ms` keeps the 9-minute runtime (I3); one reporting `granted_s·1000 + 1` ms is `failed engine_failed`, charged its runtime. |
| - `TestDispatchRefusesUnsafeRevision` (F5): `FakeEngine.Misconfigure(video-720p/short, "depends_on")` after submit and a new `Jobs` (restart): `DispatchNext` returns nil, no `Run`, no reservation; the audio rows still dispatch. |
| - `TestOversizedResultSettles` (F15): exit 0 with `ErrResultTooLarge`: `failed engine_failed` on the first `Track`, charged ECS's runtime, capacity freed, outputs and result deleted by `Cleanup`. |
| - `TestCleanupOfSettledRows` (F7): `done` and `failed` rows (settled) get `cleanup_due` cleared and the right objects deleted. |
| @@ -402,7 +402,7 @@ Rules the tests pin (spec §5.3, §7): |
| - 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): `HostClaim` → 503 `claims_console` (`media.claims_console`); `MediaEngine == nil` → 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. |
| +- POST checks, in order, each before any row is written (spec table, plus three this plan places): `HostClaim` → 503 `claims_console` (`media.claims_console`; spec §11 A1); `MediaEngine == nil` → 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`. |
| @@ -483,7 +483,7 @@ Rules the tests pin (spec §5.3, §7): |
| **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: `HostClaim` → 503 `claims_console`; `StoreConversion` false or `StoreBuckets` nil → 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`); then, whatever eligibility answered (a minted or earlier-verified store included), `Inspect` the bucket now and refuse 409 `store_unverified` with the `cors` or `lifecycle` phrase when its CORS or lifecycle is present and its hash is not the one `Conversion.Uploads` recorded (none recorded: any present configuration is foreign); `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. |
| +- Enable, under the walk lock: `HostClaim` → 503 `claims_console` (spec §11 A1); `StoreConversion` false or `StoreBuckets` nil → 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`); then, whatever eligibility answered (a minted or earlier-verified store included), `Inspect` the bucket now and refuse 409 `store_unverified` with the `cors` or `lifecycle` phrase when its CORS or lifecycle is present and its hash is not the one `Conversion.Uploads` recorded (none recorded: any present configuration is foreign); `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 `. |
| @@ -548,10 +548,19 @@ Round 1 of at most 3: Astra against `99398b7d` (`docs/superpowers/plans/CODEX-FI |
| | F3 P1 `Minted` records intent | Accepted. Only a `CreateBucket` this walk made and that returned success earns `Minted` (`BucketCreator`); `BucketAlreadyOwnedByYou`, `us-east-1`'s bare success, a re-run and claim wrappers verify. Task 3, `TestPreExistingMintedNameIsNotMinted` with SSE-KMS and a foreign policy. | |
| | F4 P1 uploads overwrite foreign config | Accepted. Enable and update re-inspect CORS and lifecycle immediately before `PutUploads`, for minted and verified stores too. Task 9, `TestUploadsReinspectsMintedAndVerifiedStores`. | |
| | F5 P1 no revision check at dispatch | Accepted. `DispatchNext` checks the selected class key's revision before reserving. Task 2 `TestDispatchRefusesUnsafeRevision`; Task 1 `TestWitnessUnsafeRevisionAfterRestart` and a sim action. | |
| -| F6 P1 untrusted durations | Accepted with Opus's settlement: `0 <= duration <= granted_s·1000` or `engine_failed`; a `done` job is charged `w × min(max(duration, ECS runtime), reservation)` (told to Paul). Global Constraints, Task 2, `TestWitnessHostileResults`, sim hostile finishes, I8 extended. | |
| +| F6 P1 untrusted durations | Accepted with Opus's settlement: `0 <= duration <= granted_s·1000` or `engine_failed`; a `done` job is charged `w × min(max(duration, ECS runtime), reservation)` (told to Paul). Global Constraints, Task 2, `TestWitnessHostileResults`, sim hostile finishes, I8 extended. Superseded in round 2: the charge is `w × source_ms` again (spec §11 A2); the bound stays. | |
| | F7 P1 transaction guards | Accepted. A guard per transition (table in Task 2), success requires `retired_at = 0`, cleanup covers settled rows. `TestCleanupOfSettledRows`, `TestRetiredBetweenValidationAndCommit`. | |
| | F8 P1 compaction drops `x-id` (plan 2 half) | Accepted. `Transfer.Query` keeps every non-shared parameter raw; `Transfers.Shared` holds only the four identical ones. Task 1 `TestTransfersURLEscapesKeys` compares query multisets; plan 3 Task 9 tests the real presigner and MinIO. | |
| | F12 P2 host-claim exclusion | Accepted in part. Host-claim is still live on `main` (`cmd/console/main.go:2042`), so the refusal stays, with its own code and copy (`claims_console`), and goes to Paul as an exception to G1 until the claims cleanup removes the mode. | |
| | F15 P2 oversized results retried | Accepted. `ErrResultTooLarge` is terminal `engine_failed`, charged ECS's runtime, cleaned. `TestOversizedResultSettles`. | |
| | F11 P1 wrong expected values | Plan 3's finding; in the same spirit this plan's reservation and audio tests now show their arithmetic, recomputed. | |
| | F1, F2, F9, F10, F13, F14, F16 | Plans 1 and 3; nothing here changes. | |
| + |
| +Round 2: Astra (`docs/superpowers/plans/CODEX-FINDINGS-MEDIA-PLANS-R2.md`), plan 2 revise with P2 fixes only and no further round. Paul ruled on 2026-11-16 (spec §11 A1 and A2). |
| + |
| +| Finding | Handling in this plan | |
| +|---|---| |
| +| R2-1 P1 endpoint proof | Plans 1 and 3; nothing here. | |
| +| R2-2 P2 charging changed the approved policy | Accepted. A `done` job is charged `w × source_ms` again (A2); the 0 to `granted_s·1000` bound and the hostile-result witnesses stay, with a duration far below runtime now accepted and charged by its duration. A2 states the residual risk (a tenant who compromises the codec in their own job can under-report within the bound). `max(duration, runtime)` is gone from Global Constraints, metering and the tests. | |
| +| R2-3 P2 host-claim unresolved | Accepted. The refusal is now the exception spec §11 A1 authorises; Global Constraints point there and "Paul has to rule" is gone. | |
| +| R2-4 P2 foreign log group cleanup | Plan 1. | |
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| index a607ecdcf..1162002b3 100644 |
| --- 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 |
| @@ -157,13 +157,19 @@ Depends on plan 1 Task 3 Step 4: the muxer rules and the parser's accepted box s |
| **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) |
| +- Create: `cmd/carlos-media/sigv4.go` (a stdlib SigV4 signer for the drill's two signed API calls; the provider boundary keeps the SDK out), `scripts/media-endpoint-drill.sh`, `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` (none of the credential-bearing variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_SECURITY_TOKEN`, `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN`, `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`, `AWS_WEB_IDENTITY_TOKEN_FILE`, `AWS_ROLE_ARN` is set; ordinary metadata such as `AWS_EXECUTION_ENV`, `AWS_REGION` and `AWS_DEFAULT_REGION` is allowed; `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> <bucket> <key> <repository> <log-group-arn>` (requests the principal is otherwise allowed to make, a `GetObject` and a `PutObject` on the bucket, `ecr:GetAuthorizationToken`, a manifest `HEAD` on the repository, and `logs:PutLogEvents` to its own log group, are each refused with the VPC endpoint policy's denial, not an identity or resource denial; the driver runs the same command from outside the engine VPC first as the positive control, where each succeeds), `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. |
| +- 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` (none of the credential-bearing variables `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_SECURITY_TOKEN`, `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`, `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN`, `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`, `AWS_WEB_IDENTITY_TOKEN_FILE`, `AWS_ROLE_ARN` is set; ordinary metadata such as `AWS_EXECUTION_ENV`, `AWS_REGION` and `AWS_DEFAULT_REGION` is allowed; `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), `endpoints` (one pass of the endpoint drill defined below), `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`; one with only `AWS_EXECUTION_ENV=AWS_ECS_FARGATE` and `AWS_REGION`: `PASS`); `TestDrillOutputHasNoSecrets`. |
| -- [ ] **Step 2:** Run `go test ./internal/mediahandler/ ./cmd/carlos-media/ -run 'TestCorpus|TestPlaylistStyle|TestHostileChildren|TestBadOutputs|TestDrill' -count=1`. Expected: FAIL. |
| +**The endpoint drill (the one definition; plan 1 Task 4 Step 3 and rollout R3 both run it).** It proves that foreign credentials cannot use any of the four endpoints, by controls, never by error text. |
| +- **The principal and its four requests.** A user in an unrelated account whose identity policy allows, and whose target resources admit: `s3:GetObject` on one object of a drill bucket; `ecr:GetAuthorizationToken`; the image pull actions on the engine's repository; `logs:PutLogEvents` to a log stream in a log group of its own account in the same region. Before any task runs, outside the engine VPC (docs-t1, with that user's profile), the driver presigns the S3 GET (expiry 1 h), mints the user's ECR registry token with `GetAuthorizationToken`, creates the log stream, and writes the drill input: `{"s3_get_url", "ecr_token", "ecr_manifest_url" (the engine image's manifest by digest on the `*.dkr.ecr` host), "region", "access_key_id", "secret_access_key", "log_group", "log_stream"}`, passed to the task in `CARLOS_MEDIA_DRILL` (never logged). |
| +- **One pass** (`carlos-media drill endpoints`, inside a task on a media task definition with `command ["drill", "endpoints"]` on `codec`): the same four authenticated requests, each with a 20 s timeout: S3 gateway, `GET` of the presigned URL; ECR API, `GetAuthorizationToken` SigV4-signed in the task with the passed key; ECR Docker, `HEAD` of the manifest with `Authorization: Basic <ecr_token>`; Logs, `PutLogEvents` SigV4-signed with the passed key. It prints one line per endpoint, `<endpoint> ok` for a 2xx and `<endpoint> refused <status or "conn">` for anything else, and nothing else: no error text, no URL, no header. |
| +- **Three phases** (`scripts/media-endpoint-drill.sh <profile> <cluster> <task-definition> <drill-input>`, the operator's AWS CLI): save the four endpoints' policies; phase A, one pass under them: every endpoint must be `refused`; replace all four with AWS's default full-access policy, then one pass every 60 s, at most 5: phase B passes when every endpoint is `ok`; restore the saved policies byte for byte (compared with `aws ec2 describe-vpc-endpoints`), then one pass every 60 s, at most 5: phase C passes when every endpoint is `refused`. `carlos-media drill endpoints-verdict A B C` prints a table of endpoint by phase and exits 0 only when A and C are all `refused` and B all `ok`; anything else fails the drill, and the script restores the saved policies on every exit path. A refusal is causal for an endpoint only because the identical request succeeded in phase B. |
| +- **Conversion stays off** until this drill passes: `CARLOS_MEDIA_ENGINE` is not set on a console of that deployment before then. |
| + |
| +- [ ] **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`; one with only `AWS_EXECUTION_ENV=AWS_ECS_FARGATE` and `AWS_REGION`: `PASS`); `TestDrillOutputHasNoSecrets`; `TestDrillEndpointsOnePass` (four `httptest` endpoints answering 403, 200, a closed port and 200: exactly the four lines `s3 refused 403`, `ecr-api ok`, `ecr-docker refused conn`, `logs ok`, and the ECR Docker request carried `Authorization: Basic <the passed token>` unchanged); `TestSigV4Vector` (AWS's published SigV4 test vector `get-vanilla`); `TestEndpointsVerdict` (A all refused, B all ok, C all refused: exit 0; any one cell otherwise: exit 1, naming the cell). |
| +- [ ] **Step 2:** Run `go test ./internal/mediahandler/ ./cmd/carlos-media/ -run 'TestCorpus|TestPlaylistStyle|TestHostileChildren|TestBadOutputs|TestDrill|TestSigV4|TestEndpointsVerdict' -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`. |
| @@ -301,7 +307,7 @@ Ask each time with the account, region, resources, cost, duration, traffic effec |
| ### R2: Dev infrastructure, with the door still off |
| -- [ ] Ask Paul (profile `kass`, `eu-west-1`), including, in an unrelated account he names, one IAM user with an identity policy allowing `s3:GetObject` and `s3:PutObject` on a dev drill bucket, `ecr:GetAuthorizationToken` and the pull actions on the engine repository, and `logs:CreateLogStream`/`logs:PutLogEvents` on a log group in its own account; the drill bucket's policy and the repository's policy admitting that user; all removed after R3. In the dev root: `store_conversion = true` on the console's region-host; `media-engine` with `image_digest = ""`; apply. Push the image (`mediaimage push`), set `image_digest`, `image_built_at`, `image_ffmpeg`; apply. Do not set `CARLOS_MEDIA_ENGINE` yet. |
| +- [ ] Ask Paul (profile `kass`, `eu-west-1`), including the endpoint drill's scope (Task 7): in an unrelated account he names, one IAM user and key with the drill's identity policy, and one log group with a log stream; in dev, a drill bucket with one object and a bucket policy admitting that user, and a repository policy on the engine repository admitting it; and, for minutes during R3, the four endpoint policies replaced by AWS's default full-access policy and then restored. All removed in R3. In the dev root: `store_conversion = true` on the console's region-host; `media-engine` with `image_digest = ""`; apply. Push the image (`mediaimage push`), set `image_digest`, `image_built_at`, `image_ffmpeg`; apply. Do not set `CARLOS_MEDIA_ENGINE` yet. |
| - [ ] 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 activation gates (spec §5.5), before the door is on |
| @@ -309,10 +315,10 @@ Ask each time with the account, region, resources, cost, duration, traffic effec |
| Each drill names its tool; record every result in `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md`. Every task here is started with `aws ecs run-task`; no console is involved. |
| - [ ] `drill creds`, `drill dns`, `drill net <console private IP>` and `drill net <another box's private IP>`: all `PASS`. An unsigned S3 request from inside a task: refused at the endpoint. |
| -- [ ] `drill foreign` with R2's foreign user: first from docs-t1 (outside the engine VPC), where all five requests succeed (the positive control: the credentials and policies would allow them); then inside a task, where each is refused with the endpoint policy's denial at the S3, ECR API, ECR Docker and Logs endpoints. |
| +- [ ] The endpoint drill (Task 7's definition) with R2's foreign user: `scripts/media-endpoint-drill.sh kass <cluster> <video-720p/short revision> <drill input>`. Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and the saved policies are back. Record the table. |
| - [ ] A revision with `deadline` made to start late (its image padded so its pull is slow): `codec` starts only after it. A revision whose `deadline` image digest does not exist: `codec` never runs. |
| - [ ] A task running `drill hostile-timer` with `CARLOS_MEDIA_DEADLINE_S=180`: gone within 210 s, deadline exit 0, codec 137. |
| -- [ ] Remove R2's foreign user, its policies and the drill bucket's and repository's policies. |
| +- [ ] Remove R2's foreign user and key, its log group, the drill bucket and its policy, and the repository policy; verify each is gone (`aws iam get-user`, `aws logs describe-log-groups --log-group-name-prefix`, `aws s3api head-bucket`, `aws ecr get-repository-policy`), and that the four endpoint policies equal the saved ones. |
| - [ ] Only when every line above passed: 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. A failure here stops the rollout and goes to Paul. |
| ### R4: Dev drills with the door on (spec §9) |
| @@ -362,3 +368,11 @@ Round 1 of at most 3: Astra against `99398b7d` (`docs/superpowers/plans/CODEX-FI |
| | F14 P2 absent source reads as 403 | Accepted. `Head` decides absence from the console's own `ListObjectsV2` (it already has `ListBucket`); the conversion role gains nothing; stub test with AWS's 403 semantics and an R4 drill. | |
| | F16 P2 termination tasks unreviewed | Accepted. Tasks 3 and 13 are marked for Astra (termination). | |
| | F2, F3 to F7, F12, F15 | Plans 1 and 2; plan 3 consumes the changed `Transfers` shape and needs nothing else. | |
| + |
| +Round 2: Astra (`docs/superpowers/plans/CODEX-FINDINGS-MEDIA-PLANS-R2.md`), revise. R2-1 and F12 hit stopping rule 2; Paul took Opus's picks on 2026-11-16 (spec §11 A1 and A2). A narrow round 3 checks only the endpoint drill. |
| + |
| +| Finding | Handling in this plan | |
| +|---|---| |
| +| R2-1 P1 endpoint proof | Accepted, as Paul's pick: one shared drill with independent controls, defined once in Task 7. The registry token is minted outside the VPC and passed in; the same four authenticated requests run under the restrictive policies (must fail), AWS's full-access policy (must succeed) and the restored policies (must fail); causality comes from those controls, never error text. R2 adds the policy swap to the rollout's scope; R3 runs the drill and keeps the door unset until it passes. `drill foreign` is gone. | |
| +| R2-2, R2-3 | Plan 2 (spec §11 A2 and A1). | |
| +| R2-4 | Plan 1; R3 here also deletes and verifies the drill's log group. | |