member backups: 1b plan rev 4 after Astra round 2 (#898)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-11-12-member-backups-slice1b.md+57 −18
Intent
<task-notification> <task-id>ad34c2ecab73f571d</task-id> <tool-use-id>toolu_01EwTf61v1n4v6tRStQJiQkn</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 4, uncommitted, still 13 tasks (Task 0 to Task 12). I declined nothing; I checked each cited file and caller against the code first. Two choices you might not expect: - **Lifecycle rule is opt-in.** Both data-bucket modules install the `downloads/` rule only when the operator sets a new `downloads_replica_prefix` variable. With it unset, today's deployments plan no change. An unsafe prefix (empty, starting with `/`, or first segment `downloads`) fails at plan time, before any bucket change. - **New `scripts/downloads-ilm.sh` is the MinIO setup gate.** It applies the same refusal and exits before calling `mc`, and the CI fixture in Task 11 runs it too. It and its shell test sit in `scripts/`, which the census doesn't cover, and CI doesn't run the shell test.</result> <usage><subagent_tokens>409341</subagent_tokens><tool_uses>18</tool_uses><duration_ms>252325</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 48baef222..5aa9eb7e9 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 3** (2026-11-12): Fable's plan round 2 (`FABLE-FINDINGS-plan-1b-R2.md`, READY AFTER FIXES, 2 P2 + 4 P3) applied; dispositions at the end. Astra's round 2 is rerun on this revision. **Rev 2:** 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. |
| +**Plan rev 4** (2026-11-12): Astra's plan round 2 (`CODEX-FINDINGS-plan-1b-R2.md`, reviewed rev 2, NOT READY, 3 P1 + 1 P2) applied on top of rev 3, with the controller's choices under stopping rule 2 for the two repeat families (lifecycle isolation: refuse installation up front; task dependencies: one complete pass, see "Dependency check"); dispositions at the end. The next round is the last. **Rev 3:** Fable's plan round 2 (`FABLE-FINDINGS-plan-1b-R2.md`, READY AFTER FIXES, 2 P2 + 4 P3) applied; dispositions at the end. Astra's round 2 is rerun on this revision. **Rev 2:** 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. |
| @@ -25,7 +25,7 @@ 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 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. |
| +- 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). The rule is never installed unless the replica namespace is declared disjoint from `downloads/`: both data-bucket modules install it only when `downloads_replica_prefix` is set, and refuse at plan time (before any bucket change) a prefix that is empty or whose first segment is `downloads`; the MinIO setup goes through a script with the same refusal. Downloads also stay off at run time on such a deployment (box and console), because the rule would 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. |
| @@ -65,15 +65,22 @@ Decisions this plan takes (reviewers may overturn them): |
| **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/deployment-buckets/variables.tf`, `infra/modules/region-remote-host/variables.tf` (`downloads_replica_prefix`), both modules' `outputs.tf` (`downloads_lifecycle`) |
| +- Create: `scripts/downloads-ilm.sh` (the MinIO setup step) and `scripts/downloads-ilm_test.sh` |
| - 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). |
| +- Produces: |
| + - `variable "downloads_replica_prefix"` (string, default `null`) in both data-bucket modules: the deployment's `CARLOS_HIBERNATE_PREFIX` for this bucket, which the operator states to opt in. Its `validation` refuses, at plan time and so before any bucket change, a value that is empty, starts with `/`, or whose first `/`-separated segment is `downloads`, with an error message naming the value and saying why the rule would expire replicas (Astra R2 P1-1, Fable P2-5). `null` installs nothing (today's deployments plan no change until the operator opts in). |
| + - Only when it is set, the data bucket gains 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), as `dynamic` rule blocks, mirroring `db-reads-expire` in the deployment bucket. `expire-noncurrent` is unchanged. |
| + - `output "downloads_lifecycle"`: `{ installed = bool, replica_prefix = string }`, the operator-visible report of what was checked and installed. |
| + - `scripts/downloads-ilm.sh <mc-alias>/<bucket> <replica-prefix>`: applies the same refusal (same message) and exits 2 before calling `mc`; otherwise runs `mc ilm import` of the AWS-shaped rules (abort included) and prints the read-back (`mc ilm export`). |
| + - The host role gets `s3:GetLifecycleConfiguration` on the data bucket ARN alone (both statement sets). |
| - [ ] **Step 0: Measure the fast tick (before any build; Fable R2 P2-1).** The controller, who has box log access, reads the `agent: fast converge: … took …` lines (`agent.go:3201`) from the dev and flagship boxes' agent logs over at least the last 7 days and records the longest tick, per deployment, in Task 3's Latency bullet. Well under 45 s: accept and continue. Otherwise stop and take it to Paul before Task 3 is built. |
| -- [ ] **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 1: Failing tests.** `downloads_rule_expires_everything_after_a_day` (both bucket modules, `downloads_replica_prefix = "instances"`: exactly one `downloads-expire` rule with the four values above and one `downloads-delete-markers` rule; `downloads_lifecycle.installed` true); `downloads_rule_absent_by_default` (both: unset → no `downloads-*` rule, `installed` false); `downloads_rule_refused_for_unsafe_prefix` (both: `""`, `"downloads"`, `"downloads/x"` and `"/instances"` each `expect_failures = [var.downloads_replica_prefix]`; `"downloadsx"` passes); `scripts/downloads-ilm_test.sh` (with a stub `mc` first on `PATH` that records its calls: every unsafe prefix exits 2 with the message and the stub was never called; `instances` calls `mc ilm import` once with the four values); `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, and `sh scripts/downloads-ilm_test.sh` → 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.) |
| @@ -109,6 +116,7 @@ Decisions this plan takes (reviewers may overturn them): |
| **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` (`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`. |
| +- Migrate every caller of the two changed signatures (found by `grep -rn 'NewAgent(\|withDBReadCapability(' --include=*.go .`; Astra R2 P1-2): `NewAgent` now returns `(*Agent, error)` at `internal/host/dbreads.go:151` (`armDBReads`: log and don't arm), `internal/dbreads/fixture_test.go:248` (`t.Fatal`), `internal/dbreads/dbreadstest/dbreadstest.go:61` (test support: fail its `testing.TB`), `internal/host/dbreads_rootrunner_linux_test.go:623`; `withDBReadCapability` becomes `withDBReadCapabilities` at `internal/host/edgesfile.go:1381`, `internal/host/dbreads_rootrunner_linux_test.go:641` and `internal/host/dbreads_test.go:74,77`. Step 4 re-runs the grep: no caller of the old forms is left. |
| **Interfaces:** |
| - Consumes: Task 2's `OpExport`, `ExportCapability`, `HelloReply.Ops`. |
| @@ -131,13 +139,13 @@ Decisions this plan takes (reviewers may overturn them): |
| - `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 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, R2 P3-3): an `ExportOnly` agent's `listTick` channel is nil and a regional agent's isn't; a counting store under an `ExportOnly` agent's `Run` (probe through `inProcWorkers`) with no nudge for a bounded real interval sees 0 store calls; one nudge at minute 30 of an hour gives exactly one LIST, and one at minute 1 gives two (the agent's `cfg.Now` is the seam); a backstop or instances-floor pass sends no `dbExportNudge`, and a serial move sends exactly one. |
| + - `TestHomeAgentIdleBudget` (Fable P1, R2 P3-3): an `ExportOnly` agent's `listTick` channel is nil and a regional agent's isn't; a counting store under an `ExportOnly` agent's `Run` (probe through `inProcWorkers`) with no nudge for a bounded real interval sees 0 store calls; one nudge at minute 30 of an hour gives exactly one LIST, and one at minute 1 gives two (the agent's `cfg.Now` is the seam); a backstop or instances-floor pass sends no `dbExportNudge`, and a serial move sends exactly one; an `ExportOnly` agent's `serve` of an export, whatever its ending, asks for exactly one more `Pass`. |
| - `TestNewAgentRefusesMixedExportConfig`, `TestExportCapableNeedsAll` (each of the four conditions alone false → false). |
| - `TestWithDBReadCapabilities` (all four combinations). |
| - `TestDBReadsSettingsHome`: empty region → started, `exportOnly`; empty region with `CARLOS_FLEET` set → refused; `fleet/x` and `bad region` refused; host claims and `CARLOS_DB_READS=0` still refuse. `TestDBReadsSocketWantedHome` (including the `CARLOS_FLEET` row, read from host.env). |
| - [ ] **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` and `go test ./internal/host -run 'FastConverge|ChangeIndex' -count=1` unchanged; `GOOS=darwin go build . && GOOS=windows go build .`. |
| +- [ ] **Step 4:** PASS, plus `go test ./internal/dbreads/... -run 'Loop|Agent|Read|Pull' -count=1`, `go test ./internal/host -run 'FastConverge|ChangeIndex|DBRead' -count=1` and `go vet ./internal/dbreads/... ./internal/host` (compiles the root-runner test file) unchanged; `GOOS=darwin go build . && GOOS=windows go build .`; the grep from Files finds no old caller. |
| - [ ] **Step 5:** Commit; then the Astra and Fable task reviews (three rounds at most). |
| ### Task 4: The worker's `export` operation |
| @@ -226,24 +234,24 @@ Decisions this plan takes (reviewers may overturn them): |
| - `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) 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 `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 (s *Server) VerifyDownloads(ctx context.Context) error`: with `cfg.Downloads` and a non-nil `s.downloadObjs` (nil until Task 9 builds the adapter; nil refuses), 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). 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) 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: `dispatchDBDownload`. |
| + - `func (s *Server) dispatchDBDownload(ctx context.Context, d dbDownload, actor string) error` (Astra R2 P1-3): everything after a successful insert runs on one bounded context detached from the browser request, `context.WithTimeout(context.WithoutCancel(ctx), downloadDispatchBound)` with `downloadDispatchBound = 30 * time.Second`, including every failure-state write. First the `db-download` activity row through `RecordActivityContext` (Task 0's detail); audit success stays mandatory: if it fails, `MoveDBDownload(queued→failed, downloadReasonGeneric)` and nothing is published (Fable P2-3). Then 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)`, on the same detached context. |
| - `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; 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). |
| + - `TestVerifyDownloadsWithFakeObjects` (a fake `downloadObjects` whose rules retain versions, lack expiry fields, or lack multipart cleanup: `VerifyDownloads` refuses each; an unsafe hibernate prefix refuses; nil objects refuse). The adapter-through-verifier test is Task 9's, where the adapter is built. |
| - `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). |
| + - `TestStartDBDownloadSurvivesDisconnect` (Astra R2 P1-3): through the real `RecordActivityContext` (so `withAutoAppSQL` and its `demoClaimMutationRefusal` query run), with the caller's context cancelled by a hook right after `StartDBDownload` returns: the activity row exists, and the request and queue entry are published; with the activity write made to fail, the job is `failed` and nothing is 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). |
| @@ -251,7 +259,7 @@ Decisions this plan takes (reviewers may overturn them): |
| - `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|FreesAbandoned|AuditFirst|VerifyDownloadsThroughAdapter|BackupsFor' -count=1` → FAIL. |
| +- [ ] **Step 2:** `go test ./internal/console -run 'LifecycleCovers|DownloadsEndpoint|DownloadsUnavailable|CapabilityEvidence|DBForwardEvidence|StartDBDownload|ReconcileDBDownload|ReconcileClamps|ReconcileConcurrent|SweepAfterRestart|FreesAbandoned|AuditFirst|VerifyDownloadsWithFakeObjects|BackupsFor' -count=1` → FAIL. |
| - [ ] **Step 3:** Implement. |
| - [ ] **Step 4:** PASS. |
| - [ ] **Step 5:** Commit. |
| @@ -282,14 +290,15 @@ Decisions this plan takes (reviewers may overturn them): |
| - `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, 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:** `make parity-doc`; `go test ./internal/console ./internal/parity . -run 'DBDownload|S3DownloadObjects|TestLinkedPolicyCoversEveryAppRoute|TestClaimConsoleRouteCensus|TestNoBucketAppPostsRefuse|TestParityTableCoversConsoleRoutes|TestParityCLIPaths|TestCLIProjection' -count=1` → FAIL. |
| + - `TestVerifyDownloadsThroughAdapter` (moved from Task 8, Astra R2 P1-2: `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; the Task 1 rules pass). |
| +- [ ] **Step 2:** `make parity-doc`; `go test ./internal/console ./internal/parity . -run 'DBDownload|S3DownloadObjects|VerifyDownloadsThroughAdapter|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, 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`. |
| +**Files:** Modify `internal/console/instancepage.go` (`backupsSection.Download *downloadSection`; `instanceBackups` fills it, reading the job through Task 9's `downloadJob` and then `reconcileDBDownload` under its existing per-job throttle, after the binding check; no background polling (Astra R2 P2-4)), `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. |
| @@ -298,8 +307,8 @@ Decisions this plan takes (reviewers may overturn them): |
| - `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 1: Failing tests:** `TestInstancePageReconciles` (Astra R2 P2-4: a preparing job whose `result.json` and object are published shows ready on a plain page GET, with no status call and no script; a ready job past `expires_at` shows the button back on a plain GET; a job whose binding fails is neither shown nor reconciled); `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 'InstancePageReconciles|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. |
| @@ -311,7 +320,7 @@ 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 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 1: The fixture.** In the dbf section: a versioned data bucket for the region, `scripts/downloads-ilm.sh` run on it with the fixture's replica prefix (the same gate operators use), importing 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. |
| @@ -324,6 +333,27 @@ Decisions this plan takes (reviewers may overturn them): |
| - [ ] **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 two to four days; a second press during preparing lands on the same job. |
| + |
| +## Dependency check (rev 4, one pass over every task) |
| + |
| +Each task's new symbols and the first later task that uses them. No task uses a symbol before the task that creates it. |
| + |
| +| Task | New symbols | First used by | |
| +|---|---|---| |
| +| 0 | 1b copy record, `TestApprovedMemberBackups1bCopy` (skipped), re-approved `backups.preparing.note` | Task 8 (audit details), Task 10 (page strings, un-skip) | |
| +| 1 | `downloads_replica_prefix`, `downloads-expire`/`downloads-delete-markers` rules, `downloads_lifecycle` output, `scripts/downloads-ilm.sh`, the lifecycle read grant | Task 8 (verifier expects these values), Task 11 (fixture runs the script) | |
| +| 2 | `OpExport`, `ExportCapability`, `DownloadsPrefix`, `NewJobID`/`MintJobID`/`ValidJobID`/`DownloadKey`, `Request.Job`, `ExportOutcome`, `Result.Export`, `ValidExport`, `HelloReply.Ops`, `readyMsg.Bytes`, `Manifest` | Task 3 (`OpExport`, `ExportCapability`, `HelloReply.Ops`), Task 4 (`readyMsg.Bytes`), Task 5 (`Manifest`, `ExportOutcome`, `DownloadKey`), Task 6 (`DownloadsPrefix`), Task 8 (`MintJobID`, `ValidExport`, `Request.Job`) | |
| +| 3 | `HomeScope`, `QueueScope`, `DownloadStore`, `AgentConfig.ExportOnly`/`Downloads`, `NewAgent` → `(*Agent, error)`, `ExportCapable`, `listTick`, `passAgain`, `dbExportNudge`/`nudgeDBExports`, `withDBReadCapabilities`, `dbReadsEnv.exportOnly` | Task 5 (`DownloadStore`, `Downloads`, `ExportCapable`, `passAgain`), Task 6 (`DownloadStore`, `exportOnly`, `armDBReads`), Task 8 (`QueueKey` via `QueueScope`, `ExportCapability`) | |
| +| 4 | worker `OpExport` path, hello `Ops` | Task 5 | |
| +| 5 | `Agent.export`, `dbdoor.MaxPlanFiles` | Task 5 itself (`backups.go`), Task 11 | |
| +| 6 | `lease.NewDownloadStore`, host `downloadsPrefixSafe`, `armDBReads` wiring of `Downloads` | Task 11 | |
| +| 7 | `db_downloads` table, `dbDownload`, `StartDBDownload`, `DBDownloadFor`, `OpenDBDownloads`/`OpenDBDownloadsFor`, `MoveDBDownload`, caps, `errDownloadsBusy`/`errDownloadsDaily` | Task 8 | |
| +| 8 | `lifecycleRule`, `downloadObjects`, `lifecycleCoversDownloads`, `checkDownloadsEndpoint`, `VerifyDownloads`, console `downloadsPrefixSafe`, `capabilityEvidence`, `downloadAvail`, whys and reasons, `startDBDownload`, `dispatchDBDownload`, `reconcileDBDownload`, `downloadReasonFor`, `SweepDBDownloads`, `Config.Downloads`/`DownloadsEndpoint` | Task 9 (doors, adapter test), Task 10 (`downloadAvail`, reasons, `reconcileDBDownload`) | |
| +| 9 | three routes, parity row, `downloadGate`, `downloadJob`, `downloadFilename`, `NewS3DownloadObjects` (and its wiring in `cmd/console`) | Task 10 (`downloadJob`, `downloadFilename`, URLs), Task 11 (adapter) | |
| +| 10 | `downloadSection`, `downloadSectionFor`, template and script, `cli.md` paragraph | none | |
| +| 11 | `TestDBDownloadMinio`, its fixture | Task 12 (CI green) | |
| +| 12 | census overlay `member-backups-1b`, record-write inventory | none | |
| + |
| --- |
| ## Plan review round 1: dispositions |
| @@ -358,3 +388,12 @@ Decisions this plan takes (reviewers may overturn them): |
| | R2 P3-5 say that every home box with hibernation arms | Fable | Accepted | Stated in Task 3 (pool and demo boxes included, as regional boxes today), for the census claim | |
| | R2 P3-6 halve the per-move cost | Fable | Accepted | `ExportOnly` `Pass` lists the previous hour only within `PickupWindow + Skew` of the hour's start | |
| | R1 P3-9 (partly) citation slips | Fable | Accepted | `ids.go:40`; the fast loop is `agent.go:3722` | |
| + |
| +## Plan review round 2 (Astra, on rev 2): dispositions |
| + |
| +| Finding | Reviewer | Disposition | How | |
| +|---|---|---|---| |
| +| R2 P1-1 lifecycle installation is unconditional | Astra | Accepted (controller choice under stopping rule 2: Astra's recommendation) | Both modules install the rules only with a declared `downloads_replica_prefix` and refuse an unsafe one at plan time, before any bucket change; `downloads_lifecycle` output reports it; `scripts/downloads-ilm.sh` is the MinIO gate; tofu and script tests prove unsafe configurations can't install; the runtime refusals stay (Task 1) | |
| +| R2 P1-2 caller migrations and adapter test order | Astra | Accepted (controller choice: one complete dependency pass) | Verified the callers by grep; every `NewAgent` and capability-helper caller is migrated in Task 3, with a grep check; `TestVerifyDownloadsThroughAdapter` moved to Task 9, Task 8 tests with a fake; "Dependency check" table added | |
| +| R2 P1-3 disconnect after insert can stop dispatch | Astra | Accepted | Verified `withAutoAppSQL` → `demoClaimMutationRefusal` uses the caller's context; `dispatchDBDownload` runs audit, publication and failure writes on one bounded detached context; the disconnect witness goes through the real activity helper (Task 8) | |
| +| R2 P2-4 a plain reload doesn't reconcile | Astra | Accepted | The instance page reconciles after the binding check under the existing throttle; `TestInstancePageReconciles` (Task 10); no background polling | |