carlos / platform Public

plan: linked deployments slice 1 rev 3 (Paul's round-2 choices)

One writer for link channel state, the normal edge pipeline with a
pinned upstream for linked requests, connection replacement on
unpublish; plus round-2 P2s (kindLink doors, store-level guards for
linked app rows, publish-time link recheck, lost-rotation recovery).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 31f5000834d5929cef283ae62a7988599ea2f01d parent 44566ad
2 files changed, +99 −34
  • docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md +48 −34
  • docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R3.md +51 −0

CI failed — run details

diff --git a/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md
index a9ab86e82..487267875 100644
--- a/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md
+++ b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md
@@ -19,8 +19,9 @@
- Link credential: a `cli_tokens` row with `kind = "link"`; its sha256 hex is also the channel's token hash in the hub registry. One secret, two uses.
- No new per-box object-store polling (spec anti-goal 4). Everything flows through console APIs and the shared registry.
- New registry tables and columns are added to `Fingerprint()` (`registry.go:3990`) unless a task says otherwise, to `consoleRegistry` (`internal/console/view.go:522`) when the console uses them, and to `internal/registry/remote_dispatch.go` when the agent uses them through `OpenRemote`.
-- Every new console route gets its row in the parity table checked by `internal/console/parity_test.go`, and every new top-level CLI command gets its heading on the CLI reference page checked by `internal/docsite/cli_test.go` (Tasks 5, 6, 7, 9).
-- Plan revision: rev 2, after round 1 (Astra and Fable, both NOT READY; findings in `docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md`).
+- Every new console route that is a parity member gets its row in the parity table checked by `internal/console/parity_test.go`, and every new top-level CLI command gets its heading on the CLI reference page checked by `internal/docsite/cli_test.go` (Tasks 5, 6, 7, 9).
+- Plan revision: rev 3. Round 1: both NOT READY (`docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md`). Round 2: Astra NOT READY, Fable READY AFTER FIXES (`...-R2.md`). Three round-2 P1s recurred in round-1 fault families (AGENTS.md rule 2); Paul chose on 2026-11-10 (amadan discussion 812): (1) **one writer** for link channel state, (2) linked requests run the **normal edge pipeline with a pinned upstream**, (3) **unpublish replaces the whole link connection**. Rev 3 implements those three and the round-2 P2s.
+- Parity rows go only to routes that are console parity members; `/api/cli/` doors and the `kindLink` doors are not members (`parity_test.go:41-42`).
- Migrations are additive: `CREATE TABLE IF NOT EXISTS` and `ALTER TABLE ADD COLUMN` with duplicate-column errors swallowed, following `migrateFleets` (registry) and `Store.migrate()` (console). New `apps` columns go in by ALTER after `migrateAppsKey` runs.
- User-facing strings come from the approved copy deck (Task 0) verbatim. Neutral names only in examples and tests (`shop`, `blog`, `example.com`).
- Socket tests run with `TMPDIR=/tmp/g` (Unix socket path length).
@@ -33,7 +34,7 @@
2. **Unpublished app reached through the tunnel.** Missing header, header naming an unpublished app, a client-supplied `Carlos-Link-App`, a Host header naming another home app, a host later re-pointed to another app, a path-map prefix: the home handler must refuse each without touching an instance. Tests in Task 8.
3. **Revocation that doesn't cut a live connection.** Rotate and unlink while the tunnel is connected: the old channel closes within one hub reload and the old token cannot redial. Test in Task 3 (edge) and Task 5 (console end to end).
4. **Link rows deleted or altered by other passes.** A full hub `provision.Reconcile` pass and a `domains` reconcile pass leave link rows untouched and mint no platform alias for them. Test in Task 2.
-5. **Unpublish ordering.** Unpublish while requests are in flight: the home set drops the app before the serving console is called, so a hub that has not reloaded yet still gets a refusal from home. Test in Task 7.
+5. **Unpublish ordering and open streams.** Unpublish while requests and streams are in flight: the home set drops the app before the serving console is called, so a hub that has not reloaded yet still gets a refusal from home, and the link connection is replaced so open streams end. Tests in Tasks 7 and 8.
---
@@ -68,13 +69,13 @@ Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appear
- `func ValidLinkID(id string) bool`
- `func LinkChannelName(linkID string) string` → `"link:" + linkID + "/home"`
- `func LinkOfChannel(name string) (linkID string, ok bool)` — inverse; false for every fleet channel.
- - `type LinkChannel struct { LinkID, Account, TokenHash, Status string; CreatedAt time.Time }` (Status `active` | `revoked`)
- - `func (r *Registry) PutLinkChannel(c LinkChannel) error` — upsert; validates ID, 64-hex hash, non-empty account.
- - `func (r *Registry) RevokeLinkChannel(linkID string) (bool, error)`
+ - `type LinkChannel struct { LinkID, Account, TokenHash, Status string; Generation uint64; CreatedAt time.Time }` (Status `active` | `revoked`)
+ - `func (r *Registry) PutLinkChannel(c LinkChannel) (applied bool, err error)` — **one-writer contract (Paul's choice 1):** applies only when `c.Generation` is greater than the stored generation and the stored row is not `revoked` (revoked is terminal; a revoked link ID is never reused). A stale or replayed write returns `applied=false` and changes nothing. Validates ID, 64-hex hash, non-empty account. Only Task 4's `syncLinkChannel` calls it.
+ - `func (r *Registry) RevokeLinkChannel(linkID string) (bool, error)` — in one transaction marks the channel `revoked` and deletes every forward row placed `link/<linkID>`.
- `func (r *Registry) LinkChannelAuth() (map[string]string, error)` — active rows keyed by `LinkChannelName`.
- `func (r *Registry) LinkOwners() (map[string]string, error)` — active link ID → account sqid.
- - `func (r *Registry) SetLinkSeen(linkID string, connected bool, at time.Time) error` and `func (r *Registry) LinkSeen() (map[string]LinkSeen, error)` with `type LinkSeen struct { Connected bool; At time.Time }`. These columns are **excluded** from `Fingerprint` (they change on every connect and must not trigger reloads).
- - `PutForward` accepts `Region` for which `LinkPlacement` is ok, alongside fleet placements. **Placement classes are disjoint:** in the same transaction, `PutForward` returns `ErrHostHeld` when a forward row already holds the host with a different class (fleet vs link) or, for link rows, a different link ID. Fleet rows written by the provision pass can therefore never overwrite a link row, nor a link row a fleet row.
+ - `func (r *Registry) LinkSeen() (map[string]LinkSeen, error)` with `type LinkSeen struct { Connected bool; At time.Time }`. The `connected`, `seen_at` and `seq` columns are **excluded** from `Fingerprint` (they change on every connect and must not trigger reloads).
+ - `PutForward` accepts `Region` for which `LinkPlacement` is ok, alongside fleet placements. For a link row, in the same transaction, `PutForward` requires an `active` `link_channels` row for that link ID whose account equals the row's `Account`, so a publication racing an unlink can never leave a row behind. **Placement classes are disjoint:** in the same transaction, `PutForward` returns `ErrHostHeld` when a forward row already holds the host with a different class (fleet vs link) or, for link rows, a different link ID. Fleet rows written by the provision pass can therefore never overwrite a link row, nor a link row a fleet row.
- `func (r *Registry) DeleteLinkForward(host, linkID string) (bool, error)` — deletes only a forward row whose Region is exactly `link/<linkID>`. `DeleteForward` refuses (returns false) for any link-placed row, so only the link's own owner path can remove it.
- `func (r *Registry) LinkForwards(linkID string) ([]Route, error)` — every forward row placed `link/<linkID>`; unlink deletes from this list, not from console app rows.
- `SetLinkSeen` carries the connection's registration sequence: `SetLinkSeen(linkID string, seq uint64, connected bool, at time.Time) error` applies a disconnect only when the stored `seq` equals `seq` (a re-register's newer connect is never overwritten by the older connection's close). `func (r *Registry) ResetLinkSeen() error` marks every link disconnected; the hub calls it at start.
@@ -86,9 +87,11 @@ Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash
- `TestLinkChannelAuthOnlyActive`: put two links, revoke one; `LinkChannelAuth()` has exactly the active one keyed `link:<id>/home`; `LinkOwners()` likewise.
- `TestPutForwardAcceptsLinkPlacement`: `PutForward(Route{Kind: KindForward, Host: "shop.acct1.apps.example.com", App: "shop", Account: "acct1", Region: "link/0123456789ab"})` succeeds; `Region: "link/bad"` returns `ErrNotForward`.
- `TestLinkSeenDoesNotMoveFingerprint`: `Fingerprint()` before and after `SetLinkSeen` is equal; after `PutLinkChannel` it differs.
-- [ ] **Step 2:** `go test ./internal/registry -run 'TestLink|TestPutForwardAcceptsLinkPlacement|TestForwardClassesDisjoint'` — FAIL (undefined).
- `TestForwardClassesDisjoint`: with a link row on host H, `PutForward` of a fleet row on H returns `ErrHostHeld` and H is unchanged; the reverse also holds; a link row of link L2 cannot replace L1's; `DeleteForward(H)` returns false for the link row and `DeleteLinkForward(H, L2)` returns false.
- `TestLinkSeenOrdering`: connect seq 1, connect seq 2, disconnect seq 1 → still connected; disconnect seq 2 → disconnected; `ResetLinkSeen` clears all.
+ - `TestPutLinkChannelOneWriter`: generation 2 applied; generation 1 afterwards not applied and the hash is unchanged; after `RevokeLinkChannel`, generation 3 is not applied and the row stays revoked.
+ - `TestLinkForwardNeedsActiveChannel`: `PutForward` of a link row with no channel, a revoked channel, or a channel of another account fails; `RevokeLinkChannel` removes the link's forward rows in the same transaction.
+- [ ] **Step 2:** `go test ./internal/registry -run 'TestLink|TestPutForwardAcceptsLinkPlacement|TestForwardClassesDisjoint|TestPutLinkChannelOneWriter'` — FAIL (undefined).
- [ ] **Step 3:** Implement `links.go`, the migration, the `PutForward` placement check, the Fingerprint section (with `connected`, `seen_at` and `seq` excluded), and the `consoleRegistry` / `internal/registry/remote_dispatch.go` entries for `PutLinkChannel`, `RevokeLinkChannel`, `LinkChannelAuth`, `LinkOwners`, `SetLinkSeen`, `ResetLinkSeen`, `LinkSeen`, `LinkForwards`, `DeleteLinkForward`, and also `PutForward` (missing from `consoleRegistry` today), plus the home-side methods of Task 7 when that task lands.
- [ ] **Step 4:** Same command — PASS. Also `go test ./internal/registry ./internal/host -run 'Remote|Fingerprint'`.
- [ ] **Step 5:** Commit `registry: link channels and link placement for forward rows`.
@@ -107,7 +110,7 @@ Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash
- `TestNonHubReconcileKeepsLinkRows`: same on a non-hub cfg (today every forward row is retired there); the link row survives.
- `TestDomainsReconcileSkipsLinkRows`: domains reconcile over a registry with a link row mints no platform alias and removes nothing for it.
- [ ] **Step 2:** `go test ./internal/provision ./internal/domains -run 'LinkRows'` — FAIL on the retirement.
-- [ ] **Step 3:** In `retirements`, skip any row for which `registry.LinkPlacement(rt.Region)` is ok. `mint` (`internal/provision/forward.go:288-302`) treats an existing forward row as its own today; make it report a link-placed row as held (skip, with the existing held reporting), relying on Task 1's disjoint `PutForward` as the backstop. Add to the first test: a bucket record naming the link host leaves the link row unchanged and is reported held.
+- [ ] **Step 3:** In `retirements`, skip any row for which `registry.LinkPlacement(rt.Region)` is ok. `mint` (`internal/provision/forward.go:288-302`) treats an existing forward row as its own today; make it report a link-placed row as held (skip, with the existing held reporting), relying on Task 1's disjoint `PutForward` as the backstop. Reword the "the forward phase retires it" log at `internal/provision/reconcile.go:1860` for link-placed rows, which are never retired. Add to the first test: a bucket record naming the link host leaves the link row unchanged and is reported held.
- [ ] **Step 4:** Same command — PASS.
- [ ] **Step 5:** Commit `provision: keep link forward rows out of the retirement pass`.
@@ -129,7 +132,7 @@ Risk: security gate and production serving path. Gets its own review.
- `FleetArmVerdict(routes []registry.Route, owners ForwardOwners, hub, tunnels bool) FleetVerdict`. `FleetServed` gains `Link string`; the `Arm` map gets an entry for eligible link rows (today it is filled only for `FleetPlacement`, `fleetforward.go:284-286`), and `DispatchArm` returns a new `ArmLink` for them.
- `fleetArmInputs` (`internal/host/hub.go:26-36`) returns `ForwardOwners` with `LinkOwners()`; the edges file (`edgesfile.go:649`) and the console's instance view (`apiinstances.go:429`) pass the same, so link hosts are published for backhaul like fleet hosts.
- The fleet owners snapshot stored for the store door (`edge.go:1435`, read by `fleetAccount`) keeps **fleet owners only**; link owners live in a separate snapshot.
- - `VerifyDynamic` refuses every link channel name (returns false). A new `(h *TunnelHub) verifyLink(name, token string) (linkID string, ok bool)` is what `ServeHTTP` uses for names where `registry.LinkOfChannel` is ok. No fleet helper ever returns a link ID as a fleet.
+ - `VerifyDynamic` refuses every link channel name (returns false). A new `(h *TunnelHub) verifyLink(name, token string) (linkID string, ok bool)` is what `ServeHTTP` uses for names where `registry.LinkOfChannel` is ok, and `verifyLinkLocked` repeats the check under `h.mu` at publish, as `verifyDynamicLocked` does for fleets (`tunnel.go:269-276`), so a dial authenticated before a rotation never publishes on the old token. No fleet helper ever returns a link ID as a fleet. When `SetDynamicAuth` closes a link channel on a hash change it closes the **captured** connection, not the name, so a home that redials with the new token in that gap keeps its fresh connection.
- Upgrade admission: the `tenancy` value gains `Link string`; a request on an `ArmLink` row is admitted for upgrade with `{Arm: ArmLink, Account, App, Link}` and matches at reserve time (`upgrades.go:210`) the same way fleet tenancies do.
- `func linkProxy(linkID, app string, hub *TunnelHub) *httputil.ReverseProxy` — dials `LinkChannelName(linkID)`; sets `LinkAppHeader: app` after the shared `tunnelRewrite`.
- `SetDynamicAuth` closes a channel whose token hash **changed** when the name is a link channel (`registry.LinkOfChannel`). Fleet rotation keeps today's behaviour.
@@ -140,7 +143,8 @@ Risk: security gate and production serving path. Gets its own review.
- `TestLinkHeaderFromClientIsStripped`: the client sends `Carlos-Link-App: other`; the home handler sees `shop`.
- `TestLinkOwnerMismatchRefused`: link owned by `acct2`, row account `acct1` → refused at Reload (verdict `Refused`), request is not dialled.
- `TestLinkDarkServesOfflinePage`: no home connected → 503, `Retry-After` present, `Content-Type: text/html`, body contains the LD offline title from the deck; a fleet row in the same state still returns today's plain text.
- - `TestLinkRotationClosesChannel`: connected home; `PutLinkChannel` with a new hash; after `Reload` the channel is closed and the old token is refused on redial.
+ - `TestLinkRotationClosesChannel`: connected home; `PutLinkChannel` with a new hash and higher generation; after `Reload` the channel is closed and the old token is refused on redial; a redial with the new token during the close keeps its connection.
+ - `TestLinkRotateBetweenAuthAndPublish`: using the hub's `afterAuth` hook, rotate between authentication and publish; the connection is closed and never selected.
- `TestLinkCredentialRefusedByStoreDoor`: a link channel name and token against `/store/o/...` → 404.
- `TestFleetIdentityRefusesLinkChannel` (console): `fleetIdentityOK(reg, "link:<id>/home", token, "link:<id>", acct)` is false, and so is every fleet name.
- `TestConnectedOfFleetIgnoresLinks`: a connected link channel never appears in `ConnectedOfFleet(f)` for any fleet `f`.
@@ -169,7 +173,8 @@ Risk: authority. Gets its own review.
- `PrincipalLink` added to `PrincipalKind`; `Principal.LinkID string`. `CLIPrincipal` returns `{Kind: PrincipalLink, AccountID, LinkID}` for an unrevoked `kind = "link"` token whose link is not revoked.
- `POST /auth/cli/start` accepts JSON `{"purpose":"link","name":"<home name>"}`; any other purpose value is 400. Without `purpose` it behaves exactly as today. A link start's response echoes `"purpose":"link"`; the home side (Task 7) aborts with the deck's "serving console too old" string when the echo is missing, because an older console ignores unknown fields and would start an ordinary person login.
- Approval for a link request shows an account picker limited to accounts where the approver holds the role `handleAPICreateApp` requires, and passes step-up (`requireFreshAuth`) as today. Approving stores `account_id` on the request.
- - `PollCLIAuth` for an approved link request, in one transaction: mints the token with `kind='link'`, `account_id`, `name=<linkID>`; inserts the `links` row; then (after commit) calls `reg.PutLinkChannel(LinkChannel{LinkID, Account: sqid, TokenHash, Status: "active"})`. Every `/api/link/` call (Task 5) re-asserts the channel with `PutLinkChannel` when the registry row is missing or differs, so a failure here heals on the home side's next call. The poll response for a link adds `link_id`, `account` (sqid), `tunnel_url` (`https://` + `TunnelHost` + `/register`; `tunnelclient.Dial` accepts only `https` and `http`, `tunnelclient.go:204-220`) and `apps_domain`.
+ - `PollCLIAuth` for an approved link request, in one transaction: mints the token with `kind='link'`, `account_id`, `name=<linkID>`; inserts the `links` row with `token_hash` and `generation = 1`; commits; then calls `syncLinkChannel`. The token is delivered in the poll response even if that sync fails, because the console row is authoritative and the channel is derived from it: the sync runs again at console start and before every `/api/link/` handler, and can only ever write the console's current state.
+ - **One writer (Paul's choice 1).** Console `links` gains `token_hash TEXT NOT NULL` and `generation INTEGER NOT NULL`. `func (s *Server) syncLinkChannel(ctx context.Context, linkID string) error` reads the `links` row and writes the registry from it alone: `PutLinkChannel{TokenHash: row.token_hash, Generation: row.generation, Status: active}` for a live link, `RevokeLinkChannel` for a revoked one. It never takes a hash from a request. Rotate and unlink change the console row in one transaction (rotate: new hash, `generation+1`, old token revoked; unlink: `revoked_at`), then call `syncLinkChannel`. It is the only caller of `PutLinkChannel` and `RevokeLinkChannel`. The poll response for a link adds `link_id`, `account` (sqid), `tunnel_url` (`https://` + `TunnelHost` + `/register`; `tunnelclient.Dial` accepts only `https` and `http`, `tunnelclient.go:204-220`) and `apps_domain`.
- Link tokens never expire: `expires_at = 0` for `kind='link'`, and the expiry purge (`authstore.go:478`) skips them. They are excluded from `CLITokens(address)` listings (`authstore.go:718-720`), `RevokeCLIToken` (`:763`) and `RevokeAccountToken` (`svcprincipal.go:534`); the only ways to end one are rotate and unlink (Task 5, Task 6), which also revoke the channel.
- The rate key for link principals is the link ID (`principalKey`, `svcprincipal.go:577`), not the account.
@@ -180,7 +185,9 @@ Risk: authority. Gets its own review.
- `TestLinkTokenRefusedEverywhereElse`: walk `routeDecls`; for every route under `/api/cli/` and every person-only door, a request with the link token gets 401 or 403 (never 2xx). Fill every placeholder the declarations use (not only `acct`/`app`/`host`) from one table that fails the test on an unknown placeholder, and enable every configuration gate the declarations carry (`routedecls.go:35`, `:456`) so gated routes are exercised. As a positive control, the same walk with a person token reaches at least one handler past the gate.
- `TestPlainLoginUnchanged`: start without purpose → token is user-kind as today.
- [ ] **Step 2:** `go test ./internal/console -run 'TestLinkApproval|TestLinkTokenRefused|TestPlainLoginUnchanged'` — FAIL.
-- [ ] **Step 3:** Implement. Link principals must fail every existing gate by construction: check `cliGateRefused` and `serviceBinding` refuse `PrincipalLink` explicitly, and route link principals only to the `/api/link/` doors of Task 5.
+ - `TestSyncCannotResurrect`: a request authenticated with token A pauses (test barrier) before its pre-handler sync; rotate installs B (generation 2); the paused request resumes and syncs; the registry still holds B. Same with unlink: the registry stays revoked.
+ - `TestPollDeliversTokenWhenSyncFails`: a registry that fails `PutLinkChannel` once; poll still returns the token; the next `/api/link` call heals the channel.
+- [ ] **Step 3:** Implement. Link principals must fail every existing gate by construction: check `cliGateRefused` and `serviceBinding` refuse `PrincipalLink` explicitly, and route link principals only to the `kindLink` doors of Task 5.
- [ ] **Step 4:** Same command — PASS.
- [ ] **Step 5:** Commit `console: link credentials through the device-code flow`.
@@ -191,18 +198,21 @@ Risk: authority, plan caps. Gets its own review.
**Files:**
- Create: `internal/console/apilinks.go`, `internal/console/apilinks_test.go`
- Create: `internal/console/linkedpolicy.go`
-- Modify: `internal/console/routedecls.go` (new routes), the parity table read by `internal/console/parity_test.go`, `internal/console/lifetimes_store.go:430-449` (`newAppRow.LinkID`), console `apps` ALTER `linked_link_id TEXT NOT NULL DEFAULT ''`, `internal/console/apicli.go:69-98` (`apiAccountAppSaying`), `internal/console/server.go:5648` (`accountApp`)
+- Modify: `internal/console/routedecls.go` (new routes, `kindLink`), `internal/console/svcroutes_test.go`, `internal/console/lifetimes_store.go:430-449` (`newAppRow.LinkID`), console `apps` ALTER `linked_link_id TEXT NOT NULL DEFAULT ''`, `internal/console/apicli.go:69-98` (`apiAccountAppSaying`), `internal/console/server.go:4166` (`accountApp`), `internal/console/materialize.go`, `settle.go`, `expirypass.go`, `lifetimes_purge.go`, `store.go:1829` (`ReapAccount` caller)
**Interfaces:**
- Consumes: Task 4's `PrincipalLink`, `LinkByID`; Task 1's registry methods; `checkCreateApp` (`plancaps.go:285`) under `planLock`; `allowAppCreate` (`svcprincipal.go:602`); `insertAppRow`; `Config.AppsDomain`.
-- Produces (all require a `PrincipalLink`; anything else gets 401):
+- Produces:
+ - A new route kind `kindLink` in `routedecls.go`, registered through one gate `func (s *Server) linkRoute(h http.HandlerFunc) http.HandlerFunc` that resolves the bearer with `CLIPrincipal`, admits only `PrincipalLink` (anything else gets `cliNotSignedIn`'s 401), runs `syncLinkChannel` for the link, and puts the principal on the context. Link handlers call no resolver themselves. Extend `registerDecls`, `TestRouteDeclsMatchRegistrations` and the resolver scan in `TestAuthCLIFamilyResolvesOnlyPersons` (`svcroutes_test.go:1423, 1506`) so `linkRoute` is the one permitted resolver site for `kindLink`. `kindLink` is not a parity member (machine-to-machine doors with no browser twin).
+ - The doors (all `kindLink`):
- `GET /api/link` → `{"link_id","account","name","publications":[{"app","url","created_at"}]}`
- `POST /api/link/publications` body `{"app":"<name>"}` → 201 `{"app","url"}`. Name rules as for app create. Refusals: name taken in the account by anything other than this link's own linked app (409, deck string), cap (409 `{"code":"cap"}` as today), rate limit (429). Writes the `apps` row with `LinkID` set, then `reg.PutForward(Route{Kind: KindForward, Host: app+"."+acct.Sqid+"."+AppsDomain, App: app, Account: acct.Sqid, Region: "link/"+linkID})`. **Idempotent for the same link:** when this link already has a linked app of that name, it re-puts the forward row and answers 200 with the same body, so a retry after a partial failure completes instead of answering "name taken".
- `DELETE /api/link/publications/{app}` → 204. `DeleteLinkForward(host, linkID)` first, then the `apps` row (only where `linked_link_id` = this link). A missing row on either side is not an error.
- - `POST /api/link/rotate` → 200 `{"token"}`: new token, old one revoked, `PutLinkChannel` with the new hash (the hub then closes the channel, Task 3).
- - `DELETE /api/link` → 204: for every row in `reg.LinkForwards(linkID)` (the registry is the source of truth, not the `apps` table) `DeleteLinkForward`, then every `apps` row with this `linked_link_id`; token revoked, `RevokeLinkChannel`, `links.revoked_at` set.
+ - `POST /api/link/rotate` → 200 `{"token"}`: one console transaction (new token and hash, `generation+1`, old token revoked), then `syncLinkChannel` (the hub then closes the old connection, Task 3).
+ - `DELETE /api/link` → 204: `func (s *Server) unlink(ctx, l *Link, by string) error` — one console transaction sets `revoked_at` and revokes the token; then `syncLinkChannel` (which runs `RevokeLinkChannel`, removing every `link/<id>` forward row atomically in the registry); then every `apps` row with this `linked_link_id` is deleted.
+ - **Linked app rows are removed only by unpublish and unlink.** `claimRawTrashAppRow`, `PurgeAppRow`, the bucket-convergence trash and purge (`materialize.go:402, 431`; `settle.go:102, 144`) and the expiry passes (`expirypass.go:255`, `lifetimes_purge.go:258`) skip or refuse rows with `linked_link_id` set. `ReapAccount`'s caller (`materialize.go:120`) runs `unlink` for each of the account's links first.
- **One linked-app policy for every app door, browser and CLI.** `func linkedAppPolicy(pattern string) linkedPolicy` in `internal/console/linkedpolicy.go`, with `linkedPolicy` one of `linkedAllow` (reads the spec keeps: analytics, protection, usage, the app's overview) or `linkedRefuse` (everything that acts on code, config, instances, data, the app's identity or lifetime: deploy, promote, rollback, environments, config/secrets, instances, runs, exec, logs, db, moves, regions, replicas, schedules, retention, pipeline, place, sidecars, store, relay, email, ledgers, rename, delete, transfer) and, in slice 1, domains. The table is keyed by route pattern from `routeDecls`.
- - `func (s *Server) linkedAppRefusal(r *http.Request, acct *Account, app string) *doorRefusal` returns 409 with the deck's "managed by its home deployment" string when the app is linked and the matched pattern's policy is `linkedRefuse`. It is consulted by `apiAccountAppSaying` (all methods, not only mutations) **and** by the browser app resolver `accountApp` (`server.go:5648` and its callers such as `envform.go:722`).
+ - `func (s *Server) linkedAppRefusal(r *http.Request, acct *Account, app string) *doorRefusal` returns 409 with the deck's "managed by its home deployment" string when the app is linked and the matched pattern's policy is `linkedRefuse`. It is consulted by `apiAccountAppSaying` (all methods, not only mutations) **and** by the browser app resolver `accountApp` (`server.go:4166` and its callers such as `handlePromote` at `server.go:5648` and `envform.go:722`).
- [ ] **Step 1: Write failing tests:**
- `TestPublishCreatesLinkedAppAndRow`: publish `shop` → `apps` row with `linked_link_id`, registry forward row with `Region link/<id>`, response URL `https://shop.<sqid>.<AppsDomain>`.
@@ -213,8 +223,10 @@ Risk: authority, plan caps. Gets its own review.
- `TestLinkedAppRefusedOnAppRoutes`: for every `linkedRefuse` route, a request for a linked app (person token or browser session with the right role) gets 409 and the deck string, GET and non-GET alike, and the handler's side effect did not happen; for every `linkedAllow` route it does not get the linked refusal.
- `TestPublishIsIdempotent`: publish `shop`, delete its forward row behind the console's back, publish `shop` again from the same link → 200, row restored; from another link → 409.
- `TestUnlinkUsesRegistryRows`: a link forward row with no matching `apps` row is still deleted by unlink.
+ - `TestPublishRacingUnlink`: with a barrier between the `apps` insert and `PutForward`, unlink completes; the publish's `PutForward` fails and the handler removes its `apps` row; no forward row remains.
+ - `TestEveryAppDeleteRespectsLinked`: scan the console package's SQL for every `DELETE FROM apps` and trash statement (pattern: `TestEveryAppInsertMintsALifetime`); each must carry the `linked_link_id = ''` condition or be the unpublish/unlink path. Plus behaviour tests: a tombstone under `apps/<sqid>/<linked app>/` and an expiry pass leave the linked row; reaping an account unlinks first.
- `TestLinkCannotTouchAnotherLinksApps`: link L1 cannot unpublish an app published by L2 in the same account.
-- [ ] **Step 2:** `go test ./internal/console -run 'Publish|Unpublish|Unlink|Rotate|LinkedPolicy|LinkedAppRefused|AnotherLinks|Parity'` — FAIL.
+- [ ] **Step 2:** `go test ./internal/console -run 'Publish|Unpublish|Unlink|Rotate|LinkedPolicy|LinkedAppRefused|AnotherLinks|Parity|EveryAppDelete|RouteDecls|AuthCLIFamily'` — FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** Same command — PASS.
- [ ] **Step 5:** Commit `console: link API, linked apps and the linked-app guard`.
@@ -258,10 +270,11 @@ Risk: authority, plan caps. Gets its own review.
- `GET /api/cli/link` → serving console, account, claimed box, the agent's tunnel `state`, and each published app with its URL.
- `POST /api/cli/link/publications {"account":"<home acct>","app":"<home app>","name":"<public name, default app>"}` → checks the home app exists, is an instance app (static refused with the deck string, slice 2) and has no password gate or admission hold (refused with deck strings; slice 1 does not carry those gates through a link), resolves its home host (the app's primary ready route), calls serving `POST /api/link/publications`, then `PutHomeLinkApp`.
- `DELETE /api/cli/link/publications/{name}` → `DeleteHomeLinkApp` **first**, then serving `DELETE /api/link/publications/{name}`.
- - `POST /api/cli/link/rotate`, `DELETE /api/cli/link` → serving calls, then update or `DeleteHomeLink`.
+ - `POST /api/cli/link/rotate`, `DELETE /api/cli/link` → serving calls, then update or `DeleteHomeLink`. `DELETE /api/cli/link?local=1` forgets the link at home (`DeleteHomeLink`) without calling the serving console: the recovery when the serving console refuses the home's credential (for example a rotate whose response was lost). The person then unlinks the stale link on the serving console (Task 6). Without `local=1`, a 401 from the serving console is reported with the deck string that names this recovery.
+ - Where the credential sits: `home_link.token` is in the registry file, which the agent already keeps out of every app's view (instances run with an explicit mount layout that excludes `/data`). Step 3 checks the registry file's mode is not world-readable and documents this beside the table definition.
- `type linkClient struct` in `linkclient.go` (pattern: `keymail.go:55-71`): base URL, bearer token, no redirects, 30 s timeout; methods `Start`, `Poll`, `Status`, `Publish`, `Unpublish`, `Rotate`, `Remove`.
-- [ ] **Step 1: Write failing tests:** `TestHomeLinkClaimOnce` (two labels race, exactly one wins), `TestHomeStartPollStores` (fake serving console from `newConsoleFixture`; approve; home registry has the link with token, account, tunnel URL), `TestHomeStartRefusesOldServingConsole` (a fake `/auth/cli/start` that ignores `purpose`), `TestHomePublishRefusesStatic`, `TestHomePublishRefusesGatedApp`, `TestHomeUnpublishDropsHomeSetFirst` (serving fake that records call order and asserts `HomeLinkApps()` no longer has the app when the DELETE arrives), `TestHomeLinkTokenNeverReturned` (no API response body contains the token).
+- [ ] **Step 1: Write failing tests:** `TestHomeLinkClaimOnce` (two labels race, exactly one wins), `TestHomeStartPollStores` (fake serving console from `newConsoleFixture`; approve; home registry has the link with token, account, tunnel URL), `TestHomeStartRefusesOldServingConsole` (a fake `/auth/cli/start` that ignores `purpose`), `TestHomePublishRefusesStatic`, `TestHomePublishRefusesGatedApp`, `TestHomeLostRotationRecovery` (serving fake answers 401; `remove` without `local` reports the recovery string; `remove --local` clears home state with no serving call), `TestHomeUnpublishDropsHomeSetFirst` (serving fake that records call order and asserts `HomeLinkApps()` no longer has the app when the DELETE arrives), `TestHomeLinkTokenNeverReturned` (no API response body contains the token).
- [ ] **Step 2:** `go test ./internal/registry ./internal/console -run 'HomeLink|HomeStart|HomePublish|HomeUnpublish'` — FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** PASS.
@@ -278,25 +291,26 @@ Risk: the anti-goal 1 guard. Gets its own review.
**Interfaces:**
- Consumes: Task 7's registry methods, `tunnelclient.Loop`, `tunnelclient.LinkAppHeader`, `(*Edge).OnReload` (`edge.go:1519`).
- Produces:
- - `func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, want LinkedTarget) bool` with `type LinkedTarget struct { Host, Account, App string }`. It:
- - looks up the **exact** upstream map entry for `want.Host` (never `lookupUpstream`/`lookupUpstreamPath`, `edge.go:1785, 1840`, which add wildcard and path-map targets);
- - admits it only when the entry's route has `Account == want.Account`, `App == want.App`, `Kind == "instance"`, `Status == "ready"`, and is a local socket or activator-owned backend; edge-owned static and status handlers (`edge.go:1193`) never qualify;
- - keeps these stages of the normal path, in this order: `admissionRefuses` (`edge.go:2134`, holds and imports), the password gate (`:2611`, defence in depth behind Task 7's publish refusal), `trackUpgrade` (`:2666`) for upgrades, then the activator (`act.ServeHTTP`) or the proxy, with `r.Host = want.Host`;
- - returns false, writing nothing, when the entry is missing or fails the admission check. It reaches no other edge surface (no ACME, purge, devbox, admin or health paths).
- - `type linkHandler struct { reg linkRegistry; serve func(w, r, LinkedTarget) bool; streams *linkStreams }` with `ServeHTTP`: reads `LinkAppHeader`; calls `reg.HomeLinkAppByName` **per request** (so an unpublish is refused from the next request, without waiting for a reload); missing header or not published → 404 with the deck string; `serve` returns false → 502 with the deck's "not on this box" string. It never uses the request's Host.
- - `type linkStreams struct` — tracks upgraded (WebSocket) connections per published name; on every reload the loop closes the streams of names no longer published, so open sockets end within one registry watch (2 s) at home, whatever the hub does.
- - `func linkLoop(e *edge.Edge, reg linkRegistry, label string)` — `label` is the agent's box label when it has one, else `os.Hostname()`. It writes the loop's state with `SetHomeLinkState` from `OnState`: on start and on every `OnReload`, reads `HomeLink()` and `HomeLinkApps()` (closing streams for names that disappeared); claims with `ClaimHomeLink(label)` when unclaimed; when the link exists and `box_label == label`, runs one `tunnelclient.Loop` with `Name = registry.LinkChannelName(id)`, `Token`, `URL = tunnel_url`, `Handler = linkHandler`; cancels it on unlink, rotation (token change) or loss of the claim. Never claims when `tunnelEnvComplete()` is true (a fleet box).
+ - **Pinned pipeline (Paul's choice 2).** `func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, want LinkedTarget)` with `type LinkedTarget struct { Host, Account, App, PublicHost string }`. It puts `want` on the request context (`withLinkPin`) and runs the edge's **normal** `ServeHTTP` path with `r.Host = want.Host`, so every stage a tailnet request to that host passes (admission, the import gate with its header strip, plan-disabled, the password gate, upgrade tracking, activator) runs unchanged. The pin changes exactly two things:
+ - **Upstream selection.** With a pin, selection uses only the exact upstream map entry for `want.Host` (never the wildcard or path-map targets of `lookupUpstream`/`lookupUpstreamPath`, `edge.go:1785, 1840`) and admits it only when its route has `Account == want.Account`, `App == want.App`, `Kind == "instance"` and a local socket or activator-owned backend. Anything else answers 502 with the deck's "not on this box" string. With a pin, every edge-owned path handler (ACME, purge, status, devbox, admin, edge-owned static at `edge.go:1193`) is skipped: the only possible outcomes are a stage's refusal or the pinned upstream.
+ - **What the app sees.** The proxy sends `Host: want.PublicHost` (the public hostname from the hub's `X-Forwarded-Host`) and keeps `X-Forwarded-Proto: https`, so same-origin checks and generated redirects use the public origin. Selection never reads either header.
+ - `type linkHandler struct { reg linkRegistry; serve func(w, r, LinkedTarget) }` with `ServeHTTP`: reads `LinkAppHeader`; calls `reg.HomeLinkAppByName` **per request** (so an unpublish is refused from the next request, without waiting for a reload); missing header or not published → 404 with the deck string; otherwise `serve` with the published account, app and host. It never selects by the request's Host.
+ - **Connection replacement (Paul's choice 3).** No per-stream tracking. When a reload shows that a published name has disappeared, the loop cancels the running `tunnelclient.Loop` and starts a new one, which ends every in-flight request and stream on the old connection (WebSockets, SSE, long downloads alike). Other published apps reconnect within about a second. Bound: an unpublished app's open streams end within one registry watch (2 s) plus the cancel.
+ - `func linkLoop(e *edge.Edge, reg linkRegistry, label string)` — `label` is the agent's box label when it has one, else `os.Hostname()`. It writes the loop's state with `SetHomeLinkState` from `OnState`: on start and on every `OnReload`, reads `HomeLink()` and `HomeLinkApps()` (replacing the connection when a name disappeared); claims with `ClaimHomeLink(label)` when unclaimed; when the link exists and `box_label == label`, runs one `tunnelclient.Loop` with `Name = registry.LinkChannelName(id)`, `Token`, `URL = tunnel_url`, `Handler = linkHandler`; cancels it on unlink, rotation (token change) or loss of the claim. Never claims when `tunnelEnvComplete()` is true (a fleet box).
- [ ] **Step 1: Write failing tests** (real registry in a temp dir, real `edge.New`, a real hub `TunnelHub` from Task 3, real `tunnelclient.Loop`, a Unix-socket test app; pattern `replicaTunnelFixture`):
- `TestLinkServesPublishedApp`: publish `shop` → request through the hub reaches the `shop` socket.
- `TestLinkRefusesUnpublished`: a second home app `admin` with a route on the same box; hub-side requests carrying `Carlos-Link-App: admin`, no header, and `Carlos-Link-App: shop` with `Host: admin...` → the first two get 404, the third reaches `shop`, and the `admin` socket sees zero requests.
- - `TestLinkUnpublishStopsServing`: with the home edge's reload paused, unpublish → the next request is 404 from home; an already-open WebSocket for that app is closed within one watch interval after reloads resume.
+ - `TestLinkUnpublishStopsServing`: with the home edge's reload paused, unpublish → the next request is 404 from home; an already-open WebSocket and an open SSE response for that app both end within one watch interval after reloads resume, and a request to another published app succeeds after the reconnect.
- `TestLinkHostReassigned`: publish `shop` (account a1, app shop, host H); re-point host H in the registry to app `admin` → requests naming `shop` get 502, `admin` sees none.
- `TestLinkIgnoresPathMapAndEdgeHandlers`: a `route_paths` prefix on H pointing at `admin`, and an edge-owned status handler host, are never reached through the link.
- `TestLinkGatedAppRefused`: a published app that later gains a password gate gets the gate's answer, not the app.
+ - `TestLinkImportGatedAppRefused`: a published app that later gains an import gate answers 503 through the link, and a client-sent `ImportVerifyHeader` is stripped.
+ - `TestLinkAppSeesPublicOrigin`: the backend sees `Host` equal to the public hostname and `X-Forwarded-Proto: https`; a backend enforcing `Origin == https://<Host>` accepts a WebSocket and a form POST.
+ - `TestLinkPinSkipsEdgeHandlers`: with a pin, `/.well-known/acme-challenge/x`, the edge's status path and a purge request reach the pinned app or a refusal, never the edge's own handler.
- `TestLinkLoopFollowsRegistry`: link added → loop dials within one reload; token rotated → redials with the new token; unlinked → loop stops.
- `TestFleetBoxNeverClaims`: with tunnel env complete, `ClaimHomeLink` is never called.
-- [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/host ./internal/edge -run 'TestLink|TestFleetBoxNeverClaims|ServeLinked'` — FAIL.
+- [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/host ./internal/edge -run 'TestLink|TestFleetBoxNeverClaims|ServeLinked|LinkPin'` — FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** PASS.
- [ ] **Step 5:** Commit `host: home link loop that serves only published apps`.
@@ -309,7 +323,7 @@ Risk: the anti-goal 1 guard. Gets its own review.
**Interfaces:**
- Consumes: Task 7's home API, Task 6's `GET /api/cli/links/{account}`.
-- Produces: `carlos link create --to <url> [--name <n>]` (prints the approval link and code, waits, prints the linked account), `carlos link status`, `carlos link publish <app> [--account <a>] [--name <n>]` (prints the public URL), `carlos link unpublish <name>`, `carlos link rotate`, `carlos link remove`. These talk to the home console (`--console` or `CARLOS_CONSOLE`, `resolveMode`). `carlos links ls --account <a>` talks to the serving console (default console). Registered with `raw(...)` like `fleetsCommand()`. Headings for `carlos link` and `carlos links` on the CLI reference page (`internal/docsite/cli_test.go:80` checks them), and the command projection/parity docs regenerated with the repo's generator.
+- Produces: `carlos link create --to <url> [--name <n>]` (prints the approval link and code, waits, prints the linked account), `carlos link status`, `carlos link publish <app> [--account <a>] [--name <n>]` (prints the public URL), `carlos link unpublish <name>`, `carlos link rotate`, `carlos link remove [--local]`. These talk to the home console (`--console` or `CARLOS_CONSOLE`, `resolveMode`). `carlos links ls --account <a>` talks to the serving console (default console). Registered with `raw(...)` like `fleetsCommand()`. Headings for `carlos link` and `carlos links` on the CLI reference page (`internal/docsite/cli_test.go:80` checks them), and the command projection/parity docs regenerated with the repo's generator.
- [ ] **Step 1: Write failing tests** with a fake console (`newFakeConsole` pattern): each command's request path, body and printed output (deck strings).
- [ ] **Step 2:** `go test . ./internal/docsite -run 'TestLink|TestCLI'` — FAIL.
@@ -322,7 +336,7 @@ Risk: the anti-goal 1 guard. Gets its own review.
**Files:**
- Create: `docs/site/linked-deployments.md` (user guide; humane-docs + copy review)
-- [ ] **Step 1:** Write the guide: link, publish, unpublish, what Carloku can and cannot reach, offline behaviour, and recovery when a rotate's response is lost (the home side then holds a revoked token: `carlos link remove` at home and `carlos link create` again).
+- [ ] **Step 1:** Write the guide: link, publish, unpublish, what Carloku can and cannot reach, offline behaviour, and recovery when a rotate's response is lost (the home side then holds a revoked token: `carlos link remove --local` at home, Unlink on the Carloku Fleet tab, then `carlos link create` again).
- [ ] **Step 2:** After merge and a dev release (Paul's go for the roll), link a single-box home deployment to the dev console and record on the branch discussion:
- the public URL serves the published app from outside the tailnet;
- an unpublished app on the same box is not reachable by any header or Host;
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R3.md b/docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R3.md
new file mode 100644
index 000000000..5a30daa91
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R3.md
@@ -0,0 +1,51 @@
+# Review brief: linked deployments slice 1 plan, round 3 of 3
+
+Repo carlos/platform, branch `design-linked-deployments`, commit named in the reviewer's prompt.
+Under review: `docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md`.
+Authorities: the spec `docs/superpowers/specs/2026-11-10-linked-deployments-design.md` rev 3 on this branch (approved by Paul 2026-11-10; it travels with this plan), and the code on main at this branch's base. Specs merged on main for the pieces it reuses: `docs/superpowers/specs/2026-10-29-fleet-public-routes-design.md`, `docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md`.
+
+You are an independent reviewer. Read the plan and the spec, then the code the plan names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's rulings in the spec: a peer link, not a fleet; anyone with the link can use a published app (no access control); no fallback to a Carloku standby; data stays at home; Carloku shows only that the link exists, whether it is reachable and what it serves, plus Unlink.
+- The spec's designer calls (§6.0 linked app rows, §6.2 channel naming and forward rows placed `link/<id>`, §6.3 enforce by published app, §6.6 no caching for linked dynamic apps, §6.8 hub-only serving accepted, one box per link). Report only mechanisms that fail to honour them.
+
+## What to check
+
+1. **Anti-goal 1 (Carloku reaches only published apps).** Does Task 8's `ServeLinked` plus `linkHandler` really reach nothing but published apps' upstreams? Name any edge surface the plan's `ServeLinked` would still expose, and any way the hub or a client can steer the home side to an unpublished host.
+2. **Link credential containment.** Can a link token pass any existing gate: store door, `fleetIdentityOK` callers, `/register` under a fleet name, `cliGateRefused`, `serviceBinding`, person-only doors? Is Task 4's route walk test able to catch a new route added later?
+3. **Forward-row reuse.** Every consumer of `IsForward()` / `FleetPlacement()` (grep `internal/provision`, `internal/domains`, `internal/edge`, `internal/activator`, `internal/dbreads`): does any of them mishandle a forward row whose Region is `link/<id>` (delete it, mint for it, treat it as local, crash)? Task 2 covers retirement and domains; find what it misses.
+4. **Revocation.** Rotate and unlink with a live tunnel: does the plan's `SetDynamicAuth` change plus `PutLinkChannel`/`RevokeLinkChannel` close the channel and refuse redial? Any window where the old token still serves?
+5. **Interfaces.** Do names, signatures and types agree across tasks (registry methods used by console, edge and host; `consoleRegistry` and `remote_dispatch.go` additions; `FleetServeEligible`'s new signature at all call sites)?
+6. **Feasibility.** Anything that would not compile or work as described, or a step an implementer could not carry out from the plan plus the code.
+
+## Round 3 (the last)
+
+Earlier rounds: round 1 `docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md` (both NOT READY); round 2 `docs/superpowers/reviews/linked-deployments-slice1-plan-R2.md` (Astra NOT READY, Fable READY AFTER FIXES). Three round-2 P1s recurred in round-1 fault families; Paul ruled on 2026-11-10 (amadan discussion 812) and rev 3 implements his three choices. Treat them as fixed design, under "Fixed" above:
+
+- one writer for link channel state (`syncLinkChannel`, generations, revoked is terminal);
+- linked requests run the normal edge pipeline with a pinned upstream, and the app sees the public Host;
+- unpublish at home replaces the whole link connection.
+
+Report only mechanisms that fail to honour them, not the choices themselves.
+
+First give one line per P1 and P2 from round 2 (both reviewers' lists): resolved, partly, or not. Carry every unresolved or partly resolved finding forward at its current severity, then add new findings. The verdict covers everything outstanding. In round 3, a NOT READY also says whether the P1s share one cause, and whether refusing the case up front or cutting the feature would remove them.
+
+## 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. (The census, and review of any newly changed security, root, termination or production-storage behaviour, still check the fix; see AGENTS.md, "Stopping rules".)
+- **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 section or task, the problem, the evidence (file:line, verified), the failure scenario, a concrete fix and the invariant or trust boundary it breaks (that is its fault family). Keep it under 1500 words. 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.