| new file mode 100644 |
| index 000000000..a2daa8b53 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-08-instance-restore-658.md |
| @@ -0,0 +1,183 @@ |
| +# Instance restore (#658) Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** Let the owner of a deleted plain instance create it again on the same hostname with `restore: true` and wake with its own data, while every other create keeps the never-reuse rule. |
| + |
| +**Architecture:** The original create records provenance (`host_allocations.restore_origin`); delete records proven evidence of the retired body (`record_retirements.record_body`, `restorable`). One function, `restoreProof`, decides every restore in two stages (ownership answers S1, eligibility answers R2, R4 to R8), called early at the door and again at the mark step under the create's locks. A randomized simulation guards it. |
| + |
| +**Tech Stack:** Go, the console's SQLite store, the release store (bucket control plane), `internal/console` tests. |
| + |
| +**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. |
| + |
| +## Global Constraints |
| + |
| +- Every change is in `internal/console` (and docs). Nothing in the root binary changes; Task 8 confirms with `make census-card`. |
| +- A create without `restore` behaves exactly as today: S1, S4, S5 and the leftover rail are unchanged for it (spec §2 anti-goals). Every task that touches a shared path adds a test proving that. |
| +- 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. |
| +- 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. |
| + |
| +## Review Focus |
| + |
| +1. A restore and an ordinary create of the same hostname at the same moment: one wins, the other answers its normal refusal; never two records. (Task 6, `TestRestoreRacesOrdinaryCreate`.) |
| +2. A restore retried after it succeeded: the same answer an ordinary create gives for an existing record (`instance <host> already exists`, 409), not R8. (Task 6, `TestRestoreRetriedAfterSuccess`.) |
| +3. A restore while the delete's retirement is still pending: R1 (try again), and a later retry passes once it settles. (Task 5, `TestRestoreProofPendingRetirement`.) |
| +4. Delete, restore, delete, restore: the second restore passes (lineage of origin plus `restore_of` rows). (Task 6, `TestRestoreTwice`.) |
| +5. A restore whose request names the console's own region explicitly, or names none: both pass; any other region is R5. (Task 6, `TestRestoreRegion`.) |
| + |
| +## Per-task review (AGENTS.md stopping rule 3) |
| + |
| +Tasks 3, 4, 5 and 6 touch a security gate (the hostname history and the create door) and get their own cross-family review (Astra) at most three rounds each. Tasks 0, 1, 2, 7 and 8 are covered by the whole-branch Astra review before merge. Briefs follow `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. |
| + |
| +--- |
| + |
| +### Task 0: Copy review |
| + |
| +**Files:** |
| +- Create: `docs/superpowers/notes/instance-restore-658-copy.json` (the deck) |
| + |
| +- [ ] **Step 1:** Extract spec §7's strings into the deck: R1, R2, R4, R5, R6, R7, R8, C2, and the `docs/site/cli.md` section "Restoring a deleted instance" (draft it: what restore does, that only instances created after this release can be restored, the plain-instance and own-region limits, the `--restore` flag and the `restore: true` body field). |
| +- [ ] **Step 2:** Run the copy-review skill on the deck and wait for Paul's edits (or the reviewer he names). |
| +- [ ] **Step 3:** Commit the approved deck verbatim. Later tasks copy strings from it, never from the spec. |
| + |
| +### Task 1: Inventories (no code) |
| + |
| +**Files:** |
| +- Create: `docs/superpowers/notes/instance-restore-658-task1.md` |
| + |
| +- [ ] **Step 1:** List every writer of `record_retirements` (`BeginRetirement`, `BeginCancellingRetirement`, `ConvertRetirementKind`, any other) and every path that removes or tombstones a data-kind record (delete door, import rollback, seed cleanup, demo claim, app trash and purge, `deleteUnderRetiredSlot`, migration, recovery). For each: does it take spec §5's rule (only a normal retirement with a proven tombstone becomes restorable), or does it leave no restorable row? Any path that does neither is a finding for Task 4. |
| +- [ ] **Step 2:** The sibling-box warm-file check (spec §6): can a platform box in a region, other than the last one that served a host, hold a file at that host's derived path, and would a wake there prefer it over a newer replica? Answer for a hibernated instance. If yes, draft a discussion (type Issue) with the scenario; do not change restore. |
| +- [ ] **Step 3:** Confirm whether `HostUse.Account` and `Allocation.Account` hold the sqid or the account id (`recordUse`, hostsused.go:668; `createRecordWithLifetimeLocked`, lifetimes_create.go:124). State the comparison `restoreProof` must use. |
| +- [ ] **Step 4:** Commit the note. Stop and report to the controller before Task 4 if Step 1 found a path that does neither. |
| + |
| +### Task 2: Store columns and accessors |
| + |
| +**Files:** |
| +- Modify: `internal/console/store.go` (migrations list near :519-531) |
| +- Modify: `internal/console/lifetimes_store.go` |
| +- Test: `internal/console/lifetimes_store_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `Allocation` gains `RestoreOrigin bool` and `RestoreOf string`; `BeginAllocation` writes them. |
| + - `Retirement` gains `RecordBody []byte`; `BeginRetirement` writes it (nil allowed). |
| + - `func (s *Store) HostLineage(host string) ([]Allocation, error)`: every non-`void` allocation row for host, ascending by incarnation, all columns. |
| + - `func (s *Store) NewestRetirement(host string) (*RetirementEvidence, error)`: the row with the highest incarnation (ties: latest `created_at`), or nil. |
| + - `type RetirementEvidence struct { Retirement; RecordBody []byte; Restorable bool }` |
| + - `func (s *Store) MarkRetirementRestorable(opID string) error`: sets `restorable = 1` on a `normal` row only; errors on any other kind or a missing row; idempotent. |
| + |
| +- [ ] **Step 1: Write the failing tests** `TestAllocationRestoreColumns` (round-trip `RestoreOrigin`, `RestoreOf` through `BeginAllocation` and `HostLineage`; a `void` row is excluded; order is by incarnation), `TestRetirementEvidence` (round-trip `RecordBody`; `NewestRetirement` picks the highest incarnation; `MarkRetirementRestorable` on a cleanup or orphan row errors and leaves `Restorable` false; twice on a normal row is nil), `TestRestoreColumnsMigrateOldRows` (a database created by the previous schema opens; old rows read `RestoreOrigin=false`, `RestoreOf=""`, `RecordBody=nil`, `Restorable=false`). |
| +- [ ] **Step 2:** Run `go test ./internal/console -run 'TestAllocationRestoreColumns|TestRetirementEvidence|TestRestoreColumnsMigrateOldRows'`. Expected: FAIL (fields undefined). |
| +- [ ] **Step 3:** Add the migrations: `ALTER TABLE host_allocations ADD COLUMN restore_origin INTEGER NOT NULL DEFAULT 0;`, `ALTER TABLE host_allocations ADD COLUMN restore_of TEXT NOT NULL DEFAULT '';`, `ALTER TABLE record_retirements ADD COLUMN record_body BLOB;`, `ALTER TABLE record_retirements ADD COLUMN restorable INTEGER NOT NULL DEFAULT 0;`. Implement the accessors; extend `retirementInsert` and every SELECT that scans these tables. |
| +- [ ] **Step 4:** Run the same tests, then `go test ./internal/console -run 'Lifetime|Retire|Allocation'`. Expected: PASS. |
| +- [ ] **Step 5:** Commit `console: restore columns on allocations and retirements (#658)`. |
| + |
| +### Task 3: Record the origin at create |
| + |
| +**Files:** |
| +- Modify: `internal/console/hostsused.go` (`markHost` :604, `markForCreate` :631) |
| +- Modify: `internal/console/lifetimes_create.go` (:138-146) |
| +- Test: `internal/console/restore_origin_test.go` (new) |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `Allocation.RestoreOrigin`. |
| +- Produces: |
| + - `type markObservation struct { result markResult; fresh, active bool }`; `markHost` returns `(markObservation, *doorRefusal)`. `markPass`/`markConflict` keep their meaning; `markBeforeCreate` behaves exactly as today. |
| + - `markForCreate(ctx, u) (markObservation, *doorRefusal)`. |
| + - In `createRecordWithLifetimeLocked`: `a.RestoreOrigin = rec.DataKind() && obs.fresh && obs.active && s.lifetimesOn() && rec.Seed == nil` (plus any import marker Task 1 names), set before `BeginAllocation`. A restore never sets it (Task 6 sets `RestoreOf`). |
| + |
| +- [ ] **Step 1: Write the failing tests** on `newLtOn` with the history forced active (`forceHostsState`): `TestOriginOnFreshActiveCreate` (plain data-kind create: `HostLineage` has one row with `RestoreOrigin`), `TestNoOriginBeforeActivation` (mode incomplete: no origin), `TestNoOriginOnSeed` (a `--from` seed create: no origin), `TestNoOriginOnExemptKind` (static: no row or no origin), `TestNoOriginLifetimesOff` (lifetimes off: no allocation row at all), `TestMarkStepUnchangedForCreates` (S1 on a conflicting mark once active, `markPass` before activation, exactly as before). |
| +- [ ] **Step 2:** Run them. Expected: FAIL on the origin assertions. |
| +- [ ] **Step 3:** Implement as the Interfaces block says. |
| +- [ ] **Step 4:** Run them plus `go test ./internal/console -run 'HostsUsed|Mark|LifetimeCreate'`. Expected: PASS. |
| +- [ ] **Step 5:** Commit `console: record a restore origin on a fresh create (#658)`. |
| + |
| +### Task 4: Proven retirement evidence |
| + |
| +**Files:** |
| +- Modify: `internal/console/lifetimes_retire.go` (`retireRecordWithLifetimeLocked` :171, `retirementStepsLocked` :230-330) |
| +- 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. |
| + |
| +- [ ] **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 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` |
| + |
| +**Files:** |
| +- Create: `internal/console/restore.go` |
| +- Test: `internal/console/restore_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 2-4; `hostsMode`, `lifetimesOn`, `cfg.HostClaim`, `provision.ReadHostIncarnation`, `hostSettling`, `provision.HostsUsedKey`. |
| +- 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). |
| +- [ ] **Step 2:** Run `go test ./internal/console -run 'TestRestoreProof'`. Expected: FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** Run. Expected: PASS. |
| +- [ ] **Step 5:** Commit `console: one proof decides every restore (#658)`. |
| + |
| +### Task 6: The door |
| + |
| +**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) |
| +- 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. |
| + - 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 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 5:** Commit `console: restore a deleted instance through the create door (#658)`. |
| + |
| +### Task 7: Guard simulation |
| + |
| +**Files:** |
| +- Create: `internal/console/restore_sim_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: the real create, delete and recovery paths on `newLtOn`-style fixtures; `forceHostsState`; the fixture clock. |
| + |
| +- [ ] **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 4:** Commit `console: simulate restore provenance (#658)`. |
| + |
| +### Task 8: Docs, census, handoff |
| + |
| +**Files:** |
| +- Modify: `docs/site/cli.md` (beside :1230, Task 0's approved section, verbatim) |
| + |
| +- [ ] **Step 1:** Add the section. |
| +- [ ] **Step 2:** Run `make census-card`. Expected: no unit or envelope changed. If anything did, stop and run the census process in AGENTS.md. |
| +- [ ] **Step 3:** Draft the CLI's `--restore` flag request for the carlos CLI repo as an amadan discussion there, citing the body field. |
| +- [ ] **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. |