carlos / platform Public

plan: linked deployments slice 1 rev 2 after round 1 reviews

Fixes Astra and Fable round-1 P1s and P2s: https tunnel URL, every
FleetArmVerdict caller, disjoint forward classes, per-request home
publication check by account and app, one linked-app policy for browser
and CLI, parity and docsite gates, token lifecycle, WebSocket tenancy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev aac497dcafcf2ff4611f5442063e4350a045a6c0 parent 4b88eea
4 files changed, +226 −39
  • docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md +72 −38
  • docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R2.md +45 −0
  • docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md +108 −0
  • docs/superpowers/specs/2026-11-10-linked-deployments-design.md +1 −1

CI passed — 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 135822530..a9ab86e82 100644
--- a/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md
+++ b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md
@@ -18,7 +18,9 @@
- Hub-set header naming the published app: `Carlos-Link-App`. Stripped from every inbound client request and set only by the hub on requests going down a link channel.
- 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 `remote_dispatch.go` when the agent uses them through `OpenRemote`.
+- 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`).
- 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).
@@ -28,7 +30,7 @@
## Review Focus
1. **A link credential used anywhere but its own doors.** A link token presented to the store door, the replica coordinator, interactive/run/demo box doors, any `/api/cli/` route, or `/register` under another name must be refused. Tests in Tasks 3 and 4.
-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: the home handler must refuse each without touching an instance. Test in Task 8.
+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.
@@ -57,7 +59,7 @@ Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appear
**Files:**
- Create: `internal/registry/links.go`, `internal/registry/links_test.go`
-- Modify: `internal/registry/registry.go` (migrate chain after `migrateHADuties`; `Fingerprint` section), `internal/registry/forward.go:363-371` (accept link placement), `internal/host/remote_dispatch.go`, `internal/console/view.go:522`
+- Modify: `internal/registry/registry.go` (migrate chain after `migrateHADuties`; `Fingerprint` section), `internal/registry/forward.go:363-371` (accept link placement), `internal/registry/remote_dispatch.go`, `internal/console/view.go:522`
**Interfaces:**
- Produces:
@@ -72,17 +74,22 @@ Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appear
- `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.
+ - `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) 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.
-Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL, rev INTEGER NOT NULL DEFAULT 0, connected INTEGER NOT NULL DEFAULT 0, seen_at INTEGER NOT NULL DEFAULT 0)`.
+Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL, rev INTEGER NOT NULL DEFAULT 0, connected INTEGER NOT NULL DEFAULT 0, seen_at INTEGER NOT NULL DEFAULT 0, seq INTEGER NOT NULL DEFAULT 0)`.
- [ ] **Step 1: Write failing tests** in `links_test.go`:
- `TestLinkChannelNameNeverAFleet`: for 2,000 random `ValidTunnelName` strings `f` and labels, `LinkOfChannel(f+"/"+l)` is false; `LinkOfChannel(LinkChannelName(id))` round-trips for valid IDs; `LinkPlacement("fleet/x")` and `LinkPlacement("link/NOTHEX")` are false.
- `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'` — FAIL (undefined).
-- [ ] **Step 3:** Implement `links.go`, the migration, the `PutForward` placement check, the Fingerprint section, and the `consoleRegistry` / `remote_dispatch.go` entries for `PutLinkChannel`, `RevokeLinkChannel`, `LinkChannelAuth`, `LinkOwners`, `SetLinkSeen`, `LinkSeen`, plus the home-side methods of Task 7 when that task lands.
+- [ ] **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.
+- [ ] **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`.
@@ -100,7 +107,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. Confirm `decideForward` cannot write over a link host (a bucket record with the same host is refused as host-held, through `PutForward`'s existing `ErrHostHeld`/kind checks; add the assertion to the first test).
+- [ ] **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 4:** Same command — PASS.
- [ ] **Step 5:** Commit `provision: keep link forward rows out of the retirement pass`.
@@ -109,7 +116,7 @@ Table `link_channels(link_id TEXT PRIMARY KEY, account TEXT NOT NULL, token_hash
Risk: security gate and production serving path. Gets its own review.
**Files:**
-- Modify: `internal/edge/edge.go` (Reload ~956-1053, ~1433; `fleetProxy` ~4057-4072; inbound strip ~2120; `scrubTunnelMarkers` ~3984), `internal/edge/fleetforward.go:57-115, 261`, `internal/edge/tunnel.go:391` (`SetDynamicAuth`), `internal/edge/storedoor.go:169-205`, `internal/console/apiinteractivebox.go:117`
+- Modify: `internal/edge/edge.go` (Reload ~956-1053, ~1433; `fleetProxy` ~4057-4072; inbound strip ~2120; `scrubTunnelMarkers` ~3984; upgrade admission ~2687), `internal/edge/upgrades.go:210` (tenancy match), `internal/edge/fleetforward.go:117-176, 230, 261-286`, `internal/edge/tunnel.go` (`VerifyDynamic` :334-352, `ServeHTTP` :165-274, `SetDynamicAuth` :391), `internal/edge/storedoor.go:169-205`, `internal/console/apiinteractivebox.go:117`, and every `FleetArmVerdict` caller: `internal/host/hub.go:26-36, 72` (`fleetArmInputs`), `internal/host/edgesfile.go:649`, `internal/console/apiinstances.go:429`
- Create: `internal/edge/linkforward.go`, `internal/edge/linkoffline.go`
- Test: `internal/edge/link_e2e_test.go`, `internal/edge/linkforward_test.go`, `internal/console/fleetidentity_link_test.go`
@@ -117,10 +124,16 @@ Risk: security gate and production serving path. Gets its own review.
- Consumes: Task 1's registry methods.
- Produces:
- `const LinkAppHeader = "Carlos-Link-App"` (in `internal/tunnelclient` beside `UpgradeHeader`, so the home side shares it).
- - `FleetServeEligible` and `FleetArmVerdict` take link owners too: signature becomes `FleetServeEligible(rt registry.Route, hub bool, owners, linkOwners map[string]string) (ok bool, why string)`. A link row is eligible iff hub, `InertForward()`, `LinkPlacement` ok, and `rt.Account != "" && rt.Account == linkOwners[id]`. One function judges both kinds.
+ - `type ForwardOwners struct { Fleets, Links map[string]string }` replaces the bare owners map in both judges:
+ - `FleetServeEligible(rt registry.Route, hub bool, owners ForwardOwners) (ok bool, why string)`. A link row is eligible iff hub, `InertForward()`, `LinkPlacement` ok, and `rt.Account != "" && rt.Account == owners.Links[id]`. One function judges both kinds.
+ - `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.
+ - 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.
- - On link channel state change the hub calls `reg.SetLinkSeen` (connect and disconnect only, not per request).
+ - The hub calls `reg.ResetLinkSeen()` once when tunnels are enabled, then `reg.SetLinkSeen(id, seq, connected, now)` on each link channel's register and close (not per request). `seq` is the hub's per-registration sequence already used to tell a replaced connection from the current one (`tunnel.go:269-276`); add one if none is exposed.
- [ ] **Step 1: Write failing tests:**
- `TestLinkEndToEnd` (pattern: `TestTunnelEndToEnd`, `startFakeRemoteHost`): registry with a link channel and a link forward row for `shop.acct1.apps.example.com`; hub-armed edge; fake home dials `link:<id>/home` with the token; `GET https://shop.acct1.apps.example.com/up` returns the home handler's body, and the handler saw `Carlos-Link-App: shop`.
@@ -131,8 +144,11 @@ Risk: security gate and production serving path. Gets its own review.
- `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`.
- - `TestLinkSeenRecorded`: connect then disconnect flips `LinkSeen()[id].Connected`.
-- [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/edge ./internal/console -run 'Link|FleetIdentityRefusesLink'` — FAIL.
+ - `TestLinkSeenRecorded`: connect then disconnect flips `LinkSeen()[id].Connected`; a re-register (second connection with the same name) leaves it connected after the first connection closes.
+ - `TestLinkWebSocket`: a WebSocket upgrade through the link reaches the home handler and echoes; after `RevokeLinkChannel` and a reload the socket is closed.
+ - `TestVerifyDynamicRefusesLinks`: `VerifyDynamic("link:<id>/home", token)` is false even with the right token; `verifyLink` accepts it.
+ - `TestLinkHostsPublishedForBackhaul` (`internal/host`): the edges file built from a registry with an eligible link row lists the link host for the hub, as for a fleet row.
+- [ ] **Step 2:** `TMPDIR=/tmp/g go test ./internal/edge ./internal/console ./internal/host -run 'Link|FleetIdentityRefusesLink|VerifyDynamicRefusesLinks'` — FAIL.
- [ ] **Step 3:** Implement. In Reload, merge `LinkChannelAuth()` into the map passed to `SetDynamicAuth`, load `LinkOwners()` beside `FleetOwners()`, arm link rows with `linkProxy`. In the store door, refuse when `registry.LinkOfChannel(name)` is ok before `fleetAccount`. In `fleetIdentityOK`, refuse link channel names first. The offline page follows `internal/edge/plandisabled.go`'s pattern (template built once, `no-store`, `noindex`) with `Retry-After: 30`; `noteCause` stays `apperr.CauseFleetDark`.
- [ ] **Step 4:** Same command — PASS. Then `go test ./internal/edge -run 'Fleet|Tunnel|Upgrade'` to check fleet behaviour is unchanged.
- [ ] **Step 5:** Commit `edge: serve link forward rows down link channels, with an offline page`.
@@ -151,14 +167,17 @@ Risk: authority. Gets its own review.
- `type Link struct { ID string; AccountID int64; Name, CreatedBy string; CreatedAt, RevokedAt time.Time }`
- `func (s *Store) LinkByID(id string) (*Link, error)`, `func (s *Store) LinksForAccount(accountID int64) ([]Link, error)`
- `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.
+ - `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"})`. The poll response for a link adds `link_id`, `account` (sqid), `tunnel_url` (`wss://` + `TunnelHost` + `/register`) 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; 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`.
+ - 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.
- [ ] **Step 1: Write failing tests** (`newConsoleFixture`, `cliToken` helpers):
- - `TestLinkApprovalMintsLinkToken`: start with purpose link → approve for account A with step-up → poll returns token, `link_id`, `account`, `tunnel_url`; `CLIPrincipal(token)` is `PrincipalLink` for A; registry `LinkOwners()[link_id] == A.Sqid`; `LinkChannelAuth()` holds sha256(token).
+ - `TestLinkApprovalMintsLinkToken`: start with purpose link → approve for account A with step-up → poll returns token, `link_id`, `account`, `tunnel_url`; `CLIPrincipal(token)` is `PrincipalLink` for A; registry `LinkOwners()[link_id] == A.Sqid`; `LinkChannelAuth()` holds sha256(token); `tunnelclient.Dial` accepts the returned `tunnel_url`'s scheme against an `httptest` TLS hub.
+ - `TestLinkTokenLifecycle`: the token has `expires_at = 0`, survives the purge with the clock advanced past `CLITokenTTL`, does not appear in `CLITokens(address)`, and is not revoked by `RevokeCLIToken` or `RevokeAccountToken`.
- `TestLinkApprovalNeedsCreateRole`: an approver without the create role does not see account A in the picker and a forged POST naming A is refused.
- - `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). Build the path from the declared pattern with `acct`/`app`/`host` filled in.
+ - `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.
@@ -171,26 +190,31 @@ Risk: authority, plan caps. Gets its own review.
**Files:**
- Create: `internal/console/apilinks.go`, `internal/console/apilinks_test.go`
-- Modify: `internal/console/routedecls.go` (new routes), `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`)
+- 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`)
**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):
- `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 (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})`.
- - `DELETE /api/link/publications/{app}` → 204. Deletes the forward row first, then the `apps` row (only where `linked_link_id` = this link).
+ - `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: every publication deleted as above, token revoked, `RevokeLinkChannel`, `links.revoked_at` set.
- - `func linkedAppRefusal(acct *Account, app string) *doorRefusal` consulted by `apiAccountAppSaying` for **every** method (not only mutations), returning 409 with the deck's "managed by its home deployment" string.
+ - `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.
+ - **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`).
- [ ] **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>`.
- `TestPublishRefusesTakenName`, `TestPublishRespectsCap` (cap fixture at the limit → `{"code":"cap"}`).
- `TestUnpublishRemovesRowThenApp`, `TestUnlinkRemovesEverything` (two publications, then unlink: no rows, no apps, link token refused by `CLIPrincipal`, `LinkChannelAuth` empty).
- `TestRotateReplacesHash`: old token refused, new token works, registry hash changed.
- - `TestLinkedAppRefusedOnAppRoutes`: walk `routeDecls`; every route whose pattern contains `{app}` and reaches `apiAccountAppSaying` refuses a linked app with 409 and the deck string, for GET and non-GET alike. The test fails on any such route that does not consult the guard.
+ - `TestLinkedPolicyCoversEveryAppRoute`: walk `routeDecls`; every route whose pattern contains `{app}` (under `/api/cli/` and `/a/{sqid}/apps/{app}` alike) must have an entry in `linkedAppPolicy`'s table. The test fails on any unclassified route, independently of which helper the handler uses.
+ - `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.
- `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|LinkedAppRefused|AnotherLinks'` — FAIL.
+- [ ] **Step 2:** `go test ./internal/console -run 'Publish|Unpublish|Unlink|Rotate|LinkedPolicy|LinkedAppRefused|AnotherLinks|Parity'` — FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** Same command — PASS.
- [ ] **Step 5:** Commit `console: link API, linked apps and the linked-app guard`.
@@ -206,7 +230,8 @@ Risk: authority, plan caps. Gets its own review.
- `type accountLinkCard struct { ID, Name, CreatedBy string; CreatedAt time.Time; Reachable bool; LastSeen time.Time; Apps []accountLinkApp }`, `type accountLinkApp struct { Name, URL string }`. Reachability from `reg.LinkSeen()`.
- Page field `AccountLinks []accountLinkCard`.
- `POST /a/{sqid}/links/{id}/unlink` (browser, same role as fleet detach, CSRF as the existing fleet POSTs) and `GET /api/cli/links/{account}`, `DELETE /api/cli/links/{account}/{id}` (person CLI). Unlink shares one function with Task 5's `DELETE /api/link`: `func (s *Server) unlink(ctx context.Context, l *Link, by string) error`.
- - The apps list marks linked apps with the deck's "served from <home name>" label.
+ - The apps list marks linked apps with the deck's "served from <home name>" label. The Fleet tab's platform-app count (`accountfleet.go:144`) and `regionlabel.ForRoute` both treat a `link/<id>` row as linked, not as a platform app or a region code.
+ - Parity rows for the new routes.
- [ ] **Step 1: Write failing tests:** `TestFleetTabShowsLinkedDeployments` (name, reachable state from a `SetLinkSeen` fixture, both published apps with URLs; empty state when none), `TestUnlinkFromConsole` (POST removes everything, as `TestUnlinkRemovesEverything`), `TestLinksListCLI`.
- [ ] **Step 2:** `go test ./internal/console -run 'LinkedDeployments|UnlinkFromConsole|LinksListCLI'` — FAIL.
@@ -218,24 +243,25 @@ Risk: authority, plan caps. Gets its own review.
**Files:**
- Create: `internal/registry/homelink.go` (+ test), `internal/console/homelink.go`, `internal/console/linkclient.go`, `internal/console/homelink_test.go`
-- Modify: `internal/console/routedecls.go`, `internal/registry/registry.go` (migrate, Fingerprint), `internal/host/remote_dispatch.go`, `internal/console/view.go:522`
+- Modify: `internal/console/routedecls.go` and the parity table, `internal/registry/registry.go` (migrate, Fingerprint), `internal/registry/remote_dispatch.go`, `internal/console/view.go:522`
**Interfaces:**
- Produces (registry, home side):
- Table `home_link(id TEXT PRIMARY KEY, serving_url TEXT, tunnel_url TEXT, token TEXT, account TEXT, apps_domain TEXT, box_label TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT '', created_at INTEGER)` — at most one row in slice 1. `state` (`connected` | `reconnecting` | ``) is written by the claiming agent and excluded from `Fingerprint`.
- `func (r *Registry) SetHomeLinkState(state string) error`
- - Table `home_link_apps(name TEXT PRIMARY KEY, home_host TEXT NOT NULL, created_at INTEGER)` — the published set; `name` is the serving-side app name.
- - `func (r *Registry) HomeLink() (*HomeLink, error)` (nil when unlinked), `PutHomeLink(HomeLink) error`, `DeleteHomeLink() error` (also clears `home_link_apps`), `ClaimHomeLink(label string) (bool, error)` (conditional update where `box_label = ''`), `HomeLinkApps() (map[string]string, error)` (name → home host), `PutHomeLinkApp(name, homeHost string) error`, `DeleteHomeLinkApp(name string) (bool, error)`.
+ - Table `home_link_apps(name TEXT PRIMARY KEY, home_account TEXT NOT NULL, home_app TEXT NOT NULL, home_host TEXT NOT NULL, created_at INTEGER)` — the published set; `name` is the serving-side app name. `home_account`/`home_app` are the authority; `home_host` is where to find the route.
+ - `type HomeLinkApp struct { Name, HomeAccount, HomeApp, HomeHost string }`
+ - `func (r *Registry) HomeLink() (*HomeLink, error)` (nil when unlinked), `PutHomeLink(HomeLink) error`, `DeleteHomeLink() error` (also clears `home_link_apps`), `ClaimHomeLink(label string) (bool, error)` (conditional update where `box_label = ''`), `HomeLinkApps() ([]HomeLinkApp, error)`, `HomeLinkAppByName(name string) (*HomeLinkApp, error)` (nil when not published; read on **every** link request, Task 8), `PutHomeLinkApp(a HomeLinkApp) error`, `DeleteHomeLinkApp(name string) (bool, error)`.
- The `token` column is never returned by any console API and never logged.
- Produces (console, home side; system-operator gate, the one `carlos system` commands use):
- - `POST /api/cli/link/start {"to":"<serving console URL>","name":"<home name>"}` → calls the serving `/auth/cli/start` with purpose link; returns `{"verification_uri","user_code"}`; the home console polls the serving console in the background until approved, denied or expired, then `PutHomeLink`.
+ - `POST /api/cli/link/start {"to":"<serving console URL>","name":"<home name>"}` → calls the serving `/auth/cli/start` with purpose link and refuses (deck string) when the response does not echo `"purpose":"link"`, and later when the poll's approved response lacks `link_id` or `tunnel_url`; returns `{"verification_uri","user_code"}`; the home console polls the serving console in the background until approved, denied or expired, then `PutHomeLink`.
- `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 and is not static (static refused with the deck string, slice 2), resolves its home host (the app's primary ready route), calls serving `POST /api/link/publications`, then `PutHomeLinkApp`.
+ - `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`.
- `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), `TestHomePublishRefusesStatic`, `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`, `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.
@@ -252,14 +278,22 @@ 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, host string) bool` — serves the request to the exact registry host's upstream, through the activator when the route is activator-owned (the dispatch tail at `edge.go:2690-2696`), with `r.Host = host`. Returns false, writing nothing, when the host has no ready local upstream. It reaches no other edge surface (no ACME, purge, devbox, admin or health paths).
- - `type linkHandler struct { apps atomic.Pointer[map[string]string]; serve func(w, r, host string) bool }` with `ServeHTTP`: reads `LinkAppHeader`; missing, or naming no app in `apps` → 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.
- - `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()`; 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).
+ - `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).
- [ ] **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`: unpublish → next request 404 from home even before the hub reloads.
+ - `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.
+ - `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.
- `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.
@@ -275,10 +309,10 @@ 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()`.
+- 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.
- [ ] **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 . -run 'TestLink'` — FAIL.
+- [ ] **Step 2:** `go test . ./internal/docsite -run 'TestLink|TestCLI'` — FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** PASS. Also the CLI registry golden test if `Golden` is set on the new nodes.
- [ ] **Step 5:** Commit `cli: carlos link and carlos links`.
@@ -288,7 +322,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.
+- [ ] **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 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-R2.md b/docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R2.md
new file mode 100644
index 000000000..bd89275be
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-linked-deployments-slice1-plan-R2.md
@@ -0,0 +1,45 @@
+# Review brief: linked deployments slice 1 plan, round 2 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 2
+
+Earlier rounds: round 1, `docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md` (Astra and Fable, both NOT READY). The round number counts every earlier review of this plan, under any file name or reviewer.
+
+First give one line per P1 and P2 from round 1 (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, earlier rounds included. This is round 2 of 3: under AGENTS.md rule 2, if a new finding is in the same fault family as a round-1 finding, name the family explicitly.
+
+## 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.
diff --git a/docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md b/docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md
new file mode 100644
index 000000000..e96421560
--- /dev/null
+++ b/docs/superpowers/reviews/linked-deployments-slice1-plan-R1.md
@@ -0,0 +1,108 @@
+# Linked deployments slice 1 plan, round 1 findings
+
+Plan commit 4b88eeaf. Both reviewers NOT READY. Rev 2 of the plan addresses every P1 and P2 below; P3s were folded in where cheap.
+
+## Astra (gpt-6-astra, high)
+
+1. **P1 — Tasks 7–8: publication authorization is stored as a hostname, not an app identity.** `home_link_apps` retains only `name → home_host`, and `ServeLinked` receives only that host ([plan:227](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:227), [plan:255](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:255)). Registry upserts can replace the host’s app, kind and backend ([registry.go:1585](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/registry/registry.go:1585)). After reassignment, requests naming the old publication reach the new, unpublished app. The upstream map also contains edge-owned static and status handlers ([edge.go:1193](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/edge/edge.go:1193)); mere map membership is insufficient. **Fix:** retain the published home account/app identity and validate it against the selected route on every request, positively admitting only supported local instance backends. Test host reassignment and edge-owned handlers. **Fault family:** published-app identity must bound home access.
+
+2. **P1 — Tasks 7–8: deleting the publication does not immediately revoke home serving.** Unpublish deletes the registry entry before contacting the hub, but `linkHandler` reads an atomic snapshot refreshed only on reload ([plan:234](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:234), [plan:256](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:256)). The watcher polls every two seconds ([edge.go:3545](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/edge/edge.go:3545)). Requests therefore still pass after deletion and during the serving-console call. Existing WebSockets never re-enter the handler; the existing upgrade sweep belongs to the hub ([upgrades.go:259](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/edge/upgrades.go:259)). A misbehaving hub can retain those streams. **Fix:** synchronously revoke home admission before the outbound DELETE and cancel streams belonging to the publication. Test with home reload paused and an already-open WebSocket. **Fault family:** publication revocation must be enforced at home.
+
+3. **P1 — Task 2: the claimed forward-row collision protection does not exist.** The plan says existing `ErrHostHeld` checks prevent overwriting a link row ([plan:103](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:103)). In fact, `mint` accepts an existing forward row ([forward.go:288](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/provision/forward.go:288)), and `PutForward` rejects other **kinds**, then overwrites an ordinary forward row’s account, app and region ([forward.go:401](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/registry/forward.go:401), [forward.go:299](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/registry/forward.go:299)). A fleet record naming the publication host replaces the link route; the proposed test fails. `DeleteForward` likewise checks only host and kind ([forward.go:435](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/registry/forward.go:435)). **Fix:** enforce fleet/link ownership separation atomically in both writes and deletes, including expected link identity for publication deletion. **Fault family:** reconciler ownership must remain disjoint.
+
+4. **P1 — Task 5: the linked-app guard blocks required features and misses forbidden mutations.** Guarding every `apiAccountAppSaying` call ([plan:184](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:184)) rejects analytics: `handleAPIAnalytics` uses `instanceGate`, which calls that resolver ([apianalytics.go:51](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/apianalytics.go:51), [apiinstances.go:121](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/apiinstances.go:121)). Meanwhile browser promote and environment handlers use `accountApp`, outside the proposed guard ([server.go:5648](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/server.go:5648), [envform.go:722](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/envform.go:722)). The proposed test excludes routes that do not already reach the guarded resolver. **Fix:** enumerate permitted and forbidden operations across browser and CLI routes, apply one shared linked-app policy, and test coverage independently of existing helper usage. Preserve analytics/protection/usage; refuse code/config operations and slice-1 custom-domain attachment. **Fault family:** serving-side app authority.
+
+5. **P1 — Tasks 4 and 8: the registration URL cannot be dialled.** Task 4 returns `wss://…/register` ([plan:156](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:156)); Task 8 passes it directly to `tunnelclient.Loop`. `Dial` accepts only `https` and `http`, returning “unsupported scheme” otherwise ([tunnelclient.go:204](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/tunnelclient/tunnelclient.go:204)). Every real link remains disconnected. **Fix:** return an `https` registration URL and test the actual approval response through the actual dialler. **Fault family:** registration protocol compatibility.
+
+6. **P1 — Tasks 1, 3 and 5: required interface propagation is incomplete.** Task 5 calls `reg.PutForward`, but `consoleRegistry` exposes neither `PutForward` nor `DeleteForward` ([view.go:522](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/view.go:522)); Task 1’s explicit additions omit both. The changed `FleetArmVerdict` signature also has production callers outside Task 3’s file list: [edgesfile.go:649](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/host/edgesfile.go:649), [hub.go:72](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/host/hub.go:72), and [apiinstances.go:429](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/apiinstances.go:429). Leaving these unchanged fails compilation; passing empty link owners would withhold link hosts from backhaul publication. **Fix:** specify every caller’s ownership inputs and update interfaces, implementations and fixtures. Correct the dispatcher path to `internal/registry/remote_dispatch.go`; the named host path does not exist. **Fault family:** shared routing-interface consistency.
+
+7. **P1 — Tasks 5–10: the planned changes fail mandatory parity/documentation gates.** New console routes require parity entries ([parity_test.go:48](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/parity_test.go:48)); new top-level CLI commands require headings on the CLI reference page ([cli_test.go:80](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/docsite/cli_test.go:80)). Task 10 adds only a standalone guide ([plan:286](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:286)). **Fix:** add the parity rows, regenerate the command projection/parity documentation, add `link` and `links` reference headings, and run the targeted parity/docsite checks. **Fault family:** declared public-interface completeness.
+
+8. **P2 — Tasks 4/7 and self-review: unsupported serving consoles are not safely identified.** The version-floor argument relies on eventual tunnel refusal ([plan:303](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md:303)). Existing `/auth/cli/start` accepts only `label` through a decoder that ignores unknown fields ([authcli.go:762](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/authcli.go:762), [authcli.go:647](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/authcli.go:647)). Sending `purpose: link` to it starts an ordinary user login. **Fix:** require an explicit link capability/purpose acknowledgement before presenting approval, validate the poll response, and test an old serving console. **Fault family:** credential-kind negotiation must not silently widen authority.
+
+9. **P2 — Tasks 3–4: complete the credential-containment proof.** Merging link hashes into dynamic auth makes `VerifyDynamic` return `link:<id>` as a fleet ([tunnel.go:343](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/edge/tunnel.go:343)), contrary to the spec’s explicit refusal requirement. The proposed store-door refusal protects that caller but leaves the helper’s contract wrong. Also, the route-walk test needs gate-aware fixtures: declarations have configuration gates and placeholders beyond `acct/app/host` ([routedecls.go:35](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/routedecls.go:35), [routedecls.go:456](/home/paulca/.cache/tmp/claude-1001/design-linked-deployments/internal/console/routedecls.go:456)). **Fix:** separate channel authentication from fleet-identity verification, explicitly exclude links from fleet helpers, and exercise every declared gate/route with valid request fixtures and positive registration controls. **Fault family:** link credentials must never become fleet or person authority.
+
+NOT READY
+
+## Fable 5.2
+
+## P1
+
+**1. Task 4: `tunnel_url` uses a scheme the dialer refuses.**
+- Problem: the poll response sets `tunnel_url` to `wss://` + `TunnelHost` + `/register`, and Task 8 passes it as `tunnelclient.Config.URL`.
+- Evidence: `internal/tunnelclient/tunnelclient.go:204-220` accepts only `https` and `http`; anything else returns `unsupported scheme`.
+- Failure: every home dial fails and backs off forever, so no link ever connects. Task 8's tests build their own hub URL and would not catch it.
+- Fix: use `https://<TunnelHost>/register`, and have `TestLinkApprovalMintsLinkToken` pass the returned URL to `tunnelclient.Dial`.
+- Family: interface contract between tasks.
+
+**2. Task 3: `FleetArmVerdict` changes are under-specified and miss three callers.**
+- Problem: the plan gives a new signature for `FleetServeEligible` only and lists only `fleetforward.go` and `edge.go`.
+- Evidence:
+ - `FleetArmVerdict` is also called at `internal/host/hub.go:72` (alias pass), `internal/host/edgesfile.go:649` and `internal/console/apiinstances.go:429`.
+ - `fleetArmInputs` (`hub.go:26-36`) returns fleet owners only.
+ - `fleetforward.go:284-286` fills `Arm` only for a `FleetPlacement`; `DispatchArm` (`:172-176`) returns `ArmNone` for a forward row not in `Arm`.
+ - `FleetServed` (`:230`) has no link field.
+- Failure: `internal/host` and `internal/console` do not compile. If the callers pass nil link owners, link hosts are withheld from the edges file (`edgesfile.go:650-653`), so other edges cannot backhaul to the hub. Even on the hub, an eligible link row gets no map entry.
+- Fix: state `FleetArmVerdict`'s new signature, extend `fleetArmInputs` with `LinkOwners()`, add a link field to `FleetServed` and `Arm`, and list all four call sites.
+- Family: one verdict, three readers.
+
+## P2
+
+**3. Task 2 step 3: the "host-held" claim is false.**
+- Evidence: `mint` (`internal/provision/forward.go:291-302`) treats only non-forward rows as held, and `putForwardSQL` (`internal/registry/forward.go:346`) overwrites any `kind='forward'` row.
+- Failure: a fleet record naming a link host rewrites the link row to `fleet/<x>`, so the planned assertion fails. The console's `PutForward` can likewise overwrite a fleet forward row.
+- Fix: `PutForward` returns `ErrHostHeld` when the stored row's placement class (link or fleet) differs; `mint` reports it as held.
+- Family: forward-row ownership.
+
+**4. Task 5: the linked-app guard misses the browser doors and over-blocks reads.**
+- Evidence: the guard lives in `apiAccountAppSaying` (`internal/console/apicli.go:69`). Browser doors at `routedecls.go:225-280` (restart, promote, rollback, environments) never reach it.
+- Failure: any browser door that deletes, renames or transfers the app leaves a forward row that Task 2 exempts from retirement. It keeps serving outside the cap, and Unlink misses it because Unlink enumerates `apps` rows (anti-goal 3).
+- Second problem: refusing every GET contradicts spec §5.4 and §6.0, which promise analytics, protection and usage for linked apps.
+- Fix: guard the browser app resolver too, and extend the walk to `/a/{sqid}/apps/{app}` patterns. Allow-list the read surfaces the spec keeps. Have unlink delete forward rows by `Region == link/<id>` from the registry.
+- Family: one guard, every app door.
+
+**5. Task 4: the link token row's lifecycle is unspecified.**
+- Expiry: `PollCLIAuth` stamps `now+CLITokenTTL` (`authstore.go:587-590`) and the purge deletes expired rows (`:478`). If inherited, the link API dies at day 90 while the registry hash stays active: the tunnel serves but home cannot unpublish or rotate.
+- Side doors: `CLITokens(address)` lists every kind (`:718-720`), `RevokeCLIToken` deletes by hash and address (`:763`), and `RevokeAccountToken` has no kind filter (`svcprincipal.go:534`). Each kills the row without `RevokeLinkChannel`, so the channel and forward rows outlive the revocation.
+- Fix: `expires_at = 0`; exclude `kind='link'` from those listings and revokes, or route them through `unlink`. Test both.
+- Family: revocation completeness.
+
+**6. Task 8: `ServeLinked` and the published set do not fully hold anti-goal 1.**
+- `home_link_apps` stores `name → home_host` only. If that host is later reassigned to another home app, Carloku reaches an app nobody published. Fix: store the home account and app, and have `ServeLinked` require the route's `Account` and `App` to match.
+- The cited "dispatch tail" `edge.go:2690-2696` is the upgrade branch. A direct dispatch skips `admissionRefuses` (`:2134`, holds and imports), the password gate (`:2611`) and `trackUpgrade` (`:2666`). Fix: name the stages `ServeLinked` keeps; refuse to publish a gated app, or apply the gate.
+- It must use the exact map entry, not `lookupUpstream` or `lookupUpstreamPath` (`:1785`, `:1840`), which add wildcard and path-map targets. Add a test with a `route_paths` prefix pointing at `admin`.
+- Family: home-side enforcement by app.
+
+**7. Task 3: WebSockets through a link are not planned.**
+- Evidence: an upgrade is admitted only with a non-`ArmNone` tenancy (`edge.go:2687`) that still matches at reserve time (`upgrades.go:210`); otherwise `errNoAdmission` gives a 502. `tenancy` has no link field, and no task or test covers it.
+- Fix: define the link tenancy (arm, account, app, link ID) and add a WebSocket case to `TestLinkEndToEnd`.
+- Family: spec goal 3.
+
+**8. Task 3: `SetLinkSeen` has no ordering or restart rule.**
+- Evidence: `internal/edge` makes no registry writes today, and the hub exposes no state-change hook (`tunnel.go:277-284`, `:308`, `:419`).
+- Failure: a hub restart leaves `connected=1` stale. A re-register closes the old connection after the new one publishes, so "disconnected" lands last.
+- Fix: guard writes by connection generation and clear all rows at hub start, or answer reachability from the live hub.
+- Family: goal 6 truthfulness.
+
+**9. Tasks 4 and 5: the two-store writes are not retry-safe.**
+- Publish writes the `apps` row and then `PutForward`. A failure in between makes the retry return 409 "name taken".
+- `PutLinkChannel` runs after the poll transaction has burned the request, so a failure leaves a token no hub accepts.
+- Fix: make publish idempotent for the same link (re-put the row), and re-assert the link channel on each link API call.
+- Family: crash consistency.
+
+## P3
+
+- `remote_dispatch.go` is at `internal/registry/`, not `internal/host/` (Tasks 1 and 7).
+- `consoleRegistry` (`view.go:522-544`) lacks `PutForward` and `DeleteForward`; Task 5 needs both.
+- The spec says `carlos links list`; the plan says `links ls`.
+- `accountfleet.go:144` counts a link row's app as a platform app, and `regionlabel.ForRoute` labels `link/<id>` as a region code.
+- A lost rotate response leaves home holding a revoked token; document relinking as the recovery.
+- `principalKey` gives every link in an account the same rate key (`svcprincipal.go:577`).
+
+## Checked and sound
+
+- Credential containment holds. The store door 404s through `fleetAccount`, provided link owners are never merged into the map stored at `edge.go:1435`. `fleetIdentityOK` cannot match a `:` fleet name. `CLITokenAddress` refuses every non-user kind. `/register` under a fleet name fails the hash check.
+- `cliGateRefused` (`authcli.go:512-515`) would pass a third kind through today, so Task 4's explicit refusal is required. Its `routeDecls` walk does catch routes added later.
+- Revocation holds within the 2 s Watch poll plus one reload; `tunnel.go:269-276` closes the registration race.
+
+**NOT READY**: P1s 1 and 2.
diff --git a/docs/superpowers/specs/2026-11-10-linked-deployments-design.md b/docs/superpowers/specs/2026-11-10-linked-deployments-design.md
index e385f2ce8..d8157ca58 100644
--- a/docs/superpowers/specs/2026-11-10-linked-deployments-design.md
+++ b/docs/superpowers/specs/2026-11-10-linked-deployments-design.md
@@ -205,7 +205,7 @@ from the linked deployment, so analytics, protection and usage views work
for them as for any app. They have no deploy, secrets, instances or logs
views on Carloku. Those live at home.
-`carlos links list --account <acct>` gives the same on the CLI.
+`carlos links ls --account <acct>` gives the same on the CLI.
## 6. How it works