member backups: plans rev 2 after Astra plan round 1 (#898)
Slice 1: one listing for position and history, one boundary rule shared with the CLI restore, an intrinsic classifier shared with resolveReplica, the middleware's 403 for roles, parity row, path and CLAIMS fixes. Slice 2a: group-box HRW assignment from an agent-written roster, budget as a deadline, every outcome through the closing identity check, LastDecidedAt, empty-fleet publish, and a strict lease-holder test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-plans.md+60 −0docs/superpowers/notes/reviews/member-backups/CODEX-REVIEW-BRIEF-member-backups-plans-R2.md+13 −0docs/superpowers/plans/2026-11-11-member-backups-slice1.md+35 −25docs/superpowers/plans/2026-11-11-member-backups-slice2a.md+27 −16
CI failed — run details
Intent
<task-notification> <task-id>b9yjc0r7m</task-id> <tool-use-id>toolu_01YTVFyCWFzcsHyDwJFGGanN</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/b9yjc0r7m.output</output-file> <status>completed</status> <summary>Background command "Run Astra plan review round 1" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 26.9 g CO₂e (2,955,262 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-member-backups, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-plans.md b/docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-plans.md| new file mode 100644 |
| index 000000000..ab929ba40 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-plans.md |
| @@ -0,0 +1,60 @@ |
| +Round 1 review of `725d1c6bde8b7b2f44658a9fbc2c781171823942`. Static review only; no files changed or tests run. |
| + |
| +1. **P1 — Slice 1, Tasks 1 and 5: the stated function calls do not compile.** |
| + [Task 5](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:139) registers `runInstancesBackups` with `raw`, but its proposed signature takes writers and returns an integer. `raw` accepts only `func([]string)` (`commands.go:37`). Task 1 also specifies a four-argument `CalcRestorePlan` call; the installed dependency requires five, including a logger, as used in `internal/dbdoor/plan_from.go:119`. |
| + **Fix:** specify a CLI adapter around the testable runner and supply the logger argument. |
| + |
| +2. **P1 — Slice 1, Task 3: the authorization test contradicts the middleware.** |
| + [Line 106](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:106) expects every disallowed role to receive identical 404 bytes. The proposed `kindCLI` registration instead rejects disallowed roles before the handler with 403 and a role-dependent body (`internal/console/authcli.go:524–544`). The cited DB test explicitly expects 403 (`internal/console/apidb_test.go:354–378`). |
| + **Fix:** distinguish role refusals from scope refusals: test the existing 403 behavior for disallowed roles, and byte-identical 404s for admitted roles targeting another app/account. |
| + |
| +3. **P1 — Slice 1, Tasks 3 and 5: the required parity entry is missing.** |
| + [Task 5’s file list](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:137) includes generated `parity/cli.tsv`, but no edit to `parity/parity.tsv`. Regeneration cannot invent that row; `TestParityCLIPaths` requires every command to belong to one (`internal/parity/repo_test.go:62–70`). |
| + **Fix:** add the `instances backups` row before regeneration and run the parity checks. Also add the command to `docs/site/cli.md`, as repository instructions require; this does not require a separate backups documentation page. |
| + |
| +4. **P2 — Slice 1, Task 5: the API path is malformed.** |
| + [Line 147](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:147) passes `"instances/"+host+"/backups"` to `apiPath`. That helper concatenates the tail directly after the app (`apimode.go:468–469`), producing a path such as `/api/cli/apps/bab/shopinstances/…`. |
| + **Fix:** use `"/instances/"+host+"/backups"` and assert the exact requested path in the fake-console test. |
| + |
| +5. **P2 — Slice 1, Task 1: the restore boundary remains duplicated.** |
| + [Line 62](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:62) shares a helper between `PlanFrom` and `HistoryFrom` but explicitly prohibits touching `restore.go`. The actual CLI restore retains its separate boundary calculation at `internal/dbdoor/restore.go:183–187` and oldest-file selection at `:277–284`. This does not implement spec §1 and §12’s shared boundary function. |
| + **Fix:** include `restore.go` in the task and make the planner, history reader and CLI restore use the same boundary rules. Retain the restore-oracle tests. |
| + |
| +6. **P2 — Slice 1, Task 2: intrinsic classification is not shared with `db pull`.** |
| + [Lines 73–82](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:73) introduce a console classifier with its own pool and fleet checks. Existing DB reads keep those checks in `resolveReplica` (`internal/console/apidb.go:54–71`); no task changes that caller. An agreement test is useful, but does not satisfy spec §1’s single shared classification function. |
| + **Fix:** extract the intrinsic classification and call it from both paths, keeping region availability separate so forwarding remains intact. |
| + |
| +7. **P2 — Slice 1, Tasks 1–2: one cache miss lists the replica twice.** |
| + [Task 2](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:73) consumes both `PlanFrom` and `HistoryFrom`; Task 1 implements the latter with another `CalcRestorePlan`. `PlanFrom` already lists through its own `listing` (`internal/dbdoor/plan_from.go:110–119`). Without shared listing results, a miss makes twenty level listings, contradicting spec §1/§9’s ten-level budget. A shared counting wrapper would also count each file twice. |
| + **Fix:** derive position and history from one bounded listing snapshot. Test actual listing calls and acceptance at the configured file cap, alongside the over-cap test. |
| + |
| +8. **P2 — Slice 1, Task 6: the census proposal step lacks its required input.** |
| + [Line 153](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice1.md:153) requests `make census-propose` with a name but has no CLAIMS-file task. The target refuses execution without both `NAME` and `CLAIMS` (`Makefile:65–67`). |
| + **Fix:** explicitly create the per-unit CLAIMS file, supply both arguments, and commit the generated overlay and chain line. Slice 2a already describes this correctly. |
| + |
| +9. **P2 — Slice 2a, Task 5: group-box drill assignment is absent.** |
| + [Task 5](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md:109) adds identity and budget handling but no serving-roster input or group assignment step. Existing `HibernatingHosts` only walks the local registry (`internal/ops/hibernate_verify.go:45–65`). Spec §3 explicitly assigns group hosts to their HRW box over `serving(region)`; local registry membership does not implement that rule. |
| + **Fix:** add a task for group candidate discovery and deterministic assignment, preserving fixed-box behavior. Test exactly one assignment per host across multiple serving boxes and reassignment when a box leaves. |
| + |
| +10. **P2 — Slice 2a, Tasks 3 and 5: the time budget does not bound an active drill.** |
| + [Line 121](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md:121) only stops *starting* hosts after the budget expires. A planning call or restore started just before that point can continue indefinitely. Task 3 also specifies `CheckDB`, which deliberately uses `context.Background()` (`internal/lease/check.go:37–38`). The proposed fake-clock test covers completed hosts, not blocked work. |
| + **Fix:** propagate the remaining run deadline through planning, download, restore and integrity checking; use `CheckDBContext`. Add a blocked-operation test proving cancellation, scratch cleanup and publication of completed results using a separately bounded publish context. |
| + |
| +11. **P2 — Slice 2a, Tasks 1 and 5: replica-derived failures can bypass the closing identity check.** |
| + [Line 121](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md:121) immediately maps an empty plan to `nothing_replicated` and restore/integrity errors to `failed`; it does not require confirmation before those exits. Existing DB reads deliberately run check B before replica-derived failure results (`internal/dbreads/read.go:119–135`, `:174–179`). A deletion or recreation during a failing read must take precedence over that result. |
| + **Fix:** funnel every replica-derived outcome through confirmation. Add deletion, same-account recreation, cross-account recreation and move cases during both planning and download, including failure paths. Explicitly translate `CodeRecordChanged` (`"record-changed"`, `internal/dbreads/result.go:29`) to the proposed verdict reason `"record_changed"`. |
| + |
| +12. **P2 — Slice 2a, Tasks 4 and 8: the record cannot retain the last decided verdict’s age.** |
| + [The proposed verdict fields and merge rules](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md:96) retain only the latest `VerifiedAt` and `FirstSeen`. Once an unverified result replaces a passed/failed result, the timestamp needed by the seven-day coverage rule is lost. Using the latest attempt time continually refreshes coverage; using `FirstSeen` can alert immediately after a recent successful test. |
| + **Fix:** persist a separate last-decided timestamp, advance it only for passed/failed outcomes, and reset it when identity changes. Test a recent pass followed by unverified attempts across the seven-day boundary. |
| + |
| +13. **P2 — Slice 2a, Tasks 5–7: an empty fleet never clears its previous contribution.** |
| + [Task 6, line 143](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md:143) explicitly says a box with no sleeping hosts publishes nothing. That preserves today’s early return (`internal/ops/ops.go:314–316`) and contradicts the promise that departed hosts disappear on the next run. Moving the last host off a box leaves both its bucket contribution and local alert copy stale indefinitely. |
| + **Fix:** distinguish a box that has never contributed from one whose fleet became empty. For the latter, publish an empty contribution and update the local alert copy. Test moving/deleting the last host. |
| + |
| +14. **P2 — Slice 2a, Task 5: matching the owner reference does not prove a live lease.** |
| + [Line 121](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/member-backups/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md:121) selects local freshness comparison when `Ref == SelfRef`. `lease.LockState` also returns `held`, and explicitly retains the owner string for an expired lock (`internal/lease/lockstate.go:39–47`, `:78`). An expired self-owned lock therefore passes the stated reference check without proving ownership. |
| + **Fix:** require a successful read, `held == true`, successful owner parsing and a matching reference. Add expired-self, absent, malformed and unreadable-lock cases that assert no local database read and unknown freshness. |
| + |
| +Slice 1 — **NOT READY** |
| +Slice 2a — **READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/docs/superpowers/notes/reviews/member-backups/CODEX-REVIEW-BRIEF-member-backups-plans-R2.md b/docs/superpowers/notes/reviews/member-backups/CODEX-REVIEW-BRIEF-member-backups-plans-R2.md| new file mode 100644 |
| index 000000000..7995f964e |
| --- /dev/null |
| +++ b/docs/superpowers/notes/reviews/member-backups/CODEX-REVIEW-BRIEF-member-backups-plans-R2.md |
| @@ -0,0 +1,13 @@ |
| +# Plan review brief, round 2: member backups slices 1 and 2a |
| + |
| +Same plans, now rev 2. Round 1 findings: |
| +`CODEX-FINDINGS-member-backups-plans.md` in this directory. The original |
| +brief, `CODEX-REVIEW-BRIEF-member-backups-plans.md`, still applies. |
| + |
| +1. First a disposition table: for each round 1 finding (1-14), FIXED, |
| + PARTLY (say what is missing) or NOT FIXED. The plans mark their fixes |
| + (P-N). |
| +2. Then only NEW findings in rev 2, same format. Verify every citation. |
| + Prefer cuts and refusals over new mechanism. |
| +3. End with one line per plan: READY, READY AFTER FIXES, or NOT READY. |
| + Round 2 of at most three. Do not spawn other models or reviewers. |
diff --git a/docs/superpowers/plans/2026-11-11-member-backups-slice1.md b/docs/superpowers/plans/2026-11-11-member-backups-slice1.md| index d1b82b5ba..df48e4aa5 100644 |
| --- a/docs/superpowers/plans/2026-11-11-member-backups-slice1.md |
| +++ b/docs/superpowers/plans/2026-11-11-member-backups-slice1.md |
| @@ -4,7 +4,9 @@ |
| **Goal:** Owners, members and release automation can read, for one instance, the last change saved to its copy, how far back history reaches, and what isn't copied, through a console door, a section on the instance page and `carlos instances backups`. |
| -**Architecture:** One console classifier decides what is known about an instance's copy. One door, `GET /api/cli/apps/{account}/{app}/instances/{host}/backups`, answers a fixed, contents-free schema built from `dbdoor.PlanFrom` and a new `dbdoor.HistoryFrom`, bounded and memoised. The instance page calls the same function in-process; the CLI prints the door's answer. |
| +**Plan rev 2** (2026-11-11): Astra plan round 1 (`docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-plans.md`, NOT READY) fully applied; findings marked **(P-N)**. |
| + |
| +**Architecture:** One intrinsic classifier, shared with `db pull`'s `resolveReplica`, decides what is known about an instance's copy. One door, `GET /api/cli/apps/{account}/{app}/instances/{host}/backups`, answers a fixed, contents-free schema built from one bounded listing (`dbdoor.PositionAndHistory`), memoised. The instance page calls the same function in-process; the CLI prints the door's answer. |
| **Tech Stack:** Go; `internal/console` (doors, templates, copy), `internal/dbdoor` (Litestream planning), the root CLI (`clireg`). |
| @@ -21,13 +23,13 @@ |
| - Not announced as "backups" anywhere outside the section itself (no release-note headline, no docs page in this slice). |
| - Copy: only strings approved in Task 0, verbatim. No em dashes in copy. |
| - Local verification: changed packages only, with `-run`. CI runs the full suite. |
| -- `internal/dbdoor` and the root CLI are in the root binary's census scope: Task 6 runs `make census-card` and asks for approval on #280 (`census-ruling-member-backups-1`). |
| +- `internal/dbdoor` and the root CLI are in the root binary's census scope: Task 6 runs `make census-card` and proposes overlay `member-backups-1` for approval on #280. |
| - Commit subjects under 80 characters, body after a blank line, ending `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. One amadan task per plan task on the build branch. |
| ## Review Focus |
| 1. **A replica with nothing in it yet** (an instance created a minute ago): expect `not_shown`/`nothing_replicated`, never an error page. Test in Task 3. |
| -2. **A sleeping instance whose snapshots were pruned while awake, then slept for weeks**: `history_from` must still equal the earliest `--at` the CLI would accept. Oracle test in Task 1. |
| +2. **A sleeping instance whose snapshots were pruned while awake, then slept for weeks**: the history start must still equal the earliest `--at` the CLI would accept. Oracle test in Task 1. |
| 3. **A service credential bound to a different app, or an app-less `deploy` token**: byte-identical 404 as other doors. Test in Task 3 (role table). |
| 4. **A replica listing over the file cap or past the deadline**: `not_shown`/`too_large_to_plan`, and a second concurrent request does not start a second listing. Test in Task 2. |
| 5. **A demo instance and a pooled instance**: demo says no copy, pooled says not shown, and neither reads the bucket. Test in Task 2. |
| @@ -45,21 +47,26 @@ |
| - [ ] **Step 3:** Write `TestApprovedMemberBackupsCopy` calling `checkApprovedCopy(t, raw, ".", ids, fragments)` (`approved_copy_test.go:71`) against the record, pinning every ID. Run: `go test . -run TestApprovedMemberBackupsCopy` → FAIL until Tasks 4-5 land the strings; mark it `t.Skip` with a note until Task 5, then remove the skip there. |
| - [ ] **Step 4:** Commit. |
| -### Task 1: `dbdoor.HistoryFrom` |
| +### Task 1: `dbdoor.PositionAndHistory`, one listing, one boundary rule (P-1, P-5, P-7) |
| **Files:** |
| -- Modify: `internal/dbdoor/plan_from.go` |
| -- Test: `internal/dbdoor/plan_from_test.go` |
| +- Modify: `internal/dbdoor/plan_from.go`, `internal/dbdoor/restore.go:183-187,277-284` |
| +- Test: `internal/dbdoor/plan_from_test.go`, `internal/dbdoor/restore_test.go` |
| **Interfaces:** |
| -- Produces: `func HistoryFrom(ctx context.Context, rd ReplicaReader) (time.Time, bool, error)`. Returns the earliest instant an `--at` restore accepts (the oldest snapshot-level or `MinTXID == 1` file's time, `Truncate(time.Second).Add(time.Second)`, the same rule as `restore.go:183` and `plan_from.go:130`); `ok=false` when it cannot be decided (no files, or listing times absent: `ErrNoTimes`). `ErrNothingReplicated` passes through. |
| +- Produces: |
| + - `func PositionAndHistory(ctx context.Context, rd ReplicaReader, maxFiles int) (RestorePlan, time.Time /*history from*/, bool /*history known*/, error)`: ONE pass over the levels (each level listed once), from which both the newest plan (as `PlanFrom(ctx, rd, time.Time{})` computes it) and the history start are derived. `CalcRestorePlan` takes its fifth argument, the logger, as `plan_from.go:119` does. Past `maxFiles` listed files it returns `ErrTooManyFiles` (new sentinel). `ErrNothingReplicated` passes through; absent listing times give `known=false`. |
| + - One unexported pair used by `PlanFrom`, `PositionAndHistory` AND the CLI restore (`restore.go:183-187` boundary, `:277-284` oldest-file selection): `isHistoryStart(f LTXFile) bool` (snapshot level or `MinTXID == 1`) and `historyBoundary(oldest time.Time) time.Time` (`Truncate(time.Second).Add(time.Second)`). Those three call sites stop computing it themselves. |
| - [ ] **Step 1: Failing tests.** |
| - - `TestHistoryFromMatchesRestoreBoundary`: replicate with `dbdoortest.Replicate` across several batches and a snapshot; assert `HistoryFrom` equals the `Oldest` of the `*BeforeHistoryError` that `restoreAt` returns for an `--at` one hour before the first batch (the CLI path), and that `PlanFrom(ctx, rd, got)` succeeds while `PlanFrom(ctx, rd, got.Add(-time.Second))` returns the before-history error. |
| - - `TestHistoryFromTxidOneFileBeforeSnapshot`: a replica with only L0 files starting at TXID 1 and no snapshot gives `ok=true` at that file's time rule. |
| - - `TestHistoryFromEmpty`: returns `ErrNothingReplicated`. |
| -- [ ] **Step 2:** `go test ./internal/dbdoor -run TestHistoryFrom` → FAIL (undefined). |
| -- [ ] **Step 3:** Implement by sharing `PlanFrom`'s `listing{rd, asOf: true}` and `CalcRestorePlan(ctx, l, 0, time.Time{})`; factor the oldest-time rule into one unexported helper used by both `PlanFrom` and `HistoryFrom`. Don't touch `restore.go`. |
| + - `TestPositionAndHistoryMatchesRestoreBoundary`: replicate with `dbdoortest.Replicate` across batches and a snapshot; the history start equals the `Oldest` of the `*BeforeHistoryError` the CLI's `restoreAt` returns for an `--at` an hour before the first batch; `PlanFrom(ctx, rd, from)` succeeds and `PlanFrom(ctx, rd, from.Add(-time.Second))` is before-history; the plan equals `PlanFrom(ctx, rd, time.Time{})`. |
| + - `TestPositionAndHistoryTxidOneFileBeforeSnapshot`. |
| + - `TestPositionAndHistoryEmpty` → `ErrNothingReplicated`. |
| + - `TestPositionAndHistoryListsEachLevelOnce`: a counting `ReplicaReader` sees exactly one listing per level. |
| + - `TestPositionAndHistoryFileCap`: exactly `maxFiles` files succeeds; `maxFiles+1` gives `ErrTooManyFiles`. |
| + - Existing `restore_test.go` boundary tests pass unchanged. |
| +- [ ] **Step 2:** `go test ./internal/dbdoor -run 'PositionAndHistory|Restore|PlanFrom'` → FAIL (undefined). |
| +- [ ] **Step 3:** Implement: a listing that caches each level's entries for the duration of one call, so `CalcRestorePlan` and the history scan read the same snapshot; the shared helpers above replace the three copies. |
| - [ ] **Step 4:** Tests PASS. |
| - [ ] **Step 5:** Commit. |
| @@ -70,19 +77,22 @@ |
| - Test: `internal/console/backups_test.go` |
| **Interfaces:** |
| -- Consumes: `dbdoor.PlanFrom`, `dbdoor.HistoryFrom` (Task 1); `dbreads.ClassRefusal`; `registry.FleetPlacement`; `s.dbReplica`; `regionlabel.ForCode`. |
| +- Consumes: `dbdoor.PositionAndHistory` (Task 1); `dbreads.ClassRefusal`; `registry.FleetPlacement`; `s.dbReplica`; `regionlabel.ForCode`. |
| +- Modifies: `internal/console/apidb.go:54-71` (`resolveReplica`) and `:242` (`dbClassRefusal`) to call `replicaIntrinsic` (P-6), keeping their existing errors and messages byte for byte. |
| - Produces: |
| - `type backupClass string` with `backupReplicated = "replicated"`, `backupNoCopy = "no_copy"`, `backupNotShown = "not_shown"`. |
| - - `func classifyBackups(rec provision.Record, consoleRegion string) (backupClass, string /*reason*/)`. Order: `ClassRefusal` (reasons `not_instance`, `own_address`, `no_sleep`, from exactly the record fields `ClassRefusal` reads: `Kind`, `Addr`/`Addrs`, `HibernateOrDefault`; `Unit` alone is not a refusal, as in `db pull`), then `rec.Demo != nil` (`no_copy`, `demo`), then `Pool` (`not_shown`, `pooled`), then `FleetPlacement` (`not_shown`, `fleet`), then region (`not_shown`, `other_region`). Otherwise `replicated`, `""`. |
| + - `func replicaIntrinsic(rec provision.Record) (backupClass, string /*reason*/)`: the intrinsic classes only, shared by the door, `resolveReplica` and `dbClassRefusal` (P-6). |
| + - `func classifyBackups(rec provision.Record, consoleRegion string) (backupClass, string /*reason*/)`: `replicaIntrinsic`, then region (separate, so `db pull` forwarding is untouched). Order: `ClassRefusal` (reasons `not_instance`, `own_address`, `no_sleep`, from exactly the record fields `ClassRefusal` reads: `Kind`, `Addr`/`Addrs`, `HibernateOrDefault`; `Unit` alone is not a refusal, as in `db pull`), then `rec.Demo != nil` (`no_copy`, `demo`), then `Pool` (`not_shown`, `pooled`), then `FleetPlacement` (`not_shown`, `fleet`), then region (`not_shown`, `other_region`). Otherwise `replicated`, `""`. |
| - `type backupsView struct { Class backupClass; Reason, Region string; CopiedTo *backupsPosition; HistoryFrom *time.Time; HABorn bool }` and `type backupsPosition struct { Transaction uint64; WrittenAt time.Time }`, JSON tags as spec §1 (`class`, `reason`, `region`, `copied_to{transaction, written_at}`, `history_from`, plus `files: "not_copied"|"not_shown"`). |
| - - `func (s *Server) backupsFor(ctx context.Context, rec provision.Record) backupsView`, memoised per host for 5 minutes with an in-flight map (copy `analyticsMemo`, `analyticsview.go:290-395`), 10-second deadline, a `ReplicaReader` wrapper that fails with `errTooManyFiles` past 20,000 listed files. `ErrNothingReplicated` → `not_shown`/`nothing_replicated`; cap or deadline → `not_shown`/`too_large_to_plan`; any other error → `not_shown`/`unavailable` (logged). |
| + - `func (s *Server) backupsFor(ctx context.Context, rec provision.Record) backupsView`, memoised per host for 5 minutes with an in-flight map (copy `analyticsMemo`, `analyticsview.go:290-395`), 10-second deadline, one `PositionAndHistory(ctx, rd, 20000)` call per miss (P-7). `ErrNothingReplicated` → `not_shown`/`nothing_replicated`; `ErrTooManyFiles` or deadline → `not_shown`/`too_large_to_plan`; any other error → `not_shown`/`unavailable` (logged). |
| - [ ] **Step 1: Failing tests.** |
| - `TestClassifyBackupsTable`: one row per reason above, plus a Unit-only record (expects `replicated`, matching `db pull`) and a fleet record in the console's region. |
| - `TestClassifyBackupsAgreesWithResolveDBSource`: for every table row, `classifyBackups` says `replicated` exactly when `s.resolveDBSource` returns no error (the oracle that keeps the door and `db pull` in agreement, spec §1 R2-2: only intrinsic classes must agree; `other_region` rows assert `resolveDBSource` returns `ErrResidency`). |
| - - `TestBackupsForReadsPositionAndHistory`: `dbFixture` + `fx.replicate`; `CopiedTo` equals `PlanFrom(...).TXID`/`.At`, `HistoryFrom` matches Task 1. |
| + - `TestBackupsForReadsPositionAndHistory`: `dbFixture` + `fx.replicate`; `CopiedTo` and `HistoryFrom` equal Task 1's results. |
| + - `TestResolveReplicaUsesIntrinsic`: `resolveReplica` and `dbClassRefusal` return the same errors and messages as before for every table row (golden values captured before the refactor). |
| - `TestBackupsForNotShownNeverReadsBucket`: demo, pooled, fleet and other-region rows: the stubbed `dbReplica` is never called. |
| - - `TestBackupsForBounds`: a reader listing 20,001 files gives `too_large_to_plan`; a reader that blocks gives it after the deadline (inject the deadline); two concurrent calls on one host call `dbReplica` once; a second call within 5 minutes reads nothing. |
| + - `TestBackupsForBounds`: a reader listing 20,000 files succeeds and 20,001 gives `too_large_to_plan`; a reader that blocks gives it after the deadline (inject the deadline); two concurrent calls on one host call `dbReplica` once; a second call within 5 minutes reads nothing. |
| - `TestBackupsForNothingReplicated`. |
| - [ ] **Step 2:** Run `go test ./internal/console -run 'TestClassifyBackups|TestBackupsFor'` → FAIL. |
| - [ ] **Step 3:** Implement as the Interfaces block says. `HABorn` is `rec.HA`; `files` is `not_shown` when `HABorn`, else `not_copied`. |
| @@ -103,7 +113,7 @@ |
| - [ ] **Step 1: Failing tests.** |
| - `TestAPIInstanceBackupsMember`: member token, replicated host → 200 with `class`, `copied_to`, `history_from`; the body has no other keys (decode into `map[string]any` and compare key set). |
| - - `TestAPIInstanceBackupsRoles`: table over every `svcrole` role, in the style of `TestAPIDBRefusesEveryServicePrincipalTheSameWay` (`apidb_test.go:358`): deploy, operate, admin → 200; every other role, a token for another app, and another account's member → the same 404 bytes as the gate-pass door. |
| + - `TestAPIInstanceBackupsRoles` (P-2): deploy, operate, admin → 200; every other role → the `kindCLI` middleware's 403 (`authcli.go:524-544`), asserted as that middleware writes it; an admitted-role token bound to another app, an app-less token where the gate requires an app, and another account's member → the byte-identical 404 the instance gate gives. |
| - `TestAPIInstanceBackupsBadHostAndMissing`: bad shape and unknown host → the instance gate's standard 400/404. |
| - `TestAPIInstanceBackupsOtherRegion`: `not_shown`/`other_region` with the region label; and `db pull`'s forward for the same host still admits (call the existing forward door and assert it is not refused). |
| - [ ] **Step 2:** `go test ./internal/console -run TestAPIInstanceBackups` → FAIL. |
| @@ -136,20 +146,20 @@ |
| **Files:** |
| - Create: `instances_backups.go`, `instances_backups_test.go` (repo root) |
| -- Modify: `cli.go` (`instancesCommand()` gains `raw("backups", cust, runInstancesBackups)`), `parity/cli.tsv` via `make parity-doc` |
| +- Modify: `cli.go` (`instancesCommand()` gains `raw("backups", cust, runInstancesBackups)`), `parity/parity.tsv` (a new `instances backups` row, added by hand first, P-3), then `parity/cli.tsv` via `make parity-doc`; `docs/site/cli.md` (one entry) |
| - Modify: `approved_member_backups_copy_test.go` (remove the Task 0 skip) |
| **Interfaces:** |
| -- Produces: `func runInstancesBackups(args []string, stdout, stderr io.Writer) int` and `func printBackups(w io.Writer, app, host string, v backupsJSON)` (a CLI-side mirror of `backupsView`). |
| +- Produces: `func runInstancesBackups(args []string)` (the `raw` leaf, `commands.go:37`; exits as `runGeo` does) wrapping the testable `func instancesBackups(ctx context.Context, args []string, stdout, stderr io.Writer) int` (P-1), and `func printBackups(w io.Writer, app, host string, v backupsJSON)`. |
| -- [ ] **Step 1: Failing tests:** `TestInstancesBackupsPrintsLines` (each class into a `bytes.Buffer`, the approved labels); `TestInstancesBackupsJSON` (`--json` writes the body verbatim plus newline); `TestInstancesBackupsPicksOnlyInstance` (no `--instance`, one instance → uses it; several → refuses naming them, via `resolveDBInstance`); a fake console with `httptest.NewServer` + `newTestSession`. |
| +- [ ] **Step 1: Failing tests:** `TestInstancesBackupsPrintsLines` (each class into a `bytes.Buffer`, the approved labels); `TestInstancesBackupsJSON` (`--json` writes the body verbatim plus newline); `TestInstancesBackupsRequestPath` (the fake console asserts the exact path `/api/cli/apps/{acct}/{app}/instances/{host}/backups`, P-4); `TestInstancesBackupsPicksOnlyInstance` (no `--instance`, one instance → uses it; several → refuses naming them, via `resolveDBInstance`); a fake console with `httptest.NewServer` + `newTestSession`. |
| - [ ] **Step 2:** `go test . -run 'TestInstancesBackups|TestApprovedMemberBackupsCopy'` → FAIL. |
| -- [ ] **Step 3:** Implement following `runGeo` (`geo_cmd.go:35`): `requireAPISession`, `resolvedAccount`, `resolvedApp`, `sess.getJSON(ctx, apiPath(acct, app, "instances/"+host+"/backups"))`, `apiErrorFromBody`. |
| -- [ ] **Step 4:** `make parity-doc`; `go test . -run 'TestInstancesBackups|TestApprovedMemberBackupsCopy|TestCLIProjection'` → PASS. |
| +- [ ] **Step 3:** Implement following `runGeo` (`geo_cmd.go:35`): `requireAPISession`, `resolvedAccount`, `resolvedApp`, `sess.getJSON(ctx, apiPath(acct, app, "/instances/"+host+"/backups"))` (leading slash: `apiPath` concatenates, `apimode.go:468`), `apiErrorFromBody`. |
| +- [ ] **Step 4:** `make parity-doc`; `go test . ./internal/parity -run 'TestInstancesBackups|TestApprovedMemberBackupsCopy|TestCLIProjection|TestParityCLIPaths'` → PASS. |
| - [ ] **Step 5:** Commit. |
| ### Task 6: Census and branch close |
| -- [ ] **Step 1:** `make census-card`; `make census-propose` naming `census-ruling-member-backups-1`; post the card on #280 and wait for the reviewer's approval. Commit the overlay. |
| -- [ ] **Step 2:** Changed packages only: `go test ./internal/dbdoor ./internal/console . -run 'HistoryFrom|Backups|ClassifyBackups|InstancePageBackups|InstancesBackups|ApprovedMemberBackups|LinkedPolicy|ClaimConsoleRoute|DeployReaches|EveryCLIDoor|CLIProjection|Plan14'`. Push; `amadan ci status -branch <name>` green. |
| +- [ ] **Step 1 (P-8):** `make census-card`; write `docs/superpowers/notes/census-claims-member-backups-1.txt` with one claim per changed root-binary unit (the `dbdoor` boundary and listing changes, the CLI command) as AGENTS.md:303-399 describes; `make census-propose NAME=member-backups-1 CLAIMS=docs/superpowers/notes/census-claims-member-backups-1.txt`; post the proposal on #280; wait for the other-family reviewer's approval. Commit the overlay, the chain line and the proposal. |
| +- [ ] **Step 2:** Changed packages only: `go test ./internal/dbdoor ./internal/console ./internal/parity . -run 'PositionAndHistory|Restore|PlanFrom|ResolveReplica|ParityCLIPaths|Backups|ClassifyBackups|InstancePageBackups|InstancesBackups|ApprovedMemberBackups|LinkedPolicy|ClaimConsoleRoute|DeployReaches|EveryCLIDoor|CLIProjection|Plan14'`. Push; `amadan ci status -branch <name>` green. |
| - [ ] **Step 3:** Whole-branch Astra review (three rounds at most). Then release, roll dev first, and the dev check (spec §12: the section on a dev instance matches `carlos db pull`'s position line). Reply on #898 and #893 (close #893 as absorbed). |
diff --git a/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md b/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md| index 7929fab45..d8d4b0e35 100644 |
| --- a/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md |
| +++ b/docs/superpowers/plans/2026-11-11-member-backups-slice2a.md |
| @@ -4,6 +4,8 @@ |
| **Goal:** Every box with sleeping instances runs the restore drill nightly and publishes its own record, `control/verify/<ref>.json`, whose verdicts are bound to the instance identity they tested, and operators are alerted when a test fails, keeps being unverified, or falls more than 7 days behind. |
| +**Plan rev 2** (2026-11-11): Astra plan round 1 (`docs/superpowers/notes/reviews/member-backups/CODEX-FINDINGS-member-backups-plans.md`, READY AFTER FIXES) fully applied; findings marked **(P-N)**. |
| + |
| **Architecture:** `hibernate-verify` stops sharing one deployment-wide key. Each run opens the `dbreads` identity bracket per host, plans with `dbdoor.PlanFrom`, restores pinned to that TXID, closes the bracket, and records a v2 verdict. It works oldest first inside a 45-minute budget, publishes every 10 minutes, and leaves a local copy the box agent turns into alert rules. Freshness is compared only when this box holds the host's live lease. |
| **Tech Stack:** Go; `internal/dbverify`, `internal/ops`, `internal/dbreads`, `internal/lease`, `internal/host` (bootstrap, agent, moves, units), `internal/metrics` + `internal/alerting` + console alert registration, `internal/release` (change index), `internal/hostops`. |
| @@ -14,9 +16,11 @@ |
| - Record key: `control/verify/<ref>.json`, one per box, written only by that box. `<ref>` is the box's lease reference (the agent's `metricsBoxLabel`), never `os.Hostname()`. |
| - `control/restore-verify.json` is no longer written or read by any code; its text mentions move to the new key. |
| -- Verdicts never say "current". `stale` only when proved, and only on a box that holds the host's live lease (`lease.LockState` + `hafresh.ParseOwner`, `Ref == self`); otherwise freshness is `unknown` and is not a failure. |
| +- Verdicts never say "current". `stale` only when proved, and only when the lock read succeeded, `held == true`, `hafresh.ParseOwner` succeeded and `Ref == self` (`lockstate.go:39-47,78` keeps an expired owner string) (P-14); otherwise freshness is `unknown`, the local database is not read, and it is not a failure. |
| - Budget: drills oldest first (never verified, then stalest `VerifiedAt`), 45 minutes per run by default (`-budget`), `-max` default 0 (no count cap). Publish every 10 minutes and at the end. |
| -- The bracket: identity captured before planning, confirmed after the last replica byte; any difference discards the restore and records `unverified` with reason `record_changed` or `moving`. |
| +- The bracket: identity captured before planning, confirmed after the last replica byte AND before every replica-derived outcome is recorded (empty plan, restore error, integrity failure, stale), as `dbreads` does (`read.go:119-135,174-179`) (P-11). Any difference discards the restore and records `unverified` with reason `record_changed` (from `dbreads.CodeRecordChanged`, `"record-changed"`) or `moving`. |
| +- The budget is a deadline, not just a start cut-off: the run context's deadline reaches planning, download, restore and `CheckDBContext`; publishing uses its own 30-second context (P-10). |
| +- Group boxes (`CARLOS_BOX_REFERENCE=group`): a host is drilled only by `boxchoice.HRW(host, serving) == self`, over the serving roster the agent writes (Task 2); fixed boxes drill every local sleeping host as today (P-9). |
| - Scratch stays on disk (`TMPDIR=%C/carlos-verify`, `TestVerifyDrillsRestoreToDiskNotTmpfs`). |
| - Alert thresholds: `verify_failed@<host>` on a failed verdict; `verify_unverified@<host>` after 3 consecutive unverified runs for any reason except `not_reached`; `verify_coverage` when any host's last decided verdict (passed or failed) is older than 7 days, or it has none and was first seen more than 7 days ago. |
| - Copy: only strings approved in Task 0, verbatim; no em dashes. |
| @@ -60,14 +64,14 @@ |
| - [ ] **Step 4:** `go test ./internal/dbreads -run 'Identity|Agent|Read'` → PASS (the existing `agent_test.go:31` recreation cases unchanged). |
| - [ ] **Step 5:** Commit. |
| -### Task 2: The box's own reference, readable by the drill |
| +### Task 2: The box's own reference and serving roster, readable by the drill (P-9) |
| -**Files:** Create `internal/boxself/boxself.go` (leaf package) and test; modify the agent start in `internal/host` where `haSelfNow` is applied (`lease.SetSelf`) to also call `boxself.Write`. |
| +**Files:** Create `internal/boxself/boxself.go` (leaf package) and test; modify the agent start in `internal/host` where `haSelfNow` is applied (`lease.SetSelf`) to call `boxself.Write`, and the place the HA duty view refreshes (`internal/activator/haduties.go:233-242`, `boxchoice.WakeSnapshot.Serving`) to rewrite it with the roster; move `dutyHRW` (`haduties.go:401`) to `internal/boxchoice` as exported `HRW(host string, refs []string) (string, bool)`, with the activator calling it. |
| **Interfaces:** |
| -- Produces: `func Write(dataDir, ref string) error` (atomic write of `<dataDir>/monitor/self.json` `{"v":1,"ref":...}`, mode 0644) and `func Read(dataDir string) (string, error)` (`os.ErrNotExist` when absent; refuses an empty or invalid ref). |
| +- Produces: `type Self struct { Ref string; Group bool; Serving []string; ServingAt time.Time }`; `func Write(dataDir string, s Self) error` (atomic write of `<dataDir>/monitor/self.json`, `v: 1`, mode 0644); `func Read(dataDir string) (Self, error)` (`os.ErrNotExist` when absent; refuses an empty or invalid ref). `boxchoice.HRW` byte-identical to today's `dutyHRW`. |
| -- [ ] **Step 1: Failing tests:** `TestBoxSelfRoundTrip`, `TestBoxSelfReadMissing`, `TestBoxSelfRefusesEmpty`; in `internal/host`, `TestAgentWritesSelfRefEqualToLeaseRef` (the written ref equals `haSelfNow(...).Ref` for a fixed box and a group box fixture). |
| +- [ ] **Step 1: Failing tests:** `TestBoxSelfRoundTrip`, `TestBoxSelfReadMissing`, `TestBoxSelfRefusesEmpty`; in `internal/host`, `TestAgentWritesSelfRefEqualToLeaseRef` (fixed and group fixtures); `TestHRWMatchesDutyHRW` (golden values from the old function); `TestHRWAssignsEachHostOnce` (three refs, 1,000 hosts: each host has exactly one winner; removing one ref moves only that ref's hosts). |
| - [ ] **Step 2:** Run → FAIL. |
| - [ ] **Step 3:** Implement. Write after the group-reference wait, alongside `lease.SetSelf`. |
| - [ ] **Step 4:** `go test ./internal/boxself ./internal/host -run 'BoxSelf|SelfRef'` → PASS. |
| @@ -78,9 +82,9 @@ |
| **Files:** Modify `internal/lease/check.go:88`; test `internal/lease/check_test.go`. |
| **Interfaces:** |
| -- Produces: `func VerifyReplicaAt(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error)`: restores exactly through `txid` (Litestream restore options' TXID), runs `CheckDB`, returns the change counter, removes the file before returning as today. `VerifyReplica` becomes `VerifyReplicaAt(..., 0)` (0 = latest), unchanged for its callers. |
| +- Produces: `func VerifyReplicaAt(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error)`: restores exactly through `txid` (Litestream restore options' TXID) under `ctx`, runs `CheckDBContext(ctx, path)` (`check.go:44`; not `CheckDB`, which uses `context.Background()`) (P-10), returns the change counter, removes the file before returning on every path. `VerifyReplica` becomes `VerifyReplicaAt(..., 0)` (0 = latest), unchanged for its callers. |
| -- [ ] **Step 1: Failing test:** `TestVerifyReplicaAtStopsAtTheTarget` (replicate three batches; pin to the second batch's TXID; the restored counter equals a restore of batch two, not three). |
| +- [ ] **Step 1: Failing tests:** `TestVerifyReplicaAtStopsAtTheTarget` (replicate three batches; pin to the second batch's TXID; the restored counter equals a restore of batch two, not three); `TestVerifyReplicaAtHonoursCancel` (a cancelled context stops it and leaves no file in `dir`). |
| - [ ] **Step 2:** `go test ./internal/lease -run VerifyReplica` → FAIL. |
| - [ ] **Step 3:** Implement. |
| - [ ] **Step 4:** PASS, existing `VerifyReplica` tests included. |
| @@ -93,14 +97,14 @@ |
| **Interfaces:** |
| - Produces: |
| - `func KeyFor(ref string) string` → `"control/verify/" + ref + ".json"`; refuses an invalid ref. The old `Key` constant is removed. |
| - - `Verdict` v2 fields: `Result string` (`passed|failed|unverified`), `Reason string`, `Identity Identity` (a struct in `dbverify` mirroring `dbreads.Identity` field for field, so the leaf package imports nothing new; Task 5 converts), `Prefix string`, `BracketOpenedAt, VerifiedAt time.Time`, `TXID uint64`, `WrittenAt time.Time`, `RestoredBytes int64`, `Freshness string` (`stale|unknown|not_stale`), `UnverifiedRuns int`, `FirstSeen time.Time`. `OK`/`Unverified` stay as derived accessors for `Failures()`/`Unverified()`. |
| + - `Verdict` v2 fields: `Result string` (`passed|failed|unverified`), `Reason string`, `Identity Identity` (a struct in `dbverify` mirroring `dbreads.Identity` field for field, so the leaf package imports nothing new; Task 5 converts), `Prefix string`, `BracketOpenedAt, VerifiedAt time.Time`, `TXID uint64`, `WrittenAt time.Time`, `RestoredBytes int64`, `Freshness string` (`stale|unknown|not_stale`), `UnverifiedRuns int`, `FirstSeen time.Time`, `LastDecidedAt time.Time` (advanced only by `passed`/`failed`) (P-12). `OK`/`Unverified` stay as derived accessors for `Failures()`/`Unverified()`. |
| - `Record{V: 2, Box: ref, CheckedAt, Hosts map[string]Verdict}`. |
| - - `func Merge(prior *Record, ref string, now time.Time, fleet []string, results map[string]Verdict) *Record`: keeps unvisited fleet hosts, drops hosts not in the fleet, adds never-seen fleet hosts as `unverified`/`not_reached` with `FirstSeen = now`, carries `FirstSeen`, and sets `UnverifiedRuns` to prior+1 for an unverified result (except `not_reached`), else 0. |
| + - `func Merge(prior *Record, ref string, now time.Time, fleet []string, results map[string]Verdict) *Record`: keeps unvisited fleet hosts, drops hosts not in the fleet, adds never-seen fleet hosts as `unverified`/`not_reached` with `FirstSeen = now`, carries `FirstSeen`, and sets `UnverifiedRuns` to prior+1 for an unverified result (except `not_reached`), else 0. `LastDecidedAt` carries over through unverified results; when a result's identity differs from the prior verdict's, `FirstSeen`, `LastDecidedAt` and `UnverifiedRuns` reset (P-12). |
| - `func Load(ctx, s release.Store, ref string) (*Record, error)`, `func Publish(ctx, s release.Store, rec *Record) error` (CAS on `KeyFor(rec.Box)`), `func RemoveHost(ctx, s release.Store, ref, host string) error`. |
| - `ChangeScope("control/verify/<ref>.json")` → `"control/verify/<ref>", true`; anything deeper or without `.json` → false. |
| - The mutation classifier gains `{prefix: "control/verify/"}` in place of the old exact row. |
| -- [ ] **Step 1: Failing tests:** extend `TestMerge*` for `FirstSeen`, `UnverifiedRuns` (three unverified runs → 3; a pass resets; `not_reached` doesn't count); `TestPublishWritesOnlyItsOwnKey` (two refs, interleaved publishes, each record intact); `TestRemoveHostOwnRecordOnly`; `TestChangeScope` cases for `control/verify/`; the classifier's table test. |
| +- [ ] **Step 1: Failing tests:** extend `TestMerge*` for `FirstSeen`, `UnverifiedRuns` (three unverified runs → 3; a pass resets; `not_reached` doesn't count), `LastDecidedAt` (a pass six days ago then two unverified nights keeps the pass's time; an identity change resets); `TestPublishWritesOnlyItsOwnKey` (two refs, interleaved publishes, each record intact); `TestRemoveHostOwnRecordOnly`; `TestChangeScope` cases for `control/verify/`; the classifier's table test. |
| - [ ] **Step 2:** `go test ./internal/dbverify ./internal/release ./internal/hostops -run 'Merge|Publish|RemoveHost|ChangeScope|Classif'` → FAIL. |
| - [ ] **Step 3:** Implement. |
| - [ ] **Step 4:** PASS. |
| @@ -111,20 +115,27 @@ |
| **Files:** Modify `internal/ops/ops.go:260-380` (`runHibernateVerify`), `internal/ops/hibernate_verify.go`; tests in `internal/ops/hibernate_verify_test.go`. |
| **Interfaces:** |
| -- Consumes: Tasks 1-4. |
| +- Consumes: Tasks 1-4; `boxchoice.HRW` and `boxself.Read` (Task 2). |
| - Produces: |
| - `HibernatingRoute` gains `Account, App string` (from `registry.Route`). |
| - `func VerifyHibernating(ctx context.Context, d Drill, hosts []HibernatingRoute, now func() time.Time, publish func(map[string]dbverify.Verdict)) map[string]dbverify.Verdict`, where `type Drill struct { Cfg *activator.Config; Store release.Store; Region, SelfRef, TmpDir string; Budget time.Duration; Max int; PublishEvery time.Duration }`. |
| - Flags: `-budget` (default `45m`), `-max` (default 0), `-publish-every` (default `10m`, hidden). |
| - The local alert copy: after each publish, the record is also written atomically to `<data>/monitor/verify.json`. |
| -Per host, in order: `CaptureIdentity` (on a code: `unverified` with that reason, next host) → `PlanFrom(ctx, rd, time.Time{})` (`ErrNothingReplicated` → `unverified`/`nothing_replicated`) → `VerifyReplicaAt(..., plan.TXID)` → `ConfirmIdentity` (on a code: discard, `unverified`) → freshness: `lease.LockState`, `hafresh.ParseOwner`, and if `Ref == SelfRef` the existing `hibernateFreshness`, else `unknown` → verdict with the plan's `TXID`, `At`, `RestoredBytes`. A restore or integrity error → `failed`/`restore_error`; a proved stale replica → `failed`/`stale`. Stop starting hosts when the budget is spent; record the rest as `not_reached` through `Merge`. |
| +Host selection: fixed box, every local sleeping host; group box, only hosts with `boxchoice.HRW(host, self.Serving) == self.Ref`, and none if `self.ServingAt` is older than 15 minutes (those become `not_reached`, reason `no_roster`) (P-9). |
| + |
| +Per host, in order: `CaptureIdentity` (on a code: `unverified` with that reason, next host) → `PlanFrom(ctx, rd, time.Time{})` → `VerifyReplicaAt(ctx, ..., plan.TXID)` → **`ConfirmIdentity` before any outcome is recorded**, including an empty plan, a plan error, a restore error and an integrity failure (on a code: discard, `unverified`) (P-11) → only then: `ErrNothingReplicated` → `unverified`/`nothing_replicated`; restore or integrity error → `failed`/`restore_error`; otherwise freshness: `lease.LockState` must return no error and `held`, `hafresh.ParseOwner` must succeed and `Ref == self.Ref`, then the existing `hibernateFreshness` (stale → `failed`/`stale`); in every other case `unknown`, with no local database read (P-14) → verdict with the plan's `TXID`, `At`, `RestoredBytes`. The run context carries the budget's deadline into every step (P-10); when it expires, the host in progress is abandoned (scratch removed, no verdict) and the rest become `not_reached` through `Merge`. |
| + |
| +Empty fleet (P-13): if this box has no hosts to drill but `dbverify.Load` finds a prior record, it publishes an empty contribution and rewrites the local alert copy; if there is no prior record, it publishes nothing. |
| - [ ] **Step 1: Failing tests:** |
| - `TestVerifyHibernatingBindsIdentity` (verdict carries identity, prefix, TXID, `WrittenAt`, bytes, bracket time). |
| - - `TestVerifyHibernatingRecreateDuringRestore` and `TestVerifyHibernatingMoveDuringRestore` (inject the change between plan and confirm → `unverified`, no pass). |
| - - `TestVerifyHibernatingFreshnessOnlyOnLeaseHolder` (lock owned by another ref: no local source read, `unknown`, not failed; owned by self: stale detected as today). |
| + - `TestVerifyHibernatingBracket`: a table of deletion, same-account recreate, cross-account recreate and move, each injected during planning and during download, each combined with a successful restore, an empty plan, a restore error and an integrity failure: always `unverified` with `record_changed` or `moving`, never `failed` or `passed` (P-11). |
| + - `TestVerifyHibernatingFreshnessOnlyOnLeaseHolder`: lock held by another ref, expired self-owned lock, absent lock, malformed owner, unreadable lock → `unknown`, the local source never opened; held by self → stale detected as today (P-14). |
| - `TestVerifyHibernatingBudget` (fake clock; budget reached after N hosts; the rest `not_reached`; oldest first kept). |
| + - `TestVerifyHibernatingDeadlineStopsBlockedWork`: a reader that blocks during download; at the deadline the step returns, scratch is empty, and the hosts finished before it are published through the separate publish context (P-10). |
| + - `TestVerifyHibernatingGroupAssignment`: three boxes sharing a serving roster each drill a disjoint set covering every host; a stale roster drills none and marks them `no_roster` (P-9). |
| + - `TestRunHibernateVerifyEmptyFleetClearsPrior`: a prior record with one host, then a run with none, publishes an empty record and an empty local copy; with no prior record nothing is published (P-13). |
| - `TestVerifyHibernatingPublishesPeriodically` (publish called at each 10-minute mark and at the end with everything finished so far). |
| - `TestRunHibernateVerifyRefusesWithoutSelfRef` (no `self.json`: no publish, non-zero exit, log names the file). |
| - `TestRunHibernateVerifyWritesLocalAlertCopy`. |
| @@ -140,7 +151,7 @@ Per host, in order: `CaptureIdentity` (on a code: `unverified` with that reason, |
| - [ ] **Step 1: Failing test:** update `TestBootstrapPlanJSONNamesWhatALiveRunArms` so the timer is armed and only `carlos-restore-verify.timer` stays inert. |
| - [ ] **Step 2:** `go test ./internal/host -run 'TestBootstrapPlan|Units'` → FAIL. |
| -- [ ] **Step 3:** Implement. A box with no sleeping hosts runs, finds none, publishes nothing, and exits 0. |
| +- [ ] **Step 3:** Implement. A box with no sleeping hosts runs and exits 0, publishing only as Task 5's empty-fleet rule says. |
| - [ ] **Step 4:** PASS. |
| - [ ] **Step 5:** Commit. |