carlos / platform Public

Merge main into code-health-ratchet

claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e582b8916069699233627de381fd8b24bd4793a3 parent 43dbb0bparent 295fe89
25 files changed, +1,194 −24
  • AGENTS.md +5 −3
  • apimode_test.go +56 −0
  • cli.go +27 −3
  • docs/superpowers/notes/census-proposal-audit-bugs-2.md +25 −0
  • docs/superpowers/plans/2026-11-16-go-code-health.md +287 −0
  • docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md +38 −0
  • docs/superpowers/reviews/FINDINGS-code-health-plan-R1.md +80 −0
  • docs/superpowers/reviews/FINDINGS-code-health-plan-R2.md +63 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md +48 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan-R2.md +71 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan.md +48 −0
  • internal/activator/escrow.go +25 −5
  • internal/activator/escrow_alert_test.go +91 −0
  • internal/console/apisubdomain.go +5 −1
  • internal/console/apisubdomain_test.go +43 −0
  • internal/console/ownership.go +8 −3
  • internal/console/store_test.go +26 −0
  • internal/host/haplacement.go +6 −1
  • internal/host/haplacement_wiring_test.go +22 −0
  • internal/ledger/verify.go +34 −0
  • internal/ledger/verify_test.go +38 −0
  • internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv +14 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • system.go +49 −8
  • system_test.go +84 −0

CI failed — run details

