plans: media conversion plans, Astra round 1 fixes
All 16 round-1 findings accepted (F12 in part: host-claim consoles stay refused while that mode exists). Foreign-principal endpoint proofs with a positive control, provenance only from a create this walk made, re-inspected CORS and lifecycle, revision check at dispatch, bounded result durations with done charged at max(duration, ECS runtime) capped at the reservation, per-transition guards, signed query kept intact, writable scratch, muxer flags tied to spike fixtures, corrected expected values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md+24 −9docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md+76 −38docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md+59 −30
Intent
<task-notification> <task-id>afb34e431dff63a6f</task-id> <tool-use-id>toolu_01Nic11yh9P7X7wQP2eDwTXS</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>Round 2 is done: all 16 findings are handled in place across the three plans, with a "Review log" at the end of each. Nothing is committed or pushed, and no builds, tests or AWS calls were run. I checked every citation before accepting it. The S3 SDK's own presign test at `/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/service/s3@v1.105.0/internal/customizations/presign_test.go` does expect `x-id=PutObject`. `EnsureBucket` at `internal/objstore/aws.go:293` does accept `BucketAlreadyOwnedByYou`. My F11 numbers were wrong. ## Line counts - `docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md`: 129 (was 114) - `docs/superpowers/plans/2026-11-16-media-conversion-plan-2-console.md`: 557 (was 519) - `docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md`: 364 (was 335) ## Per finding - **F1 accepted.** - The spike's foreign user now has permissions that would allow all five requests: its own identity policy, plus a bucket policy and a repository policy admitting it. - Plan 1 proves the refusal two ways. The same requests succeed from outside the VPC, and succeed again with the endpoint policies temporarily swapped to full access. They are refused with the real policies, before and after the swap. Those resources are now in the scope request. - Plan 3's rollout now passes the activation gates by direct `RunTask` before `CARLOS_MEDIA_ENGINE` is set: new R3, with drills in R4, playback in R5 and flagship in R6. - **F2 accepted.** The expiry drill is now a clearly labelled diagnostic run: the deadline container gets a later expiry than the grant. The production-shape test, where the deadline ends the task before the grant expires, stays separate. - **F3 accepted.** Only a `CreateBucket` that this walk made and that returned success earns `Minted`, through a new optional `BucketCreator` interface. `BucketAlreadyOwnedByYou`, us-east-1's bare success, a re-run and the claim wrappers all go through verification. New test: a pre-existing bucket with SSE-KMS, then a foreign policy, and no `adoptBucket`. - **F4 accepted.** Enabling or updating uploads re-inspects CORS and lifecycle immediately before writing, for minted and verified stores too. - **F5 accepted.** Dispatch checks the selected revision before reserving anything. Added a restart witness and a sim action. - **F6 accepted, with your settlement.** A reported duration must be from 0 up to `granted_s·1000`, otherwise `engine_failed`. A done job is charged `w × min(max(duration, ECS runtime), reservation)`. Added hostile-result witnesses (−1, 0, grant + 1 ms, `MaxInt64`, far below runtime), sim hostile finishes, and I8 now checks the charge bounds. - **F7 accepted.** Each transition has its own guard, set out in a table. The success commit requires `retired_at = 0`, and cleanup now covers settled rows. Added two tests, one using a hook that retires the row between validation and commit. - **F8 accepted.** `Transfer.Query` keeps every non-shared query parameter exactly as encoded, including `x-id`; only four identical parameters go in `Transfers.Shared`. The round-trip test uses the real presigner, and the MinIO test runs only on rebuilt URLs. - **F9 accepted.** - The image holds `/scratch` owned by 65534, mode `0700`, declared as a volume. The spike records that the codec's user can write the bind mount. - The scratch path is now `Config.Scratch` from `CARLOS_MEDIA_SCRATCH`, the argument builders take it, and the local runner sets it. - **F10 accepted.** Both presets use `+skip_trailer`, and audio fragments by `-frag_duration 4000000`. The spike records the fixtures' box sequence and muxer flags, and plan 3 Task 4 says plainly that its parser rules depend on them. Added `TestMuxerArgsMatchTheFixtures`. - **F11 accepted.** Recomputed with the arithmetic shown in the test steps: - gain for I −30, TP −3 is +1 dB, not +12.5; - 1281x721 gives 1278x720; - 1000x3000 gives 426x1280; - `targetSize` now uses integer arithmetic only. - **F12 accepted in part.** Host-claim mode still exists on `origin/main`: `cmd/console/main.go:2042` still reads `CARLOS_HOST_CLAIM`, and only claims-cleanup r0 to r2 are in the tree. So the refusal stays, with its own copy and code (`media.claims_console`, 503 `claims_console`). - **F13 accepted.** The credentials check now names the variables that carry credentials, and allows `AWS_EXECUTION_ENV` and the region variables. - **F14 accepted.** Absence is decided by the console's own `ListObjectsV2`; its role already has `ListBucket` on store buckets. The conversion role gains nothing. Added a stub test that answers like AWS (403 for a missing key without `ListBucket`), plus an R4 drill. - **F15 accepted.** `ErrResultTooLarge` now settles the row at once as `engine_failed`, charged ECS's runtime, and cleaned up. - **F16 accepted.** Plan 3 Tasks 3 and 13 are marked for their own Astra review (termination). None declined. ## For Paul 1. **Host-claim consoles get no conversion or uploads.** That is an exception to G1 (every app with a store and a Service credential), and it lasts until the claims cleanup removes the mode. He needs to rule on it. Also, the plan you pointed me to, `2026-10-25-claims-cleanup.md` with an R9 step, isn't in the tree; only r0 to r2 are. 2. **Done jobs are now charged on max(reported duration, ECS runtime), capped at the reservation.** This changes spec §7.3, which charged done jobs by source duration alone. 3. **New spike and rollout scope.** - In an unrelated account: a foreign IAM user with real permissions, and a log group of its own. - In dev: bucket and repository policies admitting that user. - For minutes during the spike: the endpoint policies swapped to full access as a positive control. - The same foreign user and policies again in dev rollout (R2, removed after R3).</result> <usage><subagent_tokens>582879</subagent_tokens><tool_uses>37</tool_uses><duration_ms>466236</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 dc9146695..9b1bd7251 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 |
| @@ -36,8 +36,8 @@ |
| - [ ] **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. |
| +- [ ] **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. |
| --- |
| @@ -53,7 +53,7 @@ |
| - [ ] **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 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, and record each file's top-level box sequence (`mediaspike playlist --boxes`) and the exact `-movflags`, `-min_frag_duration` and `-frag_duration` used; plan 3 Task 4's parser and its `TestMuxerArgsMatchTheFixtures` are fixed by these. 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. |
| --- |
| @@ -62,10 +62,10 @@ |
| 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 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 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. |
| - [ ] **Step 7: Retention.** Stop three finished tasks; `retention` on all three. Record each time to `MISSING`; the report uses the shortest (Review Focus 5). |
| @@ -88,7 +88,7 @@ Each step runs one or more tasks through `mediaspike run` and records the probe' |
| ### 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 2: The expired transfer, in a diagnostic configuration.** The production shape cannot reach this case, since the deadline container ends the task 30 s before the grant expires (Task 4 Step 9 proves that). So this run is explicitly a diagnostic: a grant with `--session 15` (AssumeRole's shortest), and a `CARLOS_MEDIA_GRANT_EXPIRY` passed to the deadline container that is two hours later than the grant's real expiry, with `reconnect --cut-at 1GiB --pause-until <real expiry + 60 s>`. Expected: the resumed GET is refused, the codec exits 75, no result object exists, ECS reports the run time. The report labels this run diagnostic and names the one value that differed from production. (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. |
| --- |
| @@ -109,6 +109,21 @@ Each step runs one or more tasks through `mediaspike run` and records the probe' |
| - 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 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. |
| + |
| +--- |
| + |
| +## Review log |
| + |
| +Round 1 of at most 3: Astra against `99398b7d` (`docs/superpowers/plans/CODEX-FINDINGS-MEDIA-PLANS.md`), revise. Citations checked before acceptance. |
| + |
| +| Finding | Handling in this plan | |
| +|---|---| |
| +| F1 P1 foreign-credential test proves nothing (plan 1 half) | Accepted. The foreign user now holds identity, bucket and repository permissions that would allow all five requests; Task 4 Step 3 proves them from outside the VPC and with the endpoint policies swapped to full access, then refused with the real policies. The added resources are in the scope request. | |
| +| F2 P1 expiry drill unreachable | Accepted. Task 6 Step 2 is an explicitly labelled diagnostic configuration (the deadline container given a later expiry); the production-shape deadline-at-expiry test stays in Task 4 Step 9. | |
| +| F9 P1 scratch not writable (spike half) | Accepted. The spike image sets `/scratch` as plan 3's does, and Task 4 Step 4 records that the codec's user can write the bind mount. | |
| +| 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. | |
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 5bedb677f..6e8eaa314 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,7 +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. |
| -- 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`. |
| +- 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. |
| - 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). |
| @@ -51,6 +52,7 @@ The deck holds every string Tasks 3 to 11 write. Drafts below; implementers copy |
| | Key | Draft | |
| |---|---| |
| | `media.not_configured` (503) | `media conversion is not set up on this deployment` | |
| +| `media.claims_console` (503) | `media conversion and browser uploads are not available on this console while it runs in host-claim mode` | |
| | `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` | |
| @@ -121,26 +123,27 @@ The deck holds every string Tasks 3 to 11 write. Drafts below; implementers copy |
| - Payload (`payload.go`), the codec's whole input, one env var: |
| ```go |
| const PayloadVersion = 1 |
| + // A presigned URL is base + "?" + query. The query's parameters that are |
| + // identical in all five transfers (X-Amz-Algorithm, X-Amz-Credential, |
| + // X-Amz-Expires, X-Amz-Security-Token) are sent once as Shared; every other |
| + // parameter (X-Amz-Date, X-Amz-SignedHeaders, X-Amz-Signature, x-id, and any |
| + // the SDK adds) stays in the transfer's own Query. Both are kept exactly as |
| + // the SDK encoded them, never decoded and re-encoded. |
| 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 |
| + 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"` |
| + Query string `json:"q"` // the raw query less the shared parameters |
| + 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"` |
| + Shared string `json:"s"` // the four shared parameters, raw, joined by "&" |
| + 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 |
| + func (t Transfers) URL(x Transfer) string // base + "?" + x.Query + "&" + t.Shared |
| type JobLimits struct { |
| SourceBytes int64 `json:"b"` |
| GrantedMS int64 `json:"g"` |
| @@ -236,7 +239,7 @@ The deck holds every string Tasks 3 to 11 write. Drafts below; implementers copy |
| ``` |
| - 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. |
| + - `FakeGrants.Objects` (bucket/key → size, ETag, infected), `Results` (execution → bytes), `Granted` (output key → executions ever granted a PUT on it), `Deleted` (keys), `ResultTooLarge` (executions whose `ReadResult` answers `ErrResultTooLarge`). `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: |
| @@ -248,7 +251,7 @@ The simulation's steps, verbatim from spec §5.3: submit, dispatch, launch rejec |
| - **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. |
| +- **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, with a `done` row charged as Global Constraints say. The checker also requires every settled row's charge to be at least 0 and at most its reservation, and no execution to be dispatched on a revision `FakeEngine` marks misconfigured. |
| - [ ] **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. |
| @@ -260,15 +263,15 @@ The simulation's steps, verbatim from spec §5.3: submit, dispatch, launch rejec |
| - `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. |
| + - `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 its parsed query equals, as a multiset of key and value pairs, the query of the presigned URL it was compacted from (a fixture URL carrying `x-id=GetObject` and a token with `+`, `/` and `=`); `X-Amz-Security-Token` appears once. Plan 3 Task 9 repeats this against the real SDK presigner and MinIO. |
| - `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`. |
| + - `TestWorstCasePayloadFits`: a payload with a 512-byte key of 3-byte UTF-8 runes, a 1,400-character token, 64-hex signatures and an `x-id` in every transfer's query 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 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). |
| + - 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). |
| - [ ] **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`. |
| @@ -304,27 +307,43 @@ The simulation's steps, verbatim from spec §5.3: submit, dispatch, launch rejec |
| 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. |
| +- Every transition is one transaction whose `UPDATE` carries its own guard below; a guard that matches no row is a dropped result, logged, not an error. Every guard names the row by `(account, app, incarnation, job_id)` and, where it has one, `execution_id`: |
| + |
| + | Transition | Guard | |
| + |---|---| |
| + | dispatch | `state = 'queued' AND retired_at = 0` | |
| + | task recorded, recovered ARN saved | `state = 'running' AND task_arn = '' AND task_stopped = 0` | |
| + | launch rejected, never started | `state = 'running' AND task_stopped = 0 AND settled = 0` (a retired row goes to `failed retired`, settled, uncharged, never back to `queued`) | |
| + | stopped, success | `state = 'running' AND task_stopped = 0 AND settled = 0 AND retired_at = 0`; when it matches nothing because the row was retired meanwhile, the failure row below runs with `retired` | |
| + | stopped, failure; unknown | `state = 'running' AND task_stopped = 0 AND settled = 0` | |
| + | retire | `retired_at = 0`, any state; the queued part also `state = 'queued'` | |
| + | cleanup | `cleanup_due > 0 AND cleanup_due <= now AND task_stopped = 1` (settled rows included) | |
| + | prune | the `Prune` rule below | |
| +- 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`. Before anything is reserved, `Engine.CheckRevision(ClassKey{row.Preset, class})`: an error leaves every queued row of that class key queued for this pass and is logged (the revision `Run` will use is the one just checked). 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`. |
| +- `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`, require `0 <= Result.Source.DurationMS <= granted_s·1000` (both sides `int64`; `granted_s` is at most 28,800, so the product cannot overflow), `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` and `ErrResultTooLarge` leaves the row for the next pass; after exit 0, `ErrResultTooLarge`, a missing or unparseable result, a duration outside that range, an output `Head` of `ErrNotFound`, or a size or ETag mismatch is `failed engine_failed`, charged ECS's time, cleaned like any failure. 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. |
| +- 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. |
| - [ ] **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`. |
| + - `TestDispatchFitsTheReservation`: limit 30, so R = 2·30 = 60 min = 3,600 s at w = 1; a long video: `granted_s = min(7200, 3600) = 3600`, `deadline_s = min(3000, 3600 − 30) = 3000`, reservation `max(3600, 3000 + 30) = 3600` s = 60 min; a second long video waits (R = 0, another execution running); after the first settles `failed` at 5 engine minutes, R = 55 min = 3,300 s and the second dispatches with `granted_s = min(7200, 3300) = 3300`, `deadline_s = min(3000, 3270) = 3000`. |
| - `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. |
| + - `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). |
| + - `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. |
| + - `TestRetiredBetweenValidationAndCommit` (F7): a test hook (`var beforeSuccessCommit func()`, nil in production) runs `Retire` after the result and outputs validate: the row ends `failed retired`, never `done`, charged ECS's runtime. |
| - [ ] **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. |
| @@ -335,12 +354,12 @@ Rules the tests pin (spec §5.3, §7): |
| ### 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` |
| +- Modify: `internal/objstore/objstore.go` (`Record`, :154-185; new `Conversion` block), `internal/objstore/provisioner.go` (the optional interface below), `internal/objstore/aws.go` (`EnsureBucket`, :293-306), `internal/objstore/memprovisioner.go` (:67), `internal/objstore/walk.go` (step 3, :330-334), `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/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). `type BucketCreator interface{ CreateNewBucket(ctx context.Context, name string) (region string, created bool, err error) }`, implemented by `awsProvisioner` (`created` true only when `CreateBucket` itself returned success outside `us-east-1`; `BucketAlreadyOwnedByYou`, and `us-east-1`'s bare success, which AWS also gives an owner re-creating, are `created == false`) and by `MemProvisioner` (which gains `PreExisting map[string]bool`). Step 3 of the grant walk calls `CreateNewBucket` when the provisioner implements it, else `EnsureBucket` with `created == false` (the console's claim wrappers do not implement it, so they always verify). Only `created == true`, on a record with no `Conversion` block yet, earns `Conversion{Incarnation, Minted: true}`, written in the walk's next record write; anything else (an adopted bucket, a pre-existing bucket under the minted name, a crash and re-run after the create) stays unminted and goes through verification. |
| - 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 }`. |
| @@ -349,8 +368,8 @@ Rules the tests pin (spec §5.3, §7): |
| - `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 1: Write the failing tests:** `TestFirstGrantRecordsMinted`, `TestAdoptedUnderMintedNameIsNotMinted`, `TestPreExistingMintedNameIsNotMinted` (F3: `MemProvisioner.PreExisting` holds the minted name, no `adoptBucket`: no `Minted`; then, in the console, `storecfg.Fake` gives that bucket SSE-KMS and then a foreign policy: the door answers `store_unverified` with `encryption`, then `policy`), `TestRerunAfterCreateIsNotMinted`, `TestAWSCreateNewBucketTable` (stub S3: success → created; `BucketAlreadyOwnedByYou` → not created; `us-east-1` success → not created), `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|TestPreExistingMintedName|TestRerunAfterCreate|TestAWSCreateNewBucket|TestPurgeGuardIgnoresConversion' -count=1 && go test ./internal/storecfg/ -count=1 && go test ./internal/console/ -run 'TestEligible|TestRecreatedStore|TestPreExistingMintedName' -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`. |
| @@ -383,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): `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. |
| +- 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. |
| - 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`. |
| @@ -394,9 +413,9 @@ Rules the tests pin (spec §5.3, §7): |
| - `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`. |
| + - `TestMediaDoorsRefuseOnHostClaim`: `HostClaim` true → 503 `claims_console` with the deck's `media.claims_console`, for POST and GET, and no row. |
| - [ ] **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 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 refused on a host-claim console: the door answers 503 claims_console 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`. |
| @@ -464,12 +483,12 @@ 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: `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. |
| +- 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. |
| - 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 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); `TestUploadsReinspectsMintedAndVerifiedStores` (F4: a `Minted` store, and a store verified earlier, each given a foreign lifecycle rule after verification: enable refuses with `lifecycle`, `PutUploads` never called; an update of origins on a store whose CORS was changed by hand since enable: refused with `cors`); `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.) |
| @@ -517,3 +536,22 @@ The page, in order (spec §5.6, §5.7): what it does (G1, G2, the two presets an |
| - [ ] **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. |
| + |
| +--- |
| + |
| +## Review log |
| + |
| +Round 1 of at most 3: Astra against `99398b7d` (`docs/superpowers/plans/CODEX-FINDINGS-MEDIA-PLANS.md`), revise. Every citation was checked against the tree (and the S3 SDK module cache for F8) before it was accepted. |
| + |
| +| Finding | Handling in this plan | |
| +|---|---| |
| +| 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. | |
| +| 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. | |
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 46e40c0e4..a607ecdcf 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 |
| @@ -11,7 +11,8 @@ |
| - 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`. |
| +- 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`. The image holds `/scratch` owned by `65534:65534`, mode `0700`, and declares it a volume in its config, so the Fargate bind mount there is writable by the codec's user (ECS bind mounts are otherwise root-owned `0755`); plan 1 Task 4 Step 4 proves it. |
| +- Every path the handler and its argument builders use is under `Config.Scratch` (`<scratch>/in/source`, `<scratch>/out/<name>`, `<scratch>/tmp`), from `CARLOS_MEDIA_SCRATCH`, default `/scratch`. `/scratch/…` below means that default. |
| - 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. |
| @@ -63,7 +64,7 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| **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. |
| +- 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`, and `CARLOS_MEDIA_SCRATCH` or `/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`). |
| @@ -74,7 +75,7 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| --- |
| -### Task 3: Handler: sniff and probe |
| +### Task 3: Handler: sniff, probe and child cleanup **[Astra: termination]** |
| **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) |
| @@ -93,16 +94,18 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| ### Task 4: Handler: the encodes, the playlist and the child processes |
| +Depends on plan 1 Task 3 Step 4: the muxer rules and the parser's accepted box sequence are settled by the fixtures Debian 13's ffmpeg made there, and this task's parser tests run only against those. |
| + |
| **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). |
| +- Produces: `func targetSize(w, h, rotation int) (ow, oh int)` (swap for ±90/270; box `(bw, bh)` = 1280x720 when `w >= h`, else 720x1280; integer arithmetic only: inside the box unchanged; else when `w·bh > h·bw` (width-limited) `ow = bw, oh = h·bw/w`, otherwise `oh = bh, ow = w·bh/h`, with integer division; then each side rounded down to even, at least 2); `func videoArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []string`; `func posterArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []string`; `func audioArgs(cfg Config, f probeFacts, p media.Payload, demuxer string, gainDB float64) []string` (every path from `cfg.Scratch`); `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, which is what these arguments produce with `skip_trailer`; if plan 1's Debian-made fixtures show another top-level box (a `free`, an `mfra`), the parser accepts exactly the sequence plan 1's report records and no other; 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+skip_trailer -min_frag_duration 4000000 /scratch/out/video.mp4` (fragments start at the first keyframe at least 4 s on; `skip_trailer` drops the `mfra` trailer). `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`. |
| +- `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 `-f mp4 -movflags +empty_moov+default_base_moof+skip_trailer -frag_duration 4000000 /scratch/out/audio.mp4` (audio has no video keyframe to cut at, so the fragment duration itself is the trigger). |
| - 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 1: Write the failing tests:** `TestTargetSizeTable` (1920x1080 → 1280x720; 1080x1920 → 720x1280; rotation -90 on 1920x1080 → 720x1280; 640x360 unchanged; 1281x721 → 1278x720 (1281·720 = 922,320 < 721·1280 = 922,880, so height-limited: 1281·720/721 = 1279, rounded down to even); 3840x2160 → 1280x720; 1000x3000 → 426x1280 (portrait box 720x1280: 1000·1280 = 1,280,000 < 3000·720 = 2,160,000, so height-limited: 1000·1280/3000 = 426); 4000x2 → 1280x2 (never below 2 on a side)); `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` (against plan 1's Debian-made fixtures only, never hand-built ones: init length, fragment count and offsets, durations within 1 ms of the packet times saved beside each fixture, 4 s fragments for `video.mp4` and `audio.mp4` alike, no trailer box); `TestMuxerArgsMatchTheFixtures` (the `-movflags`, `-min_frag_duration` and `-frag_duration` this task builds equal the ones plan 1's report says made the fixtures); `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. |
| @@ -118,7 +121,7 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| **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 1: Write the failing tests:** `TestGainTable`, each expected value from `min(-16 − I, (-1.5 − 0.5) − TP)` (I -30, TP -3: `min(14, 1)` = +1, so the output is about -29 LUFS with its peak at -2 dBTP, quieter than -16 because the ceiling wins; I -20, TP -10: `min(4, 8)` = +4; I -10, TP 0: `min(-6, -2)` = -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. |
| @@ -157,9 +160,9 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| - 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. |
| +- 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. |
| -- [ ] **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 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. |
| - [ ] **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/`. |
| @@ -175,10 +178,10 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| - 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 …`. |
| +- 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` owned `65534:65534` with mode `0700`; an OCI layout with config `architecture arm64`, `os linux`, `Entrypoint ["/usr/local/bin/carlos-media"]`, `User "65534:65534"`, `Volumes {"/scratch": {}}`, 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 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, the `/scratch` volume, and the layer's `/scratch` entry owned 65534 with mode 0700). |
| - [ ] **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. |
| @@ -196,10 +199,10 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| - 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. |
| +- 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 raw query; the raw `X-Amz-Algorithm`, `X-Amz-Credential`, `X-Amz-Expires` and `X-Amz-Security-Token` parameters must be equal across all five (else it presigns once more, then errors) and become `Transfers.Shared`; every other parameter, `x-id` among them, stays in that transfer's `Query` exactly as the SDK encoded it; takes `SignedHeader` (less `Host`) as `Header`, and requires every output base to equal `OutPrefix + name`. The expiry is the credentials' `Expires`. `Head` first asks the console's own client (which has `s3:ListBucket` on store buckets through `host_store`) `ListObjectsV2{Prefix: key, MaxKeys: 1}`; no object with exactly that key → `ErrNotFound`. Then `HeadObject` through one session per bucket (`media-head`, `GetObject` on that bucket only), reused until 15 minutes before it expires; 403 → `ErrDenied` (the infected-tag Deny, or the object deleted in between). The conversion role never gains `ListBucket`, so S3 answers it 403, not 404, for an absent key. `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 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` (stubs with AWS's semantics for a role without `ListBucket`: the conversion session answers 403 for an absent key; the listing decides `ErrNotFound`; a listed but denied object is `ErrDenied`); `TestCompactRoundTrip` (the real SDK presigner, offline, with static credentials and a session token: for GET and PUT, the URL `Transfers.URL` rebuilds from the compact form has exactly the original query, `x-id` included); `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 the URLs rebuilt from the compact payload, never the SDK's originals). |
| - [ ] **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. |
| @@ -261,17 +264,17 @@ Expected; `make census-card` decides. In scope: every new file under `infra/` (` |
| --- |
| -### Task 13: The provider boundary |
| +### Task 13: The provider boundary and the local runner **[Astra: termination]** |
| **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. |
| +- 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`, `CARLOS_MEDIA_SCRATCH=<scratch>` 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 1: Write the failing tests:** `TestCoreLinksNoCloudSDK`; `TestRunnerDeadlineEndsAnIgnoringChild` (a fake codec that ignores SIGTERM: gone within deadline plus `StopGrace` plus 1 s, `DeadlineExit` 0); `TestRunnerScratchIsPerExecution` (two executions write only under their own `CARLOS_MEDIA_SCRATCH`, and nothing under `/scratch`); `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. |
| @@ -296,40 +299,66 @@ Ask each time with the account, region, resources, cost, duration, traffic effec |
| - [ ] 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 |
| +### R2: Dev infrastructure, with the door still off |
| -- [ ] 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. |
| +- [ ] 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. |
| - [ ] 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) |
| +### R3: Dev activation gates (spec §5.5), before the door is on |
| + |
| +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. |
| +- [ ] 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. |
| +- [ ] 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. |
| -Each drill names its tool; record every result in `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md`. |
| +### R4: Dev drills with the door on (spec §9) |
| -- [ ] 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. |
| +- [ ] Infected source refused at the door with enforcement off; tagged between submission and dispatch: `failed source_unreadable` at the download. A missing key: `source_not_found` (the listing, not the 403). |
| +- [ ] 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). A bucket pre-created under a new app's minted name before `carlos store create`: not minted, verified. |
| - [ ] 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. |
| +- [ ] Console stopped; a converting task given a 3-minute deadline and `drill hostile-timer` as its codec command: 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`. |
| +- [ ] Revisions without the `START` dependency or with `stopTimeout` 20, configured while a job is queued, then a console restart: the queued job does not start, and the door answers 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 |
| +### R5: 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 |
| +### R6: 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 (profile `keymail`). Bump `?ref=` to the release tag in `carloku-infrastructure`, read plan, apply R2's steps, pass every R3 gate before the door is set, then R4's attack drills and R5'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. |
| +Report with R4: 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. |
| + |
| +--- |
| + |
| +## Review log |
| + |
| +Round 1 of at most 3: Astra against `99398b7d` (`docs/superpowers/plans/CODEX-FINDINGS-MEDIA-PLANS.md`), revise. Citations checked before acceptance; F8's against `aws-sdk-go-v2/service/s3@v1.105.0/internal/customizations/presign_test.go`, which expects `x-id=PutObject` in a presigned query. |
| + |
| +| Finding | Handling in this plan | |
| +|---|---| |
| +| F1 P1 activation tests prove nothing; door on before gates (plan 3 half) | Accepted. `drill foreign` uses a principal whose identity, bucket and repository policies would allow every request, with a positive control from outside the engine VPC; rollout split so R3's gates pass, with no console involved, before R3's last step sets `CARLOS_MEDIA_ENGINE`. | |
| +| F8 P1 compaction drops `x-id` (plan 3 half) | Accepted. Task 9 keeps every non-shared query parameter raw; `TestCompactRoundTrip` with the real presigner, and the MinIO test runs only on rebuilt URLs. | |
| +| F9 P1 scratch not writable; local runner path | Accepted. Image `/scratch` owned 65534, `0700`, declared a volume; plan 1 proves the bind mount is writable; `Config.Scratch` from `CARLOS_MEDIA_SCRATCH`, the argument builders take `cfg`, the local runner sets it. | |
| +| F10 P1 trailer and audio fragments | Accepted. `+skip_trailer` on both; audio fragments by `-frag_duration 4000000`; the parser's box sequence and the muxer flags are fixed by plan 1's Debian-made fixtures, with `TestMuxerArgsMatchTheFixtures`, and Task 4 now says it depends on them. | |
| +| F11 P1 wrong expected values | Accepted. Recomputed: gain +1 dB for I -30, TP -3; 1278x720; 426x1280; `targetSize` now integer-only, with the arithmetic in the test step. | |
| +| F13 P2 `AWS_*` too broad | Accepted. `drill creds` names the credential-bearing variables and allows `AWS_EXECUTION_ENV` and the region variables, with a test for both. | |
| +| 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. | |