carlos / platform Public

plan #658 rev 2: answer Astra plan round 1

Lock-free proof, duplicate verdict, staging inside the proof, built-record
shape at the deciding call, evidence only for a captured body, stamp
store for the fixed trace, named legacy and enrolment witnesses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d50195c6a39413e5706b3a19a80eefc2f565e860 parent b769582
3 files changed, +200 −27
  • docs/superpowers/plans/2026-11-08-instance-restore-658.md +48 −27
  • docs/superpowers/plans/CODEX-FINDINGS-instance-restore-658-plan-R1.md +113 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-restore-658-plan-R2.md +39 −0
diff --git a/docs/superpowers/plans/2026-11-08-instance-restore-658.md b/docs/superpowers/plans/2026-11-08-instance-restore-658.md
index a2daa8b53..447e69f7c 100644
--- a/docs/superpowers/plans/2026-11-08-instance-restore-658.md
+++ b/docs/superpowers/plans/2026-11-08-instance-restore-658.md
@@ -10,6 +10,8 @@
**Spec:** `docs/superpowers/specs/2026-11-07-instance-restore-658-design.md` (rev 5, approved by Paul 2026-11-08). Read it first; this plan argues from it and does not repeat its reasoning.
+**Plan rev 2** (2026-11-08) answers Astra plan round 1 (`CODEX-FINDINGS-instance-restore-658-plan-R1.md`, NOT READY: P1 1-3, P2 4-8); dispositions at the end.
+
## Global Constraints
- Every change is in `internal/console` (and docs). Nothing in the root binary changes; Task 8 confirms with `make census-card`.
@@ -17,7 +19,8 @@
- A source that cannot be read refuses (R1 at the door, `errLifetimePending`-style in the core), never passes.
- Restore only: lifetimes on, `@mode` `active`, claims off; console's own region; plain shape (spec §4 stage 2 item 5).
- Copy: user-facing strings only as approved in Task 0, verbatim. No em dashes in copy.
-- Local verification: changed packages only with `-run`; CI runs the full suite. Simulations run niced and bounded.
+- Local verification: changed packages only with `-run`; CI runs the full suite. Simulations run niced locally and are bounded in code (CI runs `go test` without `-short`, .amadan/test-gate.sh:225), so the full-length run must stay under 60 s on one core.
+- Locks: `restoreProof` never takes the app or hostname lock. The early call holds neither and is advisory; the deciding call runs inside `createRecordWithLifetimeLocked`, which already holds both (lifetimes_create.go:47-49). Never call `hostSettling` or `withAppHost` from it (non-reentrant, lifetimes.go:181, applocks.go:38).
- 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 branch.
@@ -100,35 +103,41 @@ Tasks 3, 4, 5 and 6 touch a security gate (the hostname history and the create d
**Files:**
- Modify: `internal/console/lifetimes_retire.go` (`retireRecordWithLifetimeLocked` :171, `retirementStepsLocked` :230-330)
+- Modify: `internal/console/lifetimes_store.go` (`ConvertRetirementKind` :261)
- Test: `internal/console/restore_retire_test.go` (new)
**Interfaces:**
- Consumes: Task 2's `Retirement.RecordBody`, `MarkRetirementRestorable`.
-- Produces: a normal retirement row carries the captured body; it becomes restorable when, and only when:
- - N1's `WriteRecord` returns nil (mark immediately after, before N2); or
- - a later round or recovery observes, before any deletion of it, a tombstone at the key with `Retired`, `Incarnation == r.Incarnation` and `RecordSeq == seq(RecordBody) + 1` (`provision.RecordSequence`), in the `retired` branch (before `deleteUnderRetiredSlot`) or the `rec.Retired && rec.Incarnation == r.Incarnation` branch (before `retireSlotStep`).
-- The body stored is `obs.Raw` of the observation whose ETag is `RecordETag`; when the record was migrated in the same call (the `rec.Incarnation == 0 && slot == nil` branch), store nil.
+- Produces: a normal retirement row carries the captured body, `obs.Raw` of the observation whose ETag is `RecordETag`. When the record was migrated in the same call (the `rec.Incarnation == 0 && slot == nil` branch, :142), store nil. A row with a nil `RecordBody` (same-call migration, or a row pending from before the columns existed) is never marked.
+- A row with a non-nil body becomes restorable when, and only when, its tombstone is proven, and the mark is persisted before N2 or N3 can run:
+ - N1's `WriteRecord` against `RecordETag` returns nil: mark immediately. If the mark write fails, return pending (do not go on to N2), so recovery can still observe the tombstone.
+ - A later round or recovery observes, before any deletion of it, a tombstone at the key with `Retired`, `Incarnation == r.Incarnation` and `RecordSeq == seq(RecordBody) + 1` (`provision.RecordSequence`): in the `retired` branch before `deleteUnderRetiredSlot`, and in the `rec.Retired && rec.Incarnation == r.Incarnation` branch before `retireSlotStep`. Same failure rule.
+- `ConvertRetirementKind` clears `restorable` and `record_body` in the same UPDATE that changes the kind, so a cleanup row never keeps restore evidence.
-- [ ] **Step 1: Write the failing tests:** `TestDeleteLeavesRestorableEvidence` (create, delete through the door: `NewestRetirement` is committed, restorable, body equals the record before delete), `TestLostN1ResponseProvenByRecordSeq` (the bucket accepts N1's write but returns an error; recovery runs: restorable), `TestAbsentRecordNotRestorable` (record removed under a live slot before N1: committed, not restorable), `TestCleanupConversionNotRestorable` (corrupt body: converted, not restorable), `TestForeignTombstoneNotRestorable` (a tombstone whose `record_seq` is not candidate+1: not restorable), `TestMigratedDeleteNotRestorable` (legacy record migrated by the delete: body nil, not restorable), plus one test per extra path Task 1 found.
+- [ ] **Step 1: Write the failing tests:** `TestDeleteLeavesRestorableEvidence` (create, delete through the door: `NewestRetirement` is committed, restorable, body equals the record before delete), `TestLostN1ResponseProvenByRecordSeq` (the bucket accepts N1's write but returns an error; recovery runs: restorable), `TestEvidenceWriteFailureStaysPending` (N1 lands, `MarkRetirementRestorable` fails: the row stays pending and the tombstone is still present; the next recovery marks it and finishes), `TestAbsentRecordNotRestorable` (record removed under a live slot before N1: committed, not restorable), `TestCleanupConversionNotRestorable` (corrupt body before N1: converted, not restorable), `TestConversionAfterMarkClearsEvidence` (N1 lands and is marked, the body is then replaced by corrupt bytes, the row converts to cleanup and completes: not restorable, body nil), `TestForeignTombstoneNotRestorable` (a tombstone whose `record_seq` is not candidate+1: not restorable), `TestMigratedDeleteNotRestorable` (legacy record migrated by the delete: body nil, N1 succeeds, not restorable), `TestOldPendingRowNotRestorable` (a normal row written without a body completes: not restorable), plus one test per extra path Task 1 found.
- [ ] **Step 2:** Run them. Expected: FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** Run them plus `go test ./internal/console -run 'Retire|Lifetime'`. Expected: PASS.
- [ ] **Step 5:** Commit `console: keep proven evidence of a retired record (#658)`.
-### Task 5: `restoreProof`
+### Task 5: `restoreProof` and the staging check
**Files:**
-- Create: `internal/console/restore.go`
+- Create: `internal/console/restore.go`, `internal/console/restore_staging.go`
- Test: `internal/console/restore_test.go`
**Interfaces:**
-- Consumes: Tasks 2-4; `hostsMode`, `lifetimesOn`, `cfg.HostClaim`, `provision.ReadHostIncarnation`, `hostSettling`, `provision.HostsUsedKey`.
+- Consumes: Tasks 2-4; `hostsMode`, `lifetimesOn`, `cfg.HostClaim`, `provision.ReadHostIncarnation`, `s.store.PendingForHost(host, "")` (non-locking; never `hostSettling`), `s.readRecord`, `homeRegionIn` (apiinstancemove.go:324).
- Produces:
- - `type restoreAsk struct { Account, App, Lifetime, Host, Region string; Shape provision.Record; From, Import bool }`: `Region` is the request's ("" for none); `Shape` the record the door built.
- - `type restoreVerdict struct { Owner bool; Refusal *doorRefusal; Region string; RetirementOp string; Body *provision.Record }`. `Owner` false means answer S1 (`msgHostUsed`, 409) unless `Refusal` is an R1. `Refusal` nil with `Owner` true means eligible.
- - `func (s *Server) restoreProof(ctx context.Context, ask restoreAsk) restoreVerdict`, implementing spec §4 in its order: stage 1 (mark and slot name the account and app, compared as Task 1 Step 3 says), then stage 2 items 1-5 and region (item 6). Staging (R6) is not here; Task 6 lists it after this passes. Refusals use Task 0's strings: R1 503, R2 409, R4 409, R5 409, R7 409, R8 409 (the builder may pick 422 for R7 if the door already uses it for shape refusals; say so in the commit).
-
-- [ ] **Step 1: Write the failing table test** `TestRestoreProof` over a fixture that creates `shop.example.com` with lifetimes on and the history active, deletes it, then mutates one input per row: foreign account mark (Owner false), foreign app slot (Owner false), inventory mark with no owner (Owner false), unreadable mark (R1), mode incomplete (R2), lifetimes off (R2), claims on (R2), slot live (R8), no origin row (R8), a lineage row with neither flag (R8), a lineage row on another app lifetime (R4), no row at the slot's incarnation (R8), newest retirement not restorable (R8), stored body seeded (R7), request `From` (R7), stored body in another region (R5), request region different (R5), all good (eligible, `Region == s.cfg.Region`, `Body` equal to the deleted record). Plus `TestRestoreProofPendingRetirement` (Review Focus 3: R1 while pending, eligible after the retirement settles).
+ - `func (s *Server) hostHasStaging(ctx context.Context, host string) (bool, error)`: lists `moves/<host>/` (trailing slash) in the console region's data bucket, any object of any name, stops at the first; errors pass through. Same prefix as promotion (backend_exec.go:3849).
+ - `type restoreAsk struct { Account, App, Lifetime, Host, Region string; Shape *provision.Record; From, Import bool }`. `Region` is the request's, normalized with `homeRegionIn` (so naming the home region equals ""). `Shape` is nil at the early call and the record actually being written at the deciding call.
+ - `type restoreVerdict struct { Owner, Duplicate bool; Refusal *doorRefusal; Region string; RetirementOp string; Body *provision.Record }`.
+ - `Owner` false: the door answers S1 (`msgHostUsed`, 409), unless `Refusal` is R1.
+ - `Duplicate` true (owner, and a valid record of this account and app stands under the key): the door answers `instance <host> already exists` (409), as an ordinary create would. Checked right after stage 1, before any eligibility item.
+ - `Refusal` nil with `Owner` true and `Duplicate` false: eligible; `Region` is the record region to write (the stored body's, "" for home).
+ - `func (s *Server) restoreProof(ctx context.Context, ask restoreAsk) restoreVerdict`, in this order: stage 1 (mark and slot name the account and app, compared as Task 1 Step 3 says); the duplicate check; stage 2 items 1 to 4 (pending work by `PendingForHost` answers R1); item 5 on the stored body and on `ask.From`/`ask.Import`, and on `ask.Shape` when non-nil; region (the stored body's region must be the console's own, and `ask.Region`, if not "", must equal it: R5); then `hostHasStaging` (any object R6, error R1). Refusals use Task 0's strings: R1 503, R2 409, R4 409, R5 409, R6 409, R7 409, R8 409 (422 for R7 if the door already uses it for shape refusals; say so in the commit).
+
+- [ ] **Step 1: Write the failing table test** `TestRestoreProof` over a fixture that creates `shop.example.com` with lifetimes on and the history active, deletes it, then mutates one input per row: foreign account mark (Owner false), foreign app slot (Owner false), inventory mark with no owner (Owner false), unreadable mark (R1), a valid record of the owner under the key (Duplicate), mode incomplete (R2), lifetimes off (R2), claims on (R2), slot live with no valid record (R8), no origin row (R8), a lineage row with neither flag (R8), a lineage row on another app lifetime (R4), no row at the slot's incarnation (R8), newest retirement not restorable (R8), stored body seeded (R7), `ask.From` (R7), `ask.Shape` with a pool (R7), `ask.Shape` with HA (R7), stored body in another region (R5), request region different (R5), request naming the home region explicitly (eligible), `moves/<host>/build-state.json` present (R6), staging list error (R1), all good (eligible, `Region` equal to the stored body's, `Body` equal to the deleted record). Plus `TestRestoreProofPendingRetirement` (Review Focus 3: R1 while pending, eligible after the retirement settles) and `TestRestoreProofTakesNoLocks` (call it while holding the app lock and the hostname exclusion for the same host; it returns within 1 s).
- [ ] **Step 2:** Run `go test ./internal/console -run 'TestRestoreProof'`. Expected: FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** Run. Expected: PASS.
@@ -138,23 +147,22 @@ Tasks 3, 4, 5 and 6 touch a security gate (the hostname history and the create d
**Files:**
- Modify: `internal/console/apiinstances.go` (`handleAPIInstanceCreate`: body struct :1565, after host validation :1662, region :1796-1933, leftover rail :2295, dispatch :2509, response :2593-2603)
-- Modify: `internal/console/lifetimes_create.go` (mark step), `internal/console/hostsused.go` (C2 on S1)
-- Create: `internal/console/restore_staging.go` (`func (s *Server) hostHasStaging(ctx context.Context, host string) (bool, error)`: lists `moves/<host>/` with a trailing slash in the console region's data bucket, any object, stops at the first; errors pass through)
+- Modify: `internal/console/lifetimes_create.go` (mark step :138-146)
- Test: `internal/console/restore_door_test.go`
**Interfaces:**
- Consumes: Task 5's `restoreProof`, `restoreAsk`, `restoreVerdict`.
- Produces:
- - Body field `Restore bool \`json:"restore"\``.
- - The restore intent travels to the mark step as `withRestore(ctx, restoreAsk) context.Context` / `restoreFrom(ctx) (restoreAsk, bool)`, set only by `handleAPIInstanceCreate`.
- - At the mark step under the locks: re-run `restoreProof`; on eligible, a `markConflict` is a pass and `a.RestoreOf = verdict.RetirementOp`; anything else answers as the verdict says.
+ - Body field `Restore bool` with tag `json:"restore"`.
+ - The restore intent travels to the core as `withRestore(ctx, restoreAsk) context.Context` / `restoreFrom(ctx) (restoreAsk, bool)`, set only by `handleAPIInstanceCreate`.
+ - At the mark step in `createRecordWithLifetimeLocked`, under the locks it holds: if `restoreFrom(ctx)`, re-run `restoreProof` with `Shape: &rec` (the record about to be written) and act on that verdict alone: eligible makes a `markConflict` a pass and sets `a.RestoreOf = verdict.RetirementOp`; `Duplicate` returns `release.ErrCASConflict` (the core's existing duplicate answer); any other verdict returns its refusal as a `hostsUsedError`.
+ - C2: in the same core, when an ordinary create's mark step answers S1, run `restoreProof` with `Shape: &rec`; if eligible, the refusal message is C2 instead of S1. (`markForCreate` only sees `HostUse`, so the hint is decided here, where the record is.)
- Response gains `"restore": true` on a restore.
- - On an ordinary create's S1, if `restoreProof` (with `Shape` from the request) is eligible, the message is C2 instead of S1.
-- [ ] **Step 1: Write the failing door tests** through the real door (production-wired: real handler, store, `ltStore` bucket): `TestRestoreRoundTrip` (create, write a row to the replica prefix, delete, restore: 201 with `restore: true`, the record's host and region match, incarnation is N+1, the allocation carries `RestoreOf`), `TestRestoreTwice` (Review Focus 4), `TestRestoreRetriedAfterSuccess` (Review Focus 2), `TestRestoreRegion` (Review Focus 5), `TestRestoreStagingRefused` (any object under `moves/<host>/`, including only `build-state.json`: R6; a listing error: R1), `TestRestoreSkipsLeftoverRailOnlyForOwnReplica` (a restore over `instances/<host>` passes; an ordinary create over the same leftovers still gets the rail's refusal), `TestRestoreForeignOwnerSeesOnlyS1` (another account, and another app, each with a conflicting region, staging, missing body and older app lifetime: the response bytes equal an ordinary create's S1), `TestRestoreOwnerSeesDetail` (the rightful owner gets R2, R4, R5, R6, R7, R8 for the same setups), `TestOrdinaryCreateHintsRestore` (C2 for the owner, S1 for anyone else), `TestRestoreRacesOrdinaryCreate` (Review Focus 1, with `pauseGate` between the two evaluations), `TestCreateWithoutRestoreUnchanged` (existing S1, S4, S5, leftover-rail witnesses still pass unmodified; run them by name in Step 4).
+- [ ] **Step 1: Write the failing door tests** through the real door (production-wired: real handler, store, `ltStore` bucket): `TestRestoreRoundTrip` (create, write a row to the replica prefix, delete, restore: 201 with `restore: true`, the record's host and region match, incarnation is N+1, the allocation carries `RestoreOf`), `TestRestoreTwice` (Review Focus 4), `TestRestoreRetriedAfterSuccess` (Review Focus 2: the first restore's response is dropped, the retry answers `instance <host> already exists`, no second allocation), `TestRestoreRecordAppearsBetweenEvaluations` (a record lands after the early proof, paused with `pauseGate`: the locked evaluation answers the duplicate), `TestRestoreRegion` (Review Focus 5: none, the home region named explicitly, and the console's own region all pass; another region is R5; with the app's default region set to another region, a restore still writes the stored body's region), `TestRestoreIgnoresPlacement` (the app gains a fleet placement or manifest pool after the delete: the locked evaluation sees the built record and answers R7), `TestRestoreStagingRefused` (any object under `moves/<host>/`, including only `build-state.json`: R6; a listing error: R1; staging appearing between the evaluations, via `pauseGate`: R6 from the locked one), `TestRestoreSkipsLeftoverRailOnlyForOwnReplica` (a restore over `instances/<host>` passes; an ordinary create over the same leftovers still gets the rail's refusal), `TestRestoreForeignOwnerSeesOnlyS1` (another account, and another app, each with a conflicting region, staging, missing body and older app lifetime: the response bytes equal an ordinary create's S1), `TestRestoreOwnerSeesDetail` (the rightful owner gets R2, R4, R5, R6, R7, R8 for the same setups), `TestOrdinaryCreateHintsRestore` (C2 for the owner; S1 for anyone else; S1, not C2, for the owner when staging holds only `build-state.json` or the staging list fails), `TestRestoreRacesOrdinaryCreate` (Review Focus 1), `TestRestoreAfterLegacyLineageRefused` (spec §8: create with lifetimes off after activation, cut over, delete, purge the app and recreate it under the same name, restore: R4 or R8, never 201), `TestRestoreAfterManagedEnrolment` (create, run `admitManagedHistory` so `@mode.At` moves, delete, restore: 201), `TestCreateWithoutRestoreUnchanged` (existing S1, S4, S5, leftover-rail and lock-order witnesses still pass unmodified; run them by name in Step 4).
- [ ] **Step 2:** Run `go test ./internal/console -run 'TestRestore|TestOrdinaryCreateHintsRestore'`. Expected: FAIL.
-- [ ] **Step 3:** Implement. Order inside the handler: decode, validate host, then if `Restore`: `restoreProof` (S1 or detail), then force the region to the verdict's, then `hostHasStaging` (R6/R1), then the existing checks; the leftover rail skips its `instances/<host>` test for a restore only.
-- [ ] **Step 4:** Run the Step 2 tests, then `go test ./internal/console -run 'HostsUsed|Leftover|LifetimeCreate|InstanceCreate'`. Expected: PASS.
+- [ ] **Step 3:** Implement. Order inside the handler: decode, validate host, then if `Restore`: the early `restoreProof` with `Shape: nil` (S1, duplicate or detail), then skip the region-resolution block (:1796-1933) entirely and set `region = verdict.Region`, keeping `checkPlacement` and every later check; no app-region, nearest-region or fleet placement is consulted. The leftover rail skips its `instances/<host>` test for a restore only. Then the existing path to the core, where the deciding evaluation runs.
+- [ ] **Step 4:** Run the Step 2 tests, then `go test ./internal/console -run 'HostsUsed|Leftover|LifetimeCreate|InstanceCreate|LockOrder'`. Expected: PASS.
- [ ] **Step 5:** Commit `console: restore a deleted instance through the create door (#658)`.
### Task 7: Guard simulation
@@ -163,11 +171,12 @@ Tasks 3, 4, 5 and 6 touch a security gate (the hostname history and the create d
- Create: `internal/console/restore_sim_test.go`
**Interfaces:**
-- Consumes: the real create, delete and recovery paths on `newLtOn`-style fixtures; `forceHostsState`; the fixture clock.
+- Consumes: the real create, delete, recovery and activation paths on `newLtOn`-style fixtures; `forceHostsState`; `admitManagedHistory`.
+- Produces (test-only): `type stampStore struct{ release.Store; next func() time.Time }`, a release-store wrapper that, on a `Put` under `provision.HostsUsedPrefix` (marks and `@mode`), rewrites the body's `at` field to `next()` before passing the write through unchanged otherwise (create-only and CAS semantics kept). The mark and mode writers stamp with `time.Now()` (hostsused.go:613, hostsused_activate.go:441, managedhistory.go:60), which the cutover fixture clock does not reach; this wrapper is how the trace controls those stamps.
-- [ ] **Step 1: Write `TestRestoreRefusesUnmarkedPredecessor`** (spec §4 Guard's fixed trace): fixture with app Q's warm database at the host's derived path on an inventoried box and no mark, slot or allocation; P creates the host with lifetimes on in incomplete mode without a wake; the clock steps back; activation runs with a listing that includes Q's file; P deletes normally; P restores: R8. In the same test, evaluate rev 3's rule (mark `Source == "create"`, names P, `At > @mode.At`) on the final state and assert it would have admitted P, so the trace discriminates.
-- [ ] **Step 2: Write `TestRestoreProvenanceSimulation`:** a seeded generator (`-short`: 50 seeds x 30 steps; full: 400 x 60) over the actions of spec §4 Guard, an oracle recording which (account, app, app lifetime) wrote each hostname's data, and the assertion: a restore answers 201 only when every write under that hostname came from the restoring triple. Print the seed on failure.
-- [ ] **Step 3:** Run `nice go test ./internal/console -run 'TestRestoreRefusesUnmarkedPredecessor|TestRestoreProvenanceSimulation' -short`. Expected: PASS. Then break `restoreProof` stage 2 item 3 locally (drop the origin requirement) and confirm the simulation or the fixed trace fails; restore it.
+- [ ] **Step 1: Write `TestRestoreRefusesUnmarkedPredecessor`** (spec §4 Guard's fixed trace) on `stampStore`: fixture with app Q's warm database at the host's derived path on an inventoried box and no mark, slot or allocation, Q recorded as the writer in the data oracle; P creates the host with lifetimes on in incomplete mode without a wake (mark stamped T=110); activation runs with a listing that includes Q's file (stamped T=100); P deletes normally; P restores: R8. Before the restore, assert the stored stamps (mark 110, mode 100), P's surviving mark, P's slot, and no origin on P's allocation. Then evaluate rev 3's rule (mark `Source == "create"`, names P, `At > @mode.At`) on that state and assert it would admit P, so the trace discriminates.
+- [ ] **Step 2: Write `TestRestoreProvenanceSimulation`:** a seeded generator over the actions of spec §4 Guard (including `stampStore` steps backwards and forwards, and managed enrolment), starting each seed from either an empty store or the Q fixture of Step 1. A data oracle records which (account, app, app lifetime) wrote each hostname's data. Assertions: (a) safety, a restore answers 201 only when every write under that hostname came from the restoring triple; (b) liveness, a restore of a host whose only writer is the restoring triple, created by a plain create after activation with lifetimes on and deleted through a normal retirement with no pending work, answers 201. Bounds: `-short` 50 seeds x 30 steps; otherwise 200 x 40, under 60 s on one core. Print the seed on failure.
+- [ ] **Step 3:** Run `nice go test ./internal/console -run 'TestRestoreRefusesUnmarkedPredecessor|TestRestoreProvenanceSimulation'` and time it. Expected: PASS within the bound. Then break `restoreProof` stage 2 item 3 locally (drop the origin requirement) and confirm the fixed trace or the simulation fails; then break it the other way (refuse whenever `@mode.At` moved after the origin) and confirm liveness fails. Restore both.
- [ ] **Step 4:** Commit `console: simulate restore provenance (#658)`.
### Task 8: Docs, census, handoff
@@ -181,3 +190,15 @@ Tasks 3, 4, 5 and 6 touch a security gate (the hostname history and the create d
- [ ] **Step 4:** Commit `docs: restoring a deleted instance (#658)`. Then the whole-branch Astra review (three rounds at most), CI green on the tip, `amadan branch describe`, and merge only with Paul's go.
After release and the dev roll: the dev witness from spec §8 (create, write a row, delete, restore, read the row back; refusals), reported on #658.
+
+## Plan round 1 dispositions
+
+All accepted.
+1. P1 recursive lock: the proof uses `PendingForHost` and takes no lock (Global Constraints; Task 5 `TestRestoreProofTakesNoLocks`).
+2. P1 duplicate unreachable: `Duplicate` verdict right after stage 1 (Task 5), carried through both evaluations (Task 6).
+3. P1 migrated rows marked: only a non-nil body is ever marked; evidence-write failure stays pending (Task 4).
+4. P2 staging outside the proof: `hostHasStaging` moved into `restoreProof` (Task 5), so the locked evaluation and C2 include it.
+5. P2 effective shape and region: the deciding evaluation sees the built record; the restore skips region resolution; C2 is decided in the core with the record (Task 6).
+6. P2 conversion keeps evidence: `ConvertRetirementKind` clears it (Task 4).
+7. P2 clock: `stampStore` controls mark and mode stamps (Task 7).
+8. P2 required traces: the legacy-lineage and managed-enrolment witnesses are named door tests (Task 6); the Q fixture is a generator start state; liveness is asserted; the full run is bounded in code (Task 7).
diff --git a/docs/superpowers/plans/CODEX-FINDINGS-instance-restore-658-plan-R1.md b/docs/superpowers/plans/CODEX-FINDINGS-instance-restore-658-plan-R1.md
new file mode 100644
index 000000000..b848fe5a9
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-FINDINGS-instance-restore-658-plan-R1.md
@@ -0,0 +1,113 @@
+# Instance restore #658: implementation-plan review, round 1
+
+Reviewed `design-instance-restore-658` at `b769582f394cdb2244cc0810a2d0b581deb4046b`, as requested. The brief names `2dab3aa0b2e91f51682e3d54a776b53a18ac23d0`; the plan is unchanged between those commits. Authorities were the approved rev 5 spec and the existing implementation. The diff against the amadan remote's local `origin/main` (`f864af5efe6ad301a3e507e99c5c07589c24a186`) contains only the nine restore design/review/plan documents, so the inspected implementation is merged code. No subagents or tests were run. Only this findings file was written.
+
+This is implementation-plan round 1. The spec's three completed rounds remain closed; none of the findings below reopens the approved provenance rule or the accepted hibernation guarantee.
+
+## P1
+
+### 1. The proof's pending-operation helper reacquires locks held by its second caller
+
+**Tasks:** 5 and 6.
+
+**Problem and evidence:** Task 5 explicitly consumes `hostSettling` (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:125`), while Task 6 runs the same proof at the mark step under the create's locks (`:150`). `hostSettling` is a locking wrapper: it calls `withAppHost` (`internal/console/lifetimes.go:329`). That wrapper takes the app and hostname locks (`:206`, `:216`). The lifetime create already holds both when it enters `createRecordWithLifetimeLocked` (`internal/console/lifetimes_create.go:47`, `:49`) and reaches its mark step (`:138`). The app lock uses a plain `sync.Mutex` (`internal/console/applocks.go:38`, `:65`); hostname exclusion is also explicitly non-reentrant (`internal/console/lifetimes.go:181`).
+
+**Failure scenario:** An otherwise eligible restore passes the early proof and reaches the second proof. Its call to `hostSettling` waits for the app lock that the same request holds. It never reaches `BeginAllocation`, and the mutex wait does not end when the request context expires. Subsequent work for that app also blocks. Calling the proof from the ordinary create's locked S1/C2 path has the same problem.
+
+**Concrete fix:** Make the pending-operation read inside the proof non-locking, using `PendingForHost(host, "")` or the existing `admit` core (`internal/console/lifetimes.go:224`, `internal/console/lifetimes_store.go:345`). State which caller holds the locks: the early read is advisory; the second read is under the existing create hold. Do not invoke `hostSettling` from that hold. Add a bounded real-door witness and run the existing lock-order witness with it.
+
+**Invariant:** Restore admission must finish under one app/hostname lock hold, without recursive acquisition.
+
+### 2. The early proof makes the promised duplicate response unreachable
+
+**Tasks:** 5 and 6; Review Focus 2.
+
+**Problem and evidence:** The plan promises the ordinary `already exists` response after a successful restore (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:27`, `:154`). However, Task 5 explicitly makes a live slot R8 (`:131`), and Task 6 returns the early proof's refusal immediately after host validation (`:156`). The existing duplicate checks run much later: the leftover rail reads the record and returns its duplicate response (`internal/console/apiinstances.go:2295`, `:2302`, `:2309`; `internal/console/createleftovers.go:151`), and the locked create returns a conflict for a valid record (`internal/console/lifetimes_create.go:213`). Neither is reached after the early R8.
+
+**Failure scenario:** Restore succeeds, but its 201 response is lost. The owner retries the identical request. Ownership still passes, but the slot is now live, so the new early proof returns R8. `TestRestoreRetriedAfterSuccess` fails: the result says restore was unavailable for the old instance instead of saying this instance already exists.
+
+**Concrete fix:** Specify an owner-authorized existing-record check before the live-slot eligibility refusal. Preserve S1 for foreign ownership, R1 for pending work, and R8 for a live slot without a valid existing record. Carry the duplicate result through the door without treating it as restore eligibility; retain the locked duplicate check for races. Include the lost-response retry and a record appearing between the two evaluations.
+
+**Invariant:** Retrying an accepted create must retain the ordinary duplicate response, without weakening ownership or authorizing another allocation.
+
+### 3. Successful N1 marks migrated deletions restorable despite the task's required assertion
+
+**Task:** 4, supported by Task 2.
+
+**Problem and evidence:** Task 4 says to mark a normal row immediately whenever N1's `WriteRecord` returns nil (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:107`). It separately requires a nil candidate body after migration in the same delete call (`:110`) and a test asserting that this row is not restorable (`:112`). Task 2's setter checks only normal kind and row existence (`:71`). On main, the migration branch replaces `rec` and its ETag and then creates a normal retirement (`internal/console/lifetimes_retire.go:142`, `:157`, `:171`). That row proceeds through the same successful N1 write as any other normal retirement (`:317`, `:323`).
+
+**Failure scenario:** Delete a legacy record with lifetimes on. Migration succeeds, the planned candidate body is nil, and N1 succeeds. The specified success hook sets `restorable = 1`, so `TestMigratedDeleteNotRestorable` fails. The same unconditional hook can mark an old pending normal row that was created before the new columns existed. The missing origin may still prevent restore, but the retirement evidence itself contradicts the task's contract.
+
+**Concrete fix:** Make the successful-write rule conditional on a valid captured candidate bound to `RecordETag`. Explicitly leave nil-body rows unmarked, including same-call migrations and old pending retirements. If the candidate cannot be proven, complete retirement without restore evidence. If persisting valid evidence fails, return pending before N2/N3 so recovery can still inspect the tombstone. Add witnesses for both nil-body cases and a failed evidence write.
+
+**Invariant:** A restorable flag attests to the stored candidate body; successful retirement alone is insufficient.
+
+## P2
+
+### 4. Staging is excluded from the shared proof, so the locked evaluation and C2 are incomplete
+
+**Tasks:** 5 and 6.
+
+**Problem and evidence:** The approved spec includes staging in stage 2 and requires both stages to run again under the create locks; C2 requires both stages to pass (`docs/superpowers/specs/2026-11-07-instance-restore-658-design.md:38`, `:50`, `:54`, `:69`). The plan explicitly excludes R6 from `restoreProof` and places it only after the early call (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:129`, `:156`). The locked call and C2 call invoke only that incomplete proof (`:150`, `:152`). The old leftover check cannot substitute: it enumerates LTX files, not arbitrary objects (`internal/console/createleftovers.go:71`, `:85`), while promotion lists and mirrors the entire staging prefix (`internal/activator/backend_exec.go:3849`, `:3862`).
+
+**Failure scenario:** With only `moves/<host>/build-state.json` present, an ordinary create can pass the LTX rail and reach S1. The planned C2 probe says it is eligible and advertises restore, but the actual restore door returns R6. Also, a staging object or listing failure introduced between the early proof and the locked proof is absent from the deciding evaluation. The planned staging test only exercises the early check.
+
+**Concrete fix:** Put `hostHasStaging` inside the shared proof after ownership, shape and region checks, and call it on every deciding evaluation. Move its implementation dependency into Task 5, or an earlier task. Add C2 cases with staging and listing errors, plus a paused-door case changing the staging answer before the locked evaluation.
+
+**Invariant:** The door, the locked admission and the restore hint must use the same complete eligibility rule.
+
+### 5. The plan does not connect the early request shape to the record that will actually be written
+
+**Tasks:** 5 and 6.
+
+**Problem and evidence:** `restoreAsk.Shape` is defined as the record the door built (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:127`), but the proposed first call is immediately after host validation (`:156`). At that point no such record exists: main resolves fleet placement at `internal/console/apiinstances.go:1796`, the channel/runtime at `:2013` and `:2066`, constructs `rec` at `:2091`, sets its runtime at `:2121`, and stamps HA at `:2371`. Task 6 transports the early `restoreAsk` in context (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:149`) without specifying that the final evaluation replaces its shape with the actual `rec`.
+
+The region instruction also needs an explicit branch through this construction. Home records use `""`, even when the caller names the home region (`internal/console/apiinstancemove.go:320`). Merely forcing that empty value before the existing region block leaves app-region defaulting enabled (`internal/console/apiinstances.go:1815`, `:1824`); fleet placement can override it later (`:1922`). The approved spec forbids those placement decisions for a restore (`docs/superpowers/specs/2026-11-07-instance-restore-658-design.md:39`).
+
+**Failure scenario:** After a plain predecessor is deleted, the app acquires a pool or fleet placement. A proof built only from the decoded request sees a plain shape; the later constructor adds the new placement. Replaying the unchanged context value does not validate that resulting record. Likewise, an eligible home restore with no requested region can be redirected by the app's default region if the builder only assigns the early verdict to `req.Region`.
+
+**Concrete fix:** Specify how ownership precedes the reads needed to derive the effective request shape, and how that shape includes manifest pool, placement, runtime and prospective HA. Preserve the request's original region separately, normalize explicit home names, and bypass app/nearest-region selection for restores while retaining placement validation. At the locked evaluation, validate the actual record being passed to the create core. State how ordinary S1 handling supplies its complete shape to C2 too: `markForCreate` currently receives only `HostUse`, which contains no pool, runtime, HA or lifetime (`internal/console/hostsused.go:631`, `:668`; `internal/provision/hostsused.go:51`). Add effective-shape and home-default witnesses.
+
+**Invariant:** The proof must authorize the shape and region actually published, including values derived by the server.
+
+### 6. Cleanup conversion can retain a flag set earlier in the same retirement
+
+**Tasks:** 2 and 4.
+
+**Problem and evidence:** The spec requires conversion to cleanup to leave `restorable` unset (`docs/superpowers/specs/2026-11-07-instance-restore-658-design.md:79`). Task 4 adds marking immediately after N1 and tests a cleanup conversion, but does not specify clearing already-persisted evidence (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:108`, `:112`). The dispatcher observes again on every round (`internal/console/lifetimes_retire.go:253`) and can convert a normal row after observing corruption (`:294`). `ConvertRetirementKind` currently updates only kind and ETag (`internal/console/lifetimes_store.go:265`). Restricting the setter to normal rows does not prevent a marked normal row from subsequently becoming cleanup.
+
+**Failure scenario:** N1 succeeds and evidence is marked. Before the next classification, the record body is replaced by corrupt bytes. The dispatcher converts the pending row to cleanup and completes it. Unless conversion clears the flag, the newest evidence still reports restorable. A test that introduces corruption before N1 will not cover this transition.
+
+**Concrete fix:** Clear `restorable` atomically in the normal-to-cleanup update, and ensure the candidate is no longer usable as restore evidence after its ETag is replaced. Add the sequence successful N1 → marked evidence → corrupt body → cleanup conversion, asserting the final flag is false.
+
+**Invariant:** Cleanup retirement must never retain normal-retirement restore authority.
+
+### 7. The supplied fixture clock cannot drive the timestamp discriminator
+
+**Task:** 7.
+
+**Problem and evidence:** Task 7 consumes the fixture clock and requires a backward step followed by real activation; the old timestamp rule must then admit the final state (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:166`, `:168`). The fixture clock changes only `lifetimesNow` (`internal/console/lifetimes_cutover_test.go:45`). Mark timestamps use `time.Now().UTC()` (`internal/console/hostsused.go:613`), activation uses its own `time.Now().UTC()` (`internal/console/hostsused_activate.go:441`, `:468`), and managed enrollment does likewise (`internal/console/managedhistory.go:60`). None reads that fixture clock.
+
+**Failure scenario:** Implement the fixed trace with `l.clock.Advance` as the named fixture supports. The mark and activation still receive advancing wall-clock timestamps, so the final assertion that rev 3's `mark.At > mode.At` would admit P fails. Omitting that assertion instead lets the test pass without reproducing the earlier timestamp failure.
+
+**Concrete fix:** Add an explicit deterministic timestamp mechanism to the test design: a clock seam used by these writers, or a test store wrapper that assigns controlled timestamps at their writes while preserving their create-only/CAS behavior. Assert the stored timestamps, retained P mark, absent origin and Q data-oracle ownership before comparing the old and new rules. Do not rely on the cutover clock to control unrelated writers.
+
+**Invariant:** The fixed trace must actually discriminate the rejected timestamp rule from the approved origin rule.
+
+### 8. Required delivery witnesses are left to random action selection, and the oracle cannot detect lost eligibility
+
+**Tasks:** 5–7.
+
+**Problem and evidence:** Spec §8 explicitly requires the post-activation lifetimes-off create → cutover → delete → app purge/recreate refusal, and a managed-fleet enrollment after origin that remains restorable (`docs/superpowers/specs/2026-11-07-instance-restore-658-design.md:109`). Neither is a named door witness in Tasks 5 or 6 (`docs/superpowers/plans/2026-11-08-instance-restore-658.md:131`, `:154`). Task 7 includes the spec's actions by reference, but its only required generated assertion is that every accepted restore belongs to the writer triple (`:169`). It does not require either full trace to occur or assert that an eligible restore succeeds.
+
+**Failure scenario:** A regression that refuses every restore after managed enrollment satisfies the simulation's one-way safety assertion. A bounded random run may also never assemble the lifetimes-off/cutover/purge sequence, so it need not exercise round 2's empty-lineage failure. A table row with a manually changed app lifetime is not the real migration-and-recreation witness required by §8.
+
+**Concrete fix:** Add both deterministic real-door traces, with a required refusal for the legacy lineage and a required success after managed enrollment. Keep the randomized actions as additional coverage. Also make the historical Q-data fixture explicitly available as a generator starting state, as §4 Guard requires, rather than only as the separate fixed test. Specify how the simulation runs niced in CI: the plan currently applies `nice` only to its local command (`:170`), while the CI shard invokes ordinary `go test` (`.amadan/test-gate.sh:225`).
+
+**Invariant:** The regression suite must exercise both prior provenance failures and preserve eligibility across unrelated mode-timestamp rewrites.
+
+## P3
+
+None.
+
+**NOT READY**
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-restore-658-plan-R2.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-restore-658-plan-R2.md
new file mode 100644
index 000000000..aae34153a
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-restore-658-plan-R2.md
@@ -0,0 +1,39 @@
+# Review brief: plan "Instance restore (#658)", round 2 of 3
+
+Repo carlos/platform, branch `design-instance-restore-658`, commit 2dab3aa0b2e91f51682e3d54a776b53a18ac23d0.
+Under review: `docs/superpowers/plans/2026-11-08-instance-restore-658.md`.
+Authorities: the approved spec `docs/superpowers/specs/2026-11-07-instance-restore-658-design.md` (rev 5, approved by Paul 2026-11-08 after three Astra rounds; its findings files sit beside it) and the code on main. Do not review against unmerged branches.
+
+You are an independent reviewer. Read the plan and the spec, then the code the plan names, and check every interface, file and line reference against that code.
+
+## Fixed: do not re-argue
+
+- The spec's design and Paul's rulings in it. Report only places where the plan fails to implement the spec, or would not compile or work.
+
+## What to check
+
+1. Coverage: every requirement in spec §3-§8 has a task and a test that would fail without it.
+2. Interfaces: names, signatures and types are consistent across tasks and fit the code (`Allocation`, `Retirement`, `markHost`, `markForCreate`, `createRecordWithLifetimeLocked`, `retirementStepsLocked`, `handleAPIInstanceCreate`).
+3. Order: no task depends on a later one; the two `restoreProof` evaluations really run where the plan places them, under the create's locks.
+4. Task 4's restorable rule: does the plan mark restorable exactly where the spec says, before any deletion of the tombstone, and nowhere else?
+5. Task 7's simulation and fixed trace: would they catch the round 1 and round 2 P1 scenarios as written?
+
+## Round 2
+
+Earlier round: `docs/superpowers/plans/CODEX-FINDINGS-instance-restore-658-plan-R1.md` (NOT READY: P1 1-3, P2 4-8). The plan's "Plan round 1 dispositions" gives the author's answer to each.
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not. Carry every unresolved or partly resolved finding forward at its current severity, then add new findings. Name each finding's fault family; say when one repeats a round 1 family.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the task, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant it breaks. End with exactly one verdict: **READY**, **READY AFTER FIXES**, or **NOT READY**.
+
+Write your findings to `docs/superpowers/plans/CODEX-FINDINGS-instance-restore-658-plan-R2.md` in this worktree and nothing else. Do not edit any other file. Do not spawn subagents. Do not run the full test suites.