diff --git a/AGENTS.md b/AGENTS.md
index ad1456b00..b2f7d5299 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -300,9 +300,11 @@ anything.
into the CLI, which people run on Macs, so a Linux-only type assumption
breaks `go build .` for them. Cross-compiling is enough to catch it —
no Mac required.
-- Sandbox note: use `GOCACHE=/tmp/claude-1001/gocache GOFLAGS=-mod=mod
- GOPROXY=off`; go commands may need the sandbox disabled ("read-only file
- system" from the toolchain is the tell).
+- Sandbox note: leave `GOCACHE` at its default; the machine policy bans
+ pointing it anywhere else, `/tmp` above all. If the sandbox makes the
+ default cache read-only ("read-only file system" from the toolchain is
+ the tell), run the go command with the sandbox off. `GOFLAGS=-mod=mod
+ GOPROXY=off` still apply.
## Writing Go here (Paul, 2026-11-17)
diff --git a/apimode_test.go b/apimode_test.go
index 185a87ed3..e9ab975e2 100644
--- a/apimode_test.go
+++ b/apimode_test.go
@@ -2661,6 +2661,62 @@ func TestLedgerVerifyVerb(t *testing.T) {
}
}
+// TestLedgerVerifyRefusesEmptyHead: a status host that serves {} or null as
+// HEAD.json gets a refusal, not a "verified" line. Before the fix this
+// returned success with an empty head digest and the verb panicked slicing
+// it for display.
+func TestLedgerVerifyRefusesEmptyHead(t *testing.T) {
+ for _, body := range []string{`{}`, `null`} {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(body))
+ }))
+ res, err := verifyPublishedLedger(ts.URL+"/", "bab", "platform", "carbon")
+ ts.Close()
+ if err == nil {
+ t.Fatalf("HEAD %s verified: %+v", body, res)
+ }
+ if !strings.Contains(err.Error(), "HEAD malformed") {
+ t.Fatalf("HEAD %s: error = %v, want a malformed-HEAD refusal", body, err)
+ }
+ }
+ if got := short12("abc"); got != "abc" {
+ t.Fatalf("short12(abc) = %q", got)
+ }
+}
+
+// TestLedgerVerifyIsBounded: a status host that accepts the request and never
+// answers fails the walk within ledgerVerifyTimeout instead of hanging the
+// command. The old verb used http.DefaultClient, which has no timeout.
+func TestLedgerVerifyIsBounded(t *testing.T) {
+ hold := make(chan struct{})
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-hold:
+ case <-r.Context().Done():
+ }
+ }))
+ defer ts.Close()
+ defer close(hold)
+
+ old := ledgerVerifyTimeout
+ ledgerVerifyTimeout = 200 * time.Millisecond
+ defer func() { ledgerVerifyTimeout = old }()
+
+ done := make(chan error, 1)
+ go func() {
+ _, err := verifyPublishedLedger(ts.URL, "bab", "platform", "carbon")
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err == nil {
+ t.Fatal("a status host that never answered verified")
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("ledger verify still waiting on a silent status host after 10s")
+ }
+}
+
// ---- Task 3: config client methods (configGet/configApply/configSync) ----
// TestAPISessionConfigGetFullShape pins configGet's decode of the full wire
diff --git a/cli.go b/cli.go
index c9a63816c..26f6018cd 100644
--- a/cli.go
+++ b/cli.go
@@ -3824,12 +3824,36 @@ func runLedgerVerify(args []string) {
log.Fatalf("ledger verify: invalid ledger name %q", name)
}
- g := ledger.HTTPGetter(http.DefaultClient, strings.TrimRight(*urlBase, "/"))
- res, err := ledger.Verify(context.Background(), g, *account, *app, name)
+ res, err := verifyPublishedLedger(*urlBase, *account, *app, name)
if err != nil {
log.Fatal(err)
}
- fmt.Fprintf(stdout, "%s %d entries, head %s\n", colorFor(stdout).ok("verified:"), res.Count, res.HeadSHA256[:12])
+ fmt.Fprintf(stdout, "%s %d entries, head %s\n", colorFor(stdout).ok("verified:"), res.Count, short12(res.HeadSHA256))
+}
+
+// ledgerVerifyTimeout bounds each GET of a `carlos ledger verify` walk, the
+// header wait and the body together. Every object is a HEAD or one entry of
+// at most ledger.MaxBlob, so 30 s is generous; without it a status host that
+// accepts the connection and never answers hangs the command for good.
+var ledgerVerifyTimeout = 30 * time.Second
+
+// verifyPublishedLedger walks a published ledger over plain HTTPS with a
+// bounded client. The public status host needs no credential, so this is
+// a client of its own rather than a console session's.
+func verifyPublishedLedger(urlBase, account, app, name string) (ledger.VerifyResult, error) {
+ client := &http.Client{Timeout: ledgerVerifyTimeout}
+ g := ledger.HTTPGetter(client, strings.TrimRight(urlBase, "/"))
+ return ledger.Verify(context.Background(), g, account, app, name)
+}
+
+// short12 is the first 12 characters of a digest for display, or the whole
+// string when it is shorter: a display helper must never panic on a value a
+// remote server supplied.
+func short12(s string) string {
+ if len(s) > 12 {
+ return s[:12]
+ }
+ return s
}
// defaultGrantTTL is how long a scoped key lives when the operator does not
diff --git a/docs/superpowers/notes/census-proposal-audit-bugs-2.md b/docs/superpowers/notes/census-proposal-audit-bugs-2.md
new file mode 100644
index 000000000..0e0891548
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-audit-bugs-2.md
@@ -0,0 +1,25 @@
+# Census approval: audit-bugs-2
+
+Ruling `census-ruling-audit-bugs-2`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/escrow.go` `ExecBackend.EscrowSweep` | body | unchanged (31) | a failed publish is logged as an alert when isEscrowAlert (errors.As on the new escrowAlert type) says so, instead of strings.HasPrefix(err.Error(), "ALERT: "), so a joined or wrapped alert is logged plainly rather than once an hour as a routine failure; logging only, no new read |
+| `internal/activator/escrow.go` `ExecBackend.escrowConflict` | body | unchanged (1) | the refusal is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same Lstat, no new read |
+| `internal/activator/escrow.go` `ExecBackend.escrowConflictFound` | body | unchanged (4) | the alert is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same marker write, no new read |
+| `internal/activator/escrow.go` `ExecBackend.escrowedLaunchEnv` | body | unchanged (40) | the publish's alert branch matches isEscrowAlert(err) (errors.As) instead of the "ALERT: " prefix, so a joined or wrapped alert also refuses the launch as an alert; a joined alert was already refused via errEscrowUnreadable; only refuses, no new read |
+
+Envelopes re-pinned: `.`, `internal/activator`, `internal/host`, `internal/ledger`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/activator/escrow.go` `ExecBackend.EscrowSweep`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the agent as carlos (carlos-edge.service), no root caller, from escrowLoop: classifies each row against the rows handed in (Classify), keeps eligible rows known not HA from memory (haKnown, no read), and in host order from a round-robin cursor stats each escrowed file (stampAt) and publishes the changed ones, 8 at a time, at most 256 a sweep (sweepPublish); a box without a files store or key does nothing; opens nothing outside the rows' own data directories; writes only the hibernate bucket's files/0 prefix and the ledger Fix round 1: a host whose instance lease this box does not hold (holdsLease) is skipped, and one with a conflict marker counts as failing and is not published; the report is tallied through one lock (P1-4). Durability 3a Task 5: for each lease-held candidate, the host's held publisher (st.pub under the escrow lock) is handed to noteRawBaseline. Reads only manifests this process already holds (no request, no file opened); calls the detector, which logs and calls ExecBackend.OnRawSecret; nothing else changes. The +registry:Host sites are rt.Host as the state key and the detector's argument.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: use coordinator authority for stateless projections and the unchanged serving lease for stateful rows; followers are skipped without I/O; no new poll loop or file path.
+- `internal/activator/escrow.go` `ExecBackend.escrowConflict`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 1: new: os.Lstat of <data>/.escrow/<host>.conflict, the agent's own directory; present, every launch, mint and publish of the host is refused with an alert naming the file for an operator to remove; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 2: the alert text names the divergence generally (local secrets differ from the escrow); the same Lstat.
+- `internal/activator/escrow.go` `ExecBackend.escrowConflictFound`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 2: new: the refusal for a divergent trio item: tries to write the host's conflict marker (writeEscrowMarker: EnsureDirBeneath <data>/.escrow 0700, a 0600 temp, rename, fsync), logs if it cannot, and returns the alert; the refusal holds either way, since every later publish finds the same divergence; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 3: the alert names the env file too, since a platform-minted env variable can diverge; the same marker write.
+- `internal/activator/escrow.go` `ExecBackend.escrowedLaunchEnv`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the launch path for an eligible host: captureLaunchEnv once, publishEscrowAt over those bytes, SealedAcknowledged on the commit, and the env parsed from the captured bytes; on a supersession escrowReread and the launch preparation again (ensureAdminTokenFor, ensureInstanceKeyFor) once; a not-ready box launches only a host its ledger shows escrowed; the agent as carlos (carlos-edge.service), no root caller Fix round 0 (controller readiness ruling): before the capture, the box's mode: no files store, instanceEnvLayer exactly as before 3a (logged once); no sealing key, a host whose ledger shows it escrowed launches on instanceEnvLayer (logged), otherwise keylessEscrowed (the answer this launch's restore read, within haSecretsBudget, else one GET) refuses when the bucket holds an escrow and launches on instanceEnvLayer when it holds none; nothing is published in either. Fix round 1: ends the launch's preparation; refuses while the conflict marker exists, and with a key while this box does not hold the host's lease; an ALERT from the publish fails the launch; the keyless decision uses the preparation's read. Fix round 3: a publish that answers errEscrowNoLease (the lease lost before the commit) refuses the launch with an error saying so, never the later-launch fallback. Fix round 4: a publish that answers errEscrowUnreadable or ErrEscrowNotReady (the manifest or sealed env could not be read, or does not open here) refuses the launch, never the later-launch fallback; only refuses.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: followers take read-only escrow verification/restore and never open the publisher; stateless coordinator requires ready escrow. Existing stateful publish, first-launch and conflict branches preserved.
+
+Seal: `8df52839a0c961d3721f3a5c3247d06202dae4e00d011844b7117f8e918803d4` → `1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-16-go-code-health.md b/docs/superpowers/plans/2026-11-16-go-code-health.md
new file mode 100644
index 000000000..c8b4e9b55
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-go-code-health.md
@@ -0,0 +1,287 @@
+# Go code health: fix, hold, improve
+
+Status: draft rev 3 for Paul, 2026-11-16 (Astra rounds 1 and 2 answered; review closed at round 2). Backlog and audit reports: amadan
+discussion #1123. First batch merged the same day (958ff2e, b064b14,
+0374ac2).
+
+## What this plan is for
+
+The 2026-11-16 audit found the code careful but with three kinds of gap:
+network calls with no deadline, holes in the CI gate, and shapes that keep
+growing (a 162k-line console package, 1,200-line functions, 999
+`log.Fatal` calls in the CLI, 1,019 sleeps in tests). The first batch
+closed the worst deadlines and two gate holes.
+
+Fixing the current list once is not enough. Between the audit (5b6d5374)
+and the recheck (c4b44c34), eight days apart, by rough text counts the CLI
+gained about 45 `log.Fatal` mentions and tests about 147 `time.Sleep`
+mentions, and two of the three longest functions grew by 130 to 160 lines
+(`handleAPIInstanceCreate` 1,081 to 1,242, `runAgent` 1,090 to 1,222;
+`Reconcile` 1,255 to 1,275). These are grep estimates; the scanner in
+Part 2 sets the real baseline. So the plan has three parts:
+
+1. **Fix** what is known, in small reviewed branches.
+2. **Hold** every gain with a check in CI, so nothing that was fixed comes
+ back and nothing measured gets worse.
+3. **Improve** steadily: convert code as it is touched, and look again on
+ a fixed rhythm.
+
+## Principles
+
+- **Ratchets, not sweeps.** A count that can only go down beats a
+ one-time cleanup. Sweeps across hundreds of files cost review rounds and
+ census cards; ratchets cost nothing until someone touches the code.
+- **Convert on touch.** A branch that changes a function brings that
+ function up to the rules below. No branch exists only to restyle.
+- **Guards over rules.** A rule in AGENTS.md is read sometimes; a test
+ that fails is read every time. Where a rule can be a guard test, it is.
+- **Small branches, the stopping rules unchanged.** One concern per
+ branch, Opus builds, Astra reviews (Fable for whole-branch reviews
+ where the tier matters), three rounds at most.
+- **Recheck before building.** Every backlog item is checked against
+ current main first; the audit's own baseline was 159 commits stale.
+
+## Part 1: fix
+
+### Batch 2 (started 2026-11-16)
+
+| Branch | What | Census |
+|---|---|---|
+| `audit-bugs-2` | ledger verify timeout and `{}` HEAD panic (cli.go); system update decode errors (system.go); "ops" substring match (console/ownership.go); #1141 subdomain lost race; silent capacity page (host/haplacement.go); escrow alerts matched by string prefix (activator/escrow.go) | yes |
+| `audit-console-shutdown` | console drains HTTP and its workers on SIGTERM before releasing the policy lease, so rolls stop dropping requests | no (console) |
+| `audit-govulncheck` | `50-govulncheck` CI step with an explicit, dated exception file; GO-2026-6859 listed under the 1.26.10 pin (#897, #904) | no |
+| `audit-edge-test-sleeps` | about 13 s of fixed sleeps in edge tests replaced through the seams that exist (`Edge.watchTick`) and one new one (`holderHeaderSuspectAfter` becomes a variable a test can shrink, at the same value) | yes: the new seam changes internal/edge production code |
+
+Plus the one-line AGENTS.md fix: its sandbox note recommends a GOCACHE
+path the machine policy bans (rides `audit-bugs-2`).
+
+Batch 2 keeps the edge test-sleep branch because it was already under way
+and is small; from batch 3 on, production deadline gaps come before test
+speed.
+
+### Batch 3: production deadlines first, then the follow-ups
+
+In this order:
+
+- **Console request cancellation, in place.** Request handlers call store
+ methods without their request context (for example
+ internal/console/oppeople.go:102, :127), on a store with one connection
+ (store.go:122), so an abandoned request keeps its place in the queue.
+ Thread the request context through the store methods those handlers use,
+ starting with the busiest request paths; no package move needed.
+- **The remaining unbounded production calls:** the edge prober's dial
+ (internal/edge/upstreamdial.go:16); host `systemctl`/`journalctl` calls
+ with no timeout (internal/host/systemunits.go:327, unitsettle.go:75, and
+ the loops adoptLoop, fastConvergeLoop, statusLoop, configSync/configGen)
+ through one bounded helper with a guard test.
+- #1143: credential clients get the body bound; an explicit buildable
+ client stays the caller's; the AWS client guard catches field
+ assignment and option callbacks.
+- staticcheck's excluded families, one branch each, then switched on:
+ SA4006 (70, includes #1141's shape), SA1019 (70), SA1012 (177, mostly
+ nil contexts in internal/registry).
+- Racy test helpers (host/caps_pass_test.go captureLog,
+ activator/wakecheck_test.go), then a targeted `-race` CI step on edge,
+ activator, lease and host.
+- gitleaks as its own CI step.
+
+### Batch 4 onward: structure, each with its own short spec
+
+In this order, because each makes the next cheaper:
+
+1. **Census `moved` class** in `census-propose`: a pure file move carries
+ its disposition, its reviewer approval and its J4 witness obligations
+ instead of reading as a removal plus a new unit. It is a dependency only
+ of the relocations below that move files inside the root binary's graph
+ (2, 3, and any host split). Console-only work (4 and 5) is outside
+ the root census and does not wait for it.
+2. **Leaf package for the S3 `Store` interface** out of
+ `internal/release` (67 importers, all linking the registry and SQLite
+ today).
+3. **Leaf package for the names console takes from activator and edge**,
+ so the console stops linking about 90k lines of production code it
+ barely uses (89,626 at c4b44c34). This one is census-touching: the
+ names live in root-linked files (`edge.FleetArmVerdict` decides routing
+ eligibility, internal/edge/fleetforward.go:322), so extracting them
+ changes census-covered source. Its spec decides whether the `moved`
+ class covers it or it needs ordinary unit and envelope proposals.
+4. **Console request contexts, the rest**: after batch 3's request paths,
+ the remaining store calls, held by the ratchet's database metric.
+5. **Console split, staged**: widen the 15 package-directory source guards
+ first, then `consoledb` (the Store), then billing, alerts, operator
+ pages, architecture view and PDF, one at a time.
+6. **CLI commands return errors**: convert on touch to
+ `runXWithSession(ctx, sess, args, out) error`; the ratchet below holds
+ the count.
+
+## Part 2: hold
+
+### A code-health ratchet in CI
+
+A test-only package, `internal/codehealth`, scans the tree once per gate
+run and compares it with a checked-in record, `.amadan/code-health.tsv`.
+It is outside the census: the census scope comes from the root binary's
+production dependencies, and nothing links a test-only package. The idea
+is Rastrillo's `.rastrillo/code.txt` (offences recorded when the gate
+began, records only go down), adapted for many parallel branches.
+
+**Two kinds of record.**
+
+- **Sites**, for rules that say "no new ones": each existing offence is
+ recorded by identity (package, enclosing function, callee) with a count.
+ A new site, or a higher count at an existing one, fails the gate even if
+ an old one was removed elsewhere, so removing one offence never pays for
+ another. Moving code within a package keeps the identity. A rename or a
+ move to another package goes through `make code-health-record
+ MOVE=<old>:<new>`, which carries the existing allowance across and can
+ never increase it. It writes the new site with a `# moved-from: <old>`
+ comment and removes the old one in the same edit; the CI step below
+ accepts a new site carrying that comment only when the old site's
+ allowance in the merge base is at least as large and the old site is
+ gone. A transfer is not a raise.
+- **Totals**, for trends with no "no new ones" rule (packages importing
+ internal/release, say): a number per metric and package.
+
+**What fails, and what does not.**
+
+- An offence above its record fails the gate and names the site.
+- A count below its record does not fail. The gate prints the lower
+ number. So two branches that each remove a different sleep both pass,
+ and main after both merges passes too (it is simply below its record).
+- `make code-health-record` only lowers records and drops sites that are
+ gone. It cannot add a site or raise a number. Adding or raising needs a
+ hand edit with a `# raised: <reason>` comment on the line.
+- A separate CI step compares `.amadan/code-health.tsv` with the merge
+ base's copy (fetching main if the runner lacks it) and fails on any
+ added site or raised number unless the line carries `# raised:
+ <reason>` or is a valid `# moved-from:` transfer, so a raise is always
+ a visible, reviewed decision and a transfer is checked mechanically.
+- Records drift below the code only when nobody runs the lowering
+ command; the monthly pass catches that (Part 3).
+
+**How it measures.** With type information (`golang.org/x/tools/go/packages`,
+already a dependency), not text, for the root module and `launchctx`,
+under `GOOS=linux`, as the union of two configurations: no tags (what
+production builds) and the gate's tags (`rootrunner`,
+`carlos_cutover_witness`), with a site seen in both counted once. That
+way a `!rootrunner` production file (internal/host/departure_queue_default.go)
+is measured too; a fixture proves it. Files built only for darwin or
+windows are outside the first version and listed as such in the scanner's
+output. Generated files (`// Code generated`) and
+`testdata` are skipped. Import aliases are resolved by type, so
+`log.Fatal` under another name still counts. Each metric has fixture
+tests showing what it counts and what it ignores. Its run time is measured
+on CI before it joins the gate; if it is slow it runs as its own CI step.
+
+**Metrics at the start.** The scanner sets the real numbers; these are
+grep estimates from c4b44c34.
+
+| Metric | Kind | Estimate |
+|---|---|---|
+| `log.Fatal*` and `os.Exit` calls in root-package production files | sites | about 999 and 120 mentions |
+| `time.Sleep` calls in test files | sites | about 1,019 mentions |
+| database operations without a context (one classifier, below), in every package, so moving code into a new package (e.g. `consoledb`) does not hide them | sites | 459 in console via `s.db` alone; more with `tx`, `Stmt` and interfaces |
+| functions over 300 lines, counting only lines with code (blank and comment-only lines excluded) | sites (function, length) | 3 over 1,000 today |
+| files over 3,000 lines, same counting | sites (file, length) | to measure |
+| packages importing internal/release | total | 67 |
+| `context.Background()`/`TODO()` in internal/host production code | sites | to measure |
+
+**The database classifier** is one function with one rule, so receiver
+spelling, narrow interfaces and package moves cannot hide a call: a call
+is a database operation without a context when its static callee is
+`Query`, `QueryRow`, `Exec`, `Prepare` or `Begin` and either (a) it is a
+method of `database/sql`'s `DB`, `Tx`, `Conn` or `Stmt`, or (b) it is a
+method of any other type or interface whose signature is identical to
+the same-named `database/sql` method. (b) catches console's
+`sqlQueryer.QueryRow` (internal/console/billingpayments_store.go:73) and
+`sqlHandle.Begin` (store_gate.go:110) without listing them. Its context
+counterpart is the `...Context` method, and `BeginTx` for `Begin`.
+Fixtures cover each of those examples, `*sql.Stmt` (internal/registry/registry.go:2874)
+and the same calls after a move to another package. If a form turns up
+that the rule misses, the rule changes in that one function, with a
+fixture; no per-receiver lists.
+
+Line metrics count code, not comments, so adding a safety explanation
+never fails the gate and deleting comments never counts as a gain. Their
+physical length is printed as a report only.
+
+### Guards that already hold a line
+
+- Every edge `http.Server` sets its timeouts (958ff2e).
+- Every AWS client in the root binary goes through the bounded transport
+ (0374ac2, `TestAWSClientsAreBounded`).
+- staticcheck SA checks clean (b064b14), rootrunner tests vetted.
+
+Each later batch adds its own guard where the rule is mechanical (the
+bounded `systemctl` helper, for one).
+
+### Go rules in AGENTS.md
+
+A short "Writing Go here" section, each rule pointing at the guard or
+ratchet that enforces it:
+
+- Network calls carry a deadline; AWS clients come from internal/rootaws.
+- Functions that have a `ctx` pass it on; a detached
+ `context.Background()` carries a comment saying why.
+- New CLI commands return errors; they do not call `log.Fatal`.
+- New tests wait on a signal or a seam, not `time.Sleep`.
+- Errors are compared with `errors.Is`/`errors.As` and wrapped with `%w`
+ when a caller might branch on them; never match `err.Error()` text.
+- A function past 300 lines of code, or a file past 3,000 (comments and
+ blank lines not counted), is split by concern in the branch that would
+ grow it; deleting comments to fit is not a split.
+
+## Part 3: improve
+
+### Monthly health pass (first Monday of the month)
+
+One session, bounded (one scanner run, one staticcheck run with every
+check on, one govulncheck run, at `nice`, on cached builds), reporting
+only:
+
+1. Post the numbers on a standing discussion with the change since last
+ month: the ratchet, staticcheck with every check on (S, ST, QF, U1000
+ included), govulncheck.
+2. Where main is below its records, open one small branch that runs
+ `make code-health-record` (lowering only), reviewed like any other.
+ Anything above its record on main is a broken invariant: file it as an
+ Issue at once.
+3. Pick the next two or three items from the backlog for the month and
+ post them for Paul's go.
+
+Its cost is measured on the first run and stated in the post; if it
+exceeds an hour of agent time, the pass is cut down, not the rules.
+
+### Quarterly audit, one slice at a time
+
+Each quarter, one read-only Fable auditor takes one slice (console; host
+family; activator and edge; root CLI and the rest; in rotation) with the
+2026-11-16 brief, against current main. Astra verifies the findings
+before they reach the backlog. New findings become backlog items or new
+ratchet metrics. Every slice is seen once a year.
+
+### Tightening over time
+
+- staticcheck: SA families back on (batch 3), then U1000 (dead code),
+ then the S and ST checks worth having, one at a time, each with its
+ findings fixed or recorded first.
+- Ratchet thresholds come down once the lists are short: functions from
+ 300 lines towards 150, files from 3,000 towards 1,500.
+- Test speed: the slowest-test list from `test-weights.tsv` is reviewed
+ each health pass; sleeps over one second are the first targets.
+
+## What is not in this plan
+
+Settled by the audit as not worth doing: a `slog` migration, a repo-wide
+`%w` or context sweep, moving the CLI to `internal/cli`, subpackages
+inside activator, mass-unexporting in host.
+
+## Done means
+
+- Batches 2 and 3 merged; staticcheck runs every SA check; govulncheck,
+ gitleaks and a targeted `-race` run in CI.
+- The ratchet in CI; no record raised except by a reviewed `# raised:`
+ line, and allowances moved only by checked transfers.
+- Each structural item merged or explicitly dropped with a reason.
+- After that the monthly pass and quarterly audit continue; this plan is
+ then a rhythm, not a project.
diff --git a/docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md b/docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md
new file mode 100644
index 000000000..1d0f8e49b
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-bugs-2-R1.md
@@ -0,0 +1,38 @@
+Reviewed `origin/main...7a8aa1726585d4bb6403a4d54fc1322a98535d87`, based on `c4b44c34e5deec90e6d3fa5cdffe62c7d8cad9e9`. The requested tip differs from the brief’s `6658a8db` only by adding the brief. This is round 1 of 3.
+
+Findings: **P1: none. P2: none. P3: none.** Under the stopping rule, no further review round is needed.
+
+The seven checks:
+
+1. **Ledger verification:** `Append` stores the entry before publishing HEAD, with a positive count and a lowercase SHA-256 digest. There is no legitimate empty HEAD produced by this writer. The new validation preserves valid published chains, while rejecting `{}`, `null`, missing keys and malformed digests. The timeout bounds each HTTP request, including its body, to 30 seconds; it does not bound the entire chain walk. See [append.go:74](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/ledger/append.go:74), [verify.go:48](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/ledger/verify.go:48), and [cli.go:3834](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/cli.go:3834).
+
+2. **System update and rollback:** The status-decode refusal occurs before upload or promote, so “nothing was promoted” is accurate. After acceptance, malformed or job-less responses explicitly acknowledge acceptance and direct the operator to status. An unreadable progress response says the promote may still be running. Rollback retains success when its completed operation’s response cannot supply a version. None of these added paths recommends repeating the mutation. See [system.go:379](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:379), [system.go:497](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:497), and [system.go:727](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:727).
+
+3. **Ops-account sentinel:** Both the early deletion refusal and `Store.DeleteAccount` use the sentinel. `errors.Is` recognizes wrapped refusals; unrelated errors containing “ops” receive generic advice. See [ownership.go:161](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/ownership.go:161), [ownership.go:716](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/ownership.go:716), and [ownership.go:790](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/ownership.go:790).
+
+4. **Lost subdomain-create race:** The assignment removes the shadowed `err`. The reread updates `cur`, `etag` and `err` together. Read failures refuse; occupied claims remain untouched; retired-claim writes retain their conditional-write checks. See [apisubdomain.go:468](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/console/apisubdomain.go:468).
+
+5. **Capacity paging:** Failed delivery is now logged with host, region and error. The callback, warning level and five-second context remain unchanged. See [haplacement.go:13](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/host/haplacement.go:13).
+
+6. **Escrow alerts:** All three constructors preserve their text. Both consumers use `errors.As`. The joined sealed-open failure already refused launch through `errEscrowUnreadable`; recognizing its alert directly preserves that refusal. The sweep now logs it through the alert branch. Repository searches found text assertions and documented alert text, but no additional production classifier depending on the old concrete error type.
+
+7. **Sandbox guidance:** The change removes the conflicting `/tmp` cache instruction and preserves the existing offline module flags.
+
+Census verdicts for this tip:
+
+| Unit or envelope | Verdict and basis |
+|---|---|
+| `ExecBackend.EscrowSweep` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:1590](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:1590), including the changed classification at 1673. Eligibility, authority checks, publication limits and reads are unchanged. |
+| `ExecBackend.escrowConflict` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:497](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:497). Same `Lstat`, same refusal conditions and text; only the error representation changes. |
+| `ExecBackend.escrowConflictFound` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:1049](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:1049). Marker creation, logging and unconditional refusal remain intact. |
+| `ExecBackend.escrowedLaunchEnv` | **APPROVE — retain `legacy / accepted-legacy`.** Read [escrow.go:1394](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:1394), including 1458–1482. No readiness, lease, conflict or sealed-acknowledgement check is weakened. |
+| Envelope `.` | **APPROVE.** Reviewed changed functions in [cli.go:3812](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/cli.go:3812) and [system.go:359](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/system.go:359), plus their request paths. No new authority or root-controlled input path. |
+| Envelope `internal/activator` | **APPROVE.** Reviewed the four units, the [error helpers at 510](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/activator/escrow.go:510), `errEscrowWriter` at 1328, and publication/error propagation. No new read or write authority. |
+| Envelope `internal/host` | **APPROVE.** The sole production change is [haplacement.go:13](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/host/haplacement.go:13); it adds failure logging only. |
+| Envelope `internal/ledger` | **APPROVE.** Reviewed [verify.go:48](/home/paulca/amadan.net/carlos/platform-audit-bugs-2/internal/ledger/verify.go:48) through the verifier, HTTP getter and writer contract. Validation tightens acceptance without expanding reads. |
+
+The added tests cover the previous failures by source inspection. The race fixture is deterministic; timeout tests have generous margins; modified globals are restored and these tests do not run in parallel. I found no material flake risk.
+
+Changed Go files pass `gofmt -l`; the committed diff passes `git diff --check`. Runtime tests and the census gate were **not verified**: the targeted ledger test stopped before compilation because Go attempted to update `go.mod` in the read-only sandbox. No files were edited, reviewers spawned, or full suites run.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-code-health-plan-R1.md b/docs/superpowers/reviews/FINDINGS-code-health-plan-R1.md
new file mode 100644
index 000000000..a54b710c7
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-code-health-plan-R1.md
@@ -0,0 +1,80 @@
+Reviewed round 1 at `7977edd904c8dcabfccc2fdda5a417d6b295db5e`, against local baseline `c4b44c34`. No files changed; no builds, tests, or subagents run. Discussion #1123 was inaccessible because network access is blocked, so its reports and external issue claims remain unverified.
+
+1. **P1 — Part 2: the ratchet does not protect gains across merges or record regeneration.**
+ **Invariant: an accepted baseline cannot increase, and merged code must match it.**
+
+ [Plan lines 99–108](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:99) specify comparison against the branch’s own record and a command that rewrites it. They specify neither comparison with an accepted baseline nor integration handling.
+
+ Two branches can each remove a different sleep, changing the same record from 100 to 99. Both pass independently. Git can merge their identical record edits without conflict, leaving 98 sleeps against a record of 99: the required decrease check then fails on main. The repository explicitly gates the branch tip and checks main afterward ([AGENTS.md:185](/home/paulca/amadan.net/carlos/platform-code-health-plan/AGENTS.md:185)). Separately, rewriting the record upward would satisfy the described equality check.
+
+ **Fix:** define a lower-only update command, reject unauthorized baseline increases against the accepted base, and specify how combined changes are regenerated and gated before landing. Include the two-independent-decreases scenario in the ratchet’s acceptance checks.
+
+2. **P2 — Part 2: aggregate counts cannot enforce the proposed rules for new code.**
+ **Invariant: removing an old offence must not authorize a new one.**
+
+ The record is per metric/package ([plan:101](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:101)), while the rules prohibit new CLI fatalities and new test sleeps ([plan:141](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:141)). Removing one old call and adding one elsewhere passes the count check. Counts alone also cannot identify the “new offences” promised at line 105.
+
+ Package splits create another problem: existing sleeps transferred into a new package become new offences there, despite no increase overall. Allowing unrestricted initial records would instead permit evasion.
+
+ **Fix:** distinguish aggregate trend metrics from site-level prohibitions. Record grandfathered sites where “no new ones” is intended, and define reviewed identity transfers for moves, renames and package splits without increasing the inherited allowance.
+
+3. **P2 — Part 2: the database metric lacks a reliable measurement boundary.**
+ **Invariant: the metric follows database operations, regardless of receiver spelling or package placement.**
+
+ [Plan:117](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:117) names `db.Query`/`QueryRow`/`Exec`. Existing calls also use `tx` and a `sqlQueryer` interface: [billingpayments_store.go:72](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/billingpayments_store.go:72), [line 88](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/billingpayments_store.go:88), and [line 176](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/billingpayments_store.go:176). `Begin()` at line 170 is another context-free database operation.
+
+ A receiver-name scan misses these; an unrestricted selector-name scan counts unrelated APIs. Limiting coverage to `internal/console` also makes the proposed `consoledb` extraction appear to fix calls merely by moving them.
+
+ **Fix:** define the database types/interfaces and operations covered, including transaction acquisition. Use type information or a documented conservative syntax rule with fixtures covering these existing forms. Carry coverage into extracted packages. Specify import-alias handling, build-tag coverage and generated/fixture exclusions for the scanner generally.
+
+4. **P2 — Batch ordering: request cancellation is unnecessarily behind structural work.**
+ **Invariant: operational fixes should not wait for unrelated dependency cleanup.**
+
+ [Plan:75–87](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:75) puts console request contexts after the census extension and two package extractions. The current connection limit is indeed one ([store.go:122](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/store.go:122)); request handlers call store methods without passing their request context ([oppeople.go:102](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/oppeople.go:102), [line 127](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/oppeople.go:127)). Those paths can be improved in place.
+
+ Batch 3 also contains existing unbounded production calls—[upstreamdial.go:16](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/edge/upstreamdial.go:16), [systemunits.go:327](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/host/systemunits.go:327), and [unitsettle.go:75](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/host/unitsettle.go:75)—while batch 2 includes test-speed cleanup.
+
+ **Fix:** bring a bounded request-cancellation slice forward, and prioritize the remaining production deadline gaps ahead of sleep cleanup. Make `moved` a dependency of relocations that require it, not of every structural or cancellation change.
+
+5. **P2 — Batch 2: the edge sleep branch is incorrectly labelled census-free.**
+ **Invariant: production test seams retain the normal census review.**
+
+ [Plan:50](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:50) proposes a seam for `holderHeaderSuspectAfter` but labels the branch “no (tests).” The constant and timer construction are production code at [forwardha.go:509–521](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/edge/forwardha.go:509). Changing them changes the production envelope; the scanner fingerprints whole in-scope files ([census_scope_test.go:182](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/provision/census_scope_test.go:182)).
+
+ **Fix:** mark the branch census-required if it adds that seam, with the normal independent approval. Retain “no” only for a strictly test-file-only implementation.
+
+6. **P2 — Part 2: physical-line ratchets reward deleting useful explanation.**
+ **Invariant: readability and safety documentation must not be sacrificed to satisfy a size metric.**
+
+ [Plan:118–119](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:118) allows oversized functions/files only to shrink, and [line 145](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:145) requires splitting a growing one. Adding a safety explanation to an unchanged oversized function would fail, while deleting comments would count as improvement. This codebase puts meaningful authority explanations immediately beside implementation, for example [apiinstances.go:1573](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/apiinstances.go:1573).
+
+ **Fix:** exclude blank and comment-only lines from the blocking metric. Keep physical length as a report, and require meaningful decomposition rather than accepting comment removal as structural improvement.
+
+7. **P2 — Introduction and metric table: some quantitative claims are inaccurate or lack a counting definition.**
+ **Invariant: baseline comparisons use the same reproducible measurement.**
+
+ [Plan:16–18](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:16) says all three longest functions grew by 100–200 lines. Comparing function-body spans at the two named commits gives:
+
+ | Function | `5b6d5374` | `c4b44c34` | Growth |
+ |---|---:|---:|---:|
+ | `Reconcile` | 1,255 | 1,275 | 20 |
+ | `handleAPIInstanceCreate` | 1,081 | 1,242 | 161 |
+ | `runAgent` | 1,090 | 1,222 | 132 |
+
+ Current declarations are at [reconcile.go:1460](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/provision/reconcile.go:1460), [apiinstances.go:1578](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/apiinstances.go:1578), and [agent.go:275](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/host/agent.go:275).
+
+ The stated 999 fatalities and 1,019 sleeps reproduce literal text-occurrence counts, which include non-call text; [cli.go:49](/home/paulca/amadan.net/carlos/platform-code-health-plan/cli.go:49) is one such comment.
+
+ **Fix:** correct the growth claim and label historical text counts as estimates. Generate the authoritative baseline with the final scanner and record its scope and counting definitions.
+
+8. **P3 — Monthly pass: “read-only” conflicts with lowering records.**
+
+ [Plan:152–157](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:152) promises a read-only session, then directs it to lower records. Under a functioning exact-match ratchet, an unlocked decrease on main is also a gate failure to investigate.
+
+ **Fix:** make the pass report discrepancies and propose a separate reviewed repair branch. Treat unexplained drift as a failed invariant.
+
+The test-only `internal/codehealth` package is outside the census as proposed: scope derives from production dependency files, not test imports ([census_scope_test.go:43–79](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/provision/census_scope_test.go:43)). A single parsing pass is a reasonable approach, but gate runtime remains unmeasured.
+
+The monthly and quarterly cadence does not itself contradict the stopping rules; the plan explicitly retains them. Keep each audit and verification bounded, reuse existing caches, and measure scanner cost before claiming the hour budget. A `moved` design must preserve dispositions, reviewer approval and J4 witness obligations; current removal handling is not a safe substitute for that contract.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-code-health-plan-R2.md b/docs/superpowers/reviews/FINDINGS-code-health-plan-R2.md
new file mode 100644
index 000000000..11dbcb264
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-code-health-plan-R2.md
@@ -0,0 +1,63 @@
+- R1 P1, ratchet merges and regeneration: **resolved** for the reported cases; decreases no longer fail, updates only lower, and increases require an explicit reason.
+- R1 P2, aggregate counts versus new offences: **resolved** through site records and reviewed allowance transfers.
+- R1 P2, database measurement boundary: **partly resolved**; type-based coverage still excludes existing database forms.
+- R1 P2, batch ordering: **resolved**; request cancellation and remaining production deadlines precede structural work.
+- R1 P2, edge seam census classification: **resolved**.
+- R1 P2, comment deletion incentive: **resolved**.
+- R1 P2, growth figures and counting definitions: **resolved** for the reported discrepancies.
+
+Reviewed `732d32ba2214bab824fa6791f0a09b5238e5f465` against `c4b44c34`. The production source is unchanged between those commits. No files changed; no builds, tests, or subagents ran. Network restrictions prevented access to discussion #1123, so its reports and issue claims remain unverified.
+
+No P1 findings.
+
+1. **P2 — Part 2: the database metric still misses existing database operations.** Carried from R1.
+
+ **Invariant:** database operations remain measurable regardless of receiver spelling, interface narrowing, or package placement.
+
+ The definition at [plan:173](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:173) includes module interfaces only when they offer the corresponding `...Context` method. Its named example, `sqlQueryer`, declares **only** `QueryRow` at [billingpayments_store.go:73](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/billingpayments_store.go:73). Consequently, the proposed rule misses the existing `q.QueryRow` calls, including line 88.
+
+ Transaction acquisition has a related gap. `Store.db` is a `sqlHandle`, whose contextual transaction method is `BeginTx`, not `BeginContext` ([store_gate.go:110](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/store_gate.go:110)). The literal counterpart rule therefore misses `s.db.Begin()`. Prepared statements are also omitted: the receiver at [registry.go:2874](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/registry/registry.go:2874) is `*sql.Stmt`, which is neither among the listed SQL types nor a type defined in this module.
+
+ **Fix:** define one database-operation classifier covering SQL method signatures, narrow interfaces, `*sql.Stmt`, and the explicit `Begin`→`BeginTx` mapping. Require fixtures for these existing examples and equivalent calls after package extraction.
+
+ This is the second round in the same measurement-boundary fault family. Under [AGENTS.md:54](/home/paulca/amadan.net/carlos/platform-code-health-plan/AGENTS.md:54), do not continue with successive receiver-list patches. Recommend the rule’s centralized-invariant option; the alternatives are to reject unsupported forms explicitly or defer this metric.
+
+2. **P2 — Batch 4: extracting shared console dependencies is incorrectly classified as outside the census.**
+
+ **Invariant:** census scope follows changed production source, regardless of which consumer motivates the change.
+
+ [Plan:101](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:101) exempts items 3–5 as console work. Item 3, however, extracts definitions from activator and edge into a shared leaf package.
+
+ These are not exclusively console definitions. The console calls `edge.FleetArmVerdict` at [apiinstances.go:449](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/console/apiinstances.go:449); its implementation at [fleetforward.go:322](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/edge/fleetforward.go:322) contains routing eligibility decisions. The root command package imports edge at [commands.go:16](/home/paulca/amadan.net/carlos/platform-code-health-plan/commands.go:16). Likewise, the console’s activator helpers come from root-linked production files.
+
+ Extracting those definitions changes census-covered source and potentially adds a root-linked package. Whole-file coverage is explicit at [census_scope_test.go:125](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/provision/census_scope_test.go:125).
+
+ **Fix:** classify item 3 as census-touching. Its short spec should determine whether the proposed `moved` class applies or ordinary unit and envelope proposals are required. Keep the console-only context and store work independent of that dependency.
+
+3. **P2 — Part 2: the scanner’s build configuration omits ordinary production source.**
+
+ **Invariant:** a production file must not escape the ratchet because a test configuration substitutes another file.
+
+ [Plan:157](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:157) specifies loading with `rootrunner,carlos_cutover_witness`. But [departure_queue_default.go:1](/home/paulca/amadan.net/carlos/platform-code-health-plan/internal/host/departure_queue_default.go:1) uses `!rootrunner`; the tagged implementation replaces it.
+
+ A scanner using only the specified configuration never sees that production file. New host `context.Background()` calls there, for example, would evade the advertised host metric.
+
+ **Fix:** measure the union of ordinary production and tagged configurations, deduplicating shared source sites. Add a fixture proving that an offence in a `!rootrunner` file is counted. State explicitly whether other supported operating systems are covered or remain outside the initial ratchet.
+
+4. **P3 — Part 2: transfer and exception wording needs one consistent contract.**
+
+ [Plan:135](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:135) permits `MOVE` to create a destination identity, while lines 147–153 say the command cannot add sites and CI requires a `# raised:` annotation for every addition. The completion criterion at [plan:258](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:258) also says records are “never raised,” despite the explicit exception mechanism.
+
+ **Fix:** document how CI recognizes a valid transfer and distinguish transferred allowances from approved increases. Align the completion criterion with that policy.
+
+5. **P3 — Batch 3 and Batch 4: remove duplicated tasks and label the historical size estimate.**
+
+ The prober and host deadline tasks appear twice at [plan:72](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:72) and line 80. The “78k lines” statement at [plan:107](/home/paulca/amadan.net/carlos/platform-code-health-plan/docs/superpowers/plans/2026-11-16-go-code-health.md:107) matches the older audit baseline: direct-package, non-test Go files total 77,538 lines at `5b6d5374`, versus 89,626 at `c4b44c34`.
+
+ **Fix:** keep each deadline task once and label the size estimate with its baseline or update it.
+
+The test-only scanner remains outside the census as proposed. The corrected fatal-call, sleep, and function-growth figures reproduce against the named commits. The monthly reporting branch resolves R1’s P3. The monthly and quarterly cadence is bounded on paper; scanner runtime and shared-machine resource use remain unmeasured, so retain the first-run measurement requirement.
+
+This round has no P1, so the stopping rule ends review here. Address the P2s without reopening review, subject to the repeated-family decision above; retain P3s as follow-ups.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md
new file mode 100644
index 000000000..2a036ac74
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-bugs-2.md
@@ -0,0 +1,48 @@
+# Review brief: branch audit-bugs-2, round 1 of 3
+
+Repo carlos/platform, branch `audit-bugs-2`, commit 6658a8dbdb595c16ccaae9813defc1385f4e4c64.
+Under review: the diff `origin/main...6658a8dbdb595c16ccaae9813defc1385f4e4c64` (base c4b44c34).
+Authorities: AGENTS.md on main ("The census", "Stopping rules"). Context:
+amadan #1123 batch 2, and #1141.
+
+You are the independent reviewer and the census reviewer. Card:
+`docs/superpowers/notes/census-proposal-audit-bugs-2.md`. Give a verdict
+for every unit and envelope, citing the lines you read.
+
+## What to check (one commit per item)
+
+1. ledger verify (cli.go, internal/ledger/verify.go): `checkHead` refuses
+ a malformed HEAD; the claim that no empty-ledger HEAD exists (Append
+ writes HEAD only after the first entry): true? Could a legitimate
+ published ledger now fail verification? 30 s client bound.
+2. system update (system.go): status read, systemUpdateJob and
+ watchSystemJob refuse unreadable answers and empty job ids; the
+ rollback path reports an unknown version without failing. Any case
+ where a promote that DID start is now reported as not started, or where
+ an operator is told to retry something that would double-run?
+3. console ownership.go: `errOpsAccountUndeletable` sentinel, every path
+ that returned the old text now returns the sentinel (wrapped or not)?
+4. #1141 apisubdomain.go: the lost-race path now judges the winning claim;
+ all branches after it see the right err, cur and etag.
+5. host/haplacement.go: failed capacity page now logged.
+6. activator/escrow.go: `escrowAlert` type with identical text; both call
+ sites use errors.As. Behaviour identical except a joined alert is now
+ recognised; at the sweep site the joined alert is logged as an alert
+ instead of a routine failure. Does anything else consume these
+ errors' text (tests, log scanners, runbooks, alerting) that the type
+ change could break?
+7. AGENTS.md sandbox note.
+Tests: each new one fails on the old code; any flake risk.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3 with file:line, failure scenario and fix. Then
+the census verdict per unit and envelope. End with exactly one verdict:
+READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn
+reviewers or run full suites.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan-R2.md b/docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan-R2.md
new file mode 100644
index 000000000..2dbd5490d
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan-R2.md
@@ -0,0 +1,71 @@
+# Review brief: plan docs/superpowers/plans/2026-11-16-go-code-health.md, round 2 of 3
+
+Repo carlos/platform, branch `code-health-plan` (tip named in the reviewer's prompt).
+Under review: `docs/superpowers/plans/2026-11-16-go-code-health.md`.
+Authorities: AGENTS.md on main ("Stopping rules", "The census", "Build &
+test"). Context: amadan discussion #1123 (audit backlog, reports, and the
+recheck table against c4b44c34).
+
+You are an independent reviewer. This is a plan for keeping the Go code
+healthy over time, not a feature. Check it against the code and the repo's
+rules.
+
+## What to check
+
+1. The code-health ratchet (Part 2): is the design sound? A test-only
+ package `internal/codehealth` parsing the tree with go/parser and
+ comparing against `.amadan/code-health.tsv`; failing on increase and
+ also on decrease (forcing the record down in the same branch). Will it
+ be stable across parallel branches (merge conflicts in the record), fast
+ enough for the gate, and outside the census as claimed? Are the chosen
+ metrics measurable reliably, and do they track something that matters?
+ Is any metric gameable in a way that makes code worse?
+2. Batch ordering: is anything in batch 3 or 4 more urgent than batch 2?
+ Does the census `moved` class really need to come first for the
+ structural work?
+3. The AGENTS.md rules: each enforceable as stated, and none contradicting
+ existing AGENTS.md rules or the stopping rules?
+4. The monthly pass and quarterly audit: realistic in cost, and do they
+ respect the stopping rules (no review spirals) and the shared-machine
+ CPU budget?
+5. Anything missing that a strong Go team would hold the line on (for this
+ codebase specifically), with evidence.
+6. Factual claims (counts, commits, file:line) against main at c4b44c34.
+
+## Round 2
+
+Earlier rounds: round 1, Astra, `docs/superpowers/reviews/FINDINGS-code-health-plan-R1.md`
+(NOT READY: one P1, six P2s, one P3). The plan is now rev 2.
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not.
+Carry every unresolved or partly resolved finding forward at its current
+severity, then add new findings. The verdict covers everything outstanding.
+
+Rev 2 answers: the ratchet no longer fails on a decrease (so parallel
+decreases merge cleanly), the record command only lowers, a separate CI
+step refuses raised numbers or added sites against the merge base unless
+the line carries a `# raised:` reason; "no new ones" rules are site
+records (package, enclosing function, callee) with explicit MOVE transfers
+that cannot increase an allowance; the database metric is type-based and
+covers DB/Tx/Conn and interfaces with Context forms, in every package;
+line metrics count code lines only; batch 3 now leads with console request
+cancellation in place and the remaining production deadline gaps; `moved`
+is a dependency only of root-graph relocations; the edge sleep branch is
+marked census-touching; the growth figures are corrected and labelled as
+grep estimates; the monthly pass reports and lowers records only through
+a reviewed branch.
+
+## Severity
+
+- **P1**: unsafe, would not work, or contradicts a repo rule. Blocks.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3, each with the section, the problem, evidence
+(file:line, verified), and a concrete fix. End with exactly one verdict:
+READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run builds or tests.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan.md b/docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan.md
new file mode 100644
index 000000000..3398eba48
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-code-health-plan.md
@@ -0,0 +1,48 @@
+# Review brief: plan docs/superpowers/plans/2026-11-16-go-code-health.md, round 1 of 3
+
+Repo carlos/platform, branch `code-health-plan`, commit b2bf354b52353c4621208fe43a4cc4f4916197bf.
+Under review: `docs/superpowers/plans/2026-11-16-go-code-health.md`.
+Authorities: AGENTS.md on main ("Stopping rules", "The census", "Build &
+test"). Context: amadan discussion #1123 (audit backlog, reports, and the
+recheck table against c4b44c34).
+
+You are an independent reviewer. This is a plan for keeping the Go code
+healthy over time, not a feature. Check it against the code and the repo's
+rules.
+
+## What to check
+
+1. The code-health ratchet (Part 2): is the design sound? A test-only
+ package `internal/codehealth` parsing the tree with go/parser and
+ comparing against `.amadan/code-health.tsv`; failing on increase and
+ also on decrease (forcing the record down in the same branch). Will it
+ be stable across parallel branches (merge conflicts in the record), fast
+ enough for the gate, and outside the census as claimed? Are the chosen
+ metrics measurable reliably, and do they track something that matters?
+ Is any metric gameable in a way that makes code worse?
+2. Batch ordering: is anything in batch 3 or 4 more urgent than batch 2?
+ Does the census `moved` class really need to come first for the
+ structural work?
+3. The AGENTS.md rules: each enforceable as stated, and none contradicting
+ existing AGENTS.md rules or the stopping rules?
+4. The monthly pass and quarterly audit: realistic in cost, and do they
+ respect the stopping rules (no review spirals) and the shared-machine
+ CPU budget?
+5. Anything missing that a strong Go team would hold the line on (for this
+ codebase specifically), with evidence.
+6. Factual claims (counts, commits, file:line) against main at c4b44c34.
+
+## Severity
+
+- **P1**: unsafe, would not work, or contradicts a repo rule. Blocks.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+
+Findings ranked P1, P2, P3, each with the section, the problem, evidence
+(file:line, verified), and a concrete fix. End with exactly one verdict:
+READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run builds or tests.
diff --git a/internal/activator/escrow.go b/internal/activator/escrow.go
index cfc7b0542..fc1b3e113 100644
--- a/internal/activator/escrow.go
+++ b/internal/activator/escrow.go
@@ -499,7 +499,27 @@ func (b *ExecBackend) escrowConflict(host string) error {
if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) {
return nil
}
- return fmt.Errorf("ALERT: %s: escrow: the host's local secrets differ from its escrow in the bucket; every launch of the host on this box is refused until an operator settles them against the escrow and removes %s", host, path)
+ return newEscrowAlert("ALERT: %s: escrow: the host's local secrets differ from its escrow in the bucket; every launch of the host on this box is refused until an operator settles them against the escrow and removes %s", host, path)
+}
+
+// escrowAlert is an escrow refusal an operator has to act on. Its text is
+// unchanged, "ALERT: " first (operators and tests read it), but callers
+// recognise one by type with isEscrowAlert, never by that prefix: an alert
+// errors.Join puts second (stageEscrowReads joins a SealedOpenError ahead of
+// one), or one wrapped with context, does not start with it.
+type escrowAlert struct{ msg string }
+
+func (e *escrowAlert) Error() string { return e.msg }
+
+// newEscrowAlert formats an escrowAlert exactly as fmt.Errorf would.
+func newEscrowAlert(format string, args ...any) error {
+ return &escrowAlert{msg: fmt.Sprintf(format, args...)}
+}
+
+// isEscrowAlert reports whether err is, wraps or joins an escrowAlert.
+func isEscrowAlert(err error) bool {
+ var a *escrowAlert
+ return errors.As(err, &a)
}
// writeEscrowConflict persists host's conflict marker, durably.
@@ -1031,7 +1051,7 @@ func (b *ExecBackend) escrowConflictFound(rt registry.Route, p instancePaths, di
if err := b.writeEscrowConflict(rt.Host, diverged); err != nil {
log.Printf("activator: %s: escrow: the conflict marker %s was not written: %v (the launch stays refused while the divergence lasts)", rt.Host, path, err)
}
- err := fmt.Errorf("ALERT: %s: escrow: %s differs from what the host's escrow in the bucket holds, and an escrowed instance.key, report.token or platform-minted env variable is never replaced; the bucket's copy came first, so this launch stops and the local files (%s and the files directory) are left for an operator; every launch of the host on this box is refused until the operator settles them against the escrow and removes %s",
+ err := newEscrowAlert("ALERT: %s: escrow: %s differs from what the host's escrow in the bucket holds, and an escrowed instance.key, report.token or platform-minted env variable is never replaced; the bucket's copy came first, so this launch stops and the local files (%s and the files directory) are left for an operator; every launch of the host on this box is refused until the operator settles them against the escrow and removes %s",
rt.Host, strings.Join(diverged, " and "), p.envFile, path)
log.Print(err)
return err
@@ -1306,7 +1326,7 @@ func (b *ExecBackend) escrowEnvOf(ctx context.Context, rt registry.Route, m host
// errEscrowWriter is the alert a second supersession raises.
func errEscrowWriter(host string) error {
- return fmt.Errorf("ALERT: %s: escrow: another writer publishes this host's escrow", host)
+ return newEscrowAlert("ALERT: %s: escrow: another writer publishes this host's escrow", host)
}
// escrowReread is a superseded publish's second look: the bucket's
@@ -1435,7 +1455,7 @@ func (b *ExecBackend) escrowedLaunchEnv(ctx context.Context, rt registry.Route)
return nil, instancekey.LayerNone, fmt.Errorf("instance key for %s: %w", rt.Host, err)
}
continue
- case err != nil && strings.HasPrefix(err.Error(), "ALERT: "):
+ case isEscrowAlert(err):
return nil, instancekey.LayerNone, err
case errors.Is(err, errEscrowNoLease):
// The lease was lost on the way to the commit, and nothing was
@@ -1650,7 +1670,7 @@ func (b *ExecBackend) EscrowSweep(ctx context.Context, rows []registry.Route) Es
tally.add(func(r *EscrowSweepReport) { r.Failing = append(r.Failing, c.rt.Host) })
// A failure that repeats every sweep (a file the tenant made
// unreadable, say) is said once an hour; an alert every time.
- if strings.HasPrefix(err.Error(), "ALERT: ") {
+ if isEscrowAlert(err) {
log.Print(err)
} else {
logPerFile("escrow", c.rt.Host, fmt.Sprintf("activator: %s: escrow: %v (retried every sweep)", c.rt.Host, err))
diff --git a/internal/activator/escrow_alert_test.go b/internal/activator/escrow_alert_test.go
new file mode 100644
index 000000000..dff6ae942
--- /dev/null
+++ b/internal/activator/escrow_alert_test.go
@@ -0,0 +1,91 @@
+package activator
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestEscrowAlertsAreRecognisedJoinedOrWrapped: each of the three escrow
+// alerts keeps its "ALERT: " text, and is recognised by type whether it is
+// bare, wrapped with %w, or second in an errors.Join, as stageEscrowReads
+// puts it behind a SealedOpenError. A prefix test on the message missed the
+// joined and wrapped forms; an error that merely says "ALERT: " is not one.
+func TestEscrowAlertsAreRecognisedJoinedOrWrapped(t *testing.T) {
+ b, rt := escrowBackend(t, escrowHost)
+ if err := writeEscrowMarker(b.DataDir, rt.Host, []byte("{}")); err != nil {
+ t.Fatal(err)
+ }
+ alerts := map[string]error{
+ "conflict marker": b.escrowConflict(rt.Host),
+ "divergence": b.escrowConflictFound(rt, b.pathsFor(rt), []string{"instance.key"}),
+ "second writer": errEscrowWriter(rt.Host),
+ }
+ other := errors.New("hostfiles: sealed item env: the envelope does not open")
+ for name, alert := range alerts {
+ if alert == nil || !strings.HasPrefix(alert.Error(), "ALERT: "+rt.Host+": escrow: ") {
+ t.Fatalf("%s: %v, want the ALERT text unchanged", name, alert)
+ }
+ for form, err := range map[string]error{
+ "bare": alert,
+ "wrapped": fmt.Errorf("secrets for %s: %w", rt.Host, alert),
+ "joined": errors.Join(other, alert),
+ } {
+ if !isEscrowAlert(err) {
+ t.Errorf("%s, %s: %q not recognised as an alert", name, form, err)
+ }
+ }
+ }
+ for _, err := range []error{nil, other, errors.New("ALERT: not an escrow alert"), errEscrowUnreadable} {
+ if isEscrowAlert(err) {
+ t.Errorf("%v recognised as an escrow alert", err)
+ }
+ }
+}
+
+// TestSweepLogsAJoinedAlertAsAnAlert: after a key change the sealed env no
+// longer opens, so stageEscrowReads joins that read failure with the
+// conflict alert, the read failure first. The sweep must still treat it as
+// an alert: logged as it stands, every time, not as an hourly "retried every
+// sweep" failure. The old prefix test saw only the read failure's text.
+func TestSweepLogsAJoinedAlertAsAnAlert(t *testing.T) {
+ // A host of its own: logPerFile's once-an-hour memory is per process.
+ const host = "alertjoin.example.com"
+ ctx := context.Background()
+ b, rt := escrowBackend(t, host)
+ b.EscrowKey = testEscrowKey(t)
+ writeEnv(t, b, rt, envA)
+ mustPublish(t, b, rt)
+
+ nb := restartEscrow(t, b)
+ nb.EscrowKey = testEscrowKey(t)
+ holdLease(t, nb, rt)
+
+ var buf bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ defer log.SetOutput(prev)
+ rep := nb.EscrowSweep(ctx, []registry.Route{rt})
+ log.SetOutput(prev)
+
+ if len(rep.Failing) != 1 || rep.Failing[0] != host {
+ t.Fatalf("sweep = %+v, want %s failing", rep, host)
+ }
+ if _, err := os.Lstat(escrowConflictPath(nb.DataDir, host)); err != nil {
+ t.Fatalf("no conflict marker, so the joined alert was not raised: %v", err)
+ }
+ out := buf.String()
+ if !strings.Contains(out, "ALERT: "+host+": escrow: ") {
+ t.Fatalf("log = %q, want the alert", out)
+ }
+ if strings.Contains(out, "(retried every sweep)") {
+ t.Fatalf("the joined alert was logged as a routine sweep failure:\n%s", out)
+ }
+}
diff --git a/internal/console/apisubdomain.go b/internal/console/apisubdomain.go
index 6c1484c31..341d905da 100644
--- a/internal/console/apisubdomain.go
+++ b/internal/console/apisubdomain.go
@@ -467,7 +467,11 @@ func (s *Server) subdomainWrite(w http.ResponseWriter, ctx context.Context, acct
}
cur, etag, err := domains.GetClaimETag(ctx, s.cfg.Releases, host)
if errors.Is(err, os.ErrNotExist) {
- newETag, created, err := domains.AttachAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid,
+ // Plain assignment, not :=, so the re-read below a lost race sets
+ // the err the check after this block reads (#1141).
+ var newETag string
+ var created bool
+ newETag, created, err = domains.AttachAccountNamespace(ctx, s.cfg.Releases, name, domain, acct.Sqid,
now.UTC().Format(time.RFC3339), addr)
if err != nil {
unreadable("write", err)
diff --git a/internal/console/apisubdomain_test.go b/internal/console/apisubdomain_test.go
index ebe947589..a910c6fb7 100644
--- a/internal/console/apisubdomain_test.go
+++ b/internal/console/apisubdomain_test.go
@@ -240,6 +240,49 @@ func TestSubdomainDoorRollsBackOnRace(t *testing.T) {
}
}
+// nsLoseCreateStore lands before the door's create-only write of key, once:
+// another writer's claim reaches the key first, so the create loses with a
+// CAS conflict, as it would to a concurrent set from another console.
+type nsLoseCreateStore struct {
+ release.Store
+ key string
+ before func()
+ once sync.Once
+}
+
+func (s *nsLoseCreateStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == s.key && ifMatch == "" && s.before != nil {
+ s.once.Do(s.before)
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+// TestSubdomainSetJudgesTheClaimThatWonTheCreateRace (#1141): the key was
+// empty when the door read it, but bcd's namespace claim landed before the
+// door's create-only write, so the create lost. The door re-reads and judges
+// the claim that won: harbour is bcd's, so the answer is occupied, naming
+// it. The lost-race branch used to shadow err with :=, so the re-read's
+// result never reached the check after it and the set was refused as
+// unreadable (a 502) instead.
+func TestSubdomainSetJudgesTheClaimThatWonTheCreateRace(t *testing.T) {
+ fx, operator, _ := sdFixture(t, "code-sd-lost-create")
+ nsAccount(t, fx, 49, "bcd")
+ fx.srv.cfg.Releases = &nsLoseCreateStore{Store: fx.rel, key: domains.ClaimKey(nsHarbourHost),
+ before: func() { nsHold(t, fx, "harbour", "bcd") }}
+ fx.srv.claims.Reset()
+ code, a, out := sdReq(t, fx, http.MethodPost, "bdq", operator, `{"name":"harbour"}`)
+ want := fmt.Sprintf(subdomainRefuseOccupiedCopy, "harbour."+nsApps)
+ if code != http.StatusConflict || a.Error != want || a.Code != string(domains.SubdomainOccupied) {
+ t.Fatalf("set after losing the create race = %d %s, want 409 %q", code, out, want)
+ }
+ if wantHosts := []sdHost{{Host: nsHarbourHost, Account: "bcd", Source: occupantClaim}}; !reflect.DeepEqual(a.Hosts, wantHosts) {
+ t.Errorf("occupants = %+v, want %+v", a.Hosts, wantHosts)
+ }
+ if c := nsClaimAt(t, fx, nsHarbourHost); c == nil || c.Account != "bcd" {
+ t.Errorf("claim after the lost race = %+v, want bcd's untouched", c)
+ }
+}
+
// nsCachingRaceStore is nsRaceStore over a store that answers ListMod (the
// fixture's DirStore under its deletableStore), so the claim cache caches as
// it does in production, and it counts the reads of each key.
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 6157b416d..09a060570 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -160,7 +160,7 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
// act on by dropping its registry row.
func (s *Server) deletionRefused(w http.ResponseWriter, r *http.Request, acct *Account) bool {
if acct.ID == OpsAccountID {
- s.setFlash(w, "err", deletionAdvice(fmt.Errorf("console: ops")))
+ s.setFlash(w, "err", deletionAdvice(errOpsAccountUndeletable))
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
return true
}
@@ -718,12 +718,17 @@ func deletionAdvice(err error) string {
return "This account still holds apps. Move or retire them first — deleting an account " +
"never deletes an app."
}
- if strings.Contains(err.Error(), "ops") {
+ if errors.Is(err, errOpsAccountUndeletable) {
return "The ops account is the platform's own and cannot be deleted."
}
return "Could not delete this account."
}
+// errOpsAccountUndeletable is DeleteAccount's refusal of the ops account.
+// deletionAdvice matches it with errors.Is: matching "ops" in the message
+// also matched any store error that happened to contain those letters.
+var errOpsAccountUndeletable = errors.New("console: the ops account cannot be deleted")
+
// ---- store ------------------------------------------------------------------
// TransferOwnership promotes `to` and demotes `from`, atomically. Both must
@@ -784,7 +789,7 @@ func (s *Store) TransferOwnership(accountID int64, from, to string, now time.Tim
// done, and a deletion is not a reason to lose it.
func (s *Store) DeleteAccount(accountID int64, now time.Time) error {
if accountID == OpsAccountID {
- return fmt.Errorf("console: the ops account cannot be deleted")
+ return errOpsAccountUndeletable
}
tx, err := s.db.Begin()
if err != nil {
diff --git a/internal/console/store_test.go b/internal/console/store_test.go
index afac6ef3f..38d36bd80 100644
--- a/internal/console/store_test.go
+++ b/internal/console/store_test.go
@@ -1,6 +1,8 @@
package console
import (
+ "errors"
+ "fmt"
"path/filepath"
"reflect"
"sort"
@@ -641,6 +643,30 @@ func TestDeleteAccountRefusesOps(t *testing.T) {
}
}
+// TestDeletionAdviceNamesOpsOnlyForTheOpsRefusal: the ops-account advice is
+// given for DeleteAccount's ops refusal, wrapped or not, and for nothing else.
+// It used to be chosen by finding "ops" anywhere in the error text, so a
+// store failure such as one naming a "workshops" table told the owner their
+// account was the platform's own.
+func TestDeletionAdviceNamesOpsOnlyForTheOpsRefusal(t *testing.T) {
+ const opsAdvice = "The ops account is the platform's own and cannot be deleted."
+ s := openTestStore(t)
+ refusal := s.DeleteAccount(OpsAccountID, time.Now())
+ for _, err := range []error{refusal, fmt.Errorf("delete: %w", refusal)} {
+ if got := deletionAdvice(err); got != opsAdvice {
+ t.Fatalf("deletionAdvice(%v) = %q, want the ops advice", err, got)
+ }
+ }
+ for _, err := range []error{
+ errors.New("no such table: workshops"),
+ errors.New("database is locked; ops retried"),
+ } {
+ if got := deletionAdvice(err); got != "Could not delete this account." {
+ t.Fatalf("deletionAdvice(%v) = %q, want the generic advice", err, got)
+ }
+ }
+}
+
// TestReapAccountClearsAndMarks: materialization's verb for a manifest
// tombstoned on a LATER pass — memberships, invites and apps rows are
// deleted outright, last_account references are cleared, and the accounts
diff --git a/internal/host/haplacement.go b/internal/host/haplacement.go
index 6c6b74425..522c25604 100644
--- a/internal/host/haplacement.go
+++ b/internal/host/haplacement.go
@@ -3,6 +3,7 @@ package host
import (
"context"
"fmt"
+ "log"
"time"
"github.com/carlosframework/platform/internal/activator"
@@ -14,6 +15,10 @@ func armHAPlacement(svc *activator.Service, page func(context.Context, string, s
svc.OnHAOverCapacity = func(region, host, ref string) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- _ = page(ctx, alerting.LevelWarning, fmt.Sprintf("Region %s needs more capacity", region), fmt.Sprintf("Region %s is short on spare capacity. Instance %s is waking on %s. Add capacity to the region.", region, host, ref))
+ if err := page(ctx, alerting.LevelWarning, fmt.Sprintf("Region %s needs more capacity", region), fmt.Sprintf("Region %s is short on spare capacity. Instance %s is waking on %s. Add capacity to the region.", region, host, ref)); err != nil {
+ // As wireRawSecretPages does: a page that fails is logged, or
+ // nobody learns the region ran short.
+ log.Printf("agent: %s: the region %s capacity page failed: %v", host, region, err)
+ }
}
}
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go
index 043e62b7f..7fc96a197 100644
--- a/internal/host/haplacement_wiring_test.go
+++ b/internal/host/haplacement_wiring_test.go
@@ -1,10 +1,13 @@
package host
import (
+ "bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
+ "log"
"net/http/httputil"
"net/url"
"os/exec"
@@ -111,6 +114,25 @@ func TestHAPlacementPageWiring(t *testing.T) {
}
}
+// TestHAPlacementLogsAFailedPage: a capacity page the sink refuses is
+// logged, as the raw-secret page is (wireRawSecretPages). It used to be
+// dropped with _ =, so a region could run short with no trace anywhere.
+func TestHAPlacementLogsAFailedPage(t *testing.T) {
+ var buf bytes.Buffer
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ t.Cleanup(func() { log.SetOutput(prev) })
+ t.Cleanup(func() { setHAAwakeApps(nil) })
+ svc := &activator.Service{}
+ armHAPlacement(svc, func(context.Context, string, string, string) error {
+ return errors.New("sink unreachable")
+ })
+ svc.OnHAOverCapacity("ie", "shop.example.com", "b")
+ if got := buf.String(); !strings.Contains(got, "shop.example.com") || !strings.Contains(got, "region ie capacity page failed: sink unreachable") {
+ t.Fatalf("log = %q, want the failed capacity page", got)
+ }
+}
+
func armHAPlacementWitness(svc *activator.Service, sink func(context.Context, string, string, string) error) {
if os.Getenv("RHASIM_MUTATE") == "placement-skips-arm" {
return
diff --git a/internal/ledger/verify.go b/internal/ledger/verify.go
index 97cd9debb..a99628905 100644
--- a/internal/ledger/verify.go
+++ b/internal/ledger/verify.go
@@ -38,6 +38,37 @@ func HTTPGetter(client *http.Client, base string) Getter {
}
}
+// checkHead refuses a HEAD that cannot name a chain. There is no empty
+// ledger HEAD: Append writes HEAD.json only after the entry it points at, so
+// a ledger with no entries has no HEAD object and the GET for it fails.
+// Every HEAD therefore names at least one entry: a non-empty head_key, that
+// entry's sha256 as 64 lowercase hex digits, and a count of one or more.
+// Without this a HEAD of {} or null decodes to the zero value, the walk never
+// starts, and the empty chain "verifies" with no head digest at all.
+func checkHead(h Head) error {
+ switch {
+ case h.Count < 1:
+ return fmt.Errorf("ledger: HEAD malformed: count %d, a HEAD names at least one entry", h.Count)
+ case h.HeadKey == "":
+ return fmt.Errorf("ledger: HEAD malformed: no head_key")
+ case !isSHA256Hex(h.HeadSHA256):
+ return fmt.Errorf("ledger: HEAD malformed: head_sha256 %q is not a sha256 digest", h.HeadSHA256)
+ }
+ return nil
+}
+
+func isSHA256Hex(s string) bool {
+ if len(s) != 64 {
+ return false
+ }
+ for _, c := range s {
+ if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
+ return false
+ }
+ }
+ return true
+}
+
type VerifyResult struct {
Count int
HeadSHA256 string
@@ -56,6 +87,9 @@ func Verify(ctx context.Context, get Getter, sqid, app, name string) (VerifyResu
if err := json.Unmarshal(hb, &head); err != nil {
return VerifyResult{}, fmt.Errorf("ledger: HEAD corrupt: %w", err)
}
+ if err := checkHead(head); err != nil {
+ return VerifyResult{}, err
+ }
// The walk follows keys the CHAIN supplies (HEAD.json's head_key, then
// each entry's prev_key), so those keys are exactly as trustworthy as the
diff --git a/internal/ledger/verify_test.go b/internal/ledger/verify_test.go
index 4139c2fab..c16eb1289 100644
--- a/internal/ledger/verify_test.go
+++ b/internal/ledger/verify_test.go
@@ -134,3 +134,41 @@ func TestVerifyOverHTTP(t *testing.T) {
t.Fatalf("res=%+v err=%v", res, err)
}
}
+
+// TestVerifyRefusesMalformedHead: a HEAD that decodes but names no chain
+// ({}, null, a zero count, a missing key, a digest that is not a sha256) is
+// refused, never reported as a clean empty ledger. Before checkHead, {} and
+// null decoded to the zero Head, the walk never started, and Verify returned
+// success with an empty HeadSHA256, which the CLI then sliced and panicked on.
+func TestVerifyRefusesMalformedHead(t *testing.T) {
+ ctx := context.Background()
+ key := Prefix("bab", "platform", "carbon") + "entries/x.json"
+ sha := strings.Repeat("a", 64)
+ for name, head := range map[string]string{
+ "empty object": `{}`,
+ "null": `null`,
+ "zero count": `{"head_key":"` + key + `","head_sha256":"` + sha + `","count":0}`,
+ "negative count": `{"count":-1}`,
+ "no key": `{"head_sha256":"` + sha + `","count":1}`,
+ "no digest": `{"head_key":"` + key + `","count":1}`,
+ "short digest": `{"head_key":"` + key + `","head_sha256":"abc","count":1}`,
+ "upper digest": `{"head_key":"` + key + `","head_sha256":"` + strings.Repeat("A", 64) + `","count":1}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ get := func(_ context.Context, k string) ([]byte, error) {
+ if k == HeadKey("bab", "platform", "carbon") {
+ return []byte(head), nil
+ }
+ t.Fatalf("walked to %s from a malformed HEAD", k)
+ return nil, nil
+ }
+ res, err := Verify(ctx, get, "bab", "platform", "carbon")
+ if err == nil {
+ t.Fatalf("HEAD %s verified: %+v", head, res)
+ }
+ if !strings.Contains(err.Error(), "HEAD malformed") {
+ t.Fatalf("error = %v, want it to say the HEAD is malformed", err)
+ }
+ })
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv b/internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv
new file mode 100644
index 000000000..683200eee
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-audit-bugs-2.tsv
@@ -0,0 +1,14 @@
+# Census overlay audit-bugs-2, written by census-propose (#369). census-ruling-audit-bugs-2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-audit-bugs-2.md.
+# 4 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy 51a7ec904ec6d600eaa102b5d87f46c9c3d9417745dc91b9106420b3a7a00051 internal/activator/escrow.go ExecBackend.EscrowSweep legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the agent as carlos (carlos-edge.service), no root caller, from escrowLoop: classifies each row against the rows handed in (Classify), keeps eligible rows known not HA from memory (haKnown, no read), and in host order from a round-robin cursor stats each escrowed file (stampAt) and publishes the changed ones, 8 at a time, at most 256 a sweep (sweepPublish); a box without a files store or key does nothing; opens nothing outside the rows' own data directories; writes only the hibernate bucket's files/0 prefix and the ledger Fix round 1: a host whose instance lease this box does not hold (holdsLease) is skipped, and one with a conflict marker counts as failing and is not published; the report is tallied through one lock (P1-4). Durability 3a Task 5: for each lease-held candidate, the host's held publisher (st.pub under the escrow lock) is handed to noteRawBaseline. Reads only manifests this process already holds (no request, no file opened); calls the detector, which logs and calls ExecBackend.OnRawSecret; nothing else changes. The +registry:Host sites are rt.Host as the state key and the detector's argument.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: use coordinator authority for stateless projections and the unchanged serving lease for stateful rows; followers are skipped without I/O; no new poll loop or file path.;rev3=census-ruling-audit-bugs-2;basis=a failed publish is logged as an alert when isEscrowAlert (errors.As on the new escrowAlert type) says so, instead of strings.HasPrefix(err.Error(), "ALERT: "), so a joined or wrapped alert is logged plainly rather than once an hour as a routine failure; logging only, no new read registry:Host@1009,registry:Host@1046,registry:Host@1136,registry:Host@1292,registry:Host@1311,registry:Host@1462,registry:Host@1995,registry:Host@2341,registry:Host@2575,registry:Host@2649,registry:Host@536,registry:Host@800,registry:Host@938,whole:Route@1193,whole:Route@1197,whole:Route@1214,whole:Route@1301,whole:Route@1320,whole:Route@1471,whole:Route@1789,whole:Route@1997,whole:Route@2227,whole:Route@2343,whole:Route@2577,whole:Route@2651,whole:Route@356,whole:Route@519,whole:Route@587,whole:Route@653,whole:Route@706,whole:Route@771 1e14fab5e73211227bc9e3149d0b2ebd8275776b9e29b186bb66df72f12bb626
+@legacy 4e7267d7dedb59073fb53828c363fd955744195215cf62f75cb88999946943b6 internal/activator/escrow.go ExecBackend.escrowConflict legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 1: new: os.Lstat of <data>/.escrow/<host>.conflict, the agent's own directory; present, every launch, mint and publish of the host is refused with an alert naming the file for an operator to remove; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 2: the alert text names the divergence generally (local secrets differ from the escrow); the same Lstat.;rev3=census-ruling-audit-bugs-2;basis=the refusal is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same Lstat, no new read file:Lstat@117 2813507167377d322febb10abcb556a42d56f1a4b0715bbf190da36dd8e63c40
+@legacy 5de0a4472b24b196937fe2ea4749207e45a3cd2f1caad5e14669d5bd5124ad60 internal/activator/escrow.go ExecBackend.escrowConflictFound legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 2: new: the refusal for a divergent trio item: tries to write the host's conflict marker (writeEscrowMarker: EnsureDirBeneath <data>/.escrow 0700, a 0600 temp, rename, fsync), logs if it cannot, and returns the alert; the refusal holds either way, since every later publish finds the same divergence; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 3: the alert names the env file too, since a platform-minted env variable can diverge; the same marker write.;rev3=census-ruling-audit-bugs-2;basis=the alert is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same marker write, no new read registry:Host@144,registry:Host@186,registry:Host@355,registry:Host@819 0d17cb55ff4c39a7d079fcf81d6900467347159b3c35d01bd2358dc457a99a82
+@legacy a01e384e755d13eccb2be5fddb1cef0f68946fb6a8c9062309b5a0dfe6ce91ea internal/activator/escrow.go ExecBackend.escrowedLaunchEnv legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the launch path for an eligible host: captureLaunchEnv once, publishEscrowAt over those bytes, SealedAcknowledged on the commit, and the env parsed from the captured bytes; on a supersession escrowReread and the launch preparation again (ensureAdminTokenFor, ensureInstanceKeyFor) once; a not-ready box launches only a host its ledger shows escrowed; the agent as carlos (carlos-edge.service), no root caller Fix round 0 (controller readiness ruling): before the capture, the box's mode: no files store, instanceEnvLayer exactly as before 3a (logged once); no sealing key, a host whose ledger shows it escrowed launches on instanceEnvLayer (logged), otherwise keylessEscrowed (the answer this launch's restore read, within haSecretsBudget, else one GET) refuses when the bucket holds an escrow and launches on instanceEnvLayer when it holds none; nothing is published in either. Fix round 1: ends the launch's preparation; refuses while the conflict marker exists, and with a key while this box does not hold the host's lease; an ALERT from the publish fails the launch; the keyless decision uses the preparation's read. Fix round 3: a publish that answers errEscrowNoLease (the lease lost before the commit) refuses the launch with an error saying so, never the later-launch fallback. Fix round 4: a publish that answers errEscrowUnreadable or ErrEscrowNotReady (the manifest or sealed env could not be read, or does not open here) refuses the launch, never the later-launch fallback; only refuses.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: followers take read-only escrow verification/restore and never open the publisher; stateless coordinator requires ready escrow. Existing stateful publish, first-launch and conflict branches preserved.;rev3=census-ruling-audit-bugs-2;basis=the publish's alert branch matches isEscrowAlert(err) (errors.As) instead of the "ALERT: " prefix, so a joined or wrapped alert also refuses the launch as an alert; a joined alert was already refused via errEscrowUnreadable; only refuses, no new read registry:Host@1012,registry:Host@1115,registry:Host@1242,registry:Host@1390,registry:Host@145,registry:Host@1545,registry:Host@1630,registry:Host@1798,registry:Host@2000,registry:Host@2262,registry:Host@2423,registry:Host@2842,registry:Host@3245,registry:Host@3413,registry:Host@3534,registry:Host@3708,registry:Host@3924,registry:Host@441,registry:Host@838,registry:Host@967,registry:Stateless@158,registry:Stateless@249,whole:Route@1162,whole:Route@1313,whole:Route@1452,whole:Route@1678,whole:Route@1907,whole:Route@198,whole:Route@2165,whole:Route@2325,whole:Route@238,whole:Route@290,whole:Route@408,whole:Route@534,whole:Route@577,whole:Route@622,whole:Route@672,whole:Route@719,whole:Route@894,whole:Route@938 3b98f460b501e2b650cf5502c2407dcdaf281d8aabd0930e9fd09e1fb9e0249e
+internal/activator/escrow.go ExecBackend.EscrowSweep legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the agent as carlos (carlos-edge.service), no root caller, from escrowLoop: classifies each row against the rows handed in (Classify), keeps eligible rows known not HA from memory (haKnown, no read), and in host order from a round-robin cursor stats each escrowed file (stampAt) and publishes the changed ones, 8 at a time, at most 256 a sweep (sweepPublish); a box without a files store or key does nothing; opens nothing outside the rows' own data directories; writes only the hibernate bucket's files/0 prefix and the ledger Fix round 1: a host whose instance lease this box does not hold (holdsLease) is skipped, and one with a conflict marker counts as failing and is not published; the report is tallied through one lock (P1-4). Durability 3a Task 5: for each lease-held candidate, the host's held publisher (st.pub under the escrow lock) is handed to noteRawBaseline. Reads only manifests this process already holds (no request, no file opened); calls the detector, which logs and calls ExecBackend.OnRawSecret; nothing else changes. The +registry:Host sites are rt.Host as the state key and the detector's argument.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: use coordinator authority for stateless projections and the unchanged serving lease for stateful rows; followers are skipped without I/O; no new poll loop or file path.;rev3=census-ruling-audit-bugs-2;basis=a failed publish is logged as an alert when isEscrowAlert (errors.As on the new escrowAlert type) says so, instead of strings.HasPrefix(err.Error(), "ALERT: "), so a joined or wrapped alert is logged plainly rather than once an hour as a routine failure; logging only, no new read registry:Host@1009,registry:Host@1046,registry:Host@1136,registry:Host@1292,registry:Host@1311,registry:Host@1462,registry:Host@1995,registry:Host@2341,registry:Host@2575,registry:Host@2649,registry:Host@536,registry:Host@800,registry:Host@938,whole:Route@1193,whole:Route@1197,whole:Route@1214,whole:Route@1301,whole:Route@1320,whole:Route@1471,whole:Route@1789,whole:Route@1997,whole:Route@2227,whole:Route@2343,whole:Route@2577,whole:Route@2651,whole:Route@356,whole:Route@519,whole:Route@587,whole:Route@653,whole:Route@706,whole:Route@771 1e14fab5e73211227bc9e3149d0b2ebd8275776b9e29b186bb66df72f12bb626
+internal/activator/escrow.go ExecBackend.escrowConflict legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 1: new: os.Lstat of <data>/.escrow/<host>.conflict, the agent's own directory; present, every launch, mint and publish of the host is refused with an alert naming the file for an operator to remove; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 2: the alert text names the divergence generally (local secrets differ from the escrow); the same Lstat.;rev3=census-ruling-audit-bugs-2;basis=the refusal is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same Lstat, no new read file:Lstat@117 2813507167377d322febb10abcb556a42d56f1a4b0715bbf190da36dd8e63c40
+internal/activator/escrow.go ExecBackend.escrowConflictFound legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4 fix round 2: new: the refusal for a divergent trio item: tries to write the host's conflict marker (writeEscrowMarker: EnsureDirBeneath <data>/.escrow 0700, a 0600 temp, rename, fsync), logs if it cannot, and returns the alert; the refusal holds either way, since every later publish finds the same divergence; only refuses; the agent as carlos (carlos-edge.service), no root caller Fix round 3: the alert names the env file too, since a platform-minted env variable can diverge; the same marker write.;rev3=census-ruling-audit-bugs-2;basis=the alert is built with newEscrowAlert (an escrowAlert with the identical text) instead of fmt.Errorf; the same marker write, no new read registry:Host@144,registry:Host@186,registry:Host@355,registry:Host@819 0d17cb55ff4c39a7d079fcf81d6900467347159b3c35d01bd2358dc457a99a82
+internal/activator/escrow.go ExecBackend.escrowedLaunchEnv legacy accepted-legacy accepted-legacy;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 4: new, the launch path for an eligible host: captureLaunchEnv once, publishEscrowAt over those bytes, SealedAcknowledged on the commit, and the env parsed from the captured bytes; on a supersession escrowReread and the launch preparation again (ensureAdminTokenFor, ensureInstanceKeyFor) once; a not-ready box launches only a host its ledger shows escrowed; the agent as carlos (carlos-edge.service), no root caller Fix round 0 (controller readiness ruling): before the capture, the box's mode: no files store, instanceEnvLayer exactly as before 3a (logged once); no sealing key, a host whose ledger shows it escrowed launches on instanceEnvLayer (logged), otherwise keylessEscrowed (the answer this launch's restore read, within haSecretsBudget, else one GET) refuses when the bucket holds an escrow and launches on instanceEnvLayer when it holds none; nothing is published in either. Fix round 1: ends the launch's preparation; refuses while the conflict marker exists, and with a key while this box does not hold the host's lease; an ALERT from the publish fails the launch; the keyless decision uses the preparation's read. Fix round 3: a publish that answers errEscrowNoLease (the lease lost before the commit) refuses the launch with an error saying so, never the later-launch fallback. Fix round 4: a publish that answers errEscrowUnreadable or ErrEscrowNotReady (the manifest or sealed env could not be read, or does not open here) refuses the launch, never the later-launch fallback; only refuses.;rev3=census-ruling-stateless-replicas-1;basis=Task 3b: followers take read-only escrow verification/restore and never open the publisher; stateless coordinator requires ready escrow. Existing stateful publish, first-launch and conflict branches preserved.;rev3=census-ruling-audit-bugs-2;basis=the publish's alert branch matches isEscrowAlert(err) (errors.As) instead of the "ALERT: " prefix, so a joined or wrapped alert also refuses the launch as an alert; a joined alert was already refused via errEscrowUnreadable; only refuses, no new read registry:Host@1012,registry:Host@1115,registry:Host@1242,registry:Host@1390,registry:Host@145,registry:Host@1545,registry:Host@1630,registry:Host@1798,registry:Host@2000,registry:Host@2262,registry:Host@2423,registry:Host@2842,registry:Host@3245,registry:Host@3413,registry:Host@3534,registry:Host@3708,registry:Host@3924,registry:Host@441,registry:Host@838,registry:Host@967,registry:Stateless@158,registry:Stateless@249,whole:Route@1162,whole:Route@1313,whole:Route@1452,whole:Route@1678,whole:Route@1907,whole:Route@198,whole:Route@2165,whole:Route@2325,whole:Route@238,whole:Route@290,whole:Route@408,whole:Route@534,whole:Route@577,whole:Route@622,whole:Route@672,whole:Route@719,whole:Route@894,whole:Route@938 3b98f460b501e2b650cf5502c2407dcdaf281d8aabd0930e9fd09e1fb9e0249e
+@coverage . e0e1c2cf1540c9e2c196b7ed48b23c2a666d296157de709ca06b45236e770f83
+@coverage internal/activator 09d8de3860da15a033b9b5230383bec93eb95cff029659f7dd001ac64e958eab
+@coverage internal/host ed966179bf9c3c818a815ca284d4fd59c0bf6602bf84a9f6a1d1e91d03e4a73f
+@coverage internal/ledger 01aa8d104e7820e67739da46c184cc3c27d252e8584fe7d25e28909d14311024
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 62225b972..cb0019cd5 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -242,3 +242,4 @@ plan14-root-reads-audit-edge-test-sleeps.tsv 4abde13ec40d53a479684b7f1e2079fbedb
plan14-root-reads-ha-generations-floor.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54
plan14-root-reads-fix-1193-wal-close-test.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54
plan14-root-reads-ha-1192.tsv 8df52839a0c961d3721f3a5c3247d06202dae4e00d011844b7117f8e918803d4
+plan14-root-reads-audit-bugs-2.tsv 1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1
diff --git a/system.go b/system.go
index 3dc87b9c9..4702c331f 100644
--- a/system.go
+++ b/system.go
@@ -385,7 +385,11 @@ func runSystemUpdate(args []string) {
log.Fatalf("carlos system update: %s", apiErrorFromBody(st, body))
}
var cur systemStatusResponse
- _ = json.Unmarshal(body, &cur)
+ if err := json.Unmarshal(body, &cur); err != nil {
+ // Read on, and the preview below would say "0 box(es) will roll"
+ // about a promote that may reach every box.
+ log.Fatalf("carlos system update: could not read the console's system status, so there is no telling which boxes this would reach; nothing was promoted (%v)", err)
+ }
var reach []string
for _, b := range cur.Boxes {
if b.Channel == *channel {
@@ -455,11 +459,11 @@ func runSystemUpdate(args []string) {
}
log.Fatalf("carlos system update: %s", apiErrorFromBody(st, body))
}
- var started struct {
- Job string `json:"job"`
+ job, err := systemUpdateJob(body, *channel)
+ if err != nil {
+ log.Fatal(err)
}
- _ = json.Unmarshal(body, &started)
- if err := sess.watchSystemJob(ctx, started.Job, stdout); err != nil {
+ if err := sess.watchSystemJob(ctx, job, stdout); err != nil {
log.Fatal(err)
}
fmt.Fprintf(stdout, "%s boxes on %s roll themselves; watch with: carlos system status --channel %s\n",
@@ -486,11 +490,31 @@ func systemLadderWarning(pointers map[string]*systemPointerRow, channel, version
return fmt.Sprintf("warning: %s has not been on canary; promoting straight to stable", version)
}
+// systemUpdateJob reads the job id out of the console's 200 answer to a
+// promote. The promote is already under way by then, so neither refusal
+// says it failed: each says the job cannot be watched from here and where
+// to look instead. An empty id used to be polled as /jobs/ for 15 minutes.
+func systemUpdateJob(body []byte, channel string) (string, error) {
+ var started struct {
+ Job string `json:"job"`
+ }
+ if err := json.Unmarshal(body, &started); err != nil {
+ return "", fmt.Errorf("carlos system update: the console accepted the promote but its answer could not be read (%v); follow it with: carlos system status --channel %s", err, channel)
+ }
+ if started.Job == "" {
+ return "", fmt.Errorf("carlos system update: the console accepted the promote but named no job to watch; follow it with: carlos system status --channel %s", channel)
+ }
+ return started.Job, nil
+}
+
// watchSystemJob polls the job and prints each step once, as deploy's
// watchVersion does for a route. The console runs the promote off the
// request precisely so a dropped connection cannot abandon it, so this is a
// view of work already under way, not the work itself.
func (s *apiSession) watchSystemJob(ctx context.Context, id string, w io.Writer) error {
+ if id == "" {
+ return errors.New("carlos system update: no job to watch")
+ }
printed := 0
deadline := time.Now().Add(15 * time.Minute)
for {
@@ -506,7 +530,11 @@ func (s *apiSession) watchSystemJob(ctx context.Context, id string, w io.Writer)
Done bool `json:"done"`
Error string `json:"error"`
}
- _ = json.Unmarshal(body, &j)
+ if err := json.Unmarshal(body, &j); err != nil {
+ // An unreadable answer never says done, so polling on would
+ // spin for the whole 15 minutes on a reply that will not change.
+ return fmt.Errorf("carlos system update: job %s: could not read the console's progress report (%v); the promote may still be running", id, err)
+ }
for ; printed < len(j.Steps); printed++ {
fmt.Fprintf(w, " %s\n", j.Steps[printed])
}
@@ -688,11 +716,24 @@ func runSystemRollback(args []string) {
if st != http.StatusOK {
log.Fatalf("carlos system rollback: %s", apiErrorFromBody(st, body))
}
+ printSystemRolledBack(stdout, *channel, body)
+}
+
+// printSystemRolledBack reports a rollback the console has already done
+// (it answered 200). An answer that cannot be read or names no version
+// still means the rollback happened, so this never fails the command: a
+// non-zero exit would invite a second rollback, one release further back.
+// It says the version is unknown and where to read it instead.
+func printSystemRolledBack(w io.Writer, channel string, body []byte) {
var out struct {
Version string `json:"version"`
}
- _ = json.Unmarshal(body, &out)
- fmt.Fprintf(stdout, "%s %s → %s\n", colorFor(stdout).ok("rolled back"), *channel, out.Version)
+ if err := json.Unmarshal(body, &out); err != nil || out.Version == "" {
+ fmt.Fprintf(w, "%s %s; the console did not say which release it is on now. check with: carlos system status --channel %s\n",
+ colorFor(w).ok("rolled back"), channel, channel)
+ return
+ }
+ fmt.Fprintf(w, "%s %s → %s\n", colorFor(w).ok("rolled back"), channel, out.Version)
}
// systemPDFCommand is `carlos system pdf status`. Bare is the usage and
diff --git a/system_test.go b/system_test.go
index bafb4f22e..cda1616c5 100644
--- a/system_test.go
+++ b/system_test.go
@@ -11,6 +11,7 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "sync/atomic"
"testing"
"time"
)
@@ -432,3 +433,86 @@ func TestSystemGroupMaintenanceVerb(t *testing.T) {
}
}
}
+
+// TestSystemUpdateJobRefusesNoJob: the console's 200 answer to a promote
+// must name a job. An unreadable answer or one with no id is refused with
+// where to follow the promote instead; before, both came out as "" and the
+// CLI polled /api/cli/system/jobs/ for 15 minutes.
+func TestSystemUpdateJobRefusesNoJob(t *testing.T) {
+ for _, body := range []string{`{}`, `{"job":""}`, `not json`, ``} {
+ job, err := systemUpdateJob([]byte(body), "canary")
+ if err == nil {
+ t.Fatalf("answer %q gave job %q, want a refusal", body, job)
+ }
+ if !strings.Contains(err.Error(), "carlos system status --channel canary") {
+ t.Fatalf("answer %q: %v, want it to say where to follow the promote", body, err)
+ }
+ }
+ if job, err := systemUpdateJob([]byte(`{"job":"j1"}`), "canary"); err != nil || job != "j1" {
+ t.Fatalf("job = %q, %v; want j1", job, err)
+ }
+}
+
+// TestWatchSystemJobStopsOnNoJobOrUnreadableReport: watchSystemJob never polls
+// an empty id, and a progress report it cannot read ends the watch at once
+// instead of polling an answer that will never say done for 15 minutes.
+func TestWatchSystemJobStopsOnNoJobOrUnreadableReport(t *testing.T) {
+ var emptyPolls, jobPolls atomic.Int32
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/cli/system/jobs/":
+ emptyPolls.Add(1)
+ w.Write([]byte(`{}`))
+ case "/api/cli/system/jobs/j1":
+ jobPolls.Add(1)
+ w.Write([]byte(`<html>not a job</html>`))
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(ts.Close)
+ sess := &apiSession{c: newConsoleClient(ts.URL, "tok"), console: ts.URL}
+
+ watch := func(id string) error {
+ done := make(chan error, 1)
+ go func() { done <- sess.watchSystemJob(context.Background(), id, io.Discard) }()
+ select {
+ case err := <-done:
+ return err
+ case <-time.After(5 * time.Second):
+ t.Fatalf("watchSystemJob(%q) still polling after 5s", id)
+ return nil
+ }
+ }
+ if err := watch(""); err == nil {
+ t.Fatal("watched a job with no id")
+ }
+ if n := emptyPolls.Load(); n != 0 {
+ t.Fatalf("polled /api/cli/system/jobs/ %d times for an empty id", n)
+ }
+ err := watch("j1")
+ if err == nil || !strings.Contains(err.Error(), "could not read") {
+ t.Fatalf("unreadable report: %v, want a could-not-read error", err)
+ }
+ if n := jobPolls.Load(); n != 1 {
+ t.Fatalf("polled j1 %d times, want 1", n)
+ }
+}
+
+// TestSystemRollbackReportsAnUnreadableAnswer: a rollback the console has
+// done is reported as done even when its answer names no version, and the
+// line says where to read the version rather than ending in a blank arrow.
+func TestSystemRollbackReportsAnUnreadableAnswer(t *testing.T) {
+ for _, body := range []string{`{}`, `not json`} {
+ var out bytes.Buffer
+ printSystemRolledBack(&out, "canary", []byte(body))
+ if !strings.Contains(out.String(), "rolled back canary;") || !strings.Contains(out.String(), "carlos system status --channel canary") {
+ t.Fatalf("answer %q printed %q", body, out.String())
+ }
+ }
+ var out bytes.Buffer
+ printSystemRolledBack(&out, "canary", []byte(`{"version":"v0.31.0"}`))
+ if !strings.Contains(out.String(), "canary → v0.31.0") {
+ t.Fatalf("printed %q", out.String())
+ }
+}