design: carlos system group, the roll tool as a verb (spec + plan r1)
Port of scripts/region-group-roll.py and the probe into the carlos binary: provider-neutral engine, AWS adapter, parity proof, a claim for cross-machine serialization, rollout and retirement.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-11-09-group-roll-verb.md+237 −0docs/superpowers/specs/2026-11-09-group-roll-verb-design.md+471 −0
CI cancelled — superseded by a newer push — run details
Intent
<task-notification> <task-id>a92686154b70b9668</task-id> <tool-use-id>toolu_01Y3SZAgYdGG3CwraTnnGxnR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a92686154b70b9668.output</output-file> <status>completed</status> <summary>Agent "Placeholder check" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**1. Conditional PutObject.** Yes, but it isn't in `internal/objstore` or `internal/s3compat`. It lives in `internal/release`: - **Interface:** `release.Store` (`internal/release/store.go:50-63`), with methods `Get(ctx,key) (body, etag, err)`, `Put(ctx,key,body,ifMatch) (newEtag, err)`, `List`, `ListDirs` and `Delete`. - **How `Put` decides:** an empty `ifMatch` sends `If-None-Match: *` (create-only); a non-empty one sends `If-Match: <etag>`. Losing either race returns `ErrCASConflict` (doc at `store.go:33-49`, implementation in `S3Store.putRaw` at `store.go:992-1003`, and again at `store.go:1041-1045`). - **Extras:** `S3Store.GetIfChanged` (`store.go:1153`) and `release.DeleteIfMatch` (`internal/release/conditional_delete.go:29`). - **`internal/objstore`** is the control plane for per-app stores. Its `Put`/`PutIn` (`objstore.go:326,333`) sit on top of `release.Store`. - **`internal/s3compat`** only adds client quirks. Its one quirk, `unquotedIfMatch` (`s3compat.go:113-175`), strips the quotes from `If-Match` on PutObject because Ceph RGW (Hetzner) rejects the quoted form. **Testing:** `internal/s3fake/s3fake.go:1-10` is an in-process S3 server that handles conditional requests and is held to the same contract (`TestS3StoreFakeContract`). Against real MinIO: - `TestS3StoreMinioContract` (`internal/release/s3_minio_test.go:21`) runs the `release.Store` contract. - `TestDeliveredContractMinio` (`internal/objstore/contract_test.go:46`) covers Put/Get/List/Delete with the credentials an app receives, plus a check that a second, ungranted bucket is denied. I didn't confirm it tests conditional puts. Both are skipped unless `CARLOS_MINIO_TEST=1`. CI's `.amadan/ci.d/30-minio-contract` step starts MinIO and sets it. **2. The two AWS packages.** - **`internal/awsregiongroup`:** "completes only a box's original launch action" (`complete.go:1`). `Completer` wraps one Auto Scaling call, `CompleteLifecycleAction` with result `CONTINUE` (`complete.go:17-41`). It uses `aws-sdk-go-v2/service/autoscaling` v1.74.0 (`go.mod:10`). There is no other Auto Scaling wrapper (no describe or update-group calls). - **`internal/rootaws`:** "keeps root's AWS clients away from executable shared profiles" (`config.go:1`). It loads config and static credentials, scrubs the environment, and opens the credentials file per OS (`open_linux.go`, `open_darwin.go`). It has no Auto Scaling code. **3. golang.org/x/sys and PTY code.** `golang.org/x/sys v0.49.0` is in go.mod (`go.mod:31`). PTY code exists only in tests: - `interactive_term_linux_test.go:14-21` and `internal/instanceexec/tty_linux_test.go:27-41` both open `/dev/ptmx` and unlock it with `unix.TIOCSPTLCK`. - `internal/execsandbox/oci.go:93` only sets the `ptmxmode` mount option on devpts. There is no production PTY helper, no `Openpt` call, and no darwin PTY code. **4. How a verb is registered in `internal/clireg`.** The CLI is a tree of `clireg.Node` values (`internal/clireg/clireg.go:42-80`). Each node has a `Name`, optional `Aliases`, `Children`, `Run` (leaf handler), `Transparent`, `Fallback`, `Audience` and `Golden`. Top-level commands are listed in `commandRoot()` (`commands.go:30`), which includes `systemCommand()` at `commands.go:153`. The `system` subcommands are listed in `systemCommand()` (`system.go:50-98`, children from line 57). A leaf is usually built with `raw(name, audience, func([]string))` (`commands.go:37`); `audience` is `clireg.Operator` or `clireg.BoxLocal`. `noHint` (`commands.go:43`) wraps a node to suppress the update hint. `clireg.Dispatch` (`dispatch.go:20`) walks the tree, and `Validate` checks it is well formed. The existing `system group` branch is `systemGroupCommand()` (`system_roles.go:123`), so a new group verb would go under it.</result> <usage><subagent_tokens>38679</subagent_tokens><tool_uses>7</tool_uses><duration_ms>50118</duration_ms></usage> </task-notification>
<task-notification> <task-id>a893161493e13ba36</task-id> <tool-use-id>toolu_018Gx5Exg5m2cbFXN8XvdaSR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a893161493e13ba36.output</output-file> <status>completed</status> <summary>Agent "Survey group-maintenance verbs + infra" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I answered all eight questions from source, with file:line citations; nothing was written or changed. Paths below are relative to the worktree root. ## 1. `carlos system group-maintenance` on the box - **Where it's registered:** `system.go:62-64` registers it as one `raw("group-maintenance", box, …)` leaf (audience `clireg.BoxLocal`) that calls `os.Exit(host.RunGroupMaintenance(args, os.Stdin, os.Stdout, os.Stderr))`. The leaf takes all its arguments at once (comment at `system.go:47-49`). - **Implementation (`internal/host`):** - `group_maintenance_verbs.go`: help text at 21-60, `RunGroupMaintenance` at 64, `run` at 134, status types at 245-301, `status()` at 367, argument parsing in `maintenanceArguments` at 430. - `group_maintenance_prepare.go`: prepare 140, apply 126, rollback 261. - `group_maintenance_drain.go`: drain 72, cancel 154, `handoverStatus` 184. - Also `group_maintenance.go` (permit validation) and `group_maintenance_verbs_linux.go` (lock, permit directory, binary digest, edge process). - **Accepted argument forms:** `prepare --sha256 <64hex>`; bare `status|permit|revoke|apply|rollback`; `drain <txn>`; `drain --cancel <txn>` (becomes `drain-cancel`); `fence-clear <txn>`. A transaction must match `groupTransactionID` and must not start with `-`. - **Exit codes:** 0 ok or help, 1 refused or failed, 2 bad arguments. Errors print as `group-maintenance: …`. - **Root:** `cmd.euid() != 0` returns "root required" (`verbs.go:135`), where euid is `os.Geteuid` (`verbs.go:82`). It also needs the group marker, and takes the apply lock without waiting; a held lock gives "apply lock busy" (`verbs.go:166-169`). `status` can still run when the lock file is missing. - **`status` JSON** (`verbs.go:245-301`, at most 8192 bytes, one line): - Top level: `v` (=1), `iid`, `boot_id`, `account`, `region`, `group`, `config_digest`, `box_ref`. - `edge{state, pid, start_time, started_at, started_at_error, identity, error}`. `identity` is `"<boot_id>:<pid>:<start>"` (`verbs.go:396`). - `binary_sha256` and `binary_error` (both nullable). - `permit{state: absent|present|unknown, transaction, action, expires, consumed, accepted, rollback_consumed, error}`. - `health{state: healthy|unhealthy|unknown, code, error}`, from one GET to `127.0.0.1` + `lbhealth.Path`. - `fence{state, transaction, error}` and `drain{state, incarnation, transaction, step, result, error}`. - **Drain report** (`drainReport`, `internal/host/hadrain.go:124-146`): `v, transaction, incarnation, step (withdraw|move), result (running|ok|failed), reasons[], fence, started_at, finished_at, acked[], moved[{host,holder,gen,confirmed}], released[]/left[] {host,kind,marker,clean,reason}, unclean[], holds, connections_closed_at_bound, quiet`. Drain prints it and exits 0 only when `result=="ok"` (`drain.go:103-113`). Re-running drain joins a move already in progress (`drain.go:83`). ## 2. AWS SDK in Go - **Service modules in `go.mod`:** acm, autoscaling v1.74.0, cloudwatch, costexplorer, ec2 v1.324.0, iam, resourcegroupstaggingapi, route53, s3, sesv2, sqs, ssm v1.74.0, sts (lines 9-21), and sns (line 90). **elasticloadbalancingv2 is not in `go.mod`.** - **`internal/rootaws` exists.** `config.go` provides `LoadDefaultConfig`, which keeps the normal SDK chain for non-root users. For root it disables shared config files and profiles, and refuses `AWS_PROFILE`/`AWS_DEFAULT_PROFILE` (`config.go:52-53, 70-71`). `main.go:25` calls `rootaws.ScrubEnvironment()` for every invocation. - **Packages that build autoscaling, ec2 or ssm clients:** `internal/awsregiongroup/complete.go`, `internal/awsinv/*`, `internal/awsmanaged/*`, `internal/termfence/fence.go`, `internal/boxvolumes/volumes.go`, `internal/host/hatakeover.go`, and `internal/hostenv/awsssm.go`. The last uses `ssm.NewFromConfig` plus GetParametersByPath only (line 63). - **SSM StartSession / session-manager-plugin / SendCommand:** no Go code uses any of them. The only hit is a fake `SendCommand` in `cmd/console/hostsused_scan_test.go:154`. The Python tool shells out to the `aws` CLI with `--profile` (`template_release`, `region-group-roll.py:1087`). ## 3. Provider-neutral import test - `region_ha_boundary_test.go` (repo root): - `TestRegionHACoreImportsNoAWS` (line 76) checks the hand-written list `regionHACoreFiles` (lines 21-44). - `TestRegionHAAdaptersAreNamedForAWS` (line 91) checks that adapter files have AWS in their names. - S3 clients must go through s3compat (lines 158, 181). - The rule is per file, not per package. A new core file has to be added to the list in the same commit. - `internal/registrar/boundary_test.go` is a separate boundary test. ## 4. The command registry and console choice - **The tree:** `commands.go:30` `commandRoot()` → `buildCommandRoot()`; `main.go:35` calls `clireg.Dispatch(commandRoot(), os.Args[1:])`. - **Registry package:** `internal/clireg` (`clireg.go`, `dispatch.go`, `validate.go`). Audiences are `Customer`, `Operator`, `BoxLocal` and `Internal` (`clireg.go:28-31`). - **`carlos system`:** `systemCommand()` at `system.go:50-99` has audience Operator, a transparent `router` child, and Fallback `systemFallback`. `systemGroupCommand()` (`system_roles.go:123`) currently holds only `group role`. Helpers: `raw`, `noHint`, `skipBare`, `skipGolden` in `commands.go:37-60`. - **Console choice:** `config.go:48` `defaultConsole = "https://console.carloku.com"`, and the comment there says it is used by `auth login` only and no other verb assumes it. Operator verbs use `requireDeployAPISession(consoleFlag)` and print the console in use with `printUsing` (e.g. `system_roles.go:136-138`). - **Local AWS profiles:** there is no `--profile` flag or `WithSharedConfigProfile(<name>)` anywhere in the CLI. Grep finds only `""` or test values. There is no `carlos system root` verb. Since `rootaws` refuses profiles when run as root, a port has no existing pattern to follow for operator-side profiles. ## 5. Infra - **`infra/modules/region-host/group_operator.tf`** outputs `group_operator_policy_json` (it creates no IAM resource; empty in fixed mode). Statements: - `GroupMaintenance`: autoscaling UpdateAutoScalingGroup, EnterStandby, ExitStandby on the group ARN, conditioned on the `carlos:deployment` and `carlos:region` resource tags. - `GroupTerminateDrainedMember`: `TerminateInstanceInAutoScalingGroup`, same scoping. - `ObserveMaintenance` on `*`, limited by `aws:RequestedRegion`: DescribeAutoScalingGroups, DescribeAutoScalingInstances, DescribeLifecycleHooks, DescribeScalingActivities, elasticloadbalancing DescribeTargetHealth, ec2 DescribeInstances and DescribeLaunchTemplateVersions, ssm DescribeInstanceInformation. - `GroupSession`: `ssm:StartSession` on `instance/*` where the tag `aws:autoscaling:groupName` equals the group name, plus `BoolIfExists ssm:SessionDocumentAccessCheck=true`. - `ApprovedSessionDocument`: StartSession on the approved document. - `OwnSessions`: Terminate/ResumeSession where the session tag `aws:ssmmessages:session-id` equals `${aws:userid}`. - `OwnSessionDataChannel`: `ssmmessages:OpenDataChannel` on `session/*`. - S3: GetObject on `control/edges/*`; ListBucket with prefix `control/edges/`; lock sweep ListBucket on `<lock_prefix>/` with delimiter `/`, and on `<lock_prefix>/*/lock.json`; GetObject on `…/*/lock.json`. - A precondition requires the document to be `AWS-StartNonInteractiveCommand` or a document owned by this account in this region, and never `SSM-SessionManagerRunShell`. - **Session document:** `infra/modules/region-group-operator-document/main.tf`: - `aws_ssm_document.maintenance`, type Session; the name comes from `var.name`, which may not start with `AWS-`. - `sessionType = "NonInteractiveCommands"`, one String parameter `command` with an `allowedPattern`, and `linux{commands="{{ command }}", runAsElevated=true}`. - The pattern is in `tool-pattern.txt`. It accepts exactly the framed `env -i … /bin/sh -c` wrapper (uid check, `<nonce>:BEGIN`/`END:%s` frames) around the verbs, with timeouts: apply/rollback 900s, drain 3600s, drain --cancel 300s, `systemctl stop carlos-edge` 120s. An optional harness form is added when `harness_bundle_sha256` is set. - **CARLOS_RELEASE:** `group.tf:50` sets `CARLOS_RELEASE = var.group_config.release` inside the templated config, POSIX single-quoted (`group.tf:51`). The template is `group-init.sh.tftpl:4`, and the result is gzipped into user data (`group.tf:53`). The Python tool reads the line back with the regex `^CARLOS_RELEASE='([^']*)'$` (`region-group-roll.py:1081-1100`). ## 6. The census - **What it is:** `AGENTS.md:299-400`. `TestPlan14RootReadCensus` (`internal/provision`) fingerprints the root binary's source. Scope is guarded by `TestCensusScopeIsTheRootBinary`, and each branch has its own `*_census_test.go` cards in `internal/provision/`. - **The Python tool is out of scope:** `AGENTS.md:316-318` lists "Out: … `scripts/`". - **A Go port would be in scope.** Any new package in `go list -deps .` lands in the census, and so does `infra/`. `tool-pattern.txt` is already a census entry (`docs/superpowers/notes/census-proposal-region-ha-held-build.md:33`). ## 7. Release records - `internal/release/layoutintent.go:368` `ParseReleaseVersion`, and `:375` `BelowFloor(version, floor SemVer)`. An unparseable version counts as not below the floor. The Python versions (`release_version` and `below_floor`, `region-group-roll.py:491-502`) say they mirror these. - **Signed pointer:** - `systempointer.go:259` `GetSystemPointer(ctx, store, pub, component, channel)` → `*SystemPointer`. - `Current.Artifacts[platform].SHA256` paired with `Current.Version` is the SHA-to-version link (`SystemRelease` at :62, `SystemArtifact` at :75). - The unexported `verifySystemPointer` is at :217. - **Per-release identity record:** `systemidentity.go:22` `VerifySystemIdentity`, `:45` `IdentityKey(tag)` → `control/system/router/releases/<tag>.json`, `:98` `GetSystemIdentity`, and `:15` `ReleaseTag`. - **How prepare maps a digest to a version today:** `group_maintenance_prepare.go:169-178` checks that the pointer's artifact SHA equals `--sha256`, then takes `p.Current.Version`. The Python tool uses the `version` from prepare's result for its floor check (`region-group-roll.py:1489-1490, 1658`). - **No reverse lookup exists.** Nothing in Go goes from a SHA to a version across past releases. - Related: `internal/hostfloor/floor.go:54` `Verify`. ## 8. Tests for the Python tool | File | Tests | Covers | |---|---|---| | `region_group_roll_test.py` | 110 | Offline witnesses for the attended transaction | | `region_group_held_test.py` | 66 | Planned handovers: replace, remove, drained roll (§25.6/25.9/25.15, H4/H5); a settlement table of more than 30000 rows (:1251) | | `region_group_document_test.py` | 12 | Session grammar acceptance and refusal, seeded `Random(3512)` and `Random(60000)` | | `region_group_probe_test.py` | 28 | Unchanged-member Standby probe | | `region_group_fault_test.py` | 64 | `region-group-fault/fault.py` harness (blocks a member's HTTPS; `bundle.py`, `client.py`, `rehearse.py`) | | `region_group_contract_test.py` | 4 | Audits mock `tofu test` plans | | `check_region_group_plan_test.py` | 49 | Checks the plan guard | | `region_group_boot_witness_test.py` | 58 | `region-group-boot-witness.py` | | `region_group_ssm_boot_test.py` | 3 | SSM boot | | `region_group_boot_umask_test.py` | 6 | Boot umask | - `region_group_witness_fake.py` is a simulation-only fake of AWS. - **How CI runs them:** `internal/provision/region_group_guards_test.go`: - `TestRegionGroupPythonGuards` (:203) runs `check_region_group_plan_test` and `region_group_contract_test`. - `TestRegionGroupHeldPythonGuards` (:218) runs `region_group_held_test` and `region_group_document_test`, with TMPDIR set to the test's temp directory. - `groupGuardBinary` (:119) fails if python3 is missing in CI and skips locally. - The gate is `.amadan/ci.d/10-gate`, which runs `go test ./...`. - **Not run by any Go test:** the roll, probe, fault, ssm_boot, boot_umask and boot_witness tests. I found no wrapper for them. - **"3000 seeds"** is the Go simulation, not Python. `internal/sim/regionha/handover_test.go` (`runHandoverScenario` :2093) runs through `TestRegionHA`, which reads `RHASIM_SEEDS` and defaults to 200 (`sim_test.go:15-42`). The 3000-seed run is a manual step per implementation revision (`docs/superpowers/plans/2026-11-03-region-ha-p1b3b-duties.md:377`). `handover_witness_test.go:329` covers 200 seeds. Two gaps for the port: Go has no elbv2 SDK module and no SSM StartSession or session-manager-plugin code. And because `rootaws` refuses profiles when run as root, there is no existing pattern for an operator verb that uses a local AWS profile.</result> <usage><subagent_tokens>102766</subagent_tokens><tool_uses>45</tool_uses><duration_ms>260110</duration_ms></usage> </task-notification>
diff --git a/docs/superpowers/plans/2026-11-09-group-roll-verb.md b/docs/superpowers/plans/2026-11-09-group-roll-verb.md| new file mode 100644 |
| index 000000000..03d8ced32 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-09-group-roll-verb.md |
| @@ -0,0 +1,237 @@ |
| +# `carlos system group` (roll tool port) Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** Port `scripts/region-group-roll.py` and `scripts/region-group-probe.py` into `carlos system group <verb>` with exact behaviour parity, a provider-neutral engine and an AWS adapter, then retire the scripts. |
| + |
| +**Architecture:** `internal/grouproll` is the core (journal, lock, claim, deciders, engine, box protocol, floor) and imports no AWS SDK. `internal/grouprollaws` implements the core's `Group` and `Box` interfaces with the AWS SDK and the Session Manager plugin. The CLI leaves live in `system_group.go` under the existing `systemGroupCommand()`. |
| + |
| +**Tech Stack:** Go, aws-sdk-go-v2 (autoscaling, ec2, ssm, new: elasticloadbalancingv2), `internal/release` (`Store`, `GetSystemPointer`), `golang.org/x/sys/unix` for the pseudo-terminal, MinIO for integration tests. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-09-group-roll-verb-design.md` (rev 1). Read it and the script before any task; the script at the merge of `held-floor-sha-map` is the parity target. |
| + |
| +## Global Constraints |
| + |
| +- Parity: every behaviour not in spec §7's table (V1-V7) matches the script decision for decision. When the spec and the script disagree on something outside §7, the script wins and the spec gets a fix. |
| +- Bounds copied verbatim: `WAIT=900s`, `DRAIN_TRIES=3`, `DRAIN_BOUND=3600s`, `EDGE_STOP_BOUND=120s`, `CANCEL_BOUND=300s`, session local bounds `prepare 360, apply 990, rollback 990, drain 3690, edge-stop 210, fence-clear 60, drain-cancel 390`, default 15 s; `TERMINATE_RETRIES=2`, `TERMINATE_SETTLE=120s`, `TERMINATE_PENDING=600s`; exit freshness `0 <= age <= 5s`; readiness age `<= 60s`; publication margin 2 s; `EDGES_MAX_AGE=900s`, `EDGES_SKEW=60s`; output cap 4 MiB; status body cap 8192 bytes; drain body cap 1 MiB; journal cap 64 MiB; record cap 65536 bytes. |
| +- Regexes verbatim from the script: `SHA`, `IID`, `TX`, `EDGES_KEY`, `BUCKET`, `HOST_NAME`, and every pattern in `validate_config`. |
| +- The core never imports `github.com/aws/...`; each new core file is added to `regionHACoreFiles` in `region_ha_boundary_test.go` in the commit that creates it. |
| +- Linux/Darwin-only files carry `//go:build linux || darwin` with a `_other.go` sibling returning `errUnsupportedSystem`. Before every push: `GOOS=darwin GOARCH=arm64 go build ./... && GOOS=windows GOARCH=amd64 go build ./...`. |
| +- Operator copy is the script's `TEXT` table ported verbatim into `internal/grouproll/text.go`; no new user-facing string is invented outside that table, and Task 13's copy review is the only place strings change. |
| +- Local tests: changed packages only, with `-run`; full suite once before the branch review (memory: local verification budget). Scratch under `$TMPDIR`. |
| +- Commit subjects under 80 characters. One amadan task per plan task on the branch, advanced as each closes. |
| +- Census: every task that adds files to the root binary's closure appends its units to the branch's census proposal (`make census-propose`); Task 14 gets the reviewer's verdict. |
| + |
| +## Review Focus |
| + |
| +1. A machine whose clock is off by minutes: freshness and readiness ages use the local clock against box-published times; a skewed clock must refuse (as the script does), never pass. Test in Task 5. |
| +2. Ctrl-C or a killed process mid-call: the journal has an `intent` with no `response`; the next verb must treat it as dispatched-uncertain, never as not-sent. Test in Task 7's simulation (deaths at every boundary, including inside a provider write). |
| +3. Two machines starting a transaction on the same group within a second: exactly one wins the claim; the other refuses before writing a journal row that a later `abandon` would need. Test in Task 11. |
| +4. An AWS profile that resolves through SSO with an expired token: the first describe fails as `api` and nothing is written to the group. Test in Task 3. |
| +5. A Session Manager plugin missing from `PATH` or of a version that prints a different session banner: `plan` reports it as a refusal, and no writing verb gets past preflight. Test in Task 4. |
| + |
| +--- |
| + |
| +### Task 1: Config, journal format 2, state and the local lock |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/config.go`, `journal.go`, `state.go`, `state_unix.go` (`//go:build linux || darwin`), `state_other.go`, `text.go` |
| +- Test: `internal/grouproll/config_test.go`, `journal_test.go`, `state_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `type Config struct{...}` with the script's keys (JSON tags identical) and `func LoadConfig(path string) (Config, error)`; `type Journal`, `func (j *Journal) Add(kind string, fields map[string]any) (Row, error)`, `func (j *Journal) Last(kind string, match map[string]any) (Row, bool)`; `type State`, `func OpenState(c Config, readonly bool) (*State, error)`, `func (s *State) Lock() (unlock func(), err error)`, `func (s *State) Create(header Header) (*Journal, error)`, `func (s *State) Load(tx string, readonly bool) (*Journal, error)`, `func (s *State) ActiveID() (string, error)`, `func (s *State) Finish() error`; `type Refusal struct{Key string; Args map[string]string}` and `func Text(key string, args ...string) string`. |
| + |
| +- [ ] **Step 1: Write failing tests.** `TestConfigMatchesScriptValidation`: a table of every accept/refuse case in `scripts/region_group_roll_test.py` and `region_group_held_test.py` config tests plus the `held-floor-sha-map` keys; each refusal is `config_invalid`. `TestJournalFormat2Golden`: two fixed rows encode to the bytes in `testdata/journal-format2.golden` (header has `"format":2`, times are integer milliseconds). `TestJournalRefusesDamage`: truncated last line, duplicate key, `NaN`, a bad `previous`, a bad `hash`, `seq` gap, over 64 MiB → `record`. `TestStateRefusesUnsafe`: state dir 0755, owned by another uid, a symlinked ancestor, a group-writable ancestor → `unsafe_state`. `TestStateRefusesScriptActive`: a script `active.json` naming a journal without `"format":2` → `journal_kind` (V4). `TestLockRefusesSecondWriter`: a second `Lock()` in another process → `busy`. |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run 'TestConfig|TestJournal|TestState|TestLock'` — FAIL (undefined). |
| +- [ ] **Step 3: Implement.** Canonical encoding in one function `encodeRow(map[string]any) []byte`: keys sorted, no spaces, integers only (refuse floats), HTML escaping off. Group directory `hex(sha256(group_arn))[:32]`, files `<tx>.jsonl`, `active.json`, `group.lock` (`flock(LOCK_EX|LOCK_NB)`), `provider-observation.json`, `provider-divergence.json`, plan logs `plan-<hex>.log`. File checks as `private_file` with the owner = euid (V1). Port `TEXT` verbatim. |
| +- [ ] **Step 4: Run** the same command — PASS. |
| +- [ ] **Step 5: Commit** `grouproll: config, journal format 2 and the group lock`. |
| + |
| +### Task 2: The box protocol |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/box.go` |
| +- Create: `internal/grouproll/testdata/remote-commands.golden.json` (generated once by `scripts/grouproll-golden/remote_commands.py`, which imports the script and calls `AWS.remote_command` with fixed nonces; committed with its output) |
| +- Test: `internal/grouproll/box_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `func RemoteCommand(verb string, a BoxArgs, nonce string) (string, error)`; `type BoxStatus` (fields of `group_maintenance_verbs.go:245-301`, unknown fields kept in `Raw map[string]any`); `func ParseFramed(text, nonce, verb string) (BoxResult, error)` covering `drain_output` (exit 124 → `Uncertain{Timeout:true}`), `edge_stop_output`, the `drain-cancel` exit-1 detail, and the 8192-byte JSON decode; `type Box interface { Run(ctx, iid string, verb string, a BoxArgs) (BoxResult, error) }`. |
| + |
| +- [ ] **Step 1: Failing tests.** `TestRemoteCommandGolden`: every golden case matches byte for byte. `TestRemoteCommandMatchesDocumentPattern`: each output matches the regex in `infra/modules/region-group-operator-document/tool-pattern.txt`. `TestParseFramed`: two frames → `remote`; END code `124` on drain → uncertain; over-cap body → `remote`; the drain report is the last `{"v":1,...}` line. |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run 'TestRemoteCommand|TestParseFramed'` — FAIL. |
| +- [ ] **Step 3: Implement** as `remote_command` and the three parsers; shell quoting must reproduce `shlex.quote`. |
| +- [ ] **Step 4: Run** — PASS. |
| +- [ ] **Step 5: Commit** `grouproll: framed box commands, byte-identical to the script`. |
| + |
| +### Task 3: The AWS adapter's group calls |
| + |
| +**Files:** |
| +- Create: `internal/grouprollaws/config.go`, `group.go`, `phase.go` |
| +- Modify: `go.mod`, `go.sum` (add `github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2`) |
| +- Test: `internal/grouprollaws/group_test.go`, `phase_test.go`, `config_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1 `Config`, `Refusal`. |
| +- Produces in core `internal/grouproll/provider.go`: `type Phase string` (`Serving, Parking, Parked, Returning, ReturnHeld, Leaving, Absent, Unknown`); `type GroupView struct{Name, ARN, Deployment, Region string; Minimum, Desired, Maximum int; Members map[string]Member; Template map[string]any; TargetGroups []string}` with `Member{Phase Phase; Raw string; Healthy bool}`; `type Activity struct{ID, Kind, Status string; Time int64}`; `type Group interface { Describe(ctx) (GroupView, error); Targets(ctx, arn string) (map[string]string, error); Hook(ctx) (Hook, error); Online(ctx, iid string) (bool, error); Activities(ctx, iid string) ([]Activity, error); Instance(ctx, iid string) (InstanceState, error); TemplateRelease(ctx, tpl map[string]any) (string, error); SetMinimum(ctx, n int) (WriteResult, error); RaiseDesired(ctx, n int) (WriteResult, error); Park(ctx, iid string) (WriteResult, error); Unpark(ctx, iid string) (WriteResult, error); Terminate(ctx, iid string) (WriteResult, error) }`. `WriteResult{Activity string; Uncertain bool; Response any}`. |
| +- Produces in adapter: `func New(ctx, c grouproll.Config) (*Adapter, error)`; `func MapPhase(state string) grouproll.Phase`. |
| + |
| +- [ ] **Step 1: Failing tests.** `TestMapPhaseTotal`: every state in the spec §5.2 table maps as listed; `"Warmed:Pending"` → `Unknown`. `TestCredentialsIgnoreAmbient`: with `AWS_ACCESS_KEY_ID`, `AWS_PROFILE=other`, `AWS_ENDPOINT_URL=http://evil` set and a shared config file naming the config's profile, the resolved credentials are the profile's and the endpoint is AWS's; IMDS disabled. `TestExpiredSSOIsAPIRefusal` (Review Focus 4). `TestWriteShapes` (SDK middleware capture, no network): `Park` sends `ShouldDecrementDesiredCapacity=true` for exactly that iid; `Terminate` sends `ShouldDecrementDesiredCapacity=false` and refuses (`h4`) unless a fresh describe shows the member `Standby` and `desired == minimum`; `RaiseDesired` refuses unless `desired <= n <= maximum`; no method can lower desired. `TestActivitiesKinds`: "Moving EC2 instance out of Standby", "to Standby", "into Standby", "Terminating EC2 instance" classified as the script; a description naming another iid is ignored. `TestTemplateRelease`: gzip and plain user data; zero or two `CARLOS_RELEASE=` lines → `api`. `TestTargetsDuplicatePort`: two registrations with different states → `unknown`. `TestInstanceNotFound`: an empty filtered response → `not-found`; a CLI error is never absence. |
| +- [ ] **Step 2: Run** `go test ./internal/grouprollaws -run .` — FAIL. |
| +- [ ] **Step 3: Implement** with `awsconfig.LoadDefaultConfig` given `WithSharedConfigProfile(c.Profile)`, an explicit credentials provider resolved from that profile, `WithRegion(c.Region)`, IMDS disabled, `RetryMaxAttempts=1`, 2 s connect and read timeouts. Never read `AWS_ENDPOINT_URL*`. |
| +- [ ] **Step 4: Run** — PASS. |
| +- [ ] **Step 5: Commit** `grouprollaws: Auto Scaling, ELB and EC2 calls behind the Group interface`. |
| + |
| +### Task 4: The Session Manager transport |
| + |
| +**Files:** |
| +- Create: `internal/grouprollaws/session.go`, `pty_linux.go`, `pty_darwin.go`, `pty_other.go` |
| +- Test: `internal/grouprollaws/session_test.go`, `internal/grouprollaws/testdata/fakeplugin/main.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2 `RemoteCommand`, `ParseFramed`, `Box`. |
| +- Produces: `func (a *Adapter) Run(ctx, iid, verb string, args grouproll.BoxArgs) (grouproll.BoxResult, error)` implementing `grouproll.Box`; `SessionObserver func(sessionID string)` set by the engine before each call; `func (a *Adapter) TerminateSession(ctx, id string) error`. |
| + |
| +- [ ] **Step 1: Failing tests** using a fake plugin binary built in `TestMain` and put first on `PATH`: `TestSessionReadsFrame`; `TestSessionBoundKillsGroup` (the fake ignores SIGTERM and forks a child; at the bound both are gone, error is uncertain-timeout, the session id seen was reported to the observer); `TestSessionOutputCap` (4 MiB + 1 → `remote`); `TestPluginMissing` (Review Focus 5: `PATH` without it → `remote` refusal naming the plugin); `TestSessionStartArgs` (the StartSession request carries the config's `document`, the target iid and `{"command":[<RemoteCommand>]}`). |
| +- [ ] **Step 2: Run** `go test ./internal/grouprollaws -run TestSession -run TestPlugin` — FAIL. |
| +- [ ] **Step 3: Implement.** Call `ssm.StartSession`, then exec `session-manager-plugin '<response json>' <region> StartSession '' '<request json>' https://ssm.<region>.amazonaws.com` on a fresh pty (`Setsid`), stdin the pty slave left open and silent, read the master until frame or bound; at the bound `kill(-pgid, SIGKILL)` then reap. |
| +- [ ] **Step 4: Run** — PASS; also `GOOS=darwin GOARCH=arm64 go build ./... && GOOS=windows GOARCH=amd64 go build ./...`. |
| +- [ ] **Step 5: Commit** `grouprollaws: run framed box verbs through Session Manager`. |
| + |
| +### Task 5: Engine reads, `plan` and `status` (first merge: visible on dev) |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/engine.go` (the `Operator` equivalent: `call`, `snapshot`, `identity`, `readiness`, `preflight`), `plan.go`, `status.go` |
| +- Create: `system_group.go`; Modify: `system_roles.go:122-130` (add the new leaves to `systemGroupCommand()`) |
| +- Test: `internal/grouproll/fake_test.go` (the Go port of the script's `Fake`), `plan_test.go`, `system_group_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 1-4. |
| +- Produces: `type Engine struct{...}`; `func NewEngine(c Config, g Group, b Box, s *State, clock func() time.Time, sleep func(time.Duration), out io.Writer, attendedBy string) *Engine`; `func (e *Engine) Plan(ctx, iid, sha string) (ok bool, err error)`; `func SavedStatus(j *Journal) map[string]any`; `func runSystemGroup(verb string, args []string) int`; the fake `newFake(t, n int) *fake` that later tasks extend. |
| + |
| +- [ ] **Step 1: Failing tests.** Port every `test_plan*`, `test_status*`, `test_stale_and_racing_readiness`, `test_publication_lag_and_two_second_margin`, `test_readiness_clock_starts_at_first_response_*`, `test_live_*` parsing test. Add `TestSkewedClockRefuses` (Review Focus 1: box `started_at` 3 minutes ahead of the local clock → `admission`). `TestCLIRefusesRootBoxWindows`: euid 0 → `root` text adapted per Task 13; `/etc/carlos/host.env` present (injected path) → refused; positional args → usage error; missing `--config` → usage error; no console session is ever opened (the console client constructor is a nil func in the test and must not be called). |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll ./ -run 'TestPlan|TestStatus|TestReadiness|TestSkewed|TestCLIRefuses'` — FAIL. |
| +- [ ] **Step 3: Implement** the script's `snapshot`, `identity`, `readiness`, `preflight`, `plan`, `saved_status` and `main`'s argument rules. |
| +- [ ] **Step 4: Run** — PASS. Cross-compile check. |
| +- [ ] **Step 5: Commit** `carlos system group: plan and status`. |
| +- [ ] **Step 6: Merge A.** Whole-change review for Tasks 1-5 (one Astra pass: Task 3 touches termination), census card, CI green, merge under the standing rule for inert operator verbs. Then, read-only and only with Paul's dev go: `carlos system group plan --config <dev ie config> --member <iid> --to-sha256 <current sha>` from an operator machine; it must print the same refusals as the script's `plan` on the same group. |
| + |
| +### Task 6: The deciders and golden fixtures |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/classify.go`, `terminate.go` |
| +- Create: `scripts/grouproll-golden/record.py` (wraps `classify` and `terminate_decision`, runs the roll, held and probe suites and the simulation with `REGION_GROUP_ROLL_SIM_SEEDS=3000`, writes distinct cases), `internal/grouproll/testdata/golden/classify.jsonl`, `terminate.jsonl` |
| +- Test: `internal/grouproll/classify_test.go`, `terminate_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `type Facts struct{...}` (every key `decision_facts` builds, with `Phase Phase` in place of the raw state and `Readiness string` defaulting to `"unknown"`); `type Decision struct{Action, Reason string; Delay time.Duration}`; `func Classify(f Facts) Decision`; `type TerminateFacts struct{...}`; `func TerminateDecision(f TerminateFacts) Decision`. |
| + |
| +- [ ] **Step 1: Run the recorder** on `main` after `held-floor-sha-map` merged: `python3 scripts/grouproll-golden/record.py --out internal/grouproll/testdata/golden`. Expected: two files, each case with raw facts and the decision; record the case counts in the commit body. |
| +- [ ] **Step 2: Failing tests.** `TestClassifyGolden` (map raw states with `grouprollaws.MapPhase` through a test-only copy of the table to keep the core free of the adapter, plus a test in the adapter that the two tables are equal); `TestTerminateGolden`; `TestTerminateEveryCombination` (the >30,000-row grid with the script's `expected` oracle ported). |
| +- [ ] **Step 3: Run** `go test ./internal/grouproll -run 'TestClassify|TestTerminate'` — FAIL. |
| +- [ ] **Step 4: Implement** both deciders branch for branch from the script. |
| +- [ ] **Step 5: Run** — PASS. **Commit** `grouproll: classify and terminate deciders, golden from the script`. |
| + |
| +### Task 7: The roll engine, the simulation and the mutations |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/roll.go` (roll, resume, rollback, return, abandon, close-lost, prepare, mutation, verify, alert, divergence), `sim_test.go`, `mutation_test.go` |
| +- Test: `internal/grouproll/roll_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 1-6. |
| +- Produces: `func (e *Engine) Roll(ctx, iid, sha, tx string) error`, `Resume(ctx, tx string) error`, `Rollback(ctx, iid, tx string) error`, `Return(ctx, tx string) error`, `Abandon(ctx, tx string) error`, `CloseLost(ctx, tx string) error`; the simulation `type simulation` with `func runSeed(seed int64, classify func(Facts) Decision) (coverage map[string]int, err error)`. |
| + |
| +- [ ] **Step 1: Failing tests.** Port every roll test in `region_group_roll_test.py` (Task 12's ledger lists them) into `roll_test.go` against the fake. Port `Simulation`: `TestSeededSimulation` (seeds from `GROUPROLL_SIM_SEEDS`, default 200; with 50 or more seeds, coverage of `describe-error, diverged, failed, provider-return, death, resume, admission-drop, admission-recovery, loss:exit, phase:ReturnHeld, phase:Returning, phase:Serving` each > 0); deaths include a kill between `intent` and the provider call and between the provider call and `response` (Review Focus 2). `TestSimulationMutations`: the five classifier mutants (complete, abandon, ignore hook, terminated-pass, minimum-in-hold) each fail within 50 seeds with the script's assertion text. `TestRequiredMutations`: the script's ten source mutations as executor hooks (`decrement=false`, permit before Standby, blind desired reset, exit on timeout, ignored lock, and the rest of the list at `region_group_roll_test.py:2621`), each failing its named scenario. |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run 'TestRoll|TestSeeded|TestSimulationMutations|TestRequiredMutations'` — FAIL. |
| +- [ ] **Step 3: Implement** the script's `Operator` paths for roll in Go, decision execution only in `resume` and `returnMember` loops. |
| +- [ ] **Step 4: Run** — PASS; then once: `GROUPROLL_SIM_SEEDS=3000 go test ./internal/grouproll -run TestSeededSimulation` and record wall time and coverage in the commit body. |
| +- [ ] **Step 5: Commit** `grouproll: roll, resume, return and rollback with the seeded simulation`. |
| + |
| +### Task 8: The floor and the SHA mapping |
| + |
| +Starts only after `held-floor-sha-map` merges (stopping rule 4). |
| + |
| +**Files:** |
| +- Create: `internal/release/systemlookup.go`; `internal/grouproll/floor.go` |
| +- Test: `internal/release/systemlookup_test.go`, `internal/grouproll/floor_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `func ReleaseForArtifact(ctx, store Store, pub ed25519.PublicKey, channels []string, platform, sha string) (version string, err error)` in `internal/release` (errors: `ErrUnknownArtifact`, `ErrAmbiguousArtifact`, verification errors from `GetSystemPointer`); `func (e *Engine) Floor(ctx, kind string, version string) (rule string, err error)`. |
| + |
| +- [ ] **Step 1: Failing tests.** `TestReleaseForArtifactGolden` with `scripts/testdata/router-pointer-golden.json` and `.pub`: Current hit, History hit, unknown, two versions, scoped key, wrong channel. Port every floor test of `region_group_held_test.py` (`floor_*`, `release_*`), including: unreadable edges file → refuse (`floor_error`), never DR-4; stale edges file ignored; `ha_take` absent → DR-4 reason; SHA pin below floor; `roll --to-sha256` mapped release differs from prepare's `version` → `release_mismatch`. |
| +- [ ] **Step 2: Run** `go test ./internal/release -run TestReleaseForArtifact && go test ./internal/grouproll -run TestFloor` — FAIL. |
| +- [ ] **Step 3: Implement**; the floor reads edges files and pointers through `release.Store` on the config's buckets. |
| +- [ ] **Step 4: Run** — PASS. **Commit** `grouproll: the held-requests floor from signed release pointers`. |
| + |
| +### Task 9: Replace, remove and cancel-drain |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/depart.go` (start, depart, drain, pre-action, lock sweep, edge stop, stop-and-terminate, watch, summary, cancel-drain, `check_remove`) |
| +- Test: `internal/grouproll/depart_test.go`; extend `sim_test.go`, `mutation_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Tasks 1-8. |
| +- Produces: `func (e *Engine) Depart(ctx, iid, kind, tx string) error` (`kind` is `replace` or `remove`), `func (e *Engine) CancelDrain(ctx, iid, tx string) error`. |
| + |
| +- [ ] **Step 1: Failing tests.** Port every depart test of `region_group_held_test.py`. Extend the simulation with replace and remove runs (`TestSeededDepartSimulation`) and audits: desired never lowered except by Park of the header iid; `Terminate` only after a `drained` row of this transaction, a `pre-action-checked` row, an `edge-stopped` row with `MainPID=0`, and an empty second sweep; `Unpark` of a failed drain only when the last status showed `drain.state=known` and no running move. Mutants that must fail: terminate with decrement; terminate before edge stop; skip the second sweep; unpark on unknown drain status; restore desired before the terminate check. |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run 'TestDepart|TestCancelDrain|TestSeededDepart|TestDepartMutations'` — FAIL. |
| +- [ ] **Step 3: Implement** from the script, `terminate_decision` driving every post-intent pass. |
| +- [ ] **Step 4: Run** — PASS; one 3,000-seed depart run recorded in the commit body. |
| +- [ ] **Step 5: Commit** `grouproll: replace, remove and cancel-drain`. |
| + |
| +### Task 10: The probe |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/probe.go`; Test: `internal/grouproll/probe_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `func (e *Engine) Probe(ctx, iid string) error`, `func (e *Engine) ProbeResume(ctx, tx string) error`; journal kind `probe`. |
| + |
| +- [ ] **Step 1: Failing tests:** port all `region_group_probe_test.py` tests (status-only sessions, `read_only` refusal for any other verb, the member's own instance row overriding membership, `unchanged`). |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run TestProbe` — FAIL. **Step 3: Implement** as a wrapper over `Group` and `Box` that refuses writes outside the probe's set. **Step 4: Run** — PASS. **Step 5: Commit** `grouproll: the Standby observation probe`. |
| + |
| +### Task 11: The claim and its policy statement |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/claim.go`; Modify: `internal/grouproll/state.go` (take before `Create`, release after `Finish`), `system_group.go` (`claim-release`) |
| +- Modify: `infra/modules/region-host/group_operator.tf` (statement `GroupMaintenanceClaim`), `infra/modules/region-host/tests/group_operator.tftest.hcl` |
| +- Test: `internal/grouproll/claim_test.go`, `claim_minio_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: `func TakeClaim(ctx, st release.Store, c Config, tx, attendedBy, machine string) (etag string, err error)`, `func ReleaseClaim(ctx, st release.Store, c Config, etag, outcome string) error`, `func ForceReleaseAtRest(ctx, e *Engine, tx string) error`; key `control/group-maintenance/<hex(sha256(group_arn))[:32]>.json`. |
| + |
| +- [ ] **Step 1: Failing tests.** `TestClaimRace` (Review Focus 3: two goroutines take on an absent key; exactly one wins, the loser refuses `busy` and has written no journal). `TestClaimLifecycle`: absent → open → closed → open again with `If-Match`. `TestClaimLostRelease`: release PUT fails; the next verb on the same machine closes it first. `TestClaimForeignOpen` refuses with holder, machine and time. `TestForceReleaseAtRest`: refused when any member is not `Serving`, unhealthy, has a permit or a fence, or `min/desired/max` differ; allowed otherwise, and the forced row names the operator. `TestClaimNeverDeletes` (the fake store fails on any Delete). The MinIO variant runs under `CARLOS_MINIO_TEST=1`. The tftest asserts the exact statement: `s3:GetObject` and `s3:PutObject` on exactly `arn:<partition>:s3:::<deployment bucket>/control/group-maintenance/<hex(sha256(group_arn))[:32]>.json` (computed in tofu with `sha256()` and `substr()`), no wildcard, and nothing else in the statement. |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run TestClaim -run TestForceRelease` — FAIL. |
| +- [ ] **Step 3: Implement** with `release.Store.Put(ctx, key, body, ifMatch)` (`""` = create-only) and `ErrCASConflict` → `busy`. |
| +- [ ] **Step 4: Run** — PASS; `tofu test` in `infra/modules/region-host` with OpenTofu 1.13.9 if available, else say so in the commit body. |
| +- [ ] **Step 5: Commit** `grouproll: a claim in the deployment bucket serializes machines`. |
| + |
| +### Task 12: The parity ledger, the boundary and integration |
| + |
| +**Files:** |
| +- Create: `internal/grouproll/testdata/parity-ledger.tsv`, `internal/grouproll/parity_test.go`, `internal/grouproll/integration_minio_test.go` |
| +- Modify: `region_ha_boundary_test.go` (core files listed), `internal/provision/region_group_guards_test.go` (run `region_group_document_test.py` also against the Go builder through a small `go run` shim) |
| + |
| +- [ ] **Step 1: Failing tests.** `TestParityLedgerComplete`: parse `def test_` names from the three Python files; every name has a ledger row; every Go test a row names exists in the package (`go test -list`). `TestCoreHasNoAWS` is the existing boundary test with the new files. `TestEndToEndNoAWSEnvironment`: with every `AWS_*` unset, `plan`, `roll`, `replace` and `remove` run to completion against the fake `Group` and `Box` and MinIO (edges files, locks, pointers, claim). |
| +- [ ] **Step 2: Run** `go test ./internal/grouproll -run 'TestParity|TestEndToEnd' && go test . -run TestRegionHACoreImportsNoAWS` — FAIL until the ledger is filled. |
| +- [ ] **Step 3: Fill the ledger**; each "does not apply" row carries a reason tied to a V-row of spec §7. |
| +- [ ] **Step 4: Run** — PASS. **Commit** `grouproll: parity ledger, boundary and MinIO end to end`. |
| + |
| +### Task 13: Copy review and the runbook |
| + |
| +- [ ] **Step 1:** Extract every string in `internal/grouproll/text.go` plus the CLI usage text; run the copy-review skill; apply Paul's edits verbatim. Add the strings V1, V6 and §8 need (root refused, on a box, Windows, claim holder, claim forced) through the same review. |
| +- [ ] **Step 2:** The runbook page for `carlos system group` (from the §25 runbook branch if merged, else a new `docs/site` page), through the same review. |
| +- [ ] **Step 3:** `go test ./internal/grouproll ./ -run 'Text|Usage'` — PASS (golden usage output updated). **Commit** `grouproll: reviewed operator copy and runbook`. |
| + |
| +### Task 14: Branch review, census and merge B |
| + |
| +- [ ] **Step 1:** Full local suite once: `go test ./...` (scratch under `$TMPDIR`), both cross-compiles. |
| +- [ ] **Step 2:** Whole-branch review, Astra (`codex exec -m gpt-6-astra -c model_reasoning_effort="high" … < /dev/null`), brief from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, max three rounds; Fable as the second reader on Tasks 7, 9 and 11 (termination and the claim). |
| +- [ ] **Step 3:** `make census-card`, `make census-propose NAME=group-roll-verb CLAIMS=…`, the other-family reviewer's verdict on #280. |
| +- [ ] **Step 4:** Re-merge main, CI green on the tip, `amadan branch merge carlos/platform <branch> -expect <full sha> -squash -message "$(cat msgfile)"`. The verb is inert; release, the claim statement's apply and the witnesses are Paul's steps. |
| + |
| +### After merge (not tasks of this plan; each needs Paul's go) |
| + |
| +1. A release; apply the operator policy (claim statement) on dev, then flagship. |
| +2. Dev parity witnesses (spec §11 step 4): W1, W2, W4 (with the refused remove), one probe, one `cancel-drain` after a forced drain failure, from an operator machine other than the operator host. Compare journals and summaries with the script's runs. |
| +3. Retirement branch: delete `scripts/region-group-roll.py`, `scripts/region-group-probe.py`, `region_group_roll_test.py`, `region_group_held_test.py`, `region_group_probe_test.py`; point the document test at the Go builder only; update the runbook. |
diff --git a/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md b/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md| new file mode 100644 |
| index 000000000..8fc1aa06c |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-09-group-roll-verb-design.md |
| @@ -0,0 +1,471 @@ |
| +# `carlos system group`: the roll tool as a carlos verb (design, rev 1, 2026-11-09) |
| + |
| +**Asked by:** Paul, 2026-11-09, via agent manager 8a3d302: a spec for porting |
| +`scripts/region-group-roll.py` into the `carlos` binary. |
| +**Status:** design for Paul's approval. Nothing is built. |
| +**Review budget:** at most three Astra rounds on this spec and three on its plan |
| +(AGENTS.md stopping rules). A round with no P1 ends the review. A fault family |
| +found twice is cut or turned into an invariant, not fixed a third time. |
| + |
| +Line citations are to `origin/main` at `eed714da` unless they name a branch. |
| + |
| +## 1. Why |
| + |
| +The roll tool is the only way to roll, replace, resize or scale in a group |
| +member without dropping requests (region HA spec §25). Today it is: |
| + |
| +- about 2,400 lines of Python (`scripts/region-group-roll.py`) plus a 200-line |
| + probe (`scripts/region-group-probe.py`), copied onto the operator host from a |
| + git ref; |
| +- outside the census (`AGENTS.md:316-318`: `scripts/` is out), so the code that |
| + enters Standby, terminates members and stops edges is the least reviewed code |
| + on the path; |
| +- AWS-only in its structure: it shells out to the `aws` CLI and the Session |
| + Manager plugin, and its decider speaks Auto Scaling lifecycle states; |
| +- demanding on the host: euid 0, a root-owned 0700 state directory, `/root/.cache`, |
| + python3, the AWS CLI v2, the Session Manager plugin and, since branch |
| + `held-floor-sha-map`, `python3-cryptography` |
| + (`~/.cache/region-ha-held/REPORT.md`, witness window 1). |
| + |
| +Only half the CI runs it: `TestRegionGroupHeldPythonGuards` |
| +(`internal/provision/region_group_guards_test.go:218`) runs the held and |
| +document tests; the roll, probe and fault suites run in no CI job. |
| + |
| +## 2. What this spec decides |
| + |
| +| # | Decision | Section | |
| +|---|---|---| |
| +| D1 | Verb shape: `carlos system group <verb>`, one leaf per Python subcommand, plus `probe` and `claim-release`. | §3 | |
| +| D2 | Where it runs: any operator machine (Linux or macOS), never as root, never on a carlos box, never through the console. | §4 | |
| +| D3 | What it needs: an AWS profile with the existing operator policy (plus two statements), and the Session Manager plugin. No root, no python, no AWS CLI, no cryptography package. | §4 | |
| +| D4 | A provider-neutral engine (`internal/grouproll`) with an AWS adapter (`internal/grouprollaws`). | §5 | |
| +| D5 | Exact behaviour parity, with the deliberate deviations listed in one table. | §6, §7 | |
| +| D6 | Cross-host serialization: a claim object in the deployment bucket replaces "everyone uses the one root host". | §8 | |
| +| D7 | The floor reads signed release records through `internal/release`; no SHA or version is guessed. | §9 | |
| +| D8 | Parity proof: golden decider fixtures, a Go port of the seeded simulation and mutations, byte-identical remote commands, and a test-by-test parity ledger. | §10 | |
| +| D9 | Rollout: W1-W5 run with the Python tool as planned; the Go verb then repeats W1, W2 and W4 on dev; then the script is deleted. | §11 | |
| +| D10 | W6 (fixed-edge restart gap) is a separate small spec. | §12 | |
| + |
| +## 3. Verb shape (D1) |
| + |
| +The operator verb sits under the existing operator branch `carlos system group` |
| +(`system_roles.go:123`, which today holds only `group role`). It is not the box |
| +verb `carlos system group-maintenance` (`system.go:62`), which stays as it is: |
| +the new verb calls it over Session Manager exactly as the script does. |
| + |
| +``` |
| +carlos system group plan --config F --member I --to-sha256 S |
| +carlos system group roll --config F --member I --to-sha256 S [--transaction T] |
| +carlos system group replace --config F --member I [--transaction T] |
| +carlos system group remove --config F --member I [--transaction T] |
| +carlos system group rollback --config F --member I --transaction T |
| +carlos system group resume --config F --transaction T |
| +carlos system group return --config F --transaction T |
| +carlos system group status --config F --transaction T |
| +carlos system group abandon --config F --transaction T |
| +carlos system group close-lost --config F --transaction T |
| +carlos system group cancel-drain --config F --member I --transaction T |
| +carlos system group probe --config F --member I | resume --transaction T (the probe's verbs) |
| +carlos system group claim-release --config F --transaction T [--at-rest] |
| +``` |
| + |
| +Every verb takes `--attended-by NAME` as the script does (required when stdin is |
| +not a terminal). Flags only; positional arguments are refused, so the |
| +flags-after-positionals trap of `cli-default-console-flagship` cannot arise. |
| + |
| +- **No console, no default deployment.** `--config` is required. The verb never |
| + opens a console session, never reads the CLI's saved login, and never falls |
| + back to `console.carloku.com`. The deployment, account, region and group come |
| + only from the config file, and every AWS read is checked against them as |
| + today (`snapshot`, `region-group-roll.py:1216-1225`). |
| +- **The config file is the script's config file.** The same JSON keys, the same |
| + validation (`validate_config`, `:506-545`, plus the `held-floor-sha-map` |
| + keys `release_public_key`, `release_channels`, `release_platform`), so one file |
| + serves both tools during the overlap (§11). No key is added: the claim key |
| + is derived from the group ARN (§8). |
| +- **Exit codes and output** follow the script: 0 on success, 1 on a refusal with |
| + `Refused: <reason>` on stderr, phase lines `phase: detail` on stdout, the JSON |
| + drain summary line, and `status` printing the saved transaction as one JSON |
| + object. The operator strings are the script's `TEXT` table, ported verbatim |
| + into one Go table; they go through copy review once, in the plan's copy task, |
| + before the release that ships the verb (the script's copy pass was never run: |
| + "the controller owns the final copy pass", `:100`). |
| + |
| +## 4. Where it runs and what it needs (D2, D3) |
| + |
| +**Any operator machine, never root.** The verb refuses `euid == 0` up front. |
| +Reasons: |
| +- root is not needed: the script needed root only because its shared state |
| + directory had to be tamper-proof against the other operators on one host |
| + (`State.__init__`, `:615-640`). A per-user state directory under the |
| + operator's own account (§8) plus the claim gives the same guarantee without it; |
| +- `internal/rootaws` refuses shared profiles to root (`config.go:52-53`), and |
| + this verb is profile-driven, so root would need a second credential path; |
| +- it keeps the census disposition simple: root on a box never runs this code. |
| + |
| +**Never on a carlos box.** The verb refuses when `/etc/carlos/host.env` exists or |
| +the process runs under the `carlos` user. A box's role has no Auto Scaling |
| +write right (§12.2 of the region HA spec), and the tool must never be the box it |
| +is maintaining. |
| + |
| +**Not the console.** Running it in the console would put Auto Scaling, EC2 and |
| +Session Manager write rights on the console's role, make an attended operation |
| +unattended, and couple the flagship console to every region's maintenance. |
| +A console button can come later by calling the same engine with an adapter |
| +that runs in a separate operator context; it is not in this spec. |
| + |
| +**Platforms.** linux/amd64, linux/arm64, darwin/arm64, darwin/amd64. On Windows |
| +every verb refuses ("not supported on this system"): the session transport needs |
| +a pseudo-terminal (§5.3). Files that use Linux or Darwin calls carry build tags |
| +with a `_other.go` sibling, per the cross-compile gate. |
| + |
| +**What it needs on the machine:** |
| +1. **An AWS profile** named in the config's `profile` key, carrying the operator |
| + policy output `group_operator_policy_json` (`infra/modules/region-host/group_operator.tf`) |
| + plus the two statements in §8 and §9. The verb builds its credentials from that |
| + named shared profile only: ambient `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`/ |
| + `AWS_SESSION_TOKEN`, `AWS_PROFILE`, `AWS_DEFAULT_PROFILE` and every |
| + `AWS_ENDPOINT_URL*` are ignored, and the instance metadata service is disabled |
| + (the script's `invoke`, `:786-797`, does the same to the CLI). |
| + `AWS_CONFIG_FILE`, `AWS_SHARED_CREDENTIALS_FILE` and `AWS_CA_BUNDLE` are honoured, |
| + as today. SSO and `credential_process` profiles work, since the verb never runs |
| + as root. |
| +2. **The Session Manager plugin** (`session-manager-plugin`) on `PATH`. This is the |
| + one external program, and it belongs to the AWS adapter. §5.3 says why it |
| + stays. |
| +3. Nothing else: no python, no AWS CLI, no `python3-cryptography`, no `/root/.cache`, |
| + no `/var/lib/carlos-group-roll`. |
| + |
| +## 5. The provider boundary (D4) |
| + |
| +### 5.1 Core and adapters |
| + |
| +| Core (`internal/grouproll`, imports no AWS SDK) | AWS adapter (`internal/grouprollaws`) | |
| +|---|---| |
| +| The journal, the local lock, the transaction lifecycle (create, load, finish) | Describe the group: members and their lifecycle states, health, minimum, desired, maximum, launch template, target groups, tags | |
| +| The claim (§8), over `release.Store` (S3 or any S3-compatible store with conditional writes) | Target health in each target group | |
| +| `Classify` (the script's `classify()`) and `TerminateDecision` (`terminate_decision()`) | Lower or raise minimum; raise desired (H4: never lower) | |
| +| Preflight shape rules, readiness, identity, permit and process checks over box status | Park a member: `EnterStandby` with decrement; unpark: `ExitStandby` | |
| +| The floor: edges files, `ha_take`, the pinned and the prepared release (§9) | Terminate a parked member without decrement | |
| +| The drain, the H5 pre-action check, the lock sweep (S3-compatible reads of the data bucket) | Scaling activities for one member, classified enter, exit or terminate | |
| +| The depart watch and its reports | The lifecycle hook description; whether a member is online for sessions; whether an instance is gone | |
| +| The box-verb protocol: the framed remote command and parsing its output | Running one framed remote command on one member (Session Manager) | |
| +| All operator text | The release the pinned launch template boots (user data `CARLOS_RELEASE`) | |
| + |
| +The engine talks to two interfaces, `Group` (the left column of provider calls, |
| +in provider-neutral terms) and `Box` (run one box verb on one member, return its |
| +framed output). Object-store reads (edges files, locks, release pointers, the |
| +claim) are core and go through `release.Store`, so MinIO works as it does |
| +everywhere else. |
| + |
| +### 5.2 Provider-neutral member phases |
| + |
| +The script's decider reads raw Auto Scaling states. The core instead reads a |
| +`Phase`, and the adapter maps each Auto Scaling `LifecycleState` to exactly one: |
| + |
| +| Phase | Auto Scaling states | Where `classify` distinguishes it | |
| +|---|---|---| |
| +| `Serving` | `InService` | everywhere | |
| +| `Parking` | `EnteringStandby` | Standby waits | |
| +| `Parked` | `Standby` | Standby branches | |
| +| `Returning` | `Pending`, `PreInService`, `Pending:Proceed` | wait (`:350-351`); all three are always treated alike | |
| +| `ReturnHeld` | `Pending:Wait` | provider divergence (`:281-282`) | |
| +| `Leaving` | every `Terminat*` state | lost member (`:286`, `:396`) | |
| +| `Absent` | not in the group | lost member | |
| +| `Unknown` | anything else (warm pools, detach, and so on) | `unknown_phase` failure (`:288-290`) | |
| + |
| +The table is total and lossless for every distinction `classify()` and |
| +`terminate_decision()` make; the golden fixtures (§10.1) carry raw states and go |
| +through the adapter's mapping before the Go decider, so a lossy mapping fails them. |
| +The journal records the raw provider state beside the phase, for operators. |
| + |
| +### 5.3 The Session Manager transport |
| + |
| +The adapter calls `ssm:StartSession` itself through the SDK with the approved |
| +document and the framed command, then runs `session-manager-plugin` with the |
| +returned session (the same invocation the AWS CLI makes), on a pseudo-terminal, |
| +reading output until the frame or the bound. It keeps the script's behaviour |
| +(`session_output`, `:733-784`): a 4 MiB output cap, session-id capture for |
| +`TerminateSession` after a cut, the plugin's process group killed at the bound, |
| +and the per-verb local bounds (`SESSION_TIMEOUTS`, `:228-230`). |
| + |
| +Considered and rejected: |
| +- **Run Command (`ssm:SendCommand`).** No plugin, and a command id that survives a |
| + client cut. But it needs a new Command-type document, new IAM and a census |
| + change; `GetCommandInvocation` truncates output at 24,000 characters, which a |
| + drain report moving a few hundred hosts exceeds (its `moved` list, |
| + `internal/host/hadrain.go:124-146`); and the interruption behaviour the cards |
| + verified live is the session transport's. A transport change is its own spec. |
| +- **Speaking the session protocol in Go.** The data-channel protocol is |
| + undocumented; reimplementing it to drop one AWS binary is not worth the risk. |
| + |
| +The pseudo-terminal is opened with `golang.org/x/sys/unix` (already in `go.mod`): |
| +`/dev/ptmx` with `TIOCSPTLCK` on Linux, `posix_openpt` semantics on Darwin. |
| + |
| +### 5.4 What a deployment without AWS gets |
| + |
| +A group is AWS-only today (H26; region HA spec §12.5), so every verb refuses |
| +on a config without an AWS group ARN, naming the missing adapter. A future |
| +provider implements `Group` and `Box`; the engine, the deciders, the simulation |
| +and the parity ledger run unchanged against its fake. A self-hosted fleet on AWS |
| +(Tito) uses the AWS adapter with its own profile and config. |
| + |
| +Enforcement: the new core files go into `regionHACoreFiles` |
| +(`region_ha_boundary_test.go:21-44`) so `TestRegionHACoreImportsNoAWS` covers |
| +them, and a test runs `plan`, `roll`, `replace` and `remove` end to end against |
| +the fake provider with no AWS configuration in the environment. |
| + |
| +## 6. Behaviour parity (D5) |
| + |
| +The Go verb does what the script does, decision for decision. In particular: |
| + |
| +- **One serialized transaction per group.** The group directory is keyed by |
| + `sha256(group_arn)[:32]` (`:627`); one `active.json` names the open transaction; |
| + a non-blocking exclusive lock guards every writing verb (`State.lock`, `:642-654`); |
| + `status` stays lock-free and read-only. The claim (§8) adds cross-host |
| + serialization on top; it replaces nothing. |
| +- **The journal.** Append-only, one fsynced JSON object per line, hash-chained |
| + (`seq`, `previous`, `hash`), refusing on any gap, duplicate key, non-finite |
| + number or bad hash (`Journal`, `:566-611`). Every provider call writes an |
| + `intent` before it and a `response` or `error` after it, with `dispatched` |
| + evidence (`Operator.call`, `:1170-1211`). Rows keep the script's kinds and fields. |
| +- **One decider each.** `Classify` owns every return and resume decision and |
| + `TerminateDecision` every post-intent terminate decision; the engine only |
| + executes their decisions. Only the return executor sends `ExitStandby`. |
| +- **Fail closed.** No `CompleteLifecycleAction`, no `ABANDON`, never raises desired |
| + except the replace's final restore, never restores minimum in a hold, never |
| + replays a consumed box action, never terminates except a drained, edge-stopped, |
| + lock-free parked member. `Pending:Wait` after `ExitStandby` writes |
| + `provider-divergence.json`, alerts and blocks further rolls. A terminated or |
| + replaced member is FAIL. |
| +- **H4.** Desired is lowered only by the member's own `EnterStandby` with decrement |
| + (`Operator.call`, `:1171-1174`; the adapter's own guard, `:953`), terminate runs |
| + only with `decrement=false` against a `Standby` member when `desired == minimum` |
| + (`:1033-1036`), and raising desired is bounded by `desired <= value <= maximum` |
| + (`:1045-1046`). |
| +- **Drain first and the r2 uncertain-drain cut.** After a failed drain the member |
| + leaves Standby only when its status proves no move of this transaction runs |
| + (`refuse_while_moving`, `:1819-1838`); unknown status keeps it in Standby for |
| + `cancel-drain` then `return`. Three drain sessions per transaction; exit 124 is |
| + uncertain; a rerun joins the move. |
| +- **H5 and the retained fence.** Immediately before the action: the lock sweep, the |
| + fence of this transaction, the drain of this transaction finished `ok`, and the |
| + incarnation unchanged (`pre_action`, `:2006-2027`). Replace and remove then stop |
| + `carlos-edge.service`, prove `MainPID=0`, sweep the locks again, and terminate |
| + (`stop_and_terminate`, `:2169-2182`). |
| +- **The floor and DR-4.** `roll` drains only when the floor holds and says which |
| + rule applied; `replace` and `remove` refuse below the floor; a floor that cannot |
| + be read refuses and never falls back to DR-4 (§9). |
| +- **The same bounds:** `WAIT` 900 s, `DRAIN_TRIES` 3, `DRAIN_BOUND` 3600 s, edge stop |
| + 120 s, cancel 300 s, `TERMINATE_RETRIES` 2, settle 120 s, pending 600 s, the 5 s |
| + freshness window on `ExitStandby`, the 60 s readiness age, the 2 s publication |
| + margin, `EDGES_MAX_AGE` 15 min and `EDGES_SKEW` 60 s. |
| +- **The same remote commands.** The framed command string for every box verb is |
| + byte-identical to `AWS.remote_command` (`:824-867`), because the session |
| + document's `allowedPattern` (`infra/modules/region-group-operator-document/tool-pattern.txt`) |
| + admits exactly those strings. No document change. |
| + |
| +**How it fits T1 and DR-5.** Nothing changes in either, and the verb relies on both |
| +as the script does: |
| +- T1 (§9.9) is the backstop, not the mechanism: by the time a replace or remove |
| + terminates the member, the drain has left no lease naming it and the edge is |
| + already stopped, so T1's shutdown release has nothing to write. A roll's `apply` |
| + restarts the edge behind the fence, and T1 orders that stop. |
| +- The DR-4 variant (`ha-graceful-terminate`: deregister a pre-T1 member before |
| + terminating) is built in: a parked member is deregistered from both target |
| + groups before anything else runs, and the tool verifies it. |
| +- DR-5 (§7.5) finishes the departure; the watch waits for the member's edges file |
| + to disappear within `WAIT`. `remove` refuses up front when the survivors would |
| + leave a pool the member serves without a server (`check_remove`, `:2081-2093`), |
| + so a planned path never relies on DR-5's unserved discharge. |
| + |
| +## 7. Deliberate deviations |
| + |
| +Everything not in this table is parity, and the parity ledger (§10.4) holds the |
| +build to it. |
| + |
| +| # | Script | Go verb | Why | |
| +|---|---|---|---| |
| +| V1 | euid 0 required; root-owned state with root-owned ancestors | euid 0 refused; state owned by the invoking user, 0700, ancestors not group- or world-writable and owned by root or that user | §4 | |
| +| V2 | Serialization only among users of one host's state directory | The same local lock plus a claim object in the deployment bucket | §8 | |
| +| V3 | Journal rows hashed over Python's `json.dumps(sort_keys=True, separators=(",", ":"))`; times are Python floats | Journal format 2: a `"format": 2` header field, times as integer milliseconds, keys sorted, Go's canonical encoding defined in one function and pinned by golden bytes | Byte-identical float and escape formatting across languages is a trap; neither tool has to read the other's journals (§11) | |
| +| V4 | Refuses to adopt nothing: it cannot read a Go journal | Refuses any journal without `"format": 2` naming the script, and refuses to start while a script `active.json` exists in the same configured `state_dir` | §11 overlap | |
| +| V5 | SHA mapping verified with `python3-cryptography` (`held-floor-sha-map`) | `release.GetSystemPointer` (`internal/release/systempointer.go:259`), the code boxes use | §9 | |
| +| V6 | Refuses nothing about where it runs, beyond root | Refuses on a carlos box and on Windows | §4 | |
| +| V7 | `region-group-probe.py` is a separate script | `carlos system group probe` | Same engine; probe rules unchanged (read-only status sessions, the member's own `DescribeAutoScalingInstances` row overrides group membership) | |
| + |
| +Not deviations, recorded so nobody "fixes" them in the port: the drain-rerun |
| +backoff and the TakeHost `wake_timeout` follow-ups from the held build stay |
| +follow-ups; `check-region-group-plan.py` (the tofu plan gate), the fault harness |
| +(`scripts/region-group-fault/`) and the boot witnesses stay Python; the |
| +observation file `provider-observation.json` is still placed by the controller, |
| +not written by `probe`. |
| + |
| +## 8. The claim: one transaction per group across machines (D6) |
| + |
| +The script serializes operators only if they all use one state directory on one |
| +host. A verb that runs on any operator machine needs a shared fact. The core |
| +already assumes an object store with conditional writes, so: |
| + |
| +- **Key:** `control/group-maintenance/<sha256(group_arn)[:32]>.json` in the |
| + deployment bucket (the config's `bucket`). No box reads or writes it. |
| +- **Body:** `{v:1, group_arn, state: "open"|"closed", transaction, attended_by, |
| + machine, opened_at, closed_at, outcome}`. |
| +- **Take** (before `create` writes the journal's first row): GET the key. Absent: |
| + PUT with `If-None-Match: *`. `closed`: PUT with `If-Match` on its ETag. `open` |
| + with this transaction and a local journal for it: already ours. Anything else |
| + refuses with who holds it, from which machine, since when. A lost race |
| + (`release.ErrCASConflict`) refuses as busy. |
| +- **Release:** when the transaction finishes (`State.finish`), PUT `closed` with the |
| + outcome, `If-Match` on the ETag the take returned. The local finish comes first. |
| + A release that fails leaves the claim `open`; the next verb on this machine for |
| + this group sees its own finished transaction and closes it before anything else. |
| +- **No delete.** The store's IAM denies `s3:DeleteObject` in places |
| + (`lease-deleteobject-outage`); the claim is only ever overwritten. |
| +- **Lost machine.** A claim whose machine is gone blocks the group, fail closed. |
| + `claim-release --transaction T --at-rest` closes it from another machine only when |
| + a fresh describe shows the group at rest: `min = desired = max = N`, every member |
| + `Serving`, healthy in both target groups, and every member's box status showing |
| + no permit and no fence. The release row records who forced it. Without |
| + `--at-rest`, `claim-release` closes only a claim whose transaction this machine's |
| + journal has finished. |
| +- **`plan` and `status` take no claim.** `plan` reads the claim and reports it as a |
| + refusal when it is open. |
| +- **IAM:** one new operator policy statement, `GroupMaintenanceClaim`: |
| + `s3:GetObject` and `s3:PutObject` on exactly that key. Census: an infra change on |
| + a card. |
| +- **Request budget:** two GETs and two PUTs per transaction, none on a timer. |
| + |
| +## 9. The floor from signed release records (D7) |
| + |
| +The floor (§25.9) compares two releases with `ha_floor`: the one the pinned launch |
| +template boots (replace) and the one a roll leaves running. Both can be pinned by |
| +SHA-256. The verb never guesses a version from a SHA or a SHA from a version: |
| + |
| +- **The pinned template's release.** The adapter reads the template's user data |
| + and returns `CARLOS_RELEASE` exactly as the script does (`template_release`, |
| + `:1081-1100`). A `vX.Y.Z` value is compared directly |
| + (`release.ParseReleaseVersion`, `BelowFloor`; `internal/release/layoutintent.go:368,375`). |
| +- **A SHA-256 pin** is mapped through the deployment's signed router pointers, |
| + `control/system/router/<channel>.json` for each channel in `release_channels` |
| + (default `stable`), read and verified with `release.GetSystemPointer` under the |
| + config's `release_public_key`. The SHA must appear under `release_platform` |
| + (default `linux-arm64`) in exactly one release's `Current` or `History`; that |
| + release's `version` is compared. No key, an unreadable or unverified pointer, no |
| + match, two versions, or a version that is not `vX.Y.Z` refuses the transaction |
| + ("the floor could not be read"); it never falls back to DR-4. |
| +- **`roll --to-sha256`** is mapped the same way when `release_public_key` is set, and |
| + the mapped release must equal the `version` that `prepare` reports. |
| +- **The operator policy** already gains `ReadReleasePointers` on branch |
| + `held-floor-sha-map` (`group_operator.tf`); the verb needs nothing more. |
| + |
| +The reverse lookup (SHA to release across `Current` and `History`) is new Go code, |
| +a small exported function in `internal/release` beside `GetSystemPointer`, with the |
| +golden pointer from `held-floor-sha-map`'s `scripts/testdata/router-pointer-golden.json` |
| +as its fixture. |
| + |
| +**Dependency.** `held-floor-sha-map` is not merged. Stopping rule 4: the plan's floor |
| +task starts only after it merges, and its Python behaviour is then the parity |
| +target. If it changes on review, this section follows it. |
| + |
| +## 10. How parity is proven (D8) |
| + |
| +### 10.1 Golden decider fixtures |
| + |
| +- A recorder, run once from the plan, wraps the script's `classify` and |
| + `terminate_decision` while the whole Python suite runs (roll, held and probe |
| + tests, and the seeded simulation at 3,000 seeds). It writes every distinct |
| + `(facts, decision)` pair, with raw provider states, to |
| + `internal/grouproll/testdata/golden/{classify,terminate}.jsonl`. |
| +- The Go test maps each case's raw states through the adapter's phase table (§5.2) |
| + and asserts the Go decider returns the same action, reason and delay. |
| +- The terminate table's exhaustive grid (`test_every_combination`, more than 30,000 |
| + rows, `scripts/region_group_held_test.py:1214`) is ported with its oracle as a |
| + Go table test. |
| + |
| +### 10.2 The seeded simulation and mutations |
| + |
| +- The script's seeded return simulation (`Simulation`, |
| + `scripts/region_group_roll_test.py:2446-2576`: chaos at 12% response loss, up to |
| + three process deaths at 0.7% per boundary, a hook-or-not provider, the audits) |
| + is ported to Go against the Go fake provider. It is extended to the depart |
| + paths (replace and remove: drain failures, cut sessions, terminate activity |
| + outcomes, the watch), with the H4 and H5 audits: desired never lowered except by |
| + the member's Standby; no terminate without a finished drain of this transaction, |
| + a present fence, a stopped edge and an empty lock sweep. |
| +- CI runs 200 seeds; 3,000 seeds run once per implementation revision, as the |
| + region HA simulation does (`internal/sim/regionha/sim_test.go:15-42`). |
| +- The script's mutations (`test_simulation_mutations` and `test_ten_required_mutations`) |
| + become Go mutants injected as decider or executor functions, each of which must |
| + fail the simulation or its named scenario. The depart audits get their own |
| + mutants: terminate with decrement, terminate before the edge stop, skip the |
| + second lock sweep, exit Standby on unknown drain status. |
| + |
| +### 10.3 Byte-identical remote commands |
| + |
| +A golden file holds the script's `remote_command` output for every verb with fixed |
| +nonces and inputs. The Go builder must match it byte for byte, and every Go output |
| +must match `tool-pattern.txt`'s pattern. The document test keeps running in CI |
| +until the script is deleted, and then runs against the Go builder. |
| + |
| +### 10.4 The parity ledger |
| + |
| +`internal/grouproll/testdata/parity-ledger.tsv` lists every test in |
| +`region_group_roll_test.py`, `region_group_held_test.py` and |
| +`region_group_probe_test.py` (about 200), each mapped to the Go test that covers it |
| +or to a one-line reason it does not apply (for example, root-ownership checks that |
| +V1 replaces). A Go test fails when a Python test name is missing from the ledger |
| +or a named Go test does not exist. This is how "every fault test is ported" is |
| +checked rather than asserted. |
| + |
| +### 10.5 Integration |
| + |
| +The engine runs end to end in-process against MinIO (edges files, locks, release |
| +pointers and the claim) with a fake `Group` and a fake `Box` that runs the real |
| +`group-maintenance` status, drain and fence output shapes. The AWS adapter gets |
| +request-shape tests against the SDK's middleware stack (no network): the exact |
| +operations, the decrement flags and the group name on every write. |
| + |
| +## 11. Rollout and retirement (D9) |
| + |
| +1. **Do not wait for the port.** W1-W5 (§25.10) run with the script, as planned, once |
| + `held-floor-sha-map` merges and its IAM apply is done. They gate DR-4's |
| + retirement; the port does not. |
| +2. **Build and merge** the verb (the plan). It is inert: an operator verb nothing |
| + runs on its own. The census card covers its packages (they are in the root |
| + binary's dependency closure) and the operator policy's new claim statement. |
| +3. **Release.** Paul schedules it. The policy apply (claim statement) is a card step. |
| +4. **Parity witnesses on dev** with the Go verb, from an operator machine that is not |
| + the operator host: W1 (replace), W2 (roll) and W4 (remove, including the refused |
| + remove), on the same probe and pass bar as §25.10. Plus one probe and one |
| + `cancel-drain` after a forced drain failure. Their journals and drain summaries |
| + are compared with the script's W1, W2 and W4 runs: the same phases in the same |
| + order, the same provider writes, the same summary fields. |
| +5. **Overlap rule.** Until step 6 a card names one tool per group per window. Each tool |
| + fails closed on the other's state: the script refuses a format-2 journal named in |
| + `active.json` (it fails its hash check, "record"), and the Go verb refuses a script |
| + `active.json` (V4). The claim covers only the Go verb, so the card rule matters. |
| +6. **Retire the script.** One branch deletes `region-group-roll.py`, |
| + `region-group-probe.py` and their tests, moves the document test to the Go builder, |
| + repoints `TestRegionGroupHeldPythonGuards`, and updates the runbook to the verb. The |
| + golden fixtures stay in Go testdata. |
| + |
| +## 12. W6, the fixed-edge restart gap (D10) |
| + |
| +W6 found that a fixed edge in the region's target groups fails `lb-health` only after |
| +it has refused traffic, and is marked healthy before it is admitted (26 failed requests |
| +in 24 s on a restart of leo). It is a separate small spec. It is box-side (the edge's |
| +health answer and its stop order on fixed boxes), touches every restart of a fixed box, |
| +not just this tool's paths, and needs its own census and witness; the port is an |
| +operator-side parity change. Folding them together would put an edge behaviour change |
| +inside a "no behaviour change" review. The roll tool's paths are not affected: a group |
| +member is parked and deregistered before its edge stops. |
| + |
| +## 13. Open questions for Paul |
| + |
| +1. **The claim (§8).** Recommended: build it, since the verb runs anywhere. The cut: keep |
| + "one operator host per deployment" as a card rule, unenforced, as today. |
| +2. **Parity witnesses (§11 step 4).** Recommended: W1, W2 and W4 only, not all of W1-W5, |
| + because the script's runs already prove the box side. |
| +3. **Windows.** Recommended: refuse. Supporting it needs a ConPTY transport for one AWS |
| + plugin. |