carlos / platform Public

plans: P1b-3b plan rev 4, final

Apply the closed Opus R3 findings: trust the box role, store termination proofs in the lock region data bucket, and bound proof reads with shared caches. Correct request budgets, record all dispositions, and specify sidecar drill evidence retention.

Review closed after R3 READY AFTER FIXES (0 P1, 3 P2, 3 P3). Plan only; no production code or further review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 85659e82b22109881e25687790f79101c608bb06 parent c8b9784
1 file changed, +47 −27
  • docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md +47 −27

CI passed — run details

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 46df1cfc6..62dfbb757 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,4 +1,4 @@
-# Region HA P1b-3b: local duties and departure recovery Implementation Plan — rev 3
+# Region HA P1b-3b: local duties and departure recovery Implementation Plan — rev 4, final
> **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.
@@ -12,7 +12,7 @@
**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:** rev 3; R2 NOT READY, stopping rule 2, Paul ruled N-HA16/N-HA17; one final round 3.
+**Status:** rev 4, final. Opus R3 READY AFTER FIXES; P2s applied. Review closed.
This is an author revision, not a review verdict. The P3 document was read from `origin/region-ha-p3-group`; its lifecycle dependency does not authorize implementing unmerged P3 code.
@@ -23,7 +23,7 @@ This is an author revision, not a review verdict. The P3 document was read from
- **N-HA12:** retain the merged 10-second placement-suspect rule and its caller-cancellation correction. Duty suppression is separate from visitor placement; neither changes lease authority.
- **N-HA14:** group boxes roll only through an operator-owned ASG Standby transaction, one at a time. This plan creates no ASG, automatic replacement, drain producer or restart policy.
- **N-HA15 (Paul, 2026-11-03):** P1b-3a's dead-holder backoff does one bounded lock re-read after an unreachable cached holder. Preserve it; departure duties add no visitor probe loop.
-- **N-HA16 (Paul, 2026-11-03):** store Describe-proven termination once per departure, bound to account, region, iid and box lifetime. Only normal HA acquire consumes it, after N-HA9 expiry; it grants no scan, import, completion, deletion, duty-start or admission authority. The object contract below replaces the ageing-evidence dependency.
+- **N-HA16 (Paul, 2026-11-03):** store Describe-proven termination once per departure, bound to account, region, iid and box lifetime. Only normal HA acquire consumes it, after N-HA9 expiry; discovery may schedule a scan, but the proof grants no import, completion, deletion, duty-start or admission authority. The object contract below replaces the ageing-evidence dependency.
- **N-HA17 (Paul, 2026-11-03):** Started/cancelled are consumer lifecycle facts, independent of coverage. Completion requires a full lock rescan with no dead owner or released-marker releaser. Unsupported hosts keep that departure open and page at a bounded rate; other departures and tenants continue.
- **I3 / §7.4:** scan and import is the transfer mechanism. No duty objects, roster, enrollment, claim fence record, published awake set or invented drained flag.
- **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.
@@ -53,15 +53,15 @@ Drain, group admission/latch, role writers, ASG hooks/rolls, hairpin, §6.5 retr
|---|---|---|---|
| 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. R2 found the same I3 family; N-HA16 now supplies its central invariant. |
| 2 | `REVIEW-BRIEF-REGION-HA-P1B3B-R2.md`; `REVIEW-REGION-HA-P1B3B-R2.md`, Claude Opus 5.5, plan 412a67f5, brief 1ce5733a, review c118f89d; code c6304f2d | **NOT READY: 2 P1, 2 P2, 4 P3** | P1-A repeats **I3: post-import duty authority depends on ageing termination evidence**; stopping rule 2 fired. Paul chose one enforced invariant, N-HA16. P1-B is **A1/I3/I4: tenant coverage controls consumer lifecycle**; N-HA17 removes that coupling. Rev 3 dispositions below; no reviewer approval claimed. |
-| 3 | Not dispatched; rev 3 is the candidate | **One final round remaining** | Carry R1/R2 families and Paul's rulings; do not reset the count for T/S or this revision. |
+| 3 | `REVIEW-REGION-HA-P1B3B-R3.md`, Claude Opus 5.5, plan 59d034af, review b9fa8ecf; code origin/main at c6304f2d or later, cited files unchanged | **READY AFTER FIXES: 0 P1, 3 P2, 3 P3** | R2 P1-A/P1-B closed; neither family recurred. Rev 4 applies all three P2s and takes all three P3s below. Stopping rule 1 closes review; no further round. |
-Two rounds of this document are spent. **Stopping rule 2 fired in R2. Paul has ruled N-HA16/N-HA17; this revision implements that decision, not an unapproved third attempt. One final round 3 remains.** 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.
+Three rounds of this document are spent. **Stopping rule 2 fired in R2; Paul ruled N-HA16/N-HA17. R3 found no P1, so stopping rule 1 closes review. Rev 4 applies the final fixes without another round.** 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.
+Implementation briefs must carry those counts and distinguish implementation checks from settled plan decisions; use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`. Census and checks of newly changed security, root, termination or production-storage behavior remain required for implementation within the same review budget. This Markdown revision adds no census unit or executable behavior. Splitting T/S does not reset review history. The plan review is closed; no further round, reviewers or subagents in this planning session.
## Round 1 dispositions
-Historical rev 2 dispositions below are retained for the round record, not current requirements or reviewer approvals. R2 supersedes the no-durable-proof choice and the coverage/start refusals in R1 P1-1/P1-2, P2-1/P2-4 and P3-5; use the rev 3 contracts below. 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.
+Historical rev 2 dispositions below are retained for the round record, not current requirements or reviewer approvals. R2 supersedes the no-durable-proof choice and the coverage/start refusals in R1 P1-1/P1-2, P2-1/P2-4 and P3-5; use the final contracts below. 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 |
|---|---|---|---|
@@ -94,6 +94,19 @@ Historical rev 2 dispositions below are retained for the round record, not curre
| P3-3 | **I2: staged bytes match the under-lease manifest.** Taken: compare the freshly read manifest's wake-entry digest to the validated staged wake-object digest, never local rows. | B2: `TestHAAdoptManifestBoundary` changes wake entry while keeping staged/local rows unchanged; mutation `reuse-staged-rows-without-manifest-digest`. |
| P3-4 | **I3: successor identity is proven.** Taken: parse strict HA marker/owner, bind ref/iid through verified `ha_box_identities`, check current record lifetime and a generation strictly greater than the observed lock. | B2/B4: `TestHAAdoptSuccessorValidation` covers remote holder/releaser, forged ref, wrong iid/lifetime and equal/older generation; mutation `superseded-without-bound-successor`. |
+## Round 3 dispositions
+
+| Finding | Invariant / rev 4 final disposition | Tasks and witnesses |
+|---|---|---|
+| P2-1 | **I1: proof and lock writes share the trusted box role.** Applied. The agent runs as `User=carlos`; `rootaws` preserves its SDK credential chain. No separate confirmer credential or box-agent denial is required. Audit only tenant/app and object-store-user credential isolation. | B3 `TestTerminationProofCredentials`: trusted box-role creation/read succeeds; tenant/app and store-user writes/copies to the regional data-bucket proof prefix fail. Verify tenants cannot obtain box-role credentials. |
+| P2-2 | **I3: every proof reader and writer uses the same bucket and region.** Applied. Use the lock region's data bucket, its existing acquire client and existing box-role IAM. | B3 `TestTerminationProofBucket`: distinct deployment/data buckets in different regions; Enqueue, finalizer and visitor/due acquire all use the same data bucket/key/region, with no deployment-bucket proof request. |
+| P2-3 | **Budget: proof reads cannot scale with visitor rate.** Applied. One shared per-process cache: absence/error for 10s, valid immutable proofs for process lifetime, coalesced concurrent reads by full proof identity. | B3/B4 `TestTerminationProofRequestBudget`: 20 concurrent visitor attempts across hosts of one hung peer give one proof GET per 10s window; repeat at expiry, then prove cached-positive reuse and restart reload. Mutations `proof-cache-per-host`, `proof-absence-not-cached`, `proof-positive-not-cached`. |
+| P3-1 | **Authority: discovery only schedules work.** Taken. Align N-HA16 wording with Enqueue; only normal acquire consumes proof as authority. | Existing `TestTerminationProofAcquireOnly` and `proof-authorizes-import` mutation. |
+| P3-2 | **Budget: one proof per departure, not per adopted host.** Taken. F is normally 0 or 1 per departure/process; recalculate the example and adoption-page costs. | B4 `TestDepartureRequestBudget` shares one cache across a 32-host page and later pages; retries/conflict readbacks remain counted separately. |
+| P3-3 | **Activation: unresolved legacy sidecars retain departure evidence and page.** Taken. Inventory all dev home-scope native sidecars before approval; state affected departures, expected pages and evidence retention beyond SQS's 14 days. | Task 5B card and B3 `TestDepartureCoverageIsolation`; a blocked departure is not a completed-drill PASS. |
+
+All R3 findings are applied. The older R2 P3-1 durable cache of unrelated iids remains the named follow-up below; it is distinct from the required 10s proof-absence cache. Review stays closed.
+
## 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. Reuse main's `placementNull` bit: explicit JSON null is malformed, while omission and `""` are home. A separate known/present bit represents missing evidence.
@@ -102,7 +115,7 @@ Historical rev 2 dispositions below are retained for the round record, not curre
- 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` remains the live Describe verifier: positive cache **24h**, negative/error cache **10s**, one in-flight describe/iid. N-HA16 adds durable proof persistence and an acquire-only validated reader; a process cache is no longer required after the proof lands. The old `termfence.Verify` accepts an event; do **not** use it as the new proof path. `FromEvent` is a hint parser only.
+- `Confirmer.Terminated` remains the live Describe verifier: positive cache **24h**, negative/error cache **10s**, one in-flight describe/iid. N-HA16 adds durable proof persistence and an acquire-only validated reader; a shared process cache bounds proof reads, while durable evidence survives its loss on restart. The old `termfence.Verify` accepts an event; do **not** use it as the new proof path. `FromEvent` is a hint parser only.
- Startup/cancel acknowledgment describes the functioning consumer lifecycle, not queue contents, scan completion, cloud health or permission to take a lease. An empty successful receive counts; failed client construction does not. Runtime S3/SQS blips must not cause automatic replacement.
- Copy is a draft deck for controller → Luna, including error/notice destinations. No product string is approved here. Implementation-plan prose uses writing-pipeline's explicit plan exception; the requested draft deck is not shipped copy.
- Targeted checks use `nice -n 19`, `-run`, `-count=1`; keep `GOCACHE` at its default. Scratch only under `/home/paulca/t/`, remove only owned scratch. Bind local test listeners to `127.0.0.1`. No `sudo`.
@@ -122,7 +135,7 @@ Historical rev 2 dispositions below are retained for the round record, not curre
| `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: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 `internal/termfence/termination_proof.go` and tests for root-side persistence and acquire-only validation; include `internal/rootaws` and effective proof-prefix IAM in the census. |
+| `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 `internal/termfence/termination_proof.go` and tests for trusted box-role persistence and acquire-only validation; audit tenant/app and object-store-user isolation from the regional data-bucket proof prefix. No `internal/rootaws` change is required. |
| `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. 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. |
@@ -151,19 +164,25 @@ All accepted hints enter `Controller.Enqueue(ctx context.Context, box BoxObserva
### Durable termination evidence (N-HA16)
-**Object:** in the configured deployment/data bucket, `control/terminations/v1/<account>/<cloud-region>/<iid>/<box-lifetime>.json`. `box-lifetime` is the lowercase SHA-256 of the exact verified immutable `control/boxes/<ref>.json` bytes (`RecordSHA256`); it binds this incarnation, not a reusable box name. It is distinct from each tenant host's lifetime. One departure can cover many host lifetimes, so there is no proof object per host. Derive every key component from validated cloud identity and immutable box binding, never an event-provided key or tenant prefix.
+**Object:** in the **data bucket containing the lock, in that lock's cloud region**: `s3://<data-bucket>/control/terminations/v1/<account>/<cloud-region>/<iid>/<box-lifetime>.json`. Enqueue uses the verified `Scope.DataBucket`/`Scope.CloudRegion`; finalizer and visitor/due acquire use the same `bucket`/`region` passed to `lease.AcquireHA` (`internal/lease/ha.go:59,79`). The acquire adapter uses its existing regional S3 client; Enqueue uses the same regional data-store configuration. Never use the deployment bucket or its region for proof storage, even when immutable identity records are loaded from there. Reject a scope/lock bucket or region mismatch. `box-lifetime` is the lowercase SHA-256 of the exact verified immutable `control/boxes/<ref>.json` bytes (`RecordSHA256`); it binds this incarnation, not a reusable box name. It is distinct from each tenant host's lifetime. One departure can cover many host lifetimes, so there is no proof object per host. Derive every key component from validated cloud identity and immutable box binding, never an event-provided key or tenant prefix.
**Body:** strict version-1 JSON, at most **2 KiB**, with `v`, `account`, `region`, `iid`, `box_ref`, `box_lifetime`, `identity_sha256`, `state:"terminated"`, `source:"ec2-describe"`, `confirmed_at` (UTC), and confirming box ref/iid. Reject unknown version, duplicate/missing fields, oversized body, invalid timestamps or identity mismatch. The two digest fields must agree with the verified identity bytes. Timestamp is evidence provenance, not a TTL; valid proof never expires.
-**Writer and ordering:** the shared trusted root-side confirmer, using the existing `rootaws` credential boundary (`internal/host/hatakeover.go:37`), writes immediately after `SameAccountTerminated` accepts the exact Describe response and the immutable identity binding has been verified. Queue events, journal rows and callback booleans cannot mint proof. Preserve the verified observation through an initial PUT failure for bounded retry while the process lives; a cache-hit retry retains the original observation/time. Persist before reporting durable departure enrollment or allowing the finalizer to rely on it. Use one create-only PUT with `If-None-Match: *`; there is exactly one successful object creation per departure across receivers. A 412 or lost PUT response requires one exact-key GET and full binding/body validation; a different confirmer/time is acceptable for the same proven incarnation, conflicting identity/state is a fault. Never overwrite it. On failure leave work pending and unacknowledged.
+**Writer and ordering:** the shared confirmer, using the trusted box-role credentials already used for lock writes, writes immediately after `SameAccountTerminated` accepts the exact Describe response and the immutable identity binding has been verified. Queue events, journal rows and callback booleans cannot mint proof. Preserve the verified observation through an initial PUT failure for bounded retry while the process lives; a cache-hit retry retains the original observation/time. Persist before reporting durable departure enrollment or allowing the finalizer to rely on it. Use one create-only PUT with `If-None-Match: *`; there is exactly one successful object creation per departure across receivers. A 412 or lost PUT response requires one exact-key GET and full binding/body validation; a different confirmer/time is acceptable for the same proven incarnation, conflicting identity/state is a fault. Never overwrite it. On failure leave work pending and unacknowledged.
-The proof prefix must be writable only by that trusted confirmer credential, readable by HA acquire, and unwritable by tenant/app or unprivileged box-agent credentials. Audit the existing effective IAM and root credential delivery, including alternative object-write/copy routes; a JSON `source` field is not authentication. Add the narrow prefix restrictions in T if current policy is insufficient, and include their census and scoped deployment approval. No general proof-write RPC or caller-supplied termination flag. Effective-policy denial witnesses are required before activation; existing box-role access alone is not evidence that an agent cannot forge a proof.
+**Credential boundary (R3 P2-1):** the box role is trusted. The agent runs as `User=carlos` (`internal/host/units/carlos-edge.service:28`); `rootaws.LoadDefaultConfig` preserves the ordinary SDK chain for non-root callers (`internal/rootaws/config.go:37`). The confirmer at `internal/host/hatakeover.go:37` has no separate credential. Existing box-role GetObject/PutObject rights on `${var.data_bucket_arn}/*` (`infra/modules/region-host/main.tf:163–169`) cover proof reads/writes. A compromised box agent can already overwrite every lock; proof creation adds no I1 authority beyond that trust boundary. No credential-loader change, separate role or box-agent denial witness is required.
+
+Audit only tenant/app and object-store-user credentials: they must neither obtain the box role nor write/copy objects into the data bucket's `control/terminations/v1/` prefix. Check effective permissions, tenant credential delivery/IMDS isolation, and alternative object-write/copy routes. Store-user permissions are the intersection of their boundary (`main.tf:672–690`) and per-user inline policy. A JSON `source` field is not authentication. Effective-policy denial witnesses for these untrusted credentials, and a successful box-role proof write/read, are required before activation. If that audit exposes a gap, include its narrow fix, census and scoped deployment approval; no new IAM grant is needed for the existing box role. No general proof-write RPC or caller-supplied termination flag.
**Sole authority consumer:** normal HA acquire's OwnerTerminated proof adapter. After reading/classifying a held HA lock, and only when `now > ExpiresAt`, derive its owner's ref/iid, resolve the verified box binding in the current account/region, and validate the exact-key proof. Bind the acquire's current host record/lifetime separately; an old host marker/receipt cannot authorize a recreated host. The iid-only callback must close over the classified owner and verified context, not trust an arbitrary iid supplied by a caller. On a CAS retry, rebind to the newly read owner; a positive result for D must not authorize E. Keep `DecideAcquire` as the one take decision and the existing conditional lock PUT as the fence. No proof read or bypass on an unexpired/equal-expiry lock, same-box recovery, absent prefix, malformed owner or lifetime mismatch. Live Describe can supply missing proof through the writer, but not-found/stopped/shutting-down/error is never proof. Missing/corrupt/inaccessible proof without live confirmation fails closed.
A proof can be observed for discovery/journal retry; only acquire may consume it as authority. It cannot certify import, local-copy reuse, a completed departure, edges deletion, a duty start or P3 admission. Finalizer and visitor/due wakes share this adapter. A new process/registry with no prior confirmation must recover after EC2 forgets by reading the object; no successful Describe, original process or positive cache is required.
-**Retention:** keep proof for the deployment bucket's lifetime, with no automatic TTL, completion deletion or consumed bit. Another receiver or a delayed held lock may still need it after edges deletion. One immutable object ≤2 KiB per departure; D departures retain ≤2 KiB × D body bytes plus S3 metadata. The live drill retains its proof as evidence; any later deployment teardown is separately scoped. Ordinary quiet operation adds no reads, writes or LIST. B3/B5 witnesses cover create races, 412/lost response, denied/forged writes, malformed/cross-account/region/iid/box-lifetime proof, host recreation, CAS owner change, proof persistence then scanner crash/S3 outage/restart/+48h, and acquire-only consumption with N-HA9 equality.
+**Proof cache (R3 P2-3):** share one process-wide cache across Enqueue, finalizer and every visitor/due acquire, keyed by `(data bucket, account, cloud region, iid, box_lifetime)` after verified identity binding. Coalesce concurrent exact-key reads into one in-flight operation. Cache absence for **10s**, matching the confirmer's negative TTL; cache read/validation errors as refusals for the same bounded interval, never as termination. Demand alone refreshes an expired negative entry; no background polling. Keep fully validated immutable proofs in memory for the process lifetime, with no TTL or per-host eviction. A successful create or validated conflict readback immediately replaces a local negative entry; a proof written by another box becomes visible on demand after at most the remaining 10s negative TTL. Restart clears both caches and revalidates the object; it never requires live EC2 evidence for an existing valid proof. Cache hits still require the current acquire's owner/lifetime binding and expiry checks.
+
+For one identity, ordinary lookups cost at most **1 GET per 10s per receiving process** while proof is absent/erroring (≤360/hour under sustained demand), then one successful GET once present and **0 further GETs** for that identity during that process lifetime. Local successful creation can avoid that last GET. PUT-conflict/lost-response validation reads are additional counted persistence work, not a visitor-rate path. No per-host cache or per-attempt cache construction. `TestTerminationProofRequestBudget` must count across hosts and concurrent requests.
+
+**Retention:** keep proof for the regional data bucket's lifetime, with no automatic TTL, completion deletion or consumed bit. Another receiver or a delayed held lock may still need it after edges deletion. One immutable object ≤2 KiB per departure; D departures retain ≤2 KiB × D body bytes plus S3 metadata. The live drill retains its proof as evidence; any later deployment teardown is separately scoped. Ordinary quiet operation adds no reads, writes or LIST. B3/B5 witnesses cover create races, 412/lost response, denied tenant/app/store-user writes, successful trusted box-role writes, distinct deployment/data buckets and regions, malformed/cross-account/region/iid/box-lifetime proof, host recreation, CAS owner change, proof persistence then scanner crash/S3 outage/restart/+48h, and acquire-only consumption with N-HA9 equality.
**R2 P3-1 follow-up:** a durable cache of proven-unrelated iids is deferred on this branch. It must define invalidation for newly published immutable identity records before suppressing future discovery across restarts. T retains bounded, coalesced unknown-iid walks and the durable positive identity cache; its expected-churn cost is explicit below. This P3 does not reopen review.
@@ -248,7 +267,7 @@ 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), Q≤A additional wake GETs when the manifest changed between staging and acquire, F proof GET attempts (including acquire, discovery and PUT-conflict readback), 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. A successful final rescan adds N GETs. One successful proof creation adds 1 PUT per departure, not per host; concurrent/failed create attempts count separately. An acquire may reuse a validated in-process proof keyed by its full identity, but restart clears that optimization. A cold uncontended held-host acquire adds one proof GET; a three-round owner-changing CAS can add three. 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, F proof GET attempts (including acquire, discovery and PUT-conflict readback), 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. A successful final rescan adds N GETs. One successful proof creation adds 1 PUT per departure, not per host; concurrent/failed create attempts count separately. All readers share the proof cache above. For one departure in a healthy process, F is normally **0** after a local successful create or **1** for a cold persisted-proof read, across all hosts/pages; restart needs one fresh read. Absence/error retries cost at most one GET/10s per identity/process; PUT-conflict/lost-response readbacks are additional. A three-round owner-changing CAS may add three proof GETs only if it encounters three distinct uncached identities. The current implementation has **four total attempts**, not five, despite §18's “four retries” wording.
| Path | S3 | SQS / EC2 |
|---|---|---|
@@ -257,9 +276,9 @@ Let N be the complete regional scan's host count, A matching/importable hosts an
| One valid termination, import plus successful completion rescan | **(U+E+2N+4A+W+Q+F)G + (2A+1)P**, 0L for known identities; proof PUT counted once | 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 adoption page | Uncontended: **224G + 64P** for 32 adopted hosts including Q=32, plus ≤32 cold proof GETs = **256G + 64P**; 192G+64P before proof reads if manifests unchanged. Proof creation, identity/refresh and completion counted separately | 0 additional receives required by scanner; at most one Describe/iid/10s |
+| Single adoption page | Uncontended: **224G + 64P** for 32 adopted hosts including Q=32, plus at most one cold persisted-proof GET for this departure/process = **225G + 64P**; **193G+64P** with unchanged manifests and a cold proof, or 192G+64P with a warm proof. Later pages add zero proof GETs. Proof creation, identity/refresh and completion counted separately | 0 additional receives required by scanner; at most one Describe/iid/10s |
| Completion rescan page | **≤32G**, 0P/L; full pass N G, repeated/invalidation/error passes counted | No Describe; no ack while dead owner/releaser or unresolved entry remains |
-| Durable proof persistence/read | **1P** successful creation per departure, ≤2 KiB; +1G per 412/lost response; acquire +1G per uncached exact identity; discovery GETs counted in F | Existing Describe on initial proof; **0 Describe required** after persisted proof, even +48h/fresh process |
+| Durable proof persistence/read | **1P** successful creation per departure, ≤2 KiB; +1G per 412/lost response; shared reader +1G per cold persisted identity/process, then 0; absence/error ≤1G/10s/identity/process; discovery and readbacks counted in F | Existing Describe on initial proof; **0 Describe required** after persisted proof, even +48h/fresh process |
| 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+4a+w+q+f)G + 2a P**, plus final N-G rescan, U/E and retries; add failed/missing proof creation separately | 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 |
@@ -267,7 +286,8 @@ Let N be the complete regional scan's host count, A matching/importable hosts an
| Malformed/wrong-account or unrelated within the completed discovery batch | 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 restore R; absent lock adds **1L** prefix-empty proof. Expired peer: +1G for uncached proof, +1P only if creating its missing proof after Describe | No Describe required with valid persisted proof; otherwise live confirmation |
+| Ordinary duty acquire | Existing **1G + 1P** if acquired, plus restore R; absent lock adds **1L** prefix-empty proof. Expired peer: shared proof-cache budget below, +1P only if creating its missing proof after Describe | No Describe required with valid persisted proof; otherwise live confirmation |
+| Visitor/due attempts against expired hung or S3-lost peer | Proof GETs **≤1 per identity per 10s per process** (≤360/h with sustained demand), independent of hosts/request count; after a valid proof is cached, **0** further proof GETs. Existing lock reads remain per acquire | Shared confirmer ≤1 Describe/iid/10s while negative; no takeover until termination is proven and expiry passed |
| 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 |
@@ -276,11 +296,11 @@ Let N be the complete regional scan's host count, A matching/importable hosts an
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, plus separately counted proof GET/create attempts. Identity resolution adds U G when not cached; this includes validating a remote successor. Marker obligations and renewals keep their existing cost.
-N=500, A=W=20, Q=0, U=E=0 gives **1,100 GETs + 41 PUTs** before proof reads; with F=20 cold proof reads, **1,120 GETs + 41 PUTs = $0.000653** at §18's prices. This includes one proof creation and one final rescan, excluding completion index and ordinary wake costs. Completion adds $0.0000054 uncontended (DELETE free). A 32-host adoption page with Q=32 and 32 cold proof reads costs $0.0004224 (256 GETs +64 PUTs); its separate completion rescan page adds $0.0000128 (32 GETs). Proof creation, retries, identity and index operations are additional to those page examples. 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.
+N=500, A=W=20, Q=0, U=E=0 gives **1,100 GETs + 41 PUTs** before proof reads; with F=1 shared cold proof read, **1,101 GETs + 41 PUTs = $0.0006454** at §18's prices. This includes one proof creation and one final rescan, excluding completion index and ordinary wake costs. Completion adds $0.0000054 uncontended (DELETE free). A 32-host adoption page with Q=32 and one cold proof read costs $0.0004100 (225 GETs +64 PUTs); its separate completion rescan page adds $0.0000128 (32 GETs). Proof creation, retries, identity and index operations are additional to those page examples. 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.
**Expected unrelated churn (R2 P3-1):** for C unrelated terminations/hour, B immutable box records and J receivers on distinct queues, the uncoalesced worst case is `J*C*ceil(B/1000)` LISTs/hour plus previously unverified-record GETs and counted failed-read retries. With the durable identity cache warm, successful identity GETs are zero until records change; coalescing can reduce LIST walks. For example, C=60, B≤1000, J=2 gives ≤120 LISTs/hour ($0.0006 at §18 prices), plus receives/deletes. Restarts do not erase the positive cache; no durable-negative-cache saving is claimed. Count actual dev CI/rootrunner churn during the drill.
-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 SQS IAM permission. N-HA16 proof-prefix permissions are separately audited/scoped. 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 host slots/pass shared fairly across discovery/adoption/rescan pages and pending departures. Storage request deadlines are 5s per call; one page has a 30s work deadline and checkpoints unfinished hosts rather than blocking the next departure. Slow calls reduce throughput; the page-count latency estimates assume each page finishes within its slot. Receives continue independently of long scans.
+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 SQS IAM permission. N-HA16 uses existing box-role rights on the regional data bucket; audit tenant/app and store-user denial, with any required correction separately scoped. 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 host slots/pass shared fairly across discovery/adoption/rescan pages and pending departures. Storage request deadlines are 5s per call; one page has a 30s work deadline and checkpoints unfinished hosts rather than blocking the next departure. Slow calls reduce throughput; the page-count latency estimates assume each page finishes within its slot. 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 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 the ≤30s successful consumer-start leg (including a 20s first empty receive); inventory adds zero to that leg. Never silently substitute a reload for env replacement.
@@ -322,13 +342,13 @@ Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/
### 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, RecordView refresh provenance, hostenv allowlist and SDK module files. Add `internal/termfence/termination_proof.go`/tests and the acquire adapter in `internal/lease`; include any required proof-prefix IAM/root credential isolation changes and their effective-policy witnesses. `rootaws` selects credentials; it does not itself prove that the same role is inaccessible to an unprivileged agent. Verify that boundary explicitly. Include fixed-box host.env delivery in the deployment release card, not in the group-only allowlist.
+**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. Add `internal/termfence/termination_proof.go`/tests and the acquire adapter in `internal/lease`; share the proof cache across those callers and use the existing lock-region data-bucket client/IAM. Add effective-policy and credential-isolation witnesses for tenant/app and object-store users only; the box role remains trusted. No root credential isolation or `rootaws` change is required. 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: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 uses per-host `CanAdopt(DepartureHost, LocalPolicy)` and `CanCompleteDeparture(RescanResult)` predicates; neither is called to gate Start/Running/Done. Completion consumes the strict rescan, not a regional eligibility boolean. 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.** `TestTerminationConsumerStartupBound` exercises the 5s+25s deadlines, no inventory reads, both families indefinitely incomplete and an unchanged index; successful empty Receive still closes Started within 30s. `TestTerminationProofDurability`, `TestTerminationProofBinding` and `TestTerminationProofAcquireOnly` execute every N-HA16 contract case, including real proof-store transports and rejected unprivileged writes. `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. `TestDepartureCoverageIsolation` includes asleep legacy native sidecars with no lock, in/out of local pools, and an awake sidecar, both before startup and inserted/enabled by a tenant afterward. Started/Running/Done remain lifecycle facts; supported host imports and other departures continue. Only affected departures retain evidence and page within the persisted hourly bound. Correct an eligible pool policy: pending work resumes without restart/rearm. Add a hapair-only P3-like lifecycle observer beside shared records; it starts. A foreign-placement sidecar is irrelevant to that departure. `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 1: Write failing tests.** `TestTerminationConsumerStartupBound` exercises the 5s+25s deadlines, no inventory reads, both families indefinitely incomplete and an unchanged index; successful empty Receive still closes Started within 30s. `TestTerminationProofDurability`, `TestTerminationProofBinding` and `TestTerminationProofAcquireOnly` execute every N-HA16 contract case, including real proof-store transports. `TestTerminationProofCredentials` permits box-role writes/reads and denies tenant/app/store-user writes and copies; verify tenant processes cannot obtain box-role credentials. `TestTerminationProofBucket` puts the deployment bucket in another region and asserts the same data bucket/key/region for Enqueue, finalizer and visitor/due acquire, using acquire's existing client. `TestTerminationProofRequestBudget` uses 20 concurrent visitor attempts across several hosts of one hung peer within 10s: one proof GET and at most one Describe, zero takeover. At 10s one new GET is allowed; another receiver's persisted proof is then cached for all subsequent hosts/pages with zero GETs. Test local creation replacing cached absence, errors remaining refusals, identity/CAS isolation, and one revalidation GET after process restart. `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. `TestDepartureCoverageIsolation` includes asleep legacy native sidecars with no lock, in/out of local pools, and an awake sidecar, both before startup and inserted/enabled by a tenant afterward. Started/Running/Done remain lifecycle facts; supported host imports and other departures continue. Only affected departures retain evidence and page within the persisted hourly bound. Correct an eligible pool policy: pending work resumes without restart/rearm. Add a hapair-only P3-like lifecycle observer beside shared records; it starts. A foreign-placement sidecar is irrelevant to that departure. `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. 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. Persist verified termination through the root-side proof writer before durable enrollment; the acquire alone validates it as a take proof. Confirmation may invalidate suppression but cannot grant a start. Apply bounded asynchronous replay, independent startup deadlines and per-departure fair scheduling 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. Persist verified termination through the trusted box-role writer into the lock region's data bucket before durable enrollment; the acquire alone validates it as a take proof. Confirmation may invalidate suppression but cannot grant a start. Apply bounded asynchronous replay, independent startup deadlines and per-departure fair scheduling 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`.
@@ -338,7 +358,7 @@ Fixed dev boxes have distinct module IAM names/queues (`platform-infrastructure/
**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` uses distinct fixed queues: B serves shared, C shared+hapair, D had both; both start and poll, B imports shared work and keeps D open while hapair locks name D, C finalizes hapair work, then both rescan and acknowledge their own receipts. Introduce out-of-pool work during a scan: invalidate completion only for that departure. Add another departure with supported hosts and prove progress. `TestDepartureCompletionRescan` leaves a D-owned/released lock after an apparent import success, changes inventory mid-rescan, injects ambiguous absence and validates remote successor markers. No false completion. Count N additional reads, 32/page and fair scheduling across K departures. `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 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; both start and poll, B imports shared work and keeps D open while hapair locks name D, C finalizes hapair work, then both rescan and acknowledge their own receipts. Introduce out-of-pool work during a scan: invalidate completion only for that departure. Add another departure with supported hosts and prove progress. `TestDepartureCompletionRescan` leaves a D-owned/released lock after an apparent import success, changes inventory mid-rescan, injects ambiguous absence and validates remote successor markers. No false completion. Count N additional reads, 32/page and fair scheduling across K departures. `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, the hung-peer 20-visitor cache bound, and one shared cold proof GET across a 32-host adoption page and subsequent pages.
- [ ] **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 → authority_complete → edges_deleted_or_absent → indexed → complete. Require a complete inventory whose source read and full walk started after the locally observed departure evidence. Coverage never gates the consumer. One shared-client lock read per host for classification; matched hosts incur the additional finalizer reads/writes in the budget. After Adopted/AlreadyAdopted/validated Superseded results, run the fresh full completion rescan; require zero dead owner/releaser matches and no unresolved entries. Changed/new records invalidate checkpoints. Unknown lifetimes/read errors/malformed locks cannot conceal duties or become success. Keep unsupported hosts pending, page per departure at the persisted hourly limit, and continue eligible hosts/other departures. Never widen tenancy. No selection from public edges Hosts for the scan census.
- [ ] **Step 4: Implement completion recovery.** Persist all host authority results and the successful zero-match rescan 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.
@@ -377,11 +397,11 @@ 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.** 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, the exact N-HA16 proof prefix/write/read permission changes if required, retained ≤2 KiB proof evidence, 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 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`. Inventory **all dev home-scope native sidecars before approval**, with record IDs, HA/legacy status, pool and eligible survivors, including asleep/lockless and out-of-pool records. Name every departure each unresolved legacy sidecar will hold open. For D blocked departures and J receivers, expect at most **D×J pages/hour** (≤2×D×J during the two-hour drill), aggregated per departure rather than per host; persist the last-page time across restart. State the affected queues' **14-day message retention** (`main.tf:837`) and that message expiry never completes a departure. Keep local pending journals/status until resolution and immutable proof for the data bucket's lifetime; name the evidence location, retention and operator owner for unresolved records after the drill. Report recovery of supported timers separately from blocked completion; a legacy-sidecar blocker cannot earn a full 5B PASS.
+- [ ] **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, the exact regional data bucket and N-HA16 key/region, existing box-role write/read permission evidence and tenant/app/store-user denial witnesses (scope any required correction), retained ≤2 KiB proof evidence, 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 and a complete pre-filter inventory identifying per-departure unsupported hosts and survivors serving each intended duty; verify partial-pool receivers still start and run; 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, successful immutable proof PUT/key/digest, original expiry, queue receipt, scan/import transaction, zero-match completion rescan, 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), `2*ceil(N/32)*30s` scan/finalization plus final-rescan scheduling allowance for one active departure (multiply page wait by concurrent K under fair scheduling, add bounded I/O/retry time) 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 5: Terminate C through EC2 and observe unattended recovery.** Log API time, confirmed terminated state, successful immutable proof PUT/data bucket/region/key/digest, original expiry, queue receipt, scan/import transaction, zero-match completion rescan, 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), `2*ceil(N/32)*30s` scan/finalization plus final-rescan scheduling allowance for one active departure (multiply page wait by concurrent K under fair scheduling, add bounded I/O/retry time) 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 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, retaining C's N-HA16 proof under its stated retention contract, 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.
@@ -424,4 +444,4 @@ The bounded scanner-death acceptance is death before whole-scan completion, as
## 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. Rev 3 checked R2 against the worktree confirmer, acquire and root credential seam, retained the existing placement citations and applied Paul's N-HA15/N-HA16/N-HA17 instructions without rebasing. R2 remains NOT READY; stopping rule 2 was resolved by Paul's rulings, not by a reviewer. One final round 3 remains and was not dispatched. R2 P3-1's durable negative cache is the named follow-up; its churn cost is budgeted now. 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 4 checked the R3 fixes against the agent unit, credential loader, acquire client, data-bucket IAM, store-user boundary and queue retention. The box role is trusted; proofs use the lock region's data bucket and shared 10s negative/process-lifetime positive caches. All three P2s and all three P3s are applied. R1 NOT READY (2 P1 / 7 P2 / 7 P3), R2 NOT READY (2 / 2 / 4; rule 2 resolved by Paul's N-HA16/N-HA17), R3 READY AFTER FIXES (0 / 3 / 3): review closed under rule 1, no further round. R2 P3-1's durable unrelated-iid negative cache remains the named follow-up; its churn cost is budgeted separately from proof lookup caching. Planning validation is file/citation/format/diff checks only; no full suites, production code, reviewers, push or live drill.