carlos / platform Public

member backups: 1b plan rev 2 after Astra + Fable round 1 (#898)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 79bac85c9a2ce6673347739a51d1082d08be5df5 parent 2c50af7
1 file changed, +93 −58
  • docs/superpowers/plans/2026-11-12-member-backups-slice1b.md +93 −58

Intent

Human

<task-notification> <task-id>bg3kuqqg1</task-id> <tool-use-id>toolu_01MzyX4qPx5KPsvVtaaK65EE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/bg3kuqqg1.output</output-file> <status>completed</status> <summary>Background command "Astra code + census reviews, then wait for CI" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>ad34c2ecab73f571d</task-id> <tool-use-id>toolu_01VGfqrLJKwmBQRyTv4G3w54</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/ad34c2ecab73f571d.output</output-file> <status>completed</status> <summary>Agent "Write slice 1b plan (download)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The plan is now rev 2, uncommitted, with 13 tasks (Task 0 to Task 12). I declined no findings. One finding is fixed differently from Fable's suggestion. Fable P2-3 asked for the audit row in the same transaction as the job. Activity writes go through `withAutoAppSQL` (`store.go:3314`), so instead the audit row is written after the job row and before anything is published. If that write fails, the job fails and nothing is published, which gives the same guarantee. **Your "0 requests when idle" budget has a condition.** It holds only while the deployment's serial doesn't move. Every serial move, from any deployment change, costs 2 LISTs per home box. To get there, the home agent's nudge is sent only when the serial moves, not from the backstop or instances-floor passes. **Pickup window:** a bump reaches a home agent in about 8 s (2 s serial poll plus the 5 s full-pass clamp). That is well inside the 60 s pickup window, so the window is unchanged and no polling was added.</result> <usage><subagent_tokens>371805</subagent_tokens><tool_uses>14</tool_uses><duration_ms>247850</duration_ms></usage> </task-notification>

diff --git a/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md b/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md
index 03f7e4d7a..f81d394df 100644
--- a/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md
+++ b/docs/superpowers/plans/2026-11-12-member-backups-slice1b.md
@@ -4,7 +4,7 @@
**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.
+**Plan rev 2** (2026-11-12): plan review round 1 applied (Astra `docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-plan-1b.md`, NOT READY, 5 P1 + 2 P2; Fable `FABLE-FINDINGS-plan-1b.md`, READY AFTER FIXES, 1 P1 + 4 P2 + 4 P3), with the controller's rulings on Fable P1, Fable P2-4/Astra P1-3 and Fable P3-6; dispositions at the end. Rev 1.1: Paul's rulings on D-H and D-E applied (header); the email task removed and the tasks renumbered.
**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.
@@ -14,7 +14,7 @@
## 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-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:52`), and `dbReadsSettings` won't start on a box without a region (`internal/host/dbreads.go:56`). 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. Only home boxes take exports: regional boxes get no export capability until a regional console exists (controller ruling on Fable P3-6). 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):
@@ -25,14 +25,15 @@ Decisions this plan takes (reviewers may overturn them):
## 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.
+- 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 with no retained versions, delete markers go, and incomplete multipart uploads after 1 day, on every store (no provider waiver). Downloads stay off on a deployment whose `CARLOS_HIBERNATE_PREFIX` is empty or starts with the segment `downloads`, because the rule would then reach replicas.
+- 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 only when its binding (account, app, host, incarnation, region) is the instance's current one; an obsolete open job is retired in the same transaction. 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 (`queued`, `preparing` and unexpired `ready` all count); 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.
+- 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, with no redirect, picker or refusal page: no session, an ambiguous account segment, a non-member, a linked-app refusal, another app, a bad or unknown host, and a binding mismatch all get `http.NotFound`.
+- 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 a box whose published data bucket is the console's) 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".
+- Audit actions: `db-download` (start, written before anything is published; a start whose row can't be written publishes nothing), `db-download-link` (issuance). Never "downloaded".
+- Request budget on boxes: an export-only home agent never lists the queue on a timer. It lists only when the fast converge loop sees the serial move (2 LISTs per home box per serial move, and none from the backstop or instances-floor passes), so an idle deployment costs 0 requests per home box per day. A request that no box sees in time ends `not_picked`, and the person presses again.
- 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.
@@ -41,7 +42,7 @@ Decisions this plan takes (reviewers may overturn them):
## 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.
+2. **An instance deleted and recreated under the same name while its copy is ready (or preparing)**: status and link answer the 404 and no URL is signed; the page shows no old job; a new start retires the old job and admits a fresh one. Tests in Task 7 (store) and Task 9 (doors and page).
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.
@@ -54,7 +55,7 @@ Decisions this plan takes (reviewers may overturn them):
- [ ] **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 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 with all four values and no retained versions, MinIO's `mc ilm import` of the same rule, that the console reads the rule back only when it starts, so a rule changed later needs a console restart to be checked again, that a `CARLOS_HIBERNATE_PREFIX` that is empty or starts with `downloads` keeps downloads off, and that physical deletion takes two to four days).
- [ ] **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.
@@ -102,27 +103,38 @@ Decisions this plan takes (reviewers may overturn them):
- [ ] **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)
+### Task 3: An export-only home scope, the box's guard and its capabilities (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.
+**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. Everything that decides which box takes which op is here (the scope, the box's pre-election guard, nudge-only listing and capability publication), so the review sees the whole boundary (Astra P1-3, Fable P2-4).
-**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`.
+**Files:** Modify `internal/dbreads/ids.go`, `envelope.go`, `agent.go` (`AgentConfig`, `probe`, `consider`, `Run`, `Pass`); `internal/host/dbreads.go` (`dbReadsSettings`, `dbReadsSocketWanted`, `armDBReads`, the capability helper, a new nudge), `internal/host/agent.go` (the fast converge loop's serial-move branch, `:3280`), `internal/host/edgesfile.go:1381`; tests in `internal/dbreads/ids_test.go`, `envelope_test.go`, `homescope_test.go` (new), `internal/host/dbreads_test.go`.
**Interfaces:**
+- Consumes: Task 2's `OpExport`, `ExportCapability`, `HelloReply.Ops`.
- 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.
+ - `type DownloadStore interface { Upload(ctx context.Context, key string, body io.Reader) error; Size(ctx context.Context, key string) (int64, error) }` (the concrete store is Task 6's).
+ - `AgentConfig` gains `ExportOnly bool` and `Downloads DownloadStore`. `NewAgent` refuses (returns an error, logged by `armDBReads`) `ExportOnly` with a non-empty `Region`, and a non-nil `Downloads` without `ExportOnly` (regional boxes take no exports, Fable P3-6).
+ - `probe` keeps the passing hello's `Ops`. `func (a *Agent) ExportCapable() bool`: `Capable()`, `ExportOnly`, a non-nil `Downloads`, and the last passing probe's `Ops` holds `OpExport`.
+ - `consider`, after `Verify` and before admission and the election, decides and logs without writing anything: any op but export on an `ExportOnly` agent, and an export on an agent that isn't `ExportCapable`.
+ - `Run` on an `ExportOnly` agent has no `ListEvery` ticker: it runs `Pass` only on its nudge channel (the probe stays on its timer; it is a local socket). A regional agent's `Run` is unchanged.
+ - `dbReadsEnv` gains `exportOnly bool`. `dbReadsSettings`: an empty `CARLOS_REGION` starts with `region ""`, `exportOnly: true`; a non-empty invalid one (a fleet placement included) is refused as today. `dbReadsSocketWanted` follows it, unchanged otherwise. `armDBReads` sets `ExportOnly` and, on an export-only box, passes `dbExportNudge` instead of `dbReadsNudge`.
+ - `var dbExportNudge = make(chan struct{}, 1)` and `func nudgeDBExports()`, sent only from the fast converge loop's serial-move branch (`agent.go:3280`), before `d.runFull`, never from the backstop, scoped or instances-floor passes (`nudgeDBReads` at `changeindex.go:444` is unchanged and still feeds regional agents).
+ - `func withDBReadCapabilities(caps []string, read, export bool) []string` replaces `withDBReadCapability`; the edges loop passes `read = Capable() && !ExportOnly` and `export = ExportCapable()`. A home box never publishes `db-read-1`; a regional box never publishes `db-export-1`.
+ - Latency: the serial poll runs every 2 s plus jitter (`agent.go:3721`) and the move branch is clamped by `fastFullClamp` (5 s, `agent.go:2727`), so a bump reaches a home agent within about 8 s. That is well inside `PickupWindow` (60 s) plus `Skew`, so the window is unchanged.
- [ ] **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.
+ - `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 a test-only config that bypasses `NewAgent`'s refusal) 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 and its `Run` still lists every `ListEvery`; `dbReadsSettings` and `dbReadsSocketWanted` answer exactly as before for every non-empty `CARLOS_REGION` in `dbreads_test.go`'s table; a regional agent publishes `db-read-1` as before and never `db-export-1`, and refuses an export request before the election; `forwardable` still refuses a home record.
+ - `TestHomeAgentIdleBudget` (Fable P1): a counting store under an `ExportOnly` agent's `Run` over a fake clock of 24 hours with no nudge sees 0 store calls; one nudge gives exactly the two hour-prefix LISTs; a backstop or instances-floor pass sends no `dbExportNudge`, and a serial move sends exactly one.
+ - `TestNewAgentRefusesMixedExportConfig`, `TestExportCapableNeedsAll` (each of the four conditions alone false → false).
+ - `TestWithDBReadCapabilities` (all four combinations).
- `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 2:** `go test ./internal/dbreads ./internal/host ./internal/console -run 'HomeScope|NonHomeUnchanged|HomeAgentIdle|NewAgentRefusesMixed|ExportCapableNeedsAll|WithDBReadCapabilities|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 4:** PASS, plus `go test ./internal/dbreads -run 'Loop|Agent|Read|Pull' -count=1` and `go test ./internal/host -run 'FastConverge|ChangeIndex' -count=1` unchanged; `GOOS=darwin go build . && GOOS=windows go build .`.
- [ ] **Step 5:** Commit; then the Astra and Fable task reviews (three rounds at most).
### Task 4: The worker's `export` operation
@@ -141,45 +153,40 @@ Decisions this plan takes (reviewers may overturn them):
### 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`.
+**Files:** Create `internal/dbreads/export.go`; modify `internal/dbreads/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`.
+- Consumes: Tasks 2, 3 and 4 (`DownloadStore`, `AgentConfig.Downloads`, `ExportCapable`); `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`):
+- [ ] **Step 1: Failing tests** (fixture `newFixture` with a home region `""` and an `ExportOnly` agent, `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
+### Task 6: The box's upload store
-**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`.
+**Files:** Create `internal/lease/downloads.go` + test; modify `internal/host/dbreads.go` (`armDBReads`), `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`.
+- Consumes: Task 3's `DownloadStore`, `ExportOnly` and arming.
- 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()`.
+ - `func downloadsPrefixSafe(hibernatePrefix string) bool`: false when the prefix is empty or its first path segment is `downloads` (Fable P2-5: replicas live at `<prefix>/<host>/`, `activator.go:166`, and a bare label is a valid host).
+ - `armDBReads` builds `Downloads` from `hib.Bucket`/`hib.Region` only on an export-only box whose prefix is safe; otherwise nil, with the reason logged.
-- [ ] **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 1: Failing tests:** `TestDownloadStoreRefusesOtherKeys`; `TestDownloadsPrefixAgrees` (in `internal/host`: the literal equals `dbreads.DownloadsPrefix`); `TestDownloadsPrefixSafe` (`instances` safe; `""`, `downloads`, `downloads/x` unsafe; `downloadsx` safe); `TestArmDBReadsWiresDownloads` (an export-only box with a safe prefix gets a store; a regional box and an unsafe prefix get nil).
+- [ ] **Step 2:** `go test ./internal/lease ./internal/host -run 'DownloadStore|DownloadsPrefix|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.
@@ -194,12 +201,12 @@ Decisions this plan takes (reviewers may overturn them):
- `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) StartDBDownload(ctx context.Context, d dbDownload, now time.Time) (got dbDownload, created bool, retired *dbDownload, err error)`: one transaction. It deletes rows created more than `downloadKeep` ago and moves every `ready` row of the account past `expires_at` to `expired`. An open row for the instance whose incarnation or region differs from `d`'s is retired (`ready` → `expired`; `queued` or `preparing` → `failed`/`changed`) and returned as `retired` so the caller writes its cancel (Astra P2-6, Fable P2-2). An open row with `d`'s binding is returned (`created == false`). Otherwise it counts the account's `queued`, `preparing` and unexpired `ready` rows (`errDownloadsBusy` at 2; Astra P2-7) 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 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); `TestStartDBDownloadRetiresObsolete` (Review Focus 2: an open row of another incarnation, and one of another region, is retired and returned, and a fresh job is admitted); `TestStartDBDownloadAccountCap` (with two unexpired ready jobs on two instances, a third instance is refused; once one expires it is admitted); `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.
@@ -212,47 +219,51 @@ Decisions this plan takes (reviewers may overturn them):
**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 lifecycleRule struct { Enabled bool; Prefix string; Narrowed bool /*tag or size filter*/; ExpireDays, NoncurrentDays, AbortDays int32 /*0: absent*/; NewerNoncurrent int32 /*NewerNoncurrentVersions; 0: absent*/; ExpireDate bool /*expiry by date, not days*/; 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 lifecycleCoversDownloads(rules []lifecycleRule) error`. Each requirement is met by some enabled, un-narrowed rule whose prefix is a prefix of `downloads/`: expiry present with `1 ≤ days ≤ 1`; noncurrent expiry present with `1 ≤ days ≤ 1` and `NewerNoncurrent == 0`; delete markers; abort present with `1 ≤ days ≤ 1`. And no enabled rule covering `downloads/` retains noncurrent versions (`NewerNoncurrent > 0`), since S3 keeps that many versions whatever the days say (Astra P1-1). No store gets a waiver.
- `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 `""`).
+ - `func (s *Server) VerifyDownloads(ctx context.Context) error`: with `cfg.Downloads`, runs both checks and `downloadsPrefixSafe(cfg.HibernatePrefix)` (the same rule as Task 6, duplicated as a console function with a test pinning the two to the same table), and sets `downloadsReady`; logs why and leaves it false otherwise. It runs at console start only.
+ - `func capabilityEvidence(snap edgesSnapshot, err error, region, capability, dataBucket string) string` (`dbForwardNone`, `dbForwardDead` or `""`); with a non-empty `dataBucket`, a file counts only when its published `DataBucket` equals it (Fable P3-8). `dbForwardEvidence` passes `""`; downloads pass `cfg.HibernateBucket`.
- 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) 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). Then it reconciles every open job of the account (`OpenDBDownloadsFor`, `reconcileDBDownload`, unthrottled here), so deadlines and expiry that passed while nobody was watching free the cap (Astra P1-2). Then job id `dbreads.MintJobID`, attempt `dbreads.MintID`, incarnation `provision.Incarnation`, `object_key = dbreads.DownloadKey(id)`; `StartDBDownload` (busy and daily map to `downloadWhyBusy`, `downloadWhyDaily`; a `retired` job gets `cancelDBRead(retired.Attempt)`). Only when created: the `db-download` activity row (`RecordActivityContext`, Task 0's detail); if it fails, `MoveDBDownload(queued→failed, downloadReasonGeneric)` and nothing is published (Fable P2-3); otherwise `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: it is the only thing that wakes a home box, so a lost bump ends the job `not_picked` at the pickup deadline and the person presses again). 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`).
+ - `TestLifecycleCoversDownloads` (table: the Task 1 rules pass; each value at 2 days fails; each value absent fails; a 1-day noncurrent rule with `NewerNoncurrentVersions: 1` fails, and so does an extra covering rule that retains versions; a date-based expiry fails; a disabled rule, a tag-narrowed rule and a `downloads/x/` prefix don't count; a whole-bucket rule counts; a compatible store without abort fails).
+ - `TestVerifyDownloadsThroughAdapter` (Astra P1-1: `NewS3DownloadObjects` over `s3fake` or a stubbed lifecycle response with retained versions, with absent expiry fields, and on a compatible endpoint without multipart cleanup: `VerifyDownloads` refuses each; an unsafe hibernate prefix refuses).
- `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).
+ - `TestStartDBDownloadSurvivesDisconnect` (the caller's context cancelled right after the record is written: the request and queue entry are still published).
+ - `TestStartDBDownloadAuditFirst` (an activity store that fails: the job is `failed`, no request or queue object exists).
+ - `TestStartDBDownloadFreesAbandonedJobs` (Astra P1-2: start two jobs on two instances, never poll them, advance the clock past their pickup deadline; a start for a third instance is admitted without a restart, and both old jobs are `failed`/`not_picked`).
+ - `TestCapabilityEvidenceDataBucket` (a placement-`""` box publishing `db-export-1` for another data bucket doesn't count).
- `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 2:** `go test ./internal/console -run 'LifecycleCovers|DownloadsEndpoint|DownloadsUnavailable|CapabilityEvidence|DBForwardEvidence|StartDBDownload|ReconcileDBDownload|ReconcileClamps|ReconcileConcurrent|SweepAfterRestart|FreesAbandoned|AuditFirst|VerifyDownloadsThroughAdapter|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).
+**Files:** Create `internal/console/browserdownloads.go` + `browserdownloads_test.go`, `internal/console/downloads_s3.go` + test; modify `internal/console/routedecls.go` (three routes), `parity/parity.tsv` (a row covering the three console members) and then `parity/cli.tsv` via `make parity-doc` (Astra P1-4), `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.
+ - `func (s *Server) downloadGate(w http.ResponseWriter, r *http.Request, csrf bool) (downloadCtx, bool)`, where `downloadCtx` holds `acct, app, host, actor, rec`. It does not use `s.account` (which redirects without a session and renders a picker for an ambiguous segment, `server.go:3077-3107`) or `refuseLinkedPage` (which renders a 409 page, `linkedpolicy.go:302`) (Astra P1-5, Fable P3-7). In order: `s.session` (none → `http.NotFound`), `s.store.AccountsFor` + `matchAccounts` with exactly one match (else `http.NotFound`), CSRF when asked (a mismatch → `http.NotFound`), `HasAppIn`, `s.linkedAppRefusal(...) != nil` → `http.NotFound`, `provision.ValidHostShape`, then the record read fresh. Every refusal is the byte-identical `http.NotFound` with no `Location`.
+ - `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. The status and link doors and the instance page (Task 10) all read the job through it, so an obsolete job is never shown.
+ - Start: `startDBDownload` (which writes the `db-download` row before publishing); 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`.
@@ -260,21 +271,22 @@ Decisions this plan takes (reviewers may overturn them):
- [ ] **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).
+ - `TestDBDownloadGateUniform` (Astra P1-5: for each of the three doors, no session, a service token, an ambiguous account segment, another account's member, a linked-app refusal, a missing or wrong CSRF on the POSTs, a bad host and an unknown host all give the same status, the same body bytes and no `Location` header).
+ - `TestDBDownloadStartRefusals` (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.
+ - `TestDBDownloadRecreated` (Review Focus 2: with a ready and with a preparing job, recreate the instance; status and link → 404, presigner never called; the instance page shows no old job; a start retires the old job, writes its cancel and admits a fresh one) 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).
+ - `TestDBDownloadAudit` (one `db-download` per created job, written before the request object exists; 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 2:** `make parity-doc`; `go test ./internal/console ./internal/parity . -run 'DBDownload|S3DownloadObjects|TestLinkedPolicyCoversEveryAppRoute|TestClaimConsoleRouteCensus|TestNoBucketAppPostsRefuse|TestParityTableCoversConsoleRoutes|TestParityCLIPaths|TestCLIProjection' -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`.
+**Files:** Modify `internal/console/instancepage.go` (`backupsSection.Download *downloadSection`; `instanceBackups` fills it, reading the job through Task 9's `downloadJob`), `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.
@@ -296,15 +308,38 @@ Decisions this plan takes (reviewers may overturn them):
**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 1: The fixture.** In the dbf section: a versioned data bucket for the region, an `mc ilm import` on it of the AWS-shaped `downloads/` rules with the Task 1 values (abort included); if MinIO refuses the abort element or drops it on read-back, stop and bring it to the controller rather than waive it in code, 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 home agent's (`ExportOnly`, region `""`) `Pass` once, as its nudge would, 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 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, nudge 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.
+- [ ] **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 two to four days; a second press during preparing lands on the same job.
+
+---
+
+## Plan review round 1: dispositions
+
+| Finding | Reviewer | Disposition | How |
+|---|---|---|---|
+| P1-1 lifecycle verifier accepts retained versions and waives multipart cleanup | Astra | Accepted | `lifecycleRule` carries `NewerNoncurrent` and date expiry; every value must be present and positive; no store waiver; adapter-through-verifier test (Task 8); MinIO witness imports the abort element or stops (Task 11) |
+| P1-2 abandoned jobs block later starts | Astra | Accepted | `startDBDownload` reconciles the account's open jobs before admission; `TestStartDBDownloadFreesAbandonedJobs` (Task 8); no background polling |
+| P1-3 Task 3 needs Task 6's `ExportOnly` | Astra | Accepted (with Fable P2-4, fixed once) | `ExportOnly`, `Downloads`, `ExportCapable`, the `consider` guard, nudge-only `Run` and capability publication moved into Task 3 |
+| P1-4 parity table not updated | Astra | Accepted | Verified `TestParityTableCoversConsoleRoutes` (`parity_test.go:48`); Task 9 adds the row and runs `make parity-doc` and the parity tests |
+| P1-5 `s.account`/`refuseLinkedPage` can't give the uniform 404 | Astra | Accepted (with Fable P3-7) | Verified `server.go:3077-3107`, `linkedpolicy.go:302`; `downloadGate` uses `s.session`, `matchAccounts` and `linkedAppRefusal` and answers `http.NotFound`; `TestDBDownloadGateUniform` |
+| P2-6 start after recreation returns the old job | Astra | Accepted (with Fable P2-2, fixed once) | `StartDBDownload` compares the full binding and retires an obsolete open row in the same transaction; the caller writes its cancel; the page reads through `downloadJob` |
+| P2-7 ready jobs excluded from the account cap | Astra | Accepted | Unexpired `ready` rows count; account-wide expiry before counting; test refuses a third instance with two ready |
+| P1 idle polling on every home box | Fable | Accepted (controller ruling) | Export-only agents have no list timer and pass only on `dbExportNudge`, sent from the serial-move branch only; 0 requests per idle home box per day; `TestHomeAgentIdleBudget`; `TestStartDBDownloadBumpLost` dropped; latency (about 8 s) sized against the 60 s window, which is unchanged |
+| P2-2 recreated instance stuck behind the old job | Fable | Accepted | Fixed with Astra P2-6 |
+| P2-3 export can run with no audit row | Fable | Accepted | The `db-download` row is written after the job row and before publication; a failed write fails the job unpublished; `TestStartDBDownloadAuditFirst`. Not in the same SQL transaction: activity writes go through `withAutoAppSQL` (`store.go:3314`), and ordering gives the same guarantee |
+| P2-4 Task 3 not self-contained | Fable | Accepted (controller ruling) | Fixed with Astra P1-3 |
+| P2-5 `downloads/` rule can reach replicas under an unusual prefix | Fable | Accepted | `downloadsPrefixSafe` on the box (Task 6) and in `VerifyDownloads` (Task 8); operator docs line (Task 0) |
+| P3-6 regional boxes gain an unused op | Fable | Accepted (controller ruling) | `Downloads` only on export-only agents; `NewAgent` refuses the mix; regional boxes never publish `db-export-1` |
+| P3-7 gate not uniformly 404 | Fable | Accepted | Fixed with Astra P1-5 |
+| P3-8 capability evidence ignores the data bucket | Fable | Accepted | `capabilityEvidence` matches the published `DataBucket` for downloads; test in Task 8 |
+| P3-9 citation and wording slips | Fable | Accepted | `dbreads.go:56`, `envelope.go:52`; "two to four days"; the start-only read-back stated in the operator docs |