carlos / platform Public

Merge remote-tracking branch 'origin/main' into named-units-param-114

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c31a92285bfdeecab2aeb9c5034d02822390bdee parent 12dcd4aparent ed6ae02
28 files changed, +2,151 −37
  • .amadan/README.md +54 −3
  • .amadan/ci.d/80-gitleaks +32 −0
  • .gitleaks.toml +135 −0
  • AGENTS.md +11 −0
  • Makefile +20 −1
  • docs/superpowers/notes/census-proposal-flake-lease-teardown.md +11 −0
  • docs/superpowers/reviews/FINDINGS-flake-demo-browser-siblings.md +23 −0
  • docs/superpowers/reviews/FINDINGS-flake-demo-claim-browser.md +31 −0
  • docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md +31 −0
  • docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md +41 −0
  • docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md +21 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-browser-siblings.md +219 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-claim-browser.md +150 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md +157 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md +94 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md +53 −0
  • internal/console/testdata/demo_claim_browser.mjs +47 −5
  • internal/console/testdata/demo_claim_kept_browser.mjs +19 −0
  • internal/console/testdata/demo_claim_motion.mjs +5 −4
  • internal/console/testdata/demo_claim_resume_browser.mjs +52 −19
  • internal/lease/lease.go +2 −1
  • internal/lease/snapshotpipe.go +36 −0
  • internal/lease/teardown_linux_test.go +192 −4
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv +3 −0
  • scripts/gitleaks-gate/main.go +367 −0
  • scripts/gitleaks-gate/notscanned.go +49 −0
  • scripts/gitleaks-gate/selftest.go +295 −0

CI failed — run details

