Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: implement serialized app-to-dial focus transactions to prevent race conditions during machine navigation

0xken1594dda50aae06
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index dc00b39d9..aabac0206 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -246,6 +246,31 @@ describe('DaemonCableHost.listAgents across machines', () => {
expect(fleet.sendTurn).toHaveBeenCalledWith('other', 'r1', 'ship it')
})
+ it('reports a dial focus with the machine that owns the agent', async () => {
+ AGENTS.length = 0
+ const focused = vi.fn()
+ const host = new DaemonCableHost(
+ wiring({ focused }),
+ crossFleet({ other: [{ id: 'r1', name: 'api' }] }),
+ )
+ await settled(host)
+
+ host.focus('r1')
+
+ expect(focused).toHaveBeenCalledWith('other', 'r1')
+ })
+
+ it('does not guess a machine for an unknown dial focus', async () => {
+ AGENTS.length = 0
+ const focused = vi.fn()
+ const host = new DaemonCableHost(wiring({ focused }), crossFleet({ other: [] }))
+ await settled(host)
+
+ host.focus('missing-agent')
+
+ expect(focused).not.toHaveBeenCalled()
+ })
+
it('keeps a local agent local even while another machine is selected', async () => {
AGENTS.length = 0
AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, engine: 'claude' })
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 3fa305547..d08b2ecd8 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -42,8 +42,8 @@ export interface CableHostWiring {
updateAgent?: (agentId: string, model?: string, effort?: string) => void
/** The runtime catalog, from the same provider the web and the WiFi device read. */
listModels?: (agentId: string) => Promise<Array<{ id: string }>>
- /** The dial moved to another agent — the desktop window should show that one. */
- focused?: (agentId: string) => void
+ /** The dial moved to another agent — the desktop window should show that agent on its own machine. */
+ focused?: (machineId: string, agentId: string) => void
/** A finger on the dial's glass, in pieces, while it is down. */
scrolled?: (phase: 'down' | 'move' | 'up', dy: number, velocity: number) => void
log: (line: string) => void
@@ -379,9 +379,15 @@ export class DaemonCableHost implements CableHost {
// grew panes for remote machines. The hand is still at THIS desk; the pane it wants in front of it
// may simply belong to a machine somewhere else, and the app is the side that decides what it can do
// about an agent it does not have.
- this.wiring.log(`cable: focus ${agentId}`)
-
- this.wiring.focused?.(agentId)
+ const machineId = this.machineOf(agentId)
+ if (!machineId) {
+ // An agent id without its machine is not routable. Guessing the selected or local machine is how a
+ // remote dial move used to yank the desktop back to a local agent.
+ this.wiring.log(`cable: ignored focus for unknown agent ${agentId}`)
+ return
+ }
+ this.wiring.log(`cable: focus ${machineId}/${agentId}`)
+ this.wiring.focused?.(machineId, agentId)
}
scrolled(phase: 'down' | 'move' | 'up', dy: number, velocity: number): void {
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index 8e0bf2867..87a23de42 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -317,6 +317,113 @@ describe('cable session', () => {
await session.stop()
})
+ it('ignores stale dial focus while the app switches to a remote machine', async () => {
+ let selected = 'mac-local'
+ let finishSelection!: () => void
+ const selectionGate = new Promise<void>((resolve) => { finishSelection = resolve })
+ const host = makeHost({
+ selectedMachine: () => selected,
+ selectMachine: vi.fn(async (machineId: string) => {
+ await selectionGate
+ selected = machineId
+ return { ok: true as const }
+ }),
+ })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+
+ const following = session.followApp('remote-machine', 'r1')
+ await settle()
+ port.say({ t: 'focus', agentId: 'a1' }) // old tile reported while the list is rebuilding
+ await settle()
+ expect(host.focus).not.toHaveBeenCalled()
+
+ finishSelection()
+ await following
+ expect(port.sent.filter((m) => m.t === 'focus').map((m) => m.agentId)).toContain('r1')
+
+ port.say({ t: 'focus', agentId: 'a1' }) // stale old tile, delivered just after the switch completed
+ await settle()
+ expect(host.focus).not.toHaveBeenCalled()
+
+ port.say({ t: 'focus', agentId: 'r1' }) // echo of the app-driven focus
+ await settle()
+ expect(host.focus).not.toHaveBeenCalled()
+
+ port.say({ t: 'focus', agentId: 'r2' }) // a real subsequent dial move
+ await settle()
+ expect(host.focus).toHaveBeenCalledWith('r2')
+ await session.stop()
+ })
+
+ it('does not bounce a local app selection back to the previous remote agent', async () => {
+ let selected = 'remote-machine'
+ let finishSelection!: () => void
+ const selectionGate = new Promise<void>((resolve) => { finishSelection = resolve })
+ const host = makeHost({
+ selectedMachine: () => selected,
+ selectMachine: vi.fn(async (machineId: string) => {
+ await selectionGate
+ selected = machineId
+ return { ok: true as const }
+ }),
+ })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+
+ const following = session.followApp('mac-local', 'a2')
+ await settle()
+ port.say({ t: 'focus', agentId: 'r1' })
+ await settle()
+ expect(host.focus).not.toHaveBeenCalled()
+
+ finishSelection()
+ await following
+ port.say({ t: 'focus', agentId: 'r1' }) // late report from the previous remote tile
+ await settle()
+ expect(host.focus).not.toHaveBeenCalled()
+
+ port.say({ t: 'focus', agentId: 'a2' }) // acknowledgement of the commanded local tile
+ await settle()
+ port.say({ t: 'focus', agentId: 'r2' }) // subsequent physical dial move still works
+ await settle()
+ expect(host.focus).toHaveBeenCalledTimes(1)
+ expect(host.focus).toHaveBeenCalledWith('r2')
+ await session.stop()
+ })
+
+ it('coalesces quick app selections so the newest one focuses last', async () => {
+ let selected = 'mac-local'
+ let finishFirstSelection!: () => void
+ const firstSelectionGate = new Promise<void>((resolve) => { finishFirstSelection = resolve })
+ let selections = 0
+ const host = makeHost({
+ selectedMachine: () => selected,
+ selectMachine: vi.fn(async (machineId: string) => {
+ selections += 1
+ if (selections === 1) await firstSelectionGate
+ selected = machineId
+ return { ok: true as const }
+ }),
+ })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+ port.sent.length = 0
+
+ const oldSelection = session.followApp('remote-machine', 'r1')
+ await settle()
+ const newestSelection = session.followApp('mac-local', 'a2')
+ finishFirstSelection()
+ await Promise.all([oldSelection, newestSelection])
+
+ expect(port.sent.filter((m) => m.t === 'focus').map((m) => m.agentId)).toEqual(['a2'])
+ expect(selected).toBe('mac-local')
+ await session.stop()
+ })
+
it('forwards a whole stroke, including the reports that carry no travel', async () => {
// The ends of a stroke are the point of the message, not padding around it: a `down` with nothing in
// it is what stops a fling still running on the far side, and an `up` with nothing in it is a finger
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 3632a20e7..072071c73 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -68,6 +68,12 @@ const FW_WRITES_PER_HOUR = 3
/** How often the machine list is re-read. Slower than the agent list because it is an HTTP read, not a
* map lookup — and because a machine appearing is not something anyone is waiting on a stopwatch for. */
const MACHINES_POLL_MS = 15_000
+/**
+ * A programmatic focus write may be followed by the dial reporting the tile it was painting just before
+ * that write. Real hardware delivered that stale report 23 ms after the machine switch completed; keep
+ * a short transaction open until the commanded tile echoes, without making the dial feel unresponsive.
+ */
+const APP_FOCUS_SETTLE_MS = 750
/** What a `voice.begin` without an `sr` is assumed to be — firmware old enough not to say. */
const DEFAULT_VOICE_RATE = 16_000
@@ -228,6 +234,17 @@ export class CableSession {
private readonly writeLog = new Map<string, number[]>()
/** The agent the dial is on, as last observed or commanded. See followApp() for why this exists. */
private dialFocus = ''
+ /**
+ * App-driven machine/focus changes are one transaction. Without this queue, two quick desktop clicks
+ * can interleave their machine lists and let the older click focus last.
+ */
+ private appFocusTail: Promise<void> = Promise.resolve()
+ private appFocusGeneration = 0
+ /** While the app is rebuilding the dial's machine/list state, focus reports describe that rebuild. */
+ private drivingAppFocus = false
+ /** The dial may echo a focus command after its write promise resolves; consume that one echo. */
+ private expectedAppFocusEcho = ''
+ private expectedAppFocusEchoUntil = 0
/** The same, for the machine wheel. Both reset together on any new port — see `tryOpen`. */
private lastMachinesKey = ''
/** Throttle for the machine list, which costs an HTTP read where the agent list costs a map lookup. */
@@ -420,6 +437,10 @@ export class CableSession {
this.decoder.reset()
this.greetedMac = null
this.greetedFw = null
+ this.appFocusGeneration += 1
+ this.drivingAppFocus = false
+ this.expectedAppFocusEcho = ''
+ this.expectedAppFocusEchoUntil = 0
// A new port is a new dial until proven otherwise; tell it everything.
this.lastAgentsKey = ''
this.lastMachinesKey = ''
@@ -442,6 +463,9 @@ export class CableSession {
this.link = null
this.greetedMac = null
this.greetedFw = null
+ this.appFocusGeneration += 1
+ this.expectedAppFocusEcho = ''
+ this.expectedAppFocusEchoUntil = 0
this.lastAgentsKey = ''
this.lastMachinesKey = ''
this.voice = null
@@ -575,10 +599,30 @@ export class CableSession {
}
case 'focus':
if (str('agentId')) {
+ const agentId = str('agentId')!
+ const now = Date.now()
+ const expectationActive = this.expectedAppFocusEcho !== ''
+ && now <= this.expectedAppFocusEchoUntil
+ if (expectationActive) {
+ // Until the commanded tile echoes, every other focus is from the carousel/list repaint that
+ // command caused. Do not even update dialFocus: the daemon already commanded the newer truth.
+ if (agentId === this.expectedAppFocusEcho) {
+ this.expectedAppFocusEcho = ''
+ this.expectedAppFocusEchoUntil = 0
+ }
+ return
+ }
+ if (now > this.expectedAppFocusEchoUntil) {
+ this.expectedAppFocusEcho = ''
+ this.expectedAppFocusEchoUntil = 0
+ }
+ // A machine switch re-paints the carousel and may report its old tile while the new list is in
+ // flight. That is not a hand choosing an agent, so it must not drive the desktop back.
+ if (this.drivingAppFocus) return
// Remember where the dial IS, not just that it said so: followApp() compares against this to
// avoid echoing the dial's own move back at it.
- this.dialFocus = str('agentId')!
- this.host.focus(str('agentId')!)
+ this.dialFocus = agentId
+ this.host.focus(agentId)
}
return
case 'scroll': {
@@ -997,13 +1041,36 @@ export class CableSession {
*/
async followApp(machineId: string, agentId: string): Promise<void> {
if (!this.link?.isOpen || this.greetedMac === null) return
- if (machineId && machineId !== this.host.selectedMachine()) {
- this.host.log(`cable: following the app to machine ${machineId}`)
- await this.selectMachine(machineId)
- }
- if (!agentId || agentId === this.dialFocus) return
- this.host.log(`cable: following the app to agent ${agentId}`)
- await this.focusAgent(agentId)
+ if (!agentId) return
+
+ const generation = ++this.appFocusGeneration
+ const task = this.appFocusTail.then(async () => {
+ // A newer desktop selection made this queued one obsolete before it started.
+ if (generation !== this.appFocusGeneration) return
+ this.drivingAppFocus = true
+ try {
+ if (machineId && machineId !== this.host.selectedMachine()) {
+ this.host.log(`cable: following the app to machine ${machineId}`)
+ await this.selectMachine(machineId)
+ }
+ // A newer selection can arrive while the remote machine RPC/list push is in flight. Never let
+ // this older transaction focus after it finishes.
+ if (generation !== this.appFocusGeneration || agentId === this.dialFocus) return
+ this.host.log(`cable: following the app to agent ${agentId}`)
+ this.expectedAppFocusEcho = agentId
+ this.expectedAppFocusEchoUntil = Date.now() + APP_FOCUS_SETTLE_MS
+ await this.focusAgent(agentId)
+ } finally {
+ this.drivingAppFocus = false
+ }
+ })
+ // Keep the queue usable after one transport failure. The local websocket intentionally
+ // fire-and-forgets followApp, so the session log is the only place an unexpected rejection would
+ // otherwise be visible; consume it here rather than creating an unhandled rejection.
+ this.appFocusTail = task.catch((err) => {
+ this.host.log(`cable: could not follow app focus (${(err as Error).message})`)
+ })
+ await this.appFocusTail
}
async toast(text: string): Promise<void> {
await this.send({ t: 'toast', text })
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 95ddb2894..758206f91 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3099,7 +3099,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// Both of these are LOCAL-ONLY on purpose (backend.sendLocal, not backend.send): they describe a hand
// at this desk, not a change in what the machine is doing, and the cloud web audience may be sitting
// at another computer entirely.
- focused: (agentId) => backend.sendLocal({ type: 'dial_focus', payload: { agentId } }),
+ focused: (machineId, agentId) => backend.sendLocal({ type: 'dial_focus', payload: { machineId, agentId } }),
scrolled: (phase, dy, velocity) => backend.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),
log: (line) => console.log(`[cable] ${line}`),
}, fleet)
diff --git a/docs/plans/2026-08-28-003-mesh-secret-e2ee-plan.md b/docs/plans/2026-08-28-003-mesh-secret-e2ee-plan.md
new file mode 100644
index 000000000..00be1b7b2
--- /dev/null
+++ b/docs/plans/2026-08-28-003-mesh-secret-e2ee-plan.md
@@ -0,0 +1,290 @@
+# Mesh secret for machine-to-machine E2EE (replaces `harness link create/import`)
+
+Status: proposed · 2026-08-28
+
+## Context
+
+A user can own several **machines**, each with its own Ed25519 identity
+(`E2eeStore`, `cli/src/lib/e2ee/store.ts`). To E2EE two machines directly
+with each other (machine-to-machine relay, not through a browser), today's
+flow is per-pair and manual:
+
+1. On the target machine T: `harness link create` builds a `SetupTokenPayload`
+ signed with T's own identity (`core.ts:181-232`, `encodeSetupToken`),
+ 7-day TTL, reusable until expiry.
+2. User copies the token to source machine S, runs `harness link import
+ <token>` → `claimSetupToken` (`relayClient.ts:157-225`) dials
+ `/api/web-ws`, sends `machine_select{machineId:T}` then
+ `e2e_setup_claim{token, identityPub:S.pub, sig}`.
+3. `manager.ts` `onSetupClaim` on T verifies + pins S into T's `paired.json`;
+ S pins T into its own `machinePeers.json` (`cli.ts:3600`).
+4. Result: trust for **exactly one ordered pair**. Full-mesh over N machines
+ needs N·(N-1) manual create/copy/import cycles.
+
+**Goal of this plan:** the user generates **one secret**, imports it into
+every machine, and any two machines in that group bootstrap E2EE with each
+other automatically the first time they need to talk — zero per-pair steps.
+
+Verified in code (no backend change needed for any of this):
+- `apps/backend/src/lib/webWs.ts` `handleFrame` forwards any frame type it
+ doesn't special-case straight to the target machine once `machine_select`
+ succeeds and `binding.userId === user.sub` — pure ownership check, no
+ extra secret at the backend layer. All work below is confined to this
+ repo (`autonomous-harness/cli`).
+- Real chat traffic (post-bootstrap) uses a fresh ephemeral X25519 key per
+ connection (`sessionKeys`, `core.ts:242`), independent of whatever
+ bootstrapped the identity pin — so this redesign only changes how two
+ machines first come to trust each other's Ed25519 identity, never the
+ confidentiality of ongoing traffic.
+- CPace primitives already in `core.ts:133-179` (used today for the 6-char
+ browser pairing code) are reusable for a persistent secret: each run has
+ its own `sid`/ephemeral values, so reusing the same secret across many
+ bootstrap runs does not create cross-run transcript collisions.
+
+**Decisions locked in with the user:**
+- Bootstrap is fully automatic (zero-touch) — but every new mesh pin must be
+ logged clearly (daemon log + visible in `harness mesh status`), so a
+ compromise-driven pin still leaves a trail the user can audit. This is
+ the one accepted tradeoff: removing the human-in-the-loop step means a
+ leaked secret + one compromised machine can self-propagate trust across
+ the whole mesh — logging is the mitigation, not a blocker.
+- `harness link create/import/unlink` is **fully replaced**, not kept in
+ parallel. Existing pins in `machinePeers.json`/`paired.json` are untouched
+ (they're keyed by Ed25519 pubkey, not by how they were established) — only
+ the CLI surface for creating *new* pins changes.
+- `rotate` and `revoke` stay separate operations: rotating the mesh secret
+ only blocks *new* machines from joining with the old secret; it does not
+ revoke already-pinned peers. Revoking one peer is `harness mesh unlink
+ <machineId>`.
+
+## Dependency graph
+
+```
+Phase 1 (crypto + storage primitives)
+ │
+ ▼
+Phase 2 (bootstrap protocol: manager handlers + client-side dial)
+ │
+ ▼
+Phase 3 (CLI surface: new `mesh` commands, remove old `link` commands)
+ │
+ ▼
+Phase 4 (tests + end-to-end verification)
+```
+
+Linear dependency — each phase needs the previous phase's surface to exist
+before it can be exercised. Within Phase 2, the manager-side handler and the
+client-side dial code are two sub-tracks that touch different files and
+could be split across two people/agents in parallel, but both must land
+before either can be tested against the other.
+
+---
+
+## Phase 1 — Core crypto + storage primitives
+
+**Goal:** the building blocks a mesh bootstrap needs exist and are
+unit-testable in isolation, with no protocol wiring yet.
+
+**Depends on:** nothing (first phase).
+
+**Scope in:** new pure functions in `core.ts`; new `MeshSecretStore`; the
+`MachinePeer` shape gains a field to record how a pin was established.
+
+**Scope out:** no CLI commands yet, no manager/relay wiring, no removal of
+old `link` code (that happens in Phase 3, once the replacement works
+end-to-end).
+
+**Files:**
+- `cli/src/lib/e2ee/core.ts`
+ - `newMeshSecret(rng)` — 32 random bytes, encode as base64url with a
+ recognizable prefix (e.g. `msk_...`) so it's visually distinct from
+ setup tokens or pairing codes.
+ - `meshContext(idA, idB)` — hashes both `machineId`s in a fixed sort
+ order into a channel identifier (`ci`), replacing the browser-pairing
+ `pairContext('a:adapter'|'b:web')` convention for this use case, so a
+ transcript is bound to the exact pair of machines and can't be
+ replayed against a different pair.
+- `cli/src/lib/e2ee/meshStore.ts` (**new file**)
+ - `MeshSecretStore`: `get()`, `set(secret)`, `clear()`, persisting
+ `meshSecret.json` under `${ADAPTER_DATA_DIR}/e2e/`, mode 0600 — mirror
+ the secure-write helper `store.ts` already uses for `identity.json`.
+- `cli/src/lib/e2ee/machinePeers.ts`
+ - Add `linkMethod?: 'mesh'` to `MachinePeer`. Optional field — existing
+ records without it stay valid.
+
+**Steps:**
+1. Implement `newMeshSecret`/`meshContext` in `core.ts` next to the existing
+ CPace helpers, following the same style (pure functions, no I/O).
+2. Implement `MeshSecretStore` in `meshStore.ts`, reusing whatever secure
+ file-write helper `store.ts` exports (don't duplicate the perms logic).
+3. Add the `linkMethod` field to `MachinePeer` and thread it through
+ `MachinePeerStore.pin`'s signature as an optional param.
+
+**Verify:**
+- New unit tests in `core.test.ts` for `newMeshSecret` (length/format) and
+ `meshContext` (deterministic regardless of argument order, different
+ output for different pairs).
+- A small test for `MeshSecretStore` round-tripping get/set/clear and file
+ permissions (0600).
+
+**Exit criteria:** `npx vitest run src/lib/e2ee/core.test.ts` passes with
+the new cases; `MeshSecretStore` compiles and is usable from a scratch
+script without touching any other module.
+
+---
+
+## Phase 2 — Bootstrap protocol (manager handlers + client dial)
+
+**Goal:** two machines that both hold the same mesh secret can complete a
+CPace handshake over the existing relay channel and pin each other, with no
+user interaction.
+
+**Depends on:** Phase 1 (`meshContext`, `MeshSecretStore`, `linkMethod`).
+
+**Scope in:** new frame types, manager-side handler, client-side bootstrap
+function, glare tie-break, rate limiting. Not yet wired into the automatic
+`dial()` path — that's testable directly via the manager/relay test
+harnesses first.
+
+**Scope out:** CLI commands (Phase 3), removing old `link`/setup-token code
+(Phase 3, since it must keep working until the replacement is proven).
+
+**Files:**
+- `cli/src/lib/e2ee/manager.ts`
+ - `onMeshHello`, `onMeshPake` — parallel to the existing
+ `onPairIntent`/`onPake` but keyed by the peer's `machineId` (not
+ `connId` + a user-typed code): verify the requester against this
+ machine's own `MeshSecretStore.get()`; if no local secret, or the CPace
+ exchange fails, reply `e2e_denied{reason:'no-mesh-secret'}` — no extra
+ detail leaked.
+ - Tie-break: when both sides could initiate at once, the machine with the
+ lexicographically smaller `machineId` is always the initiator; the
+ other only responds.
+ - Rate limiting: a counter separate from the existing browser-pairing
+ `RATE_MAX`, capping new mesh pins per machine per time window — this is
+ about capping relay/CPU spam and limiting propagation speed if a secret
+ leaks, not about resisting brute force (32 random bytes makes brute
+ force moot).
+ - On success: `machinePeers.pin(peerMachineId, peerPub, 'mesh-auto', now,
+ {linkMethod:'mesh'})`, plus an info-level log line naming the peer
+ machine and fingerprint — this is the audit trail the zero-touch
+ decision relies on.
+- `cli/src/lib/e2ee/relayClient.ts`
+ - `runMeshBootstrap(ws, selfIdentity, meshSecret, targetMachineId)` — runs
+ the CPace roundtrip against the target using `e2e_mesh_hello`/
+ `e2e_mesh_pake` frame types (deliberately separate from `e2e_pake` so
+ the browser-pairing state machine is untouched), pins the result the
+ same way as the manager side.
+- New frame types `e2e_mesh_hello`, `e2e_mesh_pake` — add wherever the
+ existing `e2e_pake`/`e2e_hello` frame type constants are declared.
+
+**Steps:**
+1. Add the frame type constants and wire `manager.ts`'s frame dispatch to
+ route them to the new handlers (mirror how `e2e_pair_intent`/`e2e_pake`
+ are already routed).
+2. Implement `onMeshHello`/`onMeshPake` with the tie-break and rate limit.
+3. Implement `runMeshBootstrap` in `relayClient.ts`.
+4. Do **not** touch `remoteRelay.ts` `dial()` yet — that integration is the
+ last step of this phase, once both sides are independently testable.
+5. Wire `dial()`: before throwing `NO_PEER_LINK`, if `MeshSecretStore.get()`
+ returns a secret, call `runMeshBootstrap`; on success, fall through to
+ the existing `e2e_hello`/`e2e_welcome` session flow unchanged.
+
+**Verify:**
+- Extend `manager.test.ts` with cases: successful mesh pin, denied when
+ secrets don't match, denied when responder has no secret at all, glare
+ tie-break resolves to one initiator, rate limit trips after N attempts.
+- Extend `relayLink.spec.ts` with a case that exercises `dial()` hitting
+ `NO_PEER_LINK` → auto mesh bootstrap → success → normal session proceeds.
+
+**Exit criteria:** `npx vitest run src/lib/e2ee/manager.test.ts
+src/lib/e2ee/relayLink.spec.ts` passes; a two-instance in-process test
+(matching the existing pattern in `manager.test.ts`) shows two machines
+with the same secret pinning each other with no manual step.
+
+---
+
+## Phase 3 — CLI surface: `harness mesh …`, remove `harness link …`
+
+**Goal:** the user-facing commands exist, and the old per-pair token flow
+is gone.
+
+**Depends on:** Phase 2 (bootstrap must work before removing the fallback
+that currently provides the only way to link machines).
+
+**Scope in:** new `mesh` command group in `cli.ts`; deletion of the `link`
+command group and all setup-token code it depended on.
+
+**Scope out:** none — this phase should leave no dangling references to the
+old flow.
+
+**Files:**
+- `cli/src/cli.ts` — replace the `link` block (~line 3546-3631) with:
+ - `harness mesh secret generate` — prints the secret once with a clear
+ "store this like a password, it will not be shown again" warning; also
+ saves it locally so the machine running the command joins the mesh too.
+ - `harness mesh secret import <secret>` — validates format, saves
+ locally.
+ - `harness mesh secret rotate` — generates and prints a new secret;
+ help text must say explicitly this does not revoke existing peers.
+ - `harness mesh status` — lists peers pinned with `linkMethod:'mesh'`
+ (machineId, label, fingerprint, linkedAt) for audit.
+ - `harness mesh unlink <machineId>` — calls the existing
+ `MachinePeerStore.unlink`.
+- `cli/src/lib/e2ee/core.ts` — remove `SetupTokenPayload`,
+ `encodeSetupToken`, `verifySetupToken`, `setupClaimSig`,
+ `setupClaimVerify`.
+- `cli/src/lib/e2ee/store.ts` — remove `createSetupToken`/
+ `validateSetupToken` (confirm nothing else calls them first).
+- `cli/src/lib/e2ee/relayClient.ts` — remove `claimSetupToken`.
+- `cli/src/lib/e2ee/manager.ts` — remove `onSetupClaim`.
+
+**Steps:**
+1. `rg` across `cli/src` for every removed function/type name to make sure
+ nothing outside the files above still references them.
+2. Implement the `mesh` command group, reusing `MachinePeerStore.list`/
+ `unlink` as-is.
+3. Delete the old `link` command group and the setup-token functions listed
+ above.
+4. Update any CLI help text / `--help` output that still mentions `link`.
+
+**Verify:**
+- `npx tsc --noEmit` (or `npm run build`) — no leftover references.
+- Manual: `harness --help` shows `mesh`, not `link`.
+
+**Exit criteria:** build is clean; `grep -rn "setupClaim\|SetupTokenPayload\|linkCreateCommand\|linkImportCommand" cli/src` returns nothing.
+
+---
+
+## Phase 4 — Tests + end-to-end verification
+
+**Goal:** confidence the replacement works across machines, and the two
+adversarial cases (rotate-without-revoke, revoke) behave as documented.
+
+**Depends on:** Phase 3 (final CLI surface must exist).
+
+**Scope in:** finishing/tightening the test suite; one real two-machine
+manual run against a local backend.
+
+**Files:** `core.test.ts`, `manager.test.ts`, `relayLink.spec.ts` (no new
+files expected, just filling gaps left by Phases 1-3's incremental tests).
+
+**Steps / Verify (manual E2E):**
+1. Run two daemon instances against the same local backend and the same
+ user account (two distinct machines A and B).
+2. On A: `harness mesh secret generate` → copy the printed secret.
+3. On B: `harness mesh secret import <secret>`.
+4. Trigger B to dial A for the first time (e.g. a `remoteRelay` request via
+ `/api/local-ws`) — confirm no manual step is needed, `harness mesh
+ status` on both A and B shows the other with a matching fingerprint, and
+ the daemon log on both sides has a clear "new mesh peer pinned" line.
+5. `harness mesh secret rotate` on A → confirm B (already pinned) still
+ works; introduce a third machine C with the *old* secret → confirm C
+ fails to bootstrap (only the new secret works for new joins).
+6. `harness mesh unlink <machineId>` on A for B → confirm a subsequent dial
+ either re-bootstraps (if B still holds the secret) or fails with
+ `NO_PEER_LINK` (if the secret was cleared on B too).
+
+**Exit criteria:** full vitest suite green; the six manual steps above all
+behave as described, with no step requiring the user to type or paste a
+value on any machine except the initial secret import.