plan: tunnel WebSockets (#471), rev 1
Implementation plan for spec rev 4 (approved by Paul 2026-10-30), house style of the fleet public routes plan: Task 0 copy deck (TWS-C01..C03, pending), Tasks 1-2 the two tunnel halves in the leaf package, Task 3 the hub's registry, reservation, tenancy, capability and scrub (upgrades still refused), Task 4 the reload mutex and sweep, Task 5 switches on the hub's marker, Tasks 6-7 the production-wired witnesses, Task 8 the sample's Action Cable channel, Task 9 census and merge, Task 10 live on dev. Branch merged with main c24e7a04 so the plan's lines match main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/plans/2026-10-30-tunnel-websockets.md+334 −0
Intent
<task-notification> <task-id>ae788846b0095491a</task-id> <tool-use-id>toolu_01EEaF9tNsi9Aiq8JS1KgmjB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/ae788846b0095491a.output</output-file> <status>completed</status> <summary>Agent "Draft #471 WebSocket tunnel spec" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Rev 4 is pushed: the branch tip is **7b9fbb4d**, and `ls-remote` shows the same commit on amadan. That commit has spec rev 4 and the R3 findings file, and there is no further review round. The §0 status line now reads exactly as you gave it: "rev 4. Astra R1 NOT READY, R2 NOT READY, R3 READY AFTER FIXES (P2s applied); awaiting Paul's approval." **R3-1 (test case 12, the fallback release):** fixed. - I confirmed the finding. The edge's `countingWriter` and `slotWriter` turn a writer with no `Hijack` method into a plain error. That makes the proxy close the response body itself, so the old test never reached the fallback release. - The test writer now has a `Hijack` that returns `http.ErrNotSupported`, which both wrappers pass through unchanged. The proxy then exits early and leaves the body open. - The test holds the handler at a barrier and checks the body is still open and the slot still counted. It then releases the barrier and checks that the `AfterFunc` fallback released it after `net/http` cancelled the request. - A second variant uses a writer with no `Hijack` at all and checks release through the body instead. - The §4.6.2 table and §3.5 now tell `ErrNotSupported` apart from other hijack errors. **R3-2 (test case 18, two Reloads interleaving):** fixed, with no sleeps or timing assumptions. - `Reload` gets test hooks at five points: before taking the lock, after the registry reads, before and after publishing the map, and after the sweep. `Watch` gets a test-driven tick and hooks around recording the fingerprint. - While Reload A is paused, the test asserts `e.reloadMu.TryLock()` fails. If the lock is removed, the test fails at that step, before anything that could depend on scheduling. - The test then releases each barrier in turn and asserts the exact order of events. It also covers a Reload that fails (no fingerprint recorded, the next tick retries) and the reverse order. **Summary for Paul:** written to `/home/paulca/.cache/tmp/claude-1001/tunnel-ws-summary.md`, 18 lines. It covers what the design does, how it stays safe, its limits, compatibility, cost and the three copy strings. It says sockets close "within a few seconds" because the bound is the 2-second registry check plus one round trip, not 2 seconds flat. The worktree is still in place on the branch, and I created no other scratch files.</result> <usage><subagent_tokens>353002</subagent_tokens><tool_uses>9</tool_uses><duration_ms>118868</duration_ms></usage> </task-notification>
<task-notification> <task-id>b6a07xez2</task-id> <tool-use-id>toolu_016ir1z66pyZComL12GXKRd3</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/b6a07xez2.output</output-file> <status>completed</status> <summary>Background command "Brief, push and run Astra round 1 on the minors branch" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ae9fe8a38b46a90e9</task-id> <tool-use-id>toolu_016Qtz8URTNGGfX7Z6Dq1tss</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/ae9fe8a38b46a90e9.output</output-file> <status>completed</status> <summary>Agent "Plan 6 preflight against main" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I wrote the preflight table. **The plan is not buildable as written:** it needs three amendments and a small copy review, plus one-line rulings for the rest. Nothing in the repo was edited or committed, and there was no scratch to clean up. **File:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/preflight.md` **Row counts:** 16 task rows, 23 pair rows, 8 rows on later work, 8 copy rows, 29 problem rows. The problem ids skip 25, 28 and 31, which were merged into neighbouring rows. **Problems and proposed rulings** - **PF-1 (blocking):** `carlos run` on rootfs rows is not on main. Plan 3 Task 12 was reverted at bba9a52d. Tasks 8, 10, 15 and 16 depend on it, and Task 1 Step 2 stops on it by its own rule. Ruling: add a new Task 7a that brings back the run half without `--version`, fixes the Task 12 review's P1 #1 and P1 #4, and builds RFS-3-C27. - **PF-2:** the "does not sleep" check (`apiruns.go:274`) refuses every always-on rootfs record, so sessions would be refused too. Ruling: let rootfs records through that check, for runs and sessions. - **PF-3:** when an always-on rootfs instance loses its lease, nothing stops cmd or tty units. The tty unit's 20 s stop is longer than the lease margin. Ruling: amend Task 9 to stop and prove them beside the workers. - **PF-4:** the console's lifetimes cutover gate treats every request as one unit of work. A 6-hour WebSocket would hold a cutover drain, and its record writes would run under a read-only admission. Ruling: amend Tasks 10, 11 and 16 so each record write gets its own mutating admission and the long connection holds none. - **PF-5:** the plan's file:line references are stale. Ruling: briefs cite section 1 of the preflight instead. - **PF-6:** adding tty verbs to the control interface would break every fake, and there is no rootfs tty status verb. Ruling: a separate optional `TTYControl` with five verbs, including `TTYStatusRootfs`. - **PF-7:** cmd-only hardcoding in the unit's stop and poll, the status route, the start locks and the rootfs unit-name helpers. Ruling: make them role-aware and key the locks by role and host. - **PF-8:** the binary probe's environment never sets up the `/dev/pts` checks, so the new `pts-private` line would always fail and every box would lose nested readiness. Ruling: wire them in Task 5, roll dev first and watch. - **PF-9:** `instance-exit` and `instance-exec` don't accept a `tty` role. The plan's rootfs tty `ExecStopPost` is missing `--rootfs`. Ruling: Task 7 adds `tty` to both, and the template uses `--rootfs`. - **PF-10:** RFS-6-C47 is stale and would drop `--egress-allow` and `--size` from today's message. Ruling: a revised row, reviewed before Task 4. - **PF-11:** `-it` combined with `--idempotency-key` has no refusal string. Ruling: a new row, RFS-6-C65, reviewed before Task 13. - **PF-12:** the RFS-6 rows' file cells are not paths, so the copy gate would fail on every row once built. Ruling: each task fixes only the file cells of its own rows. - **PF-13:** RFS-3-C28 was never built. Ruling: Task 16 only marks it struck, since there is no sentence to remove. - **PF-14:** the plan says to wait for Paul on census proposals. Ruling: Astra approves on #280 under the 2026-10-26 rule, with one overlay for the branch. - **PF-15:** with region HA, every box in a region treats a born-HA host as its own, so several boxes would dial one session. Ruling: a box acts only when it holds the host awake; this is a known limit, dev only. - **PF-16:** the fleet credential check compares only the fleet name. Ruling: also check the fleet's owner matches the record's account. - **PF-17:** a running release process would block sessions, and the release would count tty holds. Ruling: don't refuse a session during a release (it has its own unit), and the release counts only cmd holds. - **PF-18:** the idle check now appears at four sites, not one. Ruling: each counts holds of either role. - **PF-19:** the runs worker now reads records through the lifetime judge. Ruling: the session worker and the relay do the same. - **PF-20:** use `provision.Incarnation`, not `hostclaim.Incarnation`. - **PF-21:** `appsSetRun` changed signature. Ruling: append `interactive *bool` after `change`. - **PF-22:** the plan has no request budget. Ruling: add one to Task 10's brief. - **PF-23:** 6-hour connections would skew the console's performance log. Ruling: skip the two door paths there. - **PF-24:** the shared brief bans `bab`, but all 125 claim fixtures use it. Ruling: claim fixtures keep `bab`; other tests use `bah`/`baj`; reuse the existing `shopManifest`. - **PF-26:** x/net is now v0.60.0. Its websocket package is present, so go.mod still doesn't change. - **PF-27:** `RoleWorker` was added since the plan. Ruling: add `RoleTTY` beside it. - **PF-29:** the fleet secrets key doesn't affect the door's credential (the tunnel token). No change. - **PF-30:** the #451 boot id is the kernel's, not the agent boot id that run pickup compares. No change. - **PF-32:** `rootfsTier` doesn't exist; use `b.tier(rt)`. **Your four conflict questions** - **Fleet public routes:** no change to how a fleet box reaches the door; the transport stays. WebSockets can't cross the fleet tunnel (#471), so the door must stay on the console's origin. The owner check is PF-16. - **Fleet secrets key:** no effect on the door's credentials. - **#451 boot ids:** no effect on run pickup or the box's launch check. - **Region HA:** session admission at the console is unaffected, because the console is one box. The box side needs PF-15. **Copy:** all 64 RFS-6 rows are approved, and none are built yet. C47 needs revising and C65 needs adding. **Recommendation:** amend the plan in three places: 1. Add Task 7a, `carlos run` on rootfs rows (PF-1, PF-2). 2. Amend Task 9 to stop sessions and runs at rootfs lease loss (PF-3). 3. Amend Tasks 10, 11 and 16 for the lifetimes gate (PF-4). Then run the copy review of C47 and C65. Tasks 2, 3, 5, 6 and 7 can start now; Task 4 follows once C47 is settled, then Task 7a, then Tasks 8 to 16.</result> <usage><subagent_tokens>333440</subagent_tokens><tool_uses>124</tool_uses><duration_ms>1050831</duration_ms></usage> </task-notification>
diff --git a/docs/superpowers/plans/2026-10-30-tunnel-websockets.md b/docs/superpowers/plans/2026-10-30-tunnel-websockets.md| new file mode 100644 |
| index 000000000..980e4e41a |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-30-tunnel-websockets.md |
| @@ -0,0 +1,334 @@ |
| +# Tunnel WebSockets 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 WebSocket handshake to a fleet app through the hub answers the app's own 101 and stays open across the fleet tunnel: `wss://shop.bab.dev.oncarlos.com/cable` answers 101 with Action Cable's welcome frame and pings, where today it answers 502. |
| + |
| +**Architecture:** The hub carries an HTTP/1.1 upgrade verbatim inside one HTTP/2 stream on the existing tunnel: `Carlos-Tunnel-Upgrade` replaces `Connection`/`Upgrade`, the box's `tunnelclient.Mark` shim rebuilds the upgrade and gives the box's edge a hijackable writer, and the app's 101 comes back in-band. Every stream is held by one reservation in the hub's open-upgrade registry, which records the tenancy that admitted it, counts it against the box's cap of 128, is released exactly once, and is swept by the first Reload under which that tenancy no longer holds. Reloads are serialised by one mutex held from the registry read through the swap and the sweep. |
| + |
| +**Tech Stack:** Go 1.26.10; `golang.org/x/net v0.60.0` (`http2`, and `websocket` in tests only, both already in the module); `internal/tunnelclient` (leaf: stdlib and x/net only); `internal/edge`; `internal/apperr`; the rootfs sample `examples/rails-shop` (Rails 8.1, Solid Cable). |
| + |
| +**Status:** rev 1, for Astra plan review round 1 of 3. |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md`, rev 4, APPROVED by Paul 2026-10-30 (recorded on amadan #471). Read §4.3 (the handshake), §4.4 (headers and the trust rule), §4.6 (enforcement, tenancy, the reservation, the reload mutex and the sweep inventory) and §4.8 (limits) before any task. Every section number below is the spec's. The spec's file:line evidence is on `65fd8060`; this plan's is on the branch after merging main `c24e7a04` (merge `4c4bc976`), so lines differ by a few in `edge.go` (`Reload` :729, swap :1231, `SetDynamicAuth` :1209, upgrade branch :2114, `Watch` :2819, `tunnelProxy` :3184, `fleetProxy` :3240). |
| + |
| +## Global Constraints |
| + |
| +- Wire (§4.3, §4.4, §4.9): request marker `Carlos-Tunnel-Upgrade: <token>`; response marker `Carlos-Tunnel-Upgraded: 1` on an HTTP/2 `200`; registration capability `Carlos-Tunnel-Caps: upgrade/1`. The `carlos-tunnel/1` protocol token does not change. The token is one RFC 7230 token, printable, at most 64 bytes. The in-band 101 is read with at most 64 KiB of header bytes and a 10 s deadline, must be status 101 and must carry the requested `Upgrade` token. |
| +- Trust (§4.4): a stream carries `Carlos-Tunnel-Upgrade` if and only if the hub's upgrade branch admitted the request. `fleetProxy` and `tunnelProxy` delete both marker headers from every inbound request in `Rewrite`; the edge deletes `Carlos-Tunnel-Upgrade` from every inbound request in `ServeHTTP`; the box's shim deletes an app-set `Carlos-Tunnel-Upgraded` from every response it did not hijack. `transportFor` refuses an upgrade with no admission on its context. |
| +- Limits (§4.8): `tunnelclient.DefaultLimits` = `MaxStreams` 250, `StreamWindow` 1 MiB (1<<20), `ConnWindow` 160 MiB (160<<20); hub cap `tunnelUpgradeCap` 128 per channel connection; `PlainHeadroom` 32 MiB. Invariant, asserted by a test over the production values: `cap < MaxStreams` and `ConnWindow >= cap x StreamWindow + PlainHeadroom`. The hub's receive windows stay at x/net's defaults (4 MiB per stream, 1 GiB per connection). No idle timeout. |
| +- Refusals: cap reached -> 503, `Retry-After: 5`, cause `tunnel_busy`, body TWS-C03; a channel without the capability -> 502, cause `tunnel_upgrade_unsupported`; stale tenancy at reservation -> 502, cause `tunnel`; a dark fleet -> today's 503 `Retry-After: 2`. |
| +- Tenancy (§4.6.1): `tenancy{Arm, Account, App, Fleet, Tunnel}`, built in `Reload` from the one shared decision (`FleetArmVerdict`'s `Arm` for `ArmForward`/`ArmFleet`; the row for `ArmTunnel`) and nowhere else. A reservation is current while `lookupUpstreamPath(host, path)` on the current map finds an upstream whose `tenancy` equals the recorded one. |
| +- Reload (§4.6.1): `e.reloadMu` is taken by `Reload`'s first statement after the nil-in-production `enter` test hook, held to return, through the registry reads, the build, `SetDynamicAuth`, the prober sync, the swap, the activator reconcile and `sweepUpgrades`. Lock order: `reloadMu` outermost; `TunnelHub.mu` and `openUpgrades.mu` are never held together; admission never takes `reloadMu`; nothing is called under `openUpgrades.mu` but map operations and `lookupUpstreamPath`; the sweep releases off-lock, one goroutine per reservation. |
| +- Reservation (§4.6.2): created only by `transportFor`, released by `release()` under `sync.Once`, with a `context.AfterFunc` backstop on the inbound request's context; per-connection counts keyed by `*tunnelConn`. |
| +- Request budget (§6): zero added bucket requests on every box. No new timer, no new object, no new poll. |
| +- No cloud API; no DNS; no release floor; no switch (§12). |
| +- Copy: every user-facing string is a row of `docs/superpowers/plans/2026-10-30-tunnel-websockets-copy.md` (ids `TWS-C01` to `TWS-C03`), approved before a task writes it, gated by `approved_tunnel_websockets_copy_test.go`. The task that writes a row adds its id to `tunnelWebSocketsCopyBuilt` in the same commit. No em dashes. Lower case after a full stop where the house deck does so. Log lines are not copy. |
| +- Names in tests: account `bah` (`fwdOwner`, `internal/edge/fleetforward_test.go:36`) and `k3x` for a second account, fleets `home` and `away`, boxes `box-1` and `box-2`, hosts under `example.com`. Never a tenant's name. Live steps name only the dev sample (`shop`, account `bab`, fleet `r10r`). |
| +- Every function a task changes: the task lists every caller, tests included (grep `-rn '<name>('` over the module), and migrates them in the same commit. |
| +- Every refusal test's fixture must be able to produce the refusal: each refusal test carries a positive control in the same fixture that shows the path succeeds when the refused condition is absent. |
| +- Every test that claims a race or interleaving uses deterministic hooks or barriers, never sleeps; a scheduling-free assertion (a `TryLock`, an ordered event log) decides it. |
| +- One shared decision, no copies: the upgrade predicate is `isUpgradeRequest` (`edge.go:2283`) everywhere in `internal/edge`; tenancy comes only from `Reload`'s arm; the limits come only from `tunnelclient.DefaultLimits` and `tunnelUpgradeCap`. |
| +- A test that corrupts or changes persisted state (raw SQL, `UpsertFleet`) reads it back through the production reader (`Get`, `FleetOwners`) and asserts the new value before using it. |
| +- Tests: touched packages only, with `-run`, under `nice -n 19`, sandbox off for the Go cache, `GOCACHE` at its default. Socket and tunnel tests: `TMPDIR=/tmp/g`. Never `make test` locally. Every new test is shown failing first; every security, tenancy or termination test also shows the mutation that makes it fail. Before each commit: `go build ./... && go vet <pkgs> && gofmt -l <files>` empty, and `GOOS=darwin go build ./... && GOOS=windows go build ./... && GOOS=linux GOARCH=arm64 go build ./...`. |
| +- Census (AGENTS.md "The census"): a task that changes a declaration in the root binary runs `make census-card` (sandbox off) after its tests pass and reconciles every unit the card shows against spec §7. A unit the card shows that §7 does not list, or the reverse, is written into spec §7 with its reason in the same commit. The overlay is proposed once, in Task 9. |
| +- Amadan: at execution start, one `amadan task add carlos/platform -branch design-tunnel-websockets-471 -title "<Task N: title>"` per task below plus "Whole-branch review" and "Census verdict on #280"; `amadan task advance` to Started at dispatch and Done at review clean. |
| +- Stopping rules (AGENTS.md): per-task Astra review only for Tasks 3, 4 and 5 (tenancy, termination, the trust boundary); the rest ride the whole-branch review. Three rounds per review. |
| +- Commits end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. No push to GitHub; the branch lives on amadan. |
| + |
| +## Review Focus |
| + |
| +1. A box whose app never answers the handshake (a hung Rails boot): the hub must not hold a reservation or a stream slot past the request's end, and the box's other traffic must keep flowing. Test in Task 5 (`TestHungHandshakeReleasesAtRequestEnd`). |
| +2. A browser that sends the WebSocket handshake with a second `Connection` header line (`Connection: keep-alive` then `Connection: Upgrade`): it must be admitted through the upgrade branch, not reach the box as a plain GET. Test in Task 5 (`TestUpgradeOnASecondConnectionLine`). |
| +3. A gated fleet app whose cookie has expired while a socket is open: the socket is not re-gated (as on a platform box), but the next handshake gets the gate's answer, never a 101. Test in Task 6 (case 1 extended: `expired cookie`). |
| +4. An app that answers 101 with `Sec-WebSocket-Extensions: permessage-deflate` and then sends compressed frames: bytes must cross unchanged both ways. Test in Task 2 (`TestUpgradeCarriesBytesVerbatim`, a 1 MiB random payload each way). |
| +5. A hub Reload that fails halfway (registry read error) while a socket is open: the socket stays, nothing is half-swept, and the next successful Reload judges it. Test in Task 4 (`TestFailedReloadSweepsNothing`). |
| + |
| +## Plan rulings (choices the spec leaves open, with cost if wrong) |
| + |
| +- P-1. The old-box log line (§4.9 says "logged once per channel per hour") uses the edge's existing `logThrottled` (first occurrence, then every 300th; `edge.go:1287`), one shared mechanism rather than a new time-based limiter. Task 5 amends spec §4.9's wording in its commit. Cost if wrong: one limiter and a test. |
| +- P-2. The scaled limits for tests travel as data, not mutable globals: `tunnelclient.Config.Limits *Limits` (nil = `DefaultLimits`) and `TunnelHub.upgradeCap` (unexported, set by `NewTunnelHub` to `tunnelUpgradeCap`). Cost if wrong: none at runtime. |
| +- P-3. `TunnelHub.conn(name) *http2.ClientConn` becomes `channel(name) *tunnelConn` (callers `tunnel.go:361`, `:395`), so admission reads caps and counts against the same connection it streams on. |
| +- P-4. The live revocation (Task 10) uses `carlos apps delete` on a throwaway copy of the sample on `r10r`, not an owner change: no `carlos` command changes a fleet's owner, and an owner change through the hub's registry would be an operator write on a deployment. The owner-change case is the in-process witness's (Task 6 case 15). **Needs the controller's confirmation** (see "Decisions needed"). |
| + |
| +## Decisions needed |
| + |
| +- D-1 (blocks Task 10 step 4 only). The live "owner change on a test fleet" has no CLI. Options: (a) P-4's throwaway copy `cable` of the sample on `r10r`, trashed by `carlos apps delete` (CLI only; costs a second rootfs app on box-1 for minutes; check box-1's free memory first, read-only); (b) a scoped operator write to the dev hub's fleets table (needs Paul's scoped approval; breaks "operate via API and CLI"); (c) rely on the witness and skip a live revocation. Recommend (a). |
| +- D-2 (blocks Task 0's approval only). TWS-C01 to TWS-C03's text: Paul is reviewing. Rows stay `pending` until then. |
| + |
| +--- |
| + |
| +## File structure |
| + |
| +| path | responsibility | |
| +|---|---| |
| +| `internal/tunnelclient/upgrade.go` (new) | marker and capability names, `Limits`, `DefaultLimits`, `ValidUpgradeToken`, the box shim (`upgradeShim`, used by `Mark`), `RoundTripUpgrade` and `UpgradeConn` (the hub half) | |
| +| `internal/tunnelclient/tunnelclient.go` | `Dial` sends the capability; `Serve`/`ServeWith` build the `http2.Server` from `Limits`; `Mark` routes through the shim; `Config.Limits` | |
| +| `internal/edge/upgrades.go` (new) | `tenancy`, `upgradeAdmission`, `openUpgrades`, `upgradeReservation`, `Edge.reserveUpgrade`, `Edge.sweepUpgrades`, the sentinels | |
| +| `internal/edge/tunnel.go` | `tunnelConn.caps`, `channel`, `upgradeCap`, `transportFor`'s upgrade branch | |
| +| `internal/edge/edge.go` | `reloadMu` and test hooks in `Reload`; `upstream.tenancy` in three arms; `sweepUpgrades` after the swap; the admission in the upgrade branch; the inbound header delete; the marker scrub and sentinel answers in `fleetProxy` and `tunnelProxy`; `Watch`'s test tick and record hooks | |
| +| `internal/apperr/availability.go` | `CauseTunnelBusy`, `CauseTunnelUpgradeUnsupported` and their text | |
| +| `internal/edge/tunnel_ws_e2e_test.go` (new) | the production-wired witness | |
| +| `examples/rails-shop/app/channels/...`, `app/views/pages/show.html.erb` | the sample's Action Cable channel and its subscription | |
| +| `docs/superpowers/plans/2026-10-30-tunnel-websockets-copy.md`, `approved_tunnel_websockets_copy_test.go` (new) | the copy deck and its gate | |
| + |
| +## Task order, and when upgrades turn on |
| + |
| +Upgrades stay refused exactly as today (the hub's 502) through Task 4. Tasks 1 and 2 add the two tunnel halves in the leaf package, unused by the hub; Task 1's box half is live on boxes but inert, because no hub sends the marker. Task 3 adds the registry, reservation, tenancy, capability and the header scrub, with `transportFor` still calling `cc.RoundTrip` for an upgrade (x/net refuses it). Task 4 serialises `Reload` and adds the sweep, a change that stands on its own. **Task 5 turns on the hub's marker**: `transportFor` sends admitted upgrades through `RoundTripUpgrade`. Tasks 6 and 7 are the witnesses, Task 8 the sample, Task 9 the census, review and merge, Task 10 the dev roll. `main` builds and passes after every task. |
| + |
| +--- |
| + |
| +### Task 0: Copy deck |
| + |
| +**Files:** |
| +- Create: `docs/superpowers/plans/2026-10-30-tunnel-websockets-copy.md` |
| +- Create: `approved_tunnel_websockets_copy_test.go` |
| + |
| +**Interfaces:** |
| +- Produces: ids `TWS-C01` to `TWS-C03`; `tunnelWebSocketsCopyBuilt []string` (empty), extended by Task 5. |
| + |
| +- [ ] **Step 1: Write the deck** in the format of `2026-10-30-fleet-public-routes-copy.md` (columns id, file, text, status), every row `pending`: |
| + |
| +| id | file | text | |
| +|---|---|---| |
| +| TWS-C01 | internal/apperr/availability.go (`causeText[CauseTunnelBusy]`) | the fleet box has too many open connections | |
| +| TWS-C02 | internal/apperr/availability.go (`causeText[CauseTunnelUpgradeUnsupported]`) | the fleet box runs a release that cannot carry WebSockets | |
| +| TWS-C03 | internal/edge/tunnel.go (503 body when a box is at its cap) | Too many open connections to this app's box. Try again shortly. | |
| + |
| +- [ ] **Step 2: Write the gate** by copying `approved_fleet_routes_copy_test.go` with this deck's path, `tunnelWebSocketsCopyIDPattern = ^TWS-C(0[1-9]|[1-9][0-9]{1,2})$`, ids `TWS-C01..03`, statuses pending/approved/struck, no const-floor rows, and an empty built list: `TestTunnelWebSocketsCopyIDPattern`, `TestTunnelWebSocketsCopyRecordIsComplete`, `TestTunnelWebSocketsCopyHasNoEmDash`, `TestTunnelWebSocketsCopyBuiltIsApproved`, `TestTunnelWebSocketsCopyBuiltIsApplied`. |
| +- [ ] **Step 3: Run** `nice -n 19 go test . -run 'TestTunnelWebSocketsCopy' -count=1`. Expected: PASS (three pending rows, nothing built). |
| +- [ ] **Step 4: Copy review.** The controller gives the approved text (D-2). Each row becomes `approved` with its final text; no later task writes a row before then. |
| +- [ ] **Step 5: Commit** deck and gate. |
| + |
| +### Task 1: The box half: the shim, the capability and the limits |
| + |
| +**Files:** |
| +- Create: `internal/tunnelclient/upgrade.go`, `internal/tunnelclient/upgrade_box_test.go` |
| +- Modify: `internal/tunnelclient/tunnelclient.go` (`Config` :66-79, `Loop` :87-139, `Dial` :190-262, `Mark` :279-288, `Serve` :290-293) |
| +- Callers checked, unchanged signatures: `Dial` (`tunnelclient_test.go:58`, `:73`; `Loop`), `Serve` (`tunnelclient_test.go:62`; `serveUntilDead` :168), `Mark` (`mark_test.go:16`, `internal/edge/reqrecords_test.go:65`, `internal/edge/guard_test.go:251`, `Loop` :120), `Loop` (`internal/host/tunnel_client.go:49`, `internal/edge/fleet_e2e_test.go:172`, `internal/edge/tunnel_e2e_test.go:197`). None needs a change: a `Config` with no `Limits` gets `DefaultLimits`, and a request with no marker passes through `Mark` byte for byte (pinned below). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `const UpgradeHeader = "Carlos-Tunnel-Upgrade"`, `UpgradedHeader = "Carlos-Tunnel-Upgraded"`, `CapsHeader = "Carlos-Tunnel-Caps"`, `CapUpgrade = "upgrade/1"`, `MaxUpgradeTokenLen = 64`. |
| + - `type Limits struct { MaxStreams uint32; StreamWindow, ConnWindow int32 }`; `var DefaultLimits = Limits{MaxStreams: 250, StreamWindow: 1 << 20, ConnWindow: 160 << 20}`; `const PlainHeadroom = 32 << 20`. |
| + - `func ValidUpgradeToken(tok string) bool`: non-empty, at most `MaxUpgradeTokenLen` bytes, every byte an RFC 7230 tchar (`httpguts.IsTokenRune`). |
| + - `Config.Limits *Limits` (nil means `DefaultLimits`); `func ServeWith(conn net.Conn, handler http.Handler, l Limits)`; `Serve(conn, handler)` calls `ServeWith(conn, handler, DefaultLimits)`. The server sets `MaxConcurrentStreams`, `MaxUploadBufferPerStream` and `MaxUploadBufferPerConnection` from `l`. |
| + - `Dial` adds `CapsHeader: CapUpgrade` to the registration request. |
| + - `Mark(h)` serves through `upgradeShim{h}` inside the mark: a request with `UpgradeHeader` set and valid gets the header deleted, `Connection: Upgrade` and `Upgrade: <token>` set, `Body` = `http.NoBody`, `ContentLength` 0, and a writer whose `Hijack` answers HTTP/2 `200` with `UpgradedHeader: 1`, flushes, and returns a `net.Conn` reading the original body and writing with a flush per `Write`. Every response the handler writes without hijacking has `UpgradedHeader` deleted at `WriteHeader`. A request without the header is passed through unchanged. An invalid token answers 400 and does not reach the handler. |
| + |
| +- [ ] **Step 1: Write failing tests** (`upgrade_box_test.go`; an in-memory pair: `net.Pipe`, `ServeWith` on one end, `http2.Transport{}.NewClientConn` on the other): |
| + - `TestShimRebuildsTheUpgrade`: a handler records the request: `Connection == "Upgrade"`, `Upgrade == "websocket"`, no `Carlos-Tunnel-Upgrade`, `ContentLength == 0`, `Sec-WebSocket-Key` unchanged; it hijacks, writes `"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"` then echoes; the client sees status 200 with `Carlos-Tunnel-Upgraded: 1`, reads those 101 bytes from the body, writes `"ping"` into the request pipe and reads `"ping"` back. |
| + - `TestShimPassesPlainRequestsThrough`: no marker: the handler sees the request exactly as sent (method, path, headers, a 4 KiB body) and its 302 arrives with its body; positive control for the next test. |
| + - `TestShimStripsAnAppSetUpgradedMarker`: a handler that sets `Carlos-Tunnel-Upgraded: 1` on a plain 200: the client sees no such header. |
| + - `TestShimRefusesABadToken`: marker `"web socket"` and a 65-byte token: 400, the handler never runs; a 64-byte token: reaches the handler (control). |
| + - `TestRegistrationCarriesTheCapability`: an `httptest` server records `/register`'s headers from `Dial`: `Carlos-Tunnel-Caps == "upgrade/1"`. |
| + - `TestServerAdvertisesTheLimits` (§8.1 case 6): an x/net `Framer` client on the raw pipe end writes the client preface and an empty SETTINGS, then reads the server's first frames: the SETTINGS frame has `SettingMaxConcurrentStreams == 250` and `SettingInitialWindowSize == 1<<20`; the next frame is a WINDOW_UPDATE on stream 0 with increment `160<<20 - 65535`. With `ServeWith(..., Limits{8, 64<<10, 768<<10})`: 8, `64<<10`, `768<<10 - 65535`. |
| + - Mutation to show: drop the `UpgradedHeader` delete; `TestShimStripsAnAppSetUpgradedMarker` fails. |
| +- [ ] **Step 2: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/tunnelclient/ -count=1`. Expected: FAIL on the new tests only. |
| +- [ ] **Step 3: Implement** as the Interfaces block says. Keep the package's imports to stdlib and `golang.org/x/net/...` (its header's rule, `tunnelclient.go:7-14`). |
| +- [ ] **Step 4: Run** Step 2, plus `TMPDIR=/tmp/g nice -n 19 go test ./internal/edge/ -run 'TestTunnel|TestFleet|TestReqRecords|TestGuard' -count=1`. Expected: PASS. |
| +- [ ] **Step 5: Census.** Expect `Dial`, `Serve`, `markedHandler.ServeHTTP` (body), `ServeWith`, `ValidUpgradeToken`, the shim (new), the `tunnelclient` envelope; reconcile with spec §7. |
| +- [ ] **Step 6: Commit.** |
| + |
| +### Task 2: The hub half: `RoundTripUpgrade` |
| + |
| +**Files:** |
| +- Modify: `internal/tunnelclient/upgrade.go` |
| +- Create: `internal/tunnelclient/upgrade_hub_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's shim, names and `ServeWith`. |
| +- Produces: |
| + - `const MaxUpgradeHeaderBytes = 64 << 10`, `UpgradeHandshakeTimeout = 10 * time.Second`. |
| + - `var ErrUpgradeHandshake = errors.New("tunnelclient: upgrade handshake failed")` (wrapped with the reason). |
| + - `func RoundTripUpgrade(ctx context.Context, cc *http2.ClientConn, req *http.Request) (*http.Response, error)`: requires `ValidUpgradeToken(req.Header.Get("Upgrade"))` (else `ErrUpgradeHandshake`, no stream opened); clones `req` with `ctx`, deletes `Connection` and `Upgrade`, sets `UpgradeHeader`, sets the body to an `io.Pipe` reader; `cc.RoundTrip`. A response without `UpgradedHeader: 1` is returned unchanged (its body the stream). With it: reads one `http.ReadResponse` from the body through a reader capped at `MaxUpgradeHeaderBytes`, under an `UpgradeHandshakeTimeout` timer that closes the stream; requires status 101 and an `Upgrade` equal (case-insensitive) to the token; returns that response with `Body` an `*UpgradeConn`. Every error path closes the pipe and the stream's body before returning. |
| + - `type UpgradeConn struct{...}` with `Read` (buffered remainder, then the stream), `Write` (the pipe), `CloseWrite() error` (closes the pipe: END_STREAM) and `Close() error` (closes the pipe and the stream's body: RST_STREAM CANCEL), idempotent. |
| + |
| +- [ ] **Step 1: Write failing tests** (same in-memory pair; the box side is Task 1's `ServeWith` over `Mark` of a test handler): |
| + - `TestRoundTripUpgradeReturnsThe101`: the box's handler checks `Sec-WebSocket-Key == "dGhlIHNhbXBsZSBub25jZQ=="` and answers 101 with `Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=`, `Sec-WebSocket-Protocol: actioncable-v1-json`: the returned response is 101 with both headers and `Upgrade: websocket`; its body is an `io.ReadWriteCloser`. |
| + - `TestUpgradeCarriesBytesVerbatim` (Review Focus 4): 1 MiB of random bytes each way through an echoing box handler, compared byte for byte. |
| + - `TestRoundTripUpgradePassesRefusalsThrough`: the box handler answers 302 `Location: /.carlos/gate` with a body: the response is that 302 and body, not an error. |
| + - `TestRoundTripUpgradeRefusesBadInBand101`: four box handlers that hijack and then write (a) 65 KiB of headers, (b) nothing for 11 s (the test passes a 200 ms timeout through an unexported test seam `upgradeHandshakeTimeout` var, read once per call), (c) `HTTP/1.1 200 OK`, (d) a 101 with `Upgrade: h2c`: each returns an error wrapping `ErrUpgradeHandshake`, and the box handler's conn `Read` returns an error within 1 s (the stream was reset). Control: a well-formed 101 in the same fixture succeeds. |
| + - `TestRoundTripUpgradeRefusesBadTokens`: `Upgrade: "web socket"` and a 65-byte token: `ErrUpgradeHandshake`, and the box handler never runs (a counter stays 0). |
| + - `TestUpgradeConnCloseResetsBothWays`: after a 101, `Close` on the hub side: the box conn's `Read` fails within 1 s and the box handler returns; `CloseWrite` instead: the box reads `io.EOF` and can still write `"bye"`, which the hub reads. |
| + - Mutation to show: skip the token check on the in-band 101; case (d) passes the 101 through and the test fails. |
| +- [ ] **Step 2: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/tunnelclient/ -count=1`. Expected: FAIL on the new tests only. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** Step 2. Expected: PASS. |
| +- [ ] **Step 5: Census** (`RoundTripUpgrade`, `UpgradeConn` and its methods: new). |
| +- [ ] **Step 6: Commit.** |
| + |
| +### Task 3: The hub's registry, reservation, tenancy and scrub (upgrades still refused) |
| + |
| +**Files:** |
| +- Create: `internal/edge/upgrades.go`, `internal/edge/upgrades_test.go` |
| +- Modify: `internal/edge/tunnel.go` (`tunnelConn` :72-79, `ServeHTTP` :122-217, `conn` :348-355 -> `channel`, `State` :360-365, `transportFor` :393-401, `NewTunnelHub` :96-98), `internal/edge/edge.go` (`upstream` :417, `Reload`'s three tunnel arms :849-855, :891-895, :916-925; `ServeHTTP` near the hop accept, `Edge` struct), `fleetProxy` :3240 and `tunnelProxy` :3184 `Rewrite` |
| +- Callers migrated: `h.conn(name)` at `tunnel.go:361` (`State`) and `:395` (`transportFor`) -> `h.channel(name)`; `NewTunnelHub` callers keep their signature (`edge.go` `enableTunnelsFromEnv`; tests `fleetforward_test.go:102`, `fleet_route_test.go`, `tunnel_e2e_test.go`, `fleet_e2e_test.go`, `fleetapi_e2e_test.go`, `tunnel_test.go`; grep `NewTunnelHub(` and confirm none constructs `TunnelHub{}` literally). |
| + |
| +**Interfaces:** |
| +- Consumes: Task 1's `CapsHeader`, `CapUpgrade`, `UpgradeHeader`, `UpgradedHeader`. |
| +- Produces: |
| + - `tunnelConn.caps string` (the registration's `CapsHeader`, set at `tunnel.go:213`); `func (h *TunnelHub) channel(name string) *tunnelConn`; `TunnelHub.upgradeCap int`, set to `tunnelUpgradeCap` by `NewTunnelHub`; `const tunnelUpgradeCap = 128`. |
| + - `type tenancy struct { Arm Arm; Account, App, Fleet, Tunnel string }`; `upstream.tenancy tenancy`, set in `Reload`'s `ArmForward` and `ArmFleet` cases from `served` (`FleetServed{Fleet, App, Account}`) and in `ArmTunnel` from `t.Account`, `t.App`, `t.Tunnel`; zero elsewhere. The alias and platform-alias folds copy the upstream and so the tenancy; no other code computes it. |
| + - `type upgradeAdmission struct { Host, Path string; Tenancy tenancy }`; `func withUpgradeAdmission(ctx context.Context, a upgradeAdmission) context.Context`; `func upgradeAdmissionFrom(ctx context.Context) (upgradeAdmission, bool)`. |
| + - `type openUpgrades struct { mu sync.Mutex; byHost map[string]map[*upgradeReservation]struct{}; perConn map[*tunnelConn]int }`; field `Edge.open openUpgrades`. |
| + - `type releaser int` with `relTransport`, `relBody`, `relBackstop`, `relSweep`; `type upgradeReservation struct { ... }` with `func (r *upgradeReservation) release(by releaser)` (`sync.Once`: cancel the stream context, close the attached pipe and body if any, remove from `byHost`, decrement `perConn[tc]` and delete it at zero, stop the backstop) and `func (r *upgradeReservation) firstReleaser() releaser` (test reads; production never does). |
| + - `func (e *Edge) reserveUpgrade(inbound context.Context, a upgradeAdmission, tc *tunnelConn, capN int) (*upgradeReservation, context.Context, error)`: under `e.open.mu`: `e.lookupUpstreamPath(a.Host, a.Path)` must find an upstream whose `tenancy == a.Tenancy` (else `errTenancyStale`); `perConn[tc] < capN` (else `errTunnelBusy`); insert, count; returns the reservation and the stream's cancelable context; then, outside the lock, `context.AfterFunc(inbound, func() { r.release(relBackstop) })`. |
| + - Sentinels: `errTenancyStale`, `errTunnelBusy`, `errTunnelNoUpgrade`, `errNoAdmission`. |
| + - `fleetProxy` and `tunnelProxy` `Rewrite`: `pr.Out.Header.Del(tunnelclient.UpgradeHeader)` and `Del(tunnelclient.UpgradedHeader)` beside `scrubInboundPurgeHeader`. `Edge.ServeHTTP`: `r.Header.Del(tunnelclient.UpgradeHeader)` once, beside the asset-header deletes (`edge.go` after `acceptHop`). |
| + - `transportFor` is unchanged in behaviour: an upgrade still goes to `cc.RoundTrip` and is refused by x/net. Nothing calls `reserveUpgrade` outside tests yet. |
| + |
| +- [ ] **Step 1: Write failing tests** (`upgrades_test.go`): |
| + - `TestTenancyComesFromReloadsArm`: on `forwardHubAndBox` (`fleetforward_test.go:64`), the hub's forward row for `shop.example.com` has `tenancy{ArmForward, "bah", "shop", "home", ""}`; a platform alias of it carries the same; a `-tunnel` row `t.example.com` (tunnel `t1`, account `k3x`, app `blog`) has `tenancy{ArmTunnel, "k3x", "blog", "", "t1"}`; an instance row on a socket has the zero tenancy. |
| + - `TestReserveUpgradeChecksTenancyAndCap`: hub cap set to 2 on the hub's `TunnelHub`: two reservations for the forward host succeed, the third is `errTunnelBusy`; releasing one admits the next (control). An admission whose tenancy names fleet `away`: `errTenancyStale`, and the count is unchanged. |
| + - `TestReleaseIsExactlyOnce`: one reservation released by `relBody`, then `relSweep`, then the backstop (cancel the inbound context): `perConn` decremented once, `firstReleaser() == relBody`, the attached pipe and body each closed once (counting closers). |
| + - `TestBackstopReleasesOnRequestEnd`: reserve with an inbound context, never call `release`; cancel the inbound context: within 1 s the count is 0 and `firstReleaser() == relBackstop`. |
| + - `TestRegistrationRecordsCaps`: `startFakeRemoteHost` (`tunnel_e2e_test.go:190`, the real `Loop`) registers; `hub.channel(name).caps == "upgrade/1"`; a registration written by hand without the header (the request `tunnelReq` builds, `tunnel_test.go:30`, sent over a raw TCP conn, the 101 read, then `tunnelclient.ServeWith` on the conn) records `""`. |
| + - `TestTheMarkersAreScrubbedAtTheHub`: through `forwardHubAndBox` with a box handler recording headers, a plain GET carrying `Carlos-Tunnel-Upgrade: websocket` and `Carlos-Tunnel-Upgraded: 1`: the box handler sees neither header, `Connection` has no `Upgrade`, and the request is a plain GET (status 200). Same through a `-tunnel` row. Control: a GET without the headers reaches the box identically. |
| + - `TestLimitsInvariant` (§8.1 case 7): `tunnelUpgradeCap < int(tunnelclient.DefaultLimits.MaxStreams)` and `int64(DefaultLimits.ConnWindow) >= int64(tunnelUpgradeCap)*int64(DefaultLimits.StreamWindow) + tunnelclient.PlainHeadroom`. |
| + - `TestUpgradesStillRefusedBeforeSwitchOn`: `polUpgrade` (`fleetforward_policy_test.go:146`) through `policyScene`: 502, and the app saw 0 upgrades (pins this task's dormancy; Task 5 changes it to 101). |
| + - Mutations to show: drop the tenancy comparison in `reserveUpgrade` (the stale case passes); drop the `Once` (`TestReleaseIsExactlyOnce` sees a double decrement). |
| +- [ ] **Step 2: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/edge/ -run 'TestTenancy|TestReserveUpgrade|TestReleaseIs|TestBackstop|TestRegistrationRecordsCaps|TestTheMarkers|TestLimitsInvariant|TestUpgradesStillRefused|TestTunnel|TestFleet|TestForward' -count=1`. Expected: FAIL on the new tests only. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** Step 2. Expected: PASS. |
| +- [ ] **Step 5: Census** (`TunnelHub.ServeHTTP`, `TunnelHub.State`, `transportFor`, `channel` replacing `conn`, `NewTunnelHub`, `Edge.Reload`, `Edge.ServeHTTP`, `fleetProxy`, `tunnelProxy`; new: `tenancy`, `upgradeAdmission` and its two functions, `openUpgrades`, `upgradeReservation` and its methods, `reserveUpgrade`, the sentinels); reconcile. |
| +- [ ] **Step 6: Commit.** |
| + |
| +### Task 4: One reload mutex, and the sweep |
| + |
| +**Files:** |
| +- Modify: `internal/edge/edge.go` (`Edge` struct; `Reload` :729-1300; `Watch` :2819-2876), `internal/edge/upgrades.go` |
| +- Create: `internal/edge/reload_serial_test.go`, `internal/edge/reload_guard_test.go` |
| +- Callers of `Reload`, all unchanged in signature and all now serialised (§4.6.3): `edge.go:495` (`New`), `:2865` (`Watch`), `:3919` (SIGHUP), `:4202` (`EnableStatic` path), `:4247` (`enableTunnelsFromEnv`), `internal/host/agent.go:1038` (`layoutReload`); every test that calls `e.Reload()` (grep `\.Reload()` under `internal/edge`, `internal/host`; none calls it while holding a lock the reload takes). |
| + |
| +**Interfaces:** |
| +- Produces: |
| + - `Edge.reloadMu sync.Mutex`: `Reload` opens with the `enter` hook call (if hooks are set), then `e.reloadMu.Lock(); defer e.reloadMu.Unlock()`; nothing else precedes the lock. |
| + - `func (e *Edge) sweepUpgrades()`, called right after `e.upstreams.Store(&m)`: under `e.open.mu`, collect every reservation for which `lookupUpstreamPath(host, path)` no longer finds its recorded tenancy and delete it from `byHost`; after unlocking, `go r.release(relSweep)` for each. |
| + - Test hooks, nil in production: `type reloadHooks struct { enter, afterRead, beforePublish, afterPublish, afterSweep func(id uint64) error; beforeRecord, afterRecord func(fp string) }` and `Edge.hooks *reloadHooks`; `Reload` numbers itself from an atomic counter and calls each hook with its id (`enter` before the lock; `afterRead` after the last registry read, its error returned as the Reload's; the other three around the swap and the sweep). `Watch` gains `Edge.watchTick <-chan time.Time` (nil: its 2 s ticker) and calls `beforeRecord`/`afterRecord` around `last = fp`. |
| + |
| +- [ ] **Step 1: Write failing tests.** |
| + - `TestTwoReloadsInterleave` (§8.2 case 18 at the registry level): `forwardHubAndBox`, a reservation for the forward host taken through `reserveUpgrade` with a recording pipe and body (no socket yet; Task 6 repeats this with sockets). Hooks append `"<id>:<point>"` to a log and block on per-point barriers the test owns. Steps exactly as spec §8.2 case 18 items 1-9: A stops at `afterRead`; the fleet's owner changes by `UpsertFleet(Fleet{Name: "home", Account: "k3x", ...})` and is read back with `FleetOwners()` before going on; `e.reloadMu.TryLock()` is false; the test sends one tick on `watchTick`; B's `enter` appears and no B `afterRead`; `TryLock` still false; A's barriers are released one at a time, the log checked after each; B runs; the final log equals `A:afterRead A:beforePublish A:afterPublish A:afterSweep B:afterRead B:beforePublish B:afterPublish B:afterSweep record:before record:after` (with `B:enter` between `A:afterRead` and `A:beforePublish`); after `B:afterSweep` the reservation is gone from `byHost` and its `firstReleaser()` becomes `relSweep`; `record:before` carries the fingerprint read after the owner change. Item 8 (B's `afterRead` returns an error: no B publish, no record; the next tick's Reload C sweeps and records) and item 9 (reverse order) as sub-tests. |
| + - Mutation to show: remove the `Lock` line; the test fails at the first `TryLock` with "TryLock succeeded while A holds the reload". |
| + - `TestFailedReloadSweepsNothing` (Review Focus 5): a reservation open; `afterRead` returns an error: the reservation stays, the current map is the old one; the next good Reload with unchanged tenancy keeps it (control). |
| + - `TestSweepKeepsCurrentReservations`: 20 Reloads that change other hosts and rotate `box-1`'s token (`SetDynamicAuth` path): the reservation stays, `firstReleaser()` is unset. |
| + - `TestSweepClosesEachLostTenancy`: table, one reservation each: the forward row's fleet owner changed (read back), the row deleted by `DeleteForward` (read back absent), the row re-minted on fleet `away` by `PutForward`, a `-tunnel` row re-pointed to `t2`, a platform alias whose source is now refused: each is released by `relSweep` in the next Reload; an unchanged control row is not. |
| + - `TestReservationRacesTheSwap` (§8.2 case 17): an unexported seam `beforeReserve func()` in `reserveUpgrade` (nil in production) blocks after the caller dispatched and before the lock; the test runs a revoking Reload to completion, then releases: `errTenancyStale`. Second sub-test: a seam after the insert and before return blocks; the revoking Reload's sweep releases it (`relSweep`). |
| + - `TestReloadIsTheOnlyPublisher` (`reload_guard_test.go`, §8.2 case 19): `go/parser` over `internal/edge` non-test files: exactly one call of `e.upstreams.Store`, inside `func (e *Edge) Reload`; `Reload`'s statements before `e.reloadMu.Lock()` are only the `enter` hook's guarded call, the `Lock` is followed directly by `defer e.reloadMu.Unlock()`, and no registry read or `e.upstreams` use precedes them; `SetDynamicAuth` is called only inside `Reload`; `sweepUpgrades` is called only inside `Reload`, after the `Store`. Mutation: move the `Store` into a helper; the guard names it. |
| +- [ ] **Step 2: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/edge/ -run 'TestTwoReloads|TestFailedReload|TestSweep|TestReservationRaces|TestReloadIsTheOnly|TestWatch|TestReload' -count=1 -race`. Expected: FAIL on the new tests only. |
| +- [ ] **Step 3: Implement.** |
| +- [ ] **Step 4: Run** Step 2, plus the host package's layout tests that drive `layoutReload` (`TMPDIR=/tmp/g nice -n 19 go test ./internal/host/ -run 'Layout' -count=1`). Expected: PASS. |
| +- [ ] **Step 5: Census** (`Edge.Reload`, `Edge.Watch`; new: `sweepUpgrades`, `reloadHooks`); reconcile. |
| +- [ ] **Step 6: Commit.** |
| + |
| +### Task 5: Switch on the hub's marker |
| + |
| +**Files:** |
| +- Modify: `internal/edge/tunnel.go` (`transportFor`), `internal/edge/edge.go` (upgrade branch :2114-2140; `fleetProxy` and `tunnelProxy` error handlers), `internal/apperr/availability.go`, `approved_tunnel_websockets_copy_test.go` (`tunnelWebSocketsCopyBuilt` += `TWS-C01`, `TWS-C02`, `TWS-C03`), spec §4.9 (P-1's wording) |
| +- Migrate: `internal/edge/fleetforward_policy_test.go`: `TestForwardUpgradeIsLimitedAtTheHub` (:200) asserts exactly 101 for handshakes 1 and 2 and `ups == 2`; `TestForwardPlanThrottleAndUpgradeClose` (:224) keeps its in-hook close and adds a socket held open: `CloseAccountUpgrades` returns 1 and the backend's `closed` channel fires within 2 s; `TestForwardUpgradeCloseCancelsTheRequest` (:340) loses its "(#471)" comment and keeps its assertions; Task 3's `TestUpgradesStillRefusedBeforeSwitchOn` is deleted (its job is done). `polBackend` (:37-87) already answers 101 and echoes. |
| +- Callers of `transportFor`: `edge.go:3194` (`tunnelProxy`), `:3255` (`fleetProxy`); no test calls it directly. |
| + |
| +**Interfaces:** |
| +- Consumes: Task 2's `RoundTripUpgrade`, `UpgradeConn`; Task 3's admission, `reserveUpgrade`, `channel`, sentinels; Task 4's sweep. |
| +- Produces: |
| + - The upgrade branch, after `rateAdmit` and before `up.proxy.ServeHTTP`: `r = r.WithContext(withUpgradeAdmission(r.Context(), upgradeAdmission{Host: host, Path: r.URL.Path, Tenancy: up.tenancy}))` when `up.tenancy.Arm != ArmNone`. |
| + - `transportFor(name)`: for `isUpgradeRequest(req)`: `upgradeAdmissionFrom` (else `errNoAdmission`); `tc := h.channel(name)` (nil: today's not-connected error); `tc.caps != tunnelclient.CapUpgrade` -> `errTunnelNoUpgrade`; `!tunnelclient.ValidUpgradeToken(...)` -> today's 502; `reserveUpgrade(req.Context(), adm, tc, h.upgradeCap)`; `tunnelclient.RoundTripUpgrade(streamCtx, tc.cc, req)`; on error `r.release(relTransport)` and return it; a 101: attach the `*UpgradeConn` to the reservation and wrap it so `Close` calls `r.release(relBody)`; any other response: wrap its body the same way. `TunnelHub` reaches the edge's registry through a field set by `EnableTunnels` (`TunnelHub.edge *Edge`). |
| + - Error answers in both proxies: `errTunnelBusy` -> `noteCause(r, apperr.CauseTunnelBusy)`, `Retry-After: 5`, `http.Error(w, "<TWS-C03>", 503)`; `errTunnelNoUpgrade` -> `noteCause(r, apperr.CauseTunnelUpgradeUnsupported)`, `logThrottled("tunnel-upgrade-unsupported "+name, ...)`, 502; `errTenancyStale` and `errNoAdmission` -> cause `tunnel`, 502. |
| + - `apperr`: `CauseTunnelBusy = "tunnel_busy"`, `CauseTunnelUpgradeUnsupported = "tunnel_upgrade_unsupported"`, `causeText` TWS-C01 and TWS-C02. |
| + |
| +- [ ] **Step 1: Migrate** the three policy tests as listed. |
| +- [ ] **Step 2: Write failing tests** (`internal/edge/tunnel_upgrade_test.go`, on `policyScene` and `forwardHubAndBox`): |
| + - `TestForwardUpgradeAnswers101`: `polUpgrade`: 101, and bytes echo through the socket both ways. |
| + - `TestUpgradeOnASecondConnectionLine` (Review Focus 2): the raw handshake with `Connection: keep-alive\r\nConnection: Upgrade\r\n`: 101; the hub's open count for the channel was 1 while it was open (control for `TestTheMarkersAreScrubbedAtTheHub`). |
| + - `TestOldBoxKeepsThe502`: the box registers by hand without the capability (as Task 3's `TestRegistrationRecordsCaps`) and serves its `Edge` with `tunnelclient.ServeWith`: an upgrade gets 502 with cause `tunnel_upgrade_unsupported` (the request's noted cause); a plain GET 200 (control). |
| + - `TestCapAnswers503`: hub `upgradeCap = 2`: two sockets open, the third handshake 503 with `Retry-After: 5` and the TWS-C03 body; a plain GET 200 while both are open; closing one admits a new handshake. |
| + - `TestHungHandshakeReleasesAtRequestEnd` (Review Focus 1): the box's app accepts the TCP connection and never answers; the client gives up after 1 s (closes); within 2 s the channel's count is 0 and a plain GET to another host on the same box answers 200. |
| + - `TestStaleAdmissionIsRefused`: the admission seam from Task 4's `beforeReserve` with a revoking Reload in between: 502 and the app saw no handshake. |
| + - Mutations to show: write the marker without checking the admission (a direct `transportFor` call with an upgrade request and no admission reaches the box; the test calls it and asserts `errNoAdmission`); drop the caps check (`TestOldBoxKeepsThe502` gets the old box's plain-GET answer instead of 502). |
| +- [ ] **Step 3: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/edge/ ./internal/apperr/ -run 'TestForward|TestUpgrade|TestOldBox|TestCap|TestHung|TestStale|TestTunnel|TestFleet|Availability' -count=1` and `nice -n 19 go test . -run 'TestTunnelWebSocketsCopy' -count=1`. Expected: FAIL on the new tests only. |
| +- [ ] **Step 4: Implement**, with the TWS rows' approved text. |
| +- [ ] **Step 5: Run** Step 3. Expected: PASS. |
| +- [ ] **Step 6: Census** (`transportFor`, `Edge.ServeHTTP`, `fleetProxy`, `tunnelProxy`, the `apperr` envelope); reconcile. |
| +- [ ] **Step 7: Commit.** |
| + |
| +### Task 6: The production-wired witness |
| + |
| +**Files:** |
| +- Create: `internal/edge/tunnel_ws_e2e_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes, all production: `New`, `EnableTunnels(NewTunnelHub(host, nil))` and `Reload` for the hub, on a registry with fleet `home` of `bah` and active `box-1`, the forward row through `PutForward`; served by an `http.Server` on a TLS listener (`httptest.NewUnstartedServer(hub)`, `StartTLS`) wrapped in a tracking listener that records every accepted `net.Conn`; the box: `New` on a second registry whose instance row for `shop.example.com` has a unix `Socket`, a `Gate` (bcrypt hash of `right`, as `TestForwardLoginThroughTheRealFleetGate` sets one) and `Account`/`App` `bah`/`shop`, served by `tunnelclient.Loop` dialing the hub over `https` as `home/box-1`; the app: an `x/net/websocket` server on that socket, Action Cable shaped (accepts only subprotocol `actioncable-v1-json` and only when `Origin == X-Forwarded-Proto + "://" + Host`, sends `{"type":"welcome"}`, `{"type":"ping","message":<n>}` every 200 ms, answers `{"command":"subscribe",...}` with `confirm_subscription`, broadcasts on a test channel, echoes `{"command":"message"}` data); the client: `x/net/websocket` against the hub with `Origin: https://shop.example.com`. A counting store wraps the hub's and the box's static stores. |
| + |
| +- [ ] **Step 1: Write** `TestTunnelWebSocketEndToEnd` with spec §8.2 cases 1-8, 10-12, 14-16 as sub-tests on one scene, each with its exact values from the spec: |
| + 1. No cookie: the gate's answer, not 101; the app saw nothing. Extended (Review Focus 3): with a cookie whose expiry has passed, the same. |
| + 2. Log in (`POST /.carlos/gate`, urlencoded, `password=right&next=%2Fcable`), then the handshake: 101, `Sec-WebSocket-Protocol: actioncable-v1-json`; welcome, two pings, subscribe and confirm, a broadcast, 100 echoes each way byte for byte; the app saw no `carlos_gate` cookie and saw `X-Forwarded-Proto: https`. |
| + 3. `SetPlanGovernedFor(bah)`, `CloseAccountUpgrades("bah")` returns 1 while open; client and app both see the close within 2 s; a second call returns 0. |
| + 4. Plan throttle awake: a new handshake 429, `Retry-After: 60`, the app saw nothing. |
| + 5. The hub's rate limit (burst 2) refuses the third handshake with `Retry-After: 1`; the box's own row has burst 1 and never applies. |
| + 6. The app closes its side: the client sees the close. |
| + 7. Tunnel loss: cancel the box's `Loop` context: client and app sockets close within 10 s; restart the loop: a new handshake 101. |
| + 8. Re-registration (a second `Loop` as `home/box-1`) and detach (`SetFleetBoxStatus("home", "box-1", "detached")`, read back with `ListFleetBoxes`, then `Reload`) each close an open socket within 2 s; rotation (`SetFleetBoxToken` with a new hash, read back, `Reload`) does not. |
| + 10. A plain GET with `Carlos-Tunnel-Upgrade: websocket`: the app sees a plain GET with no `Upgrade`; the channel's open count stays 0. |
| + 11. An old box (as Task 5's `TestOldBoxKeepsThe502`): 502, cause `tunnel_upgrade_unsupported`. |
| + 12. Spec §8.2 case 12 in full at cap 128: 200 failed attempts mixing every terminal path, count 0 after each, `firstReleaser` asserted for the two named paths: `ModifyResponse` failing on the 101 (the scene's production `fleetProxy`, built by `fleetProxy(fleet, box, hub)` with only its `ModifyResponse` replaced by one returning an error, served by the scene's TLS server; `relBody`, observed from inside the proxy's error handler; no production seam is added for it) and a hub served behind a writer whose `Hijack` returns `http.ErrNotSupported` (which `countingWriter` and `slotWriter` pass through unchanged, `usagemeter.go:138-144`, `ratelimit.go:235-242`) (the handler blocks on a barrier: count 1 and no releaser; barrier released: count 0, `relBackstop`; the box's app socket closes). Variant: a writer with no `Hijack` method: `relBody`. Then a successful upgrade on the same channel. |
| + 14. The counting store: zero calls during the upgrade sub-tests beyond a plain-request baseline run. |
| + 15. Owner change on a plans-free account (`planGoverned` nil): `UpsertFleet` gives `home` to `k3x`, read back with `FleetOwners`, then `Reload`: both endpoints closed within 2 s; with `Watch` running on a real 2 s tick instead, within 5 s of the write; a new handshake refused. Same for the row moved to `away`, deleted, and a `-tunnel` row re-pointed. |
| + 16. No false closes across 20 Reloads (other hosts, token rotation, the same forward row re-minted unchanged). |
| +- [ ] **Step 2: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/edge/ -run 'TestTunnelWebSocketEndToEnd' -count=1 -v` (sandbox off). Expected: PASS. Show it can fail, twice: give the hub `upgradeCap = 0` (case 2 gets 503); make `sweepUpgrades` a no-op (case 15 times out). |
| +- [ ] **Step 3: Census** (none expected; confirm the card is unchanged). |
| +- [ ] **Step 4: Commit.** |
| + |
| +### Task 7: Maximum load, hub restart, and the interleaving with sockets |
| + |
| +**Files:** |
| +- Create: `internal/edge/tunnel_ws_load_e2e_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: Task 6's scene builder (factor it into an unexported `wsScene(t, opts)` in Task 6's file when this task needs a second shape; Task 6's sub-tests then call it, migrated in this commit). |
| + |
| +- [ ] **Step 1: Write**: |
| + - `TestTunnelWebSocketMaximumLoad` (§8.2 case 13), production values (`DefaultLimits`, cap 128) unless `testing.Short()`, scaled (`Limits{16, 64<<10, 768<<10}`, cap 8) under `-short`: open `cap` sockets whose app side never reads; each client writes 32 KiB chunks with a 500 ms write deadline until one trips (assert it trips, and total bytes accepted per socket `<= StreamWindow + 4 MiB`); the next handshake 503 `Retry-After: 5`; while all stay stalled, 100 (scaled: 7) concurrent plain GETs held by the app until all have arrived, all arrive and complete; a 16 MiB (scaled: 512 KiB) plain POST completes within 10 s with a matching SHA-256; close all sockets: count 0; a new upgrade 101. |
| + - `TestTunnelWebSocketHubRestart` (§8.2 case 9): an open socket; "the hub dies": close the tracking listener and every accepted conn; the client's socket and the app's socket close within 2 s; a new hub (`New` over the same registry, `EnableTunnels`, `Reload`) listens on the same address; the box's `Loop` re-registers within 3 s (backoff cap 2 s, `tunnelclient.go:44`, plus jitter); a new handshake 101. Sub-test `listenerShutdownOnly`: `Server.Shutdown` alone leaves the open socket echoing. |
| + - `TestTunnelWebSocketTwoReloads` (§8.2 case 18 with sockets): Task 4's schedule over Task 6's scene, adding item 7's endpoint closes. |
| +- [ ] **Step 2: Run** `TMPDIR=/tmp/g nice -n 19 go test ./internal/edge/ -run 'TestTunnelWebSocket' -count=1 -short -v`, then without `-short` once (sandbox off; note wall time and peak RSS in the commit message). Expected: PASS both. Show the load test can fail: `ServeWith` with `ConnWindow` 1 MiB (today's default): the POST times out. |
| +- [ ] **Step 3: Commit.** |
| + |
| +### Task 8: The sample's Action Cable channel |
| + |
| +**Files:** |
| +- Create: `examples/rails-shop/app/channels/application_cable/connection.rb`, `examples/rails-shop/app/channels/application_cable/channel.rb`, `examples/rails-shop/app/channels/pings_channel.rb` |
| +- Modify: `examples/rails-shop/app/views/pages/show.html.erb`, `examples/rails-shop/app/jobs/ping_job.rb` (unchanged broadcast name `"pings"`; read it to confirm) |
| + |
| +**Interfaces:** |
| +- `ApplicationCable::Connection < ActionCable::Connection::Base` and `ApplicationCable::Channel < ActionCable::Channel::Base`, both empty (the Rails 8 generator's files). |
| +- `PingsChannel < ApplicationCable::Channel` with `subscribed` calling `stream_from "pings"`. |
| +- The page: wrap the "Jobs done" count in `<span id="done">`; an inline `<script>` (no new asset pipeline: the sample has no importmap) opens `new WebSocket((location.protocol == "https:" ? "wss://" : "ws://") + location.host + "/cable", "actioncable-v1-json")`, sends `{"command":"subscribe","identifier":"{\"channel\":\"PingsChannel\"}"}` on open, and on a message whose `message.id` is set increments `#done`. No new visible words (sample copy unchanged). |
| +- [ ] **Step 1: Build the image** as `docs/site/rails.md` says (`docker buildx build --platform linux/arm64`), then `carlos ship --check` on it. Expected: check passes. |
| +- [ ] **Step 2: Run locally**: start the image with `docker run --rm -p 127.0.0.1:3000:80` (bind loopback only) and `SECRET_KEY_BASE` set, then the §1 curl handshake against `http://127.0.0.1:3000/cable` with `Origin: http://127.0.0.1:3000`: 101 and the welcome frame. Stop the container. |
| +- [ ] **Step 3: Commit** (example files only; no census, no copy). |
| + |
| +### Task 9: Census, whole-branch review, merge |
| + |
| +- [ ] **Step 1:** `make census-card`; reconcile every unit against spec §7; CLAIMS from §7's per-unit text; `make census-propose NAME=tunnel-websockets CLAIMS=<file>`. |
| +- [ ] **Step 2:** Brief Astra from `REVIEW-BRIEF-TEMPLATE.md` for the census and the whole branch (one review, three rounds); focus: the trust rule (marker only with admission), the reservation's terminal paths, `reloadMu` and the sweep, the limits invariant. |
| +- [ ] **Step 3:** Push to amadan; `amadan ci status carlos/platform -branch design-tunnel-websockets-471` green on the tip; the census verdict on #280; `amadan branch describe`. |
| +- [ ] **Step 4:** Paul's merge go, then `amadan branch merge carlos/platform design-tunnel-websockets-471 -squash -expect <full tip> -message "..."` (full arguments; never bare). |
| + |
| +### Task 10: Live on dev |
| + |
| +- [ ] **Step 1:** A release containing the merge, rolled dev first: dev boxes including r10r's `box-1`, then the dev console box (sophie, the hub), the CLI on DOCS-T1. No flagship until Paul says. |
| +- [ ] **Step 2:** Ship the Task 8 sample to `shop` on dev (`carlos ship --rootfs`, promote, `carlos deploy` verification by `X-Carlos-Version`). |
| +- [ ] **Step 3:** From DOCS-T1, the spec §1 handshake against `https://shop.bab.dev.oncarlos.com/cable` with `curl --http1.1 -i -N --max-time 10`: `HTTP/1.1 101 Switching Protocols`, `Sec-WebSocket-Protocol: actioncable-v1-json`, then the bytes of `{"type":"welcome"}` and a `{"type":"ping",...}` about every 3 s. In a browser, "Enqueue a job" updates the count without a reload. |
| +- [ ] **Step 4:** Revocation, per D-1 as ruled. With (a): `carlos apps create --app cable --place fleet/r10r --account bab`, ship and promote the same image, instance `cable.bab.dev.oncarlos.com`; open its `/cable` with a client that logs frames; `carlos apps delete --app cable --account bab`; the socket closes within 30 s (the instance pass's convergence plus the 2 s watch); then purge `cable`. |
| +- [ ] **Step 5:** Plain HTTP unchanged: `curl -sI https://shop.bab.dev.oncarlos.com/up` 200 with one `x-carlos-version`; `railsdemo.bab.dev.oncarlos.com/up` 200. |
| +- [ ] **Step 6:** Report on #471 with the transcript. No flagship roll until Paul says so. |
| + |
| +--- |
| + |
| +## Self-review |
| + |
| +1. **Spec coverage.** §4.3 handshake: Tasks 1, 2 (halves), 5 (switch-on). §4.4 headers and trust rule: Task 1 (shim strip), Task 3 (scrub, inbound delete), Task 5 (admission required). §4.4.1 `X-Forwarded-Proto`: Task 6 case 2. §4.5 gate: Task 6 cases 1-2. §4.6 enforcement and `CloseAccountUpgrades`: Task 5 migration, Task 6 case 3. §4.6.1 tenancy and sweep: Tasks 3, 4; witness Task 6 cases 15-16. §4.6.2 reservation: Task 3; terminal paths Task 6 case 12. §4.6.3 inventory: Task 4's guard and caller list. §4.7 lifetimes: Task 6 cases 3, 6, 7, 8, 15; Task 7 hub restart. §4.8 limits: Task 1 (server), Task 3 (cap, invariant), Task 7 (maximum load). §4.9 compatibility: Task 1 (capability), Task 5 (`TestOldBoxKeepsThe502`). §5 provider: nothing to build. §6 budget: Task 6 case 14. §7 census and copy: every task's census step, Task 0, Task 9. §8.1: Tasks 1, 2, 3. §8.2: Tasks 3-7. §8.3 live: Task 10. §11 item 4 sample: Task 8. §12 rollout: Task 10. |
| +2. **Step scan.** Every test names its assertions and values; code steps give signatures and the values the spec pins; no body beyond those. |
| +3. **Type consistency.** `Limits{MaxStreams uint32; StreamWindow, ConnWindow int32}` (Tasks 1, 3, 7); `RoundTripUpgrade(ctx, cc, req) (*http.Response, error)` (Tasks 2, 5); `reserveUpgrade(inbound, a, tc, capN) (*upgradeReservation, context.Context, error)` (Tasks 3, 4, 5); `release(by releaser)`, `firstReleaser()` (Tasks 3, 4, 6); `channel(name) *tunnelConn` (Tasks 3, 5); `tenancy` and `upgradeAdmission` (Tasks 3, 4, 5); `reloadHooks` (Tasks 4, 7). |
| +4. **Review Focus.** Five lines, each with its test in its owning task (Tasks 2, 4, 5, 5, 6). |
| +5. **Proportion.** About a quarter of the spec's length; code appears only as signatures, constants and the copy table. |