diff --git a/.amadan/README.md b/.amadan/README.md
index 622b31f8a..2d7dddce4 100644
--- a/.amadan/README.md
+++ b/.amadan/README.md
@@ -33,10 +33,10 @@ no longer exists.
| `minio-contract` | `30-minio-contract` | MinIO on loopback, no container |
| `gofmt` | `10-gate` | repo-wide, via `make test` — see below |
-Six checks have no ancestor; the deleted workflow never ran them. The
+Seven checks have no ancestor; the deleted workflow never ran them. The
first three were added on 2026-11-16 after a code audit found the gate
-could not see them, and the code-health ratchet's two and the race
-detector on 2026-11-17.
+could not see them, the code-health ratchet's two and the race detector
+on 2026-11-17, and gitleaks on 2026-11-18.
| added | here | |
|---|---|---|
@@ -46,6 +46,7 @@ detector on 2026-11-17.
| code-health gate | `60-code-health` | `make code-health`: the code against `.amadan/code-health.tsv`, scanned with type information; see below |
| code-health record | `61-code-health-record` | the record against the merge base's copy; see below |
| race detector | `70-race` | `make race`: `go test -race` over the edge, rootaws and systemd packages and host's loop and lease tests, sharded like the gate; see below |
+| `gitleaks` | `80-gitleaks` | `make gitleaks`: v8.30.1 over the tracked files, after proving that planted keys are still reported; see below |
## `govulncheck`: what turns it red
@@ -147,6 +148,56 @@ step with that bump.
`-race` needs cgo, so the target sets `CGO_ENABLED=1`, and the runner
needs a C compiler.
+## `gitleaks`: what turns it red
+
+`80-gitleaks` runs `make gitleaks`, which installs gitleaks v8.30.1 and
+hands it to `scripts/gitleaks-gate`. The gate scans the tracked files as
+they are in the working tree, not the history. Untracked files are left
+out. The step fails when:
+
+- gitleaks reports anything that `.gitleaks.toml` does not allow by exact
+ value;
+- a planted key goes unreported, or a file is left out that
+ `notscanned.go` does not name (the self-test, below);
+- `scripts/gitleaks-gate/notscanned.go` names a path git does not track;
+- gitleaks is missing or is not the pinned version, its config does not
+ load, its report cannot be read, or the scan misses the key the gate
+ plants beside the tracked files;
+- a `.gitleaksignore` is tracked. Allowances are made by value, in
+ `.gitleaks.toml`, and `gitleaks:allow` comments are ignored.
+
+**Some files are not scanned at all.** Census test files pin a sha256
+digest of each unit's source, and `implementation/always-awake-consumers.json`
+pins one per file in `source_hashes`. Those are content digests, not
+secrets, but gitleaks' generic rule reads a digest as a key, and nothing in
+a 64-character hex value tells the two apart. So the gate leaves those files
+out whole. `scripts/gitleaks-gate/notscanned.go` names each one by its
+exact repository path: no globs, no directories, only the 26 files gitleaks
+flags today. A credential committed in one of them is not found. A file
+renamed away from its entry is scanned under its new name, and an entry
+for a path git does not track fails the step.
+
+If a new census layer turns the step red, check that every finding in it is
+a digest, then add the file's exact path to `notscanned.go`.
+
+**The self-test runs first, on every scan.** It plants keys generated at
+run time in ordinary source and in an allowed fixture, and scans each case
+with gitleaks' default rules alone as well, so a case the rules would never
+flag fails instead of passing for free. Then it builds a small git
+repository and scans it the way the real scan does: a tracked file named
+`gitleaks-gate-sentinel.env` (the gate's own planted key once used that
+name) must be reported, every file `notscanned.go` names must be left out,
+and the same key under a near miss of each name must be reported. It also
+checks that a broken config, a missing binary and a stale list entry fail
+the scan.
+
+The gate's own planted key goes in a file with a new random name on each
+run, created only if nothing is there, so it can never replace a tracked
+file.
+
+The log names the file and line of a finding and never its value. It needs
+the Go module proxy, to fetch gitleaks.
+
## `gofmt`: ported by widening it, not by reproducing it
This section is the reason it was safe to delete the workflow, so it is
diff --git a/.amadan/ci.d/80-gitleaks b/.amadan/ci.d/80-gitleaks
new file mode 100755
index 000000000..900fd79c4
--- /dev/null
+++ b/.amadan/ci.d/80-gitleaks
@@ -0,0 +1,32 @@
+#!/bin/sh
+# Secrets committed to the tracked files: gitleaks v8.30.1, pinned, with its
+# default rules. `make gitleaks` is the one definition; this step only runs
+# it, so a developer gets the same answer with the same command.
+#
+# Its own step, not part of `make test`, for staticcheck's reasons: a red
+# here is a finding, not a failed test, and `make test` stays no slower.
+#
+# The tree, not the history: what a branch adds is found in the run that
+# adds it, and old values already in every clone would hold every branch red.
+#
+# Not scanned at all: the census test files and the design checklist that
+# scripts/gitleaks-gate/notscanned.go names by exact path. They hold sha256
+# digests of source, not secrets, and a key committed in one is not found.
+#
+# Red means one of:
+# - a value gitleaks takes for a secret. Remove it, and rotate it if it was
+# ever real. A fake a test needs is allowed by exact value in
+# .gitleaks.toml, with its reason;
+# - the self-test: a planted key went unreported, or a file other than the
+# ones notscanned.go names was left out (scripts/gitleaks-gate/selftest.go);
+# - notscanned.go names a path git does not track;
+# - a scan that could not run: no binary, the wrong version, a config that
+# does not load. None of these passes.
+#
+# The log names the file and line of a finding, never its value.
+#
+# Network: the Go module proxy, to fetch gitleaks, as every step already uses.
+set -eu
+. .amadan/go-toolchain.sh
+
+make gitleaks
diff --git a/.gitleaks.toml b/.gitleaks.toml
new file mode 100644
index 000000000..b52233128
--- /dev/null
+++ b/.gitleaks.toml
@@ -0,0 +1,135 @@
+# gitleaks' default rules, less the values this repository commits on
+# purpose. `make gitleaks` (.amadan/ci.d/80-gitleaks) scans the tracked files
+# with it, through scripts/gitleaks-gate.
+#
+# Every allowance here names exact values, anchored, so a value that merely
+# contains one is still found. Where a value only belongs in some files, the
+# allowance is scoped to them (condition AND: a path and a value), so the
+# same value anywhere else still fails the gate.
+#
+# Some files are NOT SCANNED AT ALL: the census test files that pin sha256
+# digests of source, and the design checklist,
+# implementation/always-awake-consumers.json, which pins one per file in
+# source_hashes. They hold content digests, not secrets, but gitleaks'
+# generic rule reads a digest as a key and no allowance can tell the two
+# apart. So scripts/gitleaks-gate leaves those files out whole, each named
+# by its exact path in scripts/gitleaks-gate/notscanned.go (no globs, no
+# directories), and a credential committed in one of them is not found.
+#
+# Nothing is allowed by fingerprint or by comment: the gate refuses a tracked
+# .gitleaksignore and scans with --ignore-gitleaks-allow.
+#
+# AN ALLOWANCE WITH `paths` MUST NAME `targetRules`. In `gitleaks dir`
+# (v8.30.1), a global allowance's paths skip the whole file before it is
+# read, whatever its condition says: an AND of a path and a value allowed
+# every secret in every file the path matched. One with targetRules is
+# moved onto those rules, where the AND holds and the rest of the file is
+# still scanned.
+#
+# A new finding is fixed, not allowed, unless it is a value that has to be
+# committed. Then add it here, in the group that fits, with its reason.
+[extend]
+useDefault = true
+
+# Fake credentials typed into tests, each recognisable as one: a counting
+# run (0123456789abcdef), a word (SecretValue, SENTINEL, nope), a test's
+# own label. The Stripe keys exist to test that the console tells a live
+# key from a test key and a restricted key from a secret one, so they must
+# keep Stripe's prefixes. Three are 64-hex values: 9f86d081... is
+# sha256("test"), fd61a03a... a second stand-in for an HMAC, and
+# c7aff5eb... the callback signature key derived from the golden vector's
+# fixed master, "master-fixed-for-the-vector". Test files only: the same
+# value in production code is still found.
+[[allowlists]]
+description = "fake credentials in tests"
+targetRules = ["generic-api-key", "stripe-access-token"]
+condition = "AND"
+paths = ['''_test\.go$''']
+regexes = [
+ '''^rk_test_51SecretValue$''',
+ '''^rk_live_51SecretValue$''',
+ '''^sk_test_51SecretValue$''',
+ '''^rk_live_51AbCdEfGhIjKlMnOpQrStUv$''',
+ '''^tok-flagship-2$''',
+ '''^tok-second-64hex$''',
+ '''^tok_SECRET_123$''',
+ '''^tok-0123456789abcdef0123456789abcdef$''',
+ '''^SES_SECRET=s3kr1t$''',
+ '''^SECRET-SENTINEL-7f3a$''',
+ '''^cdk1\.bab\.titogo\.0123456789abcdef\.$''',
+ '''^cdk1\.bae\.titogo\.nope$''',
+ '''^carlos-0123456789abcdef0123456789abcdef-1$''',
+ '''^0123456789abcdef0123456789abcdef$''',
+ '''^0123456789abcdefghij0123456789abcdefghijkl$''',
+ '''^3f9a0c1d2e4b5a6978877665544332211$''',
+ '''^AbCd12_EfGh34_IjKl56_MnOp78$''',
+ '''^ba9876543210$''',
+ '''^PLAN14_E45_CONTAINED$''',
+ '''^apps/bab/other/instances/$''',
+ '''^9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08$''',
+ '''^fd61a03af4f77d870fc21e05e7e80678095c92d808cfb3b5c279ee04c74aca13$''',
+ '''^c7aff5eb65835639b68c63a226767768ac2049fe0b57ab83844691ae5cca1d17$''',
+]
+
+# The fake instance key the instance-key tests and their plans share
+# (note its tail, ...bC6dF5gH0iJ1kA=: typed, not generated). Allowed in
+# tests and docs alike, because the plans quote the tests.
+[[allowlists]]
+description = "fake instance key shared by tests and plans"
+regexes = ['''^q\+/Zk3vJ0aW1Yx9sR7tUe2oPl4mN8bC6dF5gH0iJ1kA=$''']
+
+# RFC 6455's sample Sec-WebSocket-Key ("the sample nonce", base64), the
+# one every WebSocket handshake test and its spec quotes. A nonce is not a
+# secret even when it is not the RFC's.
+[[allowlists]]
+description = "RFC 6455 sample WebSocket key"
+regexes = ['''^dGhlIHNhbXBsZSBub25jZQ==$''']
+
+# Committed fixtures. configseal_vectors.json is the cross-language
+# vector set sealed by configseal.js and opened by Go; its key is a
+# throwaway minted for the vectors and protects nothing (the file says so,
+# in the key's own name). lookup.json is a recorded registrar response
+# with its domain auth code replaced by a counting run. Each value in its
+# own file only.
+[[allowlists]]
+description = "configseal test-only vector key"
+targetRules = ["generic-api-key"]
+condition = "AND"
+paths = ['''^internal/console/testdata/configseal_vectors\.json$''']
+regexes = ['''^xKbVxY32zPtWRkhfwugpfIdsamLLebvaWKnV9WLWQ48=$''']
+
+[[allowlists]]
+description = "registrar fixture's placeholder auth code"
+targetRules = ["generic-api-key"]
+condition = "AND"
+paths = ['''^internal/registrar/openprovider/testdata/lookup\.json$''']
+regexes = ['''^1a2b3c4d5e6f$''']
+
+# The password 30-minio-contract gives a user of the MinIO it starts on
+# loopback for one job and then deletes; the plan that wrote the step
+# quotes it.
+[[allowlists]]
+description = "throwaway MinIO user in the contract step"
+targetRules = ["generic-api-key"]
+condition = "AND"
+paths = [
+ '''^\.amadan/ci\.d/30-minio-contract$''',
+ '''^docs/superpowers/plans/2026-10-22-db-region-forward-plan-2-query\.md$''',
+]
+regexes = ['''^dbfukboxsecret1$''']
+
+# Not values at all: generic-api-key matching the word after "key" in code
+# comments and prose (a function name, a header, a review's heading, a
+# CLI flag in a list of flags, an env line in a README), and a bucket name
+# whose number is an AWS account ID, which identifies and does not
+# authenticate.
+[[allowlists]]
+description = "prose and code the generic rule reads as a key"
+regexes = [
+ '''^ed25519\.Verify$''',
+ '''^if-none-match=$''',
+ '''^retry/duplicate$''',
+ '''^CARLOS_REGION=ie$''',
+ '''^--enable-primary-ipv6$''',
+ '''^carlos-flagship-271376211898$''',
+]
diff --git a/AGENTS.md b/AGENTS.md
index 94cd29d99..38fcc3754 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -304,6 +304,17 @@ anything.
`captureLogBuffer`), never a plain `bytes.Buffer`, and a goroutine a
test starts ends before the test does. `internal/activator` and
`internal/lease` are out for now (`.amadan/README.md` says why).
+- `80-gitleaks` runs `make gitleaks` (v8.30.1, pinned) over the tracked
+ files through `scripts/gitleaks-gate`, which first proves that planted
+ keys are still reported. A real finding is removed, and rotated if it
+ was ever live. A fake a test needs is allowed by exact value in
+ `.gitleaks.toml`, scoped to its files; `gitleaks:allow` comments and
+ `.gitleaksignore` do not work here. The census test files and the design
+ checklist that `scripts/gitleaks-gate/notscanned.go` names by exact path
+ are not scanned at all: they hold sha256 digests of source, not secrets,
+ and a key committed in one would not be found. A new census file that
+ turns the step red with digest findings is added there by its exact
+ path. `.amadan/README.md` has the details.
- `20-cross@5` adds `GOOS=darwin`/`windows`/`linux-arm64` compiles, one
per shard. **The gate is not Linux-only**: `internal/host` is linked
into the CLI, which people run on Macs, so a Linux-only type assumption
diff --git a/Makefile b/Makefile
index 8eeb2c8f4..f419d81df 100644
--- a/Makefile
+++ b/Makefile
@@ -7,7 +7,7 @@ LDFLAGS := -s -w -X github.com/carlosframework/platform/internal/version.Build=$
GOOS ?=
GOARCH ?=
-.PHONY: test build build-console fmt staticcheck govulncheck race census-card census-propose code-health code-health-record console-mockup-kit parity-doc
+.PHONY: test build build-console fmt staticcheck govulncheck gitleaks race census-card census-propose code-health code-health-record console-mockup-kit parity-doc
# The build gate: vet, format, tests. `.amadan/ci.d/10-gate` runs this same
# target, so what CI checks and what you check are one definition.
@@ -99,6 +99,25 @@ govulncheck:
(cd launchctx && go run $(GOVULNCHECK) -format json ./...) >"$$dir/launchctx.json" && \
go run ./scripts/govulncheck-gate -exceptions .amadan/govulncheck-exceptions.tsv "$$dir/platform.json" "$$dir/launchctx.json"
+# Secrets committed to the tracked files, as CI checks them
+# (.amadan/ci.d/80-gitleaks): gitleaks, pinned, with its default rules less
+# the exact values .gitleaks.toml allows. Not part of `make test`, like
+# staticcheck, and fetched at a pinned version for the same reason (no tool
+# line in go.mod).
+#
+# Installed once and handed to scripts/gitleaks-gate, because the gate runs
+# it many times: it plants keys and proves they are reported, then scans the
+# tracked files as they are now, uncommitted edits included. Untracked files
+# are not scanned, nor are the digest files scripts/gitleaks-gate/notscanned.go
+# names by exact path. The tree, not the history: what a branch adds is found in
+# the run that adds it, and old values already in every clone would hold
+# every branch red. The `&&` matters: no binary, no pass.
+GITLEAKS_VERSION := v8.30.1
+gitleaks:
+ @dir=$$(mktemp -d) || exit 1; trap 'rm -rf "$$dir"' EXIT; \
+ GOBIN="$$dir" go install github.com/zricethezav/gitleaks/v8@$(GITLEAKS_VERSION) && \
+ go run ./scripts/gitleaks-gate -gitleaks "$$dir/gitleaks" -version $(GITLEAKS_VERSION) -config .gitleaks.toml
+
# The race detector over the packages with real concurrency, as CI runs it
# (.amadan/ci.d/70-race). Not part of `make test`: -race compiles every
# package again and runs its tests several times slower. The tests in
diff --git a/docs/superpowers/notes/census-proposal-flake-lease-teardown.md b/docs/superpowers/notes/census-proposal-flake-lease-teardown.md
new file mode 100644
index 000000000..26c2a4009
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-flake-lease-teardown.md
@@ -0,0 +1,11 @@
+# Census approval: flake-lease-teardown
+
+Ruling `census-ruling-flake-lease-teardown`. 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).
+
+Envelopes re-pinned: `internal/lease`.
+
+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.
+
+Seal: `5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4` → `5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/FINDINGS-flake-demo-browser-siblings.md b/docs/superpowers/reviews/FINDINGS-flake-demo-browser-siblings.md
new file mode 100644
index 000000000..7178f3509
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-flake-demo-browser-siblings.md
@@ -0,0 +1,23 @@
+Reviewed `ff8a252794e5d252c78af243c4510ef7cdf2a6f2` against `origin/main` (`365a79ca0e60561a38eb31348ea159d1643f7d3c`), round 1. The diff contains the three named test scripts and the review brief.
+
+**P1: none. P2: none. P3: none.**
+
+1. **Navigation waits cover the intended document transitions.** The helpers record only main-frame commits from the attached session and wait without evaluating the document. Token exchange waits for both shell and replacement; refused tokens wait for one commit. Both reloads wait before checking the settled page. The motion helper waits for `about:blank` before changing its fixture, then waits for the scene document. See [demo_claim_browser.mjs:67](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/testdata/demo_claim_browser.mjs:67) and [demo_claim_motion.mjs:59](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/testdata/demo_claim_motion.mjs:59).
+
+ One qualification to the brief’s wording: [key():76](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/testdata/demo_claim_browser.mjs:76) sends `keyUp` after the submitting `keyDown`, before entering `committed()`. Thus the entire interval is not literally command-free. This completes the input action; it does not inspect the outgoing document. Chromium handles keyboard dispatch through its browser-side input handler. I found no demonstrated failure from this exception. Source: [https://raw.githubusercontent.com/chromium/chromium/main/content/browser/devtools/protocol/input_handler.cc](https://raw.githubusercontent.com/chromium/chromium/main/content/browser/devtools/protocol/input_handler.cc).
+
+2. **No remaining document polling bypasses the waits after an expected navigation.** I checked `Page.navigate`, `Page.reload`, Enter, `requestSubmit`, submit-button clicks and `location` references. The other submission paths either deliberately suppress navigation or test that submission does not happen.
+
+3. **The expected sequences match the fixtures.** In particular, [the resume wait:231](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/testdata/demo_claim_resume_browser.mjs:231) correctly expects two `/demo/claim` documents. Keymail and the callback return redirects; the first rendered document automatically submits the resumed selection, producing the second. Refused-token scenes remain on their shell. `liveMotion` reloads `/demo/claim` because the page removes the query with `replaceState`.
+
+ CDP defines `Frame.url` without its fragment and reports history API changes separately from document navigation. Source: [https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/pdl/domains/Page.pdl](https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/pdl/domains/Page.pdl).
+
+4. **The two submit stubs preserve the existing proof.** The page’s delayed `prototype.submit` bypasses the listeners’ `preventDefault`, so suppressing it closes an unintended navigation window. The token test retains its submitted-field, disabled-button, mail, leak and zero-operation checks. The resume stub belongs only to the preliminary disabled-button check; the following navigation creates a fresh document, and the real selection still exercises the complete round trip. Its Go assertions still require exactly one operation targeting the selected account. See [demo_claim_page_test.go:210](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/demo_claim_page_test.go:210) and [demo_claim_resume_browser_test.go:249](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/demo_claim_resume_browser_test.go:249).
+
+5. **The CSP assertion matches Chromium’s current behavior.** A `form-action` violation returns `ERR_ABORTED` specifically to avoid committing an error page. This top-level fixture has no parent-frame policy that would override that result. The empty commit sequence at [demo_claim_resume_browser.mjs:191](/home/paulca/amadan.net/carlos/platform-flake-siblings/internal/console/testdata/demo_claim_resume_browser.mjs:191) is therefore justified. A future browser behavior change could require adapting the test, but I found no current timing-dependent error-page path. Source: [https://raw.githubusercontent.com/chromium/chromium/main/content/browser/renderer_host/navigation_request.cc](https://raw.githubusercontent.com/chromium/chromium/main/content/browser/renderer_host/navigation_request.cc).
+
+6. **Strict sequence checking suits these flows.** They do not traverse history, and their status fetches update the DOM without navigating. Previous expected commits are consumed before the next snapshot. Unexpected commits should remain failures rather than be ignored. Existing assertions remain intact.
+
+Validation was static inspection and Chromium source verification. I did not run tests in this read-only environment or independently reproduce the reported failure or timings. No files were changed.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-flake-demo-claim-browser.md b/docs/superpowers/reviews/FINDINGS-flake-demo-claim-browser.md
new file mode 100644
index 000000000..6d84c81f7
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-flake-demo-claim-browser.md
@@ -0,0 +1,31 @@
+Reviewed `7910cf1e6b0ae9322c1e531bd8cb27ca95ead82a` against `origin/main` (`12158f40fdafa2b08a0ee747059289c39d09bace`), round 1. The diff contains only the browser-test change and its review brief.
+
+**P1: none. P2: none.**
+
+**P3 — The sibling scripts retain the navigation race.**
+Invariant: assertions must run against the intended document after navigation.
+
+- [demo_claim_browser.mjs:80](/home/paulca/amadan.net/carlos/platform-flake-browser/internal/console/testdata/demo_claim_browser.mjs:80) polls across the token shell’s replacement. Its reloads at lines 184–185 and 240–241 immediately poll a condition already satisfied by the outgoing document.
+- [demo_claim_resume_browser.mjs:164](/home/paulca/amadan.net/carlos/platform-flake-browser/internal/console/testdata/demo_claim_resume_browser.mjs:164) navigates between pages with the same radio-selector condition, then immediately polls it. Lines 200–201 also poll across the submission and resume navigation chain.
+
+These can fail during document replacement or accept the outgoing document and run subsequent assertions too early. In a follow-up, add passive navigation waits matched to each flow before polling. The resume flow needs to account for its intermediate documents. These are existing, out-of-scope issues, as the brief specifies.
+
+The requested checks:
+
+1. **The new waits leave no CDP command in either identified navigation window.** [demo_claim_kept_browser.mjs:56](/home/paulca/amadan.net/carlos/platform-flake-browser/internal/console/testdata/demo_claim_kept_browser.mjs:56) only checks the event array and awaits timers. Both navigation calls immediately await it. The live-mode `shot()` and completion fetch occur after the second commit, at lines 93–94. Reload assertions and the settled screenshot likewise follow the reload commit. There is no retry or suppression of a failed command.
+
+2. **The event and filtering are appropriate.** The handler checks the attached session and excludes child frames. CDP defines `Frame.url` without its fragment and distinguishes document navigation from same-document navigation, so the expected URLs are correct without additional stripping. See [https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/pdl/domains/Page.pdl](https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/pdl/domains/Page.pdl).
+
+ Chromium updates the renderer connection before committing navigation and resumes queued commands against that connection. This supports using the event as the boundary for subsequent evaluations across a renderer swap; flattening does not pin the session to the outgoing renderer. The event does not mean the DOM is ready, which is why retaining `until()` matters. See [https://raw.githubusercontent.com/chromium/chromium/main/content/browser/devtools/render_frame_devtools_agent_host.cc](https://raw.githubusercontent.com/chromium/chromium/main/content/browser/devtools/render_frame_devtools_agent_host.cc).
+
+3. **The strict sequence fits these fixtures.** The script never traverses history, so it does not trigger a back-forward-cache restoration. `history.replaceState()` does not add a document commit. The previous scene’s expected commits have already been received before the next snapshot. The live completion fetch updates server state and the page updates its DOM; neither adds a navigation. I found no legitimate extra commit that this assertion would reject in the current flow.
+
+4. **Both navigation sites in the kept script are covered.** Its only explicit navigation operations are the initial `Page.navigate` and `Page.reload`; both now wait. The shell’s implicit replacement is covered by expecting two initial commits.
+
+5. **The existing proof is preserved.** [demo_claim_kept_browser.mjs:96](/home/paulca/amadan.net/carlos/platform-flake-browser/internal/console/testdata/demo_claim_kept_browser.mjs:96) retains the reveal count, fragment and history checks, token absence, cookie scope, settled reload, and CSP assertions. The reload check is stronger because it can no longer succeed on the outgoing document.
+
+6. **The proposed cause is credible, but the exact failed command remains unproven.** The first scene is live. Its shell delay, staged completion holds and celebration precede reload, supporting the conclusion that the 3.61-second failure happened earlier. The local 4.7-second measurement alone would not establish CI timing. Chromium also explicitly emits this error for outstanding JavaScript-executing commands during renderer replacement, matching the proposed mechanism. See [https://raw.githubusercontent.com/chromium/chromium/main/content/browser/devtools/devtools_session.cc](https://raw.githubusercontent.com/chromium/chromium/main/content/browser/devtools/devtools_session.cc). Unexpected target closure remains another possible source; this change correctly leaves such failures visible.
+
+Validation was static inspection and Chromium source verification. I did not run tests in this read-only environment or independently reproduce the reported failure. No files were changed.
+
+**READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md b/docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md
new file mode 100644
index 000000000..c3c8c15db
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-flake-lease-teardown.md
@@ -0,0 +1,31 @@
+Reviewed commit `1e880e094aaed9b8915b1ad85af8a88bbccc2ede` against local `origin/main` (`365a79ca0e60561a38eb31348ea159d1643f7d3c`). No P1 findings. Two P2 findings follow; neither requires redesigning the production wrapper.
+
+1. **P2 — The regression test can pass without the pipe-closing fix.**
+ [internal/lease/teardown_linux_test.go:200](/home/paulca/amadan.net/carlos/platform-flake-lease/internal/lease/teardown_linux_test.go:200)
+
+ Receiving `context.Canceled` proves the uploader stopped, but does not prove the encoder reached its blocked body write. After the header is consumed, the encoder can be descheduled before entering `writeLTXFromDB`. The test then calls `Abandon`, which closes the database and cancels the store context. When the encoder resumes, its context check at Litestream v0.5.14 `db.go:2072`, or database read at `db.go:2099`, can fail and release the WAL without `pipeClosingClient`. The descriptor assertion then passes with the production fix removed.
+
+ **Fault family:** regression-test causality—cleanup must demonstrate the wrapper’s effect.
+ **Fix:** Capture the original snapshot pipe and assert, with bounded synchronization and without draining it, that it is closed before calling `Abandon`; retain the teardown descriptor checks.
+
+2. **P2 — The immediate database/SHM assertion assumes synchronous SQLite cleanup that the fixture does not guarantee.**
+ [internal/lease/teardown_linux_test.go:65](/home/paulca/amadan.net/carlos/platform-flake-lease/internal/lease/teardown_linux_test.go:65)
+
+ If the DB monitor initializes the database before the explicit sync, Litestream’s long-running read transaction inherits `db.ctx` (`db.go:1039`, `1132`, `2706`). `DB.Close` cancels that context, allowing `database/sql.Tx.awaitDone` to start rollback asynchronously. That goroutine marks the transaction done before finishing rollback. Litestream’s explicit rollback can consequently receive the ignored `ErrTxDone` and continue to `sql.DB.Close`.
+
+ Go’s `sql.DB.Close` closes idle connections; it does not join this checked-out transaction’s rollback (`database/sql/sql.go:926`, `2209`, `2326`). Its SQLite connection can therefore retain database and SHM descriptors briefly after teardown returns. This is another possible transient descriptor lifetime, beyond the snapshot WAL. I established this interleaving from source; I could not reproduce it in this read-only session.
+
+ **Fault family:** teardown-test synchronization—an asynchronous close is treated as a permanent leak.
+ **Fix:** Use a bounded descriptor-drain check for all three paths, retaining the immediate second-call assertion, or explicitly synchronize transaction cleanup before the immediate check.
+
+The remaining checks support the production change:
+
+- **Root cause:** Both described WAL failure paths match the pinned v0.5.14 source. `Snapshot` leaves the reader unclosed, and the S3 uploader rejects an already-cancelled context before reading the body.
+- **Wrapper safety:** S3 and `lsfile` finish consuming successful writes before returning. Closing afterward is safe. The generation client, fence gate, and compactor already tolerate repeated pipe closes.
+- **Interfaces and restores:** I found no required optional interface or concrete-client assertion lost on the store path. Restore constructs a separate replica; hiding `ReplicaClientV3` here does not affect it.
+- **v0.5.18 qualification:** Its cached source also adds a deferred reader close in `DB.Snapshot` (`db.go:3065`) and returns a `snapshotReadCloser`. This wrapper’s exact `*io.PipeReader` assertion no longer matches that snapshot reader, but upstream performs the cleanup. The wrapper remains harmless; the brief’s shutdown-order argument alone does not describe the full upgrade behavior.
+- **Census:** **Approve the `internal/lease` envelope re-pin.** The wrapper adds no root read, path selection, or authority bypass. I independently recomputed the envelope as `1af3b69b91061e6f593bc4df2756308fb4befed1fba5b4b41adff42254426a81`, matching the overlay.
+
+`git diff --check` passed. The targeted test command stopped before compilation because Go attempted to update `go.mod` on the read-only filesystem. No full suites ran and no files were edited.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md
new file mode 100644
index 000000000..cd3c1e3b8
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md
@@ -0,0 +1,41 @@
+Reviewed `origin/main...614cc4ae228f6def225d1a9fc49189a4aecd229a`, round 3 of 3. The difference from the brief’s named commit is only the brief itself.
+
+1. **P1 — Digest-shaped entries are approved without establishing that their values are checked digests.**
+ [scripts/gitleaks-gate/judge.go:127](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/judge.go:127)
+
+ **Failure scenario:** put a real 64-character lowercase hexadecimal credential under `"internal/console/auth.go"` in the checklist’s `source_hashes` object. The scanner reports it as `generic-api-key`; the judge accepts it because the line matches and `Secret` equals the value. No repository test validates that checklist’s hashes. The judge also accepts matching lines outside `source_hashes`, because it never parses the surrounding JSON.
+
+ The census protection is incomplete for the same reason. `TestPlan9B8RecordWriteCensus` compares the **effective inventory** with source digests. It does not validate every matching line in every `_census_test.go` file. An unused `[]censusEntry` declaration containing a credential passes the judge without entering that inventory. Historical entries overwritten by later layers likewise do not have their original digest checked by that comparison.
+
+ **Evidence:** the pinned v8.30.1 scanner detected generated hexadecimal keys in both a checklist entry and an unused census entry, with the exact `Secret`, rule and single-line location that `approve` accepts. All 28 existing checklist hashes match their declared historical source revision, but that relationship is not enforced by CI.
+
+ **Fix:** require independent verification of each accepted digest, including its inventory membership or historical source, and reject entries without that evidence. Add negative cases for an incorrect checklist digest, a matching line outside `source_hashes`, and an unused census declaration. Shape alone cannot provide the required approval.
+
+ **Fault family:** allowances must distinguish approved source digests from credentials—the same invariant as the earlier rounds.
+
+2. **P1 — The sentinel overwrites a tracked file before scanning it.**
+ [scripts/gitleaks-gate/main.go:159](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:159)
+
+ **Failure scenario:** commit a root-level `gitleaks-gate-sentinel.env` containing a credential. `copyTracked` copies it into the scan tree, then `os.WriteFile` truncates it and substitutes the generated sentinel. The scanner therefore never sees the committed credential. Its replacement satisfies `sawSentinel`, allowing the gate to pass.
+
+ **Evidence:** this follows directly from the copy/write ordering. The pinned scanner detected a synthetic credential in equivalent environment-file content; the wrapper would remove that content before invoking it.
+
+ **Fix:** create the sentinel exclusively at an unused path, or reject a tracked-path collision before writing. Exempt only the generated sentinel finding, and add a regression case containing a tracked file with the current sentinel name.
+
+ **Fault family:** scan coverage must preserve every tracked file’s contents.
+
+No additional P2 or P3 findings.
+
+The remaining checks found:
+
+- **Report handling:** the judge compares `Secret` with the digest captured from the actual file line, requires a single-line finding, and rejects `decoded:` tags. Malformed/truncated JSON, inconsistent exit status, missing reports, missing binaries and version mismatches have rejection paths.
+- **Empty scans:** zero copied files fails; failure to detect the generated sentinel also fails. The collision above defeats coverage despite those checks.
+- **Self-test wiring:** `80-gitleaks` invokes `make gitleaks`, whose wrapper runs the self-test before scanning tracked files. Planted cases must be detected by both the default-rule control and the configured scan after judging.
+- **Exact allowances:** all 35 expressions are anchored exact values. Their repository uses support the documented fixture, test, digest-fragment or non-secret explanations; I identified no live credential among them.
+- **Documentation:** README, AGENTS.md and the step header match the invocation and intended behavior, subject to the coverage failures above.
+
+`git diff --check`, shell syntax checking and formatting checks passed. Scanner probes used the cached, version-verified executable. The complete wrapper/self-test was not executed because it requires filesystem writes unavailable in this sandbox. Access to amadan #1251 was blocked by network restrictions. No files were changed, reviewers spawned or full suites run.
+
+This exhausts round 3 and repeats the allowance fault family. **Cutting or holding the new step is better than starting another repair/review round without Paul’s explicit decision.**
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md
new file mode 100644
index 000000000..47d39591d
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-gitleaks-1251-R4.md
@@ -0,0 +1,21 @@
+Reviewed `origin/main...8ea340c26149f7c0afa3c85a1d7ac7457cea13a8`, round 4 of 4, within the brief’s fixed scope. The change after its named commit, `99612d24`, is the review brief alone.
+
+**No P1, P2 or P3 findings.**
+
+- **Both R3 P1s are closed.** `judge.go` is deleted. The wrapper no longer approves findings by digest shape or source line. In [main.go:219](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:219), only a finding matching both the generated sentinel’s exact filename and exact value is set aside; every other reported finding remains.
+
+- **Exclusions are exact paths.** [main.go:247](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:247) obtains unquoted, NUL-delimited paths from Git. The exclusion lookup compares those full strings directly, before filesystem path conversion. There is no glob, prefix, suffix, case folding or cleaning in that comparison. Git’s canonical index paths prevent `./`, `..` and trailing-slash aliases. Symlinks and submodules do not satisfy a listed regular-file entry, so substituting either leaves the entry unsatisfied and fails the gate. All 26 current entries are unique, tracked regular files.
+
+- **The rename-and-replace edge is acceptable under the chosen contract.** Renaming listed file A to B makes B eligible for scanning. Removing A without replacement fails the stale-entry check. If the same commit installs new content at A, A remains excluded. That follows the explicitly accepted limitation that credentials at named paths are not found; it does not widen the exclusion to B.
+
+- **The sentinel cannot overwrite a copied file.** [main.go:200](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/main.go:200) uses `O_CREATE|O_EXCL` after copying tracked files. A collision fails before writing. Creation, write and close errors propagate. [selftest.go:192](/home/paulca/amadan.net/carlos/platform-gitleaks-1251/scripts/gitleaks-gate/selftest.go:192) calls production `scanTree`, which calls production `copyTracked`. Its required findings cover the former sentinel filename, an unlisted census file and three near misses per exclusion. Restoring the former fixed-name overwrite would remove a required finding and fail this test.
+
+- **The requested failure paths reject the scan.** Missing or wrong-version binaries, invalid or missing configuration, unreadable or malformed/truncated JSON, inconsistent report/exit status, zero copied files, a missing sentinel finding, stale exclusions and tracked `.gitleaksignore` files have rejection paths. The self-test runs before the repository scan.
+
+- **Documentation and allowances match the implementation.** The config header, CI step, Makefile, README and AGENTS.md identify the omitted digest files and their exact-path list. The documentation explicitly acknowledges the credential blind spot. None still describes an active digest judge. The remaining allowance definitions and comments are byte-for-byte unchanged from R3; only the 9B8 fragment allowance was removed.
+
+Shell syntax and Go formatting checks passed. `git diff --check` reported only two Markdown hard-break lines in the committed R3 findings.
+
+The complete wrapper/self-test was not executed because this sandbox prohibits filesystem writes. Network restrictions prevented independently reading amadan #1251; the review uses the ruling recorded in the R4 brief. No files were changed, reviewers spawned or full suites run.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-browser-siblings.md b/docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-browser-siblings.md
new file mode 100644
index 000000000..0c8c24556
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-browser-siblings.md
@@ -0,0 +1,219 @@
+# Review brief: navigation waits in the sibling demo claim browser scripts, round 1 of 3
+
+Repo carlos/platform, branch `flake-demo-browser-siblings`.
+Under review: the diff `origin/main..flake-demo-browser-siblings` (base
+365a79ca). Code changes, all test-only:
+
+- `internal/console/testdata/demo_claim_browser.mjs`
+- `internal/console/testdata/demo_claim_resume_browser.mjs`
+- `internal/console/testdata/demo_claim_motion.mjs` (helper used only by
+ `demo_claim_browser.mjs`; it now takes a `navigate` function)
+
+This brief is the other file. No product code changed.
+Authorities: `internal/console/static/demo_claim.js` (what the page does
+on its own), the Go tests that drive the scripts
+(`demo_claim_page_test.go` `TestDemoClaimBrowserHeadless`,
+`demo_spent_token_test.go` `TestDemoSpentTokenBrowserHeadless`,
+`demo_claim_ux_test.go` `TestDemoClaimUXHeadless*`,
+`demo_claim_resume_browser_test.go` `TestDemoClaimSelectStepUpHeadless`),
+and the merged fix for the third sibling, 365a79ca
+(`demo_claim_kept_browser.mjs`, reviewed in
+`FINDINGS-flake-demo-claim-browser.md`). This change is that review's P3.
+
+You are an independent reviewer. Read this brief, then the code it
+names, and check every claim against that code.
+
+## The race
+
+The scripts drive Chromium over CDP. After starting a navigation they
+went straight into `until()`, which polls `Runtime.evaluate` every
+100 ms. Two things go wrong:
+
+1. A command that reaches the outgoing document while the next one
+ commits can fail with CDP -32000 "Inspected target navigated or
+ closed". That is the error main CI hit in the kept script on
+ 2026-11-19.
+2. A condition the outgoing document already meets passes on the wrong
+ page, and the assertions after it run against that page.
+
+Measured locally with temporary logging (since removed; Chromium
+151.0.7922.173, node v24.19.0): **`Page.navigate` and `Page.reload` both
+answer before their navigation commits**, by 4 to 52 ms. So every
+`Page.navigate` followed by `until()` polled across a commit, not only the
+ones the P3 named.
+
+Where the outgoing page already met the condition (the wrong-page case):
+
+- `demo_claim_browser.mjs` UX scenes: every scene after the first
+ navigates from the previous scene's `/demo/claim` (another server) to
+ this one's. `until('readyState === "complete" && #claim')` is true on
+ the previous page, so `dataset.state === scene.State` could be read
+ from the previous scene.
+- Both `Page.reload` calls (fast scene and `liveMotion`): the settled
+ "claimed" condition is true before the reload.
+- `demo_claim_resume_browser.mjs`: most navigations go from one
+ `/demo/claim` with radios to another with the same radio condition
+ (e.g. old line 164 to `?csp=before`).
+
+## The navigation sequences
+
+`Frame.url` in `Page.frameNavigated` has no fragment. `history.replaceState`
+(the page's first line, which also turns `?replay=1` into `/demo/claim`)
+does not commit a document. Server redirects do not commit. Form posts in
+`#claim` are cancelled by the page and re-sent with
+`HTMLFormElement.prototype.submit` after a paint and a 650 ms hold
+(`demo_claim.js` lines 43-59).
+
+### demo_claim_browser.mjs, token flow (`TestDemoClaimBrowserHeadless`, `TestDemoSpentTokenBrowserHeadless`)
+
+1. `Page.navigate` to `/demo/claim#<token>`: commit `/demo/claim` (the
+ shell). The shell POSTs the token with `fetch`, waits for its hold,
+ then:
+ - accepted: `location.replace("/demo/claim")`: second commit
+ `/demo/claim`. Expect `[page, page]`.
+ - refused (spent token, `expectedError`): error shown, no navigation.
+ Expect `[page]`.
+2. Email typed, Enter: page holds, posts `/demo/claim/prove`, 303, commit
+ `/demo/claim` (code form). Expect `[page]`.
+3. "Use a different address", Enter: same, commit `/demo/claim`. Expect
+ `[page]`.
+4. Code typed, Enter: the test's own submit listener records the
+ submission. Before this change the page still posted the code 650 ms
+ later (the listener's `preventDefault` does not stop
+ `prototype.submit`), racing the script's last six reads. Now the same
+ evaluate stubs `HTMLFormElement.prototype.submit`, as the UX scenes
+ already do (line 238), so nothing navigates. Nothing on the Go side
+ reads that post: `TestDemoClaimBrowserHeadless` checks the intent
+ exchange count, leaks, the sent mail and that no operation exists.
+
+### demo_claim_browser.mjs, UX scenes (`TestDemoClaimUXHeadless*`)
+
+- Each scene: `Page.navigate` to `<origin>/demo/claim[#refused-token]`:
+ one commit `<origin>/demo/claim`. The fragment scenes (expired, kept,
+ taken-down, invalid) are refused tokens, so the shell stays.
+- email/code/one/many: `prototype.submit` is already stubbed (line 238);
+ no navigation.
+- fast: `Page.reload`: commit `<origin>/demo/claim`.
+- `liveMotion`: `Page.navigate` to `?replay=1`: commit `/demo/claim?replay=1`;
+ then `Page.reload`: commit `/demo/claim` (replaceState changed the URL).
+- motion (`demo_claim_motion.mjs`): `Page.navigate` to `about:blank`
+ (commit `about:blank`), then to the scene URL (commit it). Both now go
+ through `navigate`.
+
+### demo_claim_resume_browser.mjs (`TestDemoClaimSelectStepUpHeadless`)
+
+- 18 `Page.navigate` calls, none with a fragment, none to a page that
+ navigates itself (the `testProgress` pages poll `/demo/claim/status`
+ with `fetch`). Each commits exactly its URL. All now go through
+ `navigate(url)`.
+- `?csp=before`, choose and `requestSubmit`: after the hold the page
+ posts `/demo/claim/select`, the server answers with a redirect to the
+ fake Keymail on another port, and the edited CSP `form-action` blocks
+ that redirect. Measured: no document commits. The script waits for the
+ CSP log entry (no CDP commands), then reads `location.origin`. New
+ assertion: no commit since the post started, so that read is on the
+ `?csp=before` page.
+- Line 221 (was 194), submit with the test's `preventDefault`, then
+ check the button stays disabled: same as token step 4. The page would
+ have posted `/demo/claim/select` 650 ms later. If the script had been
+ slow, that post would have run the whole Keymail round trip and
+ chosen the account before the real choice below. Now stubbed;
+ `Page.navigate` on the next line gives a fresh document.
+- Lines 227-234 (was 198-201), the real choice. Two clicks on the
+ button; the second is swallowed by the page's `submitted` guard. Then:
+ hold, POST `/demo/claim/select`, 303 to Keymail `/oauth/authorize`,
+ 303 to `/auth/stepup/callback`, 303 to `/demo/claim`: **commit 1**,
+ the resumed first paint (progress view with
+ `form[data-auto-submit]`). Its script calls `requestSubmit`: hold,
+ POST `/demo/claim/select`, 303 to `/demo/claim`: **commit 2**, the
+ progress view that polls. Expect
+ `[target/demo/claim, target/demo/claim]`. Measured: two commits,
+ roughly 0.7 s apart, matching the two holds.
+
+## The fix
+
+Same helper as the kept script (365a79ca), copied into each script
+because each has its own CDP plumbing (`call`, `evaluate`, `until` are
+already per-script copies):
+
+- `commits`: every main-frame `Page.frameNavigated` URL for our session.
+- `committed(since, urls)`: waits, sending no CDP commands, until
+ `urls.length` commits have arrived after `since` (150 × 100 ms, as
+ `until()`), then `deepEqual`s them against `urls`.
+- New `navigate(url, urls = [url])`: records `since`, sends
+ `Page.navigate`, then `committed`. The reloads and the actions that
+ navigate (Enter, button clicks) use `since` and `committed` inline.
+
+The existing `until()` calls stay, for DOM readiness after the commit.
+No assertion was removed or loosened. Added: each step's exact commit
+sequence, and "the CSP-blocked post committed nothing". There are no
+new sleeps and no retries.
+
+## Tests run (docs-t1, shared and busy)
+
+Commands and results:
+
+```
+go test ./internal/console -run 'TestDemoClaimBrowserHeadless$|TestDemoSpentTokenBrowserHeadless$|TestDemoClaimUXHeadless|TestDemoClaimSelectStepUpHeadless$' -count=1 -v -timeout 25m
+go test ./internal/console -run 'TestDemoClaimBrowserHeadless$|TestDemoSpentTokenBrowserHeadless$|TestDemoClaimUXHeadless$|TestDemoClaimUXHeadlessFast390$|TestDemoClaimUXHeadlessMotion1280Dark$|TestDemoClaimSelectStepUpHeadless$' -count=5 -v -timeout 30m
+```
+
+- First command: 10/10 `--- PASS` (all four Motion variants, both Fast,
+ the quick UX scenes, token, spent token, step-up), `ok ... 211.770s`.
+- Second: 5/5 `--- PASS` for each of the six tests (30 runs),
+ `ok ... 882.054s`.
+
+Like the kept script, the -32000 never reproduced locally; this
+Chromium answered commands across these navigations. The fix is for the
+invariant, not a local repro.
+
+## What to check
+
+1. After every navigation the scripts start or expect, is there any CDP
+ command between the start and the last expected commit? Check
+ especially the token flow, the UX scene loop, both reloads,
+ `checkClaimMotion`, and the resume chain at lines 227-234.
+2. Is any navigation left that still goes straight to `until()` or
+ `evaluate()`? Search for `Page.navigate`, `Page.reload`, `key('Enter'`,
+ `requestSubmit`, `.click()` on submit buttons, and `location.`.
+3. Are the expected sequences right? In particular: two commits for the
+ resume chain (no intermediate document from the Keymail and callback
+ redirects), one commit for the refused-token scenes, `about:blank`
+ for the motion helper, `/demo/claim` (not `?replay=1`) after the
+ `liveMotion` reload.
+4. Stubbing `HTMLFormElement.prototype.submit` in token step 4 and resume
+ line 221: does it weaken anything either test proved? Both tests'
+ listeners already called `preventDefault`, so the post was never what
+ they meant to send. Does the Go side depend on that post anywhere?
+5. The new `commits.slice(blocked)` assertion after the CSP block: could
+ Chromium commit an error page for a `form-action` redirect block, now
+ or later, and make this a new flake?
+6. The strict `deepEqual` turns any unexpected commit (bfcache restore,
+ a late event from an earlier step) into a failure. Is a strict
+ sequence right for these flows?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, the evidence
+(file:line, verified), the failure scenario and a concrete fix. End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. If you run anything, run only
+`go test ./internal/console -run 'TestDemoClaimBrowserHeadless$|TestDemoClaimSelectStepUpHeadless$' -v`.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-claim-browser.md b/docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-claim-browser.md
new file mode 100644
index 000000000..ec3c38ead
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-flake-demo-claim-browser.md
@@ -0,0 +1,150 @@
+# Review brief: flake fix for TestDemoClaimKeptHeadless, round 1 of 3
+
+Repo carlos/platform, branch `flake-demo-claim-browser`, fix commit
+d4f3fc8d394e26ae474ef9944f8a2c2dce6cbc6f.
+Under review: the diff `origin/main..flake-demo-claim-browser` (base
+12158f40). The only code change is
+`internal/console/testdata/demo_claim_kept_browser.mjs`; this brief is
+the other file.
+Authorities: the kept-link behaviour as merged on main in ce7576a6
+(`internal/console/demo_claim_kept.go`, `internal/console/static/demo_claim.js`).
+The fix must not change product code or what the test proves.
+
+You are an independent reviewer. Read this brief, then the code it
+names, and check every claim against that code.
+
+## The failure
+
+Main CI at 0acb2767 (2026-11-19, shard internal_console@4) failed once
+and passed on rerun:
+
+```
+--- FAIL: TestDemoClaimKeptHeadless (3.61s)
+ demo_claim_kept_browser_test.go:62: kept browser: exit status 1
+ AssertionError [ERR_ASSERTION]: {"code":-32000,"message":"Inspected target navigated or closed"}
+```
+
+The assertion is the `message.error === undefined` check in `call()`,
+so a CDP command came back with that error. The CI excerpt has no
+stack, so it does not name the step.
+
+## Root cause (claimed)
+
+The test drives Chromium over CDP through
+`internal/console/testdata/demo_claim_kept_browser.mjs`. Each scene opens
+`/demo/claim/kept#k=<token>`. That page is a shell. `demo_claim.js` clears
+the fragment with `history.replaceState` (same document), POSTs the token,
+waits at least 650 ms, then calls `location.replace("/demo/claim")`, which
+is a second cross-document navigation the script does not trigger.
+
+Before the fix, the script started `until()` straight after
+`Page.navigate`. That polls `Runtime.evaluate` every 100 ms on the shell
+while the shell navigates away. A command that reaches the outgoing
+document as the new one commits gets -32000 "Inspected target navigated
+or closed".
+
+Timing evidence that this is the step CI hit, not the reload: a local
+timeline run (temporary logging, since reverted) showed the shell's
+replace committing about 1.1 s after the script starts and scene 1's
+`Page.reload` at about 4.7 s. The CI failure came 3.61 s into the whole Go
+test, and that time also covers building eight fixtures and launching
+Chromium. So it failed in scene 1, before any reload. Within that time,
+the shell's `location.replace` is the only navigation that commands were
+polled across.
+
+The second race has the same shape. `Page.reload` answers before its
+navigation commits, and the settled `until()` condition
+(`readyState === "complete" && state === "claimed"`) is already true on
+the outgoing page. So the first poll could fail the same way, or pass on
+the old document. Only the 1800 ms sleep then kept the following
+assertions on the new document. Locally the reload committed 8 to 50 ms
+after `Page.reload` returned. I did not see an old-document pass in
+practice.
+
+## The fix
+
+- Record every main-frame `Page.frameNavigated` for our session, with the
+ URL and no fragment, in `commits`.
+- `committed(since, urls)` waits, sending no CDP commands, until the
+ expected number of commits has arrived after `since`. It is bounded by
+ 150 × 100 ms, the same as `until()`. It then asserts with `deepEqual`
+ that the commits are exactly the expected URLs.
+- After `Page.navigate`: expect `[origin/demo/claim/kept, origin/demo/claim]`.
+ After `Page.reload`: expect `[origin/demo/claim]`. Then the existing
+ `until()` calls and assertions run unchanged.
+
+No assertion was removed or loosened. The navigation order is now
+asserted where it was only implied before. There are no sleeps and no
+retries of the failing command.
+
+## Reproduction (docs-t1, Chromium 151.0.7922.173, node v24.19.0, load 30 to 128 on 16 cores)
+
+- Before, plain: `go test ./internal/console -run 'TestDemoClaimKept' -count=50`
+ hit the 10-minute default timeout after about 10 iterations. Each
+ browser run takes about 45 s. The output had no `--- FAIL` line for the
+ browser test; it ended in `panic: test timed out after 10m0s`.
+- Before, stress (temporary edit, reverted): `until()` polled every 1 ms
+ with the same 15 s budget, `STRESS_POLL=1 go test ./internal/console -run '^TestDemoClaimKeptHeadless$' -count=6 -v`:
+ 6/6 PASS. Plus 3/3 PASS with `--enable-features=RenderDocument:level/all-frames`.
+ A first stress attempt at 0 ms with 150 iterations failed 6/6, but only
+ because 150 immediate polls ran out before the page was ready
+ (`browser_condition_timeout`). That was an artifact of the stress
+ variant, not the CDP error, and it is not counted.
+- So the -32000 never reproduced locally: 0 in about 21 valid runs. This
+ Chromium answers commands across these navigations without error.
+ CI's runners supply their own Chromium (`.amadan/ci.d` installs none;
+ the test skips when `chromium` is not on PATH), and its version and
+ features are unknown here.
+- After: `go test ./internal/console -run '^TestDemoClaimKeptHeadless$' -count=10 -timeout 20m -v`
+ gave 10/10 `--- PASS` (44.6 to 52.1 s each), `ok ... 470.888s`.
+
+## What to check
+
+1. Does `committed()` really keep every CDP command away from a document
+ that is being replaced? Is there any command between `Page.navigate`'s
+ response and the second commit, or between `Page.reload`'s response
+ and its commit? Look at `shot()` and the live-mode `fetch` evaluate.
+2. Is `Page.frameNavigated` (main frame, `parentId` absent, matching
+ `sessionId`) the right signal? Once it has arrived, are later
+ `Runtime.evaluate` calls guaranteed to reach the new document, given
+ flattened sessions across a RenderFrameHost swap?
+3. Can `commits` see a stray main-frame commit the test does not expect
+ (bfcache restore, `pageshow` persisted path, a previous scene's late
+ event)? Would the strict `deepEqual` then turn a pass into a new flake,
+ or is a strict sequence the correct thing to assert here?
+4. Is anything left in this script that navigates and then polls without
+ waiting? The sibling scripts (`demo_claim_browser.mjs`,
+ `demo_claim_resume_browser.mjs`) share the `until()` pattern. Say
+ whether they carry the same race. They are out of scope for this
+ change, so report them as P3 follow-ups, not blockers.
+5. Does the test still prove everything it proved before: reveal once,
+ settled reload, cleared fragments, scoped cookies, zero CSP
+ violations?
+6. Is the root-cause argument (the 3.61 s timing and the step order)
+ sound? Is there a simpler explanation the fix would miss?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, the evidence
+(file:line, verified), the failure scenario and a concrete fix. End with
+exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites. If you run anything, run only
+`go test ./internal/console -run '^TestDemoClaimKeptHeadless$'`.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md b/docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md
new file mode 100644
index 000000000..3ebe07062
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-flake-lease-teardown.md
@@ -0,0 +1,157 @@
+# Review brief: flake-lease-teardown
+
+You are the independent reviewer (Astra). Review branch `flake-lease-teardown`
+on origin (amadan.net) against `origin/main`. The fix is commits `c297d61b`
+(code and tests) and `057e43b0` (census re-pin); the merge of main after them
+brings in nothing under `internal/lease`.
+
+## The failure
+
+`internal/lease` `TestTeardownIsTerminal/abandon_then_close_proven` failed once
+on main CI at `0acb2767` (2026-11-19, shard `rest/internal_lease`) and passed on
+rerun:
+
+```
+teardown_linux_test.go:80: the first teardown left 1 descriptors on the database open
+```
+
+The test tears a non-HA replicator down (Close or Abandon), counts this
+process's descriptors on `app.db`, `app.db-wal` and `app.db-shm` through
+`/proc/self/fd`, and requires zero. It then calls Close or CloseProven again
+and requires ErrSpent, no bucket requests and still zero descriptors.
+
+## Root cause, with the evidence
+
+Nothing else opens the counted paths. Each subtest uses its own `t.TempDir()`
+database, and the package's tests cannot run in parallel (the lock fixture
+uses `t.Setenv`). The descriptor is the WAL, held by litestream v0.5.14's
+snapshot encoder: the goroutine `DB.SnapshotReader` starts (db.go:2368). It
+opens the WAL read-only, writes the snapshot into an `io.Pipe`, and closes the
+WAL in a `defer`. Nothing can join that goroutine. The store's snapshot
+monitor runs a pass at `Store.Open`. In the fixture's request log every run
+shows a `PUT .../0009/...` (the snapshot), interleaved with the test's own
+sync, so that pass is often still running when the test tears down.
+
+There are two outcomes. I reproduced both.
+
+1. **A delayed close (test only).** The encoder closes its pipe (success,
+ or `CloseWithError` once `DB.Close` has nil'd `db.f`: logs show
+ `write snapshot ltx: read database page 2: invalid argument` 739 times
+ across the stress runs). The upload returns, `Store.Close`'s `wg.Wait`
+ returns, and only after that does the encoder's deferred
+ `walFile.Close()` run. The race window is between the pipe close and
+ that `defer`.
+ - Unchanged test under stress: 2 failures, both `app.db-wal`, both
+ closed by the next scan ("immediately after 0, 200ms later 0").
+ - Deterministic: a scratch copy of litestream (via `-modfile` replace)
+ that sleeps 100 ms before that `defer`'s close made the unchanged test
+ fail 20/20 with the exact CI message. The fixed test passes 80/80
+ against the same copy.
+
+2. **A permanent leak (a production bug, #811 on non-HA stores).** If
+ `Store.Close` cancels the monitor after litestream's
+ `s3.ReplicaClient.WriteLTXFile` has peeked the LTX header
+ (`ltx.PeekHeader`) but before the AWS uploader reads the body, the
+ uploader's `partPool.Get(ctx)` (feature/s3/manager v1.20.18,
+ upload.go:504) refuses the cancelled context. The upload then returns
+ without reading the rest. litestream never closes the pipe, so the
+ encoder blocks in `io.(*pipe).write` (inside `ltx.(*Encoder).EncodePage`)
+ and holds the WAL descriptor and its goroutine for the life of the
+ process.
+ - Stress with the test-side fix only: 1 failure at the 30 s guard ("1
+ descriptors on .../app.db-wal after 30s").
+ - Deterministic: a scratch test cancelled the upload context once the
+ header had been read, going through the real S3 client and the lock
+ fixture. The WAL stayed open 3/3, and a goroutine dump showed the
+ encoder blocked as described.
+
+ The HA path was already guarded: `fenceGate.WriteLTXFile` closes the
+ pipe, and so do `generationClient` and `snapshotWithin`. A plain non-HA
+ store had no guard.
+
+## The fix
+
+- `internal/lease/snapshotpipe.go` (new): `pipeClosingClient` embeds
+ `litestream.ReplicaClient`. Its `WriteLTXFile` closes an `*io.PipeReader`
+ body on every outcome.
+- `internal/lease/lease.go:481` (`newStore`): every store's replica client
+ is wrapped in `pipeClosingClient`. The HA fence gate still wraps the
+ result in `Replicate`, and a double close of a `PipeReader` is harmless.
+- `internal/lease/teardown_linux_test.go`:
+ - `tornDownFiles`: the database file and `-shm` must be closed as soon as
+ the teardown returns. Any open SQLite connection, and litestream's own
+ `db.f`, holds a descriptor on the database file, so these are checked
+ at once. Only the WAL is waited on, through `WaitDescriptorsForTest`
+ (the package's #1193 helper, 30 s guard).
+ - The second-call check in `TestTeardownIsTerminal` is unchanged and
+ still immediate. By then the encoder has closed its WAL, and a reopen
+ (DB.init) holds descriptors that do not go away.
+ - `TestTeardownReleasesACancelledSnapshot` (new): wraps the real S3
+ client (`lease.ReadReplicaClient` against the lock fixture) so that the
+ snapshot upload's context is cancelled once the header has been read.
+ It asserts the upload really was cancelled (`context.Canceled`), then
+ Abandons and calls `tornDownFiles`. With `newStore` reverted to the bare
+ client it fails at the guard ("the teardown left the WAL open: 1
+ descriptors ... after 30s"). With the fix it passes.
+- Census: envelope `internal/lease` re-pinned; no unit changed
+ (`docs/superpowers/notes/census-proposal-flake-lease-teardown.md`).
+
+## Verification run (docs-t1, load average about 55 on 16 cores)
+
+| Run | Result |
+|---|---|
+| Before: `go test ./internal/lease -run TestTeardownIsTerminal -count=200` | ok (0/800 subtests) |
+| Before: test binary, `-test.count=300`, GOMAXPROCS 1/2/4 at once | 1/3600 subtests failed (WAL, delayed close) |
+| Before: 4 processes at GOMAXPROCS=4, `-test.count=300` | 1/4800 failed (WAL, delayed close) |
+| Test-side fix only: 7 processes, `-test.count=300` | 1/8400 failed (WAL still open after 30 s: the leak) |
+| Both fixes: 8 processes (GOMAXPROCS 1, 2, 4×6), `-test.count=300`, both tests | 0/9600 + 0/2400 |
+| Both fixes: `go test ./internal/lease -count=3` (whole package) | ok, 466.9 s |
+| Mutation: never close the encoder's WAL (scratch litestream) | fixed test fails at the 30 s guard |
+| Mutation: drop the `tornDown` guards in `beginClose` and `guardedSync` | all 4 subtests fail at the second check (requests, 5 descriptors) |
+| Mutation: Abandon skips `store.Close` | abandon subtests fail at once ("4 descriptors on the database or its -shm") |
+| `go test ./internal/provision -run Census` | failed (envelope), re-pinned, then ok |
+| `make code-health` | PASS |
+
+`-race` on these tests fails on main and on this branch alike: 5 and 2
+reports per 100 runs. The race is `DB.Close` writing `db.f` (db.go:802)
+while the encoder reads it (db.go:2099). This is the litestream-internal
+race that `.amadan/ci.d/70-race` already gives as the reason
+`internal/lease` is left out of the race step (fixed upstream in v0.5.18).
+This branch neither causes nor fixes it.
+
+## What to check
+
+1. Is the root cause right? Is there any other way the counted paths could
+ have a descriptor open after a teardown that the fix does not cover?
+2. `tornDownFiles`: does checking the database file and `-shm` at once still
+ catch every real teardown leak, and is waiting on the WAL alone sound?
+ Could an immediate count of the database file ever see a descriptor that
+ closes asynchronously too?
+3. `pipeClosingClient`: is closing the pipe after a successful
+ `WriteLTXFile` always safe for every client in use (S3, `lsfile`,
+ `generationClient`, `fenceGate`, the compactor's own pipes)? It hides the
+ inner client's optional `ReplicaClientV3`. Confirm nothing restores
+ through a store's `db.Replica`, and that no other optional interface or
+ concrete-type assertion on `db.Replica.Client` is lost.
+4. Under v0.5.18, which stops the monitors before closing the databases,
+ the cancellation path in item 2 of the root cause becomes more likely,
+ not less. Is the wrapper still the right layer for that?
+5. Does `TestTeardownReleasesACancelledSnapshot` go through production
+ wiring (`Held.Replicate`, `newStore`, the real S3 client and uploader),
+ and is it impossible for it to pass vacuously? It asserts the snapshot
+ upload was cancelled before tearing down.
+6. Census: is the `internal/lease` envelope re-pin acceptable (no root-read
+ change)?
+
+## Severity
+
+- **P1**: unsafe, won't compile, a test fails, or it won't work.
+- **P2**: wrong or missing; can be fixed without reopening the design.
+- **P3**: polish.
+
+## Output contract
+
+List findings ranked P1, then P2, then P3, each with `file:line` and a
+one-line fix. End with exactly one of: **READY**, **READY AFTER FIXES**,
+**NOT READY**. Do not edit files. Do not run full suites; targeted
+`go test ./internal/lease -run '<name>'` runs are fine.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md
new file mode 100644
index 000000000..55bdbe380
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251-R4.md
@@ -0,0 +1,94 @@
+# Review brief: branch gitleaks-1251, round 4 of 4
+
+Repo carlos/platform, branch `gitleaks-1251`, commit 99612d24.
+Under review: the diff `origin/main...99612d24`. The R3 diff was
+`origin/main...7aac4320`; `git diff 7aac4320 99612d24` minus the merge
+of origin/main (2b8fd0e7, no conflicts, nothing in the gate) is what changed.
+Authorities: amadan #1251 (the design and Paul's 2026-11-19 ruling),
+AGENTS.md ("Stopping rules"), `docs/superpowers/reviews/FINDINGS-gitleaks-1251-R3.md`.
+
+**This is the last round.** Paul allowed a fourth round with a fixed scope
+and there is no fifth. Review that scope. Do not ask for a different design.
+
+## What changed since R3
+
+Paul chose the first option on #1251: stop judging digests by shape, leave
+the digest files out by exact path, and say so plainly.
+
+1. **R3 P1 1 (digest-shaped approvals).** `scripts/gitleaks-gate/judge.go`
+ is deleted. The new `scripts/gitleaks-gate/notscanned.go` lists 26
+ whole repository paths: the 25 census test files gitleaks flags for their
+ sha256 digests, and `implementation/always-awake-consumers.json`.
+ `copyTracked` (`main.go:246`) compares each git path to the list for
+ equality and does not copy a listed file, so gitleaks never reads it.
+ An entry naming a path git does not track fails the step (`main.go:302`).
+ Every other finding fails the step. The 9B8 chunk-boundary fragment
+ allowance in `.gitleaks.toml` applied only to a file that is now not
+ scanned, so it was removed. The other allowances are unchanged.
+ **Accepted limit, stated in the docs:** a credential committed in one of
+ the 26 listed files is not found.
+2. **R3 P1 2 (sentinel overwrote a tracked file).** The sentinel goes in
+ `gitleaks-gate-sentinel-<random>.env`, a new name on each run, opened
+ with `O_CREATE|O_EXCL` (`main.go:200`). Only a finding with the
+ sentinel's exact value in that file is set aside (`main.go:219`).
+3. **Self-test.** The census, checklist and chunk-boundary cases went with
+ the judge. The new `trackedTest` (`selftest.go:146`) builds a git
+ repository and runs `scanTree`, the path the real scan takes. It plants
+ a key in a tracked `gitleaks-gate-sentinel.env` and in a census file the
+ list does not name, and requires both to be reported. It plants a key in
+ every listed file and requires none of those to be reported. For each
+ listed name it plants three near misses (`x/` + path, path + `.orig`,
+ `zz_` + file name) and requires each to be reported. It also untracks one
+ listed file and requires `copyTracked` to refuse. With the old sentinel
+ code restored (fixed name, `O_TRUNC`), the self-test fails with
+ "THE PLANTED KEY WAS HIDDEN in gitleaks-gate-sentinel.env".
+4. **Docs.** `.gitleaks.toml` header, `.amadan/ci.d/80-gitleaks` header,
+ the Makefile comment, `.amadan/README.md` ("`gitleaks`: what turns it
+ red") and the AGENTS.md bullet now say which files are not scanned and
+ why: they hold content digests, not secrets.
+
+Local results at 99612d24: `sh .amadan/ci.d/80-gitleaks` passes (10,581
+files scanned, 26 not scanned, clean). In a scratch clone with planted keys
+in a new source file, a tracked `gitleaks-gate-sentinel.env` and a census
+file not on the list, it fails with all three reported.
+
+## What to check
+
+1. **Both R3 P1s are closed.** No finding is accepted because of its shape
+ or its line. Nothing except the sentinel's exact value in its own random
+ file is set aside.
+2. **The exclusion is exact and cannot be widened by a rename.** Check that
+ it uses string equality on the full git path, with no glob, prefix,
+ suffix, case folding or path cleaning that a crafted tracked path
+ (`./`, `..`, a trailing slash, a different case, a symlink, a
+ submodule, a path git quotes) could exploit. Check that a listed file
+ renamed elsewhere is scanned under its new name, and that a stale entry
+ fails. Known edge: one commit that renames listed file A and adds a new
+ file at A keeps A excluded. The commit's diff shows the rename, but
+ `notscanned.go` does not change. Judge whether that is acceptable
+ under "named files are not scanned" or is a P1.
+3. **The sentinel cannot shadow a tracked file.** Look for any ordering,
+ name collision or error path where a tracked file's bytes are replaced,
+ dropped or set aside. Check that `trackedTest` really exercises the
+ production `scanTree`/`copyTracked`, and would fail if either regressed.
+4. **Fails closed.** Missing or wrong-version binary, a config that does
+ not load, a truncated report, zero files copied, a missing sentinel
+ finding, a stale list entry, a tracked `.gitleaksignore`.
+5. **The docs are true.** Every text that describes the gate (config
+ header, step header, Makefile, README, AGENTS.md) says plainly that the
+ listed files are not scanned and why, and matches the code. Nothing
+ still describes the judge.
+6. The remaining `.gitleaks.toml` allowances are byte-for-byte the R3 ones,
+ minus the 9B8 fragment.
+
+## 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, then P2, then P3, each with file:line, failure scenario
+and fix. 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-gitleaks-1251.md b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md
new file mode 100644
index 000000000..78b696947
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-gitleaks-1251.md
@@ -0,0 +1,53 @@
+# Review brief: branch gitleaks-1251, round 3 of 3
+
+Repo carlos/platform, branch `gitleaks-1251`, commit c057934314434f290a5d89459f8dc5dd7fee68f6.
+Under review: the diff `origin/main...c057934314434f290a5d89459f8dc5dd7fee68f6`.
+Authorities: amadan #1251 (the design), AGENTS.md ("Stopping rules").
+
+**Round history.** This design had two earlier rounds on branch race-helpers:
+`docs/superpowers/reviews/FINDINGS-race-helpers-R1.md` (on main) rejected a
+path-plus-hex allowance; a scoped check then rejected whole-line patterns
+because the census entry's second field accepted arbitrary text. Stopping
+rule 2 applied and Paul chose to split gitleaks out with a tighter design.
+This is the last round.
+
+You are the independent reviewer. The invariant: **an allowance can only
+ever hide an approved digest, never a credential.**
+
+The design: `.gitleaks.toml` holds 35 exact anchored values and no shape
+patterns; `scripts/gitleaks-gate` runs the scan and accepts a finding as a
+digest only if the whole line is a valid census or checklist entry AND the
+reported secret is that entry's digest field; a self-test plants generated
+keys (38 cases) and requires each to be reported.
+
+## What to check
+
+1. Try to break the invariant. Can any credential, in any field of a census
+ entry, the JSON checklist, a chunk boundary, a multi-line value, a
+ comment after an entry or an ordinary file, pass the gate or the 35
+ exact values? Does the gate parse gitleaks' report so a crafted line or
+ secret can't confuse it (Match vs Secret vs Line, encoded or decoded
+ findings)?
+2. Known limit: a 64-character lowercase hex value in the digest field is
+ accepted. Does the census test independently fail a digest that isn't
+ the real source digest, so a real key there can't reach main? Verify
+ for both census entries and the checklist file.
+3. Fails closed: bad or missing config, missing binary, wrong version,
+ truncated or unparsable report, zero files scanned.
+4. Does the self-test run in CI on every run, and fail if planted keys go
+ unreported?
+5. Are all 35 exact values really non-secrets?
+6. README, AGENTS.md and the step header match the scripts.
+
+## 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. End
+with exactly one verdict: READY, READY AFTER FIXES, or NOT READY. A NOT READY
+in this round also says whether cutting the step would be better. Do not
+edit files, spawn reviewers or run full suites.
diff --git a/internal/console/testdata/demo_claim_browser.mjs b/internal/console/testdata/demo_claim_browser.mjs
index aa7aeba68..3596317e0 100644
--- a/internal/console/testdata/demo_claim_browser.mjs
+++ b/internal/console/testdata/demo_claim_browser.mjs
@@ -22,12 +22,15 @@ const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
'--user-data-dir=' + profile], {stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe']});
let sequence = 0, buffered = '', session;
const pending = new Map();
+// Every document the tab's main frame commits, in order (fragment excluded).
+const commits = [];
chrome.stdio[4].on('data', bytes => {
buffered += bytes.toString();
let end;
while ((end = buffered.indexOf('\0')) !== -1) {
const message = JSON.parse(buffered.slice(0, end));
buffered = buffered.slice(end + 1);
+ if (message.method === 'Page.frameNavigated' && message.sessionId === session && !message.params.frame.parentId) commits.push(message.params.frame.url);
const resolve = pending.get(message.id);
if (resolve) { pending.delete(message.id); resolve(message); }
}
@@ -52,6 +55,24 @@ async function until(expression) {
}
throw Error('browser_condition_timeout: ' + await evaluate('JSON.stringify({text:document.body.innerText,email:document.getElementById("email")?.value,focus:document.activeElement.tagName,valid:document.querySelector("form")?.checkValidity()})'));
}
+// Page.navigate and Page.reload both answer before their navigation
+// commits (Chromium 151, measured 2026-11-19), the token shell replaces
+// itself with /demo/claim once its exchange lands, and a submitted form
+// posts after the page's 650 ms hold. A command that reaches the outgoing
+// document as the next one commits fails with -32000 "Inspected target
+// navigated or closed", and a condition polled too soon can pass on the
+// outgoing page. So a step that navigates waits, sending nothing, until
+// the main frame has committed exactly the documents it expects, and only
+// then polls the page.
+async function committed(since, urls) {
+ for (let i = 0; i < 150 && commits.length - since < urls.length; i++) await new Promise(resolve => setTimeout(resolve, 100));
+ assert.deepEqual(commits.slice(since), urls);
+}
+async function navigate(url, urls = [url]) {
+ const since = commits.length;
+ await call('Page.navigate', {url});
+ await committed(since, urls);
+}
async function key(key, code, number) {
await call('Input.dispatchKeyEvent', {type:key === 'Enter' ? 'keyDown' : 'rawKeyDown', key, code, windowsVirtualKeyCode:number, ...(key === 'Enter' ? {text:'\r', unmodifiedText:'\r'} : {})});
await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number});
@@ -65,7 +86,10 @@ try {
if (target.startsWith('[')) {
await runUX(JSON.parse(target));
} else {
- await call('Page.navigate', {url:target});
+ // The fragment is the token: a refused one stays on the shell, an accepted
+ // one replaces the shell with /demo/claim.
+ const page = target.split('#')[0];
+ await navigate(target, expectedError ? [page] : [page, page]);
if (expectedError) {
await until('location.hash === "" && document.getElementById("claim-error")?.hidden === false');
assert.equal(await evaluate('document.getElementById("claim-error").textContent'), expectedError);
@@ -89,7 +113,11 @@ try {
await call('Input.insertText', {text:'shop@example.com'});
await key('Tab','Tab',9);
assert.equal(await evaluate('document.activeElement.tagName'), 'BUTTON');
+ // Each address posts to /demo/claim/prove, which sends the browser back
+ // to /demo/claim.
+ let since = commits.length;
await key('Enter','Enter',13);
+ await committed(since, [page]);
await until('!!document.getElementById("code")');
assert.equal(await evaluate('document.querySelector("label[for=code]") !== null'), true);
await captureClaim(call, evaluate, screenshots, 'code', [390, 1280]);
@@ -98,7 +126,9 @@ try {
await evaluate('document.querySelector(".claim-email-change summary").click(); document.getElementById("email").focus()');
await call('Input.insertText', {text:'another@example.com'});
await key('Tab','Tab',9);
+ since = commits.length;
await key('Enter','Enter',13);
+ await committed(since, [page]);
await until('!!document.getElementById("code") && !document.querySelector(".claim-email-change").open');
assert.deepEqual(await evaluate('window.claimCSPViolations'), []);
await evaluate('document.getElementById("code").focus()');
@@ -106,7 +136,12 @@ try {
assert.equal(await evaluate('document.getElementById("code").form.checkValidity()'), true);
await key('Tab','Tab',9);
assert.equal(await evaluate('document.activeElement.textContent'), 'Confirm');
- await evaluate(`document.getElementById('code').form.addEventListener('submit', event => {
+ // The page cancels the submit event and posts the form itself after its
+ // 650 ms hold, through HTMLFormElement.prototype.submit, so the listener's
+ // preventDefault alone does not stop that post. Stub it: the reads below
+ // must not race a navigation to the code's result.
+ await evaluate(`HTMLFormElement.prototype.submit = function() {};
+ document.getElementById('code').form.addEventListener('submit', event => {
event.preventDefault();
const form = event.target;
window.claimCodeSubmission = {
@@ -145,11 +180,13 @@ async function runUX(scenes) {
if (scene.Session) cookies.push({name:'carlos_console_session',value:scene.Session,url:origin,path:'/',httpOnly:true});
await call('Network.setCookies',{cookies});
if (scene.Name === 'missing') await call('Network.setBlockedURLs',{urls:['*demo_claim.js*']});
- await call('Page.navigate',{url:scene.URL});
+ // Each scene is a fresh /demo/claim (on its own server); a scene's
+ // fragment is a refused token, so the shell stays put.
+ await navigate(scene.URL,[origin+'/demo/claim']);
await until('document.readyState === "complete" && !!document.getElementById("claim")');
assert.equal(await evaluate('document.getElementById("claim").dataset.state'),scene.State,scene.Name);
if (scene.Name === 'motion') {
- await checkClaimMotion(call, evaluate, until, screenshots, scene.URL, scene);
+ await checkClaimMotion(call, evaluate, until, navigate, screenshots, scene.URL, scene);
process.stdout.write('live progress: centred rings/dots/ticks, spin, flowing path, calm breathe, zero CSP violations; '+(scene.Widths ?? [390,1280]).join('/')+' '+(scene.Themes ?? ['light','dark']).join('/')+' passed\n');
continue;
}
@@ -181,7 +218,9 @@ async function runUX(scenes) {
}
assert.equal(await evaluate('window.claimBlankFrames'),0,'blank progress frame');
await captureClaim(call,evaluate,screenshots,'live-done',[390,1280]);
+ const since = commits.length;
await call('Page.reload');
+ await committed(since,[origin+'/demo/claim']);
await until('document.readyState === "complete" && document.getElementById("claim")?.dataset.state === "claimed"');
assert.equal(await evaluate('document.getElementById("claim").classList.contains("is-celebrating")'),false);
assert.equal(await evaluate('document.querySelector(".claim-command")?.open ?? false'),false);
@@ -218,7 +257,7 @@ async function liveMotion(scene) {
for (const width of scene.Widths ?? [390,1280]) for (const theme of scene.Themes ?? ['light','dark']) for (const motion of ['no-preference','reduce']) {
await call('Emulation.setDeviceMetricsOverride',{width,height:900,deviceScaleFactor:1,mobile:false});
await call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:theme},{name:'prefers-reduced-motion',value:motion}]});
- await call('Page.navigate',{url:scene.URL+'?replay=1'});
+ await navigate(scene.URL+'?replay=1');
await until('document.readyState === "complete" && document.getElementById("claim")?.dataset.state === "claiming"');
await until('document.getElementById("claim")?.dataset.state === "claimed"');
assert.equal(await evaluate('document.getElementById("claim").classList.contains("is-celebrating")'),true);
@@ -237,7 +276,10 @@ async function liveMotion(scene) {
await writeFile(screenshots+'/reveal-'+motion+'-'+theme+'-'+width+'.png',Buffer.from(shot.data,'base64'));
}
assert.deepEqual(await evaluate('window.claimCSPViolations'),[]);
+ // The page replaced ?replay=1 with /demo/claim, so that is what reloads.
+ const since = commits.length;
await call('Page.reload');
+ await committed(since,[new URL(scene.URL).origin+'/demo/claim']);
await until('document.readyState === "complete" && document.getElementById("claim")?.dataset.state === "claimed"');
assert.equal(await evaluate('document.getElementById("claim").classList.contains("is-celebrating")'),false);
assert.equal(await evaluate('document.getAnimations().length'),0);
diff --git a/internal/console/testdata/demo_claim_kept_browser.mjs b/internal/console/testdata/demo_claim_kept_browser.mjs
index e270fbe9c..ed6176671 100644
--- a/internal/console/testdata/demo_claim_kept_browser.mjs
+++ b/internal/console/testdata/demo_claim_kept_browser.mjs
@@ -12,6 +12,8 @@ const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
let sequence = 0, buffered = '', session;
const pending = new Map();
const violations = [];
+// Every document the tab's main frame commits, in order (fragment excluded).
+const commits = [];
chrome.stdio[4].on('data', bytes => {
buffered += bytes.toString();
let end;
@@ -19,6 +21,7 @@ chrome.stdio[4].on('data', bytes => {
const message = JSON.parse(buffered.slice(0, end));
buffered = buffered.slice(end + 1);
if (message.method === 'Runtime.bindingCalled' && message.params.name === 'keptCSP') violations.push(message.params.payload);
+ if (message.method === 'Page.frameNavigated' && message.sessionId === session && !message.params.frame.parentId) commits.push(message.params.frame.url);
const resolve = pending.get(message.id);
if (resolve) { pending.delete(message.id); resolve(message); }
}
@@ -43,6 +46,17 @@ async function until(expression) {
}
throw Error('browser_condition_timeout: ' + await evaluate('JSON.stringify({text:document.body.innerText,email:document.getElementById("email")?.value,focus:document.activeElement.tagName,valid:document.querySelector("form")?.checkValidity()})'));
}
+// The kept shell replaces itself with /demo/claim once its exchange lands,
+// and Page.reload answers before its navigation commits. A command that
+// reaches the outgoing document as the next one commits fails with -32000
+// "Inspected target navigated or closed" (main CI, 2026-11-19), and a
+// condition polled too soon can pass on the outgoing page. So a step that
+// navigates waits, sending nothing, until the main frame has committed
+// exactly the documents it expects, and only then polls the page.
+async function committed(since, urls) {
+ for (let i = 0; i < 150 && commits.length - since < urls.length; i++) await new Promise(resolve => setTimeout(resolve, 100));
+ assert.deepEqual(commits.slice(since), urls);
+}
const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 170000);
try {
@@ -70,7 +84,10 @@ try {
await call('Network.clearBrowserCookies');
await call('Emulation.setDeviceMetricsOverride', {width:scene.Width,height:900,deviceScaleFactor:1,mobile:false});
await call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:scene.Theme},{name:'prefers-reduced-motion',value:'no-preference'}]});
+ const origin = new URL(scene.URL).origin;
+ let since = commits.length;
await call('Page.navigate',{url:scene.URL});
+ await committed(since,[origin+'/demo/claim/kept',origin+'/demo/claim']);
if (scene.Mode === 'live') {
await until('location.hash === "" && document.getElementById("claim")?.dataset.state === "claiming"');
await shot(scene,'progress');
@@ -90,7 +107,9 @@ try {
assert(cookies.every(cookie => cookie.name !== 'carlos_console_session'));
const statusCookie = cookies.find(cookie => cookie.name === 'carlos_demo_claim_flow');
assert(statusCookie?.httpOnly && statusCookie.secure && statusCookie.path === '/demo/claim');
+ since = commits.length;
await call('Page.reload',{ignoreCache:true});
+ await committed(since,[origin+'/demo/claim']);
await until('document.readyState === "complete" && document.getElementById("claim")?.dataset.state === "claimed"');
await new Promise(resolve => setTimeout(resolve,1800));
assert.equal(await evaluate('window.keptReveals'),0);
diff --git a/internal/console/testdata/demo_claim_motion.mjs b/internal/console/testdata/demo_claim_motion.mjs
index a38924cfd..651f4f4ea 100644
--- a/internal/console/testdata/demo_claim_motion.mjs
+++ b/internal/console/testdata/demo_claim_motion.mjs
@@ -46,8 +46,9 @@ const motionState = `(() => {
})()`;
// only.Widths and only.Themes narrow the run to some of the variants, so the
-// Go side can split them across tests; absent, every variant runs.
-export async function checkClaimMotion(call, evaluate, until, screenshots, url, only = {}) {
+// Go side can split them across tests; absent, every variant runs. navigate
+// loads a page and returns once that document has committed.
+export async function checkClaimMotion(call, evaluate, until, navigate, screenshots, url, only = {}) {
// Change the fixture's operation, then let the real status endpoint and page
// script advance the UI. Never manufacture the state attributes in the test.
const phase = async value => {
@@ -55,13 +56,13 @@ export async function checkClaimMotion(call, evaluate, until, screenshots, url,
assert.equal(response.status, 204);
};
for (const width of only.Widths ?? [390,1280]) for (const theme of only.Themes ?? ['light','dark']) for (const motion of ['no-preference','reduce']) {
- await call('Page.navigate', {url:'about:blank'});
+ await navigate('about:blank');
await phase('future-phase');
await call('Emulation.setDeviceMetricsOverride', {width,height:900,deviceScaleFactor:1,mobile:false});
await call('Emulation.setEmulatedMedia', {features:[
{name:'prefers-color-scheme',value:theme}, {name:'prefers-reduced-motion',value:motion}
]});
- await call('Page.navigate', {url});
+ await navigate(url);
await until('document.readyState === "complete" && document.getElementById("claim-progress")?.dataset.stage === "0"');
assert.equal(await evaluate('document.querySelectorAll(".claim-steps [aria-current]").length'), 0);
let baseline;
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs
index 5b54820ea..9031fbce2 100644
--- a/internal/console/testdata/demo_claim_resume_browser.mjs
+++ b/internal/console/testdata/demo_claim_resume_browser.mjs
@@ -12,6 +12,8 @@ let sequence = 0, buffered = '', session;
const pending = new Map();
let security = [], statusRequests = 0;
const submissions = [];
+// Every document the tab's main frame commits, in order (fragment excluded).
+const commits = [];
chrome.stdio[4].on('data', bytes => {
buffered += bytes.toString();
@@ -19,6 +21,7 @@ chrome.stdio[4].on('data', bytes => {
while ((end = buffered.indexOf('\0')) !== -1) {
const message = JSON.parse(buffered.slice(0, end));
buffered = buffered.slice(end + 1);
+ if (message.method === 'Page.frameNavigated' && message.sessionId === session && !message.params.frame.parentId) commits.push(message.params.frame.url);
if (message.method === 'Network.requestWillBeSent' && new URL(message.params.request.url).pathname === '/demo/claim/status') statusRequests++;
if (message.method === 'Log.entryAdded' && message.params.entry.source === 'security') security.push(message.params.entry.text);
if (message.method === 'Runtime.bindingCalled' && message.params.name === 'claimSubmitted') submissions.push(JSON.parse(message.params.payload));
@@ -46,6 +49,23 @@ async function until(expression) {
}
throw Error('browser_condition_timeout: ' + await evaluate('JSON.stringify({text:document.body.innerText,email:document.getElementById("email")?.value,focus:document.activeElement.tagName,valid:document.querySelector("form")?.checkValidity()})'));
}
+// Page.navigate answers before its navigation commits (Chromium 151,
+// measured 2026-11-19), most steps here move between /demo/claim pages that
+// meet the same condition, and a submitted choice posts after the page's
+// 650 ms hold. A command that reaches the outgoing document as the next one
+// commits fails with -32000 "Inspected target navigated or closed", and a
+// condition polled too soon can pass on the outgoing page. So a step that
+// navigates waits, sending nothing, until the main frame has committed
+// exactly the documents it expects, and only then polls the page.
+async function committed(since, urls) {
+ for (let i = 0; i < 150 && commits.length - since < urls.length; i++) await new Promise(resolve => setTimeout(resolve, 100));
+ assert.deepEqual(commits.slice(since), urls);
+}
+async function navigate(url, urls = [url]) {
+ const since = commits.length;
+ await call('Page.navigate', {url});
+ await committed(since, urls);
+}
async function key(key, code, number) {
await call('Input.dispatchKeyEvent', {type:key === 'Enter' ? 'keyDown' : 'rawKeyDown', key, code, windowsVirtualKeyCode:number, ...(key === 'Enter' ? {text:'\r', unmodifiedText:'\r'} : {})});
await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number});
@@ -89,14 +109,14 @@ try {
{name:'carlos_console_session',value:single.session,url:single.target,path:'/',httpOnly:true,sameSite:'Lax'},
{name:'carlos_demo_claim_flow',value:single.cookie,url:single.target,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
]});
- await call('Page.navigate',{url:single.target+'/demo/claim'});
+ await navigate(single.target+'/demo/claim');
await until('document.readyState === "complete" && !!document.querySelector("#claim input[type=hidden][name=accountId]")');
assert.equal(await evaluate('document.querySelectorAll("#claim input[type=radio]").length'),0);
assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'),'Keep in shop');
assert.equal(await evaluate('document.querySelector(".claim-single").innerText.includes("Has room")'),true);
assert.equal(await evaluate('document.querySelector(".claim-single").innerText.includes("apps and instances")'),false);
await capture('one');
- await call('Page.navigate',{url:single.target+'/demo/claim?long=1'});
+ await navigate(single.target+'/demo/claim?long=1');
await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 2');
assert.equal(await evaluate('document.querySelector(".claim-card .claim-row-name").textContent.length > 100'), true);
assert.equal(await evaluate('document.querySelector(".claim-address .claim-old").textContent.length > 100'), true);
@@ -106,7 +126,7 @@ try {
{name:'carlos_console_session',value:single.capacitySession,url:single.capacityTarget,path:'/',httpOnly:true,sameSite:'Lax'},
{name:'carlos_demo_claim_flow',value:single.capacityCookie,url:single.capacityTarget,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
]});
- await call('Page.navigate',{url:single.capacityTarget+'/demo/claim'});
+ await navigate(single.capacityTarget+'/demo/claim');
await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 2');
const capacityCards = await evaluate('Array.from(document.querySelectorAll(".claim-card"), card => ({text:card.innerText,disabled:card.querySelector("input").disabled}))');
assert(capacityCards.every(card=>card.disabled));
@@ -119,7 +139,7 @@ try {
{name:'carlos_console_session',value:single.pickerSession,url:single.pickerTarget,path:'/',httpOnly:true,sameSite:'Lax'},
{name:'carlos_demo_claim_flow',value:single.pickerCookie,url:single.pickerTarget,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
]});
- await call('Page.navigate',{url:single.pickerTarget+'/demo/claim'});
+ await navigate(single.pickerTarget+'/demo/claim');
await until('document.readyState === "complete" && document.querySelectorAll(".claim-card").length === 30');
assert.equal(await evaluate('document.body.innerText.includes("2305843009213693951") || !!document.querySelector("meter")'), false, 'sentinel or meter shown');
assert.equal(await evaluate('document.querySelector(".claim-search").hidden'), false, 'script did not reveal the search box');
@@ -155,22 +175,25 @@ try {
{name:'carlos_demo_claim_flow',value:flowCookie,url:target,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'}
]});
await call('Network.setBlockedURLs', {urls:['*demo_claim.js*']});
- await call('Page.navigate', {url:target+'/demo/claim'});
+ await navigate(target+'/demo/claim');
await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
assert.equal(await evaluate('document.querySelector("button[type=submit]").disabled'),false,'script failure disabled the manual fallback');
assert.equal(await evaluate('document.querySelector("form").getBoundingClientRect().height > 0'),true,'script failure hid the form');
assert.equal(await evaluate('document.querySelector("#claim form").checkValidity()'),false,'native required radio missing');
await call('Network.setBlockedURLs', {urls:[]});
- await call('Page.navigate', {url:target+'/demo/claim?csp=before'});
+ await navigate(target+'/demo/claim?csp=before');
await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
+ const blocked = commits.length;
await evaluate(`document.querySelector('input[value='+${JSON.stringify(account)}+']').click(); document.querySelector('form[action="/demo/claim/select"]').requestSubmit()`);
for (let i=0; i<50 && !security.some(s=>s.includes('form-action')); i++) await new Promise(r=>setTimeout(r,100));
assert(security.some(s=>s.includes('form-action')), 'Chromium did not reproduce redirect CSP block: '+JSON.stringify(security));
+ // The blocked post commits nothing: this is still the ?csp=before page.
+ assert.deepEqual(commits.slice(blocked), [], 'the blocked post committed a document');
assert.equal(await evaluate('location.origin'), target);
process.stdout.write('before: Chromium blocked the cross-port Keymail redirect\n');
security = [];
submissions.length = 0;
- await call('Page.navigate', {url:target+'/demo/claim'});
+ await navigate(target+'/demo/claim');
await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").disabled'),true);
assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").textContent'),'Choose an account');
@@ -191,13 +214,23 @@ try {
assert.equal(await evaluate('document.querySelector(".claim-card:last-of-type input").disabled'),true,'the view-only account must sort last');
assert.equal(await evaluate('!!document.querySelector(".claim-search")'),false,'three accounts need no search box');
await capture('many');
- await evaluate(`const form = document.querySelector('form[action="/demo/claim/select"]'); form.addEventListener('submit', event => event.preventDefault(), {once:true}); form.requestSubmit(); document.querySelector('#claim input[type=radio]:not(:disabled)').click()`);
+ // The page cancels the submit event and posts the form itself after its
+ // 650 ms hold, through HTMLFormElement.prototype.submit, so the listener's
+ // preventDefault alone does not stop that post. Stub it: this submission
+ // must not choose the account, nor race the check and navigation below.
+ await evaluate(`HTMLFormElement.prototype.submit = function() {}; const form = document.querySelector('form[action="/demo/claim/select"]'); form.addEventListener('submit', event => event.preventDefault(), {once:true}); form.requestSubmit(); document.querySelector('#claim input[type=radio]:not(:disabled)').click()`);
assert.equal(await evaluate('document.querySelector("#claim button[type=submit]").disabled'),true,'radio change re-enabled submitted button');
- await call('Page.navigate', {url:target+'/demo/claim'});
+ await navigate(target+'/demo/claim');
await until('document.readyState === "complete" && !!document.querySelector("input[type=radio][name=accountId]")');
await evaluate(`document.querySelector('input[value='+${JSON.stringify(account)}+']').click()`);
submissions.length = 0;
+ // The choice posts after the page's hold, and fresh auth sends it through
+ // Keymail and the step-up callback, all redirects, back to /demo/claim:
+ // the resumed first paint, which posts the same account itself after the
+ // hold and lands on /demo/claim again, the progress view.
+ const chosen = commits.length;
await evaluate(`const button = document.querySelector('form[action="/demo/claim/select"] button'); button.click(); button.click()`);
+ await committed(chosen, [target+'/demo/claim', target+'/demo/claim']);
await until(`!!document.querySelector("p[role=status]") && !document.querySelector('form[action="/demo/claim/select"]')`);
assert.equal(await evaluate('location.pathname'),'/demo/claim');
assert.equal(await evaluate('location.hash'),'');
@@ -239,13 +272,13 @@ try {
await call('Page.removeScriptToEvaluateOnNewDocument', {identifier:clipboardStub.identifier});
const noClipboard = await call('Page.addScriptToEvaluateOnNewDocument', {source:
"Object.defineProperty(navigator, 'clipboard', {value:undefined})"});
- await call('Page.navigate', {url:target+'/demo/claim'});
+ await navigate(target+'/demo/claim');
await until('document.readyState === "complete" && !!document.querySelector("[data-copy-target=claim-cli-command]")');
assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").getBoundingClientRect().height'), 0);
assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), "carlos auth login --console '"+target+"'");
await call('Page.removeScriptToEvaluateOnNewDocument', {identifier:noClipboard.identifier});
await call('Network.setBlockedURLs', {urls:['*demo_claim.js*']});
- await call('Page.navigate', {url:target+'/demo/claim'});
+ await navigate(target+'/demo/claim');
await until('document.readyState === "complete" && !!document.querySelector("[data-copy-target=claim-cli-command]")');
assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").getBoundingClientRect().height'), 0);
assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), "carlos auth login --console '"+target+"'");
@@ -255,7 +288,7 @@ try {
const requestsAtDone=statusRequests;
await new Promise(r=>setTimeout(r,3500));
assert.equal(statusRequests,requestsAtDone,'done kept polling');
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=fail'});
+ await navigate(target+'/demo/claim?testProgress=fail');
await until('!!document.getElementById("claim-progress")');
const beforeFailure=statusRequests;
await until('document.getElementById("claim-reload")?.hidden === false');
@@ -266,11 +299,11 @@ try {
await new Promise(r=>setTimeout(r,3500));
assert.equal(statusRequests-beforeFailure,3,'failure fallback kept polling');
await call('Network.setBlockedURLs',{urls:['*demo_claim.js*']});
- await call('Page.navigate',{url:target+'/demo/claim'});
+ await navigate(target+'/demo/claim');
await until('document.readyState === "complete" && !!document.getElementById("claim-reload")');
assert.equal(await evaluate('document.getElementById("claim-reload").getBoundingClientRect().height > 0'),true,'no-script reload link hidden');
await call('Network.setBlockedURLs',{urls:[]});
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=abort'});
+ await navigate(target+'/demo/claim?testProgress=abort');
await until('!!document.getElementById("claim-progress")');
const beforeAbort=statusRequests;
await until('document.getElementById("claim-status")?.textContent === document.getElementById("claim-progress")?.dataset.aborted');
@@ -279,7 +312,7 @@ try {
await new Promise(r=>setTimeout(r,3500));
assert.equal(statusRequests-beforeAbort,1,'aborted kept polling');
assert.equal(security.length,0,JSON.stringify(security));
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=stopping'});
+ await navigate(target+'/demo/claim?testProgress=stopping');
await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"');
await until('document.getElementById("claim-status")?.textContent === document.getElementById("claim-progress")?.dataset.stopping');
assert.equal(await evaluate('document.querySelectorAll("[aria-current=step]").length'),0);
@@ -287,7 +320,7 @@ try {
assert.equal(await evaluate('!!document.querySelector(".claim-steps .is-failed")'),true);
await capture('stopping-live');
await until('document.getElementById("claim-status")?.textContent === document.getElementById("claim-progress")?.dataset.aborted');
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=unknown'});
+ await navigate(target+'/demo/claim?testProgress=unknown');
await until('!!document.getElementById("claim-progress") && document.querySelectorAll("[aria-current=step]").length === 0');
const unknownPolls = statusRequests;
await new Promise(r=>setTimeout(r,6500));
@@ -297,7 +330,7 @@ try {
process.stdout.write('fallback: stopped after three failures, retained no-script reload, stopped on abort; no CSP violations\n');
// A long "Starting your app": the bar sits inside the step's band and
// never goes back, and the step's detail rotates through reassurance.
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=starting'});
+ await navigate(target+'/demo/claim?testProgress=starting');
await until('document.querySelector("li[aria-current=step]")?.dataset.step === "2"');
const original = await evaluate('document.querySelector("li[aria-current=step] .claim-step-detail").textContent');
const bar = 'Number(document.querySelector(".claim-bar").getAttribute("aria-valuenow"))';
@@ -310,7 +343,7 @@ try {
assert.equal(await evaluate('document.getElementById("claim-stuck").hidden'),true,'stuck before the deadline');
await capture('starting-hint');
// Past the server's deadline plus grace, still reporting progress: stuck.
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=stuck'});
+ await navigate(target+'/demo/claim?testProgress=stuck');
await until('!!document.getElementById("claim-progress")');
assert.equal(await evaluate('document.getElementById("claim-stuck").hidden'),true,'stuck before polling');
await until('document.getElementById("claim-stuck")?.hidden === false');
@@ -325,7 +358,7 @@ try {
// Past the irreversible commit the rollback deadline does not apply: an
// overdue committed claim says it is the person's and still finishing,
// never that it will be undone.
- await call('Page.navigate',{url:target+'/demo/claim?testProgress=committed'});
+ await navigate(target+'/demo/claim?testProgress=committed');
await until('!!document.getElementById("claim-progress")?.dataset.committedFor');
const committedPolls = statusRequests;
await until('document.getElementById("claim-finishing")?.hidden === false');
diff --git a/internal/lease/lease.go b/internal/lease/lease.go
index 71a0d0705..f4daab31b 100644
--- a/internal/lease/lease.go
+++ b/internal/lease/lease.go
@@ -477,7 +477,8 @@ func (h *Held) newStore(dbPath string, syncInterval time.Duration) (*litestream.
return nil, nil, err
}
}
- db.Replica = litestream.NewReplicaWithClient(db, client)
+ // A snapshot whose upload fails must not keep the WAL open (#811).
+ db.Replica = litestream.NewReplicaWithClient(db, pipeClosingClient{client})
if syncInterval > 0 {
db.Replica.SyncInterval = syncInterval
}
diff --git a/internal/lease/snapshotpipe.go b/internal/lease/snapshotpipe.go
new file mode 100644
index 000000000..59b02b6b7
--- /dev/null
+++ b/internal/lease/snapshotpipe.go
@@ -0,0 +1,36 @@
+package lease
+
+import (
+ "context"
+ "io"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+)
+
+// pipeClosingClient is every store's replica client (newStore): its
+// WriteLTXFile closes a pipe body on every outcome, as the fence gate
+// and generationClient do, and as snapshotWithin closes its own reader.
+//
+// litestream's DB.Snapshot never closes its reader when the write fails
+// (#811). The reader is a pipe whose encoder, a goroutine nothing can
+// join, holds the WAL open. The store's snapshot monitor runs a pass at
+// Open, so a teardown soon after a wake can land while that snapshot
+// uploads: the store's Close cancels the monitor, and if the cancel comes
+// after litestream has peeked the LTX header, the S3 uploader refuses the
+// cancelled context before it reads the body. The encoder then waits on
+// the pipe for good, holding the WAL descriptor (and its goroutine) for
+// the life of the process, after a teardown that has otherwise closed
+// the database (TestTeardownReleasesACancelledSnapshot). Closing the pipe
+// fails the encoder's next write, and it closes the WAL as it returns.
+//
+// It hides the inner client's optional ReplicaClientV3, which litestream
+// uses only to restore; nothing restores through a store's replica.
+type pipeClosingClient struct{ litestream.ReplicaClient }
+
+func (c pipeClosingClient) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if pipe, ok := r.(*io.PipeReader); ok {
+ defer pipe.Close()
+ }
+ return c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, r)
+}
diff --git a/internal/lease/teardown_linux_test.go b/internal/lease/teardown_linux_test.go
index ea39c2469..7fabd2535 100644
--- a/internal/lease/teardown_linux_test.go
+++ b/internal/lease/teardown_linux_test.go
@@ -3,10 +3,19 @@
package lease_test
import (
+ "context"
"errors"
+ "fmt"
+ "io"
"os"
"path/filepath"
+ "runtime"
+ "slices"
"testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/lease"
leasetest "github.com/carlosframework/platform/internal/lease/locktest"
@@ -16,6 +25,12 @@ import (
// at path and its -wal and -shm files: litestream's DB.init opens the
// database (sql.DB and a long-running descriptor), its Close closes them.
func openDBFiles(t *testing.T, path string) int {
+ t.Helper()
+ return openFiles(t, path, path+"-wal", path+"-shm")
+}
+
+// openFiles counts this process's open file descriptors on any of paths.
+func openFiles(t *testing.T, paths ...string) int {
t.Helper()
fds, err := os.ReadDir("/proc/self/fd")
if err != nil {
@@ -27,13 +42,39 @@ func openDBFiles(t *testing.T, path string) int {
if err != nil {
continue // closed since the listing
}
- if target == path || target == path+"-wal" || target == path+"-shm" {
+ if slices.Contains(paths, target) {
n++
}
}
return n
}
+// tornDownFiles fails t unless the teardown that just returned closes
+// every descriptor on the database at path: the database file, its -wal
+// and its -shm. Each check waits for the descriptor itself (#1193), with
+// a guard only a descriptor that never closes meets. Two goroutines that
+// nothing joins can close one a moment after the teardown returns:
+//
+// - litestream's snapshot encoder (DB.SnapshotReader). The store's
+// snapshot monitor runs a pass at Open, concurrently with the test's
+// first sync. The encoder opens the WAL read-only and closes it in a
+// defer that runs after it has closed its pipe, and the store's Close
+// waits for the upload reading that pipe, not for the encoder. An
+// encoder that never lets go (#811, pipeClosingClient) meets the
+// guard.
+// - database/sql's rollback of litestream's long-running read
+// transaction, which runs under the DB's context: DB.Close cancels
+// it, the rollback starts in Tx.awaitDone, and sql.DB.Close does not
+// wait for a connection that transaction still has checked out, so
+// the connection's database and -shm descriptors can outlive it.
+func tornDownFiles(t *testing.T, path string) {
+ t.Helper()
+ for _, p := range []string{path, path + "-shm", path + "-wal"} {
+ lease.WaitDescriptorsForTest(t, p, "the teardown left "+filepath.Base(p)+" open",
+ func(open int) bool { return open == 0 })
+ }
+}
+
// replicating is a non-HA replicator of a fresh database on prefix, its
// first sync shipped.
func replicating(t *testing.T, fx *leasetest.LockFixture, prefix string) (*lease.Replicator, string) {
@@ -76,9 +117,7 @@ func TestTeardownIsTerminal(t *testing.T) {
if err := tc.first(r); err != nil {
t.Fatalf("first teardown: %v", err)
}
- if n := openDBFiles(t, dbPath); n != 0 {
- t.Fatalf("the first teardown left %d descriptors on the database open", n)
- }
+ tornDownFiles(t, dbPath)
before := len(fx.Requests())
err := tc.again(r)
reqs, open := fx.Requests()[before:], openDBFiles(t, dbPath)
@@ -88,3 +127,152 @@ func TestTeardownIsTerminal(t *testing.T) {
})
}
}
+
+// cancelAfterHeader cancels its upload's context once litestream has
+// read the snapshot's LTX header from it (ltx.PeekHeader): a store's
+// Close cancelling its snapshot monitor at that point.
+type cancelAfterHeader struct {
+ r io.Reader
+ n int
+ cancel context.CancelFunc
+}
+
+func (c *cancelAfterHeader) Read(p []byte) (int, error) {
+ n, err := c.r.Read(p)
+ if c.n += n; c.n >= ltx.HeaderSize {
+ c.cancel()
+ }
+ return n, err
+}
+
+// snapshotGuard bounds the waits of TestTeardownReleasesACancelledSnapshot,
+// as descriptorGuard bounds the descriptor checks: only a real bug (no
+// snapshot, an encoder that never writes, a pipe nobody closes) meets it.
+const snapshotGuard = 30 * time.Second
+
+// cancelledUpload is what cancelledSnapshot saw of one snapshot upload.
+type cancelledUpload struct {
+ pipe *io.PipeReader // the snapshot's own reader, litestream's pipe
+ err error // the upload's answer
+ // blocked is nil once the encoder was seen offering a body write to
+ // the pipe after the upload returned: blocked on a pipe that nothing
+ // will read again.
+ blocked error
+}
+
+// cancelledSnapshot is the real S3 replica client, except that each
+// snapshot upload is cancelled once its header has been read. The first
+// snapshot's upload is reported on done.
+type cancelledSnapshot struct {
+ litestream.ReplicaClient
+ done chan cancelledUpload
+}
+
+func (c cancelledSnapshot) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) {
+ if level != litestream.SnapshotLevel {
+ return c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, r)
+ }
+ up := cancelledUpload{}
+ up.pipe, _ = r.(*io.PipeReader)
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ info, err := c.ReplicaClient.WriteLTXFile(ctx, level, minTXID, maxTXID, &cancelAfterHeader{r: r, cancel: cancel})
+ up.err = err
+ up.blocked = errors.New("the snapshot's reader is not litestream's pipe")
+ if up.pipe != nil {
+ up.blocked = offering(up.pipe)
+ }
+ select {
+ case c.done <- up:
+ default:
+ }
+ return info, err
+}
+
+// offering waits, up to snapshotGuard, for the writer of pipe to offer a
+// write, and consumes none of it: a zero-length Read returns once a
+// writer is waiting in Write, which then goes on waiting. nil means the
+// writer is blocked in a write; an error that the pipe was closed first.
+func offering(pipe *io.PipeReader) error {
+ got := make(chan error, 1)
+ go func() {
+ _, err := pipe.Read(nil)
+ got <- err
+ }()
+ select {
+ case err := <-got:
+ if err != nil {
+ return fmt.Errorf("the pipe closed before its encoder blocked: %w", err)
+ }
+ return nil
+ case <-time.After(snapshotGuard):
+ return fmt.Errorf("the encoder offered no write in %s", snapshotGuard)
+ }
+}
+
+// readerClosed waits, up to snapshotGuard, until pipe's reader end has
+// been closed (io.ErrClosedPipe), without draining it. Its writer is
+// blocked offering a write (offering), so each zero-length Read returns
+// at once until then.
+func readerClosed(pipe *io.PipeReader) error {
+ for guard := time.Now().Add(snapshotGuard); ; runtime.Gosched() {
+ _, err := pipe.Read(nil)
+ switch {
+ case errors.Is(err, io.ErrClosedPipe):
+ return nil
+ case err != nil:
+ return fmt.Errorf("the pipe's writer ended it first: %w", err)
+ case time.Now().After(guard):
+ return fmt.Errorf("nothing closed the snapshot's pipe in %s", snapshotGuard)
+ }
+ }
+}
+
+// #811 on a non-HA replicator: the store's snapshot monitor runs a pass at
+// Open, and a teardown that cancels it after litestream has peeked the LTX
+// header makes the S3 uploader return before it reads the body. litestream
+// never closes that pipe, so its encoder would hold the WAL open for the
+// life of the process. The test cancels the upload the same way with no
+// teardown, sees the encoder blocked on the pipe once the upload has
+// returned, and requires the store's replica client (pipeClosingClient) to
+// close the pipe before anything is torn down; then the teardown leaves
+// nothing open.
+func TestTeardownReleasesACancelledSnapshot(t *testing.T) {
+ fx := leasetest.NewLockFixture(t)
+ const prefix = "instances/cancelled.example.com"
+ h, err := lease.Acquire(ctx, fx.Bucket, prefix, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s3, err := lease.ReadReplicaClient(ctx, fx.Bucket, prefix, "us-east-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ snap := cancelledSnapshot{ReplicaClient: s3, done: make(chan cancelledUpload, 1)}
+ lease.SetReplicaClientForTest(h, snap)
+ dbPath := tempDB(t)
+ r, err := h.Replicate(ctx, dbPath, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { r.Abandon(ctx) })
+ if err := r.SyncAndWait(ctx); err != nil {
+ t.Fatalf("first sync: %v", err)
+ }
+ var up cancelledUpload
+ select {
+ case up = <-snap.done:
+ case <-time.After(snapshotGuard):
+ t.Fatal("the store's snapshot monitor made no snapshot")
+ }
+ if !errors.Is(up.err, context.Canceled) || up.blocked != nil {
+ t.Fatalf("the snapshot upload = %v, its encoder: %v; want it cancelled, the encoder blocked on its pipe", up.err, up.blocked)
+ }
+ // Before any teardown: the store's replica client, not a closed
+ // database or a cancelled store, is what releases the encoder.
+ if err := readerClosed(up.pipe); err != nil {
+ t.Fatal(err)
+ }
+ r.Abandon(ctx)
+ tornDownFiles(t, dbPath)
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 89c7db953..9a901d8f4 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -252,4 +252,5 @@ plan14-root-reads-staticcheck-sa1012.tsv 5fcd060180e923773dad3faee7cc60ee250779a
plan14-root-reads-staticcheck-sa1019.tsv f9be26c06eb1c844b91a75f65faa51997048cb2900f3ed078be2ae28c65c0e98
plan14-root-reads-small-fixes-1246-1248.tsv c6d366dcf2211b714977b7a69180289555b362dfe5f36a5780af90b5ece82998
plan14-root-reads-edge-ppv2-idle.tsv 5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4
+plan14-root-reads-flake-lease-teardown.tsv 5d4a5eea79394145fdd59aa5eb87115cc1ee396e02e0ab4b21decd2b3a10e3b4
plan14-root-reads-named-units-param-114.tsv 05a5d81f4e437816fcdb142990c540033112d8d912429642f5444bf5cfb4ed8d
diff --git a/internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv b/internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv
new file mode 100644
index 000000000..fbc2ef5c4
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-flake-lease-teardown.tsv
@@ -0,0 +1,3 @@
+# Census overlay flake-lease-teardown, written by census-propose (#369). census-ruling-flake-lease-teardown, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-flake-lease-teardown.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/lease 1af3b69b91061e6f593bc4df2756308fb4befed1fba5b4b41adff42254426a81
diff --git a/scripts/gitleaks-gate/main.go b/scripts/gitleaks-gate/main.go
new file mode 100644
index 000000000..8f9e5726d
--- /dev/null
+++ b/scripts/gitleaks-gate/main.go
@@ -0,0 +1,367 @@
+// Command gitleaks-gate is `make gitleaks` (.amadan/ci.d/80-gitleaks): it
+// proves the scan still finds planted keys, then scans the tracked files.
+//
+// gitleaks does the finding, with its default rules less the exact values
+// .gitleaks.toml allows. This program decides what is scanned and what a
+// finding means, as scripts/govulncheck-gate does for govulncheck: every
+// tracked file is scanned except the ones notscanned.go names by exact path,
+// and every finding fails the step except the key the gate plants itself.
+//
+// Anything it cannot establish is a failure: the wrong binary, a config
+// gitleaks will not load, a report it cannot read, or a scan that did not
+// find the key planted beside the tracked files.
+package main
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "debug/buildinfo"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io/fs"
+ "math"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "syscall"
+)
+
+const (
+ gitleaksModule = "github.com/zricethezav/gitleaks/v8"
+
+ // exitFindings is the status gitleaks is told to use for "found
+ // something", so that its own failures (status 1) cannot be mistaken
+ // for a scan that finished.
+ exitFindings = 3
+)
+
+// finding is the part of gitleaks' JSON report the gate reads.
+type finding struct {
+ RuleID string
+ File string
+ Secret string
+ StartLine int
+}
+
+func main() {
+ bin := flag.String("gitleaks", "", "path to the gitleaks binary")
+ version := flag.String("version", "", "the version the gitleaks binary must be")
+ config := flag.String("config", ".gitleaks.toml", "path to the gitleaks config")
+ flag.Parse()
+
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ err := run(ctx, *bin, *version, *config)
+ stop()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "gitleaks-gate:", err)
+ os.Exit(1)
+ }
+}
+
+func run(ctx context.Context, bin, version, config string) error {
+ if err := checkBinary(bin, version); err != nil {
+ return err
+ }
+ bin, err := filepath.Abs(bin)
+ if err != nil {
+ return err
+ }
+ if config, err = filepath.Abs(config); err != nil {
+ return err
+ }
+ if err := selfTest(ctx, bin, config); err != nil {
+ return fmt.Errorf("self-test: %w", err)
+ }
+ return scanTracked(ctx, bin, config)
+}
+
+// checkBinary refuses anything but the pinned gitleaks. The version comes
+// from the build information, because a `go install` build prints a
+// placeholder for `gitleaks version`.
+func checkBinary(bin, version string) error {
+ if bin == "" || version == "" {
+ return errors.New("-gitleaks and -version are required")
+ }
+ info, err := buildinfo.ReadFile(bin)
+ if err != nil {
+ return fmt.Errorf("read the gitleaks binary: %w", err)
+ }
+ if info.Main.Path != gitleaksModule || info.Main.Version != version {
+ return fmt.Errorf("%s is %s %s, want %s %s", bin, info.Main.Path, info.Main.Version, gitleaksModule, version)
+ }
+ return nil
+}
+
+// scan runs gitleaks over dir and returns everything it reported. Any end
+// other than a finished scan with a report that agrees with its exit status
+// is an error.
+func scan(ctx context.Context, bin, config, dir string) ([]finding, error) {
+ reportDir, err := os.MkdirTemp("", "gitleaks-gate-report-")
+ if err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(reportDir)
+ report := filepath.Join(reportDir, "report.json")
+
+ // --ignore-gitleaks-allow: a `gitleaks:allow` comment would otherwise
+ // hide a finding on its line with no review of the value.
+ cmd := exec.CommandContext(ctx, bin, "dir",
+ "--no-banner", "--no-color", "--log-level", "error",
+ "--ignore-gitleaks-allow",
+ "--config", config,
+ "--report-format", "json", "--report-path", report,
+ "--exit-code", strconv.Itoa(exitFindings),
+ ".")
+ cmd.Dir = dir
+ var output bytes.Buffer
+ cmd.Stdout, cmd.Stderr = &output, &output
+ status := 0
+ if err := cmd.Run(); err != nil {
+ var exit *exec.ExitError
+ if !errors.As(err, &exit) {
+ return nil, fmt.Errorf("run gitleaks: %w", err)
+ }
+ status = exit.ExitCode()
+ }
+ if status != 0 && status != exitFindings {
+ return nil, fmt.Errorf("gitleaks exited %d: %s", status, strings.TrimSpace(output.String()))
+ }
+ data, err := os.ReadFile(report)
+ if err != nil {
+ return nil, fmt.Errorf("read the gitleaks report: %w", err)
+ }
+ var findings []finding
+ if err := json.Unmarshal(data, &findings); err != nil {
+ return nil, fmt.Errorf("parse the gitleaks report: %w", err)
+ }
+ if (status == exitFindings) != (len(findings) > 0) {
+ return nil, fmt.Errorf("gitleaks exited %d with %d findings in its report", status, len(findings))
+ }
+ return findings, nil
+}
+
+// scanTracked scans the tracked files of the repository in the current
+// directory and fails on every finding.
+func scanTracked(ctx context.Context, bin, config string) error {
+ tree, err := scanTree(ctx, bin, config, ".")
+ if err != nil {
+ return err
+ }
+ fmt.Printf("gitleaks: scanned %d tracked files; %d not scanned, by exact path (scripts/gitleaks-gate/notscanned.go)\n",
+ tree.scanned, tree.skipped)
+ if len(tree.standing) == 0 {
+ fmt.Println("gitleaks: clean")
+ return nil
+ }
+ for _, f := range tree.standing {
+ // Never the value: this goes to the CI log.
+ fmt.Printf("%s:%d: %s\n", f.File, f.StartLine, f.RuleID)
+ }
+ return fmt.Errorf("%d findings above: remove the value and rotate it if it was ever real; a fake a test needs is allowed by exact value in .gitleaks.toml", len(tree.standing))
+}
+
+// treeScan is what scanTree found in one repository.
+type treeScan struct {
+ scanned int // tracked files copied and scanned
+ skipped int // tracked files left out because notScanned names them
+ standing []finding // every finding but the planted sentinel, by file and line
+}
+
+// scanTree copies the tracked files of repo into a scratch directory, adds a
+// sentinel key beside them, scans the lot and returns every finding but the
+// sentinel's. A scan that does not report the sentinel is an error.
+//
+// The sentinel goes in a file whose name is random for each run and which is
+// created only if nothing is there, so it can never replace or hide a tracked
+// file: a tracked file of any name, gitleaks-gate-sentinel.env included, is
+// copied and scanned like the rest. Only the sentinel's own finding, its
+// exact value in its own file, is set aside.
+func scanTree(ctx context.Context, bin, config, repo string) (treeScan, error) {
+ dir, err := os.MkdirTemp("", "gitleaks-gate-tree-")
+ if err != nil {
+ return treeScan{}, err
+ }
+ defer os.RemoveAll(dir)
+
+ scanned, skipped, err := copyTracked(ctx, repo, dir)
+ if err != nil {
+ return treeScan{}, err
+ }
+ sentinel := newKey(40)
+ sentinelFile := "gitleaks-gate-sentinel-" + newKey(12) + ".env"
+ out, err := os.OpenFile(filepath.Join(dir, sentinelFile), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return treeScan{}, fmt.Errorf("plant the sentinel: %w", err)
+ }
+ _, err = fmt.Fprintf(out, "api_key = \"%s\"\n", sentinel)
+ if cerr := out.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return treeScan{}, fmt.Errorf("plant the sentinel: %w", err)
+ }
+
+ findings, err := scan(ctx, bin, config, dir)
+ if err != nil {
+ return treeScan{}, err
+ }
+ tree := treeScan{scanned: scanned, skipped: skipped}
+ sawSentinel := false
+ for _, f := range findings {
+ if f.File == sentinelFile && f.Secret == sentinel {
+ sawSentinel = true
+ continue
+ }
+ tree.standing = append(tree.standing, f)
+ }
+ if !sawSentinel {
+ return treeScan{}, errors.New("the scan did not report the key planted beside the tracked files")
+ }
+ sort.Slice(tree.standing, func(a, b int) bool {
+ if tree.standing[a].File != tree.standing[b].File {
+ return tree.standing[a].File < tree.standing[b].File
+ }
+ return tree.standing[a].StartLine < tree.standing[b].StartLine
+ })
+ return tree, nil
+}
+
+// copyTracked copies every tracked regular file of repo into dir, except the
+// ones notScanned names, and returns how many it copied and how many it left
+// out. It reads the list from the index and the bytes from the working tree,
+// so an uncommitted edit is scanned and an untracked file is not. git archive
+// would do the copying but honours export-ignore, which would let a tracked
+// .gitattributes take files out of the scan.
+//
+// Every notScanned entry has to be a tracked file: one that is not is an
+// error, so the list cannot keep a path that a new file could later take.
+func copyTracked(ctx context.Context, repo, dir string) (copied, skipped int, err error) {
+ cmd := exec.CommandContext(ctx, "git", "ls-files", "-z", "--stage")
+ cmd.Dir = repo
+ out, err := cmd.Output()
+ if err != nil {
+ return 0, 0, fmt.Errorf("list tracked files: %w", err)
+ }
+ excluded := map[string]bool{}
+ for _, path := range notScanned {
+ excluded[path] = false
+ }
+ seen := map[string]bool{}
+ for _, entry := range strings.Split(string(out), "\x00") {
+ meta, path, ok := strings.Cut(entry, "\t")
+ if !ok || seen[path] {
+ continue
+ }
+ seen[path] = true
+ if filepath.Base(path) == ".gitleaksignore" {
+ return 0, 0, fmt.Errorf("%s is tracked: findings are allowed in .gitleaks.toml, by value, and not by fingerprint", path)
+ }
+ // Symlinks (120000) and submodules (160000) have no content here.
+ if !strings.HasPrefix(meta, "100") {
+ continue
+ }
+ if _, listed := excluded[path]; listed {
+ excluded[path] = true
+ skipped++
+ continue
+ }
+ source := filepath.Join(repo, filepath.FromSlash(path))
+ info, err := os.Lstat(source)
+ if errors.Is(err, fs.ErrNotExist) {
+ continue // deleted in the working tree: nothing left to scan
+ }
+ if err != nil {
+ return 0, 0, err
+ }
+ if !info.Mode().IsRegular() {
+ continue
+ }
+ data, err := os.ReadFile(source)
+ if err != nil {
+ return 0, 0, err
+ }
+ target := filepath.Join(dir, filepath.FromSlash(path))
+ if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
+ return 0, 0, err
+ }
+ if err := os.WriteFile(target, data, 0o600); err != nil {
+ return 0, 0, err
+ }
+ copied++
+ }
+ for _, path := range notScanned {
+ if !excluded[path] {
+ return 0, 0, fmt.Errorf("notscanned.go names %s, which is not a tracked file: take it off the list", path)
+ }
+ }
+ if copied == 0 {
+ return 0, 0, errors.New("git lists no tracked files to scan")
+ }
+ return copied, skipped, nil
+}
+
+// newKey returns a random credential-shaped value of n characters. Its
+// alphabet leaves out vowels and the letters of gitleaks' short stopwords
+// (http, sync, vpn and the like), any of which would make the generic rule
+// wave the value through and the test prove nothing.
+func newKey(n int) string {
+ const letters = "BCDFGJKLNPRSTZbcdfgjklnprstz"
+ const digits = "2346789"
+ alphabet := letters + digits
+ raw := make([]byte, n)
+ if _, err := rand.Read(raw); err != nil {
+ panic(err)
+ }
+ key := make([]byte, n)
+ for i, b := range raw {
+ // A value of letters alone is also waved through, so every
+ // fourth character is a digit.
+ if i%4 == 3 {
+ key[i] = digits[int(b)%len(digits)]
+ } else {
+ key[i] = alphabet[int(b)%len(alphabet)]
+ }
+ }
+ return string(key)
+}
+
+// newDigest returns 64 random lowercase hex characters that gitleaks' generic
+// rule will report: no stopword inside it, and enough entropy.
+func newDigest() string {
+ for {
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ panic(err)
+ }
+ digest := hex.EncodeToString(raw)
+ if strings.Contains(digest, "dead") || strings.Contains(digest, "feed") ||
+ strings.Contains(digest, "000000") || strings.Contains(digest, "aaaaaa") {
+ continue
+ }
+ if entropy(digest) > 3.6 {
+ return digest
+ }
+ }
+}
+
+// entropy is the Shannon entropy gitleaks' generic rule requires above 3.5.
+func entropy(s string) float64 {
+ counts := map[rune]int{}
+ for _, r := range s {
+ counts[r]++
+ }
+ total := 0.0
+ for _, n := range counts {
+ p := float64(n) / float64(len(s))
+ total -= p * math.Log2(p)
+ }
+ return total
+}
diff --git a/scripts/gitleaks-gate/notscanned.go b/scripts/gitleaks-gate/notscanned.go
new file mode 100644
index 000000000..889e92e5a
--- /dev/null
+++ b/scripts/gitleaks-gate/notscanned.go
@@ -0,0 +1,49 @@
+package main
+
+// notScanned names the tracked files the gate does not scan at all. Nothing
+// in them is read by gitleaks, so a credential committed in one of them is
+// NOT found.
+//
+// They hold sha256 digests of source, not secrets: the census test files pin
+// a digest per unit, and the design checklist pins a digest per file in its
+// source_hashes. gitleaks' generic rule reads a digest after a key-like word
+// as a key, and no allowance can tell a digest from a 64-character hex key,
+// so these files are left out whole, by name, rather than judged by shape.
+//
+// Each entry is a whole repository path, compared for equality: no globs, no
+// directory prefixes, no patterns. A file renamed away from its entry is
+// scanned under its new name, and the gate fails while an entry names a path
+// that git does not track, so a stale entry cannot later cover a new file.
+//
+// The list holds only the files gitleaks flags. A census file not listed here
+// is scanned like any other; if a new census layer turns the step red with
+// digest findings, check that every finding is a digest, then add the file's
+// exact path below.
+var notScanned = []string{
+ "implementation/always-awake-consumers.json",
+ "internal/provision/agent_start_demo_3_census_test.go",
+ "internal/provision/claim_empty_cohort_fix1_census_test.go",
+ "internal/provision/console_remote_instances_census_test.go",
+ "internal/provision/demo_census_test.go",
+ "internal/provision/edge_asset_cache_1_census_test.go",
+ "internal/provision/fleet_public_routes_census_test.go",
+ "internal/provision/instance_egress_sizes_census_test.go",
+ "internal/provision/instance_restore_658_census_test.go",
+ "internal/provision/linked_deployments_slice1_census_test.go",
+ "internal/provision/nearest_region_a_census_test.go",
+ "internal/provision/nearest_region_b_census_test.go",
+ "internal/provision/operator_pages_census_test.go",
+ "internal/provision/plan14_e_write_census_test.go",
+ "internal/provision/plan14_p3_census_test.go",
+ "internal/provision/plan9_b8_census_test.go",
+ "internal/provision/platform_mail_submission_census_test.go",
+ "internal/provision/region_ha_g2_fixes_census_test.go",
+ "internal/provision/regional_domains_447_census_test.go",
+ "internal/provision/retire_app_lock_407_census_test.go",
+ "internal/provision/retire_window_415_census_test.go",
+ "internal/provision/rootfs_apps_4_census_test.go",
+ "internal/provision/self_serve_moves1_census_test.go",
+ "internal/provision/stateless_placement_census_test.go",
+ "internal/provision/stateless_replicas_4_drill1_census_test.go",
+ "internal/provision/team_scoped_credentials_census_test.go",
+}
diff --git a/scripts/gitleaks-gate/selftest.go b/scripts/gitleaks-gate/selftest.go
new file mode 100644
index 000000000..311af191c
--- /dev/null
+++ b/scripts/gitleaks-gate/selftest.go
@@ -0,0 +1,295 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+)
+
+// The self-test runs inside the gitleaks step because it needs the binary.
+// It plants keys generated at run time, so none is ever committed.
+//
+// Each single-file case is scanned twice:
+//
+// - with gitleaks' default rules alone, the control: the planted value has
+// to be found there, or the case proves nothing;
+// - with the real config: the planted key must still be reported.
+//
+// Then a whole repository is built and put through scanTree, the path the
+// real scan takes, to prove what is and is not scanned (trackedTest).
+const ordinaryFile = "internal/widgets/pump.go"
+
+// selfCase is one file to scan and the value that must be reported on line.
+type selfCase struct {
+ name string
+ file string
+ body string
+ line int
+ secret string
+}
+
+func selfTest(ctx context.Context, bin, config string) error {
+ cases := selfCases()
+
+ control, err := os.MkdirTemp("", "gitleaks-gate-control-")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(control)
+ defaults := filepath.Join(control, "defaults.toml")
+ if err := os.WriteFile(defaults, []byte("[extend]\nuseDefault = true\n"), 0o600); err != nil {
+ return err
+ }
+
+ results := make([]error, len(cases))
+ slots := make(chan struct{}, 4)
+ var wg sync.WaitGroup
+ for i, c := range cases {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ slots <- struct{}{}
+ defer func() { <-slots }()
+ results[i] = c.run(ctx, bin, defaults, config)
+ }()
+ }
+ wg.Wait()
+
+ var failed []error
+ planted := 0
+ for i, c := range cases {
+ verdict := "reported"
+ if results[i] != nil {
+ failed = append(failed, fmt.Errorf("%s: %w", c.name, results[i]))
+ verdict = "FAILED"
+ } else {
+ planted++
+ }
+ fmt.Printf("self-test: %-8s %s\n", verdict, c.name)
+ }
+ tracked, err := trackedTest(ctx, bin, config, control)
+ if err != nil {
+ failed = append(failed, fmt.Errorf("tracked files: %w", err))
+ }
+ closed, err := failClosed(ctx, bin, config, control)
+ if err != nil {
+ failed = append(failed, err)
+ }
+ if len(failed) > 0 {
+ return errors.Join(failed...)
+ }
+ fmt.Printf("self-test: %d planted keys reported, %d tracked files judged, %d broken setups refused\n",
+ planted, tracked, closed)
+ return nil
+}
+
+func (c selfCase) run(ctx context.Context, bin, defaults, config string) error {
+ dir, err := os.MkdirTemp("", "gitleaks-gate-case-")
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(dir)
+ path := filepath.Join(dir, filepath.FromSlash(c.file))
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return err
+ }
+ if err := os.WriteFile(path, []byte(c.body), 0o600); err != nil {
+ return err
+ }
+
+ found, err := scan(ctx, bin, defaults, dir)
+ if err != nil {
+ return fmt.Errorf("control scan: %w", err)
+ }
+ if !c.reported(found) {
+ return fmt.Errorf("the default rules do not flag line %d, so this case proves nothing", c.line)
+ }
+ if found, err = scan(ctx, bin, config, dir); err != nil {
+ return err
+ }
+ if !c.reported(found) {
+ return errors.New("THE PLANTED KEY WAS HIDDEN")
+ }
+ return nil
+}
+
+// reported says whether findings include this case's value on its line.
+func (c selfCase) reported(findings []finding) bool {
+ for _, f := range findings {
+ if f.File == c.file && f.StartLine == c.line && strings.Contains(f.Secret, c.secret) {
+ return true
+ }
+ }
+ return false
+}
+
+// trackedTest builds a git repository and scans it with scanTree, as the
+// real scan does, to prove three things:
+//
+// - a tracked file named gitleaks-gate-sentinel.env, the sentinel's old
+// fixed name, is scanned and its key reported: the sentinel cannot
+// replace or hide a tracked file;
+// - every file notScanned names is left out, and nothing else: the same
+// key under a near miss of each name (another directory above it, a
+// suffix, a prefix on the file name) is reported, as is one in a census
+// file the list does not name;
+// - a list entry that git does not track is refused.
+//
+// It returns how many tracked files it judged.
+func trackedTest(ctx context.Context, bin, config, scratch string) (int, error) {
+ repo := filepath.Join(scratch, "repo")
+ if err := os.MkdirAll(repo, 0o700); err != nil {
+ return 0, err
+ }
+ want := map[string]string{} // file: the key that must be reported in it
+ hidden := map[string]bool{} // files whose key must not be reported
+ plant := func(file string) (string, error) {
+ key := newKey(40)
+ target := filepath.Join(repo, filepath.FromSlash(file))
+ if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
+ return "", err
+ }
+ return key, os.WriteFile(target, []byte("api_key = \""+key+"\"\n"), 0o600)
+ }
+ expect := func(file string) error {
+ key, err := plant(file)
+ want[file] = key
+ return err
+ }
+
+ if err := expect("gitleaks-gate-sentinel.env"); err != nil {
+ return 0, err
+ }
+ if err := expect("internal/provision/zz_planted_census_test.go"); err != nil {
+ return 0, err
+ }
+ for _, p := range notScanned {
+ if _, err := plant(p); err != nil {
+ return 0, err
+ }
+ hidden[p] = true
+ dir, base := path.Split(p)
+ for _, near := range []string{"x/" + p, p + ".orig", dir + "zz_" + base} {
+ if err := expect(near); err != nil {
+ return 0, err
+ }
+ }
+ }
+ if err := git(ctx, repo, "init", "-q"); err != nil {
+ return 0, err
+ }
+ if err := git(ctx, repo, "add", "-A"); err != nil {
+ return 0, err
+ }
+
+ tree, err := scanTree(ctx, bin, config, repo)
+ if err != nil {
+ return 0, err
+ }
+ if tree.skipped != len(notScanned) {
+ return 0, fmt.Errorf("%d files left out, want the %d notscanned.go names", tree.skipped, len(notScanned))
+ }
+ got := map[string]bool{}
+ for _, f := range tree.standing {
+ switch {
+ case hidden[f.File]:
+ return 0, fmt.Errorf("%s is listed in notscanned.go but was scanned", f.File)
+ case want[f.File] == "" || f.Secret != want[f.File] || f.StartLine != 1:
+ return 0, fmt.Errorf("unexpected finding at %s:%d", f.File, f.StartLine)
+ }
+ got[f.File] = true
+ }
+ var missed []string
+ for file := range want {
+ if !got[file] {
+ missed = append(missed, file)
+ }
+ }
+ sort.Strings(missed)
+ if len(missed) > 0 {
+ return 0, fmt.Errorf("THE PLANTED KEY WAS HIDDEN in %s", strings.Join(missed, ", "))
+ }
+ fmt.Printf("self-test: %-8s a tracked file named gitleaks-gate-sentinel.env\n", "reported")
+ fmt.Printf("self-test: %-8s %d near misses of the names notscanned.go lists\n", "reported", len(want)-1)
+ fmt.Printf("self-test: %-8s the %d files notscanned.go lists\n", "skipped", len(hidden))
+
+ // Untrack one listed file: the list now names a path git does not
+ // track, which must be refused.
+ if err := git(ctx, repo, "rm", "-q", "--cached", notScanned[0]); err != nil {
+ return 0, err
+ }
+ if _, _, err := copyTracked(ctx, repo, filepath.Join(scratch, "stale")); err == nil {
+ return 0, fmt.Errorf("a notscanned.go entry git does not track (%s) was not refused", notScanned[0])
+ }
+ fmt.Printf("self-test: %-8s a notscanned.go entry git does not track\n", "refused")
+ return len(want) + len(hidden), nil
+}
+
+// git runs git in repo with no inherited repository settings, so it can
+// only act on repo.
+func git(ctx context.Context, repo string, args ...string) error {
+ cmd := exec.CommandContext(ctx, "git", args...)
+ cmd.Dir = repo
+ for _, kv := range os.Environ() {
+ if !strings.HasPrefix(kv, "GIT_") {
+ cmd.Env = append(cmd.Env, kv)
+ }
+ }
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// failClosed checks that a setup that cannot scan is an error, never a pass.
+func failClosed(ctx context.Context, bin, config, scratch string) (int, error) {
+ dir := filepath.Join(scratch, "tree")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ return 0, err
+ }
+ broken := filepath.Join(scratch, "broken.toml")
+ if err := os.WriteFile(broken, []byte("[[allowlists]\nregexes = ["), 0o600); err != nil {
+ return 0, err
+ }
+ setups := []struct{ name, bin, config string }{
+ {"a config that does not parse", bin, broken},
+ {"a config that does not exist", bin, filepath.Join(scratch, "missing.toml")},
+ {"a missing gitleaks binary", filepath.Join(scratch, "missing-gitleaks"), config},
+ }
+ for _, s := range setups {
+ if _, err := scan(ctx, s.bin, s.config, dir); err == nil {
+ return 0, fmt.Errorf("%s did not fail the scan", s.name)
+ }
+ fmt.Printf("self-test: %-8s %s\n", "refused", s.name)
+ }
+ if err := checkBinary(filepath.Join(scratch, "missing-gitleaks"), "v0.0.0"); err == nil {
+ return 0, errors.New("a missing gitleaks binary passed the version check")
+ }
+ return len(setups), nil
+}
+
+func selfCases() []selfCase {
+ key, digest := newKey(40), newDigest()
+ ordinary := func(name, line, secret string) selfCase {
+ body := "package widgets\n\n" + line + "\n"
+ return selfCase{name: name, file: ordinaryFile, body: body, line: 3, secret: secret}
+ }
+ return []selfCase{
+ ordinary("source file: a key", `const apiKey = "`+key+`"`, key),
+ ordinary("source file: a 64-hex key", `const signingSecret = "`+digest+`"`, digest),
+ ordinary("source file: a census-shaped entry", `{"internal/console/auth.go", "Pump.Start", "nonrecord", "key:RecordKey", "`+digest+`"},`, digest),
+ ordinary("source file: a key marked gitleaks:allow", `const apiKey = "`+key+`" // gitleaks:allow`, key),
+ ordinary("source file: a test's fake value outside tests", `const token = "tok-`+`flagship-2"`, "tok-"+"flagship-2"),
+ {
+ name: "allowed file: another key beside its allowed value", file: "internal/console/testdata/configseal_vectors.json",
+ body: "{\n \"note\": \"vectors\",\n \"api_key\": \"" + key + "\"\n}\n", line: 3, secret: key,
+ },
+ }
+}