| new file mode 100644 |
| index 000000000..135822530 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-11-10-linked-deployments-slice1.md |
| @@ -0,0 +1,304 @@ |
| +# Linked deployments, slice 1: link and dynamic publish — Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** A single-box home deployment links to a Carloku account and publishes a dynamic app at a public Carloku hostname, served through a tunnel the home box dials, with an offline page when home is dark and a Linked deployments view on the serving console. |
| + |
| +**Architecture:** The serving console mints a link credential through its device-code flow and writes three things into the hub's registry: the link's channel auth, and one forward row per publication placed `link/<id>`. The hub edge treats link rows like fleet forward rows (TLS, backhaul, protection, metering) but dials them down `link:<id>/home` channels and names the published app in a hub-set header. On the home side the console stores the credential and published set in its own registry; the agent on the box that claims the link runs a second, registry-driven tunnel loop whose handler serves only published apps. |
| + |
| +**Tech Stack:** Go; SQLite registry (`internal/registry`) and console store (`internal/console`); `internal/tunnelclient`; `internal/edge`; `internal/clireg` CLI. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-11-10-linked-deployments-design.md` (rev 3). Slice 1 is §7 item 1. Static copies (§6.5) and custom domains are later slices and are refused here with a clear message. |
| + |
| +## Global Constraints |
| + |
| +- Channel name for a link: `link:<linkID>/home`. `:` is outside `ValidTunnelName`'s alphabet `^[a-z0-9-]{1,32}$` (`internal/registry/registry.go:518`), so no fleet can take it. |
| +- Link IDs: 12 lowercase hex characters, regex `^[0-9a-f]{12}$`, minted from `crypto/rand` by the serving console. |
| +- Placement for link forward rows: `Region = "link/" + linkID`. One parser, `registry.LinkPlacement`. |
| +- 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`. |
| +- 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). |
| +- Locally run only the touched packages with `-run`; CI runs the full suite. `TestPlan14RootReadCensus` failing means a census overlay is needed (AGENTS.md census section). |
| +- Commit subjects under 80 characters, body after a blank line, ending with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. |
| + |
| +## 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. |
| +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. |
| + |
| +--- |
| + |
| +### Task 0: Copy deck |
| + |
| +**Files:** |
| +- Create: `docs/drafts/linked-deployments-copy/deck.md` |
| + |
| +Every user-facing string slice 1 adds, with an ID (`LD-C01`...), where it appears, and a draft: |
| +- CLI output and refusals for `carlos link create|status|publish|unpublish|rotate|remove` and `carlos links ls`; |
| +- the approval page text for a link request (names the home deployment and the account; says it will be able to publish apps under the account and nothing else); |
| +- the linked-app refusal on serving-side app commands (spec §6.0: "managed by its home deployment"); |
| +- the refusal for static apps and custom domains in slice 1; |
| +- the Linked deployments section on the Fleet tab (heading, empty state, reachable/not reachable, last seen, Unlink button and confirm); |
| +- the offline page's title and body (spec §6.4: the app runs at home and home is offline right now); |
| +- the home-side refusals (unpublished app, app not on the linked box). |
| + |
| +- [ ] **Step 1:** Draft the deck following the house voice (no em dashes, plain words). |
| +- [ ] **Step 2:** Run the copy-review skill on the deck and apply Paul's edits verbatim. Tasks that write strings wait for this. |
| +- [ ] **Step 3:** Commit the approved deck. |
| + |
| +### Task 1: Registry — link channels and link placement |
| + |
| +**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` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const LinkPlacementPrefix = "link/"` |
| + - `func LinkPlacement(region string) (linkID string, ok bool)` — ok only for `link/` + a valid link ID. |
| + - `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)` |
| + - `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. |
| + |
| +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)`. |
| + |
| +- [ ] **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 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`. |
| + |
| +### Task 2: Provision and domains leave link rows alone |
| + |
| +**Files:** |
| +- Modify: `internal/provision/forward.go:154-178` (`retirements`), `internal/provision/forward.go:104` (`decideForward` never claims a link row) |
| +- Test: `internal/provision/forward_link_test.go`, `internal/domains/reconcile_link_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `registry.LinkPlacement`, `PutForward` (Task 1). |
| + |
| +- [ ] **Step 1: Write failing tests:** |
| + - `TestHubReconcileKeepsLinkRows`: a hub-armed `Reconcile` (cfg with `FleetOwners` set) over a registry holding one fleet forward row with a record and one `link/<id>` forward row with no record. After a whole pass the link row is byte-identical (`registry.Get`), and a fleet row whose record is gone is still retired. |
| + - `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 4:** Same command — PASS. |
| +- [ ] **Step 5:** Commit `provision: keep link forward rows out of the retirement pass`. |
| + |
| +### Task 3: Hub edge — link channels, eligibility, header, offline page |
| + |
| +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` |
| +- 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` |
| + |
| +**Interfaces:** |
| +- 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. |
| + - `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). |
| + |
| +- [ ] **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`. |
| + - `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. |
| + - `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. |
| +- [ ] **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`. |
| + |
| +### Task 4: Serving console — link credential and approval |
| + |
| +Risk: authority. Gets its own review. |
| + |
| +**Files:** |
| +- Modify: `internal/console/authstore.go` (migrate `cli_auth_requests` ALTER: `purpose TEXT NOT NULL DEFAULT ''`, `link_name TEXT NOT NULL DEFAULT ''`, `account_id INTEGER NOT NULL DEFAULT 0`; kind constant `cliKindLink = "link"`; `PollCLIAuth` minting), `internal/console/svcprincipal.go:96` (`CLIPrincipal`), `internal/console/authcli.go` (`handleCLIStart` :762, `handleCLIPoll` :793, approve page :997, approve :1072), `internal/console/templates/cli_approve.html` |
| +- Create: `internal/console/links_store.go` (table `links`), `internal/console/links_auth_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - Console table `links(id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, name TEXT NOT NULL, created_by TEXT NOT NULL, created_at INTEGER NOT NULL, revoked_at INTEGER NOT NULL DEFAULT 0)`. |
| + - `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. |
| + - 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`. |
| + |
| +- [ ] **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). |
| + - `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. |
| + - `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. |
| +- [ ] **Step 4:** Same command — PASS. |
| +- [ ] **Step 5:** Commit `console: link credentials through the device-code flow`. |
| + |
| +### Task 5: Serving console — link API, linked apps and the guard |
| + |
| +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`) |
| + |
| +**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/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. |
| + |
| +- [ ] **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. |
| + - `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 3:** Implement. |
| +- [ ] **Step 4:** Same command — PASS. |
| +- [ ] **Step 5:** Commit `console: link API, linked apps and the linked-app guard`. |
| + |
| +### Task 6: Serving console — Linked deployments view and person-side unlink |
| + |
| +**Files:** |
| +- Modify: `internal/console/accountfleet.go:82` (`assembleAccountFleet` also returns links), `internal/console/templates/account_fleet.html`, `internal/console/server.go:2639` (page fields), `internal/console/routedecls.go` |
| +- Create: `internal/console/accountlinks.go`, `internal/console/accountlinks_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `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. |
| + |
| +- [ ] **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. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit `console: Linked deployments on the Fleet tab`. |
| + |
| +### Task 7: Home console — link state and the home API |
| + |
| +**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` |
| + |
| +**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)`. |
| + - 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`. |
| + - `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`. |
| + - `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 2:** `go test ./internal/registry ./internal/console -run 'HomeLink|HomeStart|HomePublish|HomeUnpublish'` — FAIL. |
| +- [ ] **Step 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit `console: home side of a link (state, publish, unpublish)`. |
| + |
| +### Task 8: Home agent — link loop and link handler |
| + |
| +Risk: the anti-goal 1 guard. Gets its own review. |
| + |
| +**Files:** |
| +- Create: `internal/host/link_client.go`, `internal/host/link_handler.go`, `internal/host/link_e2e_test.go` |
| +- Modify: `internal/host/agent.go` (~1257, start beside `tunnelLoop`), `internal/edge/edge.go` (new `ServeLinked`) |
| + |
| +**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). |
| + |
| +- [ ] **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. |
| + - `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 3:** Implement. |
| +- [ ] **Step 4:** PASS. |
| +- [ ] **Step 5:** Commit `host: home link loop that serves only published apps`. |
| + |
| +### Task 9: CLI — `carlos link` and `carlos links` |
| + |
| +**Files:** |
| +- Create: `link_cli.go`, `link_cli_test.go` (repo root, package main, beside `fleets.go`) |
| +- Modify: `commands.go:69` (`buildCommandRoot`), `apimode.go` (client calls) |
| + |
| +**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()`. |
| + |
| +- [ ] **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 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`. |
| + |
| +### Task 10: Docs and dev witness (controller) |
| + |
| +**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 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; |
| + - pulling the home box's network gives the offline page within one reload; |
| + - unpublish stops the URL; unlink empties the Linked deployments section; |
| + - the Fleet tab shows the link reachable, then not. |
| + |
| +--- |
| + |
| +## Self-review notes |
| + |
| +- Spec coverage: §5.1 (Tasks 4, 7, 9), §5.2 (5, 7, 9), §5.3 (5, 6, 7, 9), §5.4 (6), §6.0 (5), §6.1 (4, 5), §6.2 (1, 3, 8), §6.3 (8), §6.4 (3), §6.7 (5, cap and rate; metering is unchanged forward-row behaviour), §6.8 (accepted, no task), §6.9 (version floor: an old hub has no link auth, so `/register` refuses; an old home has no link commands). §6.5 and custom domains are refused in slice 1 (Tasks 5, 7). |
| +- Review Focus lines each have a test: 1 → Tasks 3, 4; 2 → Task 8; 3 → Tasks 3, 5; 4 → Task 2; 5 → Tasks 7, 8. |