plans: P3a plan rev 2 (answers Opus round 1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+103
−52
docs/superpowers/plans/2026-11-01-region-ha-p3-group.md+103 −52
diff --git a/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md b/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md| index 5ec226b07..3d3ad2e0c 100644 |
| --- a/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md |
| +++ b/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md |
| @@ -1,4 +1,4 @@ |
| -# Region HA P3: group infrastructure and admission implementation plan |
| +# Region HA P3: group infrastructure and admission implementation plan (rev 2) |
| > **For agentic workers:** Use writing-plans task-by-task, with checkbox tracking. This commission writes and commits the plan only. No implementation, push, reviewer dispatch, infrastructure plan against an account, or apply is authorized. A later controller chooses execution tooling. |
| @@ -8,23 +8,23 @@ |
| **Tech stack:** Go 1.26; existing S3 conditional stores; nftables/systemd on Linux; OpenTofu >= 1.10 and AWS provider >= 6.0 (`infra/modules/region-host/versions.tf:1`); existing SDK dependencies (`go.mod:10`). |
| -**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, rev 6.1, §§4.3–4.4, 10, 12–13, 18–21. Discussion #421 supplies N-HA8's ownership change and N-HA10–13. Read with `amadan discuss show carlos/platform 421`. |
| +**Spec:** `docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md`, rev 6.1, §§4.3–4.4, 10, 12–13, 18–21. Discussion #421 supplies N-HA8's ownership change and N-HA11–13. N-HA10 is recorded in `docs/superpowers/plans/2026-10-29-region-ha-p1b2-forwarding.md:21`. Read with `amadan discuss show carlos/platform 421`. |
| -**Citation base:** amadan `origin/main`, **65420a4d9e0d919743ea2e95e20b1a649605db3d**, also this worktree's starting HEAD. Existing platform `file:line` references below are to that commit. Proposed files have no source line numbers. No remote branch is merged, cherry-picked or used as an implementation authority. |
| +**Citation base:** fetched amadan `origin/main` on 2026-11-01: **ceee7a678780b9a742800b1a304a820bbf9f11d9**. Re-read the cited health, role/index, IAM, home-election, restart and fixed-root sources at that commit. All pre-existing source citations retain their line numbers: the only intervening main change since 65420a4d is the separate team-service prototype, outside these sources. Proposed files have no source line numbers. External private-checkout citations retain their separately stated HEAD. No unmerged branch is an implementation authority; the store-Deny branch is evidence of a blocking fix, not permission to apply it. |
| -**Status:** initial draft; no P3 review has run. Planning commit only, on `region-ha-p3-group`. |
| +**Status:** rev 2 answers Opus round 1 (NOT READY, 2 P1, 10 P2); no new review or approval is claimed. Planning commit only, on `region-ha-p3-group`. **No spec §10 change is needed with the chosen Standby mechanism. P3b does need the explicit §12.1 maintenance exception below; refuse it until approved.** The spec file is unchanged. |
| ## Scope, slices and switch-on |
| -**P3a: visible dev ingress.** The first implementation merge must travel with a scheduled dev deployment: an NLB in front of the existing fixed IE proving pair, serving an existing born-HA nested host. Keep its ordinary public DNS and regional EIP untouched; probe the NLB's new addresses with the host's real TLS SNI/Host. Admission, role publication, hairpin and instrumentation needed for that slice travel together. An empty NLB or a health endpoint permanently returning 503 is not its acceptance result. |
| +**P3a: visible dev ingress.** The first implementation merge must travel with a scheduled dev deployment: an NLB in front of the existing fixed IE proving pair, serving an existing born-HA nested host. Keep its ordinary public DNS and regional EIP untouched; probe the NLB's new addresses with the host's real TLS SNI/Host. Admission, role publication and instrumentation needed for that slice travel together. **Hairpin is cut from P3a (N1/S1)**: test inbound service from outside the VPC only; no own-region NLB call originates on the fixed boxes. Task 6 names delivery of the fixed pair's admission/region settings without editing user_data. P3b retains the hairpin acceptance gate. An empty NLB or a health endpoint permanently returning 503 is not its acceptance result. |
| **P3b: replacement group and G2.** Add the launch template, fixed-size ASG, launch hook, automatic boot, group alarms and a disposable dev group region. Integrate placement, console doors and departure/drain only after their producers merge. This separates an ingress change from the authority to replace boxes; it also avoids pretending that today's fixed pair already has the full admission predicate. |
| **Dev topology to approve:** eu-west-1, canonical region `ie`, existing home placement scope (empty CARLOS_REGION), existing dev IE data bucket, count=2 across two public AZ subnets. Reuse the operator-owned `hapair` pool and existing born-HA fixtures, with group boxes configured for **hapair only**, so they cannot adopt the shared dev tenant population. The fixed pair retains its current scopes for P3a; for the group-only G2 fault runs, first sleep the approved hapair fixtures cleanly, then temporarily withdraw only hapair from the fixed pair under the scoped roll approval. Restore it during cleanup. Readiness must prove every in-scope fixture is born HA/nested and that the merged placement/duty logic excludes boxes outside its pool. If main lacks that pool proof, the fixture inventory contains a legacy host, or the existing API refuses a needed new pool create under P2a's F5, refuse the affected drill rather than hand-write records or silently add another bucket/region. This is a dev IE group, not a new production region or an implicit grant to migrate hosts. |
| -**Sequencing refusal, rule 4:** main has no termination consumer and no active caller setting `lbhealth.State.SetHosting`. Thus neither P3a's first-serving deployment nor P3b's admission can be honestly completed against today's main alone. Tasks 1–5 specify work whose inputs exist on main; their runtime integration is held on the implementation branch until the separately listed producers merge and the outline is replaced by an executable addendum against that main. Do not land scaffolding ahead of the visible slice. Do not substitute a dummy `consumerStarted=true`, claim wiring, TCP-only health, or a second SQS consumer. P1b-3b must be able to start its consumer independently of an incoming drain producer; P3 can subsequently feed it drain completion. If that ordering is unavailable, stop at this boundary and split the integration after its merge. |
| +**Sequencing refusal, rule 4:** main has no termination consumer and no active caller setting `lbhealth.State.SetHosting`. Thus neither P3a's first-serving deployment nor P3b's admission can be honestly completed against today's main alone. Tasks 1–5 specify work whose inputs exist on main; their runtime integration is held on the implementation branch until the separately listed producers merge and the outline is replaced by an executable addendum against that main. Do not land scaffolding ahead of the visible slice. Do not substitute a dummy `consumerStarted=true`, claim wiring, TCP-only health, or a second SQS consumer. P3a's only outside runtime producer is P1b-3b's termination-consumer start acknowledgment; P2a's ingress configuration is required before P3b group publication, not before isolated P3a fixed-target probes. P1b-3b must be able to start its consumer independently of an incoming drain producer; P3 can subsequently feed it drain completion. If that ordering is unavailable, stop at this boundary and split the integration after its merge. |
| -**Who wants it / when:** Paul wants G3 (#421, finish-line note): first test carloku.com region HA after dev G1/G2. Reserve P3a for the first approved dev release after the consumer and ingress prerequisites merge; reserve P3b for **G2 in the next approved dev release after G1 passes**, not an unspecified later flag flip. Before implementation landing, Paul supplies the actual release date/window and scoped dev go (Task 6). Without that dated window, keep the implementation on its branch (rule 5). Planning this artifact does not activate a feature. G1 requires all P1b and P2, not just 3a/P2a; G3 requires G2 and readiness. P3 alone finishes none of those gates. |
| +**Who wants it / when:** Paul wants G3 (#421, finish-line note): first test carloku.com region HA after dev G1/G2. Reserve P3a for the first approved dev release after the consumer start-ack producer merges; reserve P3b for **G2 in the next approved dev release after G1 passes**, not an unspecified later flag flip. Before implementation landing, Paul supplies the actual release date/window and scoped dev go (Task 6). Without that dated window, keep the implementation on its branch (rule 5). Planning this artifact does not activate a feature. G1 requires all P1b and P2, not just 3a/P2a; G3 requires G2 and readiness. P3 alone finishes none of those gates. |
| **Retirement boundary:** P3 makes external fixed-target attachment, drain evidence, protected EIP ownership and reversible NLB mapping possible. P6 owns the production join/drain/EIP/stop/rollback runbook. No old production box is retired here; G5 additionally needs existing-host migration, P4, P5 and P6. N-HA9/storage fencing remains separate: failure recovery may wait **the remaining 15-minute lease**, not a new unconditional few-minute promise (`docs/superpowers/specs/2026-10-26-region-ha-without-claims-design.md:441,452,704`). |
| @@ -32,8 +32,9 @@ |
| | Round | Brief / findings | Verdict | Invariant / disposition | |
| |---|---|---|---| |
| +| 1 | `59cc03af`; brief `docs/superpowers/plans/REVIEW-BRIEF-REGION-HA-P3-R1.md`; findings `docs/superpowers/plans/REVIEW-REGION-HA-P3-R1.md` (Opus) | **NOT READY: 2 P1, 10 P2, 11 P3** | T1/I4 shared-dependency replacement; IAM boot scope; R1/B1, E1/S1, N1 and H4 families. Rev 2 dispositions below; not re-reviewed. | |
| -Empty means no P3 round, not an approval. Upstream history remains closed: spec R1–R3; P1a R1–R3; P1b-1 R1–R3; P1b-2 R1–R3; dead-holder backoff R1–R3. Boundary-only reads: P1b-3a final rev 3, Opus R2 READY AFTER FIXES/N-HA12; P2a final rev 4, Opus R3 READY AFTER FIXES/N-HA13. Neither is merged at this citation base. P3 does not reopen them or reset rounds on a split. |
| +One P3 round has run. This revision neither resets the count nor claims approval. Upstream history remains closed: spec R1–R3; P1a R1–R3; P1b-1 R1–R3; P1b-2 R1–R3; dead-holder backoff R1–R3. Boundary-only reads: P1b-3a final rev 3, Opus R2 READY AFTER FIXES/N-HA12; P2a final rev 4, Opus R3 READY AFTER FIXES/N-HA13. Neither is merged at this citation base. P3 does not reopen them or reset rounds on a split. |
| Future briefs use `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md:1`. Stop at the first round without P1; apply its P2s without another round and keep P3s on the branch follow-up list. Maximum three rounds; a fourth needs Paul's go. Name the invariant for every finding; a second consecutive round in one family stops fixes for Paul's refuse/cut/central-enforcement decision. Census and newly changed security/root/termination/storage behavior still check final fixes within that budget. Task-level review only for the risks in rule 3; whole-branch review before landing. No reviewers are dispatched by this plan-writing session. |
| @@ -78,32 +79,77 @@ Each implementation session owns one slice and ends at its merge. At 24 hours wi |
| | **B1, bounded I/O** | No new per-box S3, EC2, SSM, membership or health polling loop. Role reads ride the change index; health is local; boot is bounded; one existing/N-HA11 SQS receive loop only. Charge central console reads separately. | |
| | **P1, provider boundary / H26** | New core imports no AWS SDK. Generic identity, lifecycle completion, configuration and ingress addresses cross interfaces. AWS-only multi-box activation remains refused off AWS until supported identity and termination adapters exist; single-box self-hosters keep fixed behavior. | |
| | **N1, network authority** | Root installs rules only from root-owned configuration; tenant/agent-writable content never becomes nft or shell input. Hairpin preserves TLS Host/SNI, IMDS denial and egress policy; it grants no new allowed destination. | |
| -| **T1, bounded replacement** | min=max=desired; no automatic scale-in, instance refresh, AZRebalance or capacity optimizer. Existing serving instances cannot be replaced merely by editing the launch template. Bad boot abandons; an admitted hang is ELB/EC2 replacement, not a controller S3-loss auto-replacement. | |
| -| **E1, ingress and rollback ownership** | Protect every regional ingress allocation, keep one owner per EIP, and reject a fixed→group destructive migration. Zone-B rehearsal precedes any zone-A old-EIP cut-over. IE platform remains fixed/outside all target groups with its own relay/MX EIP. Platform role on an ASG member is refused; the ASG automatically attaches its members, so merely publishing platform would not remove one. | |
| +| **T1 / I4, replacement authority** | Enforce the single restart invariant in “Restart authority” below. Steady-state min=max=desired; no automatic scale-in, instance refresh, AZRebalance or capacity optimizer. Bad first boot abandons; an admitted local hang is ELB/EC2 replacement. No health action depends on S3/SSM success. | |
| +| **E1, ingress and rollback ownership** | Protect every regional ingress allocation, keep one owner per EIP, and reject a fixed→group destructive migration. Zone-B rehearsal precedes any zone-A old-EIP cut-over. Production IE platform remains fixed/outside all target groups with its own relay/MX EIP. P3a has one explicit dev exception: sophie is a temporary serving fixed target while it also runs the dev console; do not assign it platform during that probe. Remove its attachment before the later platform-role transition. Platform role on an ASG member is refused; the ASG automatically attaches its members, so merely publishing platform would not remove one. | |
| | **S1, scoped live authority** | Implementation and fake-provider/mock tests are local. Paul separately approves account/region/domain/resource/permission/traffic/cost/duration/cleanup; an infrastructure operator applies reviewed tofu. No generic dev or plan approval grants that authority. | |
| +## Restart authority: one gate for T1 / I4 |
| + |
| +**Invariant:** “a restart, a roll or a shared-dependency blip (S3, SSM) never terminates or replaces a box; only the box's own failure to serve does.” The single enforcement point is a **group maintenance transaction**, owned by the deployment release operator. The future private `scripts/roll-region-group.sh` is its only entry; root's proposed `internal/host/group_maintenance.go` checks its root-owned permit before any platform update can quiesce, repoint or stop the edge. Every restart-capable apply, rollback and recovery branch must use that same check, before mutations. The group boot writes an immutable root-owned group marker; losing an environment flag cannot turn this protection off. Fixed boxes keep their current restart behavior. |
| + |
| +Choose **ASG Standby**, rather than a health-200 timer. A bounded timer would still turn a longer S3 outage during startup into replacement. In Standby the box is deregistered and ASG health checks are suspended for that member; local tenant permission and health may remain closed for as long as shared dependencies are unavailable. No synthetic 200 and no remote-read health input are needed. AWS documents both the health exclusion and capacity semantics: [https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-enter-exit-standby.html](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-enter-exit-standby.html), [https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_EnterStandby.html](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_EnterStandby.html). |
| + |
| +- **T1, before touching a running box:** serialize maintenance per group in the deployment operator's durable transaction record; require N>=2, no other transaction and a healthy admitted peer. Stage/verify the signed binary and preserve local host.env, cert/key caches and old binary first. Set minimum N→N-1 with desired/max still N, then EnterStandby **with desired decrement**. Read back the exact iid as Standby, desired N-1/max N/min N-1 and target deregistration completed (30s delay); only then install a root-owned permit bound to account/region/group/iid/boot-id/transaction and old/new artifact digests, and close/restart the process. Never use EnterStandby without decrement: AWS launches another instance in that case. No group-wide suspension of HealthCheck or ReplaceUnhealthy, so other members remain protected. |
| +- **T1, one restart path:** group boot omits the agent system self-update leg (`internal/host/agent.go:3354`), masks the update path/service and verifies `ensureUnits` cannot re-arm them (`agent.go:5263`). Root system-apply/recovery refuses a group update without the maintenance permit, including stale queued requests (`systemapply.go:113,369,655,1797,2075`). The group-only edge drop-in sets `Restart=no`, overriding main's `Restart=always` (`internal/host/units/carlos-edge.service:23`): no automatic process retry can bypass Standby. A crash/hang outside maintenance is the box's own local failure, eligible for the existing health-driven replacement. Do not turn a rollout or S3/SSM read error into process exit. Group reboot/stop-start also requires this transaction; after reboot the operator must confirm the new boot-id and renew its root-owned permit before any recovery mutation. Arbitrary root `systemctl restart` is outside the supported recipe and must be refused by the release tooling before it issues a stop; an ExecStartPre check alone would be too late. |
| +- **T1/I4, restart while S3 or SSM is unavailable:** use the already-root-written host.env; never refetch SSM just to restart. Recheck Task 3's full readiness with tenant permission closed. Failed reconcile/role/edges work cannot release Standby. After a 15-minute operator wait, stop waiting, alert and retain the transaction/Standby/old artifact; **no timeout termination, hook ABANDON or ExitStandby** for an admitted member. Resume the same transaction after recovery. This is an operator-held outage, not a periodic watcher. The receipt suppresses a duplicate launch completion only; it grants no fresh admission or root permission. If the control API cannot confirm Standby before restart, refuse the restart and leave the running box alone. |
| +- **T1, return or roll back:** while still in Standby, require actual full local health, fresh Task 3 admission and successful role publication. ExitStandby restores desired N; verify InService/healthy and same iid, restore minimum N, revoke the permit last, then consider the next member. A failed release can restore the verified old artifact/settings under the same permit. If shared reads remain unavailable, keep that iid in Standby and alert rather than replace it. A locally broken box may be terminated only on separate explicit local-failure evidence and scoped operator authority; S3/SSM error or elapsed maintenance time is not that evidence. After any ambiguous write response, read back the actual transaction phase before advancing or retrying; never repair desired capacity by issuing a blind increase. Do not apply tofu or run another roll while a transaction is open. |
| + |
| +**Spec justification:** §10's latch still clears first on shutdown and is set only by its four acknowledgments plus the six-condition predicate. §9.5's live S3-loss box keeps health 200; a restarting box in Standby can answer 503 without becoming a termination candidate. After admission, the four startup acknowledgments remain latched until local shutdown; ongoing role/reconcile/edges/SSM errors do not clear hosting or fail health. The existing §9.5 operator termination after an S3-loss alarm remains a separately authorized recovery action, never an automatic health/roll decision. **No spec §10 sentence changes.** |
| + |
| +**NEEDS PAUL: spec §12.1 maintenance exception (T1).** Its current first sentence is “An Auto Scaling group: `min = max = desired = box_count` (H5), across at least two zones.” Proposed replacement: “An Auto Scaling group has `min = max = desired = box_count` (H5) across at least two zones, except during one serialized operator-owned maintenance transaction: temporarily lower minimum and desired by one to put that same member in Standby without launching a replacement, keep maximum and total membership fixed, and restore desired then minimum only after the member is ready to return.” Do not change the spec file here. **Refuse P3b activation/rolls until that exception is approved and recorded; P3a has no ASG and can proceed independently.** The JSON plan gate continues to refuse ordinary decreases; the named maintenance API transaction is the sole exception, with no scale-in call and no automatic cleanup on expiry. The scoped approval card must include these operator-only ASG writes; the box role gains none. |
| + |
| +## Rev 2 dispositions (not a second review) |
| + |
| +| Round-1 finding / invariant | Disposition and witness | |
| +|---|---| |
| +| P1-1 — T1/I4 shared dependency cannot authorize replacement | Central Standby transaction above; disable unattended group self-update/restart. Task 6 Step 4 proves same-iid retention beyond health thresholds and the 15m wait. §10 unchanged; §12.1 exception blocks P3b up front. | |
| +| P1-2 — IAM/A1 boot scope | Task 4 exact SSM path ARNs plus descendants in Allow and NotResource exceptions; policy-shape positive/sibling/ancestor tests. | |
| +| P2-1 — R1/B1 role freshness/budget | Task 2 ReadGate, Observed generation, 30m backstop, required arming and explicit disarmed refusal; budget adds 4G/box/h. | |
| +| P2-2 — I4/R1/S1 fixed opt-in | `CARLOS_GROUP_ADMISSION=1`; group marker mandates it. Absent fixed switch omits all P3 fields/callbacks; flagship regression witness. | |
| +| P2-3 — N1/S1 fixed root delivery | Cut P3a hairpin. Task 6 delivers only validated region/switch/index settings through the reviewed fixed roll, preserving user_data and pools. | |
| +| P2-4 — A1/H4 home election | Task 2 suppresses booting home rows and gates home selection before tie-breaking; retain holder diagnostics. Never-admitted `g-` regression. | |
| +| P2-5 — N1 client trust | P3a hairpin cut; P3b must present verified public box address or refuse, including kernel/address witness in Task 4. | |
| +| P2-6 — IAM least privilege | Task 4 removes #478 broad version rights in group mode; allow only merged production consumer needs with exact prefix conditions and assertions. | |
| +| P2-7 — E1/S1 safe dev apply | Task 6 whole-root read-plan before implementation merge, store-Deny merge gate and strict targeted saved apply; no unreviewed full dev apply. | |
| +| P2-8 — E1/T1 fixed resources | Task 1 JSON gate refuses any fixed instance/SG/IAM update, including in-place; only exact reviewed attribute exceptions. | |
| +| P2-9 — E1 fixed SG ownership | Task 1 adds no fixed SG rule; group-only target_security assertions and acyclic SG references. | |
| +| P2-10 — E1/S1 rollback ownership | Task 6 Step 2 rollback specifies release and infrastructure owners, target removal, config/binary restore and verification. | |
| +| P3-1 — evidence | N-HA10 attribution corrected to forwarding plan :21. | |
| +| P3-2 — dependency order | P3a waits only for consumer start acknowledgment; P2a console ingress belongs to P3b. | |
| +| P3-3 — reproducible checks | Task 1 ingress test filter runs from ingress child, not parent. | |
| +| P3-4 — E1 cleanup protection | Task 6 explicitly removes literal prevent_destroy in disposable child/module copy only. | |
| +| P3-5 — N1 dependency order | Task 1 NLB SG egress uses VPC CIDRs/ports, avoiding the host-SG reference cycle. | |
| +| P3-6 — S1 costs | Cost section adds custom metric series/churn and alarm estimates. | |
| +| P3-7 — A1 honest copy | Deck covers gate/boot/health strings; no pre-admission “waking elsewhere” assertion. | |
| +| P3-8 — E1 platform exception | Temporary dev sophie attachment stated; production platform stays excluded. | |
| +| P3-9 — I4 every ingress | Task 3 explicitly exercises authenticated door calls and tunnel deliveries at shared dispatch/start gate. | |
| +| P3-10 — I1 clock provenance | Task 5 bounded local `chronyc -c tracking` reading, parse/error witness, no new sampler. | |
| +| P3-11 — one source of serving truth | Coordinate edgesfile schema after P1b-3a merge; no review against that unmerged implementation. | |
| + |
| +All cheap P3s are taken; there is no new P3 follow-up requiring a round. If another round finds the same T1/I4 or IAM invariant again, this is two consecutive rounds in that family: stop fixes and ask Paul for the rule-2 refuse/cut/central-enforcement choice. R1 counts remain attached to this change. |
| + |
| ## File structure and contracts to build against main |
| These interfaces are **proposed P3 contracts**, not promises made by another branch. The integration outline must adapt merged producers to them or revise this plan before review; do not invent incoming function names. |
| | Files | Responsibility / proposed interface | |
| |---|---| |
| -| New `internal/boxroles/{roles.go,store.go,roles_test.go}`; modify `internal/release/changeindex.go` and its tests | `type Role string` constants Serve/Drain/Platform; `type Record struct { Role Role; By string; At time.Time }` with JSON role/by/at; `func Read(ctx context.Context, s release.Store, ref, region string) (Role, error)`; `func Key(target string) (string,error)`. Strict bounded keys/body, operator data only; no write API in P3a. | |
| +| New `internal/boxroles/{roles.go,store.go,roles_test.go}`; modify `internal/release/changeindex.go` and its tests; hostenv allowlist and existing home-election readers in `internal/edge/homemap.go`, `internal/edgesfile/homeelect.go` and their tests | `type Role string` constants Serve/Drain/Platform; `type Record struct { Role Role; By string; At time.Time }` with JSON role/by/at; `func Read(ctx context.Context, s release.Store, ref, region string) (Role, error)`; `func Key(target string) (string,error)`. Strict bounded keys/body, operator data only; no write API in P3a. | |
| | New `internal/groupadmission/{state.go,state_test.go}` | Pure state machine: `type Facts struct { EnvLoaded, Reconciled, RolePublished, TerminationStarted bool }`; `type Launch struct { Group, Hook, Instance string }`; `type Completer interface { Complete(context.Context, Launch) error }`; `type State` with `Observe(Facts)`, `Admit(ctx context.Context, launch *Launch, complete Completer, healthy func() bool) error`, `Admitted() bool`, `Close()`. No cloud, filesystem or goroutine in this core. Nil launch is fixed-box admission; group launch requires acknowledged completion. | |
| -| New `internal/host/{group_admission.go,group_admission_test.go,group_hairpin_rootrunner_linux_test.go}`; modify `agent.go`, `edgesfile.go`, activator wiring and `internal/edge/{lbhealth.go,forwardha.go}` | Own latch/ack wiring and process cancellation; publish effective role only after real success. Local tenant-start permission reads State plus effective role; `lbhealth.Default.SetHosting` reflects the four latch facts. Readiness for Complete is `len(lbhealth.Default.Failing(now))==0`; external health also requires admitted. See Task 3 for restart handling. | |
| +| New `internal/host/{group_admission.go,group_admission_test.go,group_maintenance.go,group_maintenance_test.go,group_hairpin_rootrunner_linux_test.go}`; modify `agent.go`, `edgesfile.go`, `systemapply.go`, group-only unit rendering, activator wiring and `internal/edge/{lbhealth.go,forwardha.go}` | Own latch/ack wiring and process cancellation; publish effective role only after real success. Opted-in fixed/group tenant-start permission reads State plus effective role; `lbhealth.Default.SetHosting` reflects the four latch facts. Readiness for Complete is `len(lbhealth.Default.Failing(now))==0`; external health also requires admitted. See Task 3 for restart handling. | |
| | New `internal/awsregiongroup/{complete.go,complete_test.go}` | Bind the SDK CompleteLifecycleAction method only; validate self identity/group/hook from immutable configuration. Satisfy groupadmission.Completer. Core never imports this package. | |
| | New `infra/modules/region-host/ingress/{main.tf,variables.tf,outputs.tf,tests/group_ingress.tftest.hcl}` | NLB, dedicated SG, protected zone EIPs, listeners/TGs. Callable alone by P3a dev root for existing fixed targets, and by region-host group mode later. External target attachments belong to deployment root. | |
| -| New `infra/modules/region-host/{group.tf,group_iam.tf,group_alarms.tf,group-init.sh.tftpl,tests/group.tftest.hcl,tests/group_iam.tftest.hcl,tests/group_alarms.tftest.hcl}`; modify `main.tf`, `variables.tf`, `outputs.tf`, fixed tests; new `scripts/check-region-group-plan.py` and local fixture tests | ASG/launch template, least-authority grants, boot and alarms. Fixed default remains supported; explicit state moves for count changes. The read-only JSON plan gate refuses count decreases, fixed-instance replacement/deletion and protected EIP deletion/replacement; only a reviewed disposable-resource cleanup manifest can exempt experiment resources. P6 owns production retirement. | |
| +| New `infra/modules/region-host/{group.tf,group_iam.tf,group_alarms.tf,group-init.sh.tftpl,tests/group.tftest.hcl,tests/group_iam.tftest.hcl,tests/group_alarms.tftest.hcl}`; modify `main.tf`, `variables.tf`, `outputs.tf`, fixed tests; new `scripts/check-region-group-plan.py` and local fixture tests | ASG/launch template, least-authority grants, boot and alarms. Fixed default remains supported; explicit state moves for count changes. The read-only JSON plan gate refuses count decreases, any fixed-instance/SG/IAM change and protected EIP deletion/replacement; only a reviewed disposable-resource cleanup manifest can exempt experiment resources. P6 owns production retirement. | |
| | Modify `internal/hostenv/{hostenv.go,hostenv_test.go}`, `internal/host/{installchannel.go,installchannel_test.go}`; new `internal/hairpin/{rules.go,rules_test.go}` and `infra/modules/region-host/hairpin.sh.tftpl` | Claim-free parameter allowlist and floor-absence install; pure IPv4-literal ingress validation and deterministic nft batch rendering: `func Rules(ingress []netip.Addr) ([]byte,error)`. Root script supplies validated addresses, never environment-as-shell. | |
| | Modify `internal/host/memwatch.go` and tests; new `internal/groupadmission/observability.go`, adapter metrics tests | Provider-neutral observation values; batch group memory/clock/admission samples through existing metrics adapter/cadence. No new sampler or S3 objects. | |
| -| Later private deployment `dev/region-ha-group.tf`, `dev/region-ha-ingress.tf`, parameter seeding and version pins | P3a fixed targets; P3b disposable group, approvals and cleanup. Separate reviewed branch in platform-infrastructure; no such file is written by this commission. | |
| +| Later private deployment `dev/region-ha-group.tf`, `dev/region-ha-ingress.tf`, `scripts/roll-region-group.sh`, `scripts/configure-p3a-fixed.sh`, parameter seeding and version pins | P3a fixed targets; P3b disposable group, approvals and cleanup. Separate reviewed branch in platform-infrastructure; no such file is written by this commission. | |
| ## Review focus |
| 1. **First service before hook acknowledgment, NLB fail-open or a signed direct hop:** Task 3's real activator witness proves zero acquire/start/holder diagnostic while booting, including shutdown races. |
| 2. **Restart after hook completion, lost success response or reused receipt:** Task 3's crash/receipt matrix refuses ambiguous admission and binds a retained receipt to this identity/configuration. |
| 3. **Unknown role mistaken for serve, or default rollback overridden by a replacement:** Task 2 pins precedence, failure behavior and a new reference under a regional default; deferred integration tests cover forwarding/drain. |
| -4. **Hairpin bypasses tenant egress or IMDS isolation:** Task 4 uses the real kernel path for agent, nested tenant, sidecar and rootfs network namespace; disallowed destinations remain blocked. |
| +4. **P3b hairpin bypasses tenant egress or IMDS isolation:** Task 4 uses the real kernel path for agent, nested tenant, sidecar and rootfs network namespace; disallowed destinations remain blocked. |
| 5. **Tofu edit replaces the old fixed box/EIP or launch succeeds before IAM/hook exists:** Tasks 1/5 pin fixed-state moves, initial-hook ordering, protected EIP ownership and negative/mock-provider plans; Task 6 observes initial and replacement launches. |
| --- |
| @@ -112,53 +158,53 @@ These interfaces are **proposed P3 contracts**, not promises made by another bra |
| **Files:** ingress child and group.tf/variables/outputs/main/fixed tests and JSON plan gate from the map above. New mock tests follow `infra/modules/region-host/tests/instance_metadata.tftest.hcl:1`. No account access. |
| -**Interfaces:** ingress inputs `vpc_id`, `zones` (map AZ→`{subnet_id, allocation_id}`; null allocation creates a protected EIP), `name`, `target_security_group_id`; outputs `public_ips`, `allocation_ids`, `target_group_arns`, `nlb_security_group_id`. The child accepts at least two distinct zones in one VPC. P3a root supplies fixed instance attachments to both TGs. Group mode supplies TG ARNs to ASG, with no per-instance attachment controller. |
| +**Interfaces:** ingress inputs `vpc_id`, `zones` (map AZ→`{subnet_id, allocation_id}`; null allocation creates a protected EIP), `name`, `target_vpc_cidrs`; outputs `public_ips`, `allocation_ids`, `target_group_arns`, `nlb_security_group_id`. The child accepts at least two distinct zones in one VPC; target_vpc_cidrs must match that VPC's validated CIDRs. It takes no host-SG reference; only the group host SG references the child's NLB SG output. P3a root supplies fixed instance attachments to both TGs. Group mode supplies TG ARNs to ASG, with no per-instance attachment controller. |
| Region-host gains `mode` (`fixed` default or `group`), `box_count` (integer >=1, default 1; dev/HA-sold region >=2), `group_subnet_ids` (>=2 AZs, public routing), `group_config` (deployment, region_code, placement, AWS/data/deployment-bucket regions, explicit pools set, config-KMS/bootstrap key names), and explicit ingress allocation map. Existing fixed subnet pairing remains; group mode instead requires VPC plus group subnets and forbids fixed `subnet_id`, relay and console-only provisioning settings. Caller must explicitly choose count/addresses; no silent default-VPC discovery for group placement. Existing fixed outputs keep their meaning; group `instance_id` is null, group outputs are additive. Refuse callers requiring a single instance in group mode. |
| -- [ ] **Step 1 — failing mock tests.** `fixed_state_unchanged` asserts no fixed replacement, unchanged profile/SG/volume and legacy outputs; `invalid_group_inputs` rejects unknown mode, fractional/zero count, one AZ, wrong-VPC subnet, duplicate allocation, relay group and fixed/group input mixture. `nlb_contract` asserts TCP 80/443 passthrough, instance targets, preserve_client_ip=true, cross-zone=true, deregistration_delay=30, HTTP health port 80/path `/.carlos/lb-health`, interval 10, thresholds 2/2, matcher exactly 200. `target_security` asserts NLB SG public 80/443, target 80 only NLB SG, target 443 NLB SG plus public backhaul, VPC-only backhaul rule, no SSH. NLB egress admits the target traffic/health ports; no second IPv6 ingress path is silently enabled. |
| -- [ ] **Step 2 — run locally.** From an owned initialized mock fixture: `tofu test -filter=tests/group_ingress.tftest.hcl` and group tests with `mock_provider "aws"`/`command = plan`. Expected FAIL for missing resources/validation, zero real API requests. Do not run an account-backed tofu plan. |
| -- [ ] **Step 3 — implement adapter resources.** Group ASG: min=max=desired=count, ELB health (includes EC2), grace 60s, no instance_refresh, suspended AZRebalance. Put the launch hook in **initial_lifecycle_hook**, timeout 900s/default ABANDON, so the initial instances cannot race a separately created hook. Launch template pins its version/AMI, IMDSv2/hop1, same encrypted gp3/delete-on-termination root, explicit public IPv4 for cross-region dials. No automatic template rollout. Preserve fixed aws_instance/EIP state using explicit moved blocks if adding count; verify old fixed fixtures at old→new addresses. Do not convert an existing fixed module invocation to group: instantiate a distinct group beside it. Preserve the old EIP owner; importing/transferring it is P6's approved operation, never duplicate ownership. |
| -- [ ] **Step 4 — pass mock tests and format.** Add assertions that ASG initial hook exists on CreateAutoScalingGroup, depends on its IAM policies, and cannot start unprotected. Never solve an IAM/ASG dependency cycle with wildcard group write rights: scope completion to exact account/region/group name ARN pattern (UUID wildcard only), plus deployment/region resource tags. Verify pinned numeric launch-template version, on-demand instances only and no refresh actions. Implement the JSON gate for `tofu show -json <saved-plan>`: refuse ASG min/max/desired decreases, fixed-instance replacement/deletion and protected EIP replacement/deletion. Local before/after fixtures prove these refusals and allow isolated ingress creation/group creation; do not rely on a comment saying “drain first”. P6 can later design a production-retirement exception. For Task 6 cleanup only, accept a reviewed manifest naming this experiment's disposable group/ingress resource addresses and allocation ids; fixture tests reject a fixed box or pre-existing regional EIP in that manifest. The gate has no blanket override. `tofu fmt -check -recursive infra/modules/region-host`; mock/gate tests PASS. |
| +- [ ] **Step 1 — failing mock tests.** `fixed_state_unchanged` asserts no fixed replacement, unchanged profile/SG/volume and legacy outputs; `invalid_group_inputs` rejects unknown mode, fractional/zero count, one AZ, wrong-VPC subnet, duplicate allocation, relay group and fixed/group input mixture. `nlb_contract` asserts TCP 80/443 passthrough, instance targets, preserve_client_ip=true, cross-zone=true, deregistration_delay=30, HTTP health port 80/path `/.carlos/lb-health`, interval 10, thresholds 2/2, matcher exactly 200. `target_security` asserts NLB SG public 80/443, target 80 only NLB SG, target 443 NLB SG plus public backhaul, VPC-only backhaul rule, no SSH. NLB egress admits only target traffic/health ports to VPC CIDRs, never a host-SG reference back to the host's inline NLB-SG rule (no graph cycle). **E1/N1:** target_security narrowing applies only to new group SGs. P3a adds no rule to the fixed SG: its existing public 80/443 already admits NLB traffic (`main.tf:97,103`); never mix standalone rules into its inline set (`main.tf:47`, `variables.tf:144`). No second IPv6 ingress path is silently enabled. |
| +- [ ] **Step 2 — run locally.** From the owned initialized **ingress child** fixture, run `tofu test -filter=tests/group_ingress.tftest.hcl`; from the parent fixture run group tests with `mock_provider "aws"`/`command = plan`. Expected FAIL for missing resources/validation, zero real API requests. Do not run an account-backed tofu plan. |
| +- [ ] **Step 3 — implement adapter resources.** Group ASG: min=max=desired=count, ELB health (includes EC2), grace 60s, no instance_refresh, suspended AZRebalance. T1 maintenance is only the gated transaction above; no generic scale-in exception. Put the launch hook in **initial_lifecycle_hook**, timeout 900s/default ABANDON, so the initial instances cannot race a separately created hook. Launch template pins its version/AMI, IMDSv2/hop1, same encrypted gp3/delete-on-termination root, explicit public IPv4 for cross-region dials. No automatic template rollout. Preserve fixed aws_instance/EIP state using explicit moved blocks if adding count; verify old fixed fixtures at old→new addresses. Do not convert an existing fixed module invocation to group: instantiate a distinct group beside it. Preserve the old EIP owner; importing/transferring it is P6's approved operation, never duplicate ownership. |
| +- [ ] **Step 4 — pass mock tests and format.** Add assertions that ASG initial hook exists on CreateAutoScalingGroup, depends on its IAM policies, and cannot start unprotected. Never solve an IAM/ASG dependency cycle with wildcard group write rights: scope completion to exact account/region/group name ARN pattern (UUID wildcard only), plus deployment/region resource tags. Verify pinned numeric launch-template version, on-demand instances only and no refresh actions. Implement the JSON gate for `tofu show -json <saved-plan>`: refuse ASG min/max/desired decreases; **every** change to any pre-existing fixed `aws_instance` (including user_data, instance_type, profile and volume in-place updates), `aws_security_group.host`/rules and host IAM role/profile/policies/attachments; and protected EIP replacement/deletion. Treat unknown values/change shapes as refusal. Allow exceptions only through a reviewed allow-list naming exact resource address, attribute, before/after values, purpose and approval; a wildcard or whole-resource exemption is invalid. Explicit state-address moves are allowed only with unchanged bytes/attributes. Local before/after fixtures reject update-only user_data/type/SG/policy changes as well as replacement/deletion, and allow isolated ingress/group creation; do not rely on a comment saying “drain first”. P6 can later design a production-retirement exception. For Task 6 cleanup only, accept a reviewed manifest naming this experiment's disposable group/ingress resource addresses and allocation ids; fixture tests reject a fixed box or pre-existing regional EIP in that manifest. The gate has no blanket override. `tofu fmt -check -recursive infra/modules/region-host`; mock/gate tests PASS. |
| - [ ] **Step 5 — commit locally.** Keep this on the P3a implementation branch with Tasks 2–4 and merged-input addendum until the visible-service gate is satisfied. P3b resources land only with its scheduled activation. No push/apply in this planning session. |
| ### Task 2: Desired roles, cached application and authoritative publication [own review: authority/cache] |
| -**Files:** boxroles, changeindex, host group_admission/edgesfile and tests. No console writer yet. |
| +**Files:** boxroles, changeindex, host group_admission/edgesfile and tests. No console writer yet. **R1/H4:** P1b-3a is editing the same publication/decoder files. Wait for its build to merge before implementing shared schema/election edits, rebase the slice and re-read its actual decoder; use the integration outline for its placement projection. This adds no outside P3a runtime producer beyond the consumer start-ack, but prevents parallel competing schemas. |
| -**Interfaces:** boxroles.Read does exactly two point GETs (own and regional default), no LIST. Missing own falls back to default; missing both is Serve. Validate roles strictly with a 4,096-byte body cap; unknown fields/types/oversized objects or store errors return error, never Serve. A box reference is a valid DNS label, <=63 bytes; regional code is a nonempty deployment-configured label, <=32 bytes; slashes/path syntax are refused. Distinguish absent from unreadable. Keys are `control/box-roles/<ref>.json` and `control/box-roles/@region-<code>.json`. Supply explicit canonical region_code in root-owned launch configuration (including P3a fixed boxes), matching the console's HomeRegion for the home region; retain the existing raw placement scope, including empty home placement, for record reconciliation. Do not infer a code from the AWS region or rewrite home records. Role reads come once at start, then only when the existing change-index scope moves. Failed reads retry on the next existing reconcile opportunity with backoff, not a new timer. |
| +**Interfaces:** boxroles.Read does exactly two point GETs (own and regional default), no LIST. Missing own falls back to default; missing both is Serve. Validate roles strictly with a 4,096-byte body cap; unknown fields/types/oversized objects or store errors return error, never Serve. A box reference is a valid DNS label, <=63 bytes; regional code is a nonempty deployment-configured label, <=32 bytes; slashes/path syntax are refused. Distinguish absent from unreadable. Keys are `control/box-roles/<ref>.json` and `control/box-roles/@region-<code>.json`. Supply explicit canonical region_code in root-owned launch configuration (including P3a fixed boxes), matching the console's HomeRegion for the home region; retain the existing raw placement scope, including empty home placement, for record reconciliation. Do not infer a code from the AWS region or rewrite home records. **R1/B1:** require `CARLOS_CHANGE_INDEX=read` in group and opted-in fixed settings and add it to hostenv OptionalKeys. Configuration intent is insufficient: the actual armed watch must exist (`internal/host/changeindex.go:31,50,84`). With a disarmed/nil watch, reject P3 admission before any role loop starts; non-P3 fixed boxes have no P3 reader. Do not fall back to every-pass role polling. Use one existing `release.ReadGate` with `ChangeIndexBackstop=30m` (`internal/release/changewatch.go:17,161,197,211,234`), evaluated on the existing reconcile cadence: startup, changed **Observed** scope generation or age expiry makes two GETs due. Capture generation before the read, Mark only after both reads and application succeed; never consume another reader's advisory Poll moved list as the gate. This catches a saved role whose index bump was lost. A transient unusable watch leaves restrictions applied and attempts bounded due reads on existing opportunities with backoff 5/10/20/40/60s (then >=60s); no new timer, no health coupling, and index events do not bypass the failure backoff. Each attempt costs at most 2G, <=128G/hour during sustained failure (including the initial short-backoff burst); quiet backstop adds 2G/30m = 4G/box/hour, apart from startup/events. The backstop runs at the next existing opportunity, not a new poll. |
| -- [ ] **Step 1 — failing tests.** `TestRolePrecedence` (own serve can override default drain; absent own+default platform→platform; absent both→serve); `TestRoleUnreadableIsClosed` (first read fails/invalid→booting, previously restrictive role never relaxes); `TestRoleKeys` (path separators, empty/unknown region and ref rejected); `TestRoleScopeBudget` (new scope, unchanged pass 0G, observed change exactly 2G, partial errors charged); `TestRolePublisherAck` (failed/unchanged edges write cannot impersonate first success); `TestRoleFieldsAreNotHostRoles` (per-host `role:home` untouched). |
| +- [ ] **Step 1 — failing tests.** `TestRolePrecedence` (own serve can override default drain; absent own+default platform→platform; absent both→serve); `TestRoleUnreadableIsClosed` (first read fails/invalid→booting, previously restrictive role never relaxes); `TestRoleKeys` (path separators, empty/unknown region and ref rejected); `TestRoleScopeBudget` (new scope, unchanged pass before backstop 0G, observed change exactly 2G, partial errors charged); `TestRolePublisherAck` (failed/unchanged edges write cannot impersonate first success); `TestRoleFieldsAreNotHostRoles` (per-host `role:home` untouched); `TestRoleReadGateBackstop` (lost bump, another consumer took moved list, change during GET, 30m due); `TestRoleDisarmed` (unset/misspelled flag or failed arm refuses group/opted-in fixed admission with zero polling); `TestRoleBackoffBudget` counts partial errors and recovery. |
| - [ ] **Step 2 — run** `nice -n 19 go test ./internal/boxroles ./internal/release ./internal/host -run 'TestRole' -count=1`. Expected FAIL before implementation. |
| -- [ ] **Step 3 — implement.** Add `control/box-roles` scope to ChangeScope. Publish new top-level `box_role` (`booting|serve|drain|platform`), `admitted` boolean and `drained` boolean, additive with omission preserving old readers. `box_role` avoids collision with per-host role. Desired role is separate from effective role; until startup admission completes publish booting/admitted:false/drained:false. Role change forces one existing edges publication, not a second writer. Cache success only after both own/default reads complete. Keep last applied restriction on transient error; close new-wake permission while role is unknown. Platform adopts tenant records for console reads but cannot start a tenant and is never registered as a target. Group boxes may not execute platform/Unit records; refuse an unexpected such executable before launch, with a readiness blocker rather than silently dropping a production row. |
| -- [ ] **Step 4 — verify** Step 2 PASS, existing edges wire readers still decode fields and malformed safety additions fail closed in the new projection only. `view` for diagnosing an actual holder stays separate from `serving`: drain holders can still answer while being slept; no change to main's deliberate holder-view age policy. New serving projection must require <=15m generation, <=1m future, compatible region/placement/bucket/key and admitted serve; integration waits for merged placement. |
| +- [ ] **Step 3 — implement.** Add `control/box-roles` scope to ChangeScope. Only opted-in P3 boxes publish new top-level `box_role` (`booting|serve|drain|platform`), `admitted` boolean and `drained` boolean. Fixed boxes without the Task 3 switch omit **all three**, including false booleans; old-file absence preserves legacy behavior, explicit false fails closed in new readers. `box_role` avoids collision with per-host role. Desired role is separate from effective role; until startup admission completes publish booting/admitted:false/drained:false. Role change forces one existing edges publication, not a second writer. Cache success only after both own/default reads complete. Keep last applied restriction on transient error; close new-wake permission while role is unknown. Platform adopts tenant records for console reads but cannot start a tenant and is never registered as a target, subject only to the stated P3a dev-console serving exception (sophie remains serve during it). Group boxes may not execute platform/Unit records; refuse an unexpected such executable before launch, with a readiness blocker rather than silently dropping a production row. |
| +- [ ] **Step 4 — verify A1/H4** before any election, exclude explicit not-admitted/booting/drain/platform files in a shared home-eligibility projection used by `internal/edge/homemap.go:781,944` and `internal/edgesfile/homeelect.go:163` (console dial/status consumer). Audit every parser of the additive fields, not just Load callers; omitted legacy fields retain old behavior. Booting publications include identity/role but **no home/alias rows**; admission publication adds them only after State admits. Keep drain rows for holder validation/diagnostics, but they cannot win a new home choice. Fixtures put a never-admitted `g-` file first in sort order and give it the newest claim: an admitted peer still wins; without any eligible peer, return no home rather than pick the closed gate. Holders/held-service remain a separate view, unchanged. Step 2 PASS; existing edges wire readers still decode fields and malformed safety additions fail closed in the new projection only. `view` for diagnosing an actual holder stays separate from `serving`: drain holders can still answer while being slept; no change to main's deliberate holder-view age policy. New serving projection must require <=15m generation, <=1m future, compatible region/placement/bucket/key and admitted serve; integration waits for merged placement. |
| - [ ] **Step 5 — commit.** Role writes, successful drain answers and console display are not claimed. Main-only tests use injected operator records; live desired-role operations wait for the proper console door in the outline. |
| ### Task 3: Serving latch, local start gate and launch completion [own review: security/termination] |
| **Files:** groupadmission core, AWS adapter, host wiring/agent/edges, edge health; modify `internal/activator/{activator.go,hawake.go}` for the shared start gate, with tests in those packages and `internal/host/group_admission_test.go`. |
| -**Interfaces:** add `Service.TenantStartAllowed func() bool` and the corresponding backend admission callback at the existing acquire boundary. Add edge-side `type HAAdmission interface { TenantAdmitted() bool }`, implemented by the same Service; at the existing front decision, check it before exclusions/ForwardTarget or other per-request work for a tenant route, including verified hops. Nil preserves non-P3 fixed behavior. Group configuration always installs the closed gate, even when CARLOS_REGION_HA is absent/false, and then refuses that invalid configuration; a group cannot disable admission by losing the capability flag. The admitted check refuses startup/shutdown; the start callback additionally prohibits drain/platform starts. In P3 mode the same State/effective-role decision feeds the callbacks; check under existing per-host serialization before acquire and again before launch, including lease-retaining respawn paths. Place the start check after the already-owned awake-entry reuse branch, so a drain can continue serving a held instance until its paced stop. This is a local start prohibition, not a second lease algorithm. Already-awake held service may continue during drain; a process closed for shutdown cannot restart it. The incoming departure-consumer-start acknowledgment is **not implemented or guessed here**; until the outline's real wiring exists that fact is false. |
| +**Interfaces:** add `Service.TenantStartAllowed func() bool` and the corresponding backend admission callback at the existing acquire boundary. Add edge-side `type HAAdmission interface { TenantAdmitted() bool }`, implemented by the same Service; at shared tenant dispatch, check it before front-path exclusions/ForwardTarget or other per-request work for a tenant route, including verified hops, authenticated door calls and tunnel deliveries (frontForwardHA alone skips these at `forwardha.go:148`). **I4/R1/S1:** fixed admission is enabled only by the exact root-owned `CARLOS_GROUP_ADMISSION=1` switch (add it to hostenv OptionalKeys); absent/0 means no admission callback/State, no P3 role reader and no P3 publication fields. Pin `TestAdmissionFixedOptIn` and `TestAdmissionFlagshipUnchanged`: the switch-off fixed box retains HTTP/door/tunnel/worker/timer behavior, edges bytes and restart behavior even with CARLOS_REGION_HA set or absent. Group configuration is identified from its immutable root-owned marker and always installs the closed gate, even when either admission or CARLOS_REGION_HA flag is absent/false, then refuses that invalid configuration; a group cannot disable admission by losing the capability flag. The admitted check refuses startup/shutdown; the start callback additionally prohibits drain/platform starts. In P3 mode the same State/effective-role decision feeds the callbacks; check under existing per-host serialization before acquire and again before launch, including lease-retaining respawn paths. Place the start check after the already-owned awake-entry reuse branch, so a drain can continue serving a held instance until its paced stop. This is a local start prohibition, not a second lease algorithm. Already-awake held service may continue during drain; a process closed for shutdown cannot restart it. The incoming departure-consumer-start acknowledgment is **not implemented or guessed here**; until the outline's real wiring exists that fact is false. |
| - [ ] **Step 1 — failing state tests.** `TestAdmissionFacts` independently withholds env, complete first regional instance+sidecar reconcile, acknowledged initial role publication and termination consumer started: no completion/admission. With all four facts and each of six lbhealth conditions, readiness succeeds. `TestAdmissionCloudAck` pins complete-before-admitted-before-publish-serve ordering; failed/late/cancelled completion does not admit. `TestAdmissionSingleFlight` gives twenty concurrent startup callbacks one completion operation, one receipt and one admitted publication; repeated successful callbacks cost zero calls. `TestAdmissionCloseWins` races completion with Close: no reopen. `TestDrainHealth` keeps admitted drain healthy for forwarding while prohibiting starts; platform excluded from targets. Health does no store/API call. |
| - [ ] **Step 2 — run** `nice -n 19 go test ./internal/groupadmission ./internal/awsregiongroup ./internal/host ./internal/activator ./internal/edge -run 'TestAdmission|TestDrainHealth|TestPreAdmission' -count=1`; expected FAIL. |
| -- [ ] **Step 3 — implement state and adapter.** Set the hosting latch from the four successful local facts. Evaluate the full six-condition readiness in memory; do not wait for public NLB health to complete the hook (that would be circular). Group CompleteLifecycleAction sends CONTINUE with configured own group/hook and verified own iid. Fixed boxes skip the cloud action only, after the same full readiness. External LB health answers 200 only once admitted and six conditions hold. This extra admission gate prevents an ambiguous cloud success from leaving a permanently healthy booting target. Every pre-admission tenant refusal is 503 with existing retry text and **no holder identity**; a signed hop cannot bypass it. Publish booting before hook completion, then admitted effective role; never advertise serve first. |
| -- [ ] **Step 4 — pin crash behavior.** A successful hook acknowledgment is durably recorded in an agent-owned admission receipt, outside tenant trees, with account/region/iid/group/hook/config digest. The host's Completer wrapper persists that receipt before returning success to State.Admit, then rechecks health/closure; an AWS adapter success alone cannot open the local gate. Root never reads or executes this receipt. A same-instance process restart rechecks all local startup facts/health before re-admission; the receipt avoids completing a nonexistent hook again. A replacement iid or changed group/hook cannot reuse it. Absent/bad receipt plus “no active hook” is **not success**: remain closed and unhealthy for replacement/operator diagnosis. A response lost after AWS accepted CONTINUE remains unknown; do at most four total completion attempts, 2s each, backoffs 1/2/4s, then close health and let replacement/alarms handle it. No DescribeAutoScalingInstances polling, heartbeat extension or extra write privilege. Refuse on receipt-persistence failure even after cloud success. Test crash before ack, ack-before-receipt, receipt-before-publication, restart, corrupt receipt and close during retry. |
| -- [ ] **Step 5 — real production-path witnesses.** `TestPreAdmissionDirectAndHop` sends direct HTTP, verified forward and direct-public backhaul at an actual wired activator; assert **0 acquires, starts, restores, key mints, holder headers**. `TestPreAdmissionNonHTTP` drives schedule, standalone worker, co-spawn, respawn/session/run and first reconcile launch paths; no bypass. `TestAdmissionShutdownOrder` proves Close/SetHosting(false) precede edge shutdown, consumer cancellation and child stopping. `TestAdmissionAllUnhealthyNLB` sends traffic despite 503 health; still zero tenant starts. `TestAdmissionPublishedRole` observes actual store bytes and publication acknowledgment, not just a state fixture. P3a requires these real wiring witnesses after the merged consumer adapter is added. |
| -- [ ] **Step 6 — pass and commit.** Step 2 commands and existing targeted HA acquire/lease-loss witnesses PASS. Add build-time source-import assertion: new core directories import neither AWS nor the AWS adapter. Retain existing termfence/boxid adapters; do not refactor their whole API in this task. Keep the slice on branch until real termination-start input exists; no unused latch landing. |
| +- [ ] **Step 3 — implement state and adapter.** Set the hosting latch from the four successful local facts. Evaluate the full six-condition readiness in memory; do not wait for public NLB health to complete the hook (that would be circular). Group CompleteLifecycleAction sends CONTINUE with configured own group/hook and verified own iid. Fixed boxes skip the cloud action only, after the same full readiness. External LB health answers 200 only once admitted and six conditions hold. This extra admission gate prevents an ambiguous cloud success from leaving a permanently healthy booting target. Every pre-admission tenant refusal is 503/Retry-After and **no holder identity**; copy review must approve neutral startup wording (never reuse “waking elsewhere”, which falsely names a remote situation); a signed hop cannot bypass it. Publish booting before hook completion, then admitted effective role; never advertise serve first. |
| +- [ ] **Step 4 — pin crash behavior.** A successful hook acknowledgment is durably recorded in an agent-owned admission receipt, outside tenant trees, with account/region/iid/group/hook/config digest. The host's Completer wrapper persists that receipt before returning success to State.Admit, then rechecks health/closure; an AWS adapter success alone cannot open the local gate. Root never reads or executes this receipt. **T1/I4:** a same-instance managed restart is allowed only within the central maintenance transaction above; fixed boxes have no ASG. It rechecks all local startup facts/health before re-admission; the receipt avoids completing a nonexistent hook again. For an admitted member, receipt/config/SSM/S3 failure retains Standby for operator recovery, never hook ABANDON or forced replacement. A configuration change during an approved roll needs the operator to validate/rebind the original completed-launch receipt to the same iid/group/hook; never reuse it for another iid or fabricate a new launch acknowledgment. A replacement iid or changed group/hook cannot reuse it. Absent/bad receipt plus “no active hook” is **not success**: remain closed; first boot can time out/ABANDON, but admitted maintenance stays in Standby for diagnosis. A response lost after AWS accepted CONTINUE remains unknown; do at most four total completion attempts, 2s each, backoffs 1/2/4s, then close health and let first-boot timeout/alarms handle it. Never run launch completion on the Standby restart path. No DescribeAutoScalingInstances polling, heartbeat extension or extra write privilege. Refuse on receipt-persistence failure even after cloud success. Test crash before ack, ack-before-receipt, receipt-before-publication, restart, corrupt receipt and close during retry. |
| +- [ ] **Step 5 — real production-path witnesses.** `TestPreAdmissionDirectAndHop` sends direct HTTP, verified forward, direct-public backhaul, authenticated door calls and tunnel deliveries at an actual wired activator; assert **0 acquires, starts, restores, key mints, holder headers**. `TestPreAdmissionNonHTTP` drives schedule, standalone worker, co-spawn, respawn/session/run and first reconcile launch paths; no bypass. `TestAdmissionShutdownOrder` proves Close/SetHosting(false) precede edge shutdown, consumer cancellation and child stopping. `TestAdmissionAllUnhealthyNLB` sends traffic despite 503 health; still zero tenant starts. `TestAdmissionPublishedRole` observes actual store bytes and publication acknowledgment, not just a state fixture. P3a requires these real wiring witnesses after the merged consumer adapter is added. |
| +- [ ] **Step 6 — T1 guard tests, pass and commit.** `TestGroupMaintenanceRestartGuard` drives actual apply/rollback/recovery/quiesce branches with missing/forged/reused/wrong-iid permit and proves zero stops/repoints; group unit repair cannot re-enable unattended update or Restart=always. `TestGroupSharedDependencyHealth` keeps an already-admitted process healthy through failed role/reconcile/edges/SSM reads, with zero process exits and no cleared startup acknowledgments. Fake-provider transaction tests prove the minimum/desired order, no replacement launch, no ExitStandby on timeouts/shared-read errors, restart closure and same-iid recovery. Step 2 commands and existing targeted HA acquire/lease-loss witnesses PASS. Add build-time source-import assertion: new core directories import neither AWS nor the AWS adapter. Retain existing termfence/boxid adapters; do not refactor their whole API in this task. Keep the slice on branch until real termination-start input exists; no unused latch landing. |
| ### Task 4: Claim-free boot, IAM and local ingress hairpin [own review: root/security] |
| **Files:** hostenv and hairpin files, boot template/group IAM, tests; update module README and `docs/site/cli.md` only after execution-time copy review if existing host-env instructions change. No new public CLI verb is needed for boot/admission. |
| -**Interfaces:** root-owned `/etc/carlos/region-ingress.json` contains version 1 and 1–16 canonical public IPv4 addresses from operator-seeded regional SSM configuration. Hairpin input is a validated data list, not nft/shell text. `group_config` pins deployment bucket region separately from box/data AWS region, canonical region_code and raw record-placement CARLOS_REGION. Runtime reads immutable non-secret launch identifiers from root-written configuration; secret values stay in the protected host.env writer. |
| +**Interfaces (P3b only for boot/hairpin; P3a settings delivery is Task 6):** root-owned `/etc/carlos/region-ingress.json` contains version 1 and 1–16 canonical public IPv4 addresses from operator-seeded regional SSM configuration. Hairpin input is a validated data list, not nft/shell text. `group_config` pins deployment bucket region separately from box/data AWS region, canonical region_code and raw record-placement CARLOS_REGION. Runtime reads immutable non-secret launch identifiers from root-written configuration; secret values stay in the protected host.env writer. |
| -- [ ] **Step 1 — failing tests.** `TestGroupHostEnvNoClaims` removes Required/Optional/SharedKeys entries for every `CARLOS_HOST_CLAIM*`, refuses a seed containing enabled claim settings, permits no claim entry in rendered group env. `TestGroupHostEnvRegions` accepts allowlisted AWS_REGION for the deployment bucket, while data and CloudWatch/SSM regions remain the box's own; private key is never printed. `TestGroupHostEnvPools` admits explicit operator-seeded CARLOS_POOLS through provision.ParseBoxPools (`internal/host/agent.go:3542`), keeps it regional, cross-checks immutable launch scope and refuses missing/mismatched scope instead of defaulting the dev group to @shared. `TestGroupBootOrder` asserts hardening before tenant execution/credentials exposure, no binary exec before trusted SHA, env before bootstrap/install-channel, hairpin before tenant starts, fail-fast each step, no join/enroll/guard-arm. `TestGroupInstallFloor` pins both objects absent, only floor present, only authorization present, errors on either read, invalid signature, too-old image, valid floor and no-floor signed pointer/artifact mismatch. `TestGroupIAM` asserts the rights/refusals below. `TestHairpinRules` rejects empty/malformed/non-public/IPv6/nonliteral/duplicate-limit overflow inputs; only configured IPv4 destinations and TCP ports 80/443 redirect, no broad catch-all or DNS resolver loop. |
| +- [ ] **Step 1 — failing tests.** `TestGroupHostEnvNoClaims` uses a group-specific Required/Optional/SharedKeys selection that excludes every `CARLOS_HOST_CLAIM*`; the test also refuses a seed containing enabled claim settings and permits no claim entry in rendered group env. Preserve non-group selection for fixed deployments. `TestGroupHostEnvRegions` accepts allowlisted AWS_REGION for the deployment bucket, while data and CloudWatch/SSM regions remain the box's own; private key is never printed. `TestGroupHostEnvPools` admits explicit operator-seeded CARLOS_POOLS through provision.ParseBoxPools (`internal/host/agent.go:3542`), keeps it regional, cross-checks immutable launch scope and refuses missing/mismatched scope instead of defaulting the dev group to @shared. `TestGroupBootOrder` asserts hardening before tenant execution/credentials exposure, no binary exec before trusted SHA, env before bootstrap/install-channel, hairpin before tenant starts, fail-fast each step, no join/enroll/guard-arm. `TestGroupInstallFloor` pins both objects absent, only floor present, only authorization present, errors on either read, invalid signature, too-old image, valid floor and no-floor signed pointer/artifact mismatch. `TestGroupIAM` asserts the rights/refusals below. `TestHairpinRules` rejects empty/malformed/non-public/IPv6/nonliteral/duplicate-limit overflow inputs; only configured IPv4 destinations and TCP ports 80/443 redirect, no broad catch-all or DNS resolver loop. |
| - [ ] **Step 2 — run** `nice -n 19 go test ./internal/hostenv ./internal/hairpin ./internal/host -run 'TestGroupHostEnv|TestGroupBootOrder|TestGroupInstallFloor|TestHairpinRules' -count=1`, then `tofu test -filter=tests/group_iam.tftest.hcl` in the mock fixture; expected FAIL. Use scratch binaries/data below `$TMPDIR` or `~/.cache/region-ha-p3`; default GOCACHE. |
| - [ ] **Step 3 — implement boot and the floor absence rail (I1/N1).** Install nftables/chrony and a minimal service user; gate IMDSv4 and IMDSv6 to root/agent, before any tenant can run. Fetch bootstrap object and expected SHA-256 from operator-protected SSM, compare before exec. Use pinned bootstrap object/version plus digest, not mutable “latest”; keep root-signed channel verification. Add a claim-free group install-floor observation in installchannel.go: `type groupInstallFloor struct { Published bool; Identity []byte; Tag string }`; `func (in channelInstall) checkGroupInstallFloor(ctx context.Context, p *release.SystemPointer, art release.SystemArtifact, pub ed25519.PublicKey) (groupInstallFloor,error)`. Read **both** existing floor keys once. Only two genuine not-found answers mean unpublished; one absent, either error, malformed/signature failure or an incompatible published floor refuses. With a floor, read/verify the signed release identity and preserve CheckImage. With neither, verify the signed system pointer/artifact as today, and omit the claim identity/guard bookkeeping that requires a published floor; never fabricate an empty identity or arm a guard. Keep the existing claims-on/--policy path strict and unchanged. Refuse if local guard participation exists or its state is unreadable; a group marker is no bypass of an enforced floor. Run `carlos system host-env write --deployment <name> --region <code> --aws-region <box-region>`, `carlos bootstrap`, then `carlos system install-channel` with validated host.env variables loaded through the existing environment parser/systemd EnvironmentFile (not shell source), install/read back hairpin, then start agent. Include allowlisted AWS_REGION=<deployment-bucket-region>, distinct from data/SSM/metrics region. Require nested layout and run `TestBootstrapAppliesTmpfilesBeforeArming` and `TestReconcileMintsNestedUnderANestedIntent`; no chmod/chown repair after start. Bound each fetch and entire boot below 900s; timeout 15m changes only from measured dev boot plus margin in a reviewed change. Root scratch is disk-backed and removed on exit. No secrets in user-data, command arguments, shell tracing or logs. |
| -- [ ] **Step 4 — implement IAM.** Box SSM GetParameter/GetParameters/GetParametersByPath only under `/carlos/<deployment>/<region>/*` and `/carlos/<deployment>/shared/*`; explicit NotResource Deny matches **both** allowed prefixes and preserves release-key/ancestor denies. No broad `/carlos/*` group allowance. Store bootstrap key/hash and ingress data under the regional **nested** `boot/` path, excluded from hostenv's non-recursive direct-parameter enumeration; never make the hostenv parser accept arbitrary bootstrap keys as environment names. Configuration KMS Decrypt is key-specific, `kms:ViaService=ssm.<region>.amazonaws.com` plus `kms:EncryptionContext:PARAMETER_ARN` restricted to those parameter ARNs. Separate explicit HA DescribeInstances statement with own requested-region condition (resource `*` is AWS's Describe boundary); remove the group-mode duplicate from the broad inventory Allow so that the new condition actually bounds it. Preserve the fixed console's inventory rights. No EC2 writes. CompleteLifecycleAction only own group ARN/name/tags; no RegisterTargets, SetInstanceHealth, TerminateInstances, StartInstanceRefresh or other ASG writes. Keep existing queue read/delete/attributes grants and anti-forgery policy. Explicit group-role Deny for Put/Delete/tagging of `control/box-roles/*` closes the inherited deployment-bucket write route; only the trusted console role can write desired roles. Operator seed rights are PutParameter plus configuration-key Encrypt/GenerateDataKey/Decrypt as required by SecureString tier, distinct from box rights. Fixed platform-console IAM is not accidentally denied its role-writing authority. New metrics permit only named Carlos namespaces; console gains no new infrastructure write rights. |
| -- [ ] **Step 5 — implement hairpin.** Atomically replace only the owned nft table; never flush the system ruleset. Root output destination-NAT/redirect catches root, agent and host-network tenants; apply the equivalent destination rewrite on the actual tenant-network ingress/prerouting path for namespace/bridge/rootfs callers. Use local edge 80/443 and normal routing, preserving Host/SNI. Root persists/reloads rules before agent/tenant units on reboot. Updates require explicit reseed/restart; addresses are EIPs, so no periodic DNS/SSM refresh. Confirm cgroup egress policy evaluates the intended destination: a tenant disallowed the ingress address stays denied, rather than gaining loopback through NAT. Refuse network layouts for which that kernel proof fails; do not widen IPAddressAllow or loopback to make the drill pass. |
| -- [ ] **Step 6 — kernel/authority witnesses, then commit.** Run `TestHairpinKernelAgentTenantSidecar` on the designated Linux root runner: each configured zone EIP, GET/POST and TLS/WebSocket, with agent, a real nested tenant, standalone sidecar and supported rootfs namespace. Prove IMDSv4/v6 still denied to tenant/sidecar, unrelated IP/port unchanged, an egress-denied ingress address still denied, no rewrite loop, restart persistence and rollback of just the owned table. Local privilege skip is not acceptance. Wrong checksum, failed SSM page, wrong KMS context, forged config/receipt paths and disabled nft/chrony leave admission closed. Mock policy denial tests cover another region/group/key and direct role-object write. Pass targeted tests; commit with census claims, no apply. |
| +- [ ] **Step 4 — implement IAM.** **IAM/A1:** define `regional = arn:<partition>:ssm:<aws-region>:<account>:parameter/carlos/<deployment>/<region>` and `shared = arn:<partition>:ssm:<aws-region>:<account>:parameter/carlos/<deployment>/shared`. The Allow resource set and explicit NotResource-Deny exceptions are exactly **[regional, regional + "/*", shared, shared + "/*"]** for SSM parameter reads (preserve GetParameterHistory denial scope and release-key/ancestor denies). Exact paths authorize GetParametersByPath (`internal/hostenv/awsssm.go:62`); descendants authorize individual parameters. Never use `<region>*` or `shared*`. `group_iam.tftest.hcl` decodes the final policy JSON and asserts set equality in **both** statements, tests by-path on each exact path and individual boot keys, and rejects sibling `ie2`, deployment/region ancestors, other account/region and release-key reads. A mock success alone does not establish live IAM authorization; Task 6 must read both exact paths as the built box role before its first launch is accepted. No broad `/carlos/*` group allowance. Store bootstrap key/hash and ingress data under the regional **nested** `boot/` path, excluded from hostenv's non-recursive direct-parameter enumeration; never make the hostenv parser accept arbitrary bootstrap keys as environment names. Configuration KMS Decrypt is key-specific, `kms:ViaService=ssm.<aws-region>.amazonaws.com` plus `kms:EncryptionContext:PARAMETER_ARN` restricted to those parameter ARNs. Separate explicit HA DescribeInstances statement with own requested-region condition (resource `*` is AWS's Describe boundary); remove the group-mode duplicate from the broad inventory Allow so that the new condition actually bounds it. Preserve the fixed console's inventory rights. **IAM least privilege / #478:** group mode drops inherited whole-data-bucket `s3:DeleteObjectVersion` and `s3:ListBucketVersions` (`main.tf:181–197`). Audit merged callers first; if an active claim-free consumer requires them, give object actions only its exact demonstrated prefix and ListBucketVersions only its bucket with `s3:prefix` conditions covering that prefix, backed by positive consumer tests. Otherwise grant none. Do not retain `data-bucket/*` version delete or an unconditioned bucket version LIST. Mock final-policy assertions inspect all statements/attachments, prove claim/version-root and unrelated prefixes denied, and preserve fixed mode's existing policy. No EC2 writes. CompleteLifecycleAction only own group ARN/name/tags; no RegisterTargets, SetInstanceHealth, TerminateInstances, StartInstanceRefresh or other ASG writes. Keep existing queue read/delete/attributes grants and anti-forgery policy. Explicit group-role Deny for Put/Delete/tagging of `control/box-roles/*` closes the inherited deployment-bucket write route; only the trusted console role can write desired roles. Operator seed rights are PutParameter plus configuration-key Encrypt/GenerateDataKey/Decrypt as required by SecureString tier, distinct from box rights. Fixed platform-console IAM is not accidentally denied its role-writing authority. The box role gets no maintenance ASG writes; the approved operator role alone gets scoped UpdateAutoScalingGroup/EnterStandby/ExitStandby for the exact group. New metrics permit only named Carlos namespaces; console gains no new infrastructure write rights. |
| +- [ ] **Step 5 — implement hairpin.** Atomically replace only the owned nft table; never flush the system ruleset. Root output destination-NAT/redirect catches root, agent and host-network tenants; include any dedicated local listener wiring in the host/edge file map and census card; apply the equivalent destination rewrite on the actual tenant-network ingress/prerouting path for namespace/bridge/rootfs callers. **N1 client trust:** preserve Host/SNI and make the edge present the verified public box address for a hairpinned request (same value the ordinary public-EIP path presents), never loopback/private/bridge/namespace source. Reuse the existing address provider, validate with the `usableDoorAddr` property (`internal/edge/door.go:138`) and bind normalization exclusively to a dedicated kernel-delivered hairpin listener/path identified by root-owned rules; never trust X-Forwarded-For or a request flag as proof of hairpin. No public/ordinary ingress can opt into this path. If that authenticated local-path distinction or public address is unavailable, **refuse the connection before tenant dispatch**; do not silently substitute a private address. The concrete redirect/listener implementation must pass the kernel witness before P3b activation; do not ship a permissive fallback. Root persists/reloads rules before agent/tenant units on reboot. Updates require explicit reseed/restart; addresses are EIPs, so no periodic DNS/SSM refresh. Confirm cgroup egress policy evaluates the intended destination: a tenant disallowed the ingress address stays denied, rather than gaining loopback through NAT. Refuse network layouts for which that kernel proof fails; do not widen IPAddressAllow or loopback to make the drill pass. |
| +- [ ] **Step 6 — kernel/authority witnesses, then commit.** Run `TestHairpinKernelAgentTenantSidecar` on the designated Linux root runner: each configured zone EIP, GET/POST and TLS/WebSocket, with agent, a real nested tenant, standalone sidecar and supported rootfs namespace. Assert the tenant-observed RemoteAddr and derived forwarding/client headers equal the box's public IPv4 for each caller/TLS/WebSocket, including spoofed forwarded headers; private/missing public identity and forged hairpin-path attempts are refused. Prove IMDSv4/v6 still denied to tenant/sidecar, unrelated IP/port unchanged, an egress-denied ingress address still denied, no rewrite loop, restart persistence and rollback of just the owned table. Local privilege skip is not acceptance. Wrong checksum, failed SSM page, wrong KMS context, forged config/receipt paths and disabled nft/chrony leave admission closed. Mock policy denial tests cover another region/group/key and direct role-object write. Pass targeted tests; commit with census claims, no apply. |
| ### Task 5: Alarms with real producers and bounded metrics [own review: infrastructure] |
| @@ -166,7 +212,7 @@ Region-host gains `mode` (`fixed` default or `group`), `box_count` (integer >=1, |
| **Interfaces:** extend the existing once/minute host metrics batch with group dimensions and clock offset, using the same PutMetricData call in the box's actual AWS region. Pure observation type uses time/durations/identifiers, no AWS types. NLB/TG dimensions are ARN suffixes; ASG uses AutoScalingGroupName; EligibleBoxes uses existing Carlos/Region dimensions. Alerts go to a confirmed same-region topic. Do not add a second metrics loop or a periodic S3 health object. |
| -- [ ] **Step 1 — failing mock/adapter tests.** Pin every row below, missing-data behavior, target-group aggregation and metric namespace/region. A deployment with no producer may not silently arm an all-green alarm. Test minimum group memory includes the lowest individual sample, not mean memory; failed/missing clock read is unknown, never zero. |
| +- [ ] **Step 1 — failing mock/adapter tests.** Pin every row below, missing-data behavior, target-group aggregation and metric namespace/region. A deployment with no producer may not silently arm an all-green alarm. Test minimum group memory includes the lowest individual sample, not mean memory; failed/missing clock read is unknown, never zero. **I1:** on that existing metrics cadence run the installed local `chronyc -c tracking` (absolute executable path, fixed args, no shell, 1s timeout, <=4KiB output), parse the signed system-time offset in seconds, require synchronized tracking and emit its absolute value. Pin the installed chrony CSV schema in parser fixtures; missing socket/command, malformed/nonfinite fields, unsynchronized status or timeout is unknown with diagnostics, never a fabricated 0. Root boot/readback verifies chrony; no S3/SSM call or separate clock loop. Command/report reference: [https://chrony-project.org/doc/4.4/chronyc.html](https://chrony-project.org/doc/4.4/chronyc.html); verify the deployed version's CSV format before wiring it. |
| - [ ] **Step 2 — run** group_alarms mock tests and `nice -n 19 go test ./internal/host ./internal/groupadmission ./internal/awsregiongroup -run 'TestGroupMetric|TestGroupAlarm|TestAdmissionMetric' -count=1`; expected FAIL. |
| - [ ] **Step 3 — implement the following alarm contract.** Use 60s standard-resolution periods; no autoscaling/terminate action on S3 failure. Group metrics enabled in ASG without Describe polling. Reuse SNS infrastructure convention in the same region. Initial launch failure events go to SNS through EventBridge; include all launch failures so an abandoned hook is not filtered out by brittle Cause text. Both local hook failure and timeout/launch-event drill evidence are required; do not invent a native “abandoned hooks” CloudWatch metric. AWS service events are best effort, so group-size alarms are the fallback. |
| @@ -209,14 +255,14 @@ The executable addendum must also resolve the held-lease-on-drain request path u |
| **Files:** separate platform-infrastructure dev branches and a drill report in its established deployment notes; implementation branch evidence links it. This task defines the acceptance and approval card, not permission to execute it now. |
| -**Who applies what:** the P3 implementer supplies reviewed platform changes/mock evidence and the merged-input addendum. The deployment owner prepares the private dev-root change and an infrastructure operator runs the account-backed read plan and apply **only after Paul's scoped go**, passing the saved-plan JSON gate before apply. The release operator rolls dev boxes, then dev console and checks versions. Paul authorizes the destructive dev drill and its complete cleanup once; no repeated go per API call within that exact scope. Production G3 gets a different account/domain/change card. This plan authorizes none of those live calls. |
| +**Who applies what:** the P3 implementer supplies reviewed platform changes/mock evidence and the merged-input addendum. The deployment owner prepares the private dev-root change and an infrastructure operator runs the account-backed read plan and apply **only after Paul's scoped go**, passing the saved-plan JSON gate before apply. **E1/S1:** before the later P3a implementation merge, read-plan the **entire dev root** against its proposed module revision (read-only, approved credentials), inspect JSON for ie/ie-b/uk/standby-ie drift and record exact source SHAs; the fixed roots track `?ref=main`, so checking only ingress is insufficient. Current main still denies data-bucket `s3:DeleteObject` at `infra/modules/region-host/main.tf:724`; branch `region-host-store-deny` commit `55157510` removes it. Never cherry-pick it here or assume it has merged. Refuse a full dev apply until its reviewed fix is on main, module sources have been refreshed/pinned and a new whole-root plan proves no restoration of the outage. Even after the fix, P3a uses a targeted **saved** plan limited to new ingress module/attachments (include dependencies in JSON review); apply that exact saved plan, not a new unscoped apply. If targeting pulls fixed SG/IAM/instance changes outside the exact allow-list, refuse. No `-target` bypass of the JSON gate. Any intentionally required fixed IAM change is a separate named approved diff, never incidental drift. The release operator rolls dev boxes, then dev console and checks versions. Paul authorizes the destructive dev drill and its complete cleanup once; no repeated go per API call within that exact scope. Production G3 gets a different account/domain/change card. This plan authorizes none of those live calls. |
| -- [ ] **Step 1 — prepare concrete approval card.** Read current deployment config/inventory; record actual account id, eu-west-1 VPC/subnets/AZs, bucket/SSM/KMS/SNS ARNs, two fixed target ids or disposable group ids, canonical region/pool, explicit domains and fresh born-HA host/app/account. List IAM changes, new NLB/SG/two TGs/two EIPs, fixed attachments for P3a, and launch template/ASG/hook/alarms for P3b. Include maximum count, type/volume/cost, public traffic effects, 24h drill expiry, fault permissions (terminate only disposable members; never leo/sophie without separate named go), rollback and cleanup. Verify no duplicate rule/queue ownership. An existing born-HA host is not a migrated legacy host. Schedule and record actual switch-on release date before merge. |
| -- [ ] **Step 2 — P3a visible acceptance.** After merged producer addendum and approval, stage/read-plan private ingress against fixed pair; reject replacements/deletes of fixed boxes, current EIP, buckets or production DNS. Apply new isolated ingress/attachments; roll admission/hairpin before registration. Probe existing born-HA host from outside VPC through **each** NLB zone EIP, curl --resolve with real Host/SNI, GET/POST and WebSocket, version header/body and one accounting owner. Show local health from all six conditions, actual admission and matching buckets/key/pool. Traffic via NLB must serve, not just connect. Record the first visible result in UTC; do not call this G1/G2 or replace the normal ingress yet. |
| +- [ ] **Step 1 — prepare concrete approval card.** Read current deployment config/inventory; record actual account id, eu-west-1 VPC/subnets/AZs, bucket/SSM/KMS/SNS ARNs, two fixed target ids or disposable group ids, canonical region/pool, explicit domains and fresh born-HA host/app/account. List IAM changes, new NLB/SG/two TGs/two EIPs, fixed attachments for P3a, and launch template/ASG/hook/alarms for P3b. Include maximum count, type/volume/cost, public traffic effects, 24h drill expiry, T1 maintenance min/desired/Standby/ExitStandby writes and root permit/recovery owners, fault permissions (terminate only disposable members; never leo/sophie without separate named go), rollback and cleanup. Verify no duplicate rule/queue ownership. An existing born-HA host is not a migrated legacy host. Schedule and record actual switch-on release date before merge. |
| +- [ ] **Step 2 — P3a visible acceptance.** After merged producer addendum and approval, stage/read-plan private ingress against fixed pair; **E1/N1/S1:** use the whole-root read-plan and exact fixed-resource JSON gate above, not just a delete/replace check. The release owner prepares a reviewed private `scripts/configure-p3a-fixed.sh` step in the ordinary fixed roll: atomically merge `CARLOS_GROUP_ADMISSION=1`, `CARLOS_CHANGE_INDEX=read` and validated canonical region `ie` into root-owned `/etc/carlos/host.env` plus a root-owned `/etc/carlos/region-config.json`; keep CARLOS_REGION empty and preserve each box's exact CARLOS_POOLS and unrelated env. Use existing authenticated operator delivery, check owner/mode/no-symlink and config digests before restart. Save old config and signed binary for rollback. **No fixed user_data, IAM, SG or instance-type edit, no group marker and no `/etc/carlos/region-ingress.json` or nft table on leo/sophie.** Hairpin is excluded from P3a. Apply isolated ingress, deliver/roll admission settings one fixed box at a time, verify real arming/admission, then register target attachments. Sophie remains serve despite also running the dev console. If this config delivery or first consumer acknowledgment is unavailable, refuse before registration. Probe existing born-HA host from outside VPC through **each** NLB zone EIP, curl --resolve with real Host/SNI, GET/POST and WebSocket, version header/body and one accounting owner. Show local health from all six conditions, actual admission and matching buckets/key/pool. Traffic via NLB must serve, not just connect. Record the first visible result in UTC; do not call this G1/G2 or replace the normal ingress yet. **Rollback (E1/S1):** on failed acceptance, the infrastructure operator first deregisters/removes only P3a fixed-target attachments via the approved targeted saved plan, verifies both TGs contain no fixed targets and waits 30s drain; normal DNS/EIPs remain owned by the fixed modules. The release owner then restores the saved signed binary and exact old host.env/region config (switch omitted), restarts one fixed box at a time and verifies normal public host/version, console, pools, omission of P3 fields and healthy tenant service. P3a installed no hairpin state to undo. Only after that does the infrastructure owner remove the isolated NLB/listeners/TGs/SG and two **new** EIPs using the protected-resource cleanup procedure below. Failure during rollback halts further changes and alerts the named deployment owner; keep resources/state for diagnosis. The controller records every step; Paul's card names these owners and covers cleanup costs/duration. |
| - [ ] **Step 3 — G1 prerequisite and P3b staging.** Record all P1b/P2 main commits/releases and G1 pair drills, operator/readiness/capacity doors, direct/backhaul forwarding and role application. Only then prepare/apply the dev IE topology above: two zones/count=2, new group references, explicit hapair-only scope and the approved existing bucket. Group-only drills require the approved pair pool withdrawal and proof of no outside-pool placement/import. A different bucket/region is a new reviewed scope, not a fallback invented during apply. Set full console ingress before group publishes; own-region hairpin before workloads. Verify a box launched during regional-default drain remains non-serving, and that platform is outside TGs. Inspect initial hook Pending:Wait, withheld readiness, acknowledged completion, publication and InService/target health, in that order. No admission shortcut for rehearsals. |
| -- [ ] **Step 4 — admission/hang/termination drills.** Withhold each readiness fact, inject failed/ambiguous completion, send direct signed backhaul to booting box; no lease/start. Kill a disposable admitted instance with EC2 termination, measure group detection/replacement, then born-HA restores on survivors. Hang the agent/health path, including immediately after first healthy service reached through direct backhaul; full grace is 60s, not 15m. Record termination confirmation and **lease expiry separately**, never take early under N-HA9. Compare commit sequence in each replication class; stream loss ~1s, others up to configured interval. Restart admitted agent to exercise receipt without re-running a nonexistent hook. A failed boot must reach ABANDON and notify, not accumulate live Pending boxes. |
| -- [ ] **Step 5 — loss, placement, drain and networking.** Black-hole S3 for one disposable box: alarm/operator intervention, no S3-loss auto-replacement; after approved termination recover only at expiry. Concurrent cold wakes through both zone EIPs: one writer. Drain through CLI with full peers: sleep/marker/import evidence, 5s spacing, healthy forwarding; refusal if no peer. On disposable targets rehearse deregistration delay 30s, stop/restart and rollback role/default, plus an EIP mapping transfer using **disposable EIPs only**; P6 owns the exact production retirement rehearsal/runbook. Check outside-VPC public 80/443, preserved client identity, cross-region signed backhaul on public 443 and own-region hairpin from agent/tenant/sidecar, with IMDS/egress denial retained. Do not temporarily close public 443 to NLB-only: its second-hop redesign is outside P3. |
| -- [ ] **Step 6 — evidence, cleanup and gate.** UTC timelines: health/hook/admission/first service, fault/termination/expiry/restore/first200, loss window, alarm notification/recovery and per-event request counts from the built-revision counting tests. Match binary/version to tested behavior. G2 requires all §21 drills and measured §9.8 bounds including N-HA9; an unavailable producer or untested direct-hop hang is a blocker. Restore all network faults; remove disposable hosts, ASG/targets/alarms/SSM objects/EIPs with the approved operator-owned cleanup (protected EIPs require an explicit reviewed unprotect cleanup step). Never delete a shared bucket, identity or another session's files. Keep the accepted dev proving group only if the approval names it as retained; otherwise destroy temporary resources. No watcher/server/scratch outlives this work. Controller reports results on branch/#421 when authorized. G3 awaits separate readiness and production go; seven-day acceptance precedes G4, G5 stays later. |
| +- [ ] **Step 4 — admission/hang/termination drills.** Withhold each readiness fact, inject failed/ambiguous completion, send direct signed backhaul to booting box; no lease/start. Kill a disposable admitted instance with EC2 termination, measure group detection/replacement, then born-HA restores on survivors. Hang the agent/health path, including immediately after first healthy service reached through direct backhaul; full grace is 60s, not 15m. Record termination confirmation and **lease expiry separately**, never take early under N-HA9. Compare commit sequence in each replication class; stream loss ~1s, others up to configured interval. **T1/I4 restart witness:** before any group restart, run the central maintenance transaction. Capture iid/membership/launch and termination activity counts. Roll the platform, attempt unattended self-update (must produce zero stop/repoint), then restart the admitted agent under Standby with both S3 and SSM black-holed. Drive tenant HTTP/door/tunnel/timer paths: zero acquire/start and no holder leak while admission is closed. Hold the outage **over 15 minutes**, beyond the 2×10s thresholds, 60s grace and operator wait; same iid must remain Standby, no termination, no replacement/extra launch, no new lifecycle completion. Lose the operator connection mid-transaction and resume by its durable record; loss cannot auto-exit Standby. Restore dependency access, re-admit with the same receipt and six real conditions, ExitStandby and restore min=desired=max=count; verify same iid serves again. Finally hang an admitted member **outside maintenance** and prove ordinary local-failure replacement still works. Repeat update-rollback/recovery permit checks; no successful shared-read/receipt probe may stand in for ASG state readback. A failed boot must reach ABANDON and notify, not accumulate live Pending boxes. |
| +- [ ] **Step 5 — loss, placement, drain and networking.** Black-hole S3 for one already-admitted disposable box: assert external health stays 200, same iid, zero replacement/termination activity, alarm/operator intervention and no S3-loss auto-replacement; after approved termination recover only at expiry. Concurrent cold wakes through both zone EIPs: one writer. Drain through CLI with full peers: sleep/marker/import evidence, 5s spacing, healthy forwarding; refusal if no peer. On disposable targets rehearse deregistration delay 30s, stop/restart and rollback role/default, plus an EIP mapping transfer using **disposable EIPs only**; P6 owns the exact production retirement rehearsal/runbook. Check outside-VPC public 80/443, preserved client identity, cross-region signed backhaul on public 443 and own-region hairpin from agent/tenant/sidecar, with IMDS/egress denial retained. Do not temporarily close public 443 to NLB-only: its second-hop redesign is outside P3. |
| +- [ ] **Step 6 — evidence, cleanup and gate.** UTC timelines: health/hook/admission/first service, fault/termination/expiry/restore/first200, loss window, alarm notification/recovery and per-event request counts from the built-revision counting tests. Match binary/version to tested behavior. G2 requires all §21 drills and measured §9.8 bounds including N-HA9; an unavailable producer or untested direct-hop hang is a blocker. Restore all network faults; remove disposable hosts, ASG/targets/alarms/SSM objects/EIPs with the approved operator-owned cleanup (for protected **disposable** EIPs the infrastructure owner first makes a reviewed cleanup-only commit to the experiment's pinned ingress-module copy, replacing literal `prevent_destroy = true` with literal `false` only for the named new allocations; no boolean input can toggle this meta-argument. Read-plan and pass the cleanup manifest/JSON gate, then apply the exact saved plan. Never unprotect a pre-existing regional EIP or change the shared module default. Restore/remove that experiment copy after destruction). Never delete a shared bucket, identity or another session's files. Keep the accepted dev proving group only if the approval names it as retained; otherwise destroy temporary resources. No watcher/server/scratch outlives this work. Controller reports results on branch/#421 when authorized. G3 awaits separate readiness and production go; seven-day acceptance precedes G4, G5 stays later. |
| ## Exact request budget |
| @@ -224,8 +270,9 @@ Logical API attempts including unsuccessful requests; SDK retries are transport |
| | Path | P3 increment / bound | |
| |---|---| |
| -| Quiet steady box, health checks, hairpin, lease-start permission | **0 extra S3/SSM/EC2/ASG calls/hour**. Health reads atomics/local clocks only. Existing §18 box baseline remains ~3,300–3,500 S3/h, not a spending allowance. | |
| -| Role initial load / observed role-scope change | Exactly **2G** per affected box attempt, own+default, no L. At startup absent counts as an attempted G. Retry partial failure costs another at most 2G on an existing pass, bounded backoff; no per-request reads. For B boxes reacting to one coalesced role event: <=2B G plus index reads already in their normal poll. | |
| +| Quiet steady box, health checks, hairpin, lease-start permission | **4G/box/hour** from role backstop (2G each 30m), even with a quiet index. Health, hairpin and local lease-start checks add **0** calls; no additional SSM/EC2/ASG runtime calls. Health reads atomics/local clocks only. Existing §18 box baseline remains ~3,300–3,500 S3/h, not a spending allowance. | |
| +| Role initial load / observed role-scope change | Exactly **2G** per affected box attempt, own+default, no L. At startup absent counts as an attempted G. Retry partial failure costs another at most 2G on an existing pass, 5/10/20/40/60s then >=60s backoff (<=128G/h including the initial backoff burst during sustained error); no per-request reads. Capture gate generation before reads and do not Mark failure as success. For B boxes reacting to one coalesced role event: <=2B G plus index reads already in their normal poll. | |
| +| Role backstop / disarmed | Quiet armed role reader: **2G/30m = 4G/box/h**, **4B G/h** fleet-wide (~$0.0000016/box/h at the stated GET price). No-op pass before maxAge costs 0. P3 switch with disarmed watch is a configuration refusal, **0 recurring role reads**. No new polling loop. | |
| | Later console role CAS | P2b owns it: precondition **1G+1P**, then index **kG+kP**, **1<=k<=4 total**, before any explicit verification/read-back. CAS conflict returns; no unconditional overwrite. Unchanged role reads only. See main changeIndexAttempts=4; do not interpret spec shorthand as four extra retries. | |
| | Forced effective-role/admission/drained edges publication | Existing putReplacing does **a(G+P)**, **1<=a<=3**. Every successful object mutation adds index **k(G+P)**, k<=4; conflicts that do not mutate do not bump. Thus successful publication <=**7G+7P** logical calls; failed three object CAS attempts <=3G+3P, no index. Normal success 2G+2P. Receipt and state transitions are local, 0S3. | |
| | Launch phase publications | At most one forced booting and one admitted-role write on successful boot: normally **4G+4P**, bounded **14G+14P** for those two successful publication operations, plus timed/route-change writes already in baseline. Shutdown/drain applied and drained completion each add one such operation when evidence changes, not on every local tick. Failed operations retried later are charged again. | |
| @@ -234,11 +281,12 @@ Logical API attempts including unsuccessful requests; SDK retries are transport |
| | Initial boot artifact / trusted hash | Bootstrap raw GetObject exactly **1G** for named object; SSM GetParameters batch for bootstrap key/hash exactly **1 call** (2 parameters), not S3 HEAD+GET or per-tick fetch. SHA verified before exec. Existing install-channel signed pointer/artifact reads remain charged separately by its real path; record them in boot counting witness rather than claiming they are part of the single bootstrap GET. | |
| | Claim-free install-channel, fresh group box | Successful no-floor install: **4G** = signed system pointer + two absent floor keys + artifact; successful published-floor install: **5G** = pointer + both floor keys + signed release identity + artifact. **0L/0P/0D**. An already-installed same release omits artifact G; failure stops at its attempted reads. Bootstrap artifact above is another 1G, so successful boot binary preparation is **5G without floor / 6G with floor**, before existing reconcile/identity/edges work. Pin actual low-level GetObject/stream calls and prevent a second floor observation in the installer; network retries are additional attempts. No-floor does not imply network errors count as absence. | |
| | host-env / ingress configuration boot reads | Two GetParametersByPath paginator chains, one shared/one regional. Set MaxResults=10: **max(1,ceil(S/10))+max(1,ceil(R/10))** calls for S/R parameters with no empty intermediate pages; actual API pages, including empty pages/tokens, are charged. Bound total configuration to 100 parameters and **20 pages total**; fail if exceeded. Put ingress data in a separately keyed regional parameter: **1 GetParameter** once at boot; no DNS/SSM refresh. KMS decrypt service work <=number of SecureString values returned (including bootstrap/ingress); count retries, never a box KMS write. | |
| -| Launch completion | Normal **1 CompleteLifecycleAction**/new instance; worst **4 total attempts** with SDK retries disabled at that adapter, original 900s launch deadline, no heartbeat/describe. Restart with valid same-identity receipt **0 ASG calls**. Unknown/no receipt+no hook remains closed. | |
| +| Launch completion | Normal **1 CompleteLifecycleAction**/new instance; worst **4 total attempts** with SDK retries disabled at that adapter, original 900s launch deadline, no heartbeat/describe. Restart with valid same-identity receipt **0 box ASG calls**; operator Standby calls are charged separately. Unknown/no receipt+no hook remains closed. | |
| +| Operator maintenance transaction / T1 | Per member normal writes: **1 UpdateAutoScalingGroup(min=N-1), 1 EnterStandby(decrement=true), 1 ExitStandby, 1 UpdateAutoScalingGroup(min=N)**. Operator reads actual group/target state at most every 5s during two <=15m waits (<=180 rounds each, <=360 rounds total per invocation; each round <=1 ASG describe + one target-health read per TG). Then stop/alert/retain Standby; no unattended watcher/retry or timeout replacement. Resume is a separately counted invocation under the same transaction. **0 new box IAM rights or runtime polls**. | |
| | Identity / boot metadata | Reuse existing IMDS signed identity for self, owner and group ref where available; no new timer. Count actual IMDS requests separately in boot witness; no new EC2 list/describe on boot for membership. | |
| | Termination, owned by 3b | One existing queue consumer **~180 ReceiveMessage/h/box** at WaitTimeSeconds=20 when idle; event/redelivery receives and DeleteMessage attempts extra, no ChangeMessageVisibility grant presumed. P3 adds **0 receives**. Confirmer at most **1 DescribeInstances/iid/10s/box** on suspicion, none on healthy request. No new polling. | |
| | Scan/import, owned by 3b | Per attempt with H regional hosts, A matching dead/released hosts, W<=A wake objects: **(H+A+W)G**, no new region LIST if using existing reconciled records. Completion deletion **1D+kG+kP** plus any required ETag refresh G; identity at most 1G/uncached ref. Retry/duplicate attempts each charged. No per-box scan tick. P3 drain completion waits for this merged importer; it creates no second scan. | |
| -| Metrics | Extend existing host **<=60 PutMetricData/h/box**, no additional call per metric; no S3. Emit clock/group dimensions in same batch, actual AWS region. Console EligibleBoxes remains P2b's **<=60 calls/region/h** plus its separately budgeted verified observation reads; do not attribute its workload to P3's zero. EventBridge→SNS notifications are event workload, no polling. | |
| +| Metrics | Extend existing host **<=60 PutMetricData/h/box**, no additional call per metric; no S3. Emit clock/group dimensions in same batch, actual AWS region. Console EligibleBoxes remains P2b's **<=60 calls/region/h** plus its separately budgeted verified observation reads; do not attribute its workload to P3's box-side increment. EventBridge→SNS notifications are event workload, no polling. | |
| | NLB probes / operator verification | Two TGs nominally 360 HTTP checks/target/hour/TG at 10s; AWS consensus can send more, so **720 is not a hard actual-request ceiling**. Each costs 0S3/0AWS API calls in the box. Actual count measured on dev. Operator's bounded DescribeTargetHealth/ASG/alarms reads are drill-only, never installed as a per-box watcher. | |
| | Tofu | State refresh/read-plan/apply API count depends on provider diff, not a runtime polling budget. Deployment approval records the actual operation list/resource diff; no live tofu requests in this drafting session or mock tests. | |
| @@ -261,7 +309,7 @@ Sources: [https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AWSELB/current |
| AWS charges all public IPv4, including the auto-assigned box addresses: **$0.005/h = $3.65/month each**, another **$7.30/month for N=2** group boxes. Gross NLB+all IPv4 is therefore IE/AU **$32.996**, UK **$33.9158**, US **$31.025**. One primary NLB EIP reuses an already-paid regional allocation at eventual cut-over, so incremental EIP charge over today's one-EIP region is $3.65, not $7.30; during dev rehearsal both new EIPs are incremental. IE platform's separate new relay/MX EIP adds $3.65/month at its later cut-over. Each additional AZ adds $3.65/month; each public-addressed box adds $3.65 plus compute/volume. Source: [https://aws.amazon.com/vpc/pricing/](https://aws.amazon.com/vpc/pricing/). |
| -P3a reuses existing fixed compute/addresses; two new NLB EIPs cost the full $7.30/month during rehearsal. P3b disposable compute/volumes require a fresh regional quote on the approval card, **not included in those totals**. A 24h IE NLB + two EIPs + two new box IPv4 costs $1.0848 before traffic/compute/alarms; a retained group incurs the monthly line. Existing SQS estimate ~ $0.05/box/month is §18's estimate, not an additional P3 consumer. Price refresh and the complete dev maximum cost belong on the live card before go. |
| +P3a reuses existing fixed compute/addresses; two new NLB EIPs cost the full $7.30/month during rehearsal. P3b disposable compute/volumes require a fresh regional quote on the approval card, **not included in those totals**. A 24h IE NLB + two EIPs + two new box IPv4 costs $1.0848 before traffic/compute/alarms; a retained group incurs the monthly line. Existing SQS estimate ~ $0.05/box/month is §18's estimate, not an additional P3 consumer. **S1 additional observability allowance:** budget about **$0.30 per custom metric series-month** (every dimension combination is a series), plus roughly **10 standard-resolution alarms × $0.10 = $1/month** before SNS. Enumerate actual group/clock/admission/per-iid series on the card: M new series add about $0.30M/month, with replacement churn increasing the active billed series; no claim that batching eliminates metric charges. Refresh prices and region/tier/time proration, inventory retained versus new alarms and include the full dev maximum before go. These are planning allowances, not a live quote. Source: [https://aws.amazon.com/cloudwatch/pricing/](https://aws.amazon.com/cloudwatch/pricing/). |
| ## Copy deck for execution-time review |
| @@ -270,18 +318,20 @@ This is a requirements inventory for the controller, not approved product wordin |
| | ID | Destination | Required meaning / invariant | |
| |---|---|---| |
| | P3-C1 | Role CLI/API, P2b-owned `system_roles.go`, `internal/console/apiboxroles.go`, CLI docs | New serve/drain/platform vocabulary, ref/default target, operator-only; saving desired role is distinct from applied/drained. Inventory usage, invalid target/role, conflict/unreadable/write failure, audit and saved/applied messages. **R1/S1**. | |
| -| P3-C2 | Existing edge/activator pre-admission refusal | Reuse existing retry body; 503 with no holder identity. Do not expose group/account/iid or imply successful wake. Inventory any added explanation before shipping. **A1**. | |
| -| P3-C3 | Boot/admission operator diagnostics, new host/adaptor files | Identify failed phase, hook timeout/unknown acknowledgment/invalid receipt and action to inspect/replace; no secrets/raw env/credential values. Separate technical structured fields from prose. **A1/N1**. | |
| -| P3-C4 | Tofu variable validations/outputs/alarm descriptions, module README | Fixed/group constraints, protected EIP ownership, costs, no automatic refresh/scale-in, port-443 backhaul exception, approval/cleanup. Inventory every new description/error string. **T1/E1**. | |
| +| P3-C2 | Existing edge/activator pre-admission refusal | Neutral startup refusal; 503/Retry-After with no holder identity. Do not reuse “waking elsewhere”. Do not expose group/account/iid or imply successful wake. Inventory any added explanation before shipping. **A1**. | |
| +| P3-C3 | Boot/admission operator diagnostics, new host/adaptor files | Inventory boot-template stdout/stderr and phase errors, hook timeout/unknown acknowledgment/invalid receipt, Standby wait/recovery and refusal reasons; distinguish first-boot replacement from maintenance hold; no secrets/raw env/credential values. Separate technical structured fields from prose. **A1/N1**. | |
| +| P3-C4 | Tofu variable validations/outputs/alarm descriptions, module README | Fixed/group constraints, protected EIP ownership, costs, no automatic refresh/scale-in, port-443 backhaul exception, approval/cleanup. Inventory every new description/error string, JSON plan-gate refusal text, allow-list/cleanup errors and literal-unprotect guidance. **T1/E1**. | |
| | P3-C5 | Alarm notification context and operational docs | Failure/recovery/unknown producer; lease-expiry delay and replication-class loss, S3-loss manual intervention, same-region SNS. Never promise universal one-second loss or few-minute recovery before fencing. **I1/I4**. | |
| | P3-C6 | Drain/platform applied result/readiness, P2b-owned | Incomplete stop/marker/import is still draining; never report safe-to-remove from zero awake count alone. Platform continues console/relay duties outside NLB. **I3/R1**. | |
| | P3-C7 | Dev acceptance/deployment guidance and later P6 references | Explain isolated zone-EIP probe versus public cut-over, release/gate status, named go and costs; production retirement/runbook stays P6. **E1/S1**. | |
| +| P3-C8 | External health 503 condition name/text | Not admitted; no holder identity, and no suggestion that S3 loss terminates a member. **A1/I4**. | |
| + |
| JSON names, metric names and pure structured reason codes are protocol data, not approved prose. P2a's configured-ingress deck remains its owner's; P3 adds no competing DNS guidance. N-HA13's HA display cut remains in force. |
| ## Census and verification |
| -This Markdown-only plan is outside the census: **no overlay, re-pin or approval claim now**. Execution changes all regular infra files (including templates/tests), root dependencies in host/activator/edge/release/hostenv and the new packages/embeds. Expected new/body/sites/reads/envelope classes are decided by the actual card, not pre-approved here. Root-installed hairpin/boot inputs are security-sensitive; explicitly trace SSM/config provenance and show root never consumes the agent admission receipt or tenant-named paths. |
| +This Markdown-only plan is outside the census: **no overlay, re-pin or approval claim now**. Execution changes all regular infra files (including templates/tests), root dependencies in host/activator/edge/release/hostenv and the new packages/embeds. Expected new/body/sites/reads/envelope classes are decided by the actual card, not pre-approved here. Root-installed maintenance permits/group markers, fixed region settings and hairpin/boot inputs are security-sensitive; explicitly trace SSM/config provenance and show root never consumes the agent admission receipt or tenant-named paths. |
| At each real slice tip: `make census-card`; tab-separated CLAIMS per changed unit (what changed/new read or none); `make census-propose NAME=region-ha-p3a CLAIMS=<owned-file>` (P3b uses its own name); targeted `TestPlan14RootReadCensus|TestCensusScopeIsTheRootBinary|TestPlan14RootInputInventoryCoverage|TestCensusRebaseCarriesDispositions` in internal/provision. Reviewer from the other family decides every unit/envelope against actual amadan-main diff, records exact tip/verdict on #280; no census question escalates to Paul. Check record-write/9B8 inventories separately and re-pin only demonstrated digest changes. No archive entries. No reviewer is spawned in this commission. |
| @@ -290,7 +340,8 @@ Implementation iteration uses named targeted tests above, `nice -n 19`, fake AWS |
| ## Open decisions for Paul and finish line |
| 1. **Dev date/window and resources:** approve a dated P3a release/drill window once the named producers merge, and the later disposable P3b count/type/region/pool/domain/cost/expiry card. Recommended first result: existing IE hapair host through isolated new NLB addresses; no ordinary DNS/EIP cut-over or termination of the proving pair. |
| -2. **If producers cannot land in that window:** keep P3 implementation on branch. The missing consumer/serving/console contracts must merge before integration is planned/reviewed; do not spend P3 review rounds guessing them or merge a dormant switch. |
| +2. **P3b maintenance authority (T1):** approve or reject the exact §12.1 exception in “Restart authority”; no §10 change is requested. Without that exception, refuse the group activation and keep the visible fixed-target P3a slice separate. The implementation cannot silently lower min/desired. |
| +3. **If producers cannot land in that window:** keep P3 implementation on branch. The missing consumer/serving/console contracts must merge before integration is planned/reviewed; do not spend P3 review rounds guessing them or merge a dormant switch. |
| No new placement/compute/replica design decision is requested from Paul. #457 phase 2 and #498 keep provisioning ownership; #511 stateless replicas remains outside this HA plan. G3 is the series finish line; G5's routine swaps await migration/P4/P5/P6/fencing. |