plan: PDF service implementation plan
Nine tasks: copy deck, door, fair-use limits, recording, plan cap, system pdf status, pdf-host module, docs and #335 tidy, then review, merge and the Carloku switch-on. The spec gains two code-fact corrections (operator status door; the cap is monthly like bandwidth).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+523
−3
docs/superpowers/plans/2026-11-03-pdf-service.md+517 −0docs/superpowers/specs/2026-11-02-pdf-service-design.md+6 −3
CI passed — run details
diff --git a/docs/superpowers/plans/2026-11-03-pdf-service.md b/docs/superpowers/plans/2026-11-03-pdf-service.md| new file mode 100644 |
| index 000000000..fd8a04817 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-03-pdf-service.md |
| @@ -0,0 +1,517 @@ |
| +# PDF Service Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** Every app on a deployment can turn HTML, a URL or an Office file |
| +into a PDF through one console door backed by a platform-run Gotenberg. |
| + |
| +**Architecture:** A new `pdf-host` module runs Gotenberg on one fenced box |
| +per deployment. The console gets `CARLOS_PDF_ADDR` and a Service-role door, |
| +`POST /api/cli/apps/{account}/{app}/pdf/{route...}`, which checks an |
| +allow-list, applies the fair-use limits and the plan cap, streams the |
| +request to Gotenberg and the answer back, and records one row per request. |
| +#335's simulation is deleted. |
| + |
| +**Tech Stack:** Go (console, `net/http`, `httputil.ReverseProxy`), SQLite |
| +(console store), OpenTofu (module), nftables, Docker, Gotenberg 8. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-02-pdf-service-design.md` |
| +(approved 2026-11-02). Read it before any task. |
| + |
| +## Global Constraints |
| + |
| +- Door path: `POST /api/cli/apps/{account}/{app}/pdf/{route...}`, registered |
| + `svcrole.Allow(svcrole.Service)`. |
| +- Allowed routes (exact, after `pdf/`): `forms/chromium/convert/html`, |
| + `forms/chromium/convert/url`, `forms/chromium/convert/markdown`, |
| + `forms/chromium/screenshot/html`, `forms/chromium/screenshot/url`, |
| + `forms/chromium/screenshot/markdown`, `forms/libreoffice/convert`, |
| + `forms/pdfengines/merge`, `forms/pdfengines/split`, |
| + `forms/pdfengines/flatten`, `forms/pdfengines/convert`, |
| + `forms/pdfengines/metadata/read`, `forms/pdfengines/metadata/write`, |
| + `forms/pdfengines/encrypt`, `forms/pdfengines/embed`. |
| +- Request headers forwarded beyond `Content-Type`/`Content-Length`: only |
| + `Gotenberg-Output-Filename` and `Gotenberg-Trace`. Any |
| + `Gotenberg-Webhook-*` header is a 400. |
| +- Response headers passed back: status, `Content-Type`, |
| + `Content-Disposition`, `Gotenberg-Trace`. |
| +- Body limit in: 32 MiB (413). Body limit out: 64 MiB (abort, not |
| + counted). Engine response timeout: 60 s. Gotenberg `--api-timeout=55s`. |
| +- Fair use defaults: 4 in flight per account, 60/min per account with a |
| + burst of 20, 16 in flight deployment-wide. `CARLOS_PDF_LIMITS` = |
| + `per_account_inflight,per_minute,burst,total_inflight`. |
| +- Plan field: `PDFRendersMonth int` / `pdf_renders_month`. Catalog |
| + starting values Free 100, Personal 2,000 (catalog data, not code). |
| +- A render counts only when the engine answered 2xx and the whole body was |
| + streamed to the caller. |
| +- `pdf_renders` rows kept 90 days. |
| +- Every user-facing string comes from the approved copy deck (Task 0). |
| + No new string is written to a file before Paul has reviewed it. |
| +- Copy voice: no em dashes; a full stop and a new sentence, lower case |
| + for CLI and JSON errors. |
| +- Neutral examples only (shop, example.com). No tenant names in code, |
| + docs or tests. |
| +- Local tests: only the touched packages, with `-run`. CI runs the full |
| + suite. Never set `GOCACHE`. |
| +- Review budget: AGENTS.md stopping rules. Per-task cross-model review |
| + only on Tasks 1, 2, 4 and 6 (security gate, billing, production infra). |
| + One whole-branch review at the end. |
| + |
| +## Review Focus |
| + |
| +1. **Path tricks on the wildcard.** `pdf/forms/chromium/convert/html/../../../health`, |
| + `pdf/forms%2Fchromium...`, a trailing slash, doubled slashes, or a query |
| + string must never reach a route outside the list. The proxy forwards the |
| + matched allow-list entry, never the request's own path. Tests in Task 1. |
| +2. **The client hangs up mid-render.** The in-flight slots are released, |
| + the row records `aborted`, and nothing counts. Tests in Tasks 2 and 3. |
| +3. **A big upload.** A 200 MiB multipart body gets a 413 while it is being |
| + read, without the whole body being buffered first. Test in Task 1. |
| +4. **Engine down or slow.** A refused dial gives a 502 and a 61 s stall |
| + gives a 504, each with deck copy, an `error` row and no count. Test in |
| + Task 1. |
| +5. **Another app's or account's token.** An app-bound token for app A on |
| + `/apps/{acct}/B/pdf/...` gets a 404, and so does an account-wide token |
| + for another account, before any byte reaches the engine. Test in Task 1. |
| + |
| +--- |
| + |
| +### Task 0: Copy deck and review |
| + |
| +**Files:** |
| +- Create: `docs/superpowers/notes/pdf-service-copy-deck.md` |
| + |
| +The deck holds every string Tasks 1 to 5 write. Drafts are below. Run the |
| +copy-review skill on it, apply Paul's edits verbatim and commit the |
| +approved deck. Implementers copy strings from the approved deck, not from |
| +this plan. |
| + |
| +| Key | Draft | |
| +|---|---| |
| +| `pdf.unconfigured` (503) | `no PDF engine is configured for this deployment (CARLOS_PDF_ADDR)` | |
| +| `pdf.unknown_route` (404) | `that is not a PDF route. the PDFs docs page lists the routes this door carries` | |
| +| `pdf.webhook` (400) | `webhooks are not available here. the PDF comes back on the same request` | |
| +| `pdf.too_large` (413) | `the request is over 32 MiB, the most this door accepts` | |
| +| `pdf.busy_account` (429) | `this account already has %d PDFs rendering. wait for one to finish and try again` | |
| +| `pdf.rate` (429) | `this account has asked for more than %d PDFs in a minute. try again in %d seconds` | |
| +| `pdf.busy_engine` (503) | `the PDF engine is busy. try again in a few seconds` | |
| +| `pdf.engine_down` (502) | `the PDF engine did not answer. try again shortly` | |
| +| `pdf.engine_timeout` (504) | `the PDF engine took more than 60 seconds and was stopped` | |
| +| `cli.cap.pdf_renders` (402) | `this account has rendered %d PDFs this month, twice its plan's %d. rendering starts again on the 1st, or move to a bigger plan` | |
| +| `usage.label.pdf` | `PDFs` | |
| +| `limit.pdf` | `%s PDFs a month` | |
| +| `usage.pdf` (notice) | `%d of %d PDFs this month` | |
| +| `banner.pdf_refused` | `This account has used twice its PDF allowance this month. New PDFs are refused until the 1st.` | |
| +| CLI status lines | `engine: configured at %s` / `engine: not configured` / `health: ok (Gotenberg %s)` / `health: not answering (%s)` / `last 24 hours: %d rendered, %d refused, %d failed` | |
| + |
| +- [ ] **Step 1:** Write the deck file with the table above. |
| +- [ ] **Step 2:** Run the copy-review skill on it. Wait for Paul's edits. |
| +- [ ] **Step 3:** Apply them verbatim and commit: |
| + `docs: PDF service copy deck, approved`. |
| + |
| +--- |
| + |
| +### Task 1: The door |
| + |
| +**Files:** |
| +- Create: `internal/console/apipdf.go`, `internal/console/apipdf_test.go` |
| +- Modify: `internal/console/authcli.go` (register beside the scan routes, ~:1088) |
| +- Modify: `internal/console/server.go` (Config field) |
| +- Modify: `cmd/console/main.go` (env wiring beside `CARLOS_CLAMD_ADDR`, ~:541) |
| +- Modify: `internal/console/testdata/claim-routes.txt`, `internal/console/claim_invariant_fixtures_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `Config.PDFEngine string` (base URL, e.g. `http://10.0.1.5:3000`; |
| + empty = unconfigured). |
| +- Produces: `var pdfRoutes = map[string]bool{...}` (Global Constraints list). |
| +- Produces: `func pdfRoute(wild string) (string, bool)`: the exact list |
| + entry for a wildcard value, or false. No cleaning: an exact string match |
| + against the raw, still-escaped value, so anything with `..`, `%2F`, a |
| + doubled or trailing slash fails. |
| +- Produces: `func (s *Server) handleAPIPDF(w http.ResponseWriter, r *http.Request)`. |
| +- Produces: the hooks Tasks 2 to 4 fill in, called in this order inside |
| + `handleAPIPDF` after `apiAccountApp`: |
| + `s.pdfPlanCheck(ctx, acct, now) error` (Task 4; Task 1 stub returns nil), |
| + `s.pdfLimiter.acquire(acct.Sqid, now) (release func(), refusal *pdfRefusal)` (Task 2; Task 1 uses a no-op limiter), |
| + `s.store.RecordPDFRender(ctx, pdfRenderRow) error` (Task 3; Task 1 calls a no-op `s.recordPDF` seam that Task 3 points at the store). |
| +- Produces: `type pdfOutcome string` with values `rendered`, `engine_error` |
| + (engine non-2xx), `refused` (console refusal), `aborted` (client gone or |
| + out limit), `failed` (dial or timeout). |
| + |
| +- [ ] **Step 1: Write the failing tests** in `apipdf_test.go`, against an |
| + `httptest.Server` fake Gotenberg that records the path, headers and body |
| + it got: |
| + - `TestPDFDoorForwardsAllowedRoute`: POST multipart to |
| + `/api/cli/apps/{acct}/shop/pdf/forms/chromium/convert/html` with a |
| + Service token bound to `shop`. The fake gets |
| + `/forms/chromium/convert/html` and the same body. The caller gets the |
| + fake's 200, `Content-Type: application/pdf`, `Content-Disposition` and |
| + the body bytes. |
| + - `TestPDFDoorRefusesUnlistedRoutes`: table of `health`, `version`, |
| + `prometheus/metrics`, `debug`, |
| + `forms/chromium/convert/html/../../../health`, |
| + `forms%2Fchromium%2Fconvert%2Fhtml`, `forms/chromium/convert/html/`, |
| + `forms//chromium/convert/html`. Each gets a 404 with `pdf.unknown_route` |
| + and the fake sees zero requests. |
| + - `TestPDFDoorRefusesWebhooks`: `Gotenberg-Webhook-Url: https://example.com/x` |
| + gives a 400 with `pdf.webhook`, and the fake sees nothing. |
| + - `TestPDFDoorStripsOtherGotenbergHeaders`: `Gotenberg-Output-Filename` |
| + and `Gotenberg-Trace` arrive at the fake, `Gotenberg-Foo` does not, |
| + and neither does `Authorization`. |
| + - `TestPDFDoorBodyLimit`: a 33 MiB streamed body (an `io.Reader` that |
| + generates bytes, never a 33 MiB slice) gives a 413 with |
| + `pdf.too_large`. |
| + - `TestPDFDoorUnconfigured`: `PDFEngine == ""` gives a 503 with |
| + `pdf.unconfigured`. |
| + - `TestPDFDoorEngineDown` (closed listener: 502 `pdf.engine_down`) and |
| + `TestPDFDoorEngineTimeout` (the fake sleeps past a timeout injected as |
| + `s.pdfTimeout`, set to 50 ms in the test: 504 `pdf.engine_timeout`). |
| + - `TestPDFDoorOtherAppOrAccount`: a token bound to app `shop` on |
| + `/apps/{acct}/blog/pdf/...` gets a 404. An account-wide token from |
| + another account gets a 404. The fake sees zero requests. |
| + - `TestPDFDoorResponseLimit`: the fake streams 65 MiB. The caller's |
| + stream is cut short, and the outcome passed to `s.recordPDF` is |
| + `aborted`. |
| + - `TestPDFDoorEngineErrorPassesThrough`: the fake answers 400 with a |
| + Gotenberg error body. The caller gets the 400 and that body, with |
| + outcome `engine_error`. |
| +- [ ] **Step 2:** Run `go test ./internal/console -run 'TestPDFDoor' -count=1`. |
| + Expected: FAIL (undefined handler). |
| +- [ ] **Step 3: Implement.** Register |
| + `s.cliRoute("POST /api/cli/apps/{account}/{app}/pdf/{route...}", svcrole.Allow(svcrole.Service), s.handleAPIPDF)`. |
| + Read the wildcard with `r.PathValue("route")`, but take the raw segment |
| + from `r.URL.EscapedPath()` (strip the prefix) for `pdfRoute`, so escaped |
| + slashes stay visible. Do not apply `s.allowWrite`. Wrap the body in |
| + `http.MaxBytesReader(w, r.Body, 32<<20)` and map `*http.MaxBytesError` |
| + to the 413. Proxy with `httputil.ReverseProxy`: a `Rewrite` that sets the |
| + outbound URL to `PDFEngine` + `/` + the matched entry with no query, |
| + clears every inbound header and copies back only the allowed ones; a |
| + `Transport` with `ResponseHeaderTimeout = s.pdfTimeout` (default 60 s); |
| + `ModifyResponse` that deletes every header except the four passed back |
| + and wraps the body in a reader that fails after 64 MiB; an |
| + `ErrorHandler` that maps dial errors to 502 and timeouts to 504. Env: |
| + `PDFEngine: strings.TrimSpace(getenv("CARLOS_PDF_ADDR"))`. Refuse to |
| + boot if it is set but not an `http://` URL with a host |
| + (`log.Fatalf`, diagnostic, not deck copy). |
| +- [ ] **Step 4:** Add the route to `claim-routes.txt` and a `claimDoor` |
| + fixture (model the `store/scan/object` POST fixture), then run |
| + `go test ./internal/console -run 'TestPDFDoor|TestClaimConsoleRouteCensus|TestEveryCLIDoorNamesItsRoles|TestClaim' -count=1`. |
| + Expected: PASS. |
| +- [ ] **Step 5:** Commit: `console: PDF door to a platform Gotenberg`. |
| + |
| +--- |
| + |
| +### Task 2: Fair-use limits |
| + |
| +**Files:** |
| +- Create: `internal/console/pdflimit.go`, `internal/console/pdflimit_test.go` |
| +- Modify: `cmd/console/main.go`, `internal/console/server.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's call site. |
| +- Produces: `type pdfLimits struct{ PerAccountInflight, PerMinute, Burst, TotalInflight int }`, |
| + `func parsePDFLimits(v string) (pdfLimits, error)` (empty gives the |
| + defaults 4, 60, 20, 16; anything but four positive integers is an error), |
| + `func newPDFLimiter(l pdfLimits) *pdfLimiter`, |
| + `func (l *pdfLimiter) acquire(account string, now time.Time) (release func(), refusal *pdfRefusal)`, |
| + `type pdfRefusal struct{ Status int; RetryAfter int; Msg string }`. |
| + |
| +- [ ] **Step 1: Write the failing tests:** |
| + - `TestPDFLimitsParse`: `""` gives `{4,60,20,16}`, `"2,10,5,8"` parses, |
| + `"2,10,5"`, `"0,1,1,1"` and `"a,1,1,1"` are errors. |
| + - `TestPDFLimiterAccountInflight`: with limits `{4,60,20,16}`, four |
| + acquires for `acct1` succeed and the fifth is a 429 with |
| + `RetryAfter == 2` and `pdf.busy_account` filled with 4. Releasing one |
| + lets the next in. `acct2` is unaffected throughout. |
| + - `TestPDFLimiterRate`: a burst of 20 passes, the 21st at the same |
| + instant is a 429 with `pdf.rate` and `RetryAfter == 1` (60/min = one |
| + token a second). At `now + 1s` one more passes. |
| + - `TestPDFLimiterTotal`: with `{4,60,20,3}`, three accounts take one |
| + each, and the fourth account gets a 503 with `pdf.busy_engine` and |
| + `RetryAfter == 2`. |
| + - `TestPDFLimiterReleaseIdempotent`: calling `release` twice frees one |
| + slot. |
| + - `TestPDFDoorReleasesOnClientGone` (in `apipdf_test.go`): the fake |
| + blocks, the client's context is cancelled, the handler returns, and |
| + a fresh acquire for the same account sees all four slots free. |
| +- [ ] **Step 2:** Run `go test ./internal/console -run 'TestPDFLimit|TestPDFDoorReleases' -count=1`. |
| + Expected: FAIL. |
| +- [ ] **Step 3: Implement** with a mutex, per-account counters and token |
| + buckets in maps (drop an account's entry when it is idle and its bucket |
| + is full), and a deployment-wide counter. The order inside `acquire` is |
| + total, then account in flight, then rate, and a refusal leaves no |
| + counter changed. Wire it with |
| + `PDFLimits: parsePDFLimits(getenv("CARLOS_PDF_LIMITS"))` (`log.Fatalf` |
| + on error). A refusal writes `Retry-After` and the deck message through |
| + `jsonError`, then records outcome `refused`. |
| +- [ ] **Step 4:** Rerun the Step 2 command. Expected: PASS. |
| +- [ ] **Step 5:** Commit: `console: fair-use limits on the PDF door`. |
| + |
| +--- |
| + |
| +### Task 3: Recording |
| + |
| +**Files:** |
| +- Create: `internal/console/pdfrenders.go`, `internal/console/pdfrenders_test.go` |
| +- Modify: `internal/console/store.go` (`migrate`), `internal/console/store_gate.go` (`claimSQLTables`) |
| + |
| +**Interfaces:** |
| +- Produces: `type pdfRenderRow struct{ Account, App, Credential, Route string; Outcome pdfOutcome; Status int; BytesIn, BytesOut int64; Duration time.Duration; At time.Time }`. |
| +- Produces: `func (s *Store) RecordPDFRender(ctx context.Context, row pdfRenderRow) error`. |
| +- Produces: `func (s *Store) AccountPDFRenders(ctx context.Context, account string, monthStart time.Time) (int64, error)` |
| + (counts `outcome = 'rendered'` at or after `monthStart`). |
| +- Produces: `func (s *Store) PDFRenderSummary(ctx context.Context, since time.Time) (rendered, refused, failed int64, err error)` |
| + (`failed` covers `engine_error`, `failed` and `aborted`). |
| +- Produces: `const pdfRendersRetention = 90 * 24 * time.Hour` and |
| + `func (s *Store) prunePDFRenders(ctx context.Context, now time.Time) error`, |
| + following `pruneMailEvents` (stamped, at most once per interval, the |
| + gated path through `pruneMailAppRows`). |
| + |
| +- [ ] **Step 1: Write the failing tests:** |
| + - `TestPDFRenderCounts`: record rendered, engine_error, refused and |
| + aborted rows for `acct1` this month plus one rendered row last month. |
| + `AccountPDFRenders` for this month is 1. |
| + - `TestPDFRenderSummary`: rows in the last 24 h give the right three |
| + numbers, and older rows are ignored. |
| + - `TestPDFRendersPrune`: a 91-day-old row is gone after |
| + `prunePDFRenders`, and an 89-day-old row stays. |
| + - `TestPDFDoorRecordsEveryRequest` (in `apipdf_test.go`): one forwarded |
| + render, one 404 route refusal and one 429 each leave a row with the |
| + credential's name, route (empty for the 404), outcome and status. |
| + Only the render counts. |
| +- [ ] **Step 2:** Run `go test ./internal/console -run 'TestPDFRender|TestPDFDoorRecords' -count=1`. |
| + Expected: FAIL. |
| +- [ ] **Step 3: Implement** the table |
| + `pdf_renders (id INTEGER PRIMARY KEY, account TEXT NOT NULL, app TEXT NOT NULL, credential TEXT NOT NULL, route TEXT NOT NULL, outcome TEXT NOT NULL, status INTEGER NOT NULL, bytes_in INTEGER NOT NULL, bytes_out INTEGER NOT NULL, duration_ms INTEGER NOT NULL, at INTEGER NOT NULL)`, |
| + with indexes `pdf_renders_by_account (account, at)` and |
| + `pdf_renders_by_age (at)`. Classify it in `claimSQLTables` as |
| + `{Sqid: "account", App: "app"}`. Call `prunePDFRenders` from the record |
| + path, as mail events do. A record error is logged and never fails the |
| + request. |
| +- [ ] **Step 4:** Rerun the Step 2 command and the store gate tests |
| + (`-run 'TestPDFRender|TestPDFDoorRecords|TestClaimSQL|TestStoreGate'`). |
| + Expected: PASS. |
| +- [ ] **Step 5:** Commit: `console: record every PDF request`. |
| + |
| +--- |
| + |
| +### Task 4: Plan cap |
| + |
| +**Files:** |
| +- Modify: `internal/plans/catalog.go` (`Limits`, `nonNegative`, `generous`), `internal/plans/catalog_test.go` |
| +- Modify: `internal/console/plansponsor.go` (`sponsorUnlimited`) |
| +- Modify: `internal/console/plangrace.go` (`capPDF`, `capOrder`, `capPeriod`, `hasCeiling`, `graceEnd`) |
| +- Modify: `internal/console/planmeasure.go` (`measureCaps`) |
| +- Modify: `internal/console/billingusage.go`, `internal/console/billingpage.go`, `internal/console/billingpage_copy.go`, `internal/console/plancaps_copy.go` |
| +- Create: `internal/console/planpdf.go`, `internal/console/planpdf_test.go` |
| +- Modify: `internal/console/planexempt_test.go` (`planExemptSites`) |
| + |
| +**Interfaces:** |
| +- Consumes: `AccountPDFRenders` (Task 3). |
| +- Produces: `Limits.PDFRendersMonth int \`json:"pdf_renders_month,omitempty"\``. |
| +- Produces: `const capPDF capID = "pdf"`, monthly, with a 2x ceiling. |
| +- Produces: `func (s *Server) pdfPlanCheck(ctx context.Context, acct *Account, now time.Time) error`, |
| + which returns a `*planCapError` built from `capMessage("cli.cap.pdf_renders", used, limit)` |
| + when `used >= 2*limit`. It returns nil when `EffectiveLimits` is nil |
| + (exempt, or no catalog) or the field is 0. The door writes it as a 402. |
| + |
| +- [ ] **Step 1: Write the failing tests:** |
| + - `TestLimitsPDFRendersMonth` (plans): it round-trips through JSON as |
| + `pdf_renders_month`, `nonNegative` rejects `-1`, and `generous` takes |
| + the larger of two. |
| + - `TestTeamPooledLimitsMatchFields` still passes. Decide pooling with |
| + the team plan's rule for monthly counts (bandwidth's treatment) and |
| + add the field to `pooledFields` to match. |
| + - `TestPDFPlanCheck`: limit 100. 199 rendered gives nil, 200 gives a |
| + `*planCapError` whose message is the deck's `cli.cap.pdf_renders` with |
| + 200 and 100, an exempt account at 500 gives nil, and no catalog gives |
| + nil. |
| + - `TestPDFCapLevels`: `levelOf(capPDF, …)` gives warn at 80, over at |
| + 101 and ceiling at 200. `capPeriod` is the UTC month, and `graceEnd` |
| + is the 1st of next month. |
| + - `TestMeasureCapsPDF`: `measureCaps` puts `capPDF` with the month's |
| + rendered count and the plan limit. |
| + - `TestPDFDoorRefusesAtCeiling` (in `apipdf_test.go`): with 200 |
| + rendered and a limit of 100, the door answers 402 with deck copy, the |
| + fake sees nothing, and the row is `refused`. |
| + - The usage page test (beside the existing email usage test) shows |
| + `PDFs` and `%d of %d PDFs this month`. |
| +- [ ] **Step 2:** Run |
| + `go test ./internal/plans -run TestLimits -count=1 && go test ./internal/console -run 'TestPDFPlan|TestPDFCap|TestMeasureCapsPDF|TestPDFDoorRefusesAtCeiling|TestPlanExempt|Usage' -count=1`. |
| + Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Add the field in every hand-written place |
| + listed under Files. Add `capPDF` to `capOrder`, to `capPeriod` and |
| + `graceEnd` beside bandwidth, and to `hasCeiling`. Add it to `usageCaps`, |
| + `capLimit`, `capAmount` and the `addUsage` labels with deck copy. Add |
| + `pdfPlanCheck` to `planExemptSites`. The banner's ceiling stage uses |
| + `banner.pdf_refused`. |
| +- [ ] **Step 4:** Rerun the Step 2 command. Expected: PASS. |
| +- [ ] **Step 5:** Commit: `plans: monthly PDF render cap`. |
| + |
| +--- |
| + |
| +### Task 5: `carlos system pdf status` |
| + |
| +**Files:** |
| +- Modify: `internal/console/apisystem.go` (handler), `internal/console/authcli.go` (route beside `:1140`) |
| +- Modify: `internal/console/svcroutes_test.go` (`closedDoors`), `claim-routes.txt`, claim fixtures |
| +- Modify: `system.go` (verb allowlist :55, dispatch :86, help :146 and :198), `apimode.go` (client) |
| +- Test: `internal/console/apisystem_test.go`, `system_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `GET /api/cli/system/pdf` answering |
| + `{"configured": bool, "addr": string, "healthy": bool, "version": string, "error": string, "rendered_24h": int, "refused_24h": int, "failed_24h": int}`. |
| + It is registered `svcrole.Set{}`, and the handler starts with |
| + `s.apiSystemOperator`. |
| +- Produces: `func (a *apiSession) systemPDFStatus(ctx context.Context) (systemPDFStatus, error)` |
| + and `printSystemPDF(w io.Writer, st systemPDFStatus)`. |
| + |
| +- [ ] **Step 1: Write the failing tests:** |
| + - `TestSystemPDFStatus`: as an operator against a fake engine whose |
| + `/health` returns 200 and `/version` returns `8.21.1`, the response |
| + reports healthy with version `8.21.1` and the summary numbers from |
| + seeded rows. As a non-operator person: 403. As a Service token: 404. |
| + Unconfigured: `configured: false`. |
| + - `TestPrintSystemPDF`: the output uses the deck's status lines |
| + exactly. |
| + - The `closedDoors` equality test, after adding `GET /api/cli/system/pdf`. |
| +- [ ] **Step 2:** Run the new tests. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** The health check uses a 5 s timeout and is |
| + the only console call to `/health` or `/version`. |
| +- [ ] **Step 4:** Run |
| + `go test ./internal/console -run 'TestSystemPDF|TestEveryCLIDoor|TestClaim' -count=1 && go test . -run 'TestPrintSystemPDF|TestSystem' -count=1`. |
| + Expected: PASS. |
| +- [ ] **Step 5:** Commit: `cli: carlos system pdf status`. |
| + |
| +--- |
| + |
| +### Task 6: `pdf-host` module |
| + |
| +**Files:** |
| +- Create: `infra/modules/pdf-host/{main.tf,variables.tf,outputs.tf,versions.tf,README.md,pdf-init.sh.tftpl}` |
| +- Create: `infra/modules/pdf-host/tests/pdf_host.tftest.hcl` |
| +- Modify: `infra/modules/README.md` (module list; drop the "Tito's svc/pdf box is not a module" line's claim, say it moves here) |
| + |
| +**Interfaces:** |
| +- Variables, following `scanner-host`: `name`, `ami_id`, |
| + `client_security_group_id`, `region`, `instance_type` (default |
| + `t4g.medium`), `subnet_id`, `gotenberg_image` (default: Gotenberg 8.x |
| + arm64 **by digest**, the version recorded in the README), |
| + `api_timeout` (default `55s`). |
| +- Outputs: `pdf_addr` (`"http://${aws_instance.pdf.private_ip}:3000"`), |
| + `instance_id`, `security_group_id`. |
| + |
| +- [ ] **Step 1: Write the failing tftest** (`tofu test` with a mock |
| + provider, as `scanner-host`'s test does). Its asserts: |
| + - The SG has exactly one ingress rule: TCP 3000 from |
| + `client_security_group_id`, with no CIDR. |
| + - `metadata_options` has `http_tokens = "required"` and hop limit 1. |
| + - The role has the SSM core attachment and the `no_parameters` Deny. |
| + - `pdf_addr` has the right form. |
| + - `user_data` changes are ignored. |
| +- [ ] **Step 2:** Run `cd infra/modules/pdf-host && tofu init -backend=false && tofu test`. |
| + Expected: FAIL. |
| +- [ ] **Step 3: Implement** `main.tf` by adapting `scanner-host/main.tf`. |
| + The init template: |
| + - Installs Docker and nftables. |
| + - Writes an nftables table that hooks Docker's forward path for |
| + container traffic (`DOCKER-USER` or an equivalent `inet` table at |
| + forward priority, whichever survives Docker restarts on the AMI's |
| + Docker version). It drops every destination in |
| + `internal/caps/render.go`'s `docEngineEgressDeny` list (copy the 17 |
| + entries; a comment names the source), except the VPC resolver |
| + (`<vpc base>+2`, read from IMDS at boot) on port 53 UDP and TCP, and |
| + drops container-to-host traffic except that DNS. |
| + - Loads the rules in a unit ordered `Before=docker.service`, with |
| + `docker.service` given `Requires=` on it, so a failed load leaves |
| + Gotenberg stopped. |
| + - Runs Gotenberg as `docker run -d --restart=always -p <private_ip>:3000:3000 --dns <resolver> <image> gotenberg --api-timeout=<api_timeout> --chromium-deny-list='^file:(?!//\/tmp/).*' --webhook-deny-list='.*'` |
| + (check flag names against the pinned version's `--help` and note the |
| + check in the README). |
| + - Starts nothing listening on any other address. |
| +- [ ] **Step 4:** Rerun `tofu test`. Expected: PASS. Also run |
| + `tofu validate` and `tofu fmt -check`. |
| +- [ ] **Step 5:** Write the README in `scanner-host`'s shape: what the |
| + box is, the usage block, wiring (`pdf_addr` → `CARLOS_PDF_ADDR`), |
| + replacement, the fence and its acceptance checks (spec §4.2), and the |
| + Gotenberg version the route list was checked against. The README is |
| + user-facing, so run the copy-review skill before committing. |
| +- [ ] **Step 6:** Commit: `infra: pdf-host module, a fenced Gotenberg box`. |
| + |
| +--- |
| + |
| +### Task 7: Docs, comments and the #335 tidy |
| + |
| +**Files:** |
| +- Create: `docs/site/pdfs.md`; modify `docs/site/nav.json` (Reference section, slug `pdfs`) |
| +- Modify: `docs/site/plans.md` (catalog sentence ~:35, "five caps" list ~:67, per-cap stage bullets) |
| +- Modify: `README.md` "App capabilities" (~:1156-1302): one sentence by `doc_engine` pointing at the platform service |
| +- Modify: `internal/svcrole/svcrole.go:43` and `internal/release/system.go:10` comments |
| +- Modify: `docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md` (superseded header) |
| +- Delete: `internal/sim/engines/` (whole directory) |
| +- Check: `internal/sim/regionha/mutate.sh:3`, `internal/sim/regionha/witness_test.go` (comment references; reword so they stand without the deleted package) |
| + |
| +- [ ] **Step 1:** Draft `pdfs.md` covering spec §7's five items, with |
| + curl examples using `shop` and `example.com`. Draft the `plans.md`, |
| + README and nav additions. Run the copy-review skill on all of them and |
| + apply edits verbatim. |
| +- [ ] **Step 2:** Add the superseded header to the #335 spec: superseded on |
| + 2026-11-02 by `2026-11-02-pdf-service-design.md`, because the platform |
| + runs the engine, so the internal-route, grant and socket machinery has |
| + nothing left to protect. The spec and findings stay as history. |
| +- [ ] **Step 3:** `git rm -r internal/sim/engines` and update the two |
| + regionha comments. Then run `go vet ./internal/sim/...` and |
| + `go test ./internal/docsite -count=1`. Expected: PASS. |
| +- [ ] **Step 4:** Census. Run `make census-card`. Write a CLAIMS file |
| + naming the removed `internal/sim/engines/mutate.sh` and the new |
| + `infra/modules/pdf-host/*` files (what each is, and that root never |
| + reads them at runtime). Then run |
| + `make census-propose NAME=design-pdf-service CLAIMS=<file>`. Expected: |
| + an overlay with `@removed …;absent;` and `@coverage internal/sim/engines -` |
| + for the deletion and `new` rows for the module, plus a clean census. |
| + Brief Astra from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md` for |
| + the census verdict and record it on #280. |
| +- [ ] **Step 5:** Commit: `docs: PDFs page; retire #335's simulation`. |
| + |
| +--- |
| + |
| +### Task 8: Whole-branch review and merge |
| + |
| +- [ ] **Step 1:** Opus whole-branch review against the spec and this plan, |
| + briefed from the review template, within the round budget. Apply its |
| + fixes. |
| +- [ ] **Step 2:** Push and get CI green (`amadan ci status`). |
| +- [ ] **Step 3:** Merge only on Paul's go: |
| + `amadan branch merge carlos/platform design-pdf-service -squash -expect <full sha>`, |
| + with a subject under 80 characters. |
| + |
| +--- |
| + |
| +### Task 9: Carloku switch-on (needs Paul's scoped approval per step) |
| + |
| +Production infrastructure needs explicit approval (AGENTS.md). Before |
| +each apply, ask with account, region, resources, cost (one `t4g.medium` |
| +and a 20 GB gp3 volume), duration and cleanup. |
| + |
| +- [ ] **Step 1:** Release a platform version that carries the branch, and |
| + roll it dev first (memory: roll order). |
| +- [ ] **Step 2: Dev.** Apply `pdf-host` in the dev root and set |
| + `CARLOS_PDF_ADDR` on the dev console, through a roll restart. Run the |
| + spec §4.2 acceptance checks: |
| + - A render of HTML referencing `http://169.254.169.254/`, the console's |
| + private IP, another box's private IP, the bridge gateway and the VPC |
| + resolver on port 80 loads none of them (each shows as a broken |
| + image). |
| + - A public image by hostname loads. |
| + - Session Manager opens. |
| + - A dev app with a Service token renders an invoice, downloads it, and |
| + sends it as an email attachment. |
| + - `carlos system pdf status` shows it. |
| +- [ ] **Step 3: Flagship.** The same in `carloku-infrastructure`, with |
| + approval, then catalog values Free 100 and Personal 2,000 through the |
| + operator plan door. Tell Paul it is ready for Sporran. |
| +- [ ] **Step 4:** Close #335 with a pointer to the spec. Update the |
| + memory notes. |
| + |
| +Tito (spec §8 step 4) is its own plan after a week of Sporran use with no |
| +engine incident. |
diff --git a/docs/superpowers/specs/2026-11-02-pdf-service-design.md b/docs/superpowers/specs/2026-11-02-pdf-service-design.md| index e14cff80d..2754510cd 100644 |
| --- a/docs/superpowers/specs/2026-11-02-pdf-service-design.md |
| +++ b/docs/superpowers/specs/2026-11-02-pdf-service-design.md |
| @@ -157,8 +157,9 @@ configured for this deployment (CARLOS_PDF_ADDR)", following the scanner's |
| `system/pdf.json` in v1, because there is nothing for an operator to |
| consent to. **(my call)** |
| -`carlos system pdf status` (Operate role, operators) reports whether an |
| -engine is configured, whether it answers Gotenberg's `/health`, its |
| +`carlos system pdf status` (a closed door, `svcrole.Set{}`, with the same |
| +operator check `carlos system antivirus status` uses, `apiSystemOperator`) |
| +reports whether an engine is configured, whether it answers Gotenberg's `/health`, its |
| version, and the last 24 hours of renders and refusals. It sits beside |
| `carlos system antivirus status`. |
| @@ -266,7 +267,9 @@ values, changed without a release. Zero means no limit, as with the other |
| fields. |
| It is handled like the other caps in `internal/console/plangrace.go` |
| -(`evaluateCap`) and Plan 4's stages, following the email cap: |
| +(`evaluateCap`) and Plan 4's stages. It is a monthly cap with a 2x |
| +ceiling, as bandwidth and awake hours are. (Email is daily, and its pause |
| +runs from passes, so the request-time refusal below is new code.) |
| - At the limit: the usual warning banner, the owner email, and the |
| `X-Carlos-Plan-Warning` header. |