carlos / platform Public

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev eac3ee766a33c1c9bea610f7a7b589cf0d0d1bef parent d27de8c
1 file changed, +143 −80
  • docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md +143 −80
diff --git a/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md b/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md
index 225d2689b..694ede1c9 100644
--- a/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md
+++ b/docs/superpowers/plans/2026-11-01-region-ha-p1b3-placement.md
@@ -1,21 +1,23 @@
-# Region HA P1b-3: cold-wake placement Implementation Plan
+# Region HA P1b-3a: cold-wake placement implementation plan — rev 2
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. This commission is planning only; do not start implementation or dispatch reviewers from this session.
**Goal:** A request for an asleep born-HA host that reaches the other box wakes the host on the chosen box through the existing signed forward, with one writer and one owner of request accounting.
-**Architecture:** P1b-3a adds app counts to existing edges publication and passes a cached placement snapshot into the activator's front-door decision. An eligible clean releaser wins; otherwise the shared roomiest policy chooses. The receiving peer runs the existing HA acquire/restore. P1b-3b covers local duty ownership and departure scan/import; its outline below is not executable.
+**Architecture:** One applicability decision limits placement to free cold wakes with the switch on and usable cached evidence. Other requests retain the existing holder/acquire path, including same-box recovery. For placement, an eligible clean releaser wins; otherwise the shared roomiest policy chooses among reachable candidates. The receiving peer runs the existing HA acquire/restore. P1b-3b covers local duties and event-driven departure scan/import; its outline below is not executable.
**Tech Stack:** Go 1.26, `internal/{boxchoice,edge,activator}`, S3 conditional leases, local SQLite registries, seeded `internal/sim/regionha`.
**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, rev 6.1, §3.1, §4, §6.3, §7, §9, §11, §18, §19 and §21. Code citations are against **44d810d0**, the amadan `origin/main` base of `region-ha-p1b3-placement`. Use current interfaces, not those in earlier plans.
-**Status:** Draft, unreviewed. No production code or deployment authorized. Planning branch committed locally only.
+**Status:** Rev 2 answers Opus round 1 (NOT READY: 3 P1, 4 P2). This revision has not had independent review. No production code or deployment authorized; local planning commit only. All code citations below were re-read against 44d810d0; proposed files have no invented line numbers.
## Rulings
- **N-HA8, Paul, 2026-10-29:** §6.3 placement and §7 duties belong to P1b-3. §6.5 retry is later. Roles, serving latch, lifecycle hook and hairpin belong to P3.
- **N-HA10:** Forward at the front, after route lookup, before gates/assets/guards/records/limits/usage/analytics. Preserve P1b-2's insertion point and exclusions.
+- **N-HA7 / §19:** `rt.HA` selects the HA acquire regardless of `CARLOS_REGION_HA`. The box switch gates placement only; turning it off preserves P1b-2 holder probing and local HA wake.
+- **N-HA11, Paul, 2026-11-01:** P1b-3b uses a small SQS consumer on the existing EC2 termination queue, about **180 receives/hour/box**, with **no new S3 polling**. The view-age check is the fallback for lost events. This settles the trigger choice, not approval to mutate infrastructure.
- **I1 / N-HA9:** Only `lease.AcquireHA` authorizes a writer. Another box's expired lease still needs confirmed termination; a terminated owner's unexpired lease still waits. Placement supplies neither proof.
- **I2:** Clean releaser is a routing preference. Only `hafresh.DecideKeep` proves local DB/files reusable after acquire; marker alone cannot prove files still match.
- **H4 / astra-1.17:** HRW (highest random weight, rendezvous hashing) does not precede capacity. Order: eligible clean releaser, then `ChooseRoomiest`: soft app spread, free memory, greatest SHA-256 of `host + "\x00" + ref`, smallest reference. A10's HRW starter for never-woken duties belongs to 3b.
@@ -41,51 +43,90 @@ Switch-on: first dev release immediately after 3a merges, fixed sophie/leo in `h
| Round | Brief / findings | Verdict | Fault families / disposition |
|---|---|---|---|
+| 1 | `REVIEW-BRIEF-REGION-HA-P1B3-R1.md` at 0cd04be9; `REVIEW-REGION-HA-P1B3-R1.md`, Opus (other model family), code 44d810d0 | **NOT READY: 3 P1, 4 P2, 6 P3** | P1-1/2/3: placement must preserve main's recovery (same-box / switch / reachability); P2-1: adoption lag; P2-2: bounded lock reads; P2-3: executable wiring; P2-4: complete copy contract. Rev 2 dispositions below; not a new review verdict. |
-No P1b-3 review has run. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds; all remain closed. I3 duty-file transfer was cut after three P1 rounds: do not recreate it. Carry this history into briefs/handoffs. Splits/renames do not reset rounds spent on the same design/change.
+One of three P1b-3 rounds is spent; rounds 2–3 remain. Stop at the first round with no P1, fix its P2s without reopening, and list P3s as follow-ups. If a second consecutive round finds the same invariant broken, stop fixing and offer the refuse/cut/central-invariant choice before a third fix. A fourth round needs Paul's go. No reviewer is dispatched in this session. Spec, P1b-1, P1b-2 and dead-holder backoff each spent three rounds; all remain closed. I3 duty-file transfer was cut after three P1 rounds: do not recreate it. Carry this history into briefs/handoffs. Splits/renames do not reset rounds spent on the same design/change.
## Global Constraints
- Born-HA only (`rt.HA`). Legacy hosts, regional names, door calls, tunnel deliveries, static routes and verified hops retain P1b-2 behavior.
- Existing switches: `CARLOS_REGION_HA` box capability, `CONSOLE_HA_REGIONS` new-record stamp. No new flag/migration. HA never falls back to legacy acquire.
- Eligibility: **15% memory**, **10% disk**, generation at most **15 minutes** old and **1 minute** in future. Publication **5–6 minutes**, fold **30 seconds**. Missing/stale app counts mean **0**, soft spread (astra-3.5).
-- A20: low headroom never refuses an existing host if a compatible fresh serving box exists. Missing membership/configuration may refuse.
+- A20: low headroom never refuses an existing host. Missing/stale placement evidence declines placement and retains local HA acquire; explicit non-serving ingress without a usable peer refuses before work starts.
- Fixed-pair staging until P3 admission. Honor explicit non-serving roles; create no role objects/hooks and claim no ASG admission here.
- Additive wire fields; old files decode. No lock shape, registry schema, IAM, SQS consumer, root lifecycle or infrastructure change in 3a.
- Durability 3a is base: sealed secrets, original binding, write-once escrow and `stageEscrowReads` stay on ordinary selected-box wake/publish path.
-- Preserve 50,000-host cache bound, positive ceiling **1h**, negative observation **10s**, suspect **10s**, **2s** read/dial bounds, generations and per-address dial gate.
+- Preserve 50,000-host cache bound, positive ceiling **1h**, negative observation **10s**, holder suspect **10s**, **2s** read/dial bounds, generations and per-address dial gate. Add a separately bounded, per-reference placement-suspect set; it cannot change lease authority.
- Copy rows are draft controller→Luna deck. Apply accepted words verbatim at execution; no dispatch/approval claimed here.
- Targeted tests `nice -n 19`/`-run`/`-count=1`, default `GOCACHE`. Owned scratch under `$TMPDIR` or `~/.cache/region-ha-p1b3`, removed; listeners loopback.
- Implementation landing: repo build/vet/test/format once; darwin/amd64, windows/amd64, linux/arm64 cross-compiles, `CGO_ENABLED=0`; arm64 binary under **64,000,000 bytes**. No full suites for this planning commit.
## Current code and file map
+All paths in this table are relative to the module root. These are existing insertion points, not claims that proposed functions already exist.
+
| Base seam | Responsibility/change |
|---|---|
-| `internal/boxchoice/policy.go:16,63,83` | New `coldwake.go` composes thresholds/ChooseRoomiest. Claim-era Eligible (`boxchoice.go:120`) requires roster: do not use. |
-| `internal/host/headroom.go:14`; `edgesfile.go:173,228,1230` | Add headroom.apps from live activator entries. Hibernate is policy (`registry/registry.go:229`); awakeCount is not new producer. |
-| `internal/host/edgesfile.go:945,962` | Headroom outside gate; existing HA timed writes refresh generation even if readings unchanged. No heartbeat. |
-| `internal/edgesfile/snapshot.go:72,280`; `boxchoice/boxchoice.go:29` | Carry additive map through shared decoder/converter. |
-| `internal/edge/homemap.go:134,456`; `holderview.go:35` | New wakeplacement.go projects one cached fold. Holder view deliberately ignores age; cold placement ages separately. |
-| `internal/edge/forwardha.go:41,173,210` | Extend real interface; disappearing placement target refuses instead of local fallback. |
-| `internal/activator/haforward.go:73,104`; `hacache.go:217,271` | Preserve SplitBackend dispatch; retain negative observation; distinguish preference from holder. |
-| `internal/activator/activator.go:3211`; `host/agent.go:576,746,1048` | Counts use HoldsAwake predicate; register source in real Service construction. |
-| `internal/lease/ha.go:35,169`; `hafresh/acquire.go:72` | Existing authority/read path unchanged. Absent acquire also costs LIST (`ha.go:100`). |
-| `internal/activator/hawake.go:413,657,730`; `hafiles.go:192`; `escrow.go:852` | Real acquire→keep/restore→sealed publication; witnesses reach these paths. |
+| `internal/boxchoice/policy.go:16,63,83`; `internal/boxchoice/boxchoice.go:120` | Reuse thresholds/Placeable/ChooseRoomiest; do not use roster-based Eligible. |
+| `internal/host/headroom.go:13`; `internal/host/edgesfile.go:173,228,1230`; `internal/registry/registry.go:229` | Publish additive headroom.apps from live activator ownership, not Hibernate policy/awakeCount. |
+| `internal/host/edgesfile.go:945,962,974` | Headroom outside the gate; timed writes refresh generation; no extra write for app-count changes. |
+| `internal/boxchoice/boxchoice.go:27`; `internal/edgesfile/snapshot.go:72,280` | Headroom starts at 27. Leave console PlacementView/BoxChoice unchanged: 3a does not consume its app counts. |
+| `internal/edge/homemap.go:134,169,456,730`; `internal/edge/holderview.go:33` | Placement-only decode/projection from cached fold; holder parsing/age policy survives malformed additions. |
+| `internal/edge/forwardha.go:41,147,180` | Extend interface; front decision at 147, signed forward at 180; one hop/accounting owner. |
+| `internal/activator/haforward.go:67,108,146,164`; `internal/activator/hacache.go:217,271` | SplitBackend reader at 67, ForwardTarget at 108. Retain typed negative observations; distinguish owner/recovery/placement outcomes. |
+| `internal/activator/activator.go:3211`; `internal/host/agent.go:576,744,746,944,1048` | Owned-awake predicate; arm one helper after Service creation, before Start/edges loop, pass same Service to edge. |
+| `internal/lease/ha.go:35,100,169`; `internal/hafresh/acquire.go:72,87,93` | Only acquire authorizes; absent acquire costs a LIST; same-box expiry requires emptiness, other-owner expiry termination. Equality at expiry still held in DecideAcquire. |
+| `internal/activator/hawake.go:413,635,657,730`; `internal/activator/hafiles.go:192`; `internal/activator/escrow.go:852` | Real acquire→keep/restore→sealed publication, including restoreFilesClean at 635. |
+
+## Placement applicability and failure answers
+
+**One rule: placement is advice for a free wake, never a prerequisite for main's recovery.** Enforce this table only in the new pure `activator.DecidePlacement` (Task 3). Service keeps existing early bypasses and positive-holder/suspect resolution; edge keeps the hop/accounting boundary. Tests and simulation call this function rather than reimplementing its table. “Base” means P1b-2 holder behavior followed by ordinary local **HA** acquire, with all its proofs/refusals; it never selects legacy acquire.
+
+| Input after existing positive-holder/suspect handling | Decision / invariant |
+|---|---|
+| Switch off | Base, even with born-HA route and zero snapshot. **N-HA7/§19.** |
+| No usable lock observation (read error/cancel/timeout/malformed), leftover owner, malformed marker | Decline placement; Base re-reads/classifies locally. Never represent unknown as absent. **I1 / no guessed free lock.** |
+| HA owner is this instance id or self reference, expired or not | Base local acquire; no capacity/releaser override. **§9.6 / I4 same-box recovery.** |
+| Parsed HA peer owner, no marker | Never H4. Unexpired/equality retains holder behavior. If expired and owner is in the fresh Serving set and not ref-suspect, issue a short-lived Recovery hint; edge still validates boxInView. Otherwise Base: local acquire can confirm termination/take over, or refuse an alive owner. After a failed Recovery dial, next request uses Base while ref-suspect, rather than retrying the dead owner forever. Out-of-view/no key also uses Base. Never cache an expired owner for an hour. **§9.6 / I1 / I4.** |
+| Absent lock or valid HA release marker, but no usable own placement identity/freshness/compatible candidates | Decline placement; Base on ordinary serving ingress. Missing/stale fold cannot make a known local route unavailable. **N-HA7 / A20 / I4.** |
+| Same free observation, switch on, usable snapshot | Filter placement-suspect refs, then ChooseColdWake. Eligible clean releaser or H4; if all remaining candidates lack headroom, choose roomiest and page. No candidates: Base on ordinary serving ingress. **H4 / I4.** |
+| Switch on and own file explicitly forbids local service (non-serve role, draining/drained) | Never take a Base local wake from the rows above. For a free observation choose a usable serving peer; owner hops still allowed. No permitted route: refuse up front with C1. Unknown safety-field types also forbid local placement. One LocalDenied input to this rule, not a second edge/acquire policy. **§4.4 / refuse before work.** |
+
+**H4, only in ChooseColdWake.** Inputs: canonical host, account/app key, optional clean releaser and scoped WakeSnapshot. Prefer clean releaser in `Placeable(Serving,nil,now)`. Otherwise ChooseRoomiest on eligible candidates with app loads. None eligible: ChooseRoomiest on remaining serving candidates without spread, return OverCapacity. Missing headroom contributes zero, never guessed totals. Only V==1, Clean, non-empty Box on a valid HA release marker supplies affinity; DecideKeep still proves reuse after acquire. Thresholds remain in existing policy helpers.
-## Placement contract and failure answers
+**§4.3 scope, only in edge wakeSnapshot.** From one immutable homeSnapshot require same region/placement, non-empty data bucket/key fingerprint, hibernation_configured:true, region-ha-1 and fresh generation; peers also need a dialable address. Candidate.BoxID and Running keys use published **box**, never box_id (which may be an EC2 iid). A peer must publish primary role:home for rt.Host with matching account/app; alias/wildcard/cert-only/replica never qualifies. **Self adopts through the request's local route**, even before its hosts entry is folded. Missing/stale own file returns unusable evidence and applicability chooses Base; add no publisher→edge freshness bridge. Reject non-serving candidates; absent role means serve. ServesSharedPool is not required (leo legitimately serves hapair). Holder view remains independent of this policy and age.
-**H4, enforced only in ChooseColdWake.** Host, account/app key, optional clean releaser, WakeSnapshot. No choice without self evidence/serving set. Prefer clean releaser in `Placeable(Serving,nil,now)`. Otherwise ChooseRoomiest on eligible set with app loads. None eligible: choose all serving with no spread map (most memory then HRW), return OverCapacity. Missing headroom contributes zero to last resort, never guessed totals.
+**Additive decode boundary.** Keep the existing holder fields' decoder unchanged. New placement fields live in RawMessage/secondary decode, including host Replica. A bad required placement type excludes that candidate from placement only; it cannot reject the whole file or remove a P1b-2 holder target. Decode Apps separately: missing/bad/stale map or negative counts mean zero spread, never invalidate core headroom/holder fields. A malformed own role/draining field sets LocalDenied rather than permitting local placement. No new tolerance in existing identity/lease parsers.
-**§4.3 scope, enforced only in edge wakeSnapshot.** One immutable homeSnapshot: require own/candidate files, same AWS region/placement, same non-empty data bucket, matching non-empty secrets fingerprint (sealed HA needs key), dialable address, explicit hibernation_configured:true, region-ha-1, fresh generation. Candidate publishes primary role:home for **rt.Host**, matching account/app; alias/wildcard/cert-only/replica cannot qualify. This proves adoption of this pool's host; requiring ServesSharedPool would wrongly exclude leo from hapair. Reject draining:true, drained:true, explicit role other than serve; absent means serve (§4.4). No per-request identity/status read; P1b-2 deployment-store trust remains.
+**Counts, only in AwakeApps.** Key `release.RouteAccount(rt)+"/"+rt.App`: owned awake hosts once, standalone workers included, co-spawn no second host. Exclude waking/stopping/fenced/lease-lost/shutdown. Missing callback omits map. No store/registry call; Hibernate is policy, not an awake count.
-**Budget/H4, publisher/projection.** Counts keyed `release.RouteAccount(rt)+"/"+rt.App`: owned awake hosts once, standalone workers included, co-spawn no second host. Exclude waking/stopping/fenced/lease-lost/shutdown. Missing source omits map. Never claims, all registry rows or published host lists. Negative counts become zero. Default counts cannot make stale membership usable.
+**Placement reachability, only in placementPeers.** Bounded per-ref suspicion lasts 10s after failed dial, renewed only by a subsequent admitted failed dial; any answer from that ref clears it. Filter before releaser/H4. The failed request still gets 503, no second choice in that request; the next request (including a different host) can choose a survivor immediately. Suspect placement never becomes a per-host holder-suspect refusal. Re-admit after 10s; retain per-address dial gate. A true holder is never replaced by H4 because it is suspect. A failed expired-owner Recovery hint uses this ref suspicion to return Base on the next request, preserving main's termination check; it cannot set a positive-holder suspect entry. Stale results cannot poison a newer answer/acquire.
-**I1/I2, existing acquire/keep.** Unexpired other holder outranks placement; same-box owner retains local acquire/refusal. Only V==1, Clean, non-empty Box marker offers releaser preference; no copy guarantee. Absent lock, unclean marker or expired owner routes H4; receiver still needs all acquire proofs. Read-error/malformed lock is not free: refuse. Verified hop never rechooses/forwards; receiver acquires or returns P1b-2 diagnostic.
+**N-HA10, only in frontForwardHA.** Chosen placement peer disappearing/no mesh key/dial failure answers existing 503 Retry-After:10, zero ingress begin/second hop/accounting. Ordinary holder/recovery ForwardNotInView keeps Base behavior. Verified hop never rechooses; receiver acquires or returns P1b-2 diagnostics. C1 is only for prohibited local service with no usable route; missing snapshot/read alone is not C1.
-**N-HA10/bounded forwarding, frontForwardHA.** Selected peer gone/no mesh key/dial failure: existing 503 Retry-After:10, no ingress wake/second choice. Ordinary holder ForwardNotInView unchanged. Awake/waking here bypasses placement. Missing snapshot/choice/read result uses C1 with same status/retry.
+**Races.** Equal evidence yields equal preference; differing folds may choose differently. Conditional acquire is still the one writer gate. Without §6.5 retry a loser may return 503. A headerless successful placement answer is reachable, not proof of a holder.
-**“One box” under races.** Equal snapshots yield equal preference. Different cached folds can choose differently; §6.7 allows conditional-acquire race, one winner/start. No consensus placement record. Test divergence; do not promise identical global preference during membership changes. Without §6.5 retry a loser can return retryable 503.
+## Round 1 dispositions
+
+Evidence names existing code; tasks name proposed changes. All P1/P2 findings are addressed in rev 2, awaiting independent review. Fault-family names are invariants, not affected files.
+
+| Finding / invariant | Verified evidence | Rev 2 disposition, witness and mutation |
+|---|---|---|
+| **P1-1 — §9.6/I4, preserve main's recovery** | `internal/hafresh/acquire.go:72,93,99`; `internal/activator/haforward.go:146,193,207`; `internal/activator/activator.go:6145` | **Take.** Tasks 2–4: DecidePlacement excludes owner-bearing locks from H4; self local, expired peer recovery hint. TestPlacementExpiredOwner / TestColdPlacementExpiredOwnerRecovery (crash/restart, roomiest peer, requests at both), mutation **placement-ignores-expired-owner**. |
+| **P1-2 — N-HA7/§19, preserve main's recovery** | `internal/host/edgesfile.go:196`; `internal/host/headroom.go:13`; `internal/edge/homemap.go:362`; `internal/edge/forwardha.go:147` | **Take.** Tasks 2–4: Enabled input, off returns Base after holder probe, born-HA still acquires HA. TestPlacementSwitchOff / TestColdPlacementSwitchOff; mutation **placement-ignores-switch**. |
+| **P1-3 — I4, preserve main's recovery** | `internal/boxchoice/policy.go:27`; `internal/host/edgesfile.go:974`; `internal/edge/forwardha.go:204,299` | **Take.** Tasks 3–4: per-ref placementPeers, 10s, filter before H4/affinity, any answer clears. TestPlacementSuspectBox / TestColdPlacementDeadChoice: listener dies, next request within 10s wakes on survivor, cross-host exclusion; mutation **placement-ignores-suspect-box**. |
+| **P2-1 — A20/I4, local adoption precedes fold** | `internal/edge/forwardha.go:147`; `internal/host/edgesfile.go:1202,1252`; `internal/edge/homemap.go:123,392` | **Take.** Tasks 2–4: self adoption from local route, peers from publication. TestWakeSnapshotSelfAdoptsBeforePublication / TestColdPlacementNewHostNoFold; mutation **placement-requires-published-self-host**. Missing own file uses Base. |
+| **P2-2 — budget, bounded ingress GETs** | `internal/activator/haforward.go:170,178`; `internal/activator/hacache.go:31,271` | **Take.** Tasks 3–4: keep original negative observation/deadline on placement none/headerless 503; no sliding TTL or guessed holder. TestPlacementRefusalKeepsObservation / TestColdPlacementRequestBudget; mutation **placement-drops-negative-on-refusal**, ingress/receiver counters. |
+| **P2-3 — executable production wiring** | `internal/host/agent.go:576,744,944`; `internal/host/haforward_wiring_test.go:15,21`; `internal/host/hatakeover_wiring_test.go:20` | **Take.** Tasks 1/3/4/5A: one armHAPlacement helper wires both callbacks, called once by runAgent and executable witness. Accept single-call/order syntactic check only for uncallable agent entry; helper behavior executes. Read Apps from both live files. TestAgentArmsHAPlacement / TestHAPlacementPageWiring / TestColdPlacementProductionWiring; integration mutation **placement-skips-arm** suppresses the common helper's invocation. |
+| **P2-4 — complete copy/interface contract** | `internal/host/alertsink.go:137`; `internal/edge/forwardha.go:147` | **Take.** Task 3/deck: C2 subject/body, C1 destination forwardha.go, C2 host/haplacement.go. TestHAPlacementPageWiring asserts both accepted strings, warning level/deadline; **placement-drops-page-subject** rejects loss of subject at that sink. Wording stays draft pending controller approval. |
+| **P3-1 — avoid unused census surface** | `internal/edgesfile/snapshot.go:72,280` | **Take:** no console decoder/converter Apps change or test. Only writer, edge placement decoder and boxchoice.Headroom need it. Cheap removal. |
+| **P3-2 — reference identity** | `internal/host/edgesfile.go:337`; `internal/edge/holderview.go:33` | **Take:** Task 2 TestWakeSnapshotUsesBoxReference sets box=group-ref, box_id=i-ec2; choice matches boxInView. |
+| **P3-3 — additive decoding preserves holders** | `internal/edge/homemap.go:730` | **Take:** Task 2 secondary placement decode; TestWakeSnapshotMalformedAdditionsPreserveHolder covers each new field and bad Apps independently. |
+| **P3-4 — stale self fold cannot strand local wake** | `internal/release/changewatch.go:17`; `internal/edge/homemap.go:392` | **Take outcome with simpler cut:** decline placement on stale own fold and use Base; no second freshness source. TestPlacementStaleSelfUsesBase / TestColdPlacementNewHostNoFold; zero extra S3. Publisher-time bridge unnecessary. |
+| **P3-5 — observable drill/count source** | `internal/edge/forwardha.go:193,205` (failure logs only); `internal/boxchoice/policy.go:63` | **Take:** Task 3 bounded decision/reason log; 5A reads both files' Apps and 15%/10% eligibility before reuse claim. Exact API counts from Task 4 counting transport, not inferred dev logs. No live telemetry infrastructure. |
+| **P3-6 — accurate citations** | `internal/edge/forwardha.go:147,180`; `internal/activator/haforward.go:67,108`; `internal/boxchoice/boxchoice.go:27`; `internal/sim/regionha/invariants_test.go:10` | **Take:** corrected these anchors and re-read every code citation, including file map, budgets and 3b seams. |
+
+No P3 is left as a reason to reopen review. Publisher freshness plumbing and live API telemetry stay outside this slice; the cheaper remedies above remove the acceptance gaps.
## S3 request budget
@@ -99,19 +140,23 @@ Logical API attempts, failed conditional calls included. SDK transport retries a
| Cold forwarded observation miss | 1G ingress + 1G+1P chosen peer = **2G+1P**, plus R; verified receiver skips front |
| Cold cached 10s observation | **1G+1P** target acquire, plus R |
| First absent-lock wake | Above **+1L** prefix-empty proof, then existing baseline/secret publication |
-| No fresh compatible serving box | 0 if observation cached, else 1G; 0P/0L; 503 |
-| Probe error/malformed | 1 attempted G, 0P/0L; 503, never cached “free” |
+| No usable placement snapshot/candidate on ordinary serving ingress | Base: 1G front on miss + local acquire (1G+1P if taken), plus R; absent +1L. No placement-induced 503 |
+| Explicit non-serving ingress, no usable permitted route | 0 if observation cached, else 1G; 0P/0L; C1/503 |
+| Probe error/malformed | Base: 1 attempted front G + local acquire read; persistent fault/refusal 0P/0L. If second read succeeds, ordinary acquire costs; never cached as free |
| Choice gone/no mesh key/unreachable | Probe as above; no ingress acquire; dial costs 0 S3 |
-| Holder or placement suspect window | **0 S3**, 0 dials for 10s |
-| Refused target acquire | 1G, 0P; expired other owner at most 1 EC2 describe/10s/iid |
+| True holder suspect window | **0 S3**, 0 dials for that host for 10s; existing holder backoff |
+| Placement ref suspect, free observation cached | **0 ingress G**, 0 dials to suspect ref for 10s; next request chooses survivor/Base, whose acquire costs 1G (+1P if taken), plus R |
+| First refused placement target acquire (none/headerless 503) | **2G, 0P** = 1G ingress observation + 1G receiver refusal; no LIST unless absent-prefix check |
+| Repeated refused placement within original 10s | **1G/request, 0P** at receiver; **0 ingress G**, no expiry extension. After deadline next request returns to 2G; legacy/leftover locks use Base with 1G local refusal per cached observation |
+| Expired owner recovery hop | Miss 1G ingress + 1G owner acquire (+1P if proven empty), plus R; cached observation removes ingress G. Failed Recovery dial: next request Base, 1G local acquire (+1P after confirmed termination), no ingress GET before original deadline; at most 1 EC2 describe/10s/iid |
| Projection/awake-count pass | **0G+0P+0L+0D** |
| Existing 2s edges check, only counts change | **0 new calls**, headroom outside gate |
| Existing timed HA publication | Existing replacement 1G+1P + index 1G+1P = **2G+2P**; increment 0 |
| Existing full fold, B keys | `ceil(B/1000)L+B*G`; increment 0 |
-Acquire CAS conflicts: at most 3 rounds (`lease/ha.go:48`), `gG+pP+lL`, 1<=g<=3, 0<=p<=g, 0<=l<=g (LIST only absent round). Add ingress probe. Pending marker obligation may add PUT before reads (`ha.go:82`). Renewals/release retries unchanged.
+Acquire CAS conflicts: at most 3 rounds (`internal/lease/ha.go:48`), `gG+pP+lL`, 1<=g<=3, 0<=p<=g, 0<=l<=g (LIST only absent round). Add ingress probe. Pending marker obligation may add PUT before reads (`internal/lease/ha.go:82`). Renewals/release retries unchanged.
-Edges replacement at most 3 attempts (`host/snapshot_loop.go:221`); index **4 total attempts** (`release/changeindex.go:31,130`), despite §18 “up to 4 retries.” For a replacements, k index attempts after success: (a+k)G+(a+k)P, a<=3,k<=4, max 7G+7P. Failed replacement has no bump. Do not turn 4 attempts into 5.
+Edges replacement at most 3 attempts (`internal/host/snapshot_loop.go:221`); index **4 total attempts** (`internal/release/changeindex.go:31,130`), despite §18 “up to 4 retries.” For a replacements, k index attempts after success: (a+k)G+(a+k)P, a<=3,k<=4, max 7G+7P. Failed replacement has no bump. Do not turn 4 attempts into 5.
Quiet: **0 incremental S3 requests/box/pass and /day**. §18 baseline about 3,300–3,500/hour (79,200–84,000/day) stays, not new allowance. Existing HA writer makes 10–12 timed publications/hour. Additive fields cause one rollout rewrite, not per-app/count-change writes. Coalesced fold fan-out stays `120*(ceil(B/1000)+B)`/hour/box. Count no-op passes in tests.
@@ -122,6 +167,7 @@ Quiet: **0 incremental S3 requests/box/pass and /day**. §18 baseline about 3,30
3. Hint becomes hour-long holder: Task 3 TestPlacementHintIsNotAHolder.
4. Counts create polling bill: Task 1 TestAwakeAppsRideTimedPublication; Task 4 budget witness.
5. Different choices/sealed restore: Task 4 TestColdPlacementCompetingViews/TestColdPlacementSealedWake.
+6. Applicability/recovery: round-1 disposition witnesses and mutations; switch off, expired-owner restart, lost target, route before fold, stalled index without extra reads.
---
@@ -129,16 +175,16 @@ Tasks 2/3 **[own review]** for routing/cache; Task 4 production wiring, census,
### Task 1: Live app counts and pure cold-wake choice
-**Files:** Create `internal/activator/awakeapps.go`, `internal/activator/awakeapps_test.go`, `internal/boxchoice/coldwake.go`, `internal/boxchoice/coldwake_test.go`, `internal/host/haawake_source.go`. Modify `internal/host/headroom.go:14`, `internal/host/edgesfile.go:173` and `:1230`, `internal/host/agent.go:576`, `internal/edgesfile/snapshot.go:72` and `:280`, `internal/boxchoice/boxchoice.go:29`. Test `internal/host/headroom_test.go`, `internal/edgesfile/snapshot_headroom_test.go`.
+**Files:** Create `internal/activator/awakeapps.go`, `internal/activator/awakeapps_test.go`, `internal/boxchoice/coldwake.go`, `internal/boxchoice/coldwake_test.go`, `internal/host/haawake_source.go`. Modify `internal/host/headroom.go:13`, `internal/host/edgesfile.go:173,1230`, `internal/boxchoice/boxchoice.go:27`; test `internal/host/headroom_test.go`. Task 3 adds the single agent arming call at `internal/host/agent.go:576`. Do not change `internal/edgesfile/snapshot.go` or its console conversion (P3-1).
**Interfaces:**
- `func (a *Service) AwakeApps() map[string]int`: fresh map under a.mu, count `ownedLocked(e,false)==nil`, valid account/app only. No store/registry call.
-- Add `Apps map[string]int`, JSON tag `apps,omitempty`, to edgeHeadroom/boxchoice.Headroom and shared edgesfile.PlacementView.Headroom; deep-copy through Snapshot.BoxChoice.
-- `func setHAAwakeApps(fn func() map[string]int)` / `func haAwakeApps() map[string]int`: atomic callback in haawake_source.go, nil yields nil. Register Service method before edges-loop start; headroomFor attaches snapshot. Tests restore source. Keep existing Awake field meaning.
-- `type WakeSnapshot struct { Self string; Region string; Serving []Candidate; Running map[string]Load }`; `type ColdChoice struct { Ref string; OverCapacity bool }`.
-- `func ChooseColdWake(host, app, cleanReleaser string, s WakeSnapshot, now time.Time) (ColdChoice, bool)`: contract above; empty Self invalid. Ref is published box reference, not EC2 iid/claim id.
+- Add `Apps map[string]int`, JSON tag `apps,omitempty`, only to writer edgeHeadroom and boxchoice.Headroom. Edge placement decode (Task 2) deep-copies maps into Running. Console ignores additive Apps as before.
+- `func setHAAwakeApps(fn func() map[string]int)` / `func haAwakeApps() map[string]int`: atomic callback in haawake_source.go, nil yields nil. Task 3 armHAPlacement alone registers Service.AwakeApps before Start/edges-loop; headroomFor attaches snapshot. Tests restore source. Keep existing Awake field meaning.
+- `type WakeSnapshot struct { Enabled bool; Usable bool; LocalDenied bool; Self string; Region string; Serving []Candidate; Running map[string]Load }`; `type ColdChoice struct { Ref string; OverCapacity bool }`. Enabled comes from the box switch; Usable means projection succeeded, not that a lock is free. LocalDenied carries explicit self prohibition, independently of freshness. Zero snapshot declines placement.
+- `func ChooseColdWake(host, app, cleanReleaser string, s WakeSnapshot, now time.Time) (ColdChoice, bool)`: H4 policy above over already-scoped candidates; empty Self/Serving yields false. DecidePlacement owns applicability and suspect filtering, not this chooser. Ref is published box reference, not EC2 iid/claim id.
-- [ ] **Step 1: Write failing tests.** TestAwakeAppsUsesOwnedEntries: two owned acct/shop hosts count 2; another account's shop 1; no alias/co-spawn duplication; waking/stopping/fenced/lease-lost/shutdown 0; returned map cannot alter service. TestColdWakeCleanEligibleReleaser: eligible releaser wins; below 15% memory/10% disk falls to H4. TestColdWakeRoomiestAndSpread: app-free, memory, exact existing HRW hash; reverse input order identical. TestColdWakeMissingInputs: no serving false; absent map zero spread; none eligible → roomiest + OverCapacity; nil headroom-derived zeros alone never refuse. TestAwakeAppsRideTimedPublication: changed Apps on ordinary pass zero calls, timed pass one replacement. TestBoxChoiceCarriesAwakeApps: old JSON decodes; new map survives conversion/copy.
+- [ ] **Step 1: Write failing tests.** TestAwakeAppsUsesOwnedEntries: two owned acct/shop hosts count 2; another account's shop 1; no alias/co-spawn duplication; waking/stopping/fenced/lease-lost/shutdown 0; returned map cannot alter service. TestColdWakeCleanEligibleReleaser: eligible releaser wins; below 15% memory/10% disk falls to H4. TestColdWakeRoomiestAndSpread: app-free, memory, exact existing HRW hash; reverse input order identical. TestColdWakeMissingInputs: no serving false; absent map zero spread; none eligible → roomiest + OverCapacity; nil headroom-derived zeros alone never refuse. TestAwakeAppsRideTimedPublication: changed Apps on ordinary pass zero calls, timed pass one replacement. TestAwakeAppsWireIsAdditive: old/new writer bodies decode with unchanged console PlacementView; Apps appears only when source present. TestColdWakeCopiesApps: caller mutation cannot change snapshot maps.
Pin the public policy with literal cases (the rest of Step 1 adds ownership/publication fixtures):
@@ -160,56 +206,70 @@ func TestColdWakeCleanEligibleReleaser(t *testing.T) {
}
```
-- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/boxchoice ./internal/host ./internal/edgesfile -run 'TestAwakeApps|TestColdWake|TestBoxChoiceCarriesAwakeApps' -count=1`. Expected FAIL.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/boxchoice ./internal/host -run 'TestAwakeApps|TestColdWake' -count=1`. Expected FAIL.
- [ ] **Step 3: Implement** interfaces using Placeable/ChooseRoomiest, no duplicate thresholds/sort. Preserve timed generation and headroom-excluded gate; update exact-wire fixture only for present additive field.
-- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/host ./internal/edgesfile ./internal/boxchoice -run 'Headroom|EdgesFileSchedule|Roomiest|Placeable' -count=1`. Expected PASS.
+- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/host ./internal/boxchoice -run 'Headroom|EdgesFileSchedule|Roomiest|Placeable' -count=1`. Expected PASS.
- [ ] **Step 5: Commit** `region-ha p1b-3a: publish awake app counts and define cold choice`.
### Task 2: Project a host's snapshot from cached fold [own review]
-**Files:** Create `internal/edge/wakeplacement.go`, `internal/edge/wakeplacement_test.go`. Modify `internal/edge/homemap.go:134` and `:169` decoders; leave holderview.go age-independent.
+**Files:** Create `internal/edge/wakeplacement.go`, `internal/edge/wakeplacement_test.go`. Modify the extension decode beside `internal/edge/homemap.go:134,169,730`. Leave holderview.go's age-independent compatibility rules unchanged.
**Interfaces:**
-- `func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot`: one snapshot read, copied slices/maps, canonical rt.Host/account.
-- edgesFileView gains Generation, Capabilities, HibernationConfigured *bool, Draining, Role, Drained, Headroom *boxchoice.Headroom; edgesHostView gains Replica bool. Existing writer JSON names plus future additive role/drained. Include self without boxInView's self-exclusion.
+- `func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot`: read one immutable snapshot, copy slices/maps; canonical rt.Host/account/app. Set Enabled from the existing parsed box switch (`internal/edge/homemap.go:362`). No homes means zero/unusable snapshot and Base, not a mandatory placement refusal.
+- Capture placement-only fields as RawMessage, then decode Generation, Capabilities, HibernationConfigured, Draining, Role, Drained, headroom scalars/Apps, and host Replica separately. Keep existing holder fields strict. Invalid required additions exclude placement only; bad Apps means empty spread. Track LocalDenied from own non-serving/malformed safety fields even if generation is stale. Missing fields use established defaults (absent role serve, absent capability/config not placement evidence).
+- Usable requires a compatible fresh own file with identity matching self; it need not be in Serving if explicitly non-serving. Self membership for this host comes from the local route, not own Hosts. Peer membership still requires exact primary role:home/account/app and compatible published evidence. Map Candidate.BoxID/Running by f.Box, never f.BoxID. Reuse one freshness predicate from boxchoice (export the existing `headroomFresh` as `HeadroomFresh`, with callers updated), not duplicate constants/comparisons.
-- [ ] **Step 1: Write failing tests.** TestWakeSnapshotCompatibility: require matching store/key/region/placement, capability/config/dial. TestWakeSnapshotRequiresThePrimaryHost: leo shared-pool false + hapair host in; no primary, alias/cert/wildcard/replica or account/app mismatch out. TestWakeSnapshotFreshness: age 15m in, 15m+1ns out; future 1m in, +1ns out; absent/bad generation out; absent/stale self invalid; drain/platform/booting/unknown role, Draining/Drained out. TestWakeSnapshotHeadroomAndApps: missing headroom serving but ineligible, missing/negative count zero, refs key candidates/loads. TestWakeSnapshotNoIO: 100 projections zero calls, no held-fold mutation. Old holder JSON still decodes.
+- [ ] **Step 1: Write failing tests.** TestWakeSnapshotCompatibility: store/key/region/placement/capability/config/dial. TestWakeSnapshotRequiresThePrimaryHost: leo shared-pool false + hapair host in; peer no primary, alias/cert/wildcard/replica/account/app mismatch out. TestWakeSnapshotSelfAdoptsBeforePublication: own fresh compatible file lacks new host, local route qualifies self; same absence on peer does not. TestWakeSnapshotUsesBoxReference: box!=box_id and choice passes boxInView. TestWakeSnapshotFreshness: 15m in, +1ns out; future 1m in, +1ns out; absent/bad generation unusable; original generation for carried-forward files; explicit non-serving self LocalDenied independent of age. TestWakeSnapshotMalformedAdditionsPreserveHolder: wrong type in each new field/Replica leaves file/holder forwarding intact, candidate excluded; bad Apps alone keeps headroom/candidate with zero spread. TestWakeSnapshotHeadroomAndApps: missing headroom in Serving but ineligible, negative count zero, copies immutable. TestWakeSnapshotNoIO: 100 projections zero calls.
- [ ] **Step 2: Run** `nice -n 19 go test ./internal/edge -run 'TestWakeSnapshot' -count=1`. Expected FAIL.
-- [ ] **Step 3: Implement** projection/decoders. Carried-forward files age by original generation. No roster/read/refresh-on-request/global holder-view change.
-- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/edge -run 'TestHolderView|TestForwardHANotInView|TestHome' -count=1`. Expected PASS.
+- [ ] **Step 3: Implement** projection/extension decoder; refuse incomplete placement cases at this boundary instead of adding stale-self tolerances or request refreshes. No roster, publisher bridge or global holder-view change.
+- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/edge ./internal/boxchoice -run 'TestHolderView|TestForwardHANotInView|TestHome|Fresh|Placeable' -count=1`. Expected PASS.
- [ ] **Step 5: Commit** `region-ha p1b-3a: derive cold placement from cached fold`.
-### Task 3: Use choice at front without local fallback [own review]
+### Task 3: One applicability rule at the front [own review]
-**Files:** Create `internal/activator/haplacement.go`, `internal/activator/haplacement_test.go`. Create `internal/host/haplacement.go`; modify `internal/host/agent.go:576`. Modify `internal/edge/forwardha.go:41` and `:173`, `internal/activator/haforward.go:104`, `internal/activator/hacache.go`, their tests, `internal/host/haforward_wiring_test.go`; create `internal/host/haplacement_wiring_test.go` here for the page test, extended in Task 4.
+**Files:** Create `internal/activator/haplacement.go`, `internal/activator/haplacement_test.go`, `internal/activator/haplacement_peers.go`, `internal/host/haplacement.go`, `internal/host/haplacement_wiring_test.go`. Modify `internal/host/agent.go:576` (one call), `internal/edge/forwardha.go:41,147,180`, `internal/activator/haforward.go:108,164`, `internal/activator/hacache.go:217,271`, their tests and `internal/host/haforward_wiring_test.go`.
-**Interfaces:**
-- Replace interface method with `ForwardTarget(ctx context.Context, rt registry.Route, s boxchoice.WakeSnapshot) edge.ForwardDecision`. Update all callers/doubles (`rg 'ForwardTarget'`). Edge passes wakeSnapshot, zero if homes nil; zero cannot disable asleep-HA placement.
-- ForwardDecision/ForwardResult gain `Placement bool`, copied through result. ForwardDecision gains `Unavailable bool` for absent snapshot/choice/read result (C1). Existing Refuse means suspect/dial-failure answer. Check Unavailable before Refuse in frontForwardHA; both stop before accounting.
-- Replace private cache tuples with `type holderResolution struct { Ref string; Refuse bool; Gen uint64; View *hafresh.View }` and `type holderRead struct { Ref string; View *hafresh.View; Err error }`. `func (c *holderCache) resolve(ctx context.Context, host string, read func() holderRead) holderResolution` retains immutable decoded negative view for original 10s. Positive lifetime unchanged. Error/cancel/timeout returns no usable View (Unavailable/C1); Refuse is reserved for an actual suspect entry, never inferred from an ordinary read failure. Preserve detached bounded single-flight read.
-- `func (c *holderCache) placement(host, ref string) uint64`: preference/token alongside observation, never extend observation expiry. Same choice reuses token; new choice advances it. Dial failure marks peer suspect 10s. Expired placement suspect with free read clears/rechooses; failed read keeps suspicion. All states share 50,000-host bound.
-- NoteForward never promotes placement 200 without holder header to 1h holder. Platform holder header may set positive. None/headerless 503 drops observation. Old failure cannot poison newer choice/acquire; generations/dial gate preserved.
-- Add `Service.OnHAOverCapacity func(region, host, ref string)`, installed before Start by `func wireHAPlacement(svc *activator.Service, page func(context.Context, string, string, string) error)` in `internal/host/haplacement.go`. Use snapshot.Region from own file; Service throttles one observation/region/hour/process, host helper sends accepted C2 as subject/body at alerting.LevelWarning on a detached 5s-bounded goroutine via PageOperator (`internal/host/alertsink.go:137`), never blocks a request or reads S3. No new unreviewed subject string. Multiple ingress processes can report the same condition; a deployment-wide deduplication guarantee is outside this slice.
-- ForwardTarget order: non-HA/unmanaged/live entry local; positive holder/suspect as today; unexpired self owner local acquire/refusal; missing View unavailable; otherwise ChooseColdWake. No choice unavailable, self local, peer {Ref,Placement:true,Gen}. OverCapacity pages C2 through existing operator path, once/region/hour, zero S3.
-
-- [ ] **Step 1: Write failing tests.** TestPlacementPrefersCleanReleaser, TestPlacementChoosesRoomiest, TestPlacementNoCapacityStillWakes (one callback/region/hour and no store calls), TestPlacementNoSnapshotRefuses, TestPlacementProbeFailureRefuses assert decisions/API counts/C1. TestPlacementCachesObservationNotChoice: changed fold within 10s recomputes with no GET, expiry one GET. TestPlacementHintIsNotAHolder: bare 200 never hour entry. TestPlacementSingleFlight: 20 misses one GET/full marker to all; one cancellation cannot cancel others. TestPlacementSuspectGeneration: 10s zero calls/dials, expiry re-probes, late failure cannot poison newer choice/acquire. TestPlacementHeldOwnerWins: no capacity/releaser override; self refusal unchanged. TestFrontPlacementNeverFallsBack: choice gone/no mesh key → 503 RA10, zero ingress begins; holder behavior unchanged. TestPlacementHopNeverRechooses: receiver differing view never onward-forwards. TestHAPlacementPageWiring: real helper reaches supplied page sink with accepted C2, warning level and 5s deadline; repeated Service observations throttle.
-- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/edge ./internal/host -run 'TestPlacement|TestFrontPlacement|TestAgentActivatorForwards|TestHAPlacementPageWiring' -count=1`. Expected FAIL.
-- [ ] **Step 3: Implement** interfaces/cache, one pure chooser/projection. Cached view never authorizes AcquireHA take. Preserve front-door ordering.
-- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/activator ./internal/edge -run 'TestForwardTarget|TestHolderCache|TestFrontForward|TestForwardHA|TestHopped|TestScheduledTickNeverForwards|TestLegacyHop|TestTakingTheLease' -count=1`. Expected PASS; update old free-lock-always-local assertions. Run TestHAPlacementPageWiring with `nice -n 19 go test ./internal/host -run TestHAPlacementPageWiring -count=1`.
+**Interfaces / invariant ownership:**
+- **Applicability / I4/N-HA7:** `func DecidePlacement(rt registry.Route, self hafresh.Self, view *hafresh.View, s boxchoice.WakeSnapshot, peers PlacementPeerView, now time.Time) PlacementDecision`, pure and callable by simulation. `PlacementDecision` has `Kind` (Base, Recovery, Place, Refuse), `Ref`, `OverCapacity`, `Reason`. Implement only the contract table above here; call ChooseColdWake after filtering suspects. Never call DecideAcquire/proofs here or grant authority. A valid release for placement requires HAOn and marker V==1 with non-empty Box; unclean valid marker has no affinity. Unknown markers/legacy owner/read failure use Base. Expiry equal to now is not proof of freedom. LocalDenied blocks Base only when Enabled. An expired peer is Recovery only while present in fresh Serving and not suspect; otherwise Base preserves termination recovery. Peer saturation declines placement in this same table (Base or explicit LocalDenied refusal), before any forwarding; reserve peer tracking as part of the bounded snapshot used for this decision.
+- **Front boundary / N-HA10:** `ForwardTarget(ctx context.Context, rt registry.Route, s boxchoice.WakeSnapshot) edge.ForwardDecision`; update all callers/doubles (`rg 'ForwardTarget'`). Add `ForwardKind` enum to Decision/Result: Holder (zero), Recovery, Placement; copy through result. Add Unavailable only for the rule's Refuse/C1. Existing Refuse remains true-holder suspicion. Base returns zero decision. Recovery routes owner with Kind Recovery; Place self returns local, Place peer forwards with Kind Placement. Edge checks Unavailable/Refuse before all accounting; only Placement changes ForwardNotInView to 503. Holder/Recovery preserve local fallback. Hops skip the whole front decision.
+- **Observation budget:** `holderRead { Ref string; View *hafresh.View; Err error }`, `holderResolution { Ref string; Refuse bool; Gen uint64; View *hafresh.View }`; resolve retains immutable negative View for original 10s. Include detached bounded single-flight, generations, canceled waiter behavior, failed re-probe of true suspect remaining refused. Nil View never means absent. ForwardTarget keeps existing non-HA/unmanaged/live-entry bypass and positive holder/suspect behavior, then calls DecidePlacement even on zero View/snapshot.
+- **Preference is not holder:** `holderCache.placement(host,ref)` tags choice under the observation's generation without resetting expiry. Recovery hints also use original negative deadline. NoteForward branches once by Kind. For Placement/Recovery, none or headerless 503 retains View/deadline; headerless 200 only clears reachability, never a 1h positive. A platform holder header can install positive; self header invalidates for local acquire. NotInView retains negative observation for these hints; Placement refuses this request, Recovery serves Base. True Holder retains P1b-2 drop semantics. No expired owner is installed positive without a fresh platform holder header.
+- **Reachability / I4:** one Service-owned `placementPeers` keyed by ref, max 50,000 tracked refs, 10s failure deadline. `snapshot(now)` supplies suspect set and saturation state to DecidePlacement; add `PlacementPeerView { Suspect map[string]bool; Saturated bool }` as that argument instead of an unbounded caller map. `begin(ref)` reserves a ref epoch token, copied as PeerGen in Decision/Result; `note(result)` records failed Placement/Recovery dials and clears on any real answer from ref (any Kind). Epoch advances on new answer/failure; stale failure cannot overwrite later success, nor a superseded host generation/acquire. Track tokens before dial, reuse during concurrent choices, never sliding-renew from a filtered request. At bound, decline new placement attempts until expired/idle entries can be reclaimed; do not evict an active suspect early or grow unbounded. Keep true Holder per-host suspicion separate; Recovery never installs it. No new S3 or background probe.
+- **One arming function / P2-3:** `func armHAPlacement(svc *activator.Service, page func(context.Context,string,string,string) error)` in host/haplacement.go calls setHAAwakeApps(svc.AwakeApps) and installs `Service.OnHAOverCapacity func(region,host,ref string)`. runAgent calls it exactly once with PageOperator after creation and before the startup coordinator invokes svc.Start (`internal/host/agent.go:744`) and before edgesFileLoop. The witness identifies the actual startup coordinator in agent.go, not an invented startupWork variable. Executable witnesses invoke this exact helper and clean up the atomic source. The only allowed syntactic witness checks call count, Service identity and order in agent.go; it is not evidence for callback behavior.
+- **Operator notice / P2-4:** Service throttles over-capacity callback once/region/hour/process. armHAPlacement sends accepted **C2 subject and body** with snapshot.Region, host, ref, warning level via PageOperator (`internal/host/alertsink.go:137`), detached with 5s timeout. Never block request/read S3. Cross-process page deduplication outside scope.
+- **Drill evidence / P3-5:** throttled decision log includes host, decision Kind, ref, stable Reason (base-switch-off, base-no-snapshot, owner-recovery, clean-releaser, roomiest, over-capacity, peer-suspect) and evidence generation. At most once/host/minute, within bounded host state, no S3. Wrapped diagnostic fields are not product copy. Reason selection is part of DecidePlacement, not a second policy.
+
+- [ ] **Step 1: Write failing tests.** TestPlacementExpiredOwner: self expired/equality local despite roomiest peer; expired serving peer recovery despite low headroom; owner outside fresh Serving/out of holder view or ref-suspect uses Base, never H4; failed Recovery dial followed by confirmed termination recovers locally, no repeated-hop blackout; no termination proof invented. TestPlacementSwitchOff: born-HA empty fold/zero snapshot, first local HA wake, held peer still forwarded, no H4/page. TestPlacementStaleSelfUsesBase / TestPlacementNoSnapshotUsesBase / TestPlacementProbeFailureUsesBase: no new C1, local acquire still validates; explicit LocalDenied instead refuses before begin when no peer. TestPlacementSuspectBox: marker-affinity and roomiest ref excluded across hosts; next request picks survivor within 10s; no repeated dial; expiry re-admits, any response clears, late failure cannot poison newer success/acquire; bound declines new placement safely. TestPlacementRefusalKeepsObservation: none/headerless 503 repeated through original t+10s uses one ingress GET, one receiver GET/request, no sliding expiry. TestPlacementCachesObservationNotChoice: fold change within 10s recomputes, no GET; expiry one GET. TestPlacementHintIsNotAHolder covers Placement and Recovery headerless answers. TestPlacementSingleFlight: 20 misses one GET/full view, one canceled waiter cannot cancel others. TestPlacementHeldOwnerWins / TestPlacementPrefersCleanReleaser / TestPlacementChoosesRoomiest / TestPlacementNoCapacityStillWakes: ordinary holder, H4, one warning callback/region/hour, zero extra calls. TestFrontPlacementNeverFallsBack: disappeared choice/no mesh key → 503 RA10, zero ingress begin. TestPlacementHopNeverRechooses: differing receiver view, no onward hop. TestAgentArmsHAPlacement checks the one agent call; TestHAPlacementPageWiring executes helper and asserts Apps, callback, accepted subject/body, warning/deadline/throttle. TestPlacementDecisionLogIsBounded: reason/ref, no visitor log flood/store calls.
+- [ ] **Step 2: Run** `nice -n 19 go test ./internal/activator ./internal/edge ./internal/host -run 'TestPlacement|TestFrontPlacement|TestAgentActivatorForwards|TestAgentArmsHAPlacement|TestHAPlacementPageWiring' -count=1`. Expected FAIL.
+- [ ] **Step 3: Implement** the interfaces and one applicability table. Cache/edge only carry decisions; no duplicate switch/owner/reachability policy. Cached observations never authorize AcquireHA.
+- [ ] **Step 4: Run** Step 2 plus `nice -n 19 go test ./internal/activator ./internal/edge -run 'TestForwardTarget|TestHolderCache|TestFrontForward|TestForwardHA|TestHopped|TestScheduledTickNeverForwards|TestLegacyHop|TestTakingTheLease' -count=1`. Expected PASS; update only assertions for free wakes where placement applies, preserve off/owner/Base cases.
- [ ] **Step 5: Commit** `region-ha p1b-3a: route cold wakes through front-door choice`.
### Task 4: Production witnesses, simulation and landing gate
**Files:** Extend `internal/host/haplacement_wiring_test.go`; create `internal/host/haplacement_root_linux_test.go`. Share production fixtures from `internal/host/plan14_lifecycle_root_linux_test.go` as needed. Modify `internal/sim/regionha/world_test.go`, `actions_test.go`, `invariants_test.go`, `rules_test.go`, `witness_test.go`, `sim_test.go`. Census artifacts generated during execution.
-**Interfaces:** Real activator.New→SplitBackend→edge.New, writer/decoder/fold/ForwardTarget. Run each logical box in its own child process: lease identity/obligation state are process globals, so two Services in one process are not a two-box authority witness. Low-level S3/EC2/dial seams inject faults; chooser/acquire/restore/launch/accounting cannot be replaced. Fake forwarders/AST-presence checks are not acceptance. Root acceptance uses isolated designated runner, real ensureSystemUnits/guard-armed edge dependencies, never sleep-service stand-ins or sudo. Any CLI-shelling witness must use the root package's carlosTestEnv and scratch cmd.Dir; do not inherit operator credentials/config.
+**Interfaces:** Real activator.New→SplitBackend→edge.New, writer/decoder/fold/ForwardTarget. Run each logical box in its own child process: lease identity/obligation state are process globals, so two Services in one process are not a two-box authority witness. Low-level S3/EC2/dial seams inject faults; chooser/acquire/restore/launch/accounting cannot be replaced. Fake forwarders/AST-presence checks are not behavioral acceptance. The sole exception is Task 3's one-call/order syntactic check of the uncallable runAgent entry, following `internal/host/haforward_wiring_test.go:15`; the common arming function and every callback must execute in this witness. Root acceptance uses isolated designated runner, real ensureSystemUnits/guard-armed edge dependencies, never sleep-service stand-ins or sudo. Any CLI-shelling witness must use the root package's carlosTestEnv and scratch cmd.Dir; do not inherit operator credentials/config.
+
+Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxchoice.WakeSnapshot` in world_test.go and `func (w *world) requestPlaced(b *box, h string, hopped bool)` in actions_test.go. Model each ingress's switch, local route versus published host membership, aged fold, typed lock observation with original deadline, ref suspicion/answer epoch, and ingress/receiver read counters. Call production DecidePlacement→ChooseColdWake then existing modeled acquire/keep; a hopped receiver skips the decision. Existing `internal/sim/regionha/invariants_test.go:10` checks I1/I2/I5; add bounded recovery assertions that require actual requests through this action. A direct finalTakeovers call must not mask a stranded placement path.
-Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxchoice.WakeSnapshot` in world_test.go and `func (w *world) requestPlaced(b *box, h string, hopped bool)` in actions_test.go. This request action distinguishes a forwarded receiver from the initial ingress; existing acquire/keep actions remain the authority model.
+| Mutation (one at a time) | Deterministic witness / invariant |
+|---|---|
+| placement-ignores-expired-owner | Restart expired owner with a roomier peer, direct request at owner and request via peer both recover only at owner, emptiness proof still required; then terminate that owner/fail Recovery dial and prove next survivor request takes only after confirmation. **P1-1, §9.6/I4/sim I5.** |
+| placement-ignores-switch | Born-HA route, flag off, no capable files: request still wakes through HA; held peer still followed. **P1-2, N-HA7.** |
+| placement-ignores-suspect-box | Both clean-releaser and roomiest variants: fail target dial, next request before 10s goes to survivor, second host cannot redial suspect; response clears, old failure cannot re-poison. **P1-3, I4.** |
+| placement-requires-published-self-host | Route exists locally before either file lists new host; self may wake, unadopted peer cannot be selected. **P2-1, A20.** |
+| placement-drops-negative-on-refusal | Ingress reads free marker, store changes before receiver acquire to another unconfirmed expired owner; none/headerless 503, repeat within original 10s: one receiver GET/request and zero ingress re-reads, then one re-read at deadline. **P2-2, bounded reads.** |
+| placement-ignores-releaser / placement-ignores-room | Shared views check affinity/thresholds/spread/hash ordering against public properties. **H4.** |
+| placement-local-fallback / placement-onward-hop | Remove chosen peer after decision; no ingress begin on that request; receiver with different view never forwards onward. **N-HA10 / one accounting owner.** |
+
+**Wiring/copy mutation boundary (P2-3/4).** The protocol simulation cannot prove Go agent registration or accepted words. Use test-only integration mutations `placement-skips-arm` and `placement-drops-page-subject` in TestHAPlacementPageWiring/TestColdPlacementProductionWiring instead; each must fail alone when the production helper is omitted or its subject is lost. First compares published owned Apps and observes the capacity page; second asserts the exact accepted subject/body at the supplied sink. No duplicate simulated arming/copy implementation can substitute for that witness.
-- [ ] **Step 1: Write failing witnesses.** TestColdPlacementProductionWiring: real provisioned HA record, production publication/fold, non-choice request → one peer acquire/start, no ingress begin, one gate/usage/analytics/guard owner. TestColdPlacementSealedWake: real clean release with sealed trio; non-releaser request keeps local/same key/token; make releaser ineligible and repeat → real restoreFilesClean/sealed restore/stageEscrowReads, no raw publish/second mint. TestColdPlacementCompetingViews: differing choices race real conditional store → one start, retryable loser, at most one hop. TestColdPlacementRequestBudget: count every budget row, absent LIST/errors/conflicts/no-op passes/suspect. Add TestColdPlacementRootRunner: actual nested host on selected box, failed wake/crash stop-and-prove before marker, restart one writer. Designated Linux root runner must execute; local privilege skip is not acceptance.
+- [ ] **Step 1: Write failing witnesses.** TestColdPlacementProductionWiring: real provisioned HA record, production publication/fold, non-choice request → one peer acquire/start, no ingress begin, one gate/usage/analytics/guard owner. TestColdPlacementSealedWake: real clean release with sealed trio; non-releaser request keeps local/same key/token; make releaser ineligible and repeat → real restoreFilesClean/sealed restore/stageEscrowReads, no raw publish/second mint. TestColdPlacementCompetingViews: differing choices race real conditional store → one start, retryable loser, at most one hop. TestColdPlacementExpiredOwnerRecovery: child leo acquires, crashes/restarts after expiry; sophie has more room; requests at each ingress both recover on leo after real empty proof, no sophie start while leo lives; equality/pre-expiry refuses, missing proof refuses. Separate expired terminated-owner case fails Recovery dial then takes on survivor through real confirmation, never strands behind stale file. TestColdPlacementSwitchOff: born-HA record with flag off and no capable files still wakes locally under AcquireHA; existing held peer path intact. TestColdPlacementDeadChoice: kill chosen listener with file still fresh, first request 503/zero fallback; next within 10s wakes survivor for marker and absent-lock variants, cross-host failed dials at most one/ref/10s, lease not bypassed. TestColdPlacementNewHostNoFold: real local route ahead of publication; first request serves, peers not yet advertising host excluded; repeat with stale own generation/lost index bump, no forced GET/refresh. TestColdPlacementRequestBudget: separate ingress/receiver low-level S3 counting transports, each budget row including first/repeated none/headerless 503, original deadline, absent LIST/errors/conflicts/no-op passes, true-holder versus Placement/Recovery suspicion. No production counter added to pass this test. Add TestColdPlacementRootRunner: actual nested host on selected box, failed wake/crash stop-and-prove before marker, restart one writer. Designated Linux root runner must execute; local privilege skip is not acceptance.
- [ ] **Step 2: Run** `nice -n 19 go test ./internal/host -run 'TestColdPlacement' -count=1`. Expected FAIL before integration; execute root witness on designated runner as well.
-- [ ] **Step 3: Extend simulation.** Independent aged ingress views call production ChooseColdWake then existing modeled acquire. Shared-view H4/one-hop oracles; preserve I1/I2/I5. Mutations placement-ignores-releaser, placement-ignores-room, placement-local-fallback, placement-onward-hop each caught alone by deterministic witness. H4 oracle asserts ordering properties, no duplicate chooser. Remove choice after decision to witness no fallback; pin divergent-view CAS race. No I3-duty claim/new expected miss.
-- [ ] **Step 4: Run** Step 2/root witness, then `nice -n 19 go test ./internal/sim/regionha -run 'TestWitnesses|TestSeedDeterministic' -count=1`. Once/revision build test binary in owned disk scratch; `RHASIM_PAR=1 nice -n 19 internal/sim/regionha/mutate.sh <binary> 3000`; remove scratch. Expect clean baseline/every rule caught alone.
+- [ ] **Step 3: Extend simulation.** Implement the interfaces/mutation table above, register each protocol mutation in rules_test.go and its isolated witness in witness_test.go. Preserve I1/I2/I5; extend I5 with request-path recovery for live recovered owners and free hosts whose preferred listener fails. H4 oracle asserts ordering properties, no duplicate chooser/applicability table. Pin divergent-view CAS race. No I3-duty claim/new expected miss.
+- [ ] **Step 4: Run** Step 2/root witness, then `nice -n 19 go test ./internal/sim/regionha -run 'TestWitnesses|TestSeedDeterministic' -count=1`. Once/revision build test binary in owned disk scratch; `RHASIM_PAR=1 nice -n 19 internal/sim/regionha/mutate.sh <binary> 3000`; remove scratch. Expect clean baseline/every protocol rule caught alone. Separately run `RHASIM_MUTATE=placement-skips-arm nice -n 19 go test ./internal/host -run 'TestHAPlacementPageWiring|TestColdPlacementProductionWiring' -count=1`, then the same command with `RHASIM_MUTATE=placement-drops-page-subject`. Only test fixtures read this variable for these mutations; clean baseline passes, each mutation fails its named assertion. Never add mutation switches to production code.
- [ ] **Step 5: Census/review.** Census below, all named witnesses, task/whole-branch reviews within budget against actual amadan-main diff. Record invariant/verdict/tip; do not claim 3b built.
- [ ] **Step 6: Implementation landing only.** `go build ./...`, `go vet ./...`, `make test` once; cross-build `CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build ./...`, windows/amd64 likewise; linux/arm64 with explicit binary output in owned scratch, check 64MB ceiling, remove. Commit evidence/follow-ups. Later authorized session pushes/describes implementation branch, requires exact-tip green CI before amadan squash merge, checks main CI. This drafting session runs none of those suites/pushes/merges.
@@ -219,10 +279,10 @@ Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxch
**5A: 3a, modeled on P1b-2 Task 5.**
-- [ ] **Step 1: Release/pre-check.** README dev recipe, boxes before console; UTC log, built version and behavior. Matching non-empty bucket/key fingerprint, CARLOS_REGION_HA, fresh compatible files, born-HA nested host adopted on both in hapair, healthy startup sweep, no obligation. Check live app counts. hapair-a1 only if approved.
-- [ ] **Step 2: Clean reuse.** Wake on one box, write sentinel/timer, real idle sleep, confirm clean marker. Twenty requests through other box, TLS SNI/Host via `curl --resolve`. All from choice; first kept local; one generation advance/start; no ingress acquire/start/accounting. Record body/version/owner/API counts.
-- [ ] **Step 3: Capacity/spread.** Fresh never-woken born-HA host avoids affinity. Read snapshots/compute production choice, request non-choice; one chosen acquire/start. Repeat with app spread. No-eligible/missing/stale cases in local fixtures; do not exhaust dev memory/disk or withhold files without scoped approval.
-- [ ] **Step 4: Race/backoff.** Asleep host, simultaneous pair requests: journals/live units show one writer, no fallback/onward hop. Loser may see 503. Approved choice-dial fault → failure within 2s, 10s suspect without GET/dial storm. Edge kill is not EC2 termination evidence.
+- [ ] **Step 1: Release/pre-check.** README dev recipe, boxes before console; UTC log, built version and behavior. Matching non-empty bucket/key fingerprint, CARLOS_REGION_HA, fresh compatible files, born-HA nested host adopted on both in hapair, healthy startup sweep, no obligation. Read Apps from **both live edges files** (not only svc fixtures) and compare to the owned-awake hosts. Before clean reuse assert releaser fresh, compatible, at least 15% memory and 10% disk; otherwise choose another eligible setup or stop the drill. hapair-a1 only if approved.
+- [ ] **Step 2: Clean reuse.** Wake on one box, write sentinel/timer, real idle sleep, confirm clean marker. Twenty requests through other box, TLS SNI/Host via `curl --resolve`. All from choice; first kept local; one generation advance/start; no ingress acquire/start/accounting. Record body/version/owner plus throttled placement Kind/ref/Reason/generation from ingress journal; reuse log from selected box. Exact API-call evidence is Task 4 counting-transport output for the built revision, linked in the drill report. Dev journals establish starts/acquires, not a claim to count every AWS API call.
+- [ ] **Step 3: Capacity/spread.** Fresh never-woken born-HA host avoids affinity. Read snapshots and production decision log (offline ChooseColdWake result as cross-check), request non-choice; one chosen acquire/start. Repeat with app spread. No-eligible/missing/stale cases in local fixtures; do not exhaust dev memory/disk or withhold files without scoped approval.
+- [ ] **Step 4: Race/backoff.** Asleep host, simultaneous pair requests: journals/live units show one writer, no fallback/onward hop. Loser may see 503. Approved choice-listener fault → first failure within 2s/503, next request within 10s serves on survivor, no second choice in first request, no further suspect-ref dials during its 10s window. Repeat across hosts; no ingress re-read within original observation TTL. Held-owner refusal/backoff remains separate. Edge kill is not EC2 termination evidence.
- [ ] **Step 5: Report/clean.** Timelines/counts/binaries/pass-fail to implementation branch and #421 through controller. Remove approved temporary hosts/artifacts/faults; no leftover process. Retained hosts asleep/clean. Pass before claiming switch-on; no flagship roll.
**5B: 3b outline.** After executable plan/trigger exist, scoped approval for disposable third hapair box or explicit pair-member removal. IE pair observes; never infer permission to terminate sophie/leo. Departing box holds one host and released another, synced once-timer/next_due, standalone sidecar included. Terminate EC2 or real P3 drain. **No visitor requests.** Record trigger/evidence/import/adopted mark/delivery/deletion. Kill scanner after one import; repeat on another survivor. Pass: every durable duty delivered, only unsynced final ~1s lost, no pre-expiry take/early delete, H7 duplicate tick only. Restore pair/remove disposable resources under approval. Visitor restore alone does not pass.
@@ -231,19 +291,21 @@ Simulation interfaces: add `func (w *world) coldSnapshot(b *box, h string) boxch
Required to finish §7, not ready to execute/review until 3a merges; drain acceptance also needs P3's producer on main. Write a separate executable plan with exact tests/steps. No duty files or published awake sets.
-**Trigger (I3/I4).** Request-driven P1b-1 alone cannot discover an asleep host's duties without traffic. Minimum no-SQS option: inspect cached generation ages on existing 30s home-map tick, even when index skips read (`homemap.go:392,1185`); crossing 15m schedules confirmation. Successful request-driven confirmation enqueues same work. Zero S3 polling, but only §9.8 lost-event/view-age fallback: up to 15m+30s from last publication, then remaining expiry/restore/delivery. Missing file/dial failure is suspicion, never evidence. Persist local pending departure before dropping discovery evidence.
+**Trigger (I3/I4, N-HA11 settled).** A small consumer on the **existing EC2 termination queue** is required in 3b. Use 20s long-poll waits, about **180 receives/hour/box** when quiet; existing queue/rule/receive/delete IAM are `infra/modules/region-host/main.tf:835,851,890`. No new queue, IAM expansion or S3 polling. Request-only P1b-1 cannot discover an asleep host's duties without traffic.
+
+Decode with `termfence.FromEvent` (`internal/termfence/fence.go:117`), bind iid to this deployment/account/region, confirm through cached `Confirmer.Terminated` (`internal/termfence/confirm.go:112`), durably enqueue departure scan, acknowledge only after completion. Shared SQS is work distribution, not broadcast: the receiver must retain responsibility for completion; HRW cannot discard an event in favor of an unnotified scanner. Duplicate delivery is retry-safe. If the scanner dies before ack, redelivery/another survivor resumes; no ChangeMessageVisibility permission assumed. Persist pending state before dropping evidence.
-**Recommendation: minimal SQS consumer in 3b** for normal §9.8 event-driven recovery. Existing 20s long-poll permission, `termfence.FromEvent` (`fence.go:117`), cached `Confirmer.Terminated`, enqueue scan, acknowledge after completion; retain age fallback for lost events. **180 SQS receives/hour/box, zero new S3 polls**, no heartbeat object. Request confirmation also enqueues. Paul may choose slower no-SQS contract; do not advertise prompt unattended recovery if consumer is cut. Drain trigger is P3's merged drained:true.
+**Lost-event fallback.** On the existing 30s home-map run tick (`internal/edge/homemap.go:123,392,1185`), inspect cached generations even when change-index polling skips the fold; age crossing 15m schedules the same bounded confirmation/enqueue path. Successful request-driven confirmation also enqueues it. Zero extra S3 polls; fallback bound up to 15m+30s from last publication plus expiry/restore/delivery. Missing file/dial failure is suspicion, never termination proof. No open no-SQS alternative remains. Drain trigger still waits for P3's merged drained:true producer.
| Proposed task / production seams | Invariant, interface and acceptance needed |
|---|---|
-| B1 new `internal/activator/haduties.go`; `internal/schedule/runner.go`, `converge.go`; `internal/host/schedule_wiring.go`, `runexec.go`; `internal/activator/activator.go:5615` and `:5642`; worker boot in agent | **I3, one duty gate.** Awake holder, sleeping releaser/adopter, never-woken HRW starter. Gate before token prep/ticks/due/boot/sweep/run picking. Non-owner advances ticks only after 15m; younger remain deliverable. Acquire before authority; live-peer result drops duty/suppresses probes until view/evidence changes. No HTTP forwarding of ticks. Co-spawn stays holder; WebSockets use hop, static/housekeeper unchanged. |
-| B2 new `internal/activator/haadopt.go`; `internal/hostfiles/wake.go:84` and `:134`; registry transaction/adopted mark | **I3, one adoptHost(ctx,route,departure).** Manifest+WakeItem only, never DB/tree/secrets restore. Missing referenced object/corruption keeps incomplete; no wake entry means no durable wake state. ImportWake replaces in 3 non-atomic writes: combine timers/next_due/replication/adopted mark transactionally. Serialize wake/registration/delivery; stale retry must not overwrite newly acquired host/advanced timer. Pin lifetime/departure identity/checkpoints. Held terminated-owner import must not grant delivery before expiry (N-HA9). |
-| B3 new `internal/host/hadepartures.go`; `internal/termfence/confirm.go:112`; cached fold tick; existing queue IAM | **I1/I3, evidence before scan.** Bind iid to verified deployment box record, same account/region; event alone insufficient. Cache immutable record (one GET/new ref), no claim enrollment. HRW over departed ref selects survivor; duplicate scans on different views tolerated. Durable local pending/retries on existing passes. Out-of-pool host needs eligible adopter; never call skipped host completed. |
+| B1 new `internal/activator/haduties.go`; `internal/schedule/runner.go`, `converge.go`; `internal/host/schedule_wiring.go`, `runexec.go`; `internal/activator/activator.go:5615,5642`; worker boot in agent | **I3, one duty gate.** Awake holder, sleeping releaser/adopter, never-woken HRW starter. Gate before token prep/ticks/due/boot/sweep/run picking. Non-owner advances ticks only after 15m; younger remain deliverable. Acquire before authority; live-peer result drops duty/suppresses probes until view/evidence changes. No HTTP forwarding of ticks. Co-spawn stays holder; WebSockets use hop, static/housekeeper unchanged. |
+| B2 new `internal/activator/haadopt.go`; `internal/hostfiles/wake.go:84,134`; registry transaction/adopted mark | **I3, one adoptHost(ctx,route,departure).** Manifest+WakeItem only, never DB/tree/secrets restore. Missing referenced object/corruption keeps incomplete; no wake entry means no durable wake state. ImportWake replaces in 3 non-atomic writes: combine timers/next_due/replication/adopted mark transactionally. Serialize wake/registration/delivery; stale retry must not overwrite newly acquired host/advanced timer. Pin lifetime/departure identity/checkpoints. Held terminated-owner import must not grant delivery before expiry (N-HA9). |
+| B3 new `internal/host/hadepartures.go`; `internal/termfence/confirm.go:112`; `internal/termfence/fence.go:117`; `infra/modules/region-host/main.tf:890`; cached fold tick | **I1/I3, evidence before scan.** Bind iid to verified deployment box record, same account/region; event alone insufficient. Cache immutable record (one GET/new ref), no claim enrollment. Required SQS consumer plus age/request fallback feed one enqueue function; receiver owns completion until ack, HRW is only a scanner preference with explicit handoff, never grounds to discard work. Duplicate scans tolerated. Durable local pending/retries on existing passes. Out-of-pool host needs eligible adopter; never call skipped host completed. |
| B4 same departure file, conditional edges deletion/index | **I3, scan before deletion.** Existing region-HA records include asleep/sidecar, not only public edges. One lock GET/host/attempt, match parsed owner **or marker releaser**, validate iid/lifetime, one adoption function. Complete after all classified and every match imported/safely superseded. Persist progress. Scanner death retries elsewhere. Delete only same departed identity/ETag after completion, then index/cancel backoff/ack. Drain scan repeats while drained evidence remains. |
-| B5 simulation, production multi-box/root witness, 5B | **I3/sim I6.** Model durable wake state/timers; current `internal/sim/regionha/invariants_test.go:9` checks I1/I2/I5, not I6. Mutations skip scan, owners-not-releasers, delete early, partial-scanner death. Death before first sync loses only unsynced timer; replay cannot erase delivered/advanced timer. Fixture-only acceptance insufficient. |
+| B5 simulation, production multi-box/root witness, 5B | **I3/sim I6.** Model durable wake state/timers; current `internal/sim/regionha/invariants_test.go:10` checks I1/I2/I5, not I6. Mutations skip scan, owners-not-releasers, delete early, partial-scanner death, ignore queue event, ignore lost-event age trigger, ack-before-import; duplicate-message/consumer-crash redelivery and skipped-index-tick witnesses. Death before first sync loses only unsynced timer; replay cannot erase delivered/advanced timer. Fixture-only acceptance insufficient. |
-**3b per-attempt S3 budget:** N region hosts, A matches, W<=A manifests with wake state: **(N+A+W)G, 0L/0P**. Host list from existing reconciliation, no LIST. Identity at most one GET/uncached ref. Pending/progress/adopted marks local, zero S3. Termination completion adds **1D + kG+kP** index, 1<=k<=4; retain ETag from existing fold read (currently discarded), otherwise +1G refresh. Drain scan itself does not delete serving file/change role; P3 owns completion. SQS ack is not S3. CAS conflict incomplete, never unconditional delete.
+**3b per-attempt S3 budget:** N region hosts, A matches, W<=A manifests with wake state: **(N+A+W)G, 0L/0P**. Host list from existing reconciliation, no LIST. Identity at most one GET/uncached ref. Pending/progress/adopted marks local, zero S3. Termination completion adds **1D + kG+kP** index, 1<=k<=4; retain ETag from existing fold read (currently discarded), otherwise +1G refresh. Drain scan itself does not delete serving file/change role; P3 owns completion. SQS ack is not S3. Quiet SQS workload remains about 180 receives/hour/box; delivery/redelivery adds event receives/deletes. Back off queue errors without spinning; all consumers and age checks stop with the agent. CAS conflict incomplete, never unconditional delete.
Partial retry costs remaining hosts or worst full formula; duplicate scanner a second formula. N=500,A=W=20 → **540 GETs**, about **$0.000216** at §18 prices, plus evidence/deletion/index. Event workload, never N GETs/box/30s. Quiet pass/no pending departure: **0 new S3 calls**. Evidence false/error cached 10s; retry with bounded backoff on existing passes, not visitor-rate describes. Ordinary duty acquire adds existing 1G (+1P if taken); duplicate live-holder encounter 1G, then suppress. Counter tests cover idle/partial/duplicate/import/delete failure. B2 reads no sealed trio.
@@ -253,26 +315,27 @@ Draft only. No Luna invocation or approval in this session. Inventory destinatio
| ID | Slice / destination | Draft text | Context / constraints |
|---|---|---|---|
-| HA3-C1 | 3a front refusal, `internal/edge/wakeplacement.go` | This instance cannot wake right now. Please try again shortly. | 503 RA10 for absent compatible snapshot/choice or unreadable probe; not low headroom. No box/account leakage. |
-| HA3-C2 | 3a operator-page call, `internal/activator/haplacement.go` | No box in region %s has enough spare capacity. Instance %s is waking on %s. Add capacity to this region. | Host still wakes; once/region/hour, preserve three placeholders. |
+| HA3-C1 | 3a front refusal, `internal/edge/forwardha.go:147` | This instance cannot wake right now. Please try again shortly. | 503 RA10 only for explicitly prohibited local service with no usable permitted route. Missing placement snapshot/read falls Base; no box/account leakage. |
+| HA3-C2-body | 3a operator-page body, new `internal/host/haplacement.go` | No box in region %s has enough spare capacity. Instance %s is waking on %s. Add capacity to this region. | Host still wakes; once/region/hour, preserve three placeholders. |
+| HA3-C2-subject | 3a operator-page subject, new `internal/host/haplacement.go` | Region %s needs more capacity | Paired with C2-body in PageOperator, warning level; preserve region placeholder. |
| HA3-C3 | 3b scan-failure operator notice | Duties from box %s have not been recovered. The scan will retry. Check the box's wake state before removing its records. | Incomplete scan/no deletion; actionable cause appended separately. |
| HA3-C4 | 3b completion notice | Recovered duties for %d instances from box %s. | Durable import/completion only; count hosts including sidecars. |
-Controller supplies accepted C1/C2 before writing product destinations; C3/C4 wait for 3b plan. Implementation-plan prose uses writing-pipeline's explicit plan exception.
+Controller supplies accepted C1/C2-subject/C2-body before writing product destinations; C3/C4 wait for 3b plan. Implementation-plan prose uses writing-pipeline's explicit plan exception.
## Census
-Plan-only Markdown outside census; no overlay now. Execution touches root dependencies `internal/{boxchoice,edge,activator,host,edgesfile}` even for JSON fields: bodies/sites/new units/file envelopes. Agent-run is not exemption. No new root read/authority intended; reviewer checks callbacks/decoders/cache/full diff. Test-only edits can change envelopes.
+Plan-only Markdown outside census; no overlay now. Execution touches root dependencies `internal/{boxchoice,edge,activator,host}` even for JSON fields: bodies/sites/new units/file envelopes. Agent-run is not exemption. No new root read/authority intended; reviewer checks callbacks/decoders/cache/full diff. Test-only edits can change envelopes.
Run `make census-card`; tab-separated CLAIMS per changed unit (new read or none); `make census-propose NAME=region-ha-p1b3a CLAIMS=<owned-file>`. No invented disposition/archive layer. Run `nice -n 19 go test ./internal/provision -run 'TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary|TestPlan14RootInputInventoryCoverage|TestCensusRebaseCarriesDispositions' -count=1`. Check 9B8, re-pin demonstrated changed digest only. Independent cross-family reviewer approves each unit/envelope versus amadan main and records tip/verdict on #280 at implementation landing. No review dispatched now; no census unit escalates to Paul. P2 fixes still need census/new-security-behavior checks within budget.
## Open decisions and follow-ups
- **Paul, before implementation landing:** schedule/approve dev-only 3a drill scope. Recommend next dev release after 3a; flagship activation unchanged.
-- **Paul, before 3b plan:** minimal SQS consumer (recommended), or explicitly slower age-based no-SQS recovery. Request-only cannot recover unattended duties.
+- **Settled N-HA11:** 3b uses existing termination SQS consumer plus lost-event view-age fallback. Complete its separate executable plan after 3a merges; no further trigger choice requested.
- Drain acceptance waits for P3's merged drained producer; no mocked flag to hide dependency or early G1/G3 claim.
- §6.5 retry, regional/cross-region non-holder handling, storage fencing (#501), existing-host migration (#502), roles/latch/hook/hairpin and G5 replacement stay separate.
## Self-review record
-§6.3/§11 → Tasks 1–3; I1/I2/front accounting → Task 4; visible drill → 5A. §7/I3/removal drill → explicitly deferred 3b/5B. §18 counts new paths/passes/mutations/fan-out. §19 has first visible result/release gate. §21 has production witnesses/mutations. Every Review Focus item has owning test. No tests/drills/reviewer verdict while drafting.
+§6.3/§11 → Tasks 1–3; I1/I2/front accounting → Task 4; visible drill → 5A. §7/I3/removal drill → explicitly deferred 3b/5B. §18 counts new paths/passes/mutations/fan-out. §19 has first visible result/release gate. §21 has production witnesses/mutations. Every Review Focus item and round-1 P1/P2 has an owning witness; protocol mutations exercise the common applicability rule, wiring/copy mutations run at the real helper boundary. Citation/file-path and diff checks only in this revision; no tests, drills, reviewer dispatch, production edits or push. Rev 2 does not claim READY.