member backups: plans for slices 1b (download) and 2b (test results) (#898)
1b rev 1.1 carries Paul's rulings (2026-11-12): export-only home scope for the dbreads worker; no ready email, preparing note 'Usually a minute or two.'. 2b: UX pass and copy review before the build.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+530
−0
docs/superpowers/plans/2026-11-12-member-backups-slice1b.md+310 −0docs/superpowers/plans/2026-11-12-member-backups-slice2b.md+220 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md b/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md| new file mode 100644 |
| index 000000000..03f7e4d7a |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md |
| @@ -0,0 +1,310 @@ |
| +# Member backups, slice 1b: "Download a copy" in the console: 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. Opus implements each task; Astra reviews each task before the next starts. |
| + |
| +**Goal:** An account member presses "Download a copy" on an instance's Backups section and, a minute or two later, downloads a zip holding a checked copy of that instance's database plus a manifest, from a short-lived signed link, without the console ever holding the database. |
| + |
| +**Plan rev 1.1** (2026-11-12): Paul's rulings on D-H and D-E applied (header); the email task removed and the tasks renumbered. Not yet reviewed. |
| + |
| +**Architecture:** The console stores a durable job in `console.db` first, then publishes a signed `dbreads` request with a new operation, `export`, to the region's queue. The elected box runs the identity bracket around a capped plan and restore inside its sandboxed worker, which streams the checked database back after check B. The trusted agent zips it with a manifest, uploads it to `downloads/<job-id>.zip` in its own region's data bucket, confirms it and writes `result.json`. The console reconciles the job from that known key on status requests and at start, then presigns one exact GET per press. A lifecycle rule on `downloads/` is the only deletion, and the console keeps downloads off until it has read that rule back. |
| + |
| +**Tech Stack:** Go; `internal/dbreads` (wire, worker, agent), `internal/host` + `internal/lease` (arming, capability, upload), `internal/console` (job store, dispatch, doors, page, presign), OpenTofu modules (`deployment-buckets`, `region-remote-host`, `region-host`), the MinIO CI contract (`.amadan/ci.d/30-minio-contract`). |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-11-member-backups-design.md` rev 6.1: §2b in full, §2 layout, §11 D8 and D9, §12 where it applies. §2b's reviews: `docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-2b.md` and `-2b-R2.md`. Discussion #898. |
| + |
| +## Paul's rulings (2026-11-12) |
| + |
| +- **D-H, home scope: export-only home scope approved.** §2b refuses other regions and rides the `dbreads` queue. But the only console runs in the home region with `CARLOS_REGION` empty, home records keep `region: ""`, and `dbreads` can't address home: `Request.valid` and `ParseQueueKey` require `ValidRegion` (`ids.go:38`, `envelope.go:49`), and `dbReadsSettings` won't start on a box without a region (`internal/host/dbreads.go:52`). Without a fix, 1b would refuse every instance on dev and the flagship. Task 3 adds an export-only home queue scope (`_home`) and starts the worker on home boxes for export jobs only; `db query` and `db pull` forwarding are unchanged. It is the slice's security-sensitive task: Astra AND Fable review it, and the census covers it. |
| +- **D-E, email: drop the email sentence.** No background notify pass and no emails. `backups.preparing.note` becomes exactly "Usually a minute or two." (Paul approved this text in his answer, 2026-11-12). Task 0 updates the record and its pinned test. |
| + |
| +Decisions this plan takes (reviewers may overturn them): |
| +- The worker streams only the checked database. The agent writes `manifest.json` from the plan's TXID and time and its own SHA-256 of the relayed bytes, because the worker has nothing else to add. §2b has the worker stream both. |
| +- "Verified" means the console reads the data bucket's lifecycle back at start (`GetBucketLifecycleConfiguration`) and checks it. That needs `s3:GetLifecycleConfiguration` on the data bucket for the host role (Task 1). |
| +- Retrying a plan once after a vanished LTX file, as reads already do, is not a job retry. There are no job-level retries. |
| + |
| +## Global Constraints |
| + |
| +- Approved copy (Paul, copy review ddwtnxr27ojv5j7v5ntnrha6cq, record `docs/superpowers/plans/member-backups-slice1-copy.json`), verbatim: `backups.download` "Download a copy"; `backups.preparing` "Preparing your copy"; `backups.preparing.note` "Usually a minute or two." (re-approved by Paul 2026-11-12; the earlier text also promised an email); `backups.ready` "Download {file} ({size})"; `backups.ready.note` "Ready until {time} tomorrow."; `backups.toolarge` "Too large to download here. Use the command line below." Every other human-facing string (reasons, audit details, docs) comes only from Task 0's record. No em dashes. |
| +- Object key `downloads/<job-id>.zip` in the data bucket of the console's own region, derived from the job id on the server and never taken from browser input. Lifecycle on `downloads/`: current versions expire after 1 day, noncurrent versions after 1 day, delete markers go, and incomplete multipart uploads after 1 day. |
| +- Job states `queued`, `preparing`, `ready`, `failed`, `expired`. One open job per instance (`queued`, `preparing` or unexpired `ready`) by an atomic unique key, and a second start returns it. Owner deadline 20 minutes (`dbreads.OwnerDeadline`), no takeover, no job retries. `ready` only after the upload is confirmed. A result whose job or attempt id isn't the record's is refused. Records are deleted after 7 days. |
| +- Caps: restored size ≤ the box's `MaxRestored` (2 GiB default); planned LTX bytes ≤ `PlanBytesFactor`×that (the worker's rule); planner files ≤ `dbdoor.MaxPlanFiles` (20,000); the archive is streamed (no third scratch file) and capped at restored + restored/64 + 1 MiB; at most 2 open jobs per account; at most 10 starts per instance in any 24 hours; worker slots shared with reads through the existing admission. |
| +- `expires_at` = ready time + 24 hours, where ready time is `min(result.Ended, console now)`. After it, no link. A link's lifetime is the lesser of 15 minutes and the time left. Response: `Cache-Control: no-store`, `Referrer-Policy: no-referrer`, `response-content-disposition=attachment; filename="<file>"`. Signed URLs never appear in logs, audit details, `console.db` or analytics. There are no download emails. |
| +- Start (POST), status (GET) and link (POST) are person-only (browser session); the POSTs check CSRF. Admitted for current members of the job's account. Every request checks the route against the job's binding (account, app, host) and the record's current incarnation and region. Unauthorised and not found answer the same byte-identical 404. |
| +- Refused with the reason and, where `db pull` serves the instance, the CLI command, never an enabled button: other region, fleet-placed, pooled, no-copy classes, host claims on, no capable box (`db-export-1`) on complete evidence, no root signer, downloads not enabled or not verified, endpoint not HTTPS or not public. |
| +- The worker keeps no network and no credentials. The agent never opens SQLite; zipping relayed bytes is not decoding. |
| +- Audit actions: `db-download` (start), `db-download-link` (issuance). Never "downloaded". |
| +- No apply, release or roll in this plan: those are Paul's. The rule must be applied and verified on a deployment before `CONSOLE_DOWNLOADS=on` is set there. |
| +- Census: `internal/dbreads`, `internal/host`, `internal/lease` and every file under `infra/` are root-binary scope (Task 12, overlay `member-backups-1b`). The console isn't. |
| +- Local verification: changed packages only, with `-run`. CI runs the full suite. |
| +- Commit subjects under 80 characters, body after a blank line, ending `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. One amadan task per plan task. |
| + |
| +## Review Focus |
| + |
| +1. **Two tabs press Download within the same second**: one job, one signed request, one queue entry; the second press lands on the first job. Tests in Task 7 (store) and Task 9 (doors). |
| +2. **An instance deleted and recreated under the same name while its copy is ready**: status and link answer the 404; no URL is signed. Test in Task 9. |
| +3. **A member removed from the account while still signed in, with a copy ready**: status and link answer the 404. Test in Task 9. |
| +4. **A box whose clock runs ahead writes `result.Ended` in the future**: `expires_at` is never later than console now + 24 hours. Test in Task 8. |
| +5. **A status poll and the startup sweep reconcile one job at once**: exactly one transition and one audit row. Test in Task 8. |
| + |
| +--- |
| + |
| +### Task 0: UX pass and copy review |
| + |
| +**Files:** Create `docs/superpowers/plans/member-backups-slice1b-copy.json`; create `approved_member_backups_1b_copy_test.go` (repo root); mockup under the kit (untracked review folder, as slice 1's). |
| + |
| +- [ ] **Step 1: UX pass (AGENTS.md "Every UI change gets a UX pass").** In `docs/console-mockup-kit/shell.html`, mock the Backups section in each download state: none (primary "Download a copy" in the section head), preparing (button disabled, note), ready (button "Download {file} ({size})", note), failed (one reason line, button back), expired (button back), refused (reason line, no button, CLI disclosure) and too large. Look at it at 390 px and desktop width, light and dark; run the `impeccable` critique and distill passes. Fix what reads badly. Constraint from §2: one primary action, in the section head. |
| +- [ ] **Step 2: Apply the re-approved note (D-E).** In `docs/superpowers/plans/member-backups-slice1-copy.json`, set `backups.preparing.note`'s text to exactly "Usually a minute or two." and add `"note": "Re-approved by Paul on 2026-11-12: the email sentence was dropped, since 1b sends no email."`; it stays `pending: "slice 1b"` until Task 10 applies it. The record names `internal/console/instancecopy.go` as its home, not `internal/backupswords` (the string is page-only), so Task 10 puts it there. `approved_member_backups_copy_test.go` pins ids, not text; run `go test . -run TestApprovedMemberBackupsCopy -count=1` → PASS. |
| +- [ ] **Step 3: Draft the new strings** (ids `backups.dl.*`), in the layout from Step 1: the failed reasons `notpicked`, `timeout`, `changed` (record changed or moving), `nothing`, `generic`; the refusals `off` (every deployment-side reason), `busy` (2 open on the account), `daily` (10 today), `moving`; `expired` if the UX pass keeps a line for it; the two audit details (start, link); the `docs/site/cli.md` paragraph under `carlos instances backups` (downloading from the console, the 24-hour hold, that a link works for anyone who has it until it runs out, which can be sooner than 15 minutes, and that leaving the account doesn't cancel a link already issued); the operator section for `infra/modules/README.md` (`CONSOLE_DOWNLOADS`, `CONSOLE_DOWNLOADS_ENDPOINT`, the `downloads/` rule, MinIO's `mc ilm rule add`). |
| +- [ ] **Step 4:** Run the copy-review skill; apply Paul's edits verbatim to the JSON record. |
| +- [ ] **Step 5:** `TestApprovedMemberBackups1bCopy` via `checkApprovedCopy` (`approved_copy_test.go:71`), `t.Skip` until Task 10 lands the strings. |
| +- [ ] **Step 6:** Commit. |
| + |
| +### Task 1: The `downloads/` lifecycle rule, its read grant and the MinIO contract |
| + |
| +**Files:** |
| +- Modify: `infra/modules/deployment-buckets/main.tf` (`aws_s3_bucket_lifecycle_configuration.data`), `infra/modules/region-remote-host/main.tf` (same resource) |
| +- Modify: `infra/modules/region-host/main.tf` (`host_buckets` statements) and `infra/modules/region-host/group_iam.tf` (`group_bucket_statements`) |
| +- Modify: `infra/modules/README.md` (Task 0's operator section, verbatim) |
| +- Test: create `infra/modules/deployment-buckets/tests/downloads.tftest.hcl`, `infra/modules/region-remote-host/tests/downloads.tftest.hcl`, `infra/modules/region-host/tests/downloads_lifecycle_read.tftest.hcl`; modify both `data_lifecycle.tftest.hcl` (their `one(...rule)` stops being one) |
| + |
| +**Interfaces:** |
| +- Produces: in each data bucket, rules `downloads-expire` (filter prefix `downloads/`, expiration days 1, noncurrent days 1, abort multipart 1 day) and `downloads-delete-markers` (same prefix, `expired_object_delete_marker = true`; S3 refuses it beside days), mirroring `db-reads-expire` in the deployment bucket. `expire-noncurrent` is unchanged. The host role gets `s3:GetLifecycleConfiguration` on the data bucket ARN alone (both statement sets). |
| + |
| +- [ ] **Step 1: Failing tests.** `downloads_rule_expires_everything_after_a_day` (both bucket modules: exactly one `downloads-expire` rule with the four values above and one `downloads-delete-markers` rule); `expire_noncurrent_unchanged` (both); `host_role_reads_data_bucket_lifecycle` (region-host, group off and group on: the action on `var.data_bucket_arn` only, never on the deployment bucket). Rewrite `data_noncurrent_days_is_configurable` to select the `expire-noncurrent` rule by id. |
| +- [ ] **Step 2:** `tofu -chdir=infra/modules/<module> init -backend=false && tofu -chdir=infra/modules/<module> test` for the three modules → FAIL. Where tofu or the provider cache is unavailable, say so in the task report; CI does not run these, so the reviewer reads the plans. |
| +- [ ] **Step 3:** Implement. Comment each rule like the `db-reads` ones (why it exists, that it is the only deletion, that deletion is asynchronous). |
| +- [ ] **Step 4:** Tests PASS. |
| +- [ ] **Step 5:** Commit. (Applying is Paul's, Global Constraints.) |
| + |
| +### Task 2: The `export` operation on the wire |
| + |
| +**Files:** Modify `internal/dbreads/protocol.go`, `envelope.go`, `ids.go`, `result.go`, `worker.go` (hello only); test in `internal/dbreads/envelope_test.go`, `ids_test.go`, `export_wire_test.go` (new). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const OpExport = "export"`, `const ExportCapability = "db-export-1"`, `const DownloadsPrefix = "downloads/"`. |
| + - `func NewJobID(r io.Reader) (string, error)` (`"dbd_"` + 26 base32 characters, as `NewID`), `func MintJobID() (string, error)`, `func ValidJobID(id string) bool`, `func DownloadKey(job string) string` (`DownloadsPrefix + job + ".zip"`). |
| + - `Request` gains `Job string \`json:"job,omitempty"\`` after `IssuedAt` (last: the wire's field order). `valid()`: `OpExport` requires `SQL == ""`, `At == ""`, `ReplyKey == ""`, `ValidJobID(Job)`; every other op requires `Job == ""` and keeps today's reply-key rule. |
| + - `type ExportOutcome struct { Job, Attempt, Key string; Bytes int64; TXID uint64; At time.Time }` (JSON `job, attempt, key, bytes, txid, at`); `Result` gains `Export *ExportOutcome \`json:"export,omitempty"\``. |
| + - `func (r Result) ValidExport(job, attempt string) error`: today's state/code vocabulary; `LastSeq == 0`; `Sealed == ""`; `done` requires code `""` and `Export` with `Job == job`, `Attempt == attempt`, `Key == DownloadKey(job)`, `Bytes > 0`; any other state requires `Export == nil`. |
| + - `HelloReply` gains `Ops []string \`json:"ops,omitempty"\``; `ServeWorker` answers the hello with `Ops: []string{OpQuery, OpPull, OpExport}` beside `opt.Self()`'s view. |
| + - `readyMsg` gains `Bytes int64 \`json:"bytes,omitempty"\``. |
| + - `type Manifest struct { V int; TXID uint64; At time.Time; SHA256 string; Bytes int64; PlatformVersion string; Files string }`, JSON `v, txid, at, sha256, bytes, platform_version, files`; `Files` is always `"not_included"`. |
| + |
| +- [ ] **Step 1: Failing tests.** |
| + - `TestQueryAndPullWireUnchanged`: golden canonical bytes of a signed query and a signed pull, captured before the change, are byte-identical after it. |
| + - `TestExportRequestRefusedByOldType`: an export envelope verified into a copy of today's `Request` type (no `Job` field) fails `VerifyRootEnvelope` (`DisallowUnknownFields`), so an old box never runs one. |
| + - `TestExportRequestValid`: a table of an export with SQL, with At, with a reply key, without a job, with a malformed job, and a query with a job, all refused by `Sign`; a well-formed export signs and `Verify`s. |
| + - `TestValidExport`: every row of the vocabulary; a `done` with a wrong job, a wrong attempt, a key not `DownloadKey(job)`, zero bytes, a `last_seq` or a `sealed` is refused; a `failed` carrying `export` is refused. |
| + - `TestJobIDShape` (mirrors `ids_test.go`'s id tests). |
| +- [ ] **Step 2:** `go test ./internal/dbreads -run 'WireUnchanged|ExportRequest|ValidExport|JobID|Envelope|IDs' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS, with the existing envelope and id tests. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 3: An export-only home scope (security-sensitive; Paul approved D-H) |
| + |
| +**Review:** Astra AND Fable review this task before Task 4 starts, and its units are named in Task 12's census claims. This is new reach for the root-signed protocol: home boxes start the `dbreads` worker for the first time. |
| + |
| +**Files:** Modify `internal/dbreads/ids.go`, `envelope.go`, `agent.go` (`Pass`); `internal/host/dbreads.go` (`dbReadsSettings`, `dbReadsSocketWanted`); tests in `internal/dbreads/ids_test.go`, `envelope_test.go`, `internal/host/dbreads_test.go`. |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const HomeScope = "_home"` (outside `regionShape`, so no region code can collide); `func QueueScope(region string) string` (`""` → `HomeScope`, else `region`). `QueueRegionPrefix`, `QueueHourPrefix` and `QueueKey` map their region through `QueueScope`. `ParseQueueKey` accepts `HomeScope` and returns `QueueEntry.Region == ""` for it. `QueueMatches` compares through `QueueScope`. |
| + - `Request.valid()`: `Region == ""` is valid only for `OpExport`. `ValidRegion` itself is unchanged (forwarding's `forwardable` keeps refusing home). |
| + - `dbReadsEnv` gains `exportOnly bool`. `dbReadsSettings`: an empty `CARLOS_REGION` arms with `region ""`, `exportOnly: true`; a non-empty invalid one (a fleet placement included) is refused as today. `dbReadsSocketWanted` follows it, unchanged otherwise. |
| + - `AgentConfig.Region == ""` is a home agent: `Verify` already requires `req.Region == region`, and `valid` makes such a request an export. |
| + |
| +- [ ] **Step 1: Failing tests.** |
| + - `TestQueueKeyHomeScope`: round trip; a key under `queue/_home/` parses with region `""`; `queue/home/` is a region called `home`, not the home scope. |
| + - `TestHomeScopeNeverQueryOrPull` (the ruling's first proof): for both `OpQuery` and `OpPull`, a `Region ""` request is refused by `Sign`; a hand-signed root envelope of one (bypassing `Sign`) is refused by `Verify` on a home agent; a queue entry under `_home` pointing at one is decided and logged with no `picked` written, no worker dialled and no `result.json`; an `ExportOnly` agent given a validly signed query or pull for a region (its own region set to that region in the test) still refuses it before the election. Only `OpExport` with `Region ""` is accepted. |
| + - `TestNonHomeUnchanged` (the second proof): golden canonical bytes and queue keys for a regional query, pull and export are byte-identical to before the change; `QueueScope("uk") == "uk"`; `ParseQueueKey` gives the same entries for every existing `ids_test.go` key; a regional agent's `Pass` lists exactly the prefixes it listed before; `dbReadsSettings` and `dbReadsSocketWanted` answer exactly as before for every non-empty `CARLOS_REGION` in `dbreads_test.go`'s table; a regional agent's capabilities are unchanged; `forwardable` still refuses a home record. |
| + - `TestDBReadsSettingsHome`: empty region → started, `exportOnly`; `fleet/x` and `bad region` refused; host claims and `CARLOS_DB_READS=0` still refuse. `TestDBReadsSocketWantedHome`. |
| +- [ ] **Step 2:** `go test ./internal/dbreads ./internal/host ./internal/console -run 'HomeScope|NonHomeUnchanged|QueueKey|DBReadsSettings|DBReadsSocketWanted|Forwardable' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS, plus `go test ./internal/dbreads -run 'Loop|Agent|Read|Pull' -count=1` unchanged. |
| +- [ ] **Step 5:** Commit; then the Astra and Fable task reviews (three rounds at most). |
| + |
| +### Task 4: The worker's `export` operation |
| + |
| +**Files:** Modify `internal/dbreads/worker.go`; test `internal/dbreads/worker_export_test.go` (new). |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `OpExport`, `readyMsg.Bytes`. |
| +- Produces: `ServeWorker` accepts `OpExport` headers. It receives and checks the files as for a query (header names, the plan ending at its target, `planWithinBounds`), restores with `opt.Restore` (`dbdoor.RestoreLocal`, which runs the integrity check), refuses a file over `h.MaxRestored` with `CodeTooLarge`, and sends `frameReady` with `{txid, bytes: <restored file size>}`. On `frameStop` it ends. On `frameRun` with empty SQL it streams the file's bytes as `frameOutput` frames and ends with `endMsg{Code: ""}`; a run with SQL is `errProtocol`. |
| + |
| +- [ ] **Step 1: Failing tests:** `TestWorkerExportSendsTheCheckedFile` (output bytes equal a direct `RestoreLocal` of the same files; ready's bytes equal their length); `TestWorkerExportStopsWithoutSending`; `TestWorkerExportRefusesSQL`; `TestWorkerExportIntegrityFailure` (a `Restore` stub returning an error → `CodeCheckFailed`, no output frame); `TestWorkerExportTooLarge`; `TestWorkerHelloListsOps`. |
| +- [ ] **Step 2:** `go test ./internal/dbreads -run 'WorkerExport|WorkerHello|Worker' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement beside the query path; no new scratch file. |
| +- [ ] **Step 4:** PASS, including `worker_linux_test.go`. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 5: The agent's export: bracket, caps, archive, upload, result |
| + |
| +**Files:** Create `internal/dbreads/export.go`; modify `internal/dbreads/agent.go` (`AgentConfig`, `NewAgent`, `probe`, `consider`), `read.go` (`serve` branches on `OpExport`); modify `internal/dbdoor/plan_from.go` (export `MaxPlanFiles`) and `internal/console/backups.go` (`backupsMaxFiles` becomes `dbdoor.MaxPlanFiles`); test `internal/dbreads/export_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 2 and 4; `dbdoor.PositionAndHistory`; `ConfirmIdentity`; `sendFile`; `admission`. |
| +- Produces: |
| + - `const dbdoor.MaxPlanFiles = 20000`. |
| + - `type DownloadStore interface { Upload(ctx context.Context, key string, body io.Reader) error; Size(ctx context.Context, key string) (int64, error) }`; `AgentConfig.Downloads DownloadStore` (nil: no export). |
| + - `func (a *Agent) ExportCapable() bool`: `Capable()`, a non-nil `Downloads`, and the last passing probe's `Ops` holds `OpExport`. |
| + - `consider` decides and logs an `OpExport` request on an agent that isn't `ExportCapable` without entering the election. |
| + - `func (a *Agent) export(ctx context.Context, req Request) Result`, called by `serve` for `OpExport` (whose past-deadline path writes `failed`/`interrupted` without sealing). Order: check A → `PositionAndHistory(pctx, rd, dbdoor.MaxPlanFiles)` (its `ErrTooManyFiles` → `too-large`) → restored size over `MaxRestored` → `too-large` → reservation `LTXBytes + RestoredBytes` through `adm.grow` (else `no-room`) → stream the files to the worker → `frameReady` (TXID equal to the plan's, `0 < bytes ≤ MaxRestored`, else `check-failed`) → check B (`refused` with its code; `frameStop`) → `frameRun` → relay the output into a `zip.Writer` piped into `Downloads.Upload(ctx, DownloadKey(req.Job), pipe)`: the entry `db.sqlite3` (method Deflate, modified time = the plan's `At`), then `manifest.json` last (`Manifest{V: 1, TXID, At, SHA256 of the relayed bytes, Bytes, PlatformVersion: version.Build, Files: "not_included"}`), with the archive capped by a counting writer → relayed bytes must equal ready's bytes, else `check-failed` → `Downloads.Size` must equal the archive bytes written, else `interrupted` → `Result{State: done, Export: &ExportOutcome{Job, Attempt: req.ID, Key, Bytes, TXID, At}}`. Every ending derived from the replica goes through check B first, as `afterCheckB` does. A vanished planned file re-plans once (as `read` does), then `changed-twice`. Nothing is uploaded before check B passes. |
| + |
| +- [ ] **Step 1: Failing tests** (fixture `newFixture`, `inProcWorkers`, a recording `DownloadStore`): |
| + - `TestExportUploadsAZipThatOpens`: the uploaded archive opens with `archive/zip`; `db.sqlite3` restores to the fixture's rows (open it in the test with the `sqlite` driver); `manifest.json` is the last entry, its SHA-256 and bytes match the entry, `files` is `not_included`, TXID and `at` equal the plan's; `result.json` is `done` and passes `ValidExport(job, req.ID)`. |
| + - `TestExportBracket`: deletion, same-account recreate, cross-account recreate and a move, each injected during planning and during download: `refused` with `record-changed` or `moving`, and the recording store saw no `Upload` call. |
| + - `TestExportCaps`: restored over `MaxRestored` and files over `MaxPlanFiles` → `failed`/`too-large`, no upload, no worker dialled; a disk short of the reservation → `no-room`. |
| + - `TestExportUploadFails`: `Upload` errors → `failed`/`interrupted`, never `done`; `Size` disagreeing → `interrupted`. |
| + - `TestExportShortStream`: a worker that sends fewer bytes than ready said → `check-failed`. |
| + - `TestExportCancelAndDeadline`: a cancel object mid-stream → `cancelled`; the owner deadline mid-upload → `failed`/`interrupted`; scratch reservations released as for reads. |
| + - `TestExportNotCapableNotElected`: a nil `Downloads`, or a probe without `export` in `Ops` → no `picked` written. |
| + - `TestExportSharesReadSlots`: two reads running → an export waits for admission like a third read. |
| +- [ ] **Step 2:** `go test ./internal/dbreads ./internal/dbdoor ./internal/console -run 'Export|PositionAndHistory|BackupsFor' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement in `export.go`; don't thread exports through `attempt` (whose sealing they don't use). |
| +- [ ] **Step 4:** PASS, plus `go test ./internal/dbreads -count=1 -run 'Read|Pull|Loop|Agent'`. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 6: The box: upload store, arming and the capability |
| + |
| +**Files:** Create `internal/lease/downloads.go` + test; modify `internal/host/dbreads.go` (`armDBReads`, capability helper), `internal/host/edgesfile.go:1381`, `go.mod` (`github.com/aws/aws-sdk-go-v2/feature/s3/manager` becomes direct); tests `internal/host/dbreads_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 5's `DownloadStore`, `ExportCapable`; Task 3's `exportOnly`. |
| +- Produces: |
| + - `func lease.NewDownloadStore(ctx context.Context, bucket, region string) (*DownloadStore, error)`: an S3 client built by `NewFilesStore`'s rule (region resolution, `s3compat.Options()`, when-required checksums); `Upload` through `manager.NewUploader` with `ContentType: application/zip`; `Size` by `HeadObject`. Both refuse a key not under `"downloads/"` (a literal: `lease` can't import `dbreads`). |
| + - `AgentConfig.ExportOnly bool` (set from `dbReadsEnv.exportOnly`): `consider` decides and logs every op but export without entering the election (Task 3's validity already refuses them; this is the box's own check too). |
| + - `armDBReads` passes `Downloads` built from `hib.Bucket`/`hib.Region` (nil, logged, when building it fails) and `ExportOnly`. |
| + - `func withDBReadCapabilities(caps []string, read, export bool) []string` replaces `withDBReadCapability`; the edges loop passes `read = Capable() && !ExportOnly` and `export = ExportCapable()`. |
| + |
| +- [ ] **Step 1: Failing tests:** `TestDownloadStoreRefusesOtherKeys`; `TestDownloadsPrefixAgrees` (in `internal/host`: the literal equals `dbreads.DownloadsPrefix`); `TestWithDBReadCapabilities` (four combinations; a home agent never publishes `db-read-1`); `TestArmDBReadsWiresDownloads` (the configured agent has a non-nil store when the bucket is set). |
| +- [ ] **Step 2:** `go test ./internal/lease ./internal/host -run 'DownloadStore|DownloadsPrefix|DBReadCapabilit|ArmDBReads' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement. A failed multipart upload is left to the lifecycle rule's 1-day abort (the host role has no `s3:AbortMultipartUpload`). |
| +- [ ] **Step 4:** PASS; `GOOS=darwin go build . && GOOS=windows go build .` (the CLI links `internal/host`). |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 7: The job record in `console.db` |
| + |
| +**Files:** Create `internal/console/downloadstore.go` + `downloadstore_test.go`; modify `internal/console/store.go` (`migrate` calls `migrateDBDownloads`). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - Table `db_downloads(id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, account TEXT NOT NULL, app TEXT NOT NULL, host TEXT NOT NULL, region TEXT NOT NULL, incarnation TEXT NOT NULL, attempt TEXT NOT NULL, by_address TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('queued','preparing','ready','failed','expired')), reason TEXT NOT NULL DEFAULT '', object_key TEXT NOT NULL, bytes INTEGER NOT NULL DEFAULT 0, txid INTEGER NOT NULL DEFAULT 0, copy_at INTEGER, created_at INTEGER NOT NULL, issued_at INTEGER NOT NULL, owner_deadline INTEGER, ready_at INTEGER, expires_at INTEGER)`; `CREATE UNIQUE INDEX db_downloads_open ON db_downloads(account_id, app, host) WHERE state IN ('queued','preparing','ready')`; an index on `(account_id, state)`. |
| + - `type dbDownload struct` with those fields as Go types (times as `time.Time`, zero for NULL). |
| + - `const downloadOpenPerAccount = 2`, `downloadStartsPerDay = 10`, `downloadKeep = 7 * 24 * time.Hour`, `downloadHold = 24 * time.Hour`. |
| + - `var errDownloadsBusy, errDownloadsDaily error`. |
| + - `func (s *Store) StartDBDownload(ctx context.Context, d dbDownload, now time.Time) (dbDownload, bool /*created*/, error)`: one transaction. It deletes rows created more than `downloadKeep` ago, moves this instance's `ready` rows past `expires_at` to `expired`, returns an existing open row (`created == false`), counts the account's `queued`+`preparing` (`errDownloadsBusy` at 2) and the instance's rows created in the last 24 hours (`errDownloadsDaily` at 10), then inserts `d` as `queued`. A unique-index conflict re-reads and returns the winner. |
| + - `func (s *Store) DBDownloadFor(ctx context.Context, accountID int64, app, host string) (dbDownload, bool, error)`: the newest row. |
| + - `func (s *Store) OpenDBDownloads(ctx context.Context) ([]dbDownload, error)` (`queued`, `preparing`) and `OpenDBDownloadsFor(ctx, accountID int64)`. |
| + - `func (s *Store) MoveDBDownload(ctx context.Context, id, from string, to dbDownload) (bool, error)`: `UPDATE ... WHERE id = ? AND state = ?`; false when another caller moved it first. |
| + |
| +- [ ] **Step 1: Failing tests:** `TestStartDBDownloadOnePerInstance` (two concurrent starts from goroutines → one created, both return the same id); `TestStartDBDownloadReturnsReady` (an unexpired ready row is returned; an expired one is moved to `expired` and a new job starts); `TestStartDBDownloadAccountCap` (third open job on the account refused; a ready one doesn't count); `TestStartDBDownloadDailyCap` (the 11th start in 24 hours refused, the next day admitted); `TestDBDownloadPrune` (rows past 7 days go); `TestMoveDBDownloadCAS` (two moves from `preparing`: one wins). |
| +- [ ] **Step 2:** `go test ./internal/console -run 'DBDownload' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 8: Availability, dispatch and reconciliation |
| + |
| +**Files:** Create `internal/console/downloads.go` + `downloads_test.go`; modify `internal/console/backups.go` (`restoredBytes`), `internal/console/server.go` (`Config` gains `Downloads bool`, `DownloadsEndpoint string`; `Server` gains `downloadObjs downloadObjects`, `downloadsReady atomic.Bool`), `internal/console/apidbforward.go` (`dbForwardEvidence` delegates to `capabilityEvidence`, unchanged behaviour), `cmd/console/main.go` (`CONSOLE_DOWNLOADS=on`, `CONSOLE_DOWNLOADS_ENDPOINT`, `VerifyDownloads` and `SweepDBDownloads` at start). |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 2, 3 and 7; `classifyBackups`, `backupsFor`; `s.liveEdges`; `release.RootSigner`, `release.BumpSerial`; `s.cancelDBRead`. |
| +- Produces: |
| + - `type lifecycleRule struct { Enabled bool; Prefix string; Narrowed bool /*tag or size filter*/; ExpireDays, NoncurrentDays, AbortDays int32; DeleteMarkers bool }` (no SDK types in the core). |
| + - `type downloadObjects interface { Rules(ctx context.Context) ([]lifecycleRule, error); Size(ctx context.Context, key string) (int64, error); PresignGet(ctx context.Context, key, filename string, ttl time.Duration) (string, error) }` (adapter in Task 9). |
| + - `func lifecycleCoversDownloads(rules []lifecycleRule, compatible bool) error`. Each requirement is met by some enabled, un-narrowed rule whose prefix is a prefix of `downloads/`: expiry ≤ 1 day, noncurrent ≤ 1 day, delete markers, and, unless `compatible` (a `CARLOS_S3_ENDPOINT` store, whose own stale-upload cleanup the contract documents), abort ≤ 1 day. |
| + - `func checkDownloadsEndpoint(raw string, compatible bool, lookup func(context.Context, string) ([]netip.Addr, error)) error`. AWS (`raw == ""`, not compatible) passes. A compatible store needs `raw`: `https`, no userinfo or query, and a host that is not an IP literal and resolves only to addresses no `egressaddr` class or `egressaddr.FenceDeny` refuses. |
| + - `func (s *Server) VerifyDownloads(ctx context.Context) error`: with `cfg.Downloads`, runs both checks and sets `downloadsReady`; logs why and leaves it false otherwise. |
| + - `func capabilityEvidence(snap edgesSnapshot, err error, region, capability string) string` (`dbForwardNone`, `dbForwardDead` or `""`). |
| + - Refusal whys (each maps to one Task 0 string): `downloadWhyOff`, `downloadWhyMoving`, `downloadWhyTooLarge`, `downloadWhyBusy`, `downloadWhyDaily`. Failure reasons stored on a job: `downloadReasonNotPicked = "not_picked"`, `downloadReasonTimeout = "timeout"`, `downloadReasonTooLarge = "too_large"`, `downloadReasonChanged = "changed"`, `downloadReasonNothing = "nothing"`, `downloadReasonGeneric = "generic"`. |
| + - `type downloadAvail struct { OK bool; Why string }`. `func (s *Server) downloadsAvailable(ctx context.Context, rec provision.Record) downloadAvail`, with `Why` one of `downloadWhyOff` (not ready, host claims, no root signer whose public half is `ReleasePub`, no capable or live box on complete evidence) or `downloadWhyMoving`. Incomplete evidence admits, as forwarding does. |
| + - `func (s *Server) startDBDownload(ctx context.Context, acct *Account, app string, rec provision.Record, actor string, now time.Time) (dbDownload, string /*why*/, error)`: class must be `replicated` (`classifyBackups`), availability ok, `backupsFor`'s restored size ≤ `dbreads.DefaultMaxRestored` (else `downloadWhyTooLarge`; `backupsView` gains an unexported `restoredBytes` from the plan it already reads); job id `dbreads.MintJobID`, attempt `dbreads.MintID`, incarnation `provision.Incarnation`, `object_key = dbreads.DownloadKey(id)`; `StartDBDownload` (busy and daily map to `downloadWhyBusy`, `downloadWhyDaily`); only when created, `publishDBDownload`. |
| + - `func (s *Server) publishDBDownload(ctx context.Context, d dbDownload) error`: on a context detached from the browser request (`context.WithoutCancel`, 20 s), sign `Request{Op: OpExport, Job: d.ID, ID: d.Attempt, Account, App, Host, Incarnation, Region: d.Region, By, IssuedAt}`, then create `RequestKey`, then the `QueueKey` entry, then `BumpSerial` (best effort and logged: boxes list the queue every 30 s anyway). If the request or queue create fails: `MoveDBDownload(queued→failed, reason downloadReasonGeneric)` and `cancelDBRead(d.Attempt)`. |
| + - `func (s *Server) reconcileDBDownload(ctx context.Context, d dbDownload, now time.Time) dbDownload`, at most one store read per job every `downloadReconcileEvery = 3 * time.Second`. `queued` with `picked` → `preparing`, `owner_deadline = min(picked.Deadline + OwnerGrace, issued + RequestBound)`. Then `result.json`, which must pass `ValidExport(d.ID, d.Attempt)`; a done result also needs `Size(key) == Export.Bytes`, and then becomes `ready` with `ready_at = min(res.Ended, now)`, `expires_at = ready_at + downloadHold`, bytes, txid and `copy_at`. A failed or refused result becomes `failed` with `downloadReasonFor(code)`. With no result: `queued` past `issued + ConsoleWaitsPicked` → `failed`/`not_picked`, and `preparing` past `owner_deadline` → `failed`/`timeout`, each writing the cancel. `ready` past `expires_at` → `expired`. A result that doesn't validate is logged and ignored. Every move is `MoveDBDownload`'s compare-and-set. |
| + - `func downloadReasonFor(code string) string`: `too-large` → `too_large`; `record-changed`, `moving` → `changed`; `nothing-replicated` → `nothing`; `timeout` → `timeout`; anything else → `generic`. |
| + - `func (s *Server) SweepDBDownloads(ctx context.Context)`: reconcile every open job once (and prune), at start. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestLifecycleCoversDownloads` (table: the Task 1 rules pass; each value at 2 days fails; a disabled rule, a tag-narrowed rule and a `downloads/x/` prefix don't count; a whole-bucket rule counts; abort missing passes only when `compatible`). |
| + - `TestCheckDownloadsEndpoint` (AWS default passes; `http://`, an IP literal, a name resolving to `10.0.0.1`, `127.0.0.1` or `169.254.169.254`, and userinfo are refused; a public name passes). |
| + - `TestDownloadsUnavailable` (each `Why`: not verified, host claims, scoped key, complete evidence with no `db-export-1` box, a moving record; incomplete evidence admits). |
| + - `TestCapabilityEvidenceKeepsForwarding` (`dbForwardEvidence`'s existing cases unchanged). |
| + - `TestStartDBDownloadPublishesOnce` (two starts → one request object, one queue entry in the store; the record is written before the request: a store that fails `Put` leaves a `failed` job and a cancel). |
| + - `TestStartDBDownloadSurvivesDisconnect` (the caller's context cancelled right after the record is written: the request and queue entry are still published) and `TestStartDBDownloadBumpLost` (a failing `BumpSerial` leaves the job `queued`, and a box's next `Pass` picks it). |
| + - `TestReconcileDBDownload`: picked → preparing; a done result with matching size → ready; a size mismatch stays preparing; a result for another job or attempt is ignored; no picked by 2 minutes → `not_picked` and cancel written; owner deadline passed → `timeout`; a late done result after `failed` changes nothing; ready past 24 hours → expired. |
| + - `TestReconcileClampsFutureEnded` (Review Focus 4). |
| + - `TestReconcileConcurrentOneTransition` (Review Focus 5: a status reconcile and `SweepDBDownloads` on one job at once → one move, the other sees false). |
| + - `TestSweepAfterRestart` (a job queued before a "restart", that is a new `Server` over the same `console.db` and store, ends `ready` when its result is there and `failed` when its deadline passed). |
| +- [ ] **Step 2:** `go test ./internal/console -run 'LifecycleCovers|DownloadsEndpoint|DownloadsUnavailable|CapabilityEvidence|DBForwardEvidence|StartDBDownload|ReconcileDBDownload|ReconcileClamps|ReconcileConcurrent|SweepAfterRestart|BackupsFor' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 9: The doors and the signed link |
| + |
| +**Files:** Create `internal/console/browserdownloads.go` + `browserdownloads_test.go`, `internal/console/downloads_s3.go` + test; modify `internal/console/routedecls.go` (three routes), `linkedpolicy.go`, `testdata/claim-routes.txt`, `claim_invariant_fixtures_test.go`, `nobucket_posts_test.go` (as their tests demand), `cmd/console/main.go` (build the adapter). |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 7 and 8. |
| +- Produces: |
| + - Routes: `POST /a/{sqid}/apps/{app}/instances/{host}/backups/download` → `handleDBDownloadStart`; `GET /a/{sqid}/apps/{app}/instances/{host}/backups/download` → `handleDBDownloadStatus`; `POST /a/{sqid}/apps/{app}/instances/{host}/backups/download/link` → `handleDBDownloadLink`. |
| + - `func (s *Server) downloadGate(w http.ResponseWriter, r *http.Request, csrf bool) (downloadCtx, bool)`, where `downloadCtx` holds `acct, app, host, actor, rec`. The gate, in order: `s.account` (a session; members only), CSRF when asked, `HasAppIn`, `refuseLinkedPage`, `provision.ValidHostShape`, then the record read fresh. Every refusal after the session check is the byte-identical `http.NotFound`. |
| + - `func (s *Server) downloadJob(ctx context.Context, dc downloadCtx) (dbDownload, bool)`: `DBDownloadFor`, then the job's account, app and host must equal the route's, its incarnation must equal `provision.Incarnation` of the fresh record, and its region the record's; else not found. |
| + - Start: `startDBDownload`; a `db-download` activity row (Task 0's detail) only when created; then `303` to the instance page `#backups`. A refusal also `303`s back; the page shows the why. |
| + - Status: reconcile, then JSON `{"state": "..."}` with `Cache-Control: no-store`. It never includes the key, size or URL. |
| + - Link: the job must be `ready` with `now < expires_at`, and `Size(key)` must answer (a missing object moves the job to `expired` and 404s). Then `PresignGet(key, filename, min(15*time.Minute, expires_at - now))`, a `db-download-link` activity row, and `303` with `Location` set to the URL, `Cache-Control: no-store` and `Referrer-Policy: no-referrer`. |
| + - `func downloadFilename(host string, copyAt time.Time) string`: the host's first label + `-` + `copyAt.UTC().Format("20060102T1504Z")` + `.zip`. |
| + - `func NewS3DownloadObjects(ctx context.Context, bucket, region, publicEndpoint string) (downloadObjects, error)`: rules via `GetBucketLifecycleConfiguration` mapped to `lifecycleRule`; size via `HeadObject`; presign via `s3.NewPresignClient` on a client whose base endpoint is `publicEndpoint` when set, with `ResponseContentDisposition: attachment; filename="<file>"` and `ResponseContentType: application/zip`. |
| + |
| +- [ ] **Step 1: Failing tests** (`newConsoleFixture`, `signInAs`, a fake `downloadObjects`): |
| + - `TestDBDownloadStartTwoTabs` (Review Focus 1: two concurrent POSTs → one job, one request object). |
| + - `TestDBDownloadStartRefusals` (no CSRF → refused; a service token, another account's member, a bad host and an unknown host → the same 404 bytes; other region, pooled, fleet, demo, no-sleep, host claims, not verified → no job and the page's why). |
| + - `TestDBDownloadLinkSignsExactObject` (the presigner gets exactly `DownloadKey(job)`, the filename, and a ttl of 15 minutes, or what's left when that is less; headers `no-store` and `no-referrer`; `Location` is the URL). |
| + - `TestDBDownloadLinkRecreated` (Review Focus 2) and `TestDBDownloadLinkRemovedMember` (Review Focus 3): status and link → 404, presigner never called. |
| + - `TestDBDownloadLinkExpiredAndMissing` (past `expires_at` → 404, no presign; object gone → `expired`, 404). |
| + - `TestDBDownloadURLNeverStored`: capture `log` output, every activity row and every `db_downloads` column after a link: none contains the URL, `X-Amz-` or `Signature`. |
| + - `TestDBDownloadAudit` (one `db-download` per created job, one `db-download-link` per issuance, details verbatim from Task 0's record). |
| + - `TestNewS3DownloadObjectsPresign` (against `s3fake` or a signer stub: the URL's host is the public endpoint, it carries the disposition and an expiry equal to the ttl). |
| +- [ ] **Step 2:** `go test ./internal/console -run 'DBDownload|S3DownloadObjects|TestLinkedPolicyCoversEveryAppRoute|TestClaimConsoleRouteCensus|TestNoBucketAppPostsRefuse' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 10: The section on the instance page, and the docs |
| + |
| +**Files:** Modify `internal/console/instancepage.go` (`backupsSection.Download *downloadSection`; `instanceBackups` fills it), `internal/console/instancecopy.go` (the six approved strings and Task 0's), `internal/console/templates/app_instance.html`, `approved_member_backups_copy_test.go` (move the six `slice 1b` ids from `memberBackupsPendingIDs` to `memberBackupsCopyIDs`), `docs/superpowers/plans/member-backups-slice1-copy.json` (drop their `pending`), `approved_member_backups_1b_copy_test.go` (remove the skip), `docs/site/cli.md` (Task 0's paragraph); test `internal/console/instancepage_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 7-9. |
| +- Produces: |
| + - `type downloadSection struct { State string; Button, Note, Why string; Enabled, Poll bool; StartURL, LinkURL, StatusURL string }`. |
| + - `func downloadSectionFor(d *dbDownload /*nil: no job*/, avail downloadAvail, v backupsView, host string, now time.Time) *downloadSection` (pure). A failed job's reason line comes from its stored `downloadReason*` (`too_large` uses `backups.toolarge`). It gives nil for classes other than `replicated` and `not_shown`/`too_large_to_plan`, whose existing Why lines and commands stand. Too large gives `backups.toolarge` and no button. Not available gives its why and no button. None, failed and expired give "Download a copy" (failed adds its reason line). Queued or preparing give "Preparing your copy", disabled, with the note and `Poll`. Ready gives "Download {file} ({size})" (`humanBytes`) and "Ready until {time} tomorrow." (`expires_at` as `15:04 UTC`). |
| + - The template puts the action in `.sectionhead` beside the heading, as two forms with the CSRF field (start, link), never a link carrying a URL. An inline script polls `StatusURL` every 5 s while `Poll`, stops after 25 minutes, and reloads the page when the state leaves `queued`/`preparing`. Without script, a reload shows the state. |
| + |
| +- [ ] **Step 1: Failing tests:** `TestDownloadSectionFor` (table over every state and why, exact strings from the records); `TestInstancePageDownloadStates` (rendered page: one primary button in the section head; preparing disabled with the note and the poll script; ready shows file, size and time; refused shows the why, the CLI disclosure and no enabled button); `TestInstancePageBackupsNoForbiddenWords` extended to every download state ("backed up", "up to date", "current", "✓", "downloaded"); `TestApprovedMemberBackupsCopy`, `TestApprovedMemberBackups1bCopy`. |
| +- [ ] **Step 2:** `go test ./internal/console . -run 'DownloadSectionFor|InstancePageDownload|InstancePageBackups|ApprovedMemberBackups|TestConsoleStyleguideClassesExist' -count=1` → FAIL. |
| +- [ ] **Step 3:** Implement with styleguide classes only (`docs/console-styleguide.md`), as the UX pass mocked it; no left-border accents. |
| +- [ ] **Step 4:** PASS. Screenshot the section at 390 px and desktop against Task 0's mock and attach both to the task report. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 11: The MinIO witness, end to end |
| + |
| +**Files:** Create `internal/console/dbdownload_minio_test.go`; modify `.amadan/ci.d/30-minio-contract` (the fixture and the PASS-line guard). |
| + |
| +**Interfaces:** |
| +- Consumes: everything above, through production wiring: the real console handlers and `NewS3DownloadObjects`, a real `dbreads.Agent` with `lease.NewDownloadStore`, and `ServeWorker` reached through a test socket (labelled non-acceptance, as `TestDBForwardMinio` is). |
| + |
| +- [ ] **Step 1: The fixture.** In the dbf section: a versioned data bucket for the region, an `mc ilm rule add` on it for `downloads/` with the Task 1 values, a box user allowed `s3:PutObject` and `s3:GetObject` on `downloads/*` there, and the console user allowed `s3:GetLifecycleConfiguration` and `s3:GetObject` on it. Run `TestDBDownloadMinio` with `CARLOS_MINIO_TEST=1`, and fail the step unless `--- PASS: TestDBDownloadMinio (` appears. |
| +- [ ] **Step 2: The witness.** Replicate a database into the region's prefix. Then `VerifyDownloads` (with the endpoint check seamed, since CI's MinIO is plain HTTP on loopback; Task 8's unit test owns that check), POST start as a member, run the agent's `Pass`, poll status until `ready`, and POST link. GET the URL with a plain `http.Client`: the zip opens, `db.sqlite3` passes `PRAGMA integrity_check` and holds the replicated rows, and the manifest's SHA-256 matches. Then remove the rule and restart: `VerifyDownloads` refuses and start answers the off why. |
| +- [ ] **Step 3:** Push the branch and read `amadan ci status carlos/platform -branch <branch>`; the MinIO step must show the PASS line. |
| +- [ ] **Step 4:** Commit. |
| + |
| +### Task 12: Census and branch close |
| + |
| +- [ ] **Step 1: Root-read census.** `make census-card`; write `docs/superpowers/notes/census-claims-member-backups-1b.txt`, one claim per changed root-binary unit: the `dbreads` wire (export op, job ids, result, home scope), the worker's export, the agent's export and upload, `lease.NewDownloadStore`, the host's arming and capabilities, and the infra files (lifecycle rules, the lifecycle read grant). Run `make census-propose NAME=member-backups-1b CLAIMS=<file>`, brief Astra from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, record the verdict on #280, and commit the overlay, the chain line and the proposal. |
| +- [ ] **Step 2: Record-write census.** `go test ./internal/provision -run TestPlan9B8RecordWriteCensus -count=1`; for every new write site it names (the console's request and queue creates, the agent's result and upload), add an inventory in `internal/provision/db_downloads_census_test.go` following `db_region_forward_census_test.go`. |
| +- [ ] **Step 3:** Changed packages only, with `-run` for every test named in Tasks 1-11; `gofmt -l .` clean; push; `amadan ci status` green. |
| +- [ ] **Step 4:** Whole-branch review by Astra, three rounds at most, with Task 3 called out for a security read; Fable reads Task 3 again in the whole-branch review. |
| +- [ ] **Notes for Paul's roll (not done here):** apply Task 1 (both data-bucket modules, the region-host grant) on dev, then roll boxes before the console (an old box ignores export requests, and the console refuses without `db-export-1` evidence). Set `CONSOLE_DOWNLOADS=on` only after `VerifyDownloads` logs ready. Dev check: a download of a dev instance opens and matches `carlos db pull` at the same TXID; the object is gone within about two days; a second press during preparing lands on the same job. |
diff --git a/docs/superpowers/plans/2026-11-12-member-backups-slice2b.md b/docs/superpowers/plans/2026-11-12-member-backups-slice2b.md| new file mode 100644 |
| index 000000000..8967b4550 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-12-member-backups-slice2b.md |
| @@ -0,0 +1,220 @@ |
| +# Member backups, slice 2b: the console reads restore tests — 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:** The console reads every box's `control/verify/<ref>.json`, shows an instance's last accepted restore test in the Backups section's third tile, in the door's `last_test` and in `carlos instances backups`, and gives operators `/fleet/backups` (and its JSON) with the fleet's restore-test evidence per region. |
| + |
| +**Plan rev 1** (2026-11-12), not yet reviewed. Opus implements; Astra reviews each task (three rounds at most); whole-branch Astra review at the end. |
| + |
| +**Architecture:** One in-memory reader in the console (`verifyReader`) lists `control/verify/` at start, then re-reads a box's record only when its change-index scope `control/verify/<ref>` moves, through a `release.ReadGate` with a 6-hour maximum age, and relists every 6 hours. One acceptance rule decides whether a verdict may be shown for an instance: the verdict's identity equals the instance's current identity, its bracket opened after the instance's `copy_since`, and its box hasn't left the roster for 7 days. The door, the instance page, the CLI and the operator view all go through that rule. Nothing on boxes changes. |
| + |
| +**Tech Stack:** Go; `internal/console` (reader, acceptance, door, page, operator view, templates, copy), `cmd/console` (wiring), `internal/backupswords` and the root CLI (`instances_backups.go`) for the shared test line. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-11-member-backups-design.md` rev 6.1: §1 (`last_test`), §2 (tile 3), §3 (the reader, `copy_since`, acceptance, roster), §4, §8, §9, §12 (verdict validity, dev check). Also the 2a plan's "Notes for slice 2b" (`2026-11-11-member-backups-slice2a.md`, Task 9) and the 2a ledgers in `docs/superpowers/notes/sdd-ledgers/`. Discussion #898. |
| + |
| +## Decisions this plan takes (reviewer: challenge any) |
| + |
| +- **B-1 `copy_since` is derived from the record, not stamped.** Spec §3 says the console stamps it at restore, move landing and region change. Move closes are written by box-side provision transitions (`MoveClose`, `MoveRolledBackClose`, `MoveRevertClose`, `MoveGuardedAbortComplete`, `OfflineFinish`), so a console-only stamp can't see them, and a stored field would change root-binary code. Every case is already in the record: a completed move changes `Region` (moves refuse the same region), which changes the identity; every move close, done, rolled back or aborted, writes `LastMove.At`; a restore (#658) or recreate is a new record with a new `CreatedAt`, so a new incarnation. So `copySince(rec) = rec.LastMove.At` (zero when nil), and an instance with `rec.Move != nil` shows no verdict. Verdicts exist only from 2a on, and every move since then writes `LastMove`, so no backfill is needed. The spec's "test that fails when a new path appears" is Task 3's inventory of record-field writes. |
| +- **B-2 The JSON door is gated by `apiSystemRoller`** (ops-account owners and `CARLOS_SYSTEM_OPERATORS`), the gate of `GET /api/cli/system/status`. The spec names `apiSystemOperator`, which is the storage-scanning gate (`CARLOS_STORE_OPERATORS`) and refuses with a scanning message. |
| +- **B-3 Owners see passed or failed only.** `last_test` is the newest *decided* verdict the acceptance rule admits, from any box record or from the reader's memory of earlier reads. An `unverified` verdict never appears to owners; it is operator evidence. |
| +- **B-4 `last_test` gains `operators_alerted`** (true only for `failed` when the deployment would deliver `verify_failed`), so the CLI prints the page's "We've been alerted" line from the door alone. |
| +- **B-5 The roster** is `status/boxes/<ref>.json` (the same label as the verify ref, `metricsBoxLabel`), read by one `ListMod` per relist. A box's last-seen time is the later of that object's modified time and its record's `CheckedAt`; a record whose box was last seen over 7 days ago is dropped. Fleet boxes, whose status lives under `fleets/<name>/`, fall back to `CheckedAt` alone. |
| +- **B-6 Seeding (2a note F2-7)** is the reader's in-memory `seen` map: per host, the newest decided verdict it has read and the box it came from. It covers a group host reassigned to another box between the old box dropping it and the new box drilling it. It is re-checked by the acceptance rule on every use and is lost on restart (the new box drills a never-verified host first, so the gap is one night at most). The box-side coverage clock restarting on reassignment is not fixable from the console and stays as 2a left it. |
| +- **B-7 Not reached.** 2a's record has no "not reached" count. The operator view counts a host as not reached in its box's last run when its verdict is `unverified`/`not_reached`, or its `VerifiedAt` is more than 12 hours before the record's `CheckedAt` (a run's budget is 45 minutes by default; 12 hours is safe for any budget under that). |
| +- **B-8 §4's "drill is inert"** has no box-side signal (the box status carries no timer state for `carlos-hibernate-verify`). The operator view lists **boxes with sleeping instances** (`status.Box.Routes.Hibernating > 0`) **whose record is missing or older than 36 hours**, which includes every inert box. A true inert flag would need a box status field and the root census; not in 2b. |
| +- **B-9 §4's off-account row** shows "No record" for every region: `control/offsite.json` has no writer and no schema yet (durability §5.5). The exports row waits for 3b. |
| + |
| +## Global Constraints |
| + |
| +- The console only reads. No box, unit, provision transition or bucket record changes. No new per-box poll, no loop that lists replicas. |
| +- Request budget (spec §9): at start one LIST of `control/verify/` and one GET per record; then one conditional GET per moved scope; every relist (at most every 6 hours) one LIST of `control/verify/`, one `ListMod` of `status/boxes/` and up to N conditional GETs (N = known records). With no change index (`CARLOS_CHANGE_INDEX` unset) or a watch that cannot vouch, only the start read and the relists run: never a per-minute read. |
| +- `ReadGate` maximum age: exactly 6 hours. Relist period: 6 hours minus up to 10% jitter (never more than 6 hours). |
| +- Acceptance (one function, `acceptVerdict`, used by every surface): `Result` is `passed` or `failed`; `Identity` equals the instance's current identity on all five fields, none empty; `BracketOpenedAt` is non-zero and strictly after `copySince(rec)`; `rec.Move == nil`; for an instance in the console's own region, `Prefix == activator.HibernatePrefix(s.cfg.HibernatePrefix, host)`; the box was last seen within 7 days; `VerifiedAt` no more than 5 minutes ahead of now. Among accepted verdicts the newest `VerifiedAt` wins; on a tie, `failed` wins. |
| +- A record is ignored (logged once per etag) when it is over 4 MiB, does not parse, has `V != 2`, or its `Box` is not the ref in its key. |
| +- Only instances whose intrinsic class is replicated (`replicaIntrinsic`) get `last_test`; pooled and fleet-placed stay "not shown", as in slice 1. |
| +- Never "backed up", "up to date" or "current" in any shown string; ages and dates only, in UTC as the page's other times are. No ticks, no em dashes, no left-border accents. |
| +- Copy: only strings approved in Task 1, verbatim. The UX pass (Task 0) comes before the copy review. |
| +- Root census: Tasks 4 and 5 change root-binary sources (`internal/backupswords`, `instances_backups.go`). Everything else is console-only (`internal/console`, its templates, `cmd/console`). Overlay `member-backups-2b`, Task 8. |
| +- Local verification: changed packages only, with `-run`. CI runs the full suite. Go cache at its default. |
| +- Commit subjects under 80 characters, body after a blank line, ending `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. One amadan task per plan task on the build branch. |
| + |
| +## Review Focus |
| + |
| +1. **No records yet** (2a released but no night run, or a deployment with no sleeping hosts): every tile says the slice-1 "not shown yet", the door omits `last_test`, `/fleet/backups` counts every replicated instance as never tested and says the evidence is loaded, with no error. Tests in Tasks 4 and 6. |
| +2. **One bad record among good ones** (oversize, v1, unparseable, `Box` naming another ref): it is skipped and logged, every other box's verdicts still show, and the operator view names the box as unreadable. Test in Task 2. |
| +3. **Two boxes with verdicts for one host** (a double drill on group boxes, or a reassignment): the newest decided verdict shows; a later pass replaces an older fail; the operator view counts the host once. Test in Task 3. |
| +4. **A move back to the original region** (A to B to A): the verdict from before the first move has the same identity again and must stay hidden; the first verdict after the second move's close shows. Test in Task 3. |
| +5. **The change index unarmed or failing for a day**: the reader makes no per-minute requests and still sees a new verdict within 6 hours. Test in Task 2, counting store calls. |
| + |
| +## Not in this slice |
| + |
| +The exports row (3b); a box-side inert flag (B-8); the off-account record's reader (B-9); the 2a follow-up "bare number on the metrics page; all-snoozed message" (Fable T8, its own small change). |
| + |
| +--- |
| + |
| +### Task 0: UX pass in the mockup kit |
| + |
| +**Files:** scratch only (`d=$(mktemp -d)` under `$TMPDIR`), nothing committed. |
| + |
| +- [ ] **Step 1:** Copy `docs/console-mockup-kit/shell.html` (README there) and mock the instance page's Backups section with the third tile in each state: passed today; passed on an earlier date; failed with "We've been alerted"; failed without it; no accepted test (slice 1's "not shown yet"); and the sections where slice 1 hides the tiles (other region, too large, unavailable). Decide whether the test tile shows when the other two tiles don't; Task 4 implements what you decide. Draft wording from spec §8; the tile leads with the state (one or two words as the value), the date and time as the detail, the "using the copy up to" time only if it reads at a glance. |
| +- [ ] **Step 2:** Mock the `carlos instances backups` output for the same states, as terminal text. |
| +- [ ] **Step 3:** Mock `/fleet/backups` from the operator shell's components (`docs/console-styleguide.md`: `.pagehead`, stat tiles, tables, chips): per region, restore-test tiles (passed in the last 7 days, failed, never tested, oldest test's age, not reached last run), a short instances-by-class table with "not shown" reasons, the boxes not publishing tests (B-8) with their last record's age, the off-account row (B-9). States: a healthy region, a region with failures and a quiet box, a partial read (some records unreadable), evidence not loaded yet, no records at all. Failures and quiet boxes show as chips or tile tone, not sentences. |
| +- [ ] **Step 4:** Shoot each at 390 px and 1280 px, light and dark (README step 3). Run the `impeccable` skill's critique and distill passes on them; fix what reads badly, wraps or overflows. The bar: the state is the first thing seen, about a dozen words to understand the screen. |
| +- [ ] **Step 5:** Keep the final HTML for Task 1's preview. Record the layout decisions (which states, tile values, tones, what shows where) as a short list at the top of Task 1's copy JSON (`"layout"` field). |
| + |
| +### Task 1: Copy review |
| + |
| +**Files:** Create `docs/superpowers/plans/member-backups-slice2b-copy.json`; create `approved_member_backups_2b_copy_test.go` (repo root). |
| + |
| +- [ ] **Step 1:** Extract every new string from Task 0's mockups with IDs: `backups.test.passed`, `backups.test.failed`, `backups.test.when` (the date/time detail's pattern), `backups.test.copyupto` (if kept), `backups.test.alerted`, the CLI's test-row forms (`backups.cli.test.*`), and `fleetbackups.*` (rail label, page heading, region heading, every tile label and detail, table headings, class and reason labels, chips, the quiet-box heading and "never", the off-account label and "No record", the partial-read banner, the not-loaded line, the empty-state line). Reused slice 1 strings (`backups.test.label`, `backups.test.none`, the chips) keep their IDs and are not re-reviewed. |
| +- [ ] **Step 2:** Run the copy-review skill with Task 0's HTML as the preview; apply Paul's edits verbatim to the JSON. Delete the scratch directory afterwards. |
| +- [ ] **Step 3:** `TestApprovedMemberBackups2bCopy` via `checkApprovedCopy` (`approved_copy_test.go:71`) with the IDs pinned as a literal (as `approved_member_backups_2a_copy_test.go` does), `t.Skip` until Task 7 lands the last string. |
| +- [ ] **Step 4:** Commit. |
| + |
| +### Task 2: The reader |
| + |
| +**Files:** Create `internal/console/verifyreader.go`, `internal/console/verifyreader_test.go`; modify `internal/console/server.go` (a `verify *verifyReader` field), `cmd/console/main.go` (start it beside `RunRegionNames`, with `edgesWatch`). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const verifyScopePrefix = "control/verify/"`, `verifyReadMaxAge = 6 * time.Hour`, `verifyRecordMax = 4 << 20`, `verifyRosterGone = 7 * 24 * time.Hour`, `verifyTick = time.Minute`. |
| + - `type verifyBox struct { Ref string; Rec *dbverify.Record /*nil: unreadable*/; ETag string; ReadAt time.Time; LastSeen time.Time /*B-5*/; Err string }` |
| + - `type boxVerdict struct { Box string; LastSeen time.Time; V dbverify.Verdict }` |
| + - `func newVerifyReader(store release.Store, watch *release.ChangeWatch, now func() time.Time) *verifyReader` |
| + - `func (r *verifyReader) start(ctx context.Context) error`: LIST `control/verify/`, GET each `<ref>.json` whose ref passes `boxself.ValidRef`, `ListMod("status/boxes/")`; sets loaded only on a successful LIST. |
| + - `func (r *verifyReader) tick(ctx context.Context, now time.Time)`: if not loaded, `start`; if the watch is non-nil and `Usable()`, for every known ref and every `control/verify/<ref>` scope in `watch.Observed()` not yet known, `gate.Due(scope, now)` and, when due, one conditional read (`GetIfChanged` with the held ETag; plain `Get` when the store isn't a `ConditionalGetter`), then `gate.Mark(scope, gen, now, ok)`; when the relist is due, `relist`. |
| + - `func (r *verifyReader) relist(ctx context.Context, now time.Time)`: LIST, drop refs no longer listed, conditional-read every listed ref (marking the gate), refresh the roster, prune `seen` entries whose `VerifiedAt` is over 30 days old, draw the next relist time. |
| + - `func (r *verifyReader) Loaded() bool`, `func (r *verifyReader) For(host string) []boxVerdict` (every box's verdict for host plus the `seen` entry, B-6), `func (r *verifyReader) Boxes() []verifyBox` (a copy, for the operator view). |
| + - `func (s *Server) RunVerifyReader(ctx context.Context, watch *release.ChangeWatch)`: no-op when `s.cfg.Releases == nil` or `s.cfg.HostClaim`; else sets `s.verify`, then `tick` every `verifyTick` under `instanceStoreTimeout` until ctx ends. |
| +- The host index (`host -> []boxVerdict`) and `seen` are rebuilt under the reader's mutex on every record change; `For` takes a read lock and copies. |
| + |
| +- [ ] **Step 1: Failing tests** (a `release.NewDirStore(t.TempDir())` wrapped in a counting store; records written with `dbverify.Publish`; a fake clock): |
| + - `TestVerifyReaderStartReadsEveryRecord`: three boxes' records; after `start`, `For(host)` returns each box's verdict; exactly one LIST of `control/verify/`, three GETs, one `ListMod`. |
| + - `TestVerifyReaderRereadsOnlyMovedScope`: bump one box's scope; the next tick reads that record once (conditional) and no other. |
| + - `TestVerifyReaderMaxAgeRereadsLostBump`: overwrite a record without its index bump; within 6 hours of fake time it is re-read and the new verdict is seen (spec §12). |
| + - `TestVerifyReaderNoWatchNoPerMinuteReads` (Review Focus 5): nil watch, then a watch whose index read fails; 6 hours of one-minute ticks make zero reads between relists; the relist sees a changed record. |
| + - `TestVerifyReaderFindsNewBoxFromIndex`: a new box's first publish appears in `watch.Observed()`; it is read on the next tick, before any relist. |
| + - `TestVerifyReaderDropsDeletedAndGoneBoxes`: a record deleted from the bucket leaves at the relist; a box whose status object and record are both over 7 days old has no verdicts in `For`; a fleet box with no status object but a fresh `CheckedAt` keeps them. |
| + - `TestVerifyReaderSkipsBadRecords` (Review Focus 2): oversize, v1, unparseable, and `Box` mismatching the key: each skipped with `Err` set in `Boxes()`, the good records still served. |
| + - `TestVerifyReaderSeedsReassignedHost` (B-6): box A's record has a pass for H; A's next record drops H; `For(H)` still returns A's pass from `seen`; after B publishes a newer verdict, B's wins in Task 3's selection. |
| + - `TestVerifyReaderRelistNeverLaterThanSixHours`: 1,000 drawn relist periods all in (5h24m, 6h]. |
| +- [ ] **Step 2:** `go test ./internal/console -run 'VerifyReader'` → FAIL. |
| +- [ ] **Step 3:** Implement. Wire `go srv.RunVerifyReader(context.Background(), edgesWatch)` in `cmd/console/main.go` after `RunRegionNames`. |
| +- [ ] **Step 4:** `go test ./internal/console ./cmd/console -run 'VerifyReader'` → PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 3: Acceptance, `copy_since` and the path inventory |
| + |
| +**Files:** Create `internal/console/verifyaccept.go`, `internal/console/verifyaccept_test.go`, `internal/console/copysince_paths_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `boxVerdict`, `verifyReader.For` (Task 2). |
| +- Produces: |
| + - `func verifyIdentityOf(rec provision.Record) (dbverify.Identity, bool)`: `{rec.Account, rec.App, rec.Host, rec.Region, provision.Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)}`; false on an `Incarnation` error or any empty field. |
| + - `func copySince(rec provision.Record) time.Time` (B-1). |
| + - `func acceptVerdict(rec provision.Record, ownRegion, ownPrefix string, bv boxVerdict, now time.Time) bool` (the Global Constraints rule; `ownPrefix` is "" for another region's instance). |
| + - `func pickTest(rec provision.Record, ownRegion, ownPrefix string, cands []boxVerdict, now time.Time) (dbverify.Verdict, string /*box*/, bool)`: newest accepted, failed on a tie. |
| + - `func (s *Server) acceptedTest(rec provision.Record, now time.Time) (dbverify.Verdict, bool)`: `pickTest` over `s.verify.For(rec.Host)`; false when `s.verify` is nil or not loaded. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestVerifyIdentityMatchesBracket`: for a sleeping instance record in a `DirStore`, `verifyIdentityOf(rec)` equals `dbreads.CaptureIdentity(ctx, store, rec.Region, ...)`'s identity field for field. |
| + - `TestAcceptVerdictTable`: one row each, accepted or not: passed and failed accepted; unverified refused; another incarnation (recreate, same and other account); another region; empty identity; bracket equal to `LastMove.At` refused, one second after accepted; `rec.Move != nil` refused; own-region prefix mismatch refused, other-region prefix ignored; box last seen 7 days and one second ago refused; `VerifiedAt` 6 minutes ahead refused. |
| + - `TestCopySinceEveryMoveOutcome`: `LastMove` done, rolled_back and aborted each hide a verdict whose bracket opened before `At`. |
| + - `TestMoveThereAndBackHidesOldVerdict` (Review Focus 4). |
| + - `TestRestoreIsNewIdentity`: a record recreated through the create path's `CreatedAt = now` (#658) refuses the old incarnation's verdict. |
| + - `TestPickTestNewestWins` (Review Focus 3): fail at T1 and pass at T2 on two boxes shows the pass; a tie shows the fail; a seen-only verdict loses to a newer record verdict. |
| + - `TestCopySincePathInventory` (spec §3, "a test that fails when a new one appears"): with `golang.org/x/tools/go/packages` (as `recordcreators_guard_test.go` does), load the module's non-test packages and find every assignment, tuple assignments included, whose left side is a field `LastMove`, `Region`, `CreatedAt`, `Account`, `App` or `Host` of a `provision.Record` value or pointer. Pin `map[field]map[enclosing func]count`, each entry with a comment saying why it needs no new `copy_since` source (it is a move close writing `LastMove`, a move flip of `Region`, a create, or not a copy change). A new site fails with its position and asks the author to classify it and extend `copySince` if it starts a new copy. |
| +- [ ] **Step 2:** `go test ./internal/console -run 'VerifyIdentity|AcceptVerdict|CopySince|MoveThereAndBack|RestoreIsNewIdentity|PickTest'` → FAIL. |
| +- [ ] **Step 3:** Implement. Build the inventory by running the test once and classifying every site it prints; none may be pinned unclassified. |
| +- [ ] **Step 4:** Same command → PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 4: `last_test` in the door, the shared words and the tile (root: `internal/backupswords`) |
| + |
| +**Files:** Modify `internal/backupswords/words.go`, `display.go`, `display_test.go`; `internal/console/backups.go` (`backupsView.LastTest`), `apibackups_test.go`, `instancepage.go` (`backupsSection` test fields), `instancecopy.go`, `templates/app_instance.html`, `instancepage_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `acceptedTest` (Task 3); Task 1's strings. |
| +- Produces: |
| + - `type backupsTest struct { Result string; At time.Time; CopyWrittenAt *time.Time; OperatorsAlerted bool }`, JSON keys `result`, `at`, `copy_written_at` (omitempty), `operators_alerted` (omitempty); `backupsView.LastTest *backupsTest`, key `last_test` (omitempty). `At` is `VerifiedAt`, `CopyWrittenAt` is `WrittenAt` when non-zero. |
| + - `backupsFor` fills `LastTest` after the memo load, never inside it (the memo keeps only the position), for every record `replicaIntrinsic` calls replicated, in any region. |
| + - `func (s *Server) verifyAlertsReach() bool`: the `verify_failed` rule's effective setting in `alertScopeFleet` is enabled and `alertRuleConnectors` leaves at least one connector that is also not suspended, not needing re-entry and not unsubscribed; cached for one minute. |
| + - `backupswords.Input.Test *TestInput` with `type TestInput struct { Result string; At time.Time; CopyWrittenAt *time.Time; Alerted bool }`; `Display` gains `TestValue, TestDetail, TestNote string; TestGap bool` (TestGap: failed, warning tone). No test: `TestValue` is the unknown dash and `TestDetail` is `TestNone`, as today. Whether the tile shows without the other two is Task 0's decision, carried as a `Display` field Show sets. |
| + - Constants for Task 1's `backups.test.*` strings in `words.go`. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestShowRestoreTest` (backupswords): passed today, passed on an earlier date and an earlier year, failed with and without `Alerted`, no test; values, details, note and tone per Task 1; the forbidden-words loop of `TestShowEveryClassAndReason` extended to every new field. |
| + - `TestAPIInstanceBackupsLastTest` (console, through the real router and gate, spec §12): a published passing record gives `last_test` with `result`, `at`, `copy_written_at`; a failing one adds `operators_alerted` only with a reachable connector; no record or an unaccepted verdict omits the key; pooled and fleet records never carry it. |
| + - `TestBackupsLastTestNotMemoised`: a door call, then a new record read by the reader, then a second call within 5 minutes: the second shows the new test. |
| + - `TestInstancePageBackupsRestoreTest`: the rendered section shows each state; Review Focus 1's no-records case shows the slice-1 "not shown yet"; the section contains no forbidden word. |
| +- [ ] **Step 2:** `go test ./internal/backupswords ./internal/console -run 'ShowRestoreTest|ShowEvery|APIInstanceBackups|BackupsLastTest|InstancePageBackups'` → FAIL. |
| +- [ ] **Step 3:** Implement. Styleguide classes only; the failed tone is the existing warning chip or tile class Task 0 chose. |
| +- [ ] **Step 4:** Same command plus `TestConsoleStyleguideClassesExist` → PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 5: The test row in `carlos instances backups` (root) |
| + |
| +**Files:** Modify `instances_backups.go`, `instances_backups_test.go`; CLI goldens if `TestCLIGolden` covers this output. |
| + |
| +**Interfaces:** |
| +- Consumes: `backupsTest`'s JSON (Task 4), `backupswords.TestInput`/`Display` (Task 4). |
| +- Produces: `backupsJSON.LastTest *struct{ Result string; At time.Time; CopyWrittenAt *time.Time; OperatorsAlerted bool }` (JSON tags as the door's); `printBackups` passes it as `Input.Test` and prints the test row from `TestValue`/`TestDetail`, and `TestNote` under the rows when set. |
| + |
| +- [ ] **Step 1: Failing tests:** extend `TestInstancesBackupsPrintsLines` with passed, failed-and-alerted and absent `last_test`; `TestInstancesBackupsJSON` unchanged (body verbatim). |
| +- [ ] **Step 2:** `go test . -run 'TestInstancesBackups|TestCLIGolden'` → FAIL. |
| +- [ ] **Step 3:** Implement; re-record goldens only for this command's output. |
| +- [ ] **Step 4:** Same command → PASS. Cross-compile: `GOOS=darwin go build .` and `GOOS=windows go build .`. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 6: The operator view's data |
| + |
| +**Files:** Create `internal/console/fleetbackups.go`, `internal/console/fleetbackups_test.go`. |
| + |
| +**Interfaces:** |
| +- Consumes: `replicaIntrinsic` (slice 1), `acceptVerdict`/`pickTest` (Task 3), `verifyReader.Boxes`/`Loaded` (Task 2), `s.recordWalkStore` + `provision.ListAllRecordsTolerant`, `status.LoadBoxesComplete`, `regionlabel.ForCode`. |
| +- Produces: |
| + - `type fleetBackupsView struct { GeneratedAt time.Time; Loaded, Complete bool; Regions []fleetBackupsRegion }` |
| + - `type fleetBackupsRegion struct { Region, Label string; Classes fleetBackupsClasses; Tests fleetBackupsTests; QuietBoxes []fleetBackupsBox; UnreadableBoxes []string; Offsite string /*"no_record", B-9*/ }` |
| + - `type fleetBackupsClasses struct { Replicated int; NoCopy, NotShown map[string]int /*reason -> count*/ }` |
| + - `type fleetBackupsTests struct { PassedWeek, Failed, NeverTested, NotReached int; OldestAt *time.Time }`, over replicated instances only; `Failed` and `PassedWeek` from each host's picked test; `NeverTested` is no picked test; `OldestAt` the oldest picked test's `VerifiedAt`; `NotReached` per B-7 over each box's record, counted once per host. |
| + - `type fleetBackupsBox struct { Box, Name string; LastRecord *time.Time }`: B-8. |
| + - `func (s *Server) fleetBackups(ctx context.Context, now time.Time) (fleetBackupsView, error)`, memoised 5 minutes (one build in flight; the `backupsMemo` shape). |
| +- JSON keys are the field names in snake case (`generated_at`, `passed_week`, `oldest_at` omitempty, `quiet_boxes`, `last_record`), since the system door serves this struct as is. |
| +- Regions: an instance's `rec.Region`, a box's `status.Box.Region`, a verdict's `Identity.Region`; labels through `regionlabel.ForCode(code, s.regionHome(), s.regionNames())`. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestFleetBackupsCountsPerRegion`: two regions; records of every class and reason; verdicts passed (3 days old), passed (9 days old), failed, unverified, and none; expect the counts, `OldestAt`, and a not-reached host per B-7 (including a `not_reached` verdict and one whose `VerifiedAt` is 13 hours before `CheckedAt`). |
| + - `TestFleetBackupsQuietBoxes`: four boxes: sleeping instances and a 37-hour-old record; sleeping instances and no record; sleeping instances and a fresh record; no sleeping instances and no record. Only the first two are listed, with `LastRecord` set for the first and nil for the second. |
| + - `TestFleetBackupsNoRecordsYet` (Review Focus 1): reader loaded, no records: every replicated instance is never tested; `Loaded` true. |
| + - `TestFleetBackupsNotLoaded`: reader not loaded: `Loaded` false and no test counts. |
| + - `TestFleetBackupsPartial`: an unreadable record, a failed status read or an incomplete record walk sets `Complete` false and names the unreadable box. |
| + - `TestFleetBackupsMemoised`: two calls within 5 minutes walk records once. |
| +- [ ] **Step 2:** `go test ./internal/console -run 'FleetBackups'` → FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 7: `/fleet/backups` and `GET /api/cli/system/backups` |
| + |
| +**Files:** Create `internal/console/templates/fleet_backups.html`, `internal/console/fleetbackups_page.go`, `internal/console/fleetbackups_page_test.go`; modify `internal/console/routedecls.go`, `internal/console/opshell.go` (`opRail` gains `{Key: "backups", Href: "/fleet/backups", Label: <Task 1's rail label>}`), `parity/parity.tsv` (row `op-backups`, status `operator`, console `GET /fleet/backups`), then `make parity-doc`; remove Task 1's skip. |
| + |
| +**Interfaces:** |
| +- Consumes: `fleetBackups` (Task 6). |
| +- Produces: `func (s *Server) handleFleetBackups(w, r)` behind `operatorOnly`, rendered with `s.opPage(addr, raw, "backups")`; `func (s *Server) handleAPISystemBackups(w, r)` behind `apiSystemRoller` (B-2), declared `{Pattern: "GET /api/cli/system/backups", Kind: kindCLI, Allow: svcrole.Set{}}`, writing `fleetBackupsView` as JSON. |
| + |
| +- [ ] **Step 1: Failing tests:** |
| + - `TestFleetBackupsPageOperatorOnly`: a member gets what `operatorOnly` gives every non-operator; an operator gets 200. |
| + - `TestFleetBackupsPageStates`: healthy, failures with a quiet box, partial, not loaded, no records: each shows Task 0's layout and Task 1's strings; the page's `<main>` content contains no forbidden word (scan only inside `<main>`: the shell has `aria-current`). |
| + - `TestAPISystemBackupsGate`: a system operator and an ops owner get the JSON; a member, a service credential and an anonymous caller get 404. |
| + - `TestAPISystemBackupsMatchesPage`: the JSON is the view the page rendered. |
| +- [ ] **Step 2:** `go test ./internal/console ./internal/parity . -run 'FleetBackupsPage|APISystemBackups|RouteDecls|EveryCLIDoor|ParityCLIPaths|CLIProjection|ApprovedMemberBackups2b'` → FAIL. |
| +- [ ] **Step 3:** Implement. Add the door to any other route table those tests name. |
| +- [ ] **Step 4:** Same command plus `TestConsoleStyleguideClassesExist` → PASS. |
| +- [ ] **Step 5:** Commit. |
| + |
| +### Task 8: Census, branch close, release and dev check |
| + |
| +- [ ] **Step 1:** Root census: `make census-card`; write `docs/superpowers/notes/census-claims-member-backups-2b.txt` (the `backupswords` display and words units, the CLI's `printBackups`/`backupsJSON`; no new reads); `make census-propose NAME=member-backups-2b CLAIMS=<file>`; post on #280; wait for the other-family reviewer's approval; commit the overlay, chain line and card. The record-write census is untouched (the console writes no record); confirm `go test ./internal/provision -run TestPlan9B8RecordWriteCensus` still passes. |
| +- [ ] **Step 2:** Changed packages only: `go test ./internal/backupswords ./internal/console ./internal/parity ./cmd/console . -run 'VerifyReader|VerifyIdentity|AcceptVerdict|CopySince|MoveThereAndBack|RestoreIsNewIdentity|PickTest|ShowRestoreTest|ShowEvery|APIInstanceBackups|BackupsLastTest|InstancePageBackups|InstancesBackups|CLIGolden|FleetBackups|APISystemBackups|RouteDecls|EveryCLIDoor|ParityCLIPaths|CLIProjection|ApprovedMemberBackups|StyleguideClasses|Plan14'`. Push; `amadan ci status -branch <name>` green. |
| +- [ ] **Step 3:** Whole-branch Astra review (three rounds at most). |
| +- [ ] **Step 4:** Release and roll, dev first, after 2a's release (2b reads what 2a writes). Dev check (spec §12): after one night, a dev instance on a box with sleeping hosts shows its restore test on the page, in the door and in the CLI, with the same time; `/fleet/backups` counts match the boxes' records; move a dev instance to another region and back: its tile shows "not shown yet" until the next night's test. Report on #898; ask Paul before the flagship roll. |