carlos / platform Public

plans: P1b-3b plan rev 2 (answers Opus round 1)

Answer the shared duty-authority fault family with one adoption finalizer that takes and releases the ordinary HA lease as the adopter. Add explicit scope refusals, durable identity lookup, authoritative restore and fresh inventory requirements; gate the drill on the delete-permission fix. Record every finding with witnesses, mutations and request costs, and carry round 1 history forward.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev cdfeac5a0a8aba5b7f90d28477ea559c282a5592 parent 4467b0e
1 file changed, +111 −67
  • docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md +111 −67
diff --git a/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md b/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md
index e41555c85..6a34abb79 100644
--- a/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md
+++ b/docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md
@@ -1,18 +1,18 @@
-# Region HA P1b-3b: local duties and departure recovery Implementation Plan — rev 1
+# Region HA P1b-3b: local duties and departure recovery Implementation Plan — rev 2
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. This commission is planning only: no production code, reviewer dispatch, push, release or live drill. Preserve the execution method chosen by the controller.
**Goal:** Recover a terminated box's durable timers and due wakes without visitor traffic, and expose a truthful termination-consumer start/cancel acknowledgment for P3a.
-**Architecture:** One local duty gate selects work; the existing HA acquire remains the writer gate. One termination consumer per box, request-confirmation notifications and cached view ageing feed a durable local departure journal. One import transaction installs wake state before conditional edges deletion. Drain remains a named integration hook until its producer merges.
+**Architecture:** One local duty gate selects work; the existing HA acquire remains the writer gate. One termination consumer per box, request-confirmation notifications and cached view ageing feed a durable local departure journal. One adoption function installs wake state and takes/releases the ordinary HA lease to name the adopter before conditional edges deletion. Drain remains a named integration hook until its producer merges.
**Tech Stack:** Go 1.26, SQLite registries, `hostfiles` manifests/wake state, conditional S3 leases/deletes, the existing EC2/SQS adapters, and `internal/sim/regionha`.
**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, especially §3.1/I3, §4, §7, §9, §18–21. Parent: `docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md`, B1–B5 and Task 5B. Formatting reference: `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md`.
-**Base:** amadan `origin/main` **9a064ebeba6fb07ecce97fdf276f8caa00d90c8a**. Every code citation below is at that commit; new files have no invented line numbers. P1a, P1b-1, P1b-2, dead-holder backoff, P1b-3a, P2a and durability 3a are already merged. Read current code rather than the old plans' line numbers.
+**Base:** worktree implementation base **9a064ebeba6fb07ecce97fdf276f8caa00d90c8a**, unchanged. Read-only main check: home-placement fix **c6304f2d**, also present at observed `origin/main` **c42baa2edaa84d4295bc14e5664ff632e2024b43**. Citations use the worktree except `internal/edge/{homemap,wakeplacement}.go`, read with `git show origin/main:<path>`; those lines are identical at c6304f2d. No rebase. New files have no invented line numbers. P1a, P1b-1, P1b-2, dead-holder backoff, P1b-3a, P2a and durability 3a are already merged. Read current code rather than the old plans' line numbers.
-**Status:** draft executable termination slice, with a separately gated native-sidecar extension. No review verdict claimed. The P3 document was read with `git show origin/region-ha-p3-group:docs/superpowers/plans/2026-11-01-region-ha-p3-group.md`; its :27 and integration row “Termination-start latch / I3,A1” describe a downstream need, not authority to implement unmerged P3 code.
+**Status:** rev 2 answers Opus round 1 (NOT READY); this is an author revision, not a new review verdict. T has executable scope refusals; S remains separately gated. The P3 document was read with `git show origin/region-ha-p3-group:docs/superpowers/plans/2026-11-01-region-ha-p3-group.md`; its :27 and integration row “Termination-start latch / I3,A1” describe a downstream need, not authority to implement unmerged P3 code.
## Rulings
@@ -24,7 +24,7 @@
- **N-HA7:** HA classification is a durable host fact. Switching off placement must not route an HA duty through legacy acquire. P1a's explicit legacy-sidecar classification stays until the separate birth-only extension below is approved and implemented.
- **H7:** duplicate ticks during adoption are allowed; losing a durable once-timer, repeatedly probing a live holder, or overwriting a newer registration is not.
-These decisions come from the merged spec/parent plan and `amadan discuss show carlos/platform 421`, read for this revision. The discussion records the 2026-11-03 home-scope failure and the correction on `region-ha-home-placement`; that branch is not an implementation dependency to review against. Rebase after it merges before the dev drill.
+These decisions come from the merged spec/parent plan and the #421 record consulted for rev 1. Rev 2 re-read the local spec rev 6.1, parent plan and code. The home-placement correction is merged at c6304f2d; the drill must use a binary containing it. No review against its former branch is needed.
## Scope and slices
@@ -32,7 +32,11 @@ These decisions come from the merged spec/parent plan and `amadan discuss show c
**S — native-sidecar coverage and full Task 5B acceptance.** Task B6 adds birth-only HA support for native sidecars, then reuses T's gate/importer; Task 5B drills the combined result. This is separate because main deliberately classifies every sidecar as legacy (`internal/activator/hawake.go:74`), `SidecarRecord` has no HA bit (`internal/provision/sidecar.go:71`), and its legacy release cannot supply an HA releaser marker. Merely including sidecar rows in a scan cannot recover an asleep sidecar whose lock was deleted. Changing that behavior touches record creation, classification, lease/restore, secrets and workers. Do not hide it behind a fixture setting `Route.HA=true`.
-T inventories sidecar records and reports unsupported coverage; it never declares them imported or deletes evidence for a departure it cannot cover. T can be activated for a fixed-pair scope whose departing boxes have no native-sidecar duties. The preflight/card must establish that restriction. S needs Paul's birth-only extension decision below; existing sidecars are never silently migrated. This restriction must be carried into P3a's integration/activation card.
+**T scope gate (P2-1/P2-4, I3):** `Controller.CheckCoverage(snapshot, localPolicy)` runs before Start can poll and on every new inventory generation. Refuse T if **any extant native-sidecar record in the receiver's exact placement scope** exists, regardless of pool, awake state or apparent lock absence. This deliberately rejects more than hibernating sidecars: legacy release erases the evidence needed to identify their departing releaser. Also refuse if any regional born-HA record is outside the receiver's normal reconcile eligibility (pool, placement restrictions or supported shape). The gate uses the complete pre-filter record inventory and the actual local `ReconcileConfig` policy, not edges Hosts. Incomplete inventory waits without polling. A refused receiver does not consume or ack its own queue and reports C7/C8 once per refusal generation; it cannot advertise a healthy consumer.
+
+This chooses **full-scope receivers only**, rather than partial completion attributed to another box. On a shared-only B and shared+hapair C, with records in both pools, B refuses before receiving; C alone imports all matches, deletes evidence and acks its own queue. B's retained queue is an explicit operator/configuration issue, not an hourly scan/page loop or a claim that C acked B's queue. Fixed queues broadcast separately; a shared queue is polled only by admitted receivers. P3a's activation card must exclude/refuse B until it can cover the scope. No blanket G2 claim for heterogeneous pools.
+
+If a new record invalidates coverage after startup, finish already admitted HA-host transactions safely, retain all departure evidence, emit one refusal and stop this consumer lifecycle: clear `Running` immediately, join admitted work, then close `Done` with the coverage fault retained in status. `Started` is a historical latch and cannot be reopened. No pending departure completes or acks. Persist the refusal fingerprint across restart so an unchanged fault does not page again. Rearming requires an explicit configuration/activation action and a new complete generation passing the gate; no timer retry of an unsupported scope. Already imported instance duties continue through ordinary HA gates. S needs Paul's birth-only extension decision; it permits supported born-HA sidecars but **still refuses any legacy native sidecar** in the scope. Carry this restriction into P3a's integration/activation card.
Drain, group admission/latch, role writers, ASG hooks/rolls, hairpin, §6.5 retry, migration, offline moves and imports remain outside both slices. No G1/G2/G3 claim from this plan alone. P3 later owns a separate executable drain integration addendum against merged producers.
@@ -42,17 +46,40 @@ Drain, group admission/latch, role writers, ASG hooks/rolls, hairpin, §6.5 retr
| Round | Brief / findings | Verdict | Fault families / disposition |
|---|---|---|---|
+| 1 | `REVIEW-BRIEF-REGION-HA-P1B3B-R1.md`; `REVIEW-REGION-HA-P1B3B-R1.md`, Claude Opus 5.5, plan bc7eeb04, review 73406540; code 9a064ebe plus c6304f2d | **NOT READY: 2 P1, 7 P2, 7 P3** | P1-1/P1-2 are **one I3 family: duty authority after import depends on an earlier dead owner**. Rev 2 uses one adoption finalizer; P2/P3 dispositions below. Round 2 has not run. |
-Empty means no review of this document has run, not a reset of inherited history. Parent P1b-3 plan: Opus R1 NOT READY (3 P1, 4 P2, 6 P3), R2 READY AFTER FIXES (0 P1, 2 P2, 6 P3); N-HA12 closed the repeated I4 family, rev 3 final. Its B1–B5/5B decisions are inherited, not reopened. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds and are closed; duty-file transfer was cut after three P1 rounds.
+One round of this document is spent. **If round 2 finds the I3 family again, stop fixing under rule 2 and offer Paul refuse/cut/one enforced invariant; do not write a third fix.** Parent P1b-3 plan: Opus R1 NOT READY (3 P1, 4 P2, 6 P3), R2 READY AFTER FIXES (0 P1, 2 P2, 6 P3); N-HA12 closed the repeated I4 family, rev 3 final. Its B1–B5/5B decisions are inherited, not reopened. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds and are closed; duty-file transfer was cut after three P1 rounds.
A reviewer of the newly executable mechanisms must carry those counts and distinguish new findings from settled decisions. Use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. Stop at the first round without P1; apply P2s without another round, retaining census/new-security checks. Two rounds in one invariant/trust-boundary family stop fixes; offer the prescribed refuse/cut/central-invariant choice. A fourth round needs Paul's go. Splitting T/S does not reset review history. No reviewers or subagents run in this planning session.
+## Round 1 dispositions
+
+All findings below were checked against the cited code. These are rev 2 changes, not reviewer approvals. New functions live in the task's named new files; file:line anchors identify the existing behavior they must preserve or replace. B5 must run the production predicates for the I6 witnesses, including the refusal cases. The review's sidecar exclusion citation (:481–500) is stale: the checked IsSidecar refusal is at `internal/host/edgesfile.go:611`; no behavior difference was found.
+
+| Finding | Invariant and checked code | Rev 2 disposition / task | Witness and mutation |
+|---|---|---|---|
+| P1-1 + P1-2 | **One I3 family: imported duty authority must name its current owner**; I1/N-HA9, I2. `internal/termfence/confirm.go:14,38,112`; `internal/hafresh/acquire.go:79,87,112`; `internal/lease/release.go:24,87` | **Accepted together.** B2 central AdoptHost finalizer imports, ordinary-acquires after expiry, releases unclean as self and verifies before completion, for held and released hosts. No durable-cache substitute or deferred sequential-loss exception. | `TestHAAdoptAuthority`, `TestAdoptFutureDueAfterRestart` (+48h, EC2 forgets, restart clears cache; separately visitor on a previously uninvolved box), `TestAdoptSequentialDepartures` (E→D→F before wake, held/clean/unclean starts). Mutations `complete-import-without-marker`, `marker-keeps-dead-releaser`, `release-412-is-adopted`; existing `take-before-expiry` still caught. |
+| P2-1 | **I3: no claimed coverage of unidentifiable legacy sidecar duties**. `internal/activator/hawake.go:77`; `internal/provision/sidecar.go:71` | **Accepted by stronger refusal.** T CheckCoverage rejects any regional native-sidecar record before polling; runtime additions suspend after finishing admitted instance transactions, retain evidence, report once. S still refuses legacy sidecars. B3/B4/B6. | `TestDepartureSidecarPreflight`, partial-import/runtime insertion witness. Mutation `sidecar-absence-means-covered`. |
+| P2-2 | **I3: HRW winner must actually serve the host's pool**. Main `internal/edge/wakeplacement.go:157,168`; `internal/host/edgesfile.go:327,611` | **Accepted.** T uses per-host home entries for eligibility only; census remains full records. S adds validated served_pools box metadata, not public sidecar Hosts. B1/B6. | `TestHADutyNeverWokenPool`, `TestSidecarDutyPoolProjection`. Mutation `hrw-ignores-pool`. |
+| P2-3 | **I3: missing edges is not deployment irrelevance**. `internal/boxid/record.go:38,65`; `internal/boxid/verify.go:96,102`; `internal/console/apisystemgeoip.go:336` | **Accepted.** B3 durable verified ref↔iid cache and bounded unknown-iid immutable-record walk. Missing edges cannot prevent a known departure scan; unknown binding refuses/escalates. ETag needed only for actual deletion. | `TestDepartureIdentityWithoutEdges`, fresh-registry/partial-list variants. Mutation `missing-edges-is-irrelevant`. |
+| P2-4 | **I3: each receiver either covers the complete scope or refuses before work**. `infra/modules/region-host/main.tf:835,851`; `internal/provision/reconcile.go:1304` | **Accepted via refusal alternative.** B3/B4 require full local coverage; no partial receiver delegates completion by observing another box. Shared-only B does not poll; shared+hapair C finishes its own queue. Unsupported queues remain explicitly outside activation. | `TestDeparturePoolCoverage`, two queues/two pools and runtime new-pool record. Mutation `partial-scope-admitted`. |
+| P2-5 | **I2/I3: a new lease's S3 wake state outranks local advisory progress**. `internal/activator/hawake.go:738`; `internal/hostfiles/wake.go:80,107` | **Accepted.** B2 splits adoption CAS from exact atomic restore. Local revision/digest/receipt never filters new-lease restore. | `TestHAAdoptThenOrdinaryRestore` with interim-holder once-timer. Mutation `local-progress-overrides-new-lease`. |
+| P2-6 | **I3: permission failure cannot certify completion; apply must preserve required delete authority**. `infra/modules/region-host/main.tf:693,719–728`; private `dev/region-ie.tf:27` | **Accepted.** B4 pending/one-alert/no-ack on AccessDenied. Live T/5B requires merged/released/consumed region-host-store-deny fix plus saved-plan/effective-permission evidence; no apply restoring the Deny. Reported live drift is not independently verified here. | `TestDepartureDeleteDenied`, saved-plan policy assertion at drill preparation. Mutation `delete-denied-is-complete`. |
+| P2-7 | **I3: completion inventory must include the dead box's last host**. `internal/host/agent.go:931`; `internal/host/changeindex.go:147,167`; `internal/provision/reconcile.go:1080` | **Accepted with source freshness too.** B3/B4 wait for ordinary source refresh and full pass begun after confirmation; old cached records cannot get a fresh timestamp. | `TestDepartureInventoryAfterEvidence`, just-created held host with synced timer and unchanged index. Mutations `complete-old-inventory`, `restamp-stale-recordview`. |
+| P3-1 | **Home scope identity: null is malformed**. Main `internal/edge/homemap.go:168,788`; `internal/edge/wakeplacement.go:136,157` | **Taken.** Reuse placementNull; corrected edge citations; read main without rebasing. B3. | `TestDepartureHomeScopeAndPools`: omission/empty accepted, null rejected on self/peer. Mutation `null-is-home`. |
+| P3-2 | **Request budget includes discovery**. `internal/lease/ha.go:96`; main `internal/edge/wakeplacement.go:168` | **Taken.** Added B×N_due first-duty GET burst separately from quiet baseline. B1/B4. | `TestHADutySuppressLivePeer` and counted upgrade/first-duty workload. |
+| P3-3 | **Bounded observation/log traffic for a nonterminated stale peer**. `internal/termfence/confirm.go:19,112` | **Taken.** 300s scanner ceiling = ≤12 Describe/h/peer; state-change log plus ≤1 reminder/h; suspect alarm retained. B3/B5. | Fake clock/counting transport with stopped/hung peer, never termination; no deletion/ack. |
+| P3-4 | **Configuration reaches the actual fixed-box process**. `internal/hostenv/hostenv.go:70`; `internal/host/units/carlos-edge.service:18`; `infra/modules/region-host/variables.tf:47` | **Taken.** B3/5B card delivers per-box queue URL via host.env, includes rollback and restart outage; group allowlist alone is insufficient. | Config-delivery witness reads generated env and arms actual helper; record restart/admission times on built binary. ~11s outage is a reported estimate, not a new measurement. |
+| P3-5 | **Started is truthful, not an immediate constructor fact**. `infra/modules/region-host/main.tf:897` (Receive permission); new B3 consumer seam | **Taken.** First empty long poll may take 20s; inventory preflight adds its own wait. No zero-wait polling to satisfy P3 admission. | `TestTerminationConsumerLifecycle` keeps Started open before delayed successful empty Receive; existing `start-before-client` mutation retained. |
+| P3-6 | **Count shared-queue visibility redelivery**. `infra/modules/region-host/main.tf:835,837`; new B3 Receive configuration | **Taken.** 120s visibility can redeliver ~8 times during 15m expiry, plus scanning; count per-receiver journals/scans, ack only own completion. B3/B4. | Fake queue visibility expiry across multiple receivers, counted scans, no early ack. |
+| P3-7 | **Bounded scan client construction**. `internal/lease/ha.go:169,174` | **Taken.** B4 adds reusable lock reader/client per page, keeping validation/decoding; acquire retains its existing handle path. | `TestDepartureRequestBudget` counts one scan-reader client, up to 32 classification reads per page, plus separately counted finalizer reads. |
+
## Global Constraints
-- **Home scope, lesson of 2026-11-03:** dev and every home region run with `CARLOS_REGION` unset. It is `provision.Reconcile`'s record scope, not the AWS region. Empty placement is a real scope and matches only empty placement; it is neither unknown nor a wildcard. Dev IE records have `region:""`; `hapair-a1` is in pool `hapair`. Never set `CARLOS_REGION=ie` to make the drill pass: that would remove home records. Test every new comparison with those values. A separate known/present bit represents missing evidence.
+- **Home scope, lesson of 2026-11-03:** dev and every home region run with `CARLOS_REGION` unset. It is `provision.Reconcile`'s record scope, not the AWS region. Empty placement is a real scope and matches only empty placement; it is neither unknown nor a wildcard. Dev IE records have `region:""`; `hapair-a1` is in pool `hapair`. Never set `CARLOS_REGION=ie` to make the drill pass: that would remove home records. Test every new comparison with those values. Reuse main's `placementNull` bit: explicit JSON null is malformed, while omission and `""` are home. A separate known/present bit represents missing evidence.
- AWS region/account/iid must be proven and non-empty; placement may be empty. Require compatible non-empty data bucket and secrets fingerprint. Keep box reference, iid, record lifetime and registry `Pair` distinct.
- Host universe comes from existing instance **and sidecar** reconciliation, including asleep/hidden hosts. Public edges, the local in-pool registry and `LifetimeIndex` alone are not a complete regional census. Pool equality is a tenancy boundary; do not widen it to finish a scan.
-- HA duties use the existing nested acquire → restore → sealed-secrets publication → start path. Import reads only manifest and `wake.json`; it neither restores DB/files/secrets nor starts a process. All publish-before-start and positive-proof reuse rules remain.
+- HA duties use the existing nested acquire → restore → sealed-secrets publication → start path. Adoption reads only manifest and `wake.json` data and finalizes through an ordinary acquire/unclean release; it neither restores DB/files/secrets nor starts a process. All publish-before-start and positive-proof reuse rules remain.
- One local import transaction and one duty-selection policy; no claim-mode activation. No dependency on `CARLOS_HOST_CLAIM` or an unmerged role/drain producer.
- Existing view freshness: **15 minutes**, future tolerance **1 minute**; fold tick **30 seconds**, timed publication **5–6 minutes**. The ageing callback runs even when the change index skips the host fold. No new S3 polling loop or request-time membership reads.
- `Confirmer.Terminated` stays shared with acquire: positive cache **24h**, negative/error cache **10s**, one in-flight describe/iid. The old `termfence.Verify` accepts an event; do **not** use it as the new proof path. `FromEvent` is a hint parser only.
@@ -64,9 +91,9 @@ A reviewer of the newly executable mechanisms must carry those counts and distin
## Current code and file map
-| Existing seam at 9a064ebe | Work and proposed files |
+| Existing seam (edge citations at c6304f2d/current main) | Work and proposed files |
|---|---|
-| `internal/host/agent.go:485,583,915,1313`; `internal/host/hatakeover.go:22,35` | Share the confirmer, arm the controller once before workers/runner, give it the agent lifetime. New `internal/host/hadepartures.go`, `hadepartures_wiring_test.go`. |
+| `internal/host/agent.go:487,583,915,1313`; `internal/host/hatakeover.go:22,35` | Share the confirmer, arm the controller once before workers/runner, give it the agent lifetime. New `internal/host/hadepartures.go`, `hadepartures_wiring_test.go`. |
| `internal/activator/activator.go:2383,3855,5151,5242,6150`; `internal/activator/hawake.go:74,294,340,738` | Duty eligibility, wake cause, acquisition result and ordinary restore integration. New `haduties.go`, `haadopt.go` and focused tests. |
| `internal/lease/ha.go:59,99,169`; `internal/hafresh/acquire.go:72` | Restriction-only duty predicate on the acquire's existing lock read; preserve the authority decision. No independent pre-acquire probe. |
| `internal/schedule/runner.go:564`; `internal/host/schedule_wiring.go:64,186`; `internal/host/instancekeys.go:75` | Gate before token preparation; preserve escrow read-after-restore and HA backfill exclusion. New duty-runner tests. |
@@ -74,10 +101,10 @@ A reviewer of the newly executable mechanisms must carry those counts and distin
| `internal/hostfiles/wake.go:47,84,134`; `internal/hostfiles/manifest.go:64,133`; `internal/activator/hawake.go:593,738` | Reuse validated manifest/LoadWake; replace non-atomic import via new registry transaction, including ordinary wake restore. |
| `internal/registry/timers.go:54,126,321`; `internal/registry/registry.go:1878,3236,3265`; `internal/registry/remote_dispatch.go:143` | New `ha_duties.go`, `ha_departures.go`, tests and remote dispatch parity. Add tables in registry initialization; atomic state/receipt, guarded progress, removal cleanup. |
| `internal/provision/reconcile.go:1068,1230,1304`; `internal/provision/sidecar_reconcile.go:190,451`; `internal/provision/lifetimeindex.go:40` | New `departure_inventory.go`: complete validated regional record snapshot before pool filtering, from existing reads; no extra list. Both record families participate. |
-| `internal/edge/homemap.go:265,420,519,1221`; `internal/edge/wakeplacement.go:133` | Retain exact ETags with cached files; export immutable departure observations and 30s callback independent of fold skip. New `hadepartures.go` and tests. Empty home scope fixed in every new predicate. |
+| `internal/edge/homemap.go:168,270,433,524,788,1232`; `internal/edge/wakeplacement.go:136,168` | Retain exact ETags with cached files; export immutable departure observations and 30s callback independent of fold skip. New `hadepartures.go` and tests. Empty home scope fixed in every new predicate. |
| `internal/termfence/confirm.go:112`; `internal/termfence/fence.go:117`; `internal/boxid/record.go:65`; `internal/boxid/verify.go:102` | Confirmation callback after cache publication; signed identity binding without roster. New adapter tests. |
| `internal/release/conditional_delete.go:29,94`; `internal/release/changeindex.go:125,179` | Existing conditional deletion, plus an explicitly acknowledged index completion seam; current automatic bump logs/swallow errors. |
-| `infra/modules/region-host/main.tf:835,841,865,890`; `infra/modules/region-host/outputs.tf:41`; `internal/hostenv/hostenv.go:71` | Existing queue/rule/receive-delete-getattributes policy and queue URL output. Add optional queue-URL configuration, no new queue or IAM actions. New `internal/awsterminations/queue.go` and adapter tests; `go.mod`/`go.sum` for SQS SDK if needed. |
+| `infra/modules/region-host/main.tf:835,841,865,890`; `infra/modules/region-host/outputs.tf:41`; `internal/hostenv/hostenv.go:71` | Existing queue/rule/receive-delete-getattributes policy and queue URL output. Deliver the fixed-box queue URL through host.env; hostenv.Optional covers group SSM only. T adds no queue actions. Edges deletion depends on the separately merged/released `region-host-store-deny` module fix (`main.tf:693,723`). New `internal/awsterminations/queue.go` and adapter tests; `go.mod`/`go.sum` for SQS SDK if needed. |
| `internal/sim/regionha/{world_test.go,actions_test.go,rules_test.go,invariants_test.go:59,sim_test.go:27,witness_test.go:101,mutate.sh}` | Durable timer/queue model and I6, sharing production pure decisions. |
| `internal/host/haplacement_root_linux_test.go:1` and `haplacement_scenarios_root_linux_test.go` | Follow the existing Linux rootrunner harness; new `hadepartures_root_linux_test.go` executes real import/acquire/delivery paths. |
| `internal/provision/sidecar.go:71`; `sidecar_reconcile.go:131`; `internal/activator/backend_exec.go:3335` | S only: additive birth stamp, sidecar lifetime/reconcile, contained HA worker path; console sidecar create/enable doors and their refusal tests. |
@@ -90,11 +117,15 @@ New provider-neutral protocol/lifecycle types live in `internal/hadeparture/{typ
Use `hadeparture.Scope{CloudRegion, Placement, DataBucket, SecretsKeyFP string}` plus `Known bool` on the observation containing it. `Placement:""` is valid. A `Box` carries `Ref, InstanceID, Account, RecordSHA256 string` and `Scope`. A `Departure` carries that Box, exact `EdgesKey, EdgesETag string`, `ObservedAt time.Time`, and a stable ID derived from deployment bucket + cloud account/region + ref + iid + record digest. It contains no tenant-supplied path or arbitrary object prefix.
-`provision.DepartureInventory.Snapshot() (generation uint64, records []DepartureHost, complete bool)` returns immutable, validated records from the existing full passes. `DepartureHost` contains canonical account/app/host, kind, placement, pool, lifetime ID, record revision and HA classification. Complete requires both families' successful scans under one reconciled generation; parse/read failures retain the old data but clear completeness. Capture records before the pool filter. Fresh startup without a complete inventory cannot complete a departure. Local route eligibility still uses the normal provision policy.
+`provision.DepartureInventory.Snapshot() InventorySnapshot` returns `{Generation, Records, Complete, WalkStartedAt, SourceReadStartedAt}`. `DepartureHost` contains canonical account/app/host, kind, placement, pool, lifetime ID, record revision and HA classification. Both record families must finish successful complete scans under one generation, **before pool filtering** (`reconcile.go:1304`, `sidecar_reconcile.go:190`). Parse/read failures retain old data but clear completeness. CheckCoverage uses the same normal reconcile eligibility predicate; inventory presence never grants a local route.
-The edge exports `DepartureView{Self BoxObservation, Peers []BoxObservation, Complete bool}`; each observation retains source key/ETag and generation. Keep stale files for suspicion; do not filter them out before the age callback. Verify immutable `control/boxes/<ref>.json` once per new ref against existing AWS certificates, expected account/region and the cached published iid. The unsigned record Box field alone cannot bind a reference: require agreement with the scoped edges identity, signed iid and, for group refs, the existing deterministic reference derivation. Duplicate iid/ref assignments are unusable. No enrollment write or claim roster is created.
+**Fresh inventory (P2-7, I3):** completing a departure requires the full pass **and its source bucket refresh** to have started strictly after the locally recorded successful termination confirmation time. A pass started before confirmation, or started after it over an older RecordView, cannot qualify. Wait for the next ordinary full refresh/pass (`internal/host/agent.go:931`, `internal/host/changeindex.go:147,167`); use the existing index/backstop, without a new read loop. A scoped pass or unchanged-index skip cannot restamp an old snapshot. Persist the source generation/times; after restart require a newly qualifying pass. Before completion, changed/new records invalidate the affected scan checkpoints and coverage gate; a newer incomplete generation prevents completion. This adds up to one existing backstop interval to the latency bound.
-For a queue iid absent from a **complete** known deployment view, delete as irrelevant. An uninitialized/partial view is not proof of irrelevance: retain/retry. Wrong event account/region/source/type/state and malformed bodies are rejected without a scan. Validation/read errors are not proof of irrelevance; retain the message and report them. `termfence.FromEvent` does not check terminated by itself; the adapter must. Bound event bodies to 64 KiB; no payload field chooses a bucket, URL, key or AWS region.
+The edge exports `DepartureView{Self BoxObservation, Peers []BoxObservation, Complete bool}`; observations retain key/ETag/generation and main's `placementNull`. Keep stale files for suspicion. Store verified immutable identity bytes/digest and their ref↔iid binding in a local `ha_box_identities` table; never remove a binding when its edges file disappears. Verify `control/boxes/<ref>.json` against AWS certificates and expected account/region (`boxid/record.go:38,65`, `boxid/verify.go:96,102`). Require the independent fixed-box expected iid/cached verified binding, or the existing deterministic group-ref binding; the unsigned Record.Box alone grants nothing. Reject duplicate ref/iid assignments. Store the last valid scope/edges revision separately, with explicit known bits. This is a cache of existing immutable evidence, not an enrollment write or an S3 roster.
+
+**Irrelevance (P2-3, I3):** resolve a queue iid from that durable map. For an unknown iid, perform an event-triggered, paginated `control/boxes/` walk: at most one LIST page and 32 previously unverified record GETs per ordinary callback, persist the cursor, and finish/verify every relevant record before declaring no deployment match. Coalesce unknown events onto one walk. An incomplete walk, malformed record, duplicate binding or read error cannot certify absence. Only a complete verified walk with no matching signed iid can reject the event as unrelated. A matching signed iid with unresolved ref/scope is relevant-but-unbound: retain and escalate for missing identity configuration, never ack as unrelated. Missing edges alone never means irrelevant (`internal/console/apisystemgeoip.go:336` explicitly tells operators to delete retired edges).
+
+Known bindings with missing edges still confirm and scan. Exact edges ETag is required **only if an edges object exists to delete**. After a complete adopted scan, an exact-key GET proving absence may skip deletion and proceed to acknowledged index/completion; absence alone never discharges a host. An unbound/unknown scope remains refused. Wrong event account/region/source/type/state and malformed bodies are rejected without a scan. `termfence.FromEvent` is a hint parser only; the adapter checks terminated. Bound bodies to 64 KiB; no payload field chooses bucket, URL, key or AWS region.
All accepted hints enter `Controller.Enqueue(ctx context.Context, box BoxObservation) error`. Enqueue confirms via the shared `Confirmer.Terminated`, verifies the binding, then durably upserts pending work before returning success. The request path reports a successful confirmation through a callback after the confirmer publishes its result and releases locks; a failed enqueue must remain retryable on subsequent positive-cache hits. Never run a scan while holding a confirmer, edge-fold or activator mutex.
@@ -122,7 +153,7 @@ func (c *Controller) Start(ctx context.Context,
makeQueue func(context.Context) (Queue, error)) (Lifecycle, error)
```
-`Started` closes once, after journal recovery, handler registration and the first **successful** Receive result, empty included. A first result containing messages must have each message durably recorded as received (or definitively rejected) before startup is acknowledged; confirmation/import may still be pending. Keep a bounded local received-message record keyed by message ID/body digest, without a reusable receipt handle. Failure to persist leaves Started open and the receipt unacknowledged. Queue construction failure returns an error and no started lifecycle. Initialization does not wait for a message, a drained producer, a completed scan, a tenant wake or P3 admission. A receive error before first success leaves Started open and retries with bounded backoff. Start twice on the same controller returns an error, never a second consumer.
+`Started` closes once, after journal recovery, a passing coverage gate, handler registration and the first **successful** Receive result, empty included. A first result containing messages must have each message durably recorded as received (or definitively rejected) before startup is acknowledged; confirmation/import may still be pending. Keep a bounded local received-message record keyed by message ID/body digest, without a reusable receipt handle. Failure to persist leaves Started open and the receipt unacknowledged. Queue construction failure returns an error and no started lifecycle. Initialization does not wait for a message, a drained producer, a completed scan, a tenant wake or P3 admission. A receive error before first success leaves Started open and retries with bounded backoff. Start returns a lifecycle while inventory preflight waits asynchronously, so arming before the reconcile loops cannot deadlock their startup. Running remains false and no Receive occurs until coverage passes; a definite preflight refusal is a typed start error (or terminal lifecycle error if discovered asynchronously). Start twice on the same controller returns an error, never a second consumer. With an empty queue the first success can take the full **20-second long poll**; P3 restart-to-admission measurements must include that delay plus inventory preflight. Do not reduce WaitTimeSeconds or add zero-wait polls to improve the measurement.
After first start, transient queue/store/describe failures keep the loop alive and the start fact latched. `Running` becomes false synchronously when Stop or parent cancellation begins; Done closes after receiver and scan work have joined. Stop is idempotent, context-bounded, and cannot acknowledge uncommitted work; a timeout reports an unfinished stop. Unexpected terminal exit also clears Running and closes Done. P3 will set its `TerminationStarted` fact only from Started while Running, then close admission before invoking Stop or reacting to Done. This plan adds no P3 import, no `lbhealth.SetHosting` call and no cloud reads to health.
@@ -133,27 +164,35 @@ Use one process-owned cancellation context in `runAgent`; pass it into the new c
Store received-message bodies, pending departures and host receipts in the existing registry DB, not a new disk path or S3 object. Cap one received body at 64 KiB and the active inbox at 1,024 rows; at the cap pause Receive until existing work drains, leaving messages on SQS. Do not evict incomplete work. New tables:
- `ha_termination_inbox`: message ID/body digest/body, received time and validation state; delete after completion or definite rejection. No receipt handle persists.
-- `ha_departures`: departure ID, bound identity/scope/edges revision, verified evidence time, inventory generation, phase, next attempt, last error code. Phases: pending → scanning → imported → edges_deleted → indexed → complete. Receipt handles are ephemeral; never persist them as permanent queue identity.
-- `ha_departure_hosts`: departure ID + host + lifetime, lock fingerprint, manifest sequence/wake digest, status (`pending`, `wait_expiry`, `imported`, `superseded`, `unsupported`), retry time. A skipped pool/unknown lifetime/failed read cannot become imported.
+- `ha_departures`: departure ID, bound identity/scope/edges revision, verified evidence time, inventory generation, phase, next attempt, last error code. Phases: pending → scanning → authority_complete → edges_deleted_or_absent → indexed → complete; `scope_refused` is a suspended state, not a retry deadline. Receipt handles are ephemeral; never persist them as permanent queue identity.
+- `ha_departure_hosts`: departure ID + host + lifetime, lock fingerprint, manifest sequence/wake digest, status (`pending`, `wait_expiry`, `imported_pending_authority`, `acquired`, `marker_pending`, `adopted`, `superseded`, `unsupported`), retry time. A skipped pool/unknown lifetime/failed read cannot become imported.
- `ha_duties`: host + lifetime, owner basis (`local-holder`, `local-release`, `adopted`), departure ID, wake digest/sequence, registry revision and suppression holder. Host retirement/recreation invalidates entries; historical receipts never authorize a new lifetime.
-`Service.AdoptHost(ctx context.Context, rt registry.Route, req Adoption) (AdoptResult, error)` is the one entry. `Adoption` carries departure identity, expected lifetime/registry Pair, observed lock and local revision. Results are `Imported`, `AlreadyImported`, `Superseded`, or `Deferred`; only the first three can discharge a matching host. Superseded requires a proven newer local owner/committed import or a complete authoritative record retirement, not absence from a stale cache. A changed remote lock alone is not proof this local import completed; classify it from the new view on the next attempt.
+`Service.AdoptHost(ctx context.Context, rt registry.Route, req Adoption) (AdoptResult, error)` is the one entry. `Adoption` carries departure identity, expected lifetime/registry Pair, observed lock and local revision. Results are `Adopted`, `AlreadyAdopted`, `Superseded`, or `Deferred`; only the first three can discharge a matching host. An import receipt alone is not Adopted. Superseded requires a validated subsequent HA holder/releaser (local or remote, with identity, current record lifetime and later lock generation established), or complete authoritative record retirement; a staged import or absence from a stale cache is insufficient. A changed remote lock alone is not proof this local import completed; classify it from the new view on the next attempt.
Use existing `hostfiles.Load` and `LoadWake` at the backend's configured `filesPrefix` (`<hibernatePrefix>/files/0/`). Validate manifest version, object origin, digest, wake V/Host, replication class and every timer before writing. No wake entry means no durable wake state; a referenced missing/corrupt wake object is incomplete. A missing whole manifest on a previously held host is reported as ambiguous, not silently installed as an empty timer set. Never read sealed items or instantiate a files publisher for adoption.
-Add `Registry.ImportHAWake(ctx context.Context, host string, expected Pair, state HAWakeImport) (ImportResult, error)`. `HAWakeImport` contains validated timer rows, next_due, replication, lifetime, expected local revision and adoption receipt. In one SQL transaction: compare lifetime/Pair/revision, replace the intended wake state, record adoption and host progress, commit. Reuse the same atomic wake-state primitive from `hostfiles.ImportWake` for ordinary restore. Remote registry methods must preserve the comparison/result/error behavior.
+Add `Registry.ImportHAWake(ctx context.Context, host string, expected Pair, state HAWakeImport) (ImportResult, error)`. `HAWakeImport` contains validated timer rows, next_due, replication, lifetime, expected local revision and adoption receipt. In one SQL transaction: compare lifetime/Pair/revision, replace the intended wake state, record the import receipt and pending-authority progress, commit. Use a separate `Registry.ReplaceHAWake` entry for ordinary restore; it shares only validation and the atomic SQL replacement primitive, not adoption receipt/revision ordering. Remote registry methods must preserve the comparison/result/error behavior.
+
+Advance a per-host local revision transactionally for registration/deletion, timer advancement, next_due consumption, relevant reconcile changes, successful acquire and release. Read the revision before I/O; commit only if unchanged. Serialize wake/adoption in the activator's host operation state without holding `a.mu` over I/O. An acquire begun after a scan invalidates the scan commit; an import begun during wake defers. A repeat import receipt skips row replacement but must resume unfinished authority phases; only a finalized receipt returns AlreadyAdopted. **P2-5 / I2,I3:** under a newly acquired lease, ordinary restore installs the validated S3 wake state exactly (`hawake.go:738`, `hostfiles/wake.go:80`), atomically, before delivery. No local revision, timer tombstone, receipt or digest orders local state above a manifest written by an interim holder. Non-owner old-tick advancement is advisory. Revision/receipt CAS only prevents replay of adoption I/O done without a lease. Lease-acquired restore changes the local revision and invalidates outstanding adoption I/O. Keep adoption receipts to prevent their replay; never use them to filter the new holder's authoritative restore.
-Advance a per-host local revision transactionally for registration/deletion, timer advancement, next_due consumption, relevant reconcile changes, successful acquire and release. Read the revision before I/O; commit only if unchanged. Serialize wake/adoption in the activator's host operation state without holding `a.mu` over I/O. An acquire begun after a scan invalidates the scan commit; an import begun during wake defers. A repeat receipt returns AlreadyImported without restoring old timer rows. Ordinary restore must not replay an older manifest over delivery progress made after adoption; use the same receipt/digest/revision rules. Keep registration identity and completion tombstones until the corresponding receipt can no longer replay.
+**One authority rule (P1-1/P1-2, I3; I1/N-HA9 and I2): an adopted host is complete only when its durable lock names the adopter as holder/releaser, or a verified successor has taken responsibility.** Enforce this in **`Service.AdoptHost` alone**, including its replay/resume path. SQL import cannot independently mark a duty adopted, and Controller.Complete accepts only the finalizer's committed result. This applies to **held locks and clean/unclean release markers**, including hosts with no due work until days later. It closes both dependence on an old EC2 cache and discovery on the adopter's later departure.
-For a terminated **held** lock, import completion waits until the observed expiry has passed, then reads the current lock/manifest in a new attempt. This prevents a last in-flight wake-state publication before expiry from being missed. Waiting is a persisted local deadline, not a lock poll. The later actual duty still acquires normally under N-HA9. A released marker needs matching ref **and iid and lifetime**, whether clean or unclean; cleanliness only controls local-copy reuse.
+1. For a held departed lock, wait strictly past its expiry (equality is held), then re-read the lock and latest manifest/wake object and stage the atomic import as `imported_pending_authority`. Released markers match ref+iid+lifetime and need no expiry wait. No candidate duty is runnable yet.
+2. In the same serialized host operation, acquire through the existing `lease.AcquireHA` core (`ha.go:59,96`; `hafresh/acquire.go:79,87,112`). Use a restriction callback on every CAS round to require the matching departed identity/lifetime and observed lock revision; a changed lock is reclassified, never forcibly replaced. Confirmation comes from the shared confirmer while fresh; no relaxed proof or early take. The base marker is **self ref/self iid/current lifetime**, never the departed base.
+3. Under that acquired handle, revalidate/load the manifest and install its exact wake state atomically before finalization. This second validation prevents an import staged before acquisition from defeating a later authoritative publication. If an earlier staged digest still matches, avoid a second wake-object GET; still read the manifest. Start no tenant, restore no DB/file tree, publish no wake state or secrets, and claim no clean local copy.
+4. Immediately call `Held.Release` (`lease.go:314,324` → `release.go:28,87`), which writes the ordinary **unclean self marker**. Persist/retry existing release obligations on errors. **Release returning nil is not proof of the self marker:** its 412 path also returns nil (`release.go:24,48`). Read the lock back and require the self ref/iid/lifetime and expected acquired generation's unclean marker before committing `adopted`/local duty basis. A later valid HA holder/releaser can discharge as Superseded only after identity/lifetime/generation validation; malformed, absent or ambiguous state remains pending. No wrapper bypasses ordinary acquire/release authority.
+5. Persist phase transitions before effects and replay them after crashes. Death before the acquire leaves the original lock discoverable; death after acquire names this scanner; death after marker publication but before local commit also names it. Process restart uses existing same-box-empty proof/release obligations, never a fresh EC2 guess about self. A replay of an already adopted receipt must revalidate its authority status without reinstalling old timers or repeatedly acquiring a self marker. A different scanner seeing the new owner/releaser suppresses its duplicate import; if that adopter later terminates, its own departure scan imports it normally.
+
+The future duty still uses ordinary HA acquire and restore. Any box can take an unclean marker without describing the earlier dead owner (`hafresh/acquire.go:79`); unclean forbids local reuse. Both a once-timer due at +48h after a cache-clearing restart and E→D→F sequential departures before any wake are mandatory witnesses, not deferred limits. No S3 duty file, new lock wire shape or permanent termination exception is introduced.
### Duty selection
One pure `DecideDuty(DutyInput) DutyDecision` in `activator/haduties.go`: non-HA retains existing behavior; an owned awake HA entry may act; a local releaser/adopter may attempt its sleeping work; only HRW over compatible serving boxes may attempt an unknown/never-woken host. HRW uses the greatest SHA-256 of `host + "\x00" + ref`, lexical ref tie-break, and **no capacity ranking**. Never use H4's roomiest choice for timer ownership. Missing scope/view defers an unknown starter without dropping rows; known local duty remains eligible subject to local service restrictions and acquire.
-The cached serving projection for duties must support sidecar pool eligibility without using public Hosts entries as a roster. Explicit booting/drain/platform forbids new duty starts; absent role retains fixed-box behavior. P3 will later supply its merged admission predicate. On upgrade/restart with no duty basis yet, allow one discovery attempt at the first due work through the same acquire read: a self-owned release can establish the local basis even when self is not HRW; an absent lock may be taken only by HRW. A peer answer establishes suppression. This is demand-driven discovery, never a new per-host poll, and costs at most one losing GET per box/host until the relevant evidence changes. Non-owners leave younger schedule ticks untouched and advance only occurrences at least **15 minutes** old, guarded by registration/DueAt. Once-timers and imported next_due are not blanket-pruned by this rule.
+**P2-2 / I3:** for T instances, build the cached HRW candidate set from main's per-host home entries exactly as `wakeplacement.go:157–174`: matching scope/bucket/key, fresh compatible serving evidence, canonical host/account/app, home role, no alias/wildcard/replica, plus normal local route eligibility for self. A peer without that entry is ineligible even if its box is fresh. Hosts is an eligibility projection only; the complete scan census remains the record inventory. Never-woken hapair work must not select a shared-only peer. For S, sidecars remain absent from Hosts (`edgesfile.go:611`); B6 adds a separately validated optional `served_pools` field to the existing box snapshot, derived from the actual ReconcileConfig, with explicit empty pool, absent/null = unknown. S sidecar HRW requires this field and supported local sidecar policy; no field means ineligible, not wildcard. Explicit booting/drain/platform forbids new duty starts; absent role retains fixed-box behavior. P3 will later supply its merged admission predicate. On upgrade/restart with no duty basis yet, allow one discovery attempt at the first due work through the same acquire read: a self-owned release can establish the local basis even when self is not HRW; an absent lock may be taken only by HRW. A peer answer establishes suppression. This is demand-driven discovery, never a new per-host poll, and costs at most one losing GET per box/host until the relevant evidence changes. Non-owners leave younger schedule ticks untouched and advance only occurrences at least **15 minutes** old, guarded by registration/DueAt. Once-timers and imported next_due are not blanket-pruned by this rule.
-Add a restriction-only acquire entry `lease.AcquireHAForDuty(ctx, bucket, prefix, region, base, proofs, allow func(hafresh.View) error)` sharing `classifyAndTake` with AcquireHA. Invoke allow on the existing read on each CAS round; it can refuse, never override `DecideAcquire`. This avoids a second GET and closes the race between a cached duty choice and a peer release. A live peer/another releaser drops local duty eligibility; an exact adoption receipt allows the departed releaser case. Keep the typed refusal private to background work, not a new visitor response.
+Add a restriction-only acquire entry `lease.AcquireHAForDuty(ctx, bucket, prefix, region, base, proofs, allow func(hafresh.View) error)` sharing `classifyAndTake` with AcquireHA. Invoke allow on the existing read on each CAS round; it can refuse, never override `DecideAcquire`. This avoids a second GET and closes the race between a cached duty choice and a peer release. A live peer/another releaser drops local duty eligibility; only a finalized adoption basis permits sleeping duty work; an imported-pending-authority receipt grants nothing. The adoption finalizer uses the same restriction-only core for its separate matching-departure acquire. Keep the typed refusal private to background work, not a new visitor response.
Suppression is keyed by host lifetime + holder ref/iid + relevant view/duty generation. A live-holder encounter costs one GET, then zero probes until that holder leaves view or confirmed departure cancels the suppression. An imported dead-holder lock waiting for expiry gets a local not-before deadline; it must not be suppressed forever. Ordinary visitor wakes remain able to acquire and thereby become the local duty owner. Local release saves its duty basis only after the real marker/release result, never before a failed release is settled.
@@ -161,42 +200,47 @@ Suppression is keyed by host lifetime + holder ref/iid + relevant view/duty gene
Counts are logical API attempts, including failed CAS; instrument transport retries separately. New SQS/EC2 adapters set SDK max attempts to **1** so their retry loop is the count. S3 keeps existing adapter behavior; report actual wire retries alongside logical counters. G/P/L/D mean S3 GET/PUT/LIST/DELETE.
-Let N be the complete regional scan's host count, A matching/importable hosts and W manifests containing wake state (W≤A). Let U be previously unverified box references, E be event-required edges refresh reads (normally 0), and k be index CAS attempts (1≤k≤4). The current implementation has **four total attempts**, not five, despite §18's “four retries” wording.
+Let N be the complete regional scan's host count, A matching/importable hosts and W manifests containing wake state (W≤A). Let U be previously unverified box references, E be event-required edges refresh reads (normally 0), Q≤A additional wake GETs when the manifest changed between staging and acquire, and k be index CAS attempts (1≤k≤4). Every adopted host, held or released, adds one acquire GET, one under-lease manifest GET, one release-verification GET and two PUTs; failed/reclassified attempts are additional. The current implementation has **four total attempts**, not five, despite §18's “four retries” wording.
| Path | S3 | SQS / EC2 |
|---|---|---|
| Quiet enabled box, no pending departure; each ordinary duty/age pass with nothing eligible | **0 incremental G/P/L/D** | 1 Receive/20s ≈ **180/h**, **4,320/day**; 0 Delete, 0 Describe |
| Startup, identity cache empty | U G for discovered signed records, one-time; no LIST | At most 1 GetQueueAttributes to validate the configured queue, then receives; no GetQueueUrl |
-| One valid termination, successful full scan | **(U+E+N+A+W)G**, 0L/0P before completion | 1 delivering Receive + 1 Delete after complete; 1 Describe on cache miss, 0 on hit |
+| One valid termination, successful full scan | **(U+E+N+4A+W+Q)G + 2A P**, 0L for known identities | 1 delivering Receive + 1 Delete after complete; 1 Describe on cache miss, 0 on hit |
| Completion, uncontended | **1D + 1G+1P** index | Message deletion above |
| Completion with index conflicts | **1D + kG+kP**, k≤4 | No ack until indexed or a later acknowledged retry |
-| Single scan pass | At most **32 lock G + 32 manifest G + 32 wake G = 96G**, plus identity/refresh G and completion if last page | 0 additional receives required by scanner; at most one Describe/iid/10s |
+| Single scan pass | Uncontended: at most **224G + 64P** for 32 adopted hosts including Q=32; 192G+64P if manifests unchanged. Plus bounded identity/refresh and completion | 0 additional receives required by scanner; at most one Describe/iid/10s |
| Held lock still unexpired | 1 lock G in this attempt, 0 manifest/wake G; persist deadline | No repeat describe within negative/positive cache bounds |
-| Resume after expiry/error, n remaining/revalidated hosts, a/w imports | **(n+a+w)G**, plus U/E; worst a full formula again | Redelivery adds a Receive and eventually a Delete for its current receipt |
+| Resume after expiry/error, n remaining/revalidated hosts, a/w imports | **(n+4a+w+q)G + 2a P**, plus U/E and retries; worst a full formula again | Redelivery adds a Receive and eventually a Delete for its current receipt |
| Duplicate completed event on same durable registry | 0 scan G; completion receipt checked locally | 1 Receive + 1 Delete; evidence cache hit 0 Describe |
-| Concurrent scanner on another box | Up to another full formula; no claim that queues broadcast once | Its own receive/redelivery and delete attempts |
-| Malformed/wrong-account/known unrelated event | 0 scan S3; unknown identity binding can cost U G | 1 Receive + 1 Delete for definitively irrelevant message; 0 Describe |
+| Concurrent scanner / future shared queue | Up to one full scan formula per distinct receiver, plus bounded retry/revalidation pages; journals coalesce duplicate receipts locally | 120s visibility versus up to 15m expiry permits roughly 8 deliveries before expiry alone, and more while scanning; each receiver journals, acks only on its own complete scan. No visibility extension |
+| Malformed/wrong-account/already proven unrelated event | 0 scan S3 | 1 Receive + 1 Delete for definitively irrelevant message; 0 Describe |
| Identity/view/inventory incomplete | No host scan; at most bounded U/E reads on work retry | No Delete; confirmation retry respects cache |
| Delete CAS conflict / ambiguous delete result | Failed 1D; next attempt +1G exact edges key, then repeat only after identity/revision check | No ack from conflict/error |
| Ordinary duty acquire | Existing **1G + 1P** if acquired, plus ordinary restore R; absent lock adds **1L** prefix-empty proof | At most existing confirmation on expired peer |
| Duplicate duty meets live owner/releaser | **1G**, 0P, then **0** until suppression invalidation | No duty-rate describes |
+| Unknown queue iid, complete identity lookup | `ceil(B/1000)L + U G` for B immutable box records; page retries counted; ≤1 LIST +32G/callback; no periodic walk | No Delete until complete verification proves unrelated or departure completes |
+| First due work after upgrade, no local duty basis | Up to **B×N_due G** across B boxes, once per sleeping HA host with due work until suppression changes | Not part of the quiet baseline |
+| Stale peer, stopped/hung but not terminated | 0 new membership S3 | Describe at 30/60/120/300s then ≤12/h/peer indefinitely (free API per spec); one state-change log, ≤1 reminder/hour/peer, existing suspect >10m alarm |
| Gate, HRW, local journal/receipt, inventory projection | **0** | **0** |
R is unchanged: up to five Litestream LISTs plus extra pages per 1,000 L0 files, object GETs, manifest GET and referenced objects; sealed escrow reads/publication remain on ordinary wake. CAS acquisition retains the existing maximum three classification rounds, so gG+pP+lL with 1≤g≤3, 0≤p,l≤g, and L only for absent-prefix proof. Marker obligations and renewals keep their existing cost.
-N=500, A=W=20 gives **540 GETs = $0.000216** at §18's prices, before evidence, completion and ordinary wake costs. Completion adds $0.0000054 uncontended (DELETE free). A fully populated 32-host pass costs at most $0.0000384 in scan GETs. An identity cache of B references adds at most B successful GETs per process lifetime, with explicit bounded retry attempts for failures. No claim that failed identity reads are free.
+N=500, A=W=20, Q=0 gives **600 GETs + 40 PUTs = $0.000440** at §18's prices, before evidence, completion and ordinary wake costs. Completion adds $0.0000054 uncontended (DELETE free). A full 32-host pass with Q=32 costs at most $0.0004096 (224 GETs +64 PUTs), excluding retries/evidence/completion. A new durable identity cache of B references adds B successful GETs once, with explicit bounded retry attempts for failures. The durable identity cache survives process restarts. No claim that failed identity reads, paginated unknown-iid discovery or conflicting adoption attempts are free. Budget and test each; the quiet known-identity path still performs no new LIST.
One successful edges deletion causes the existing coalesced fold: per reader `ceil(B/1000)L+B*G`. Existing cap is `120*(ceil(B/1000)+B)` requests/hour/box. Quiet S3 baseline remains §18's **3,300–3,500/hour**, not additional allowance. SQS's ~180/h applies to empty long polls; event bursts/redeliveries add receives. Use MaxNumberOfMessages=1, WaitTimeSeconds=20, VisibilityTimeout=120 on Receive; no ChangeMessageVisibility, SendMessage or new IAM permission. Empty early responses are paced to 20s; errors back off 1,2,4,8,16,30s with bounded jitter, cancelable. Scanner retries run on the existing 30s callback with 30/60/120/300s backoff, one worker and 32 hosts/pass. Receives continue independently of long scans.
-Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/dev/region-ie.tf:9`, `region-ie-b.tf:13`); each polls its own authorized existing queue. A future shared group queue distributes messages. Do not point leo at sophie's queue and assume its existing IAM permits that. Queue URL is supplied from `termination_queue_url` into optional `CARLOS_TERMINATION_QUEUE_URL`; URL/account/region validation happens once, with no inferred URL or discovery poll. Missing URL means not started, with a notice; no IAM widening to make configuration work.
+Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/dev/region-ie.tf:9`, `region-ie-b.tf:13`); each polls its own authorized existing queue. A future shared group queue distributes messages. Do not point leo at sophie's queue and assume its existing IAM permits that. Queue URL is supplied from `termination_queue_url` into optional `CARLOS_TERMINATION_QUEUE_URL`; URL/account/region validation happens once, with no inferred URL or discovery poll. Missing URL means not started, with a notice; no IAM widening to make configuration work. Fixed boxes require the deployment release/config operator to write each queue output into root-owned mode-0600 `/etc/carlos/host.env`, then restart `carlos-edge.service` (`internal/host/units/carlos-edge.service:18`; `infra/modules/region-host/variables.tf:47` says the module does not write host.env). Adding `hostenv.Optional` only enables future group SSM delivery. Include the fixed-box config update, rollback value and restart in the approved release card; a bare restart has a reported ~11s tenant outage, to measure on the built revision, plus up to 20s first empty receive before Started. Never silently substitute a reload for env replacement.
+
+**P2-6 / completion permissions:** `host_store` exists when `store_bucket_prefix` is set (`infra/modules/region-host/main.tf:693–694`); its explicit deployment/data-bucket DeleteObject Deny (:719–728) defeats the existing Allow. Dev host_ie sets the prefix (`platform-infrastructure/dev/region-ie.tf:27`). T's live activation/5B apply is blocked until **`region-host-store-deny` is merged, released and consumed by the dev root** and the saved plan proves no reintroduction of this Deny on existing or disposable roles. Do not implement or review that unmerged design here, depend on a hand-edited live policy, or add another Allow. The card must show the resolved module revision, exact policy diff and effective edges-delete/legacy-release permissions for every affected role. If the saved plan restores the Deny, refuse the apply before requesting approval. AccessDenied during completion stays pending, preserves edges/message and emits one permission-fault alert until policy changes; no hourly page loop or false ack.
## Review Focus
-1. **Empty home placement and pool mismatch:** Task B3 `TestDepartureHomeScopeAndPools` uses dev-shaped records; an unserved matching host keeps completion false.
+1. **Empty home placement and pool mismatch:** Task B3 `TestDepartureHomeScopeAndPools` uses dev-shaped records and explicit-null refusals; CheckCoverage rejects partial receivers before Receive (B4 two-receiver witness).
2. **Scanner dies after importing one host, before ack:** B4/B5 restart on a different registry and replay through real import; every durable obligation survives and no early delete occurs.
-3. **Replay races delivery, registration, ordinary restore or hostname recreation:** B2 transaction/CAS witnesses preserve advanced rows and refuse old lifetimes.
+3. **Replay races delivery, registration, ordinary restore or hostname recreation:** B2 adoption-CAS witnesses preserve advanced rows and refuse old lifetimes; newly acquired restore installs S3 exactly, including an interim holder's new once-timer.
4. **Queue empty, construction fails, or cancellation wins startup:** B3 lifecycle tests establish exactly when Started/Running/Done change; no fake P3 boolean.
-5. **Held terminated owner has time left, or final wake publication lands late:** B4 waits the expiry deadline and re-reads before completion; B5 proves zero pre-expiry starts.
+5. **Held terminated owner has time left, or final wake publication lands late:** B4 waits the expiry deadline and re-reads before completion; B5 proves zero pre-expiry takes and starts, +48h delivery after restart and discovery after two sequential departures.
---
@@ -204,9 +248,9 @@ Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/
**Files:** create `internal/activator/haduties.go`, `haduties_test.go`; modify the activator/acquire, schedule, worker boot and run seams in the file map; create `internal/host/haduties_wiring_test.go`. B2 supplies persistent duty state; declare those interfaces first, then integrate before landing T.
-**Interfaces:** `DecideDuty(DutyInput) DutyDecision`; `Service.Duty(ctx context.Context, rt registry.Route) (DutyDecision, error)`; decisions Attempt/Inspect/Defer/AdvanceOldTick; Inspect is the first-duty discovery above and grants no write on its own. Inputs name lifetime, self, owned-awake, local duty basis, suppression and compatible serving refs. Add `Service.WithDuty(ctx context.Context, rt registry.Route, work func(context.Context) error) error` to carry the duty restriction through the existing singleflight wake; foreground callers joining that wake must not inherit a permanent background refusal. `AcquireHAForDuty` is as defined above; no second authority implementation.
+**Interfaces:** `DecideDuty(DutyInput) DutyDecision`; `Service.Duty(ctx context.Context, rt registry.Route) (DutyDecision, error)`; decisions Attempt/Inspect/Defer/AdvanceOldTick; Inspect is the first-duty discovery above and grants no write on its own. Inputs name lifetime, self, owned-awake, finalized local duty basis, suppression and per-host eligible serving refs from the projection defined above. Add `Service.WithDuty(ctx context.Context, rt registry.Route, work func(context.Context) error) error` to carry the duty restriction through the existing singleflight wake; foreground callers joining that wake must not inherit a permanent background refusal. `AcquireHAForDuty` is as defined above; no second authority implementation.
-- [ ] **Step 1: Write failing tests.** `TestHADutyOwnerTable` covers awake holder, sleeping releaser/adopter, unknown HRW starter, pre-upgrade releaser with no new duty row, localDenied, missing view, peer release and HA switch-off. `TestHADutyTickAge` asserts 14m59s retained, 15m advanced, guarded registration and once-timer preservation. `TestHADutySuppressLivePeer` asserts one lock GET across 20 sweeps, then retry on view departure/confirmation. `TestHADutyBeforeEveryProducer` drives schedule Tick, due sweep, worker boot/sweep and both run sinks; losing box makes zero token-mint, RunPick or start calls. `TestDutyAcquireRestrictionOnly` checks every acquire state including equality at expiry and three-round CAS reclassification.
+- [ ] **Step 1: Write failing tests.** `TestHADutyOwnerTable` covers awake holder, sleeping releaser/adopter, unknown HRW starter, pre-upgrade releaser with no new duty row, localDenied, missing view, peer release and HA switch-off. `TestHADutyNeverWokenPool` places a hapair host beside a shared-only peer whose raw HRW score wins; exclude that peer and deliver on the in-pool box without a visitor (main `wakeplacement.go:168`, I3). `TestHADutyTickAge` asserts 14m59s retained, 15m advanced, guarded registration and once-timer preservation. `TestHADutySuppressLivePeer` asserts one lock GET across 20 sweeps, then retry on view departure/confirmation. `TestHADutyBeforeEveryProducer` drives schedule Tick, due sweep, worker boot/sweep and both run sinks; losing box makes zero token-mint, RunPick or start calls. `TestDutyAcquireRestrictionOnly` checks every acquire state including equality at expiry and three-round CAS reclassification.
- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/lease ./internal/schedule ./internal/host -run 'TestHADuty|TestDutyAcquire' -count=1`; expected failures at the missing gate/observed effects.
- [ ] **Step 3: Implement** the single policy, local suppression/deadlines and restriction callback. Evaluate schedule ownership before Token; ordinary restored token preparation remains in ServeScheduled. A held result leaves younger timers queued, not marked as a failed delivered tick. Gate run pickup before `sinkFor`/`Pickup` and recheck ownership before exec. Preserve co-spawn's holder attachment, WebSocket backhaul, static and housekeeper behavior. Never hold `a.mu` across registry or store calls.
- [ ] **Step 4: Run the same tests**, plus existing schedule/escrow/instance-key tests for changed entry points. Prove no new token/key before restore and no HTTP forwarding of ticks. Test visitor/background wake coalescing and lease loss during delivery.
@@ -216,63 +260,63 @@ Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/
**Files:** new `internal/activator/haadopt.go`, `haadopt_test.go`; new `internal/registry/ha_duties.go`, `ha_departures.go` and tests; modify registry initialization/remote dispatch, timer/next_due mutations, `internal/hostfiles/wake.go`, ordinary restore in `hawake.go`.
-**Interfaces:** AdoptHost/Adoption/AdoptResult and ImportHAWake above. `hostfiles.ImportWake` retains its existing public signature and delegates its three changes to one registry transaction. Registry exposes `HADuty(host, lifetime string) (DutyState, bool, error)` and guarded revision/receipt operations to B1; it does not import activator or hostfiles (convert wire timers at the hostfiles boundary).
+**Interfaces:** AdoptHost/Adoption/AdoptResult, adoption-only ImportHAWake and lease-authoritative ReplaceHAWake above. AdoptHost owns import → ordinary acquire → exact wake-state validation → unclean self release → readback → committed adoption. All phase replay uses that entry. `hostfiles.ImportWake` retains its existing public signature and delegates its three changes to one registry transaction. Registry exposes `HADuty(host, lifetime string) (DutyState, bool, error)` and guarded revision/receipt operations to B1; it does not import activator or hostfiles (convert wire timers at the hostfiles boundary).
-- [ ] **Step 1: Write failing tests.** `TestHAAdoptAtomic` injects failure before each write and COMMIT: all old rows or all imported rows, never mixed; close/reopen DB after each crash point. `TestHAAdoptReplay` imports, delivers/advances a timer, then repeats the same receipt: no resurrection. `TestHAAdoptRaces` registers a same-name new once-timer, consumes next_due, starts a visitor wake, and replaces the route lifetime during manifest I/O. `TestHAAdoptManifestBoundary` covers absent wake entry, absent referenced object, bad digest/origin/V/Host/replication, duplicate timer names and malformed timer kinds/specs. Count zero DB/file-tree/sealed-secret GETs. `TestHAAdoptRemoteParity` runs the transaction through the actual remote registry transport. `TestHAAdoptThenOrdinaryRestore` preserves newer registration/delivery against an older restored wake object.
+- [ ] **Step 1: Write failing tests.** `TestHAAdoptAtomic` injects failure before each write and COMMIT: all old rows or all imported rows, never mixed; close/reopen DB after each crash point. `TestHAAdoptReplay` imports, delivers/advances a timer, then repeats the same receipt: no resurrection. `TestHAAdoptRaces` registers a same-name new once-timer, consumes next_due, starts a visitor wake, and replaces the route lifetime during manifest I/O. `TestHAAdoptManifestBoundary` covers absent wake entry, absent referenced object, bad digest/origin/V/Host/replication, duplicate timer names and malformed timer kinds/specs. Count zero DB/file-tree/sealed-secret GETs. `TestHAAdoptRemoteParity` runs the transaction through the actual remote registry transport. `TestHAAdoptThenOrdinaryRestore` has an interim holder register a new once-timer and publish; a later acquire on the former adopter must install that manifest exactly despite a higher local revision and advisory old-tick advancement. `TestHAAdoptAuthority` covers held/clean/unclean locks, no work due yet, expiry equality, acquire CAS races, marker PUT failure/412/ambiguous response, death at every phase and process restart. Only a verified self marker or validated successor discharges the host; no tenant/file restore/secret publish occurs (lease/ha.go:96, release.go:24,87; I1/I2/I3).
- [ ] **Step 2: Run** `nice -n 19 go test ./internal/registry ./internal/hostfiles ./internal/activator -run 'TestHAAdopt|TestImportWake' -count=1`; expect the transaction/replay cases to fail against the current three writes.
-- [ ] **Step 3: Implement** the journal schema, transaction and per-host revision guards. Validate all input before beginning effects. AdoptHost uses the existing files store/prefix and validates lifetime via the current record/index; no arbitrary prefix parameter. Stage I/O outside locks and commit only against the captured revision. Add cleanup at route retirement, but retain receipt history needed to reject replay. No import writes an instance env file, changes a lease or marks an unproven host locally reusable.
+- [ ] **Step 3: Implement** the journal schema, transaction and per-host revision guards. Validate all input before beginning effects. AdoptHost uses the existing files store/prefix and validates lifetime via the current record/index; no arbitrary prefix parameter. Stage I/O outside locks and commit only against the captured revision. Add cleanup at route retirement, but retain receipt history needed to reject replay. The registry import alone writes no lease/env file and grants no duty authority. Finish adoption only through the central finalizer; its ordinary acquire/release changes the lock, with no claim of local-copy reuse.
- [ ] **Step 4: Run the same tests**, ordinary wake restore/once-timer tests and the schema/remote round-trip checks. Assert an adopted held host remains unable to start until existing acquire allows it. No golden test that merely mirrors SQL.
- [ ] **Step 5: Commit** `ha: import departure wake state atomically`.
### Task B3: Evidence, one consumer and independent start acknowledgment [T; own review: termination]
-**Files:** new `internal/hadeparture/*`, `internal/awsterminations/*`, `internal/host/hadepartures.go`; new `internal/provision/departure_inventory.go`; new `internal/edge/hadepartures.go`; modify agent, hatakeover, confirmer, home-map, both reconciles, hostenv allowlist and SDK module files.
+**Files:** new `internal/hadeparture/*`, `internal/awsterminations/*`, `internal/host/hadepartures.go`; new `internal/provision/departure_inventory.go`; new `internal/edge/hadepartures.go`; modify agent, hatakeover, confirmer, home-map, both reconciles, RecordView refresh provenance, hostenv allowlist and SDK module files. Include fixed-box host.env delivery in the deployment release card, not in the group-only allowlist.
-**Interfaces:** Lifecycle/Queue/Start/Enqueue above. `armHADepartures` takes the same confirmer installed at `agent.go:485`, registry, service, stores and immutable view/inventory callbacks; returns controller/lifecycle or a typed initialization error. Edge exposes `WithDepartureTick(func(context.Context, DepartureView))`; invoke after the existing poll on every 30s tick, including skipped/error folds. Controller exposes `Tick(context.Context, DepartureView) error`, used for age suspicion and pending retries. Tick may schedule asynchronous work but never blocks the fold on a full scan.
+**Interfaces:** Lifecycle/Queue/Start/Enqueue above. `armHADepartures` takes the same confirmer installed at `agent.go:487`, registry, service, stores and immutable view/inventory callbacks; returns controller/lifecycle or a typed initialization error. Edge exposes `WithDepartureTick(func(context.Context, DepartureView))`; invoke after the existing poll on every 30s tick, including skipped/error folds. Controller exposes `CheckCoverage(InventorySnapshot, LocalPolicy) CoverageResult` with Ready/Waiting/Refused and record-bound reasons; Start and every inventory change use it. Add the durable verified-identity repository and bounded unknown-iid lookup described above. Controller exposes `Tick(context.Context, DepartureView) error`, used for age suspicion and pending retries. Tick may schedule asynchronous work but never blocks the fold on a full scan.
-- [ ] **Step 1: Write failing tests.** `TestTerminationConsumerLifecycle` covers successful empty receive, client/attributes failure, initial receive failure then recovery, repeated Start, cancel before first success, cancel during Receive/import, bounded Stop and unexpected exit. `TestTerminationEventEvidence` supplies event-only, wrong account/region, stopped/shutting-down/not-found, poisoned ref/iid, duplicate iid, self and invalid signatures; no scan/deletion follows. `TestDepartureHomeScopeAndPools` uses cloud eu-west-1, placement "", hapair-a1/pool hapair, plus shared/cohort1 and foreign-region records. `TestDepartureAgeOnSkippedFold` holds change-index generation constant, advances past 15m, and proves one queued confirmation on the real tick with zero extra S3 membership calls. `TestRequestConfirmationEnqueues` tests cached-positive retries after journal failure. `TestDepartureInventoryComplete` includes hidden sidecars and an out-of-pool record; incomplete family/record scans cannot certify coverage.
+- [ ] **Step 1: Write failing tests.** `TestTerminationConsumerLifecycle` covers successful empty receive, client/attributes failure, initial receive failure then recovery, repeated Start, cancel before first success, cancel during Receive/import, bounded Stop and unexpected exit. `TestTerminationEventEvidence` supplies event-only, wrong account/region, stopped/shutting-down/not-found, poisoned ref/iid, duplicate iid, self and invalid signatures; no scan/deletion follows. `TestDepartureHomeScopeAndPools` uses cloud eu-west-1, placement "", hapair-a1/pool hapair, plus shared/cohort1 and foreign-region records; omitted/empty placement is home, explicit null is malformed, on self and peers (main homemap.go:168,788; I3). `TestDepartureAgeOnSkippedFold` holds change-index generation constant, advances past 15m, and proves one queued confirmation on the real tick with zero extra S3 membership calls. `TestRequestConfirmationEnqueues` tests cached-positive retries after journal failure. `TestDepartureInventoryComplete` includes hidden sidecars and an out-of-pool record; incomplete family/record scans cannot certify coverage. `TestDepartureSidecarPreflight` includes an asleep legacy native sidecar with no lock, in/out of local pools, and an awake sidecar: T refuses all in the exact regional scope before Receive/Started; sidecars in another placement do not refuse. Insert one after startup: complete any already admitted instance transaction but retain edges/receipt and suspend with one C8 (hawake.go:77; I3). `TestDepartureIdentityWithoutEdges` reopens the durable verified map after edges deletion, plus an unknown iid discovered through immutable records, unrelated iid, poisoned binding and partial list; only proven unrelated gets acked without scanning (boxid/record.go:38; I3). `TestDepartureInventoryAfterEvidence` adds a just-created/woken host after the old snapshot, confirms D, then skips the index: no completion until both fresh source and full pass start after confirmation; the new host is recovered (agent.go:931, changeindex.go:147; I3).
- [ ] **Step 2: Run** `nice -n 19 go test ./internal/hadeparture ./internal/awsterminations ./internal/host ./internal/edge ./internal/termfence ./internal/provision -run 'TestTermination|TestDeparture|TestRequestConfirmation' -count=1`; expect missing consumer/callback failures.
-- [ ] **Step 3: Implement** the SDK method-value adapter and provider-neutral lifecycle. Receive uses the exact values/bounds in the budget; no queue per departure or visibility extension. Validate configured URL against own cloud identity and attributes; never log receipt handles. Retain existing queue policy. Export inventory completeness before filtering; preserve partial-fold evidence and ETags. On age crossing, failed holder observation or request confirmation, coalesce one journal entry per bound departure. Confirmed evidence cancels duty suppression and records counters without changing N-HA9.
+- [ ] **Step 3: Implement** the SDK method-value adapter and provider-neutral lifecycle. Receive uses the exact values/bounds in the budget; no queue per departure or visibility extension. Validate configured URL against own cloud identity and attributes; never log receipt handles. Retain existing queue policy. Persist source refresh start time separately from pass start time; export inventory completeness before filtering; preserve partial-fold evidence and ETags. On age crossing, failed holder observation or request confirmation, coalesce one journal entry per bound departure. Confirmed evidence cancels duty suppression and records counters without changing N-HA9.
- [ ] **Step 4: Run the same tests**, including method-value binary linking and config disabled/legacy parity. The common arm helper must be called once before service/worker/runner start and stopped by actual agent cancellation; permit one syntactic call/order check only for the uncallable runAgent wrapper, paired with executable helper tests. Test one receiver even when future P3-like lifecycle observation is attached; the observer is only a test consumer of Lifecycle, not a fake drain producer.
- [ ] **Step 5: Commit** `ha: consume termination hints with lifecycle acknowledgment`.
### Task B4: Complete scan before deletion and queue acknowledgment [T; own review: termination/storage]
-**Files:** extend `internal/host/hadepartures.go`, `internal/registry/ha_departures.go`, importer and their tests; add acknowledged conditional-delete/index seam in `internal/release/conditional_delete.go`/`changeindex.go` with tests.
+**Files:** extend `internal/host/hadepartures.go`, `internal/registry/ha_departures.go`, importer, `internal/lease/ha.go` and their tests; add acknowledged conditional-delete/index seam in `internal/release/conditional_delete.go`/`changeindex.go` with tests.
-**Interfaces:** `Controller.ScanPass(ctx context.Context) (progress bool, err error)` runs one bounded page; `Controller.Complete(ctx context.Context, departureID string) error` performs completion phases. Add `release.DeleteIfMatchIndexed(ctx context.Context, s Store, key, etag string) error` for stores that can acknowledge both operations; unsupported stores refuse. Keep existing DeleteIfMatch semantics for other callers. Use raw delete plus one explicit index bump, not the existing automatic bump plus a second bump.
+**Interfaces:** `Controller.ScanPass(ctx context.Context) (progress bool, err error)` runs one bounded page; `Controller.Complete(ctx context.Context, departureID string) error` performs completion phases. Add `release.DeleteIfMatchIndexed(ctx context.Context, s Store, key, etag string) error` for stores that can acknowledge both operations; unsupported stores refuse. Keep existing DeleteIfMatch semantics for other callers. Add `lease.NewLockReader(ctx, region)` with `ReadLock(ctx, bucket, prefix)` reusing one configured client per scan page; retain key validation and readView classification, no per-host client creation (`ha.go:169,174`; request-budget invariant). Use raw delete plus one explicit index bump, not the existing automatic bump plus a second bump.
-- [ ] **Step 1: Write failing tests.** `TestDepartureScanOwnersAndReleasers` scans all records, awake/asleep/sidecar included, matches strict HA owner or marker ref/iid/lifetime, and calls the one importer. `TestDepartureNoEarlyDelete` injects every lock/manifest/object/import/commit failure and verifies edges and receipt remain. `TestDepartureWaitsExpiry` schedules an unexpired dead-owner lock, lands a final wake publication before expiry, and proves final import uses it. `TestDepartureScannerDeath` kills scanner after one import and before each completion phase; a different live registry rescans/redelivers. `TestDepartureDeletionRace` changes the edges ETag/iid, makes Delete succeed with lost response, and fails index bump. `TestDeparturePoolCoverage` cannot complete when a matched host is unserved or a native sidecar is unsupported. `TestDepartureRequestBudget` asserts every budget row, including idle/partial/duplicate and index conflict maxima.
+- [ ] **Step 1: Write failing tests.** `TestDepartureScanOwnersAndReleasers` scans all records, awake/asleep/sidecar included, matches strict HA owner or marker ref/iid/lifetime, and calls the one importer. `TestDepartureNoEarlyDelete` injects every lock/manifest/object/import/commit failure and verifies edges and receipt remain. `TestDepartureWaitsExpiry` schedules an unexpired dead-owner lock, lands a final wake publication before expiry, and proves final import uses it. `TestDepartureScannerDeath` kills scanner after one import and before each completion phase; a different live registry rescans/redelivers. `TestDepartureDeletionRace` changes the edges ETag/iid, makes Delete succeed with lost response, and fails index bump. `TestDeparturePoolCoverage` uses distinct fixed queues: B serves shared, C shared+hapair, D had both; B refuses before polling, C imports all and completes, B never retries/pages hourly. Introduce out-of-pool work during a scan: suspend without deletion/ack. `TestDepartureDeleteDenied` injects AccessDenied at conditional deletion: pending durable progress, one permission alert, no ack; recovery after permission correction does not re-import (main.tf:723; I3). `TestDepartureRequestBudget` asserts every budget row, including idle/partial/duplicate and index conflict maxima.
- [ ] **Step 2: Run** `nice -n 19 go test ./internal/host ./internal/registry ./internal/release -run 'TestDeparture' -count=1`; expect incomplete scans currently lack durable ordering.
-- [ ] **Step 3: Implement** pending → scanning → imported → edges_deleted → indexed → complete. Iterate a stable complete inventory generation; changed records during the scan invalidate their checkpoints. One lock read per host/attempt; do not select from public edges Hosts. Read errors and malformed old locks stay visibly unresolved when they could conceal duties. Never call an out-of-pool match complete. Preserve the SQS message and edges for redelivery to an eligible box; report a scope with no eligible adopter instead of widening tenancy or discarding work. Shared-queue nonchosen receivers do not ack based on HRW.
-- [ ] **Step 4: Implement completion recovery.** Persist full import completion before conditional deletion of the retained revision. On 412 re-read that exact edges key, revalidate the same bound identity, and rescan invalidated work; never delete a replacement box's file. On uncertain response, read back and resume the journal phase. Index failure remains locally pending and unacknowledged; retry the explicit bump, not the scan. Do not fabricate a successful bump from the existing swallowed error. Only after durable completion cancel remaining relevant duty backoffs and Delete the currently received SQS receipt. Delete failure redelivers safely. Known absence alone is never proof that this scanner imported anything.
-- [ ] **Step 5: Run the tests**, plus a two-scanner race where one deletes edges while the other is still importing; the latter must use its retained verified departure, not treat missing edges as success. For scanner death before durable whole-scan completion, the original edges revision and unacknowledged message remain the discovery evidence; a fresh process must re-confirm and rescan rather than rely on the lost scanner journal. Record the boundary separately: local durability proves process-restart replay, while the independent-survivor witness proves partial-scan machine loss. Do not label either as proof of arbitrary simultaneous losses after completed transfer.
+- [ ] **Step 3: Implement** pending → scanning → authority_complete → edges_deleted_or_absent → indexed → complete. Require a passing whole-scope coverage gate and a complete inventory whose source read and full walk started after confirmation. One shared-client lock read per host for classification; matched hosts incur the additional finalizer reads/writes in the budget. Complete only Adopted/AlreadyAdopted/validated Superseded results. Changed/new records invalidate checkpoints and rerun coverage. Unknown lifetimes/read errors/malformed locks cannot conceal duties or become success. Refuse unsupported scope before more work, preserve evidence and report once; do not retry it forever or widen tenancy. No selection from public edges Hosts for the scan census.
+- [ ] **Step 4: Implement completion recovery.** Persist all host authority results before conditional deletion of the retained revision. If edges were already absent, require full scan completion and exact-key absence before the acknowledged index phase. On 412 re-read that exact key, revalidate identity, and rescan invalidated work; never delete a replacement file. Uncertain deletion/index results remain locally pending and unacknowledged. Retry the explicit index bump, not the scan. Do not fabricate success from swallowed errors. AccessDenied is a permission fault, alerted once and blocked pending correction. Only durable completion allows Delete of the currently received receipt; Delete failure redelivers safely. Missing edges is never proof of imports.
+- [ ] **Step 5: Run the tests**, plus two-scanner races, death between every import/acquire/release/commit phase, and restart on a different registry. Use immutable identity records even if another scanner or an operator deleted edges. A transferred host is now discoverable through its adopter's lock/marker; cover that adopter's later termination **before any wake**, alongside partial-scanner death. Test readback after release returns nil on 412. Verify one scan-reader client per page and the counted acquisition/marker/readback requests. Each completed host has recoverable S3 wake state and a named duty owner, not merely a local receipt.
- [ ] **Step 6: Commit** `ha: finish departure imports before removing evidence`.
### Task B5: I6, production witnesses, observability and T landing
**Files:** simulation files in the map; new `internal/host/hadepartures_root_linux_test.go`; counting transport tests; host departure log/metric wiring and `internal/host/metrics_loop.go`; implementation census artifacts only when code exists.
-**Interfaces:** simulation calls production DecideDuty and the production scan-match predicate extracted from B4 (`MatchesDeparture(view hafresh.View, departure Box, lifetime string) bool`). Simulation owns virtual queues/time/crash scheduling; it must not copy either decision table. Host records transfer/confirmation counters and latency into the existing metrics flush, with no new PutMetricData loop.
+**Interfaces:** simulation calls production DecideDuty, CheckCoverage, the adoption phase-transition guard and the production scan-match predicate extracted from B4 (`MatchesDeparture(view hafresh.View, departure Box, lifetime string) bool`). Simulation owns virtual queues/time/crash scheduling; it must not copy these decision tables or turn an import-only receipt into completion. Model EC2 forgetting after 1h, process-local confirmation expiry at 24h, restart, lock generation/marker identity and inventory source/walk timestamps. Host records transfer/confirmation counters and latency into the existing metrics flush, with no new PutMetricData loop.
-- [ ] **Step 1: Write failing I6 tests.** Add durable wake/timer state, registrations, due times, receipt visibility/redelivery, scanner progress and inventory/fold generations to the 2–5-box model. `TestWitnesses` includes held+released departure, scanner death, duplicate import after delivery, lost queue event with no visitors, skipped-index ageing and a timer registered immediately before death whose wake state never synced. After faults stop and a compatible live adopter/store exist, all durable work must eventually deliver within event/age + expiry + bounded scan pages + next runner/sweep; only the final unsynced ~1s timer may be absent. State fairness assumptions; never turn persistent store failure into a false pass.
-- [ ] **Step 2: Add mutations.** `skip-departure-scan`, `scan-owners-not-releasers`, `delete-before-import`, `ack-before-import`, `ignore-termination-event`, `skip-age-on-unchanged-index`, `replay-overwrites-delivered-timer`, `duty-ignores-owner`, `take-before-expiry`, `start-before-client`. Each must have a deterministic witness and be caught; no expected-missed exemption for I6. Startup mutation is an executable wiring mutation, not a model-only boolean.
-- [ ] **Step 3: Build real witnesses.** `TestHADepartureProductionWiring` runs the actual arm helper, queue adapter boundary, shared confirmer, complete reconcile inventory, importer, runner/sweeper and counted stores. `TestHADepartureRootLifecycle` uses separate survivor processes/registries, real ExecBackend acquire/restore, nested instance control and schedule delivery. Mock only EC2/SQS transport and storage endpoints; do not mock successful acquire, AdoptHost, timer delivery or edges deletion. No visitor request is allowed to rescue a missing trigger. Prove another live registry recovers after partial scanner death. Preserve instance key/token identity and one writer. Run through the approved rootrunner; a skipped privileged test is not PASS.
+- [ ] **Step 1: Write failing I6 tests.** Add durable wake/timer state, registrations, due times, receipt visibility/redelivery, scanner progress and inventory/fold generations to the 2–5-box model. `TestWitnesses` includes held+released departure, scanner death, duplicate import after delivery, lost queue event with no visitors, skipped-index ageing and a timer registered immediately before death whose wake state never synced. Add the finding-specific witnesses/mutations in the disposition table: +48h due after restart and EC2 forgetting; E→D→F sequential departures while asleep; native-sidecar scope refusal; never-woken hapair exclusion; missing edges with retained identity; heterogeneous receiver refusal; interim-holder registration; delete denied; post-confirmation fresh inventory. After faults stop and a compatible live adopter/store exist, all durable work must eventually deliver within max(event/age + expiry + bounded scan/finalization pages + qualifying inventory delay, duty due time) + next runner/sweep; only the final unsynced ~1s timer may be absent. The qualifying inventory delay can reach the existing 30m backstop +10% jitter (`release/changewatch.go:17`, host/changeindex.go:175), with no new polling. State fairness assumptions, including one fully covering admitted survivor and initial confirmation before EC2 forgets; future-due work after completed adoption needs no such evidence window; never turn persistent store failure into a false pass.
+- [ ] **Step 2: Add mutations.** `skip-departure-scan`, `scan-owners-not-releasers`, `delete-before-import`, `ack-before-import`, `ignore-termination-event`, `skip-age-on-unchanged-index`, `replay-overwrites-delivered-timer`, `duty-ignores-owner`, `take-before-expiry`, `start-before-client`. Each must have a deterministic witness and be caught; no expected-missed exemption for I6. Add every finding-specific mutation from the disposition table and record its deterministic witness; refuse-scope mutations must fail at preflight, not pass by timing out liveness. Startup mutation is an executable wiring mutation, not a model-only boolean.
+- [ ] **Step 3: Build real witnesses.** `TestHADepartureProductionWiring` runs the actual arm helper, queue adapter boundary, shared confirmer, complete reconcile inventory, importer, runner/sweeper and counted stores. `TestHADepartureRootLifecycle` uses separate survivor processes/registries, real ExecBackend acquire/restore, nested instance control and schedule delivery. Mock only EC2/SQS transport and storage endpoints; do not mock successful acquire, AdoptHost, timer delivery or edges deletion. No visitor request is allowed to rescue a missing trigger. Prove another live registry recovers after partial scanner death and after a completed adopter later terminates while its host remains asleep. Use a virtual clock for +48h/cache-expiry witnesses; do not sleep for days. Include actual readback and 412/AccessDenied transports, stale RecordView provenance and the two fixed-queue receivers. Preserve instance key/token identity and one writer. Run through the approved rootrunner; a skipped privileged test is not PASS.
- [ ] **Step 4: Run once per implementation revision:** `RHASIM_SEEDS=3000 nice -n 19 go test ./internal/sim/regionha -run '^TestRegionHA$' -count=1`; build its test binary under owned `/home/paulca/t/` and run `RHASIM_PAR=1 nice -n 19 internal/sim/regionha/mutate.sh <binary> 3000 <new-rules>`. Record failing mutation seeds and witness names. Use targeted deterministic tests during fixes; no repeated full sweep without a new revision.
-- [ ] **Step 5: Wire §20 evidence.** Structured transfer/confirmation logs carry host, lifetime, dead ref/iid, scan ID, result and latency. Metrics carry counts/age/latency without per-host cardinality. Export oldest pending scan and consumer start/error state through the existing status/metrics path. On incomplete recovery, emit C3 once per departure/hour/process; C4 only after durable completion. Queue oldest-message >10m alarm remains part of the scoped infrastructure card, using the existing queue; do not create it from the box. Suspect-holder >10m and existing alarms remain intact. A stopped consumer before startup cannot report healthy start.
+- [ ] **Step 5: Wire §20 evidence.** Structured transfer/confirmation logs carry host, lifetime, dead ref/iid, scan ID, result and latency. Metrics carry counts/age/latency without per-host cardinality. Export oldest pending scan and consumer start/error state through the existing status/metrics path. On transient incomplete recovery, emit C3 once per departure/hour/process; unsupported coverage and permission faults instead emit once per durable fault/configuration generation, with status retained until corrected; C4 only after durable completion. Queue oldest-message >10m alarm remains part of the scoped infrastructure card, using the existing queue; do not create it from the box. Suspect-holder >10m and existing alarms remain intact. A stopped consumer before startup cannot report healthy start.
- [ ] **Step 6: Obtain accepted copy and complete census**, then run build/vet/format/test once and cross-compiles. Review T's full diff against current amadan main, including all new registry/provision/release/SDK surfaces. Use the bounded review rules; no automatic extra review after P2 fixes.
- [ ] **Step 7: Commit** `ha: prove unattended departure duty recovery`. At implementation time only: push to amadan, describe exact scope/restrictions/tests/review, check green CI at the full tip and squash-land through `amadan branch merge -expect`; read main CI afterward. This planning commission stops at its local commit and never runs those commands.
### Task B6: Native sidecars born HA [S; needs the decision below; own review]
-**Files:** `internal/provision/sidecar.go`, `sidecar_reconcile.go`, `internal/console/apisidecars.go:223,330,598` and its tests; `internal/activator/hawake.go`, worker acquire/restore/files paths; B1/B2/B4 tests, sidecar record-write inventories and census. No CLI verb is added.
+**Files:** `internal/host/edgesfile.go`, `internal/edgesfile` snapshot schema, `internal/edge/homemap.go` duty projection and tests; `internal/provision/sidecar.go`, `sidecar_reconcile.go`, `internal/console/apisidecars.go:223,330,598` and its tests; `internal/activator/hawake.go`, worker acquire/restore/files paths; B1/B2/B4 tests, sidecar record-write inventories and census. No CLI verb is added.
**Decision proposed:** extend the existing new-record HA stamp to native sidecars created in configured HA regions, with the same empty home-scope resolution as instance creation. Add `HA bool` with `json:"ha,omitempty"` to SidecarRecord; absent remains legacy. Every actual record-creation path (create, enable/auto-create) must stamp/refuse before writes. Existing sidecars and co-spawn children do not change classification. No migration by enabling a box switch.
-**Interfaces:** derive the sidecar lifetime from canonical account/app/synthetic host/CreatedAt; populate the existing lifetime index and sticky route HA bit. `haLegacyRoute` retains legacy behavior for unprovisioned/unstamped sidecars, but stamped, proven native sidecars use the same HA containment/acquire/restore/release/import path as an instance. They remain `IsSidecar()`, socketless and explicitly refused at ingress. Reuse AdoptHost; no sidecar-specific transfer protocol.
+**Interfaces:** derive the sidecar lifetime from canonical account/app/synthetic host/CreatedAt; populate the existing lifetime index and sticky route HA bit. `haLegacyRoute` retains legacy behavior for unprovisioned/unstamped sidecars, but stamped, proven native sidecars use the same HA containment/acquire/restore/release/import path as an instance. They remain `IsSidecar()`, socketless and explicitly refused at ingress. Reuse AdoptHost, including the unclean self-marker finalizer; no sidecar-specific transfer protocol. Publish the optional `served_pools` eligibility field from actual reconcile policy and require it for sidecar HRW as defined above; validate exact pool names, preserve explicit shared pool, reject malformed/unknown values. Include this additive wire schema and every reader in S's census/review. Legacy native sidecars still fail CheckCoverage.
-- [ ] **Step 1: Write failing tests** `TestSidecarHABirthOnly` (all create paths, configured home region with record region "", absent stamp remains legacy), `TestSidecarHADutyLifecycle` (real worker acquire, wake-state publish, sleep marker, dead-releaser scan, import, due wake), `TestSidecarHARefusals` (uncontained layout/unknown lifetime/shared secrets unavailable before writes/start), and `TestSidecarNeverAdvertisedOrDialled`. Inherit P2a's supported shape/capacity/move/import refusals rather than bypass them through the sidecar door.
-- [ ] **Step 2: Run targeted provision/console/activator/host tests** with `-run 'TestSidecarHA|TestSidecarNever' -count=1`; verify the existing unconditional legacy classification is the failing behavior.
+- [ ] **Step 1: Write failing tests** `TestSidecarHABirthOnly` (all create paths, configured home region with record region "", absent stamp remains legacy), `TestSidecarHADutyLifecycle` (real worker acquire, wake-state publish, sleep marker, dead-releaser scan, import, due wake), `TestSidecarHARefusals` (uncontained layout/unknown lifetime/shared secrets unavailable before writes/start), and `TestSidecarNeverAdvertisedOrDialled`. Add `TestSidecarDutyPoolProjection`: a never-woken hapair sidecar excludes a shared-only box despite its winning raw HRW, empty/absent/null pool fields differ, and no synthetic public Hosts entry is published. Inherit P2a's supported shape/capacity/move/import refusals rather than bypass them through the sidecar door.
+- [ ] **Step 2: Run targeted provision/console/activator/host tests** with `-run 'TestSidecarHA|TestSidecarNever|TestSidecarDutyPool' -count=1`; verify the existing unconditional legacy classification is the failing behavior.
- [ ] **Step 3: Implement the additive birth stamp and contained worker lifecycle.** Check that the worker uses the real files publisher and ~1s WakeItem sync, imports before due delivery and publishes restored/new secrets before launch. Do not settle for setting the route bit. Legacy locks/records remain legacy; an HA-shaped lock under an unstamped unsupported route is refused. Co-spawn remains attached to its parent's acquired lifetime, without a separate duty owner.
- [ ] **Step 4: Extend I6 and the production root witness** with a real standalone sidecar written through the console/provision path. Re-run S's changed-path tests, census and the one per-revision sweep; retain T's history. The full 5B drill cannot pass before this witness.
- [ ] **Step 5: Commit** `ha: preserve duties for native sidecars born HA`; land through the same reviewed amadan gate when S is authorized. If Paul defers S, leave this task unimplemented and keep native-sidecar acceptance explicitly incomplete.
@@ -282,12 +326,12 @@ Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/
**This task prepares a reviewable card before requesting scoped approval.** No live mutation is authorized by this plan. Never terminate sophie-knitting or leo-climbing. A process kill is not EC2 termination evidence. No drain drill until P3's real drained producer and durable completion integration are merged.
- [ ] **Step 1: Assemble read-only evidence and the exact card.** Private root `/home/paulca/amadan.net/carlos/platform-infrastructure/dev`, current account identity (historical #421 account **640012953448**, reverify), AWS **eu-west-1**, cloud resource IDs, both queue URLs/IAM scopes, exact third-box module/instance/profile/SG/subnet/EBS/EIP resources, and instance type/count/expiry. Name exact app/account/hosts/domains/record and data prefixes. Confirm existing dev records remain `region:""`; hapair-a1/pool hapair is an existing fixture, usable only if included in approval. Verify the merged home-placement fix is in the deployed binary. Do not change `CARLOS_REGION`.
-- [ ] **Step 2: Specify effects/cost/cleanup before asking.** One disposable third **fixed** box in pool hapair, exact role/resource changes from a saved whole-root plan and targeted closure, any new module-owned queue/rule/IAM resources explicitly enumerated rather than called “no infra change.” T uses existing queues; provisioning C may create its own module resources. No ASG or NLB needed. List dev-only binary roll, `CARLOS_REGION_HA=1`, each box's own queue URL, console isolation from host.env, permitted restarts, temporary records/timer writes and EC2 termination of **C's exact iid only**. No customer DNS/traffic shift. Produce a currency estimate from the selected instance/storage/IP/queue/metric/alarm prices with a numeric cap and at most **2 hours**; unresolved IDs/cost make the card non-approvable. Name the operator, cleanup owner, expiry and verification commands. S3-loss/negative-evidence tests stay local unless separately added to the card.
+- [ ] **Step 2: Specify effects/cost/cleanup before asking.** First prove the merged/released `region-host-store-deny` dependency is consumed and the saved plan does not restore the deployment/data-bucket DeleteObject Deny on sophie/leo/C; attach effective-policy evidence for edges deletion and legacy release. Refuse an unsafe plan before approval or apply. One disposable third **fixed** box in pool hapair, exact role/resource changes from a saved whole-root plan and targeted closure, any new module-owned queue/rule/IAM resources explicitly enumerated rather than called “no infra change.” T uses existing queues; provisioning C may create its own module resources. No ASG or NLB needed. List dev-only binary roll, `CARLOS_REGION_HA=1`, each box's own queue URL, root-owned 0600 fixed-box host.env delivery and rollback (not only hostenv.Optional), console isolation, permitted restarts with ~11s reported outage and measured first-poll/admission delay, temporary records/timer writes and EC2 termination of **C's exact iid only**. No customer DNS/traffic shift. Produce a currency estimate from the selected instance/storage/IP/queue/metric/alarm prices with a numeric cap and at most **2 hours**; unresolved IDs/cost make the card non-approvable. Name the operator, cleanup owner, expiry and verification commands. S3-loss/negative-evidence tests stay local unless separately added to the card.
- [ ] **Step 3: Ask for one scoped approval** of that concrete account/region/domain/resources/permissions/traffic/cost/duration/cleanup card. T's implementation approval or a prior dev release is not this approval. The production-infrastructure rule in AGENTS.md requires it. No repeated per-call questions within the approved scope.
-- [ ] **Step 4: Prepare real duties on C.** Verify exact built binary/revision, identity records, consumer Started, fresh compatible edges, nested/escrow readiness and all intended records on eligible survivors. On C create one held born-HA instance, one cleanly released born-HA instance, synced once-timers and next_due, plus an S-born native sidecar. Use real worker/sleep paths. Read exact manifest/wake digests and record UTC sync acknowledgments; preserve token/key fingerprints without printing secrets. Keep all visitor probes off after setup. T's earlier restricted drill omits sidecar only under an explicit restricted acceptance label, never a full 5B PASS.
-- [ ] **Step 5: Terminate C through EC2 and observe unattended recovery.** Log API time, confirmed terminated state, original expiry, queue receipt, scan/import transaction, timer delivery and conditional edges deletion/index/ack. No start before expiry; for held work measure remaining TTL separately from scan/delivery latency. Normal event bound is event/describe latency + remaining lease + `ceil(N/32)*30s` scan allowance + ≤30s delivery sweep plus restore. Do not quote the pre-fencing 1–3m estimate as a guarantee. Reader convergence after acknowledged index is about 30s.
+- [ ] **Step 4: Prepare real duties on C.** Verify exact built binary/revision, identity records, consumer Started, fresh compatible edges, nested/escrow readiness and all intended records on eligible survivors and a passing executable full-scope CheckCoverage on every activated receiver; no legacy native sidecar may be hidden by an absent lock or pool filter. On C create one held born-HA instance, one cleanly released born-HA instance, synced once-timers and next_due, plus an S-born native sidecar. Include a future-due timer to verify the adopter's unclean marker before leaving the host asleep; +48h and sequential-departure tests use the local virtual-clock/root witnesses, not an extension of the two-hour live approval. Use real worker/sleep paths. Read exact manifest/wake digests and record UTC sync acknowledgments; preserve token/key fingerprints without printing secrets. Keep all visitor probes off after setup. T's earlier restricted drill omits sidecar only under an explicit restricted acceptance label, never a full 5B PASS.
+- [ ] **Step 5: Terminate C through EC2 and observe unattended recovery.** Log API time, confirmed terminated state, original expiry, queue receipt, scan/import transaction, timer delivery and conditional edges deletion/index/ack. No start before expiry; for held work measure remaining TTL separately from scan/delivery latency. Normal event bound includes event/describe latency, remaining lease, a qualifying full inventory refresh (up to the existing 33m backstop bound), `ceil(N/32)*30s` scan/finalization allowance and ≤30s delivery sweep plus restore; future-due timers are measured from their due time. Do not quote the pre-fencing 1–3m estimate as a guarantee. Reader convergence after acknowledged index is about 30s.
- [ ] **Step 6: Exercise partial scanner death safely.** Local multi-process/root witnesses already prove another-registry recovery. Keep live scope to the disposable third box; use the separate-process rootrunner witness to kill the confirming scanner after one import and resume on another survivor, without adding a fourth live box or terminating sophie/leo. Attach that exact built-revision result to the card and label the fault as local production-path coverage, not a live kill on dev. No production fault flag, fake EC2 proof or drained flag. Queue redelivery/age retry must recover remaining hosts without a visitor.
-- [ ] **Step 7: Prove loss bound and cleanup.** Every recorded durable timer/next_due delivered; only an intentionally unsynced final ~1s timer may be lost. H7 duplicate delivery is recorded, not called exactly-once. Compare the built revision's counting-transport budget report; journals cannot prove exact AWS API counts. Remove approved disposable resources and temporary records/prefixes, restore prior config through the release operator, verify sophie/leo instance IDs and `CARLOS_REGION` unchanged, consumers/pair healthy and no scratch/processes left. Keep app logs/evidence specified by the card. Report pass/fail and timings to the controller for #421; no flagship roll or G3 claim.
+- [ ] **Step 7: Prove loss bound and cleanup.** Every recorded timer/next_due due within the live window delivered; future-due timers retain a verified adopter marker and match the attached +48h local witness; only an intentionally unsynced final ~1s timer may be lost. H7 duplicate delivery is recorded, not called exactly-once. Compare the built revision's counting-transport budget report; journals cannot prove exact AWS API counts. Remove approved disposable resources and temporary records/prefixes, restore prior config through the release operator, verify sophie/leo instance IDs and `CARLOS_REGION` unchanged, consumers/pair healthy and no scratch/processes left. Keep app logs/evidence specified by the card. Report pass/fail and timings to the controller for #421; no flagship roll or G3 claim.
## Drain integration hook, deliberately not wired
@@ -295,7 +339,7 @@ Reserve the name `EnqueueDrained` for P3's future verified drain-completion inpu
## Copy deck for controller → Luna
-Draft source strings only. No Luna invocation or approval claimed. Obtain accepted text before writing product destinations; preserve placeholders and IDs. Structured field names, metric identifiers and internal sentinel errors are not prose, but wrapping them in notices is. Inventory any additional strings discovered during implementation rather than quietly shipping them.
+Draft source strings from rev 1, unchanged. Before implementation, revise the deck for terminal scope refusal and permission faults: C3 retry wording is only for transient failures, C7/C8 need the reconfiguration/refusal context, and C10 must not promise automatic resumption after a scope fault. Route those revisions through the controller's copy approval before product writes. No Luna invocation or approval claimed. Obtain accepted text before writing product destinations; preserve placeholders and IDs. Structured field names, metric identifiers and internal sentinel errors are not prose, but wrapping them in notices is. Inventory any additional strings discovered during implementation rather than quietly shipping them.
| ID | Destination | Draft text | Context / constraints |
|---|---|---|---|
@@ -324,8 +368,8 @@ The rootrunner witness must run with the built revision, not a stale `CARLOS_BIN
1. **Native sidecars:** approve S's proposed **birth-only HA sidecar extension**, or defer standalone-sidecar acceptance and keep T/P3a activation restricted to scopes with no such duties? Recommendation: land the useful T slice first, then approve S; do not silently reverse P1a's legacy-sidecar rule. Full §7/5B acceptance requires S or an explicitly revised scope.
2. **Switch-on slot:** reserve the next dev-only T release and restricted unattended-timer drill, then review the fully populated disposable-box card for S/5B. No resource mutation approval is requested by this planning commit.
-The bounded scanner-death acceptance is death before whole-scan completion, as §7.4 and the parent outline specify. Repeated failures after completion while adopted hosts still name an earlier dead releaser need a separate explicit coverage witness before claiming tolerance of that failure sequence; this plan does not quietly substitute local disk durability for surviving machine loss. Pool-restricted receivers cannot complete another pool's duties; unsupported scopes retain evidence and alert. Permanent object loss/EC2 evidence aged out is an operator fault, never guessed termination. Drain acceptance and group-wide liveness wait for their real producers and drills.
+The bounded scanner-death acceptance is death before whole-scan completion, as §7.4 and the parent outline specify. Sequential departures **after** completed adoption are also required: the central finalizer makes the adopted host name its current duty owner before completion. Pool-restricted receivers and legacy-sidecar scopes refuse before polling; a later coverage violation suspends and escalates. Permanent object loss or failure to obtain the **initial** termination proof before EC2 forgets remains unresolved and must be reported, never guessed. Completed adoption must survive expired confirmation caches, agent restart and a visitor on a box that never confirmed the original owner. Drain acceptance and group-wide liveness wait for their real producers and drills.
## Self-review record
-Coverage: §7.1–7.3 → B1/B2, with native-sidecar gap made explicit in S/B6; §7.4/I3 → B2/B4/B5; §4 identity/home scope → B3; §9/N-HA9/N-HA11 → B3/B4; §18 → counted event/pass/quiet formulas; §19 → T first visible merge and activation slot; §20 → B5 and card; §21 → I6 mutations and real process witnesses. P3 receives a provider-neutral, independent lifecycle interface with no drain dependency. Review Focus cases have named tests. Code/file citations were read at 9a064ebe. Planning validation is file/citation/format/diff checks only; no full suites, production code, reviewers, push or live drill.
+Coverage: §7.1–7.3 → B1/B2, with native-sidecar gap made explicit in S/B6; §7.4/I3 → B2/B4/B5; §4 identity/home scope → B3; §9/N-HA9/N-HA11 → B3/B4; §18 → counted event/pass/quiet formulas; §19 → T first visible merge and activation slot; §20 → B5 and card; §21 → I6 mutations and real process witnesses. P3 receives a provider-neutral, independent lifecycle interface with no drain dependency. Review Focus cases have named tests. Rev 2 verified the findings against worktree code and read main's placementNull correction without rebasing; the Base paragraph defines citation provenance. Round 1 remains NOT READY; no second review was run. Planning validation is file/citation/format/diff checks only; no full suites, production code, reviewers, push or live drill.