carlos / platform Public

plan: edge protection Plan 2, hard and probe tiers in watch mode

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4b4933eaee0a973611c8ef181b2bc4eff7927631 parent 542ad2c
2 files changed, +473 −0
  • docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md +62 −0
  • docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md +411 −0

CI passed — run details

diff --git a/docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md b/docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md
new file mode 100644
index 000000000..71304a74a
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md
@@ -0,0 +1,62 @@
+# Edge protection Plan 2: copy record
+
+Every user-facing string that edge protection Plan 2 writes
+(`2026-10-25-edge-protection-2-hard-probe-watch.md`): the block page, the
+`carlos explain` lines and the CLI docs. The gate is
+`approved_edge_protect_copy_test.go` at the repo root. It reuses the moves
+gate's parser, so the format is the moves record's: one table per heading,
+with columns id, file, text and status.
+
+The rules:
+
+- A row is `pending` until Paul approves it in the copy review (the
+ `copy-review` skill). His edits are applied to the text here verbatim,
+ and the row becomes `approved`.
+- Pending CLI and edge text may be wired into code while the branch is
+ being built (`edgeProtectCopyWired`). The branch does not merge until
+ every row is approved and built. Docs rows are never wired: they are
+ written only once approved.
+- In a Go file the text is one string literal, or one `fmt.Sprintf` or
+ `fmt.Fprintf` format. It equals the row, with a format verb where the
+ row has a `<placeholder>`. No trailing newline goes inside the literal.
+- A table cell holds one line, so a row writes a line break as `\n`.
+- No em dashes. Use a full stop and a new sentence instead, continuing in
+ lower case. CLI lines are lower case. The block page and the docs use
+ sentence case.
+
+Placeholders:
+
+- `<code>`: a 40-character reference code.
+- `<time>`: `2006-01-02 15:04 UTC`.
+- `<tier>`: `hard` or `probe`.
+- `<rule>`: a rule id such as `hard.secrets.env`.
+- `<hash>`: 8 hex digits.
+- `<method>`, `<path>`, `<host>` and `<status>`: as the record stores them.
+
+## The block page
+
+| id | file | text | status |
+|---|---|---|---|
+| EP-1 | internal/edge/guard.go | Not found.\n\nIf you expected a page here, send this reference to the site's owner: <code> | pending |
+
+## `carlos explain`
+
+| id | file | text | status |
+|---|---|---|---|
+| EP-2 | explain_cmd.go | usage: carlos explain <code> --app <a> [flags]\n\nWhat a reference code from a page the edge answered says: which protection rule fired, when, and the request it answered, while a record of it is kept. --json prints the console's answer as it is. | pending |
+| EP-4 | explain_cmd.go | checked yes. this deployment sealed the code | pending |
+| EP-5 | explain_cmd.go | checked no. the console has no key to check the seal with, so treat the rest as unchecked | pending |
+| EP-6 | explain_cmd.go | checked no. the code is not sealed, so anyone could have written it. treat the rest as unchecked | pending |
+| EP-7 | explain_cmd.go | rule not in this console's catalogue (hash <hash>) | pending |
+| EP-8 | explain_cmd.go | reference <code>\nwhen <time>\ntier <tier> | pending |
+| EP-9 | explain_cmd.go | request <method> <path> on <host>, answered <status> | pending |
+| EP-10 | explain_cmd.go | request not kept. it was sampled away, or is older than 7 days | pending |
+| EP-11 | explain_cmd.go | request the records could not be read just now. try again in a minute | pending |
+| EP-12 | explain_cmd.go | no reference code like that for this app. check the code, and that it came from one of this app's pages | pending |
+| EP-13 | explain_cmd.go | rule <rule> | pending |
+
+## Docs
+
+| id | file | text | status |
+|---|---|---|---|
+| EP-3 | docs/site/cli.md | `carlos explain <code> --app <a>` reads a reference code from a page the platform's edge protection answered. It says which rule fired and when, and shows the request while a record of it is kept, for 7 days. | pending |
diff --git a/docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md b/docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md
new file mode 100644
index 000000000..7508af4f0
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-25-edge-protection-2-hard-probe-watch.md
@@ -0,0 +1,411 @@
+# Edge protection Plan 2: hard and probe tiers in watch mode
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Every app gets the hard tier and the probe catalogue, matched on path structure before the cache and the activator. Every match is recorded as a watch with the app's real answer. Block mode exists and is tested, but it is off fleet-wide. The console and a new CLI verb explain a reference code by rule name.
+
+**Architecture:** A new package `internal/edgeguard` holds the catalogue (an embedded, versioned data file) and a matcher that does no allocation on ordinary paths. The edge runs it once per request in `ServeHTTP`, in front of the password gate. It leaves the verdict on the request's `outcome`, and the observer defer files one `reqrec.Match` with the real status instead of a `reqrec.Response`. On a local static site, the static handler decides probe matches itself, because it knows exactly which files exist. It also re-checks a rewritten file against the hard tier. Block mode answers `404` with a sealed reference code. The console maps a code's rule hash back to the catalogue's rule id, and `carlos explain <code>` prints it.
+
+**Tech Stack:** Go 1.26 (`go:embed`, `net/http`), the existing `internal/reqrec` (Plan 1), `internal/edge`, `internal/console`, the root CLI (package `main`).
+
+**Spec:** `docs/superpowers/specs/2026-10-24-edge-request-protection-design.md` (approved 2026-10-24). This plan is §8 step 2. Plan 1 (`docs/superpowers/plans/2026-10-24-edge-protection-1-request-records.md`, merged 6e2d9817) built the records and codes this plan uses.
+
+## Rulings made writing this plan
+
+These are the planner's calls. Each says what it costs if wrong.
+
+- **R1. Everything watches in this plan.** Spec §5.1 says the hard tier blocks by default. Spec §8 step 2 says the hard and probe tiers run in watch mode fleet-wide for the calibration window. §8 is the rollout order, so it wins. Every catalogue entry ships in mode `watch`. Promotion to `block`, the hard override, the deploy-time warning, the technology switch, learned exemptions and the probe-burst limit (§5.5) are Plan 3. All of them only matter once something blocks. If wrong: leaks stay served for the 14-day window, as they are today.
+- **R2. A box-level mode switch, `CARLOS_EDGE_PROTECT`.** Values: unset (each rule's catalogue mode), `off` (no checks), `watch` (every rule watches), `block` (every rule blocks, except `burst` rules). `block` exists so dev boxes can exercise the block page, the codes and `carlos explain` end to end. It must not be set on the flagship in this plan. It is read once when the edge is built, as `CARLOS_EDGE_GZIP` is. If wrong: one env var to remove.
+- **R3. Some of the spec's hard-tier extensions go in the probe tier.** The spec lists `.sql`, `.sql.gz`, `.sqlite` and `.db` dumps by extension as hard, and gives the rule "a hard entry must be something no deployed app should ever serve" (§5.2). Static sites do serve `.sqlite` and `.db` files to the browser on purpose (sql.js and its HTTP VFS), and `.sql` schema downloads are plausible. So they are probe entries, which are served when the file exists. The well-known root dump names (`/db.sql`, `/dump.sql`, `/backup.sql`, `/database.sql`) stay hard. `*.bak` goes in the probe tier. `*.old` is left out. If wrong: Plan 3's review promotes them.
+- **R4. Admin panels are mode `burst`.** They are matched and watched, so calibration sees them and Plan 3's burst limit can use them. No mode, forced or not, ever blocks them (spec §5.3).
+- **R5. Where the check runs.**
+ - Skipped for requests that arrived through a tunnel (`fromTunnel`): the hub that forwarded them already checked them and records them. This matches Plan 1's `observeRecords`.
+ - Run on hopped requests (the sending edge had no route, so it checked nothing).
+ - Skipped for door callers (`isDoor`): those are the app's own code, not public traffic.
+ - Skipped for `Kind == "status"` routes, which get no outcome.
+ - On a hub, a static site served over a tunnel is checked as an app whose routes are unknown. The hub cannot see the far box's files. If wrong: such a site's watch records over-report probe matches until Plan 3 decides.
+- **R6. One verdict per request, first one wins.** The `ServeHTTP` check runs first. The static handler adds a verdict only if there is none yet. This carries out Plan 1's handoff: "never call Response and Match for one request".
+- **R7. Watch records carry no reference code.** Codes are for pages a visitor sees. Only blocks mint one.
+- **R8. Lookups of codes are already rate-limited.** The instance gate in front of `GET …/edge-refs/{code}` spends `s.cli.instances` (60 a minute per token, `internal/console/apiinstances.go:96`). No new limiter. The Plan 1 handoff asked for "lookups rate-limited", and this is it. Unverified codes are shown as unchecked by the CLI (Task 5).
+- **R9. Add `CARLOS_EDGE_PROTECT` and `CARLOS_EDGE_RECORDS` to `hostenv.Optional`.** That way a group box takes them from the parameter store like `CARLOS_EDGE_GZIP`. Plan 1 left `CARLOS_EDGE_RECORDS` out.
+- **R10. The calibration report is Plan 3's.** The records this plan writes are its input. Plan 3 also has to write the report, review it and promote.
+- **R11. The two §9 requests are filed with this plan.** One asks the framework for route lists in the release manifest. The other asks #366 for the rootfs image's file list. The probe tier's existence for framework and rootfs apps waits on both, and Plan 3's blocking of unknown apps should not start before the answers are known. Task 6 files them.
+
+## Global Constraints
+
+- Rules match path structure, never a word inside a path: exact path, prefix on segment boundaries, whole segment, final-segment extension, segment sequence, or one named query parameter's value prefix (spec §4 anti-goals, §5.3).
+- Matching is case-insensitive, on the decoded path with `\` treated as `/`, and on one further percent-decoding when the decoded path still holds a `%` (spec §5.2).
+- `/.well-known/` is exempt from every rule except traversal (spec §5.2).
+- Hard and probe checks run before the password gate, the upgrade branch, the cache and the activator, so a check never waits on a wake (spec §5.3, `internal/edge/edge.go` around the gate).
+- A watched request is forwarded unchanged. Its record carries the upstream status and whether it woke the app (spec §7, "Calibration needs more").
+- Hard and probe blocks answer `404`, `Content-Type: text/plain; charset=utf-8`, `Cache-Control: no-store`, the code in the `X-Carlos-Ref` header and in the body (spec §5.1).
+- No storage write per request. Records go through `reqrec.Recorder` only (spec §7).
+- Provider-neutral: nothing here touches AWS or a plan catalog.
+- User-facing words are pending until copy review. Their text lives in `docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md` and is used verbatim. No em dashes in any copy (house rule). Platform docs use neutral names (`shop`, `example.com`), never tenant names.
+- Local test runs cover only the touched packages, with `-run` (house rule). CI runs everything. Cross-compiles for darwin and windows must still build (nothing here is Linux-only).
+
+## Review Focus
+
+1. **Case and encoding tricks:** `/.ENV`, `/.Git/config`, `/%2eenv` (a decoded path still holding `%2e` came from `%252e`), `/static/..%5c.env` and `/x/..;/.env`. All must match the hard tier. Test in Task 1 (`TestCheckEncodingTricks`).
+2. **Real paths that look close:** `/wp-content/uploads/…png`, `/assets/admin/app-3f2a.js`, `PMA_FULL_LOGO.png`, `photo..jpg`, `.envoy`, `/index.php-guide`. None may match. Test in Task 1 (`TestCheckMisfireCorpus`).
+3. **A 1 MiB path:** must complete in linear time with a bounded number of allocations, and still match a `.env` segment at its far end. Test in Task 1 (`TestCheckLongPath`).
+4. **A static site with a single-page splat** (`/* /index.html 200`) asked for `/wp-login.php`: still a probe match, because a splat is not existence. Test in Task 3 (`TestStaticSplatIsNotExistence`).
+5. **A watched probe the app answers 200, on a hibernating instance:** the record says `status=200`, `woke=1`, kind `watch` and no `ref`, and there is exactly one record for the request. Test in Task 2 (`TestGuardWatchRecordsUpstreamStatus`).
+
+---
+
+### Task 1: The catalogue and its matcher (`internal/edgeguard`)
+
+**Files:**
+- Create: `internal/edgeguard/catalogue.txt` (embedded data)
+- Create: `internal/edgeguard/catalogue.go` (parse, `Rule`, `Mode`, lookup)
+- Create: `internal/edgeguard/match.go` (`Check`)
+- Test: `internal/edgeguard/catalogue_test.go`, `internal/edgeguard/match_test.go`
+
+**Interfaces:**
+- Consumes: `reqrec.Tier` (`TierHard`, `TierProbe`), `reqrec.RuleHash(string) uint32`.
+- Produces:
+ - `type Mode uint8` with `ModeWatch`, `ModeBlock`, `ModeBurst`, and `func (m Mode) String() string` returning `"watch" | "block" | "burst"`.
+ - `type Rule struct { ID, Group string; Tier reqrec.Tier; Mode Mode }`. ID is `<tier>.<group>.<name>`, for example `hard.secrets.env`.
+ - `type Hit struct { Rule *Rule; Fragment string; FromQuery bool; QueryName string }`. Fragment is the raw matched text: a segment, a path, or a query value.
+ - `func Check(path, rawQuery string) (Hit, bool)`. `path` is `r.URL.Path` (already decoded once). Hard rules are tried before probe rules, and each tier in file order.
+ - `func CheckTier(path, rawQuery string, tier reqrec.Tier) (Hit, bool)`: the same, limited to one tier (Task 3 uses it).
+ - `func RuleByHash(h uint32) (*Rule, bool)` and `func Rules() []Rule`.
+ - `const Version` is the catalogue's `# version N` line, parsed. Plan 2 ships version 1.
+
+- [ ] **Step 1: Write the catalogue file.** Format: one rule per line, `#` comments, blank lines ignored, whitespace-separated columns `tier group name kind pattern mode`. `tier` is `hard` or `probe`. `group` and `name` match `[a-z0-9-]+`. Patterns are lower case. `kind` is one of:
+ - `exact`: the cleaned path equals the pattern.
+ - `prefix`: the cleaned path equals the pattern, or starts with the pattern followed by `/`.
+ - `segment`: some segment equals the pattern.
+ - `segglob`: some segment matches a pattern holding one `*`.
+ - `ext`: the final segment is longer than the pattern and ends with it.
+ - `segseq`: the pattern's segments appear consecutively.
+ - `qparam`: the pattern is `name=valueprefix`. A value of that query parameter, lower-cased, starts with `valueprefix`.
+ - `dotdot`: the pattern is `-`. Some segment is `..`, before cleaning.
+
+ The first line is `# version 1`. Contents, in this order:
+
+```
+# version 1
+# tier group name kind pattern mode
+hard traversal dotdot dotdot - watch
+hard traversal proc-self segseq proc/self watch
+hard traversal vite-fs segment @fs watch
+hard secrets env segment .env watch
+hard secrets env-variant segglob .env.* watch
+hard secrets git segment .git watch
+hard secrets git-credentials segment .git-credentials watch
+hard secrets svn segment .svn watch
+hard secrets hg segment .hg watch
+hard secrets aws segment .aws watch
+hard secrets ssh segment .ssh watch
+hard secrets docker segment .docker watch
+hard secrets kube segment .kube watch
+hard secrets npmrc segment .npmrc watch
+hard secrets pypirc segment .pypirc watch
+hard secrets netrc segment .netrc watch
+hard secrets htpasswd segment .htpasswd watch
+hard keys id-rsa segment id_rsa watch
+hard keys id-dsa segment id_dsa watch
+hard keys id-ecdsa segment id_ecdsa watch
+hard keys id-ed25519 segment id_ed25519 watch
+hard keys credentials-json segment credentials.json watch
+hard keys gcp-credentials segment gcp-credentials.json watch
+hard keys firebase-admin segglob firebase-adminsdk*.json watch
+hard dumps db-sql exact /db.sql watch
+hard dumps dump-sql exact /dump.sql watch
+hard dumps backup-sql exact /backup.sql watch
+hard dumps database-sql exact /database.sql watch
+hard source php-save ext .php.save watch
+hard source php-bak ext .php.bak watch
+hard source php-old ext .php.old watch
+hard source php-swp ext .php.swp watch
+hard source php-tilde ext .php~ watch
+probe wordpress wp-login exact /wp-login.php watch
+probe wordpress xmlrpc exact /xmlrpc.php watch
+probe wordpress wp-links-opml exact /wp-links-opml.php watch
+probe wordpress wp-admin prefix /wp-admin watch
+probe wordpress wp-json prefix /wp-json watch
+probe wordpress site-wp-json prefix /site/wp-json watch
+probe wordpress news-wp-json prefix /news/wp-json watch
+probe wordpress cms-wp-json prefix /cms/wp-json watch
+probe wordpress blog-wp-json prefix /blog/wp-json watch
+probe wordpress wp-wp-json prefix /wp/wp-json watch
+probe wordpress wordpress-dir prefix /wordpress watch
+probe wordpress press-wp-json prefix /press/wp-json watch
+probe phpframework phpunit prefix /vendor/phpunit watch
+probe phpframework composer-json exact /vendor/composer/installed.json watch
+probe phpframework ignition prefix /_ignition watch
+probe phpframework telescope prefix /telescope watch
+probe phpframework debugbar prefix /_debugbar watch
+probe phpframework profiler-phpinfo prefix /_profiler/phpinfo watch
+probe phpframework thinkphp qparam s=/index/\think watch
+probe phpmyadmin phpmyadmin prefix /phpmyadmin watch
+probe phpmyadmin pma prefix /pma watch
+probe php php ext .php watch
+probe java actuator prefix /actuator watch
+probe java action ext .action watch
+probe java do ext .do watch
+probe java jsp ext .jsp watch
+probe cgi cgi-bin prefix /cgi-bin watch
+probe cgi setup-cgi exact /setup.cgi watch
+probe cgi hnap1 exact /hnap1 watch
+probe cgi gponform prefix /gponform watch
+probe status server-status prefix /server-status watch
+probe status server-info prefix /server-info watch
+probe metadata meta-data prefix /latest/meta-data watch
+probe devconfig docker-compose exact /docker-compose.yml watch
+probe devconfig dockerfile exact /dockerfile watch
+probe devconfig gitlab-ci exact /.gitlab-ci.yml watch
+probe dumps sql ext .sql watch
+probe dumps sql-gz ext .sql.gz watch
+probe dumps sqlite ext .sqlite watch
+probe dumps sqlite3 ext .sqlite3 watch
+probe dumps db ext .db watch
+probe dumps bak ext .bak watch
+probe admin admin exact /admin burst
+probe admin admin-login exact /admin/login burst
+probe admin admin-settings exact /admin/settings burst
+probe admin admin-dashboard exact /admin/dashboard burst
+probe admin administrator prefix /administrator burst
+```
+
+- [ ] **Step 2: Write the failing catalogue tests** in `catalogue_test.go`:
+ - `TestCatalogueParses`: `Rules()` is non-empty, `Version == 1`, every ID is unique and has the form `tier.group.name`, and the hard rules all come before the probe rules.
+ - `TestCatalogueRuleHashesUnique`: no two IDs share `reqrec.RuleHash`. For every rule, `RuleByHash(reqrec.RuleHash(r.ID))` returns that rule.
+ - `TestCatalogueAdminIsBurst`: every rule in group `admin` has `ModeBurst`, and no other rule does.
+ - `TestParseRejects`: the unexported parser (`parseCatalogue([]byte) ([]Rule, int, error)`) refuses an upper-case pattern, an unknown kind, an unknown mode, a duplicate ID, a `segglob` with zero or two `*`, a `qparam` without `=`, and a missing version line. Each refusal names the line number.
+
+- [ ] **Step 3: Write the failing match tests** in `match_test.go`. Table-driven, each case `{path, rawQuery, wantID}`, with `""` meaning no match:
+ - `TestCheckHardTier`: `/.env`→`hard.secrets.env`, `/.env.local`, `/.env.production` and `/backend/.env`→env or env-variant (assert the exact ID per row: `/.env.local`→`hard.secrets.env-variant`), `/.git/config` and `/.git/HEAD`→`hard.secrets.git`, `/.git-credentials`→`hard.secrets.git-credentials`, `/.aws/credentials`→`hard.secrets.aws`, `/.docker/config.json`→`hard.secrets.docker`, `/credentials.json`→`hard.keys.credentials-json`, `/gcp-credentials.json`→`hard.keys.gcp-credentials`, `/firebase-adminsdk.json` and `/firebase-adminsdk-x1y2.json`→`hard.keys.firebase-admin`, `/@fs/.env`→`hard.traversal.vite-fs` (file order puts traversal first), `/@fs/proc/self/environ`→`hard.traversal.vite-fs`, `/x/proc/self/environ`→`hard.traversal.proc-self`, `/static/../.env`→`hard.traversal.dotdot`, `/db.sql`→`hard.dumps.db-sql`, `/index.php.save`→`hard.source.php-save`, `/home/.ssh/id_rsa`→`hard.secrets.ssh`, `/id_ed25519`→`hard.keys.id-ed25519`.
+ - `TestCheckProbeTier`: `/wp-login.php`→`probe.wordpress.wp-login`, `/xmlrpc.php`→`probe.wordpress.xmlrpc`, `/blog/wp-json/wp/v2/users`→`probe.wordpress.blog-wp-json`, `/wp-admin/install.php`→`probe.wordpress.wp-admin`, `/info.php`→`probe.php.php`, `/_profiler/phpinfo`→`probe.phpframework.profiler-phpinfo`, `/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php`→`probe.phpframework.phpunit`, `/_ignition/execute-solution`→`probe.phpframework.ignition`, `/vendor/composer/installed.json`→`probe.phpframework.composer-json`, `("/", "s=/index/\\think\\app/invokefunction")`→`probe.phpframework.thinkphp`, `/phpmyadmin/index.php`→`probe.phpmyadmin.phpmyadmin`, `/pma/`→`probe.phpmyadmin.pma`, `/actuator/env`→`probe.java.actuator`, `/login.action`→`probe.java.action`, `/index.jsp`→`probe.java.jsp`, `/cgi-bin/luci`→`probe.cgi.cgi-bin`, `/HNAP1`→`probe.cgi.hnap1`, `/GponForm/diag_Form`→`probe.cgi.gponform`, `/server-status`→`probe.status.server-status`, `/latest/meta-data/iam/`→`probe.metadata.meta-data`, `/Dockerfile`→`probe.devconfig.dockerfile`, `/.gitlab-ci.yml`→`probe.devconfig.gitlab-ci`, `/backup/site.sql`→`probe.dumps.sql`, `/data/app.sqlite`→`probe.dumps.sqlite`, `/admin`→`probe.admin.admin`, `/administrator/`→`probe.admin.administrator`.
+ - `TestCheckEncodingTricks` (Review Focus 1): `/.ENV`→`hard.secrets.env`, `/.Git/config`→`hard.secrets.git`, `/%2eenv`→`hard.secrets.env`, `/static/%2e%2e/.env`→`hard.traversal.dotdot`, `/static/..\\.env`→`hard.traversal.dotdot`, `/x/..;/.env`→`hard.traversal.dotdot`, `/.env;x=1`→`hard.secrets.env`, `//.env`→`hard.secrets.env`, `/./.git/config`→`hard.secrets.git`.
+ - `TestCheckWellKnownExempt`: `/.well-known/acme-challenge/abc`, `/.well-known/security.txt` and `/.well-known/.env` all give no match. `/.well-known/../.env` still gives `hard.traversal.dotdot`.
+ - `TestCheckMisfireCorpus` (Review Focus 2, spec §3): each of these gives no match.
+ - Paths: `/help/vat-in-the-european-union`, `/docs/display-a-selection-of-tickets`, `/docs/update-the-widget-from-version-1`, `/en/articles/how-do-i-delete-a-hub`, `/help/export-attendees-from-all-events`, `/docs/embeddable-javascript-widget`, `/assets/admin/application-3f2a9c.js`, `/favicon-admin-32.png`, `/help/the-admin-pane`, `/wp-content/uploads/2024/05/logo.png`, `/uploads/PMA_FULL_LOGO.png`, `/img/photo..jpg`, `/en/articles/\"https:/x.example\"`, `/api/union/members`, `/env`, `/environment`, `/blog/.envoy`, `/docs/index.php-guide`, `/products/admin-chair`, `/static/app.min.js`, `/todo`, `/telescopes`.
+ - Queries on `/`: `redirect_uri=https://example.com/cb`, `sig=ZXZhbCBkcm9wIHVuaW9u`, `s=search+terms`.
+ - `TestCheckLongPath` (Review Focus 3): a path of 1 MiB of `/a` segments ending `/.env` gives `hard.secrets.env`, and `testing.AllocsPerRun` on it is at most 4.
+ - `TestCheckOrdinaryPathAllocs`: `testing.AllocsPerRun(100, …)` on `Check("/blog/2026/10/some-article-slug", "")` and on `Check("/assets/app-3f2a9c.js", "v=2")` is 0.
+ - `BenchmarkCheckOrdinary`: same two inputs. Informational only, not asserted.
+
+- [ ] **Step 4: Run the tests to see them fail.** Run `go test ./internal/edgeguard/ -run 'TestCatalogue|TestParse|TestCheck' -count=1`. Expected: FAIL (package does not build).
+
+- [ ] **Step 5: Implement `catalogue.go`.** `//go:embed catalogue.txt`. Parse once at package init with `parseCatalogue`. A parse error panics at init: the file ships in the binary, and the tests catch a bad edit. Build the index structures:
+ - a map for `exact`;
+ - a map for `segment`;
+ - a map keyed by first segment for `prefix`;
+ - small slices for `segglob`, `ext`, `segseq` and `qparam`;
+ - a map from hash to rule.
+
+ Each index keeps file order within its tier.
+
+- [ ] **Step 6: Implement `match.go`.**
+ - `Check` runs over one or two forms of the path: the path as given, and, only when it contains `%`, `url.PathUnescape` of it (ignore the error and skip that form).
+ - For each form, read it as lower case with `\` as `/`, without allocating when the path has neither upper case nor `\`.
+ - The `dotdot` rule looks at raw segments. A segment is the text up to `;`.
+ - The other kinds look at the segments of `path.Clean("/"+form)`. Strip any `;…` from each segment before comparing.
+ - If the first segment is `.well-known`, only `dotdot` is tried.
+ - `qparam` uses `url.ParseQuery` only when `rawQuery` contains the parameter's name. A parse error keeps the pairs that did parse.
+ - Walk segments by index, not with `strings.Split`, so an ordinary path allocates nothing.
+
+- [ ] **Step 7: Run the tests to see them pass.** Run `go test ./internal/edgeguard/ -count=1 -bench BenchmarkCheckOrdinary -benchtime=10000x`. Expected: PASS. Report the benchmark ns/op in the task report.
+
+- [ ] **Step 8: Commit.**
+
+```bash
+git add internal/edgeguard
+git commit -m "edgeguard: the hard tier and probe catalogue, matched on path structure"
+```
+
+### Task 2: The edge runs the guard once per request
+
+**Files:**
+- Create: `internal/edge/guard.go`
+- Modify: `internal/edge/edge.go` (the field on `Edge`, set in `New`; the call in `ServeHTTP` after the observer defer and before the password gate)
+- Modify: `internal/edge/answered.go` (`outcome` gains `guard *guardState`)
+- Modify: `internal/edge/reqrecords.go` (replace `recordMatch` with `mintRef`; `observeRecords` files a `Match` when the outcome holds a verdict)
+- Modify: `internal/edge/reqrecords_test.go` (the three `recordMatch` tests move to `mintRef` and to the defer)
+- Modify: `internal/hostenv/hostenv.go` (R9: add `CARLOS_EDGE_PROTECT` and `CARLOS_EDGE_RECORDS` to `Optional`, keeping the list sorted)
+- Test: `internal/edge/guard_test.go`
+
+**Interfaces:**
+- Consumes: `edgeguard.Check`, `edgeguard.Rule`, `edgeguard.Mode*`, `reqrec.NewRef`, `reqrec.Fragment(reqrec.SourcePath|SourceQuery, name, value)`, `reqrec.Match`, `e.homes.Load().meshKeys()`, `e.box`.
+- Produces (used by Task 3):
+ - `type guardMode uint8` with `guardCatalogue` (zero value), `guardOff`, `guardWatch`, `guardBlock`.
+ - `func guardModeFromEnv(getenv func(string) string) guardMode` reads `CARLOS_EDGE_PROTECT`. It trims and lower-cases the value. `off`, `watch` and `block` map to the matching mode. Anything else, including unset, is `guardCatalogue`, and an unknown value is logged once.
+ - `type guardVerdict struct { rule *edgeguard.Rule; frag string; block bool; ref string }`.
+ - `type guardState struct { mode guardMode; mint func(reqrec.Tier, string) string; verdict *guardVerdict }`. `outcome` gains `guard *guardState`. `ServeHTTP` sets it whenever the guard runs for the request. A nil `guard` means the guard is off for this request, as for door callers, tunnel-delivered requests and mode `off`.
+ - `func (m guardMode) blocks(rule *edgeguard.Rule) bool`: `guardOff` and `guardWatch` never block. `guardBlock` blocks every rule except `ModeBurst`. `guardCatalogue` blocks only `ModeBlock` rules.
+ - `func guardDecide(w http.ResponseWriter, r *http.Request, hit edgeguard.Hit) (served bool)` is package-level, so the static handler, which has no `*Edge`, can call it. It reads the request's `guardState`, does nothing when that is nil or already holds a verdict, and otherwise notes the verdict. In block mode it mints a code with `state.mint`, writes the block response and returns true.
+ - `func writeGuardBlock(w http.ResponseWriter, code string)` writes the `404` (Global Constraints) with the body from copy row EP-1.
+ - `func (e *Edge) mintRef(tier reqrec.Tier, ruleID string) string` replaces `recordMatch`. It holds the mint half: mesh key, box, `time.Now()`. `ServeHTTP` passes `e.mintRef` as `guardState.mint`.
+ - `func outcomeFrom(r *http.Request) *outcome` (if no such accessor exists yet; reuse the one `MarkWoke` uses if it does).
+
+- [ ] **Step 1: Write the failing tests** in `guard_test.go`. Build the edge as `reqrecords_test.go` does, with a fake `RequestRecorder` that keeps every `Response` and `Match`. Assertions:
+ - `TestGuardModeFromEnv`: `""`→catalogue, `"off"`→off, `" Watch "`→watch, `"block"`→block, `"bogus"`→catalogue.
+ - `TestGuardWatchForwards`: in mode catalogue (every rule watches), `GET /.env` on an instance route reaches the upstream, which answers 404. The client gets the upstream's 404 body. The recorder has exactly one `Match` (`Kind` watch, `Tier` hard, `RuleID` `hard.secrets.env`, `Status` 404, `Ref` empty) and no `Response`.
+ - `TestGuardWatchRecordsUpstreamStatus` (Review Focus 5): on a hibernating route whose fake activator wakes it and calls `MarkWoke`, `GET /wp-login.php` answered 200 by the app gives one `Match` with `Status` 200, `WokeKnown` true, `Woke` true, and `Kind` watch.
+ - `TestGuardBlockMode`: with `guardBlock`, `GET /.git/config` gets 404 with `Content-Type: text/plain; charset=utf-8` and `Cache-Control: no-store`. The `X-Carlos-Ref` header equals the code in the body. `reqrec.ParseRef(code, meshKey)` verifies with `Tier` hard and `RuleHash == reqrec.RuleHash("hard.secrets.git")`. The upstream and the activator were never called. The recorder has one `Match` (`Kind` block, `Ref` == code, `Status` 404, `WokeKnown` true, `Woke` false) and no `Response`.
+ - `TestGuardBlockModeSparesBurst`: with `guardBlock`, `GET /admin` is forwarded, and its `Match` is a watch.
+ - `TestGuardBeforeGateAndCache`: with `guardBlock`, a gated route (`Gate` set) asked for `/.env` without a cookie gets the guard's 404, not the login page. A cached response stored for `/.env` (seeded with `e.cache.Put`) is not served.
+ - `TestGuardOffDoesNothing`: with `guardOff`, `GET /.env` is forwarded, and the recorder has one `Response` and no `Match`.
+ - `TestGuardSkipsTunnelDelivered`: a request whose context carries the tunnel mark (as `TestRecordsSkipTunnelDelivered` builds it) is forwarded with no verdict, even in `guardBlock`.
+ - `TestGuardOrdinaryRequestUntouched`: `GET /blog/post` gets one `Response` and no `Match`, and `outcome.guard` stays nil.
+ - `TestMintRefSealed` and `TestMintRefUnsealed`: the old `recordMatch` code tests, moved to `mintRef`.
+
+- [ ] **Step 2: Run the tests to see them fail.** Run `go test ./internal/edge/ -run 'TestGuard|TestMintRef|TestRecords' -count=1`. Expected: FAIL (undefined: `guardModeFromEnv` …).
+
+- [ ] **Step 3: Implement `guard.go`, and the changes to `answered.go` and `reqrecords.go`.**
+ - `observeRecords` keeps its `fromTunnel` return.
+ - With `out.guard != nil && out.guard.verdict != nil` it files `reqrec.Match{Response: x, Kind: block or watch, Tier: rule.Tier, RuleID: rule.ID, Fragment: frag, Ref: ref}`.
+ - `x` is `requestResponse(...)` with the real status. For a watch, `WokeKnown = !viaTunnel` and `Woke = out.woke`. For a block, `WokeKnown = true` and `Woke = false`.
+ - Otherwise it files the `Response` exactly as today.
+ - `frag` comes from `reqrec.Fragment(reqrec.SourcePath, "", hit.Fragment)`. When `hit.FromQuery` is set, it comes from `reqrec.Fragment(reqrec.SourceQuery, hit.QueryName, hit.Fragment)` instead.
+ - A fragment that may not be kept is stored as `""`.
+
+- [ ] **Step 4: Wire `ServeHTTP`.**
+ - In `New`: `e.guard = guardModeFromEnv(os.Getenv)`, next to `gzipOn`.
+ - In `ServeHTTP`, inside the `up.route.Kind != "status"` block after `withOutcome`, set `out.guard = &guardState{mode: e.guard, mint: e.mintRef}` when all of these hold:
+ - `e.guard != guardOff`;
+ - `!isDoor`;
+ - `!fromTunnel(r.Context())`.
+ - Immediately before the password-gate block (`if loginPost && up.route.Gate == ""`), when `out != nil && out.guard != nil`, check once:
+ - When `up.route.Kind == "static" && !up.viaTunnel`, Task 3 decides the probe tier, so call `edgeguard.CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierHard)`.
+ - For every other route, call `edgeguard.Check`.
+ - On a hit, call `guardDecide`. If it returns true, return.
+ - `out` must be visible at that point: hoist its declaration out of the `if` block. Keep the defer where it is.
+
+- [ ] **Step 5: Run the tests to see them pass.** Run `go test ./internal/edge/ -run 'TestGuard|TestMintRef|TestRecords|TestGate|TestCache' -count=1` and `go test ./internal/hostenv/ -count=1`. Expected: PASS.
+
+- [ ] **Step 6: Commit.**
+
+```bash
+git add internal/edge internal/hostenv
+git commit -m "edge: run the hard and probe tiers once per request, watch by default"
+```
+
+### Task 3: Static sites decide probe matches from their own files
+
+**Files:**
+- Modify: `internal/edge/static.go` (`serveTree`)
+- Modify: `internal/edge/redirects.go` (add `names`)
+- Test: `internal/edge/static_guard_test.go`
+
+**Interfaces:**
+- Consumes: Task 2's `guardDecide`, `outcomeFrom`, `outcome.guard`; `edgeguard.CheckTier`.
+- Produces: `func (rs *redirectRules) names(host, p string) bool`. It is true when some rule without splat and without `:placeholder` segments matches `p` for `host`. A nil `rs` is false.
+
+- [ ] **Step 1: Write the failing tests** in `static_guard_test.go`. Use the static test tree helpers in `static_test.go`. The edge runs in mode catalogue (watch) unless a test says `guardBlock`. Each test asserts the recorder's single `Match` or `Response`.
+ - `TestStaticProbeAbsentIsMatched`: a tree without `wp-login.php`, asked `GET /wp-login.php`, gives a watch `Match` `probe.wordpress.wp-login` with `Status` 404. In `guardBlock` the response is the guard's 404 with `X-Carlos-Ref`.
+ - `TestStaticProbePresentIsServed`: a tree holding `wp-login.php` (and, in a second case, `admin/index.html` for `/administrator/`) is served with its bytes and 200, in `guardBlock` too, and there is no `Match`.
+ - `TestStaticSplatIsNotExistence` (Review Focus 4): with `_redirects` holding `/* /index.html 200`, `GET /wp-login.php` gives a probe `Match`. In `guardBlock` it is blocked, not the fallback page.
+ - `TestStaticExplicitRedirectIsExistence`: with `_redirects` holding `/xmlrpc.php /api/rpc.html 200`, `GET /xmlrpc.php` is served, with no `Match`.
+ - `TestStaticRewriteToHardFile`: a tree holding `.env` (packed through the test helper, not `PackDir`, which would refuse it if it does) and `_redirects` holding `/download /.env 200`. `GET /download` gives a hard `Match` `hard.secrets.env`, and in `guardBlock` the guard's 404. In the default mode the file is served (watch).
+ - `TestStaticHardAtEdgeOnce`: `GET /.env` on a static site gives exactly one `Match`. The `ServeHTTP` check saw it first, and `serveTree` added nothing.
+
+- [ ] **Step 2: Run the tests to see them fail.** Run `go test ./internal/edge/ -run 'TestStatic' -count=1`. Expected: the new tests FAIL.
+
+- [ ] **Step 3: Implement.**
+ - In `serveTree`, after the redirect loop has settled `found` for the request path (before `if !found`): if the outcome has no verdict and `CheckTier(r.URL.Path, r.URL.RawQuery, reqrec.TierProbe)` hits, the hit counts only when `!found && !tree.redirects.names(requestHost(r.Host), p)`. Then `guardDecide`, and return if it served.
+ - When a rewrite set `rewritten`, run `CheckTier(p, "", reqrec.TierHard)` on the rewritten file path before `serveFile`, with the same `guardDecide`.
+ - Do nothing when `outcomeFrom(r)` is nil or its `guard` is nil. `guardDecide` already declines when a verdict exists. Check that first anyway, so `serveTree` skips the matcher too.
+
+- [ ] **Step 4: Run the tests to see them pass.** Run `go test ./internal/edge/ -run 'TestStatic|TestRedirect|TestGuard' -count=1`. Expected: PASS.
+
+- [ ] **Step 5: Commit.**
+
+```bash
+git add internal/edge
+git commit -m "edge: static sites serve probe paths they have, and never a rewrite onto a leak"
+```
+
+### Task 4: The console names the rule behind a code
+
+**Files:**
+- Modify: `internal/console/apiedgeref.go`
+- Test: `internal/console/apiedgeref_test.go`
+
+**Interfaces:**
+- Consumes: `edgeguard.RuleByHash`.
+- Produces: `apiEdgeRef` gains `Sealed bool \`json:"sealed"\``, `Rule string \`json:"rule,omitempty"\`` and `Group string \`json:"group,omitempty"\``. Task 5 reads them.
+
+- [ ] **Step 1: Write the failing tests:**
+ - `TestAPIEdgeRefNamesCatalogueRule`: a sealed code for `hard.secrets.env` gives `rule == "hard.secrets.env"`, `group == "secrets"`, `sealed == true` and `verified == true`.
+ - `TestAPIEdgeRefUnknownRule`: a code for rule id `tenant-x` gives no `rule` or `group` field, and the `rule_hash` is still present.
+ - `TestAPIEdgeRefUnsealed`: an unsealed code gives `sealed == false` and `verified == false`.
+
+- [ ] **Step 2: Run them to see them fail.** Run `go test ./internal/console/ -run TestAPIEdgeRef -count=1`. Expected: FAIL.
+
+- [ ] **Step 3: Implement.** Fill `Sealed` from `ref.Sealed`. Fill `Rule` and `Group` when `RuleByHash(ref.RuleHash)` finds a rule whose tier equals `ref.Tier`.
+
+- [ ] **Step 4: Run the tests to see them pass.** Same command. Expected: PASS. Also run `go test ./internal/console/ -run 'TestClaimConsoleRouteCensus|TestSvcRoutes' -count=1`. The route table is unchanged, so it passes as before.
+
+- [ ] **Step 5: Commit.**
+
+```bash
+git add internal/console
+git commit -m "console: a reference code names its catalogue rule"
+```
+
+### Task 5: `carlos explain`, its docs and the copy record
+
+**Files:**
+- Create: `explain_cmd.go`, `explain_cmd_test.go`
+- Modify: `main.go` (the `case "explain":` dispatch and the command list in the top-level usage)
+- Create: `approved_edge_protect_copy_test.go`
+- The copy record `docs/superpowers/plans/2026-10-25-edge-protection-2-copy.md` already exists. Rows EP-1 to EP-13 are pending. EP-3 is the docs row: it is not written in this task (docs are never wired), and Task 6 writes it once approved.
+
+**Interfaces:**
+- Consumes: `GET /api/cli/apps/{account}/{app}/edge-refs/{code}` (Task 4's shape), and the CLI helpers `runGeo` uses (`appFlag`, `consoleOption`, `requireAPISession`, `resolvedAccount`, `resolvedApp`, `apiPath`, `sess.getJSON`, `apiErrorFromBody`, `flagUsage`).
+- Produces: `func runExplain(args []string)` and `func printExplain(w io.Writer, res apiEdgeRefResponse)`.
+
+- [ ] **Step 1: Write the failing tests** in `explain_cmd_test.go`, against `printExplain` with fixed responses. Compare whole output strings built from the copy record's EP rows:
+ - `TestPrintExplainVerifiedFound`: the output is EP-8, then EP-4, then EP-13, then EP-9, in that order, one per line. The time is in UTC (`2006-01-02 15:04 UTC`).
+ - `TestPrintExplainSealedUnverified`: EP-5 in place of EP-4.
+ - `TestPrintExplainUnsealed`: EP-6 in place of EP-4.
+ - `TestPrintExplainUnknownRule`: EP-7, with the response's `rule_hash`, in place of EP-13.
+ - `TestPrintExplainAbsent` and `TestPrintExplainUnavailable`: EP-10 and EP-11 in place of EP-9.
+ - `--json` prints the body unchanged. Test it through a fake session if the geo tests have one; otherwise test `printExplain` only and note it in the report.
+ - In `approved_edge_protect_copy_test.go`, following `approved_db_forward_copy_test.go` and reusing its helpers (`parseCopyTable`, `checkMovesInventory`, `checkMovesNoEmDash`, `checkRunBuilt`, `checkRunApplied`, and the shape of `checkDBForwardWired`):
+ - `TestEdgeProtectCopyRecordIsComplete`: the record names exactly EP-1 to EP-13.
+ - `TestEdgeProtectCopyHasNoEmDash`.
+ - `TestEdgeProtectBuiltCopyIsApproved`: ids in `edgeProtectCopyBuilt` are approved rows.
+ - `TestEdgeProtectBuiltCopyIsApplied`.
+ - `TestEdgeProtectWiredCopyIsPendingAndApplied`: a wired id is a pending, non-docs row whose text is in its file.
+ - `TestEdgeProtectCopyAccounted`: every id except EP-3 is in exactly one of `edgeProtectCopyBuilt` and `edgeProtectCopyWired`.
+ - In this task every id except EP-3 goes in `edgeProtectCopyWired`, and `edgeProtectCopyBuilt` is empty.
+
+- [ ] **Step 2: Run them to see them fail.** Run `go test . -run 'TestExplain|TestEdgeProtectCopy' -count=1`. Expected: FAIL.
+
+- [ ] **Step 3: Implement** `runExplain`.
+ - Usage: `carlos explain <code> --app <a> [--json] [--console …] [--account …]`. The usage text is EP-2.
+ - The code goes into the path through `url.PathEscape`.
+ - A 404 from the console prints EP-12 and exits 1.
+ - Any other non-200 answer goes through `apiErrorFromBody`, as `runGeo` does.
+ - All strings come verbatim from the copy record.
+
+- [ ] **Step 4: Run the tests to see them pass.** Same command, plus `go vet .` and `GOOS=darwin go build -o /dev/null .` and `GOOS=windows go build -o /dev/null .`. Expected: PASS and clean builds.
+
+- [ ] **Step 5: Commit.**
+
+```bash
+git add explain_cmd.go explain_cmd_test.go main.go approved_edge_protect_copy_test.go
+git commit -m "carlos explain: what a block page's reference code says"
+```
+
+### Task 6: Copy review (controller, with Paul)
+
+Not dispatched to an implementer. The controller runs the copy-review tool over EP-1 to EP-13, which needs Paul's approval. Then, in one commit, it:
+- applies the approved text to the record and the code;
+- writes EP-3 as an `explain` section in `docs/site/cli.md` after the `logs` section;
+- moves every id into `edgeProtectCopyBuilt`, EP-3 included;
+- adds `TestEdgeProtectCopyNoneWired` (`edgeProtectCopyWired` is empty).
+
+It also files R11's two requests:
+- an amadan discussion on carlos/platform naming the framework's route-list request;
+- a reply on #366 for the file list. Verify with `go test . -run TestEdgeProtectCopy -count=1` and `go test ./internal/edge/ -run TestGuardBlockMode -count=1`.
+
+Rollout after merge (Paul's go, dev first):
+1. Release, then roll to dev boxes with `CARLOS_EDGE_PROTECT` unset (watch).
+2. On one dev box, set `CARLOS_EDGE_PROTECT=block` for a hand check of the block page and `carlos explain`. Then unset it.
+3. Roll to the flagship unset. The 14-day calibration window starts there.