carlos / platform Public

spec: video conversion design, revision 1 (Fable 5.2 draft)

A platform ffmpeg engine box, shaped like the PDF service, converts a
phone clip in an app's store bucket into one 720p H.264 CMAF MP4 that
plays progressively and as HLS (byte-range playlist), plus a poster.
Per-job presigned URLs from a narrowed assumed role carry the store's
infected-object deny. Amends media roadmap stage 3 and rulings 7, 11.
Nine decisions for Paul in section 12. Not yet reviewed.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b2241759876308ae3cfdb0ff0ebe66168b450ef0 parent 15b1ee6
1 file changed, +798 −0
  • docs/superpowers/specs/2026-11-16-video-conversion-design.md +798 −0

CI cancelled — superseded by a newer push — run details

Intent

Human

<task-notification> <task-id>ad8a1b25ebf69fbf7</task-id> <tool-use-id>toolu_01S7sfBtSg3bpNcfzSMGk5XH</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/8509ad95-d983-414c-9679-b3ef222618ef/tasks/ad8a1b25ebf69fbf7.output</output-file> <status>completed</status> <summary>Agent "Fable drafts video conversion design" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The spec is written and uncommitted at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-video-conversion/docs/superpowers/specs/2026-11-16-video-conversion-design.md`, 798 lines. That is longer than a v1 single-rendition design should be; the tables and the security section carry most of it. I created no scratch directory and ran nothing but reads. ## The main design call The engine never holds bucket authority. The console assumes a dedicated conversion role per job, narrowed by a session policy built from the store record, and hands the engine four presigned URLs (one GET, three PUTs). That carries the infected-object Deny exactly when the store user does, and URL expiry is the lease. I could not use the store user's own key, which would have been simpler: the console only seals config and cannot open it (`appconfig.Open` is called only from `internal/hostfiles/sealed.go` and `internal/moves/archive/seal.go`). Because the platform serves nothing here, the design drops the roadmap's publication fence in favour of deterministic output keys plus a `result.json` commit marker the console writes last. ## Decisions for Paul 1. **Box (moves ruling 7):** dedicated `c7g.large` per deployment (recommended), `c7g.xlarge`, or the roadmap's `t4g.medium` behind limits. 2. **No wait for stage 1 (moves ruling 11, narrows ruling 6):** ship on the app's own bucket and serving, with derivative deletion left to the app (recommended), or wait for `kind:media`. 3. **Authority:** per-job assumed role with a session policy (recommended), console-role presigning with a door-side verdict check, or a bucket grant to the engine. 4. **Admission caps:** 180 s, 512 MiB, 4K, 60 fps (recommended); or 300 s and 1 GiB; or 60 s and 200 MB. 5. **Plan values:** `media_minutes_month` at Free 30 and Personal 600, refused at twice the limit like PDFs (recommended), or no cap until usage is measured. 6. **Browser uploads in scope** as `carlos store uploads enable`, a member verb with explicit origins (recommended), or native clients only for now. 7. **Always re-encode, HDR tone-mapped, one JPEG poster** (recommended), or add the roadmap's remux path. 8. **On for every app** with a store and a Service credential, as PDFs are (recommended), or a per-app switch. 9. **Codec licences:** accept the H.264/AAC position of running ffmpeg and x264 on our own box, or have it checked before flagship. This is a question with no recommendation. ## What I could not verify Each is marked in the text as an estimate or unverified. - **Encode times and throughput** on `c7g.large` are estimates from general knowledge, not measurements. The spike is the plan's first task. - **Single fragmented MP4 playback:** whether it plays and seeks progressively in Safari on iOS is untested. The fallback is a second faststart MP4, which doubles storage and amends the "single file" goal. - **Session-policy Deny:** whether `s3:ExistingObjectTag` conditions are honoured inside an STS session policy is unproven. The spec says to prove it on dev before anything else is built and gives a fallback. - **Figures from memory:** the `c7g.large` price (about 55 to 60 dollars a month), the 5 GB single-PUT limit, and the phone per-minute file sizes behind the 512 MiB cap. - **MinIO behaviour:** that it offers `AssumeRole` with a session policy, and that community builds lack per-bucket CORS. - **Helper unit precedent:** the `carlos-dbread@` hardening is cited through the image resize spec; I did not find those properties in the Go files I searched. - **Permissions boundary:** whether the store user boundary allows the two multipart actions the design adds is left as a builder check. - **Agent delivery:** how the agent binary reaches the engine box is left to the builder, because I did not check how release artifacts are published. - **Console restart:** how the scan queue's in-memory index is rebuilt after a restart is unchecked; the new queue copies that pattern. Citations to `main` were checked by grep at 15b1ee6b, and three line ranges were corrected after writing. The one exception is the two-key-slot claim in §5.5's option 3: it is cited by field name only, and it rests on an AWS limit I did not check.</result> <usage><subagent_tokens>169138</subagent_tokens><tool_uses>30</tool_uses><duration_ms>673248</duration_ms></usage> </task-notification>

diff --git a/docs/superpowers/specs/2026-11-16-video-conversion-design.md b/docs/superpowers/specs/2026-11-16-video-conversion-design.md
new file mode 100644
index 000000000..008abdaab
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-16-video-conversion-design.md
@@ -0,0 +1,798 @@
+# Video conversion: a phone clip in, a playable video out
+
+**Date:** 2026-11-16
+**Status:** draft for review. Not approved.
+**Asked for by:** Paul, 2026-11-16. He picked approach A (§4).
+**Builds on:** the PDF service's shape (`2026-11-02-pdf-service-design.md`):
+one engine box per deployment, a console door, a Service credential, plan
+caps and fair-use limits.
+**Amends:** the media roadmap (`2026-09-07-media-platform-roadmap-design.md`),
+stage 3's first product and part of stage 5. See §11.
+**Review budget:** AGENTS.md "Stopping rules". At most three cross-model
+rounds on this spec, and review stops at the first round with no P1.
+
+Claims marked **(estimate)** are not measured. Claims marked **(unverified)**
+were not checked against a source in this tree. Calls marked **(my call)** are
+the author's and cheap to overturn.
+
+## 1. Intent
+
+An app that accepts video from a phone gets a file that plays nowhere
+reliably: HEVC in a `.mov`, 4K at 60 frames a second, 400 MB, rotation held
+in metadata. Today an app on the platform either stores that file and hopes,
+or runs ffmpeg itself on a burstable box.
+
+This design makes conversion a **platform service**. The app uploads the
+original straight to its own store bucket, asks the console to convert it,
+and polls. The platform writes one H.264/AAC video, an HLS playlist over
+that same file, and a poster image into the app's bucket. The app serves
+them the way it serves its other objects.
+
+First consumer (non-normative): a social app with content-addressed public
+media that currently caps uploads at 8 MiB and is moving its blobs into a
+store bucket. Nothing in the design is specific to it.
+
+## 2. Goals, non-goals, anti-goals
+
+**Goals**
+
+- G1. Any app with a store and a Service credential converts a phone clip
+ with one HTTP call and a poll. No operator grant and no per-app switch.
+- G2. One rendition in v1: H.264/AAC, at most 720p, never upscaled, in a
+ single fragmented MP4 that plays progressively with `Range` and is also
+ an HLS stream through a byte-range playlist; plus one JPEG poster.
+- G3. The source goes app to store directly. Browser uploads work: the
+ platform owns the bucket's CORS rule for the origins the app names (§5.9).
+- G4. Bad input is refused up front with a named error: at the door when
+ the door can know (size, key, store state), at the probe otherwise.
+- G5. Plan cap and fair use from the first job, counted per account the way
+ `pdf_renders_month` is.
+- G6. The engine is a platform module (`infra/modules/media-host`) consumed
+ by every deployment's root the same way.
+- G7. The output layout leaves room for a ladder: a later preset adds
+ rungs and a multivariant playlist beside the v1 files without moving them.
+
+**Non-goals**
+
+- **Encrypted media.** The platform cannot convert ciphertext. An app whose
+ users encrypt media client-side converts on the device (approach B, §4).
+ A ciphertext source fails the probe as `unsupported_container`.
+- A ladder, AV1, DASH, captions, DRM, watermarking, live packaging.
+- Audio-only inputs, waveforms, more than one poster.
+- Serving. The roadmap's stage 1 (`kind:media`, the three doors,
+ capabilities, distributed purge) is not needed and not built here.
+- Completion callbacks. v1 polls (roadmap stage 3, codex R2-8).
+- Environment stores. The door converts in the app's default store only,
+ as the scan door does (`internal/console/apiscan.go:902-905` has no
+ environment field). A follow-up adds the field.
+- An upload door through the edge. Writes never cross the data plane.
+- A client library. The helper package lives in the app framework's repo.
+
+**Anti-goals**
+
+- A standing grant that lets the engine box read or write tenant buckets.
+- ffmpeg with a network, or ffmpeg given a tenant-chosen path or URL.
+- An infected object readable through conversion when the store user
+ cannot read it (media roadmap §1, codex 4, 26, R4-8).
+- A free account turning the box into an encode farm.
+- Encoding on a box that serves requests. Approach C is dropped for this.
+
+## 3. Where things stand on `main` (15b1ee6b)
+
+- **Stores are per app, and apps talk to them directly.** The package header
+ says the control plane "never touches the data plane"
+ (`internal/objstore/objstore.go:1-5`). Coordinates arrive as
+ `<PREFIX>_BUCKET`, `_REGION`, `_ENDPOINT` and keys
+ (`internal/objstore/objstore.go:246`).
+- **The store user's policy** is `ListBucket` on the bucket and
+ `GetObject`, `PutObject`, `DeleteObject`, `GetObjectTagging` under it
+ (`internal/objstore/aws.go:192-199`). It carries a Deny on `GetObject` for
+ objects tagged infected when the record's `Enforce` is set
+ (`aws.go:228-237`), and an unconditional Deny on `PutObject` when the
+ store is past its storage grace (`aws.go:238-247`,
+ `objstore.go:161-164`). It has no multipart-abort action.
+- **Nothing sets bucket CORS or a lifecycle rule on a store.** No
+ `PutBucketCors` call exists under `internal/`, `cmd/` or `infra/`.
+- **The console cannot read a store secret.** It seals with a public key
+ (`internal/appconfig/sealer.go:18-23`). The only callers of
+ `appconfig.Open` are `internal/hostfiles/sealed.go` and
+ `internal/moves/archive/seal.go`.
+- **The console's role does not read tenant objects** unless scanning is
+ switched on. The store grant is bucket lifecycle and `DeleteObject`
+ (`infra/modules/region-host/main.tf:847-862`); `GetObject` and tagging
+ sit in a separate policy behind `store_scanning` (`main.tf:963-972`).
+- **Only the AWS store backend exists.** `CARLOS_STORE_BACKEND` accepts
+ `aws` and nothing else (`cmd/console/main.go:1093-1094`), and buckets are
+ created in one region, `CARLOS_STORE_REGION` (`main.go:1098`). The
+ `Provisioner` seam ships the AWS implementation and an in-memory fake
+ (`internal/objstore/provisioner.go:5-11`). A MinIO contract test runs in
+ CI (`internal/objstore/contract_test.go:46`, `.amadan/ci.d/30-minio-contract`).
+- **One bucket-backed queue exists**, the scan queue: one object per item
+ under `apps/<acct>/<app>/scan-queue/`, placed there so `PurgeApp` and the
+ name-claim gate find it (`internal/objstore/queue.go:1-14`, `:90`), with
+ an in-memory index of apps that have work (`queue.go:99-111`).
+- **The Service role and its doors exist.** `store/scan/object` and
+ `pdf/{route...}` register with `svcrole.Allow(svcrole.Service)`
+ (`internal/console/routedecls.go:1028-1032`).
+- **The PDF service is the shape to copy:** door
+ (`internal/console/apipdf.go:63`), limiter with defaults `4,60,20,16`
+ (`pdflimit.go:25`), plan check that refuses at twice the limit
+ (`planpdf.go:8-27`), `plans.Limits.PDFRendersMonth`
+ (`internal/plans/catalog.go:53`), one row per request
+ (`pdfrenders.go:11`), cap id `capPDF` (`plangrace.go:18`), module
+ `infra/modules/pdf-host` (default `t4g.medium`, `variables.tf:36`; IMDSv2
+ with hop limit 1, `main.tf:118-119`).
+- **An engine box may install packages at init.** The scanner box does
+ (`infra/modules/scanner-host/scanner-init.sh.tftpl:47`).
+- **The Go tree is `CGO_ENABLED=0`** (`.amadan/ci.d/20-cross@5:56`). The
+ roadmap's §3 allows `ffmpeg` as a codec helper: a separate process under
+ a hardened unit with no network (ruling 10).
+- **There is no ffmpeg, no media job, and no conversion code** in the tree.
+
+How PDF differs, and what follows from it: a conversion takes minutes, not
+seconds, so the door is asynchronous; the input is hundreds of megabytes,
+so it never passes through the console; the output belongs in the tenant's
+bucket, so the engine needs a way to write there.
+
+## 4. Approaches considered
+
+**A. A platform engine box (chosen, Paul).** One ffmpeg box per deployment,
+reached only from the console. Works for every app and every client, costs
+one box, and keeps a large C codebase away from the edge and the console.
+Its limits: one region, a queue under load, and it cannot touch ciphertext.
+
+**B. Conversion on the device, in the app.** WebCodecs in a browser or the
+platform encoder in a native app, before upload. No platform cost and the
+only option for client-side encrypted media. Rejected for v1 as the main
+path: browser support is uneven, a phone encode drains battery and fails
+when the tab closes, and every app would build it again. Kept as the
+answer for encrypted media.
+
+**C. Conversion on demand at the edge.** Convert on first request, like
+edge image resizing. Dropped: a resize is tens of milliseconds, an encode
+is minutes of CPU on the box that terminates every tenant's TLS, and the
+region boxes are burstable (roadmap §1, "The fleet is small ARM").
+
+## 5. The design
+
+### 5.1 The flow
+
+1. The app's server presigns a PUT for a key in its own bucket. The client
+ uploads to the store directly.
+2. The app's server calls the door with the key (§5.3). The door refuses
+ what it can and files a job record (§5.4).
+3. A console pass takes the job, mints a per-job grant on the bucket
+ (§5.5), and hands the engine one GET URL and three PUT URLs.
+4. The engine's agent downloads the source, probes it, converts it with a
+ sandboxed ffmpeg (§6), and uploads the three outputs.
+5. The console checks the outputs, writes `result.json` beside them, and
+ marks the job done. The app's poll sees it.
+
+### 5.2 The preset and its outputs
+
+One preset in v1, `clip-720p`. Every admitted source is re-encoded; there
+is no remux path **(my call: one code path, and a 1080p source must be
+scaled anyway)**.
+
+- Video: H.264 High, `yuv420p`, at most 1280 on the long side and 720 on
+ the short side, aspect kept, never upscaled, rotation applied, at most
+ 30 frames a second, a keyframe every 2 seconds, constant quality with a
+ bitrate ceiling of about 2.5 Mbit/s. HDR sources are tone-mapped to SDR.
+- Audio: AAC-LC stereo, 48 kHz, 128 kbit/s. A source with no audio makes
+ a video with no audio track.
+- Container: one fragmented MP4 with 4-second fragments. The same file is
+ the progressive source and, through an HLS version 7 playlist using
+ `EXT-X-MAP` and `EXT-X-BYTERANGE`, the HLS stream.
+- Poster: one JPEG at output size, from one second in or the midpoint of a
+ shorter clip.
+- Source metadata is dropped from the outputs, including location.
+
+Output keys are derived by the door, never named by the app:
+
+ derived/<source key>/<etag>/clip-720p/video.mp4
+ derived/<source key>/<etag>/clip-720p/video.m3u8
+ derived/<source key>/<etag>/clip-720p/poster.jpg
+ derived/<source key>/<etag>/clip-720p/result.json
+
+`<etag>` is the source's ETag with quotes removed (the scanner's
+normalisation, `internal/objstore/clamav.go:517`). It is an opaque content
+version: a key rewritten with new bytes gets a new output directory. A
+later ladder preset is a sibling directory of `clip-720p`. Deleting
+`derived/<source key>/` removes every output of that source.
+
+`result.json` is the commit marker. The console writes it last, so its
+presence means the other three are complete. It holds the source's
+duration, dimensions and codecs, and each output's key, size, ETag,
+content type and dimensions. An app can read it with its own credentials
+and never call the console again.
+
+### 5.3 The door
+
+ POST /api/cli/apps/{account}/{app}/media/conversions
+ GET /api/cli/apps/{account}/{app}/media/conversions/{id}
+ DELETE /api/cli/apps/{account}/{app}/media/conversions/{id}
+
+All three register with `svcrole.Allow(svcrole.Service)` and resolve the
+app through `apiAccountApp`, as the PDF and scan doors do. The credential
+is the one an app already holds for PDFs or scanning (PDF spec §5.4).
+
+The POST body is strict JSON: `{"key": "uploads/a1b2.mov", "preset":
+"clip-720p"}`. `preset` may be omitted. The door checks, in this order,
+and stops at the first failure:
+
+| Check | Refusal |
+|---|---|
+| `CARLOS_MEDIA_ADDR` unset | 503 `not_configured` |
+| key empty, over 512 bytes, has control characters, or starts `derived/` | 400 `bad_key` |
+| unknown preset | 400 `unknown_preset` |
+| no provisioned default store | 409 `no_store` |
+| store region is not the engine's region | 409 `no_engine_in_region` |
+| store record has `writes_denied` | 402 `store_writes_denied` |
+| HEAD of the key: absent | 404 `source_not_found` |
+| HEAD of the key: denied (an enforced infected verdict lands here) | 409 `source_unreadable` |
+| size zero or over the source cap (§7.1) | 413 `source_too_large` |
+| plan cap (§7.3) | 402 from `capCopy` |
+| fair use (§7.2) | 429 or 503 with `Retry-After` |
+
+The HEAD uses the per-job grant (§5.5), so it sees exactly what the store
+user would see. A passing request answers 202 with `id`, `state`,
+`output_prefix` and `result_key`.
+
+**Idempotency.** `id` is the first 32 hex characters of
+`sha256("v1\0" + key + "\0" + etag + "\0" + preset)`. The job record is
+written create-only, so two submissions of the same bytes are one job.
+A repeat submission answers 200 with the existing record, with three
+exceptions:
+
+- No record, but `result.json` already exists at the derived key: answer
+ 200 `done` from it. No job, no charge.
+- The record is `failed` with a retryable error, or `cancelled`: it is
+ requeued, subject to the same checks.
+- The record is `done` but `result.json` is gone (the app deleted its
+ outputs): it is requeued.
+
+A `failed` record with a non-retryable error stays failed: the same bytes
+give the same answer.
+
+`DELETE` cancels a queued or running job and removes a terminal record.
+
+### 5.4 The job record and the queue
+
+ apps/<acct>/<app>/media-jobs/<id>.json the record the app polls
+ apps/<acct>/<app>/media-queue/<qid>.json a marker while work is pending
+
+Both sit under the app's prefix for the scan queue's reason: `PurgeApp`
+lists only that prefix. The marker uses `NewQueueID` and an in-memory
+index like `QueueIndex`, so the pass lists only apps with work. The door
+writes the record, then the marker; a requeue rewrites the marker, which
+also repairs a crash between the two writes.
+
+The record: `schema`, `id`, `key`, `etag`, `bytes`, `preset`, `state`
+(`queued`, `running`, `done`, `failed`, `cancelled`), `attempt`,
+`lease_until`, `submitted` (`at`, `by`), `started`, `finished`, `error`
+(`code`, `message`, `retryable`), and on `done` the contents of
+`result.json`. Delivered store credentials cannot write it: it lives in
+the deployment bucket, not the tenant's.
+
+A terminal record is pruned by the pass 7 days after it finished. The
+lasting record is `result.json`, in the tenant's bucket.
+
+### 5.5 Authority: how the engine reads and writes a tenant bucket
+
+Four options were compared.
+
+| Option | New standing authority | Carries the infected Deny | Verdict |
+|---|---|---|---|
+| 1. Grant the engine's role read and write on the store prefix | the ffmpeg box holds every tenant's bucket | only by duplicating the Deny for all stores | rejected: breaks the first anti-goal |
+| 2. The console's own role presigns the URLs | the console role gains `PutObject` on every store | no; the door would check the tag and race the verdict | rejected |
+| 3. A second key on the store user, minted per job | none | yes | rejected: a user has two key slots and rotation uses both (`objstore.go` `KeyID`, `PrevKeyID`), and `ReapKeys` deletes unknown keys |
+| 4. A conversion role the console assumes per job, narrowed by a session policy built from the store record | one role, usable only through the console | yes, written by the same rule as the store user's | **chosen** |
+
+Option 4 in detail:
+
+- The deployment has one conversion role. Its policy allows `GetObject`
+ under the store bucket prefix and `PutObject` under `derived/` in those
+ buckets. Only the console's role may assume it.
+- For each job the console assumes it for 20 minutes with a **session
+ policy** scoped to that one bucket: `GetObject` on the bucket,
+ `PutObject` under `derived/`, and the store record's Denies copied in by
+ the same writer that builds the store user's policy: the infected Deny
+ when `Enforce` is set, the write Deny when `writes_denied` is set, and
+ the scan-tag anti-forgery Denies always. The new reader carries the Deny
+ exactly when the store user does.
+- The console presigns with those session credentials: one GET for the
+ source, with `If-Match: <etag>` as a signed header so a rewritten source
+ fails instead of being converted under the wrong key, and three PUTs for
+ the fixed output keys with their content types signed. The credentials
+ never leave the console. The engine receives four URLs, each good for
+ one method on one key until the lease ends.
+- The store enforces the lease: an expired URL is refused by the store,
+ with no platform component in the path.
+
+This does not widen what the console box can already reach: its role can
+mint an access key for any store user (`main.tf:911`, `iam:CreateAccessKey` on
+the store user path). It does add a second way the console reads tenant
+bytes (a HEAD and the `result.json` write), which §11 records.
+
+Whether `s3:ExistingObjectTag` conditions are honoured inside a session
+policy must be proven on dev before anything else is built **(unverified)**.
+If they are not, the fallback is the same Deny on the conversion role
+itself, unconditional for every store, which is stricter than the store
+user's when enforcement is off.
+
+### 5.6 The pass, leases and attempts
+
+A console pass, shaped like the scan drain, picks the oldest job of the
+account served least recently, so one account's burst does not starve
+another's single clip. For each job it:
+
+1. Takes the lease by compare-and-swap on the record: `running`,
+ `attempt+1`, `lease_until = now + 20 min`. A job whose `result.json`
+ already exists is marked `done` here without encoding.
+2. Mints the grant, presigns the URLs, and posts the job to the engine.
+3. Polls the engine. On success it HEADs the three outputs against the
+ sizes the engine reported, writes `result.json`, and swaps the record
+ to `done`. On failure it deletes any output the attempt uploaded, using
+ the `DeleteObject` the console role already has (`main.tf:859-862`).
+
+A job is dispatched again only after `lease_until` plus a 5-minute margin,
+and at most twice. The engine stops all work for a job at its deadline. A
+second failure of a retryable kind ends as `failed`.
+
+The engine keeps no durable state. If it restarts, the console's poll
+gets a 404 and the attempt counts as failed and retryable. If the console
+restarts, the pass resumes from the records.
+
+### 5.7 Deletion, verdicts and late writes: why v1 has no publication fence
+
+The roadmap's fence exists because stage 1 serves and caches derivatives
+and a late commit could republish purged bytes. Here the platform serves
+nothing, and three simpler rules cover each case.
+
+- **App deleted.** `PurgeApp` removes the records and markers. The pass
+ tolerates a marker whose record is gone, and a result for a missing
+ record is dropped and its outputs deleted. Store teardown is a separate,
+ explicit verb; once the bucket or its conversion grant is gone, a late
+ PUT fails at the store.
+- **Source deleted during a job.** The download fails (`source_changed`),
+ or, if the download had finished, outputs land under
+ `derived/<source key>/`. The rule for apps: when you delete a source,
+ cancel its conversion and delete that prefix. Roadmap ruling 6's
+ "removed with their source" is the app's duty in v1 (§11).
+- **Infected verdict.** With enforcement on, the HEAD at the door and the
+ GET at the engine are both denied by the store. A verdict that lands
+ after the download does not stop the job: the output is re-encoded
+ pixels, not the source's bytes, and it is swept like any other object.
+ With enforcement off the store user can read the object too, and
+ conversion matches that.
+- **A job outliving its lease.** Its URLs have expired. The one residual
+ window is a PUT that began before expiry and ends after it. The 5-minute
+ redispatch margin covers it, and the write order (video, poster,
+ playlist, then `result.json` by the console) means a half-written set
+ never has a commit marker.
+- **Key rotation or store re-grant during a job.** Unaffected: the URLs are
+ signed by the conversion role's session, not the store user's key.
+
+When stage 1 lands and serves `derived/`, `result.json` is the record its
+fence would check. That is stage 1's design, not this one.
+
+### 5.8 The engine box
+
+`infra/modules/media-host`, a sibling of `pdf-host`, with the same rules:
+AMI passed in, replacement always explicit, a security group admitting the
+agent's port only from the console's group (and a standby's), Session
+Manager only, the explicit Deny on SSM parameter reads, IMDSv2 with a hop
+limit of 1, **no bucket grant of any kind**. Output `media_addr`; console
+variable `CARLOS_MEDIA_ADDR`. Unset, the door answers 503, and that is the
+whole switch, as for PDF (PDF spec §4.3).
+
+On the box:
+
+- **The agent**, a small pure-Go program. It listens on the private
+ address and speaks four calls: `POST /v1/jobs` (id, the four URLs,
+ preset, limits, deadline), `GET /v1/jobs/{id}`, `DELETE /v1/jobs/{id}`,
+ `GET /health` (agent and ffmpeg versions, region, slots, busy). It does
+ the network I/O itself: download to scratch, upload from scratch. It
+ dials only hosts on a configured allow-list (the store endpoint), follows
+ no redirects, and refuses a private address unless the operator
+ configured one as the endpoint. A full box answers 429 and the job stays
+ queued.
+- **ffmpeg and ffprobe**, installed at init at a pinned version, run only
+ through the sandbox in §6.
+- Console to agent is plain HTTP inside the VPC, closed by the security
+ group: the trust model already accepted for clamd and Gotenberg (PDF
+ spec §4.1).
+
+`carlos system media status` sits beside `carlos system pdf status` with
+the same operator check: engine configured, health, versions, queue depth,
+and 24 hours of conversions and refusals.
+
+### 5.9 Uploads from a browser
+
+In scope, because a phone video that cannot be uploaded from a web page is
+not "just working". The roadmap put this under `carlos media enable`
+(stage 5); with no `kind:media` here, it belongs to the store.
+
+ carlos store uploads enable --app shop --origin https://shop.example.com
+ carlos store uploads status --app shop
+ carlos store uploads disable --app shop
+
+- A member verb on the member's own bucket: no cost to the deployment, so
+ no operator step **(my call)**.
+- Origins are explicit: `https://` plus a host, no wildcard, at most 8,
+ and `http://localhost:<port>` for development. With no `--origin`, the
+ app's ready platform hostnames at that moment are used and printed.
+ Nothing reconciles them later; re-run to change them.
+- The record gains an additive `uploads` block (`origins`, `at`, `by`).
+ The walk writes one CORS rule: methods `GET`, `HEAD`, `PUT`; any request
+ header; `ETag` exposed; a one-hour max age. The roadmap's rule stands: a
+ bucket that already has a CORS configuration the platform did not write
+ is refused until an operator clears it.
+- The same walk sets a lifecycle rule that aborts incomplete multipart
+ uploads after one day, and the store user's policy gains
+ `s3:AbortMultipartUpload` and `s3:ListMultipartUploadParts`. The
+ permissions boundary must allow both; the builder checks it.
+
+**Multipart.** A single presigned PUT carries up to 5 GB **(unverified)**,
+far above the source cap, so multipart is never required. It is worth
+having on a mobile network, where a retry costs one part instead of the
+whole file. v1 makes it possible and safe (the policy actions, the abort
+rule, `ETag` exposed) and documents the recipe. The helper that drives it
+belongs to the app framework.
+
+Native apps need none of this: a presigned PUT has no CORS.
+
+### 5.10 CLI, docs, and an app end to end
+
+ carlos media convert <key> --app shop [--wait]
+ carlos media status <id> --app shop
+ carlos media cancel <id> --app shop
+ carlos system media status
+
+A docs page, `docs/site/video.md`, with `docs/site/cli.md` headings for
+every verb (the docsite gate), a row on the plans page, and the residency
+sentence: conversion happens in the store's region.
+
+What the page teaches, with a neutral app `shop` on `shop.example.com`:
+
+```
+# once
+carlos store uploads enable --app shop --origin https://shop.example.com
+carlos services create --role service --app shop media
+carlos secrets set --app shop CARLOS_SERVICE_TOKEN=<secret>
+
+# per upload, on the app's server
+1. presign PUT uploads/<id>.mov -> the browser uploads to it
+2. POST $CARLOS_CONSOLE/api/cli/apps/<account>/shop/media/conversions
+ Authorization: Bearer $CARLOS_SERVICE_TOKEN
+ {"key": "uploads/<id>.mov"} -> 202 {id, state, result_key}
+3. GET .../media/conversions/<id> every few seconds until done
+4. store the output keys from the answer (or read result_key later)
+```
+
+Serving has one trap the page must spell out. The playlist names the
+video by a relative URL, so a player given a presigned playlist URL asks
+for `video.mp4` without the signature. The app serves both through paths
+on its own origin, `/media/<id>/video.m3u8` and `/media/<id>/video.mp4`,
+each either proxied with `Range` or redirected to a presigned GET. Then
+`<video src=".../video.mp4" poster=".../poster.jpg">` plays everywhere,
+and the playlist is there for players that prefer HLS.
+
+Every user-facing string (docs, refusals, `capCopy`, CLI output) goes
+through copy review before it is written.
+
+## 6. Security: ffmpeg and hostile input
+
+ffmpeg parses dozens of formats in C. Treat every source as an exploit
+attempt, and assume the helper is compromised when judging what it can
+reach.
+
+**Before ffmpeg starts.** The agent enforces the byte cap while
+downloading. It reads the first bytes in Go and accepts two container
+families only: ISO BMFF (`ftyp`: MP4, MOV, 3GP) and Matroska/WebM (EBML
+magic). Anything else is `unsupported_container` and ffmpeg never runs.
+
+**Probe before transcode.** `ffprobe` runs in the sandbox with the demuxer
+forced to the sniffed family. The agent picks the first video stream and
+the first audio stream and ignores every other stream (phone files carry
+metadata tracks). It then checks:
+
+| Condition | Error (non-retryable) |
+|---|---|
+| no video stream | `no_video` |
+| video codec not H.264, HEVC, VP8, VP9 or AV1 | `unsupported_video_codec` |
+| audio codec not AAC, Opus, Vorbis, MP3 or 16-bit PCM | `unsupported_audio_codec` |
+| either side over 4096, or over 3840x2160 pixels | `source_dimensions` |
+| over 60 frames a second | `source_frame_rate` |
+| longer than the duration cap (§7.1) | `source_too_long` |
+| probe fails or times out (30 s) | `unreadable` |
+
+**The sandbox.** ffprobe and ffmpeg each run as a transient systemd unit
+per job, modelled on the roadmap's §3 rule and the helper unit the image
+resize design describes: `DynamicUser`, `PrivateNetwork`, read-only
+filesystem except the job's scratch directory, `PrivateDevices`,
+`NoNewPrivileges`, an empty capability set, no address families, a
+`@system-service` syscall filter, `MemoryDenyWriteExecute`,
+`RestrictNamespaces`, `MemoryMax=2G` with no swap, `TasksMax=64`,
+`LimitFSIZE=256M`, and `RuntimeMaxSec` set to the wall-time budget.
+
+**The command.** The input is a fixed scratch path the agent chose, never
+the tenant's key. `-nostdin`, `-protocol_whitelist file`, the demuxer
+forced, a decoder allow-list matching the table, only the two chosen
+streams mapped, and `-t` set to the duration cap so a lying header cannot
+extend the encode. A playlist-style input that names other files or URLs
+is excluded twice: by the forced demuxer and by the protocol list.
+
+**What a compromised helper holds.** One tenant's one source file and a
+scratch directory. No network, no credential, no URL: the presigned URLs
+stay in the agent's memory. A compromised agent holds four URLs for one
+job. Scratch is deleted after each job and checked empty before the next.
+
+**Wall time.** 15 minutes per attempt **(my call, reset from the spike)**.
+Over it, the job fails as `too_slow`, non-retryable.
+
+**The build.** A minimal ffmpeg carrying only the formats above is better
+than a distribution build with allow-lists. v1 requires the allow-lists;
+the spike decides whether a minimal build is practical. Either way the
+module pins the version and records the codecs it carries (roadmap §3).
+
+## 7. Limits and sizing
+
+### 7.1 Admission caps
+
+| Cap | Value | Why |
+|---|---|---|
+| Source size | 512 MiB | Three minutes of 1080p H.264 from a phone is about 390 MB and of 4K30 HEVC about 510 MB **(unverified, from the phone maker's published per-minute sizes)**. 4K60 clips of that length are refused. |
+| Duration | 180 seconds | "Short clips from a phone." Bounds a job to a few minutes of one box. |
+| Dimensions | 3840x2160 | What phones record. |
+| Frame rate | 60 | Slow-motion captures are out of scope. |
+
+All four are console and agent settings (`CARLOS_MEDIA_LIMITS`), changed
+without a release.
+
+### 7.2 Fair use (every deployment)
+
+Per account, as for PDF:
+
+- at most 20 jobs queued or running: a 21st gets a 429;
+- 30 submissions a minute, burst 10: a 429 with `Retry-After`;
+- deployment-wide, at most 200 queued: a 503 with `Retry-After`.
+
+Scheduling is round-robin across accounts (§5.6). The console's
+`allowWrite` limit does not apply to this door, for the reason PDF gives
+(PDF spec §6.1). The numbers are **my call**.
+
+### 7.3 Plan cap (deployments with a catalog)
+
+A new `plans.Limits` field, `MediaMinutesMonth` (`media_minutes_month`),
+handled exactly as `pdf_renders_month` is: a monthly cap, warning at the
+limit, refusal with a 402 from `capCopy` at twice the limit, ops accounts
+exempt, zero meaning no limit, a new `capID`. Starting catalog values:
+**Free 30, Personal 600 (my call)**.
+
+What counts: the source duration of a job that reached `done`, in seconds,
+summed and shown as minutes. A refusal, a failure or a cancellation counts
+nothing. The check runs at submission against what has finished, so an
+account can overshoot by at most its queued jobs: 20 jobs of 3 minutes.
+
+### 7.4 Recording
+
+A console table `media_conversions`, one row per job reaching a terminal
+state: account, app, credential, preset, outcome, error code, source bytes
+and milliseconds, output bytes, wall time, time. Pruned at 90 days. The
+plan measure, `carlos system media status` and the account usage page read
+it, as they read `pdf_renders`.
+
+Outputs are ordinary objects in the tenant's bucket and count as its
+storage (roadmap ruling 6).
+
+### 7.5 The box
+
+**`c7g.large`**: two Graviton3 vCPUs that are not burstable, 4 GiB. The
+roadmap says a `t4g` is not a transcoding box and names this size for
+ladders; a dedicated engine box that always re-encodes should start there.
+About 55 to 60 US dollars a month on demand per deployment
+**(unverified)**.
+
+Encode time for a three-minute 1080p30 phone clip to 720p H.264 on that
+box, with a fast x264 preset **(estimate, from general knowledge of x264
+on two modern ARM cores, not a measurement)**:
+
+| Source | Speed | Wall time |
+|---|---|---|
+| 1080p30 H.264 | 2 to 4 times real time | 45 to 90 s |
+| 1080p30 HEVC | 1.5 to 3 times | 60 to 120 s |
+| 4K30 HEVC | about real time | 2 to 4 min |
+| any HDR source, tone-mapped | may fall below real time | unknown |
+
+x264 uses both cores, so the box runs **one job at a time**
+(`slots = 1`). At twice real time that is about 20 three-minute clips an
+hour. Ten clips submitted together finish in about 15 minutes. Slots and
+instance type are module variables.
+
+**The spike is the plan's first task**, and nothing above is promised
+until it reports. On a `c7g.large` and a `c7g.xlarge`, with a corpus of
+real phone files (1080p30 H.264, 1080p30 HEVC, 4K30 HEVC, 4K60 HDR,
+portrait with rotation metadata, variable frame rate, WebM from a browser
+recorder, no audio, five seconds long), it measures:
+
+1. wall time, peak memory and scratch per file at two or three x264
+ presets, and picks the preset;
+2. whether tone-mapping fits the wall-time budget, and what to do if not
+ (refuse HDR with a named error rather than ship washed-out video);
+3. whether the single fragmented MP4 plays and seeks progressively in
+ Safari on iOS and macOS, Chrome and Firefox, and whether the byte-range
+ playlist plays in Safari natively and through a JavaScript HLS player.
+ If progressive playback fails anywhere, the fallback is a second,
+ ordinary faststart MP4 beside the fragmented one, at the cost of double
+ storage, and G2's "single file" is amended;
+4. the session-policy Deny (§5.5);
+5. whether a minimal ffmpeg build is practical.
+
+## 8. Provider boundary
+
+**Core, no cloud API:** the door, records, queue, pass, leases, limits,
+meter, the engine protocol, the agent, the preset, the sandbox, and two
+seams in `internal/objstore`: a per-job grant ("give me a presigner for
+this store, narrowed by its record") and bucket upload configuration
+(CORS and the abort rule). Both get the in-memory fake.
+
+**AWS adapter:** the grant seam through STS `AssumeRole` with a session
+policy; the conversion role and the console's permission to assume it, as
+a `region-host` switch (`store_conversion`, off by default like
+`store_scanning`); `media-host` as an EC2 module; `PutBucketCors` and the
+lifecycle call, with their console grants.
+
+**A non-AWS deployment today** has no object stores at all (§3), so it has
+nothing to convert. When a MinIO-compatible backend arrives it implements
+the two seams. The grant needs an S3-compatible `AssumeRole` that accepts
+a session policy; MinIO documents one **(unverified)**. Per-bucket CORS is
+not available on every MinIO build **(unverified)**; there the operator
+sets CORS on the server and `uploads enable` says so. The engine box is
+any Linux box that runs the agent unit and is reachable only from the
+console; the module README states that contract so it can be met without
+AWS. Presigned URLs and conditional GETs are plain S3 and travel as they
+are.
+
+## 9. Rollout and acceptance gates
+
+Rule 5 (no dormant feature): the code merges with the module, and the
+door is live wherever `CARLOS_MEDIA_ADDR` is set.
+
+0. **Spike** (§7.5) on a throwaway box in dev. Its report amends this spec
+ where the numbers disagree.
+1. **Merge** the door, pass, limits, meter, agent, module, uploads verbs
+ and docs. Release.
+2. **Dev:** apply `media-host` and `store_conversion` in the dev root, set
+ `CARLOS_MEDIA_ADDR`, run every drill below.
+3. **Flagship:** the same in the flagship root. Production infrastructure
+ needs Paul's scoped approval with account, region, resources, cost and
+ cleanup stated (AGENTS.md).
+
+**Drills, attacks first:**
+
+- A source tagged infected in an enforcing store is refused at the door.
+ One tagged after submission and before dispatch fails at the download.
+- A token for another app or account is refused. A key under `derived/`
+ is refused.
+- A playlist-style file with a video extension that names
+ `http://169.254.169.254/` and a local path produces no request and reads
+ no file. A truncated file, a file with a lying duration, a decompression
+ bomb and a fuzzed corpus each end in a named error with the box healthy.
+- From inside the helper's unit: no route to any address. From the box:
+ no bucket call succeeds with the instance role.
+- A source rewritten between submission and dispatch fails as
+ `source_changed`. An expired PUT URL is refused by the store.
+- A job cancelled mid-encode leaves no outputs and no charge. An app
+ deleted mid-job leaves no record and no marker.
+- A 600 MB file, a 4-minute clip and an account at twice its plan cap are
+ each refused with the documented status.
+- Two accounts, one submitting 20 clips and one submitting one: the single
+ clip is second in line.
+- The engine killed mid-job: the job is retried once and completes. The
+ console restarted mid-job: the pass resumes it.
+
+**Then playback:** a two-minute 1080p phone clip, uploaded from a browser
+on `shop.example.com` to a dev app, plays in Safari on iOS, Chrome and
+Firefox from `video.mp4`, and in Safari from `video.m3u8`, within a time
+the spike sets (expected under two minutes on an idle engine). The same
+submission repeated returns the same `id` and encodes nothing.
+
+## 10. Left to the builder
+
+- How the agent binary reaches the box (a release artifact fetched and
+ hash-checked at init is the obvious fit) and how it is pinned.
+- The record and table schemas, the pass's cadence, how the index is
+ rebuilt after a console restart.
+- The exact unit properties and ffmpeg arguments, as long as §6 and its
+ drills hold.
+- The module's variable names, following `pdf-host`.
+- The session-policy writer's shape, as long as it shares the store
+ policy's Deny logic rather than restating it.
+- Test shape. The guards that matter: every refusal in §5.3 happens
+ before a record is written; a repeat submission creates nothing; a
+ failed or cancelled job is not counted; a result for a missing record
+ is dropped; no code path hands the engine anything but the four URLs.
+
+## 11. Amendments
+
+**Media roadmap (`2026-09-07-media-platform-roadmap-design.md`):**
+
+- **Stage 3, single rendition:** replaced by this design. Jobs still live
+ under the app's prefix and completion is still a polled record. What
+ changes: the door's path and the verb (`carlos media convert`); every
+ source is re-encoded to a 720p cap instead of remuxed or kept at source
+ size; one poster instead of three; no audio products.
+- **Ruling 7 moves.** The worker is not `carlos-media.service` on the
+ Ireland `t4g.medium`. It is a dedicated `c7g.large` engine box per
+ deployment from the start.
+- **Ruling 11 moves.** The single-rendition product no longer follows
+ stage 1. Image resizing already broke that ordering the same way.
+- **Ruling 6 is kept in part.** Outputs land under `derived/` in the
+ tenant's bucket and count as its storage. "In the source's namespace"
+ has no meaning before stage 1. "Removed with their source" is the app's
+ duty until stage 1 exists.
+- **Stage 3 authority and the fence:** the worker does not read through a
+ media bucket policy or commit through stage 1's publication fence. It
+ uses per-job grants (§5.5) and the rules in §5.7. Stage 1 still owns the
+ fence for anything it serves.
+- **Stage 3 eligibility** is kept: a store outside the engine's region is
+ refused at the door.
+- **Stage 5:** bucket CORS moves from `carlos media enable` to
+ `carlos store uploads enable`. "Quotas come after measurement" is
+ replaced by a cap from the first job, following the PDF service.
+- **§9, stage 3 gate:** replaced by §9 here.
+- Rulings 2 and 10 are unchanged. The ladder remains a later stage.
+
+**Object storage:** the primitive spec and the comment at
+`infra/modules/region-host/main.tf:847-851` say the console does not read
+tenant data except for scanning. Conversion is a second, switched
+exception: a HEAD of the source and the write of `result.json`, through
+the conversion role.
+
+**Others:** `svcrole.go`'s `Service` comment gains conversion. The unit
+economics spec gains a conversion-minutes line. The PDF spec is unchanged.
+
+## 12. Decisions for Paul
+
+1. **The box (moves ruling 7).** (a) a dedicated `c7g.large` per
+ deployment, about 55 to 60 dollars a month each, dev and flagship;
+ (b) `c7g.xlarge` for two jobs at once; (c) the roadmap's `t4g.medium`
+ behind hard limits. Recommend (a), confirmed by the spike.
+2. **No wait for stage 1 (moves ruling 11, narrows ruling 6).** (a) ship
+ on the app's own bucket and serving, with deletion of derivatives left
+ to the app; (b) wait for `kind:media`. Recommend (a).
+3. **Authority.** (a) a conversion role assumed per job with a session
+ policy copied from the store record; (b) the console's own role
+ presigns and the door checks the verdict; (c) a bucket grant to the
+ engine. Recommend (a). It adds one IAM role and a second switched case
+ of the console touching tenant objects.
+4. **Admission caps.** (a) 180 seconds, 512 MiB, 4K, 60 frames a second;
+ (b) 300 seconds and 1 GiB; (c) 60 seconds and 200 MB. Recommend (a).
+5. **Plan values.** `media_minutes_month`: Free 30, Personal 600,
+ refused at twice the limit like PDFs. Or no cap until usage is
+ measured. Recommend the cap.
+6. **Browser uploads in scope**, as `carlos store uploads`, a member
+ verb with explicit origins. Or leave CORS to a later stage and ship
+ for native clients only. Recommend in scope.
+7. **Always re-encode, HDR tone-mapped, one JPEG poster.** Or add the
+ roadmap's remux path for sources that already fit. Recommend always
+ re-encode; revisit if the spike shows HDR is too slow.
+8. **On for every app** that has a store and a Service credential, as
+ PDFs are. Or a per-app switch. Recommend on for every app.
+9. **Codec licences.** The engine encodes H.264 and AAC with ffmpeg and
+ x264 on the platform's own box. Either accept that position, as the
+ PDF box accepts Chromium's, or have it checked before flagship. This
+ is a question, not a recommendation.
+
+## Appendix: what a consuming app does (non-normative)
+
+An app with content-addressed public media at `/media/<sha256>` would:
+store the original at a key derived from its hash; submit it and keep the
+`id` beside the hash; show the poster and a "processing" state until the
+poll says `done`; then serve `/media/<sha256>/video.mp4`,
+`/video.m3u8` and `/poster.jpg` from the derived keys with long cache
+lifetimes, since both the source and its outputs are immutable. When a
+person deletes the post it deletes the source and `derived/<key>/`. Media
+from accounts that encrypt client-side skips all of this and is converted
+on the device. That work belongs in the app's repository.