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.

Buddy on Windows: prove a command's pane from its parents, as on a Mac (#2979)

lingrd7114d649faf8
diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.ts
index 5fffd93dc..cede61ba6 100644
--- a/backend/src/superTabs/buddies.test.ts
+++ b/backend/src/superTabs/buddies.test.ts
@@ -411,16 +411,20 @@ describe('adding a Buddy', () => {
expect(f.state.conversations.filter(c => c.kind === 'swarm-buddy')).toHaveLength(1)
})
- // Security review of #2093 (Lead's ruling): Harness cannot yet tell a Buddy's window from another agent's on Windows, so a
- // Buddy there made every agent's Swarm command on that PC refuse. None is added there until a real caller check exists.
- it('is refused on a Windows machine, with the reason, and allowed on a Mac or Linux one', () => {
+ // Security review of #2093 (Lead's ruling): a Windows host from before its caller check made every agent's Swarm command on
+ // that PC refuse while a Buddy ran there. One that reports the check takes a Buddy as a Mac does.
+ it('is refused on a Windows machine from before its caller check, and allowed on one that has it, a Mac or Linux', () => {
+ const seen = (g: ReturnType<typeof fresh>) => g.state.machines!.find(m => m.machineId === 'peer-mac')!.observation!
const f = fresh()
- const os = (name: string | null) => { f.state.machines!.find(m => m.machineId === 'peer-mac')!.observation!.resources.os = name }
+ const os = (name: string | null) => { seen(f).resources.os = name }
os('Windows')
- expect(() => addBuddy(f, peer, f.app.projectId)).toThrow('A Buddy cannot run on a Windows machine yet')
+ expect(() => addBuddy(f, peer, f.app.projectId)).toThrow('Update Harness on this Windows machine')
expect(f.state.starts ?? []).toEqual([])
- os('Linux')
+ seen(f).capabilities = [...seen(f).capabilities ?? [], 'windowsBuddy']
expect(addBuddy(f, peer, f.app.projectId).result.startId).toBeTruthy()
+ const g = fresh()
+ seen(g).resources.os = 'Linux'
+ expect(addBuddy(g, peer, g.app.projectId).result.startId).toBeTruthy()
})
// A machine of theirs outside the Swarm takes a Buddy only with its setup (buddyMachines.test.ts).
diff --git a/backend/src/superTabs/buddyMachines.test.ts b/backend/src/superTabs/buddyMachines.test.ts
index e0db4e249..26b897e6a 100644
--- a/backend/src/superTabs/buddyMachines.test.ts
+++ b/backend/src/superTabs/buddyMachines.test.ts
@@ -179,11 +179,18 @@ describe('a Buddy on its person\'s own machine outside the Swarm', () => {
expect(rows.roster.filter(r => 'joinTeam' in r)).toEqual([])
})
- it('refuses its Buddy\'s launch once the machine reads as Windows', () => {
+ it('refuses its Buddy\'s launch once the machine reads as a Windows host from before its caller check', () => {
const f = setup()
const added = addOwn(f, f.app.projectId)
buddyOnly(f)!.observation = reading(1000, 'Windows')
- expect(() => f.run({ type: 'agent.startDispatch', startId: added.result.startId as string }, peer)).toThrow('A Buddy cannot run on a Windows machine yet')
+ expect(() => f.run({ type: 'agent.startDispatch', startId: added.result.startId as string }, peer)).toThrow('Update Harness on this Windows machine')
+ })
+
+ it('launches its Buddy on a Windows host that has the caller check', () => {
+ const f = setup()
+ const added = addOwn(f, f.app.projectId)
+ buddyOnly(f)!.observation = { ...reading(1000, 'Windows'), capabilities: ['swarmBuddy', 'windowsBuddy'] }
+ expect(() => f.run({ type: 'agent.startDispatch', startId: added.result.startId as string }, peer)).not.toThrow()
})
it('keeps its record through storage', () => {
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index fb5171727..1f560480b 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,6 +1,6 @@
import { applyPushOrigin, failPushUnknown, failTeamWritten, hasStep, mainAccountMembers, markTeamWritten, requireNameable, requireTeamWrittenAccount, requireTeamWrittenMachine, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
import type { PushOrigin } from '../github/pushOrigin.js'
-import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machinesFull, MACHINES_FULL_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'
+import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machinesFull, MACHINES_FULL_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'
import { setName, writtenNameOf } from './personNames.js'
@@ -2526,10 +2526,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// else of the Swarm reaches it.
const pool = listed ?? (command.setup ? addBuddyMachine(command.machineId, command.setup, me) : fail('BUDDY_MACHINE', 'Update Harness, then add your Buddy again.', 403))
if (pool.contributorId !== me.id || pool.hostMachineId || pool.observation?.sessionKind === 'team') notOwn()
- // Harness cannot yet tell a Buddy's window from another agent's on Windows (security review of #2093): its machine
- // refused every agent's Swarm command while one ran there. None is added on Windows until a real caller check exists
- // (Lead's ruling, 10-29); the machine's own refusal stays as the backstop, and its launch is checked again (machines.ts).
- if (pool.observation?.resources.os === 'Windows') fail('BUDDY_WINDOWS', BUDDY_WINDOWS_REFUSAL, 403)
+ // A Windows host from before its caller check refused every agent's Swarm command while a Buddy ran there (security
+ // review of #2093; Lead's ruling, 10-29): none is added on one, and its launch is checked again (machines.ts).
+ if (refusesWindowsBuddy(pool)) fail('BUDDY_WINDOWS', BUDDY_WINDOWS_REFUSAL, 403)
// A host that runs a Swarm Buddy makes its folder of project worktrees (spec: Folder). One not yet reporting (a machine
// just added for Buddies) is let through: an older host would start it in an empty folder that reads nothing.
if (pool.observation && !pool.observation.capabilities?.includes(SWARM_BUDDY_CAPABILITY)) {
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 22b7b6cc2..53aff8404 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -576,8 +576,12 @@ export function recordAgentPresence(state: SuperTabState, machineId: string, run
/** Why a start other than its own person's Buddy is refused on a Buddy-only machine: worded as for any machine outside the
* Swarm, so the refusal says nothing about whose it is or what runs there. */
-/** Harness cannot yet tell a Buddy's window from another agent's on Windows (security review of #2093). */
-export const BUDDY_WINDOWS_REFUSAL = 'A Buddy cannot run on a Windows machine yet. Pick one of your Macs or Linux machines.'
+/** A host that can tell a Buddy's window from another agent's on Windows (CLI callerPane.ts `windowsRunningPane`). An older one
+ * cannot: a Buddy there refused every agent's Swarm command on that computer (security review of #2093). */
+export const WINDOWS_BUDDY_CAPABILITY = 'windowsBuddy'
+export const BUDDY_WINDOWS_REFUSAL = 'Update Harness on this Windows machine to run a Buddy on it, or pick another of your machines.'
+export const refusesWindowsBuddy = (pool: ContributedMachine): boolean => pool.observation?.resources.os === 'Windows'
+ && !pool.observation.capabilities?.includes(WINDOWS_BUDDY_CAPABILITY)
export const NOT_SWARM_MACHINE = 'This machine is not one of the Swarm\'s machines.'
/** Real machines only: a Mac's Harness Team account is that same Mac (Ken, 2026-11-04). It stays 32 until a machine's reading
* stops re-reading every machine; #2900 has what grows with the count. */
@@ -781,7 +785,7 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
if (!pool) return null
if (pool.buddyOnly && request.buddyOf?.personId !== pool.contributorId) fail('NOT_SWARM_MACHINE', NOT_SWARM_MACHINE, 403)
// At its add and again at its launch: a Buddy-only machine is first read after its Buddy was asked for.
- if (request.buddyOf && pool.observation?.resources.os === 'Windows') fail('BUDDY_WINDOWS', BUDDY_WINDOWS_REFUSAL, 403)
+ if (request.buddyOf && refusesWindowsBuddy(pool)) fail('BUDDY_WINDOWS', BUDDY_WINDOWS_REFUSAL, 403)
if (pool.removal) fail('MACHINE_REMOVED', 'This machine is being removed from the Swarm.')
if (start && start.poolGeneration !== pool.generation) fail('CONTRIBUTION_REVOKED', 'This machine contribution changed. Reconcile the original start.', 403)
if (pool.paused) fail('MACHINE_PAUSED', 'New work is paused on this machine.')
diff --git a/cli/src/agentClient/model.spec.ts b/cli/src/agentClient/model.spec.ts
index 0fac7da3e..ff48bb215 100644
--- a/cli/src/agentClient/model.spec.ts
+++ b/cli/src/agentClient/model.spec.ts
@@ -50,6 +50,10 @@ describe('a harness as the agent verbs show it', () => {
frame('ghost', { tmuxPane: '%5', status: 'stopped' })]
expect(callerOf(frames, '%4', 'm')).toEqual({ machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' })
expect(callerOf(frames, '%5', 'm')).toBeNull()
+ // Windows: HARNESS_PANE names the host and the pane, and tmuxPane holds only the pane, whose number restarts in every host.
+ const windows = [frame('win', { tmuxPane: '%3', terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p2', paneId: '%3' }] } })]
+ expect(callerOf(windows, 'p2:%3', 'm')).toMatchObject({ agentId: 'win' })
+ expect(callerOf(windows, 'p9:%3', 'm')).toBeNull()
// Stopped or offline, an agent is still that agent, never the person.
expect(callerOf(frames, '%6', 'm')?.agentId).toBe('old')
expect(callerOf(frames, '%8', 'm')?.agentId).toBe('away')
diff --git a/cli/src/agentClient/model.ts b/cli/src/agentClient/model.ts
index 6294d99a9..6f0a7e59e 100644
--- a/cli/src/agentClient/model.ts
+++ b/cli/src/agentClient/model.ts
@@ -2,6 +2,7 @@
* What the agent verbs show, as pure functions of what the daemon answers (docs/design/2026-10-11-agent-client.md):
* a harness's row in `harness ps`, which harness a name means, and its last turn from a page of its transcript.
*/
+import { PTY_HOST_PANE } from '../lib/ptyHost/instance.js'
import { engineName } from '../messages/model.js'
import type { Ledger, LedgerMember } from './ledger.js'
@@ -15,6 +16,8 @@ export interface Frame {
status?: string
activity?: { state?: string } | null
tmuxPane?: string | null
+ /** Where it runs: a PTY host's pane is named by its instance and pane (Windows). */
+ terminal?: { runtimes?: Array<{ backend?: string; instance?: string; paneId?: string }> } | null
project?: { cwd?: string; root?: string; branch?: string | null; worktree?: boolean } | null
createdAt?: string
updatedAt?: string
@@ -112,10 +115,16 @@ export function stateOf(frame: Frame): State {
* or one Harness does not know. Matching active harnesses only made an agent the person, with the person's right to
* close anything, whenever the daemon listed it offline for a moment (found by e2e/agentClient.e2e.ts). A stopped
* harness keeps no pane (`toStoppedProject`), so an old pane number never matches one.
+ *
+ * A pane on Windows is named `<instance>:%N` (HARNESS_PANE), and `tmuxPane` holds only its %N, which restarts in every PTY
+ * host. So it is matched on the frame's runtime: comparing it with `tmuxPane` found no harness on Windows at all, and every
+ * agent there read as a person.
*/
export function callerOf(frames: Frame[], pane: string | undefined, machineId: string): Caller | null {
if (!pane) return null
- const on = frames.filter((f) => f.tmuxPane === pane)
+ const pty = PTY_HOST_PANE.exec(pane)
+ const on = frames.filter((f) => f.tmuxPane === pane
+ || !!pty && f.terminal?.runtimes?.some(r => r.backend === 'ptyhost' && r.instance === pty[1] && r.paneId === pty[2]))
const frame = on.find((f) => f.status === 'active') ?? on.filter(isAgent).sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))[0]
if (!frame || !isAgent(frame)) return null
return { machineId, agentId: frame.id, name: frame.name || frame.id.slice(0, 8), engine: frame.engine ?? '', ...(frame.startedBy === 'agent' || frame.parentAgentId ? { startedByAgent: true } : {}) }
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index e34101940..831d9f3e2 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2846,8 +2846,8 @@ switch (cmd) {
break
}
case 'mcp': {
- const pane = process.env.TMUX_PANE
- mcpCommand({ run: harnessRunner(SCRIPT_PATH), inPane: !!pane && !!paneOwner(pane) }).then(code => { process.exitCode = code }).catch(onError)
+ const pane = sendPane(process.env)
+ mcpCommand({ run: harnessRunner(SCRIPT_PATH), inPane: !!pane && (!pane.startsWith('%') || !!paneOwner(pane)) }).then(code => { process.exitCode = code }).catch(onError)
break
}
case 'show':
diff --git a/cli/src/lib/buddyGuard.spec.ts b/cli/src/lib/buddyGuard.spec.ts
index 46f0ca5af..07b84a3d7 100644
--- a/cli/src/lib/buddyGuard.spec.ts
+++ b/cli/src/lib/buddyGuard.spec.ts
@@ -45,6 +45,26 @@ function decide(tool: string, input: Record<string, unknown>, guard = script): s
}
const bash = (command: string) => decide('Bash', { command, description: 'x' })
+// Seen on a real Windows PC: `D:x` reads another drive's current folder and `ls C:` a drive's, and a split at ":" hid both.
+describe('a Windows Buddy and a drive named in a word', () => {
+ const windows = join(root, 'buddy-guard-windows.mjs')
+ writeFileSync(windows, readFileSync(script, 'utf8').replace("const OS_WINDOWS = process.platform === 'win32'", 'const OS_WINDOWS = true'))
+ const onWindows = (command: string) => decide('Bash', { command, description: 'x' }, windows)
+
+ it('refuses it, alone or after an option', () => {
+ for (const command of ['cat C:secret.txt', 'cat D:x', 'ls C:', 'grep x --file=D:x a.txt']) expect(onWindows(command), command).toBe('deny')
+ })
+
+ it('still lets the folder\'s own names through', () => {
+ for (const command of ['cat a.txt', 'git show HEAD:a.txt', 'git log main..HEAD']) expect(onWindows(command), command).toBe(bash(command))
+ expect(onWindows('cat a.txt')).toBe('allow')
+ })
+
+ it('leaves other systems alone: a one-letter name there is a file', () => {
+ expect(bash('cat C:a.txt')).toBe(bash('cat a.txt'))
+ })
+})
+
describe('a one Buddy\'s proposal carries a summary (security review of #2530)', () => {
const proposal = (scope: string) => JSON.stringify({ conversationId: 'c', ownerMessageId: 'm', projectId: 'p', goal: 'Cut API CPU', scope, priority: 'normal' })
const pasted = [['a code block', 'See:\n```\nconst secret = 1\n```'], ['more than 10 lines', Array.from({ length: 11 }, (_, i) => `line ${i}`).join('\n')]]
diff --git a/cli/src/lib/buddyGuard.ts b/cli/src/lib/buddyGuard.ts
index a25ff98bd..c36202837 100644
--- a/cli/src/lib/buddyGuard.ts
+++ b/cli/src/lib/buddyGuard.ts
@@ -409,8 +409,10 @@ function escapes(part) {
// A word that names a place out of the folder: itself, what follows "=" or ":" (--file=/x, HEAD:../x), and for a short
// option what follows each of its letters, since a value may be glued on (-S/x, -f../x, -fout/x). A range such as
-// main..HEAD has no ".." part.
-const outward = (word) => word.split(/[=:]/).some(escapes)
+// main..HEAD has no ".." part. On Windows a drive names a place with or without a slash after it (D:x, ls C:), which the
+// split at ":" would hide.
+const OS_WINDOWS = process.platform === 'win32'
+const outward = (word) => (OS_WINDOWS && /(^|=)[A-Za-z]:/.test(word)) || word.split(/[=:]/).some(escapes)
|| (/^-[^-]/.test(word) && [...word].some((_, at) => at >= 2 && escapes(word.slice(at))))
const short = (word) => /^-[^-]/.test(word)
diff --git a/cli/src/lib/daemonRecord.spec.ts b/cli/src/lib/daemonRecord.spec.ts
new file mode 100644
index 000000000..71487a9fa
--- /dev/null
+++ b/cli/src/lib/daemonRecord.spec.ts
@@ -0,0 +1,34 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { configuredPortOf, writeDaemonRecord } from './daemonRecord.js'
+
+const dirs: string[] = []
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+function dataDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'daemon-record-'))
+ dirs.push(dir)
+ return dir
+}
+
+describe('configuredPortOf', () => {
+ // A Harness Team account holds the configured port, so the daemon is given another, which `daemonPort` hands every command.
+ it('finds a daemon by the port it was given, and by the one it was configured with', () => {
+ const dir = dataDir()
+ writeDaemonRecord(dir, 18473, 55332)
+ expect(configuredPortOf(dir, 55332)).toBe(18473)
+ expect(configuredPortOf(dir, 18473)).toBe(18473)
+ })
+
+ it('leaves a port no record names, a missing folder and other files alone', () => {
+ const dir = dataDir()
+ writeDaemonRecord(dir, 18473, 55332)
+ writeFileSync(join(dir, 'daemon-token'), 'x')
+ writeFileSync(join(dir, 'daemon-x.json'), '{"port":4000}')
+ writeFileSync(join(dir, 'daemon-5000.json'), 'not json')
+ expect(configuredPortOf(dir, 4000)).toBe(4000)
+ expect(configuredPortOf(dir, 5000)).toBe(5000)
+ expect(configuredPortOf(join(dir, 'gone'), 55332)).toBe(55332)
+ })
+})
diff --git a/cli/src/lib/daemonRecord.ts b/cli/src/lib/daemonRecord.ts
index 2fb29f92a..d23d2544f 100644
--- a/cli/src/lib/daemonRecord.ts
+++ b/cli/src/lib/daemonRecord.ts
@@ -4,7 +4,7 @@
* pid (lib/windows/pipeAuth.ts). Both are new on each start, so a client cannot derive them as it derives a Unix
* socket's path. Written once the core is bound.
*/
-import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { isPipePath } from './windows/pipeAuth.js'
@@ -32,6 +32,23 @@ export function readDaemonRecord(dataDir: string, configuredPort: number, platfo
}
}
+/**
+ * The port whose record holds the daemon on [port]. [port] may be the one the daemon was given rather than the one it was
+ * configured with (`daemonPort` hands that to every command), when another account holds the configured one, as a Harness
+ * Team account on the same PC does. [port] itself when no record says otherwise.
+ */
+export function configuredPortOf(dataDir: string, port: number, platform: NodeJS.Platform = process.platform): number {
+ if (readDaemonRecord(dataDir, port, platform)) return port
+ let names: string[] = []
+ try { names = readdirSync(dataDir) } catch { return port }
+ for (const name of names) {
+ if (!name.startsWith('daemon-') || !name.endsWith('.json')) continue
+ const configured = Number(name.slice('daemon-'.length, -'.json'.length))
+ if (readDaemonRecord(dataDir, configured, platform)?.port === port) return configured
+ }
+ return port
+}
+
export function writeDaemonRecord(dataDir: string, configuredPort: number, port: number, pipe?: DaemonPipeRecord): void {
mkdirSync(dataDir, { recursive: true, mode: 0o700 })
const target = daemonRecordPath(dataDir, configuredPort)
diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.ts
index 9f04c5c5f..e049e793c 100644
--- a/cli/src/lib/localSocket.ts
+++ b/cli/src/lib/localSocket.ts
@@ -22,7 +22,7 @@ import type { Duplex } from 'node:stream'
import { chmodSync, linkSync, lstatSync, mkdirSync, renameSync, unlinkSync, type Stats } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
-import { readDaemonRecord } from './daemonRecord.js'
+import { configuredPortOf, readDaemonRecord } from './daemonRecord.js'
import { daemonPipe, type LocalDaemonOptions } from './windows/daemonPipe.js'
import { checkPipeAuth, newPipePath, NonceWindow, PIPE_AUTH_HEADER, PIPE_PROOF_HEADER, pipeIdOf, pipeProofValue } from './windows/pipeAuth.js'
import { pipeAbsent, pipeRequest, PipeUnproven } from './windows/pipeClient.js'
@@ -80,7 +80,7 @@ export function unixSocketPath(dataDir: string, port: number, platform: NodeJS.P
* A caller that needs a filesystem socket (`ws+unix://`, the services) uses unixSocketPath.
*/
export function localSocketPath(dataDir: string, port: number, platform: NodeJS.Platform = process.platform): string | null {
- return platform === 'win32' ? readDaemonRecord(dataDir, port, platform)?.pipe ?? null : unixSocketPath(dataDir, port, platform)
+ return platform === 'win32' ? readDaemonRecord(dataDir, configuredPortOf(dataDir, port, platform), platform)?.pipe ?? null : unixSocketPath(dataDir, port, platform)
}
/** Where a daemon starting on `port` listens: its Unix socket, or on Windows a pipe of a new random name. */
diff --git a/cli/src/lib/localTransport.spec.ts b/cli/src/lib/localTransport.spec.ts
index b9260ca62..dd1be2365 100644
--- a/cli/src/lib/localTransport.spec.ts
+++ b/cli/src/lib/localTransport.spec.ts
@@ -179,6 +179,14 @@ describe('daemonPipeNow: the daemon\'s pipe for a client that opens at once', ()
expect(daemonPipeNow(data, 4242)).toEqual({ pipe, token })
})
+ // A Harness Team account on the same PC holds the configured port, so the daemon is given another and `daemonPort` says
+ // that one. Its record keeps the configured port's name: every `harness new` there was told Harness was not running.
+ it('finds the record of a daemon that was given another port than it was configured with', () => {
+ const { data, pipe } = prepared(process.pid)
+ expect(daemonPipeNow(data, 50_000)).toEqual({ pipe, token })
+ expect(daemonPipeNow(data, 50_001)).toBeNull()
+ })
+
it('is none with no record, no token, or a daemon that has exited', () => {
expect(daemonPipeNow(prepared(null).data, 4242)).toBeNull()
expect(daemonPipeNow(prepared(process.pid, false).data, 4242)).toBeNull()
diff --git a/cli/src/lib/localTransport.ts b/cli/src/lib/localTransport.ts
index 627968500..7be783784 100644
--- a/cli/src/lib/localTransport.ts
+++ b/cli/src/lib/localTransport.ts
@@ -16,7 +16,7 @@ import { request } from 'node:http'
import { dirname, join } from 'node:path'
import { Readable } from 'node:stream'
import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
-import { readDaemonRecord } from './daemonRecord.js'
+import { configuredPortOf, readDaemonRecord } from './daemonRecord.js'
import { localCredentialHeaders } from './localCredential.js'
import { unixSocketPath } from './localSocket.js'
import { NOT_RUNNING } from './unreachable.js'
@@ -139,7 +139,7 @@ export function daemonFetch(
): typeof fetch {
return async (input, init) => {
const url = new URL(input instanceof Request ? input.url : String(input))
- const saved = readDaemonRecord(dataDir, port, platform)?.port
+ const saved = readDaemonRecord(dataDir, configuredPortOf(dataDir, port, platform), platform)?.port
const daemon = url.hostname === '127.0.0.1' && (Number(url.port) === port || Number(url.port) === saved)
if (daemon && platform === 'win32') {
const target = await pipe(dataDir, port)
@@ -170,7 +170,7 @@ function ownProcessRuns(pid: number): boolean {
* (`pipeWebSocket`), so a squatter is refused before any frame is sent to it.
*/
export function daemonPipeNow(dataDir: string, port: number): PipeTarget | null {
- const record = readDaemonRecord(dataDir, port)
+ const record = readDaemonRecord(dataDir, configuredPortOf(dataDir, port))
if (!record?.pipe || !record.pid || !ownProcessRuns(record.pid)) return null
const token = readDaemonToken(dataDir)
return token ? { pipe: record.pipe, token } : null
diff --git a/cli/src/lib/swarmGitHub.spec.ts b/cli/src/lib/swarmGitHub.spec.ts
index 39ff5383c..51ecd63de 100644
--- a/cli/src/lib/swarmGitHub.spec.ts
+++ b/cli/src/lib/swarmGitHub.spec.ts
@@ -121,7 +121,7 @@ describe('commits in a Swarm session', { timeout: 60_000 }, () => {
const dir = fresh('commit')
const repo = join(dir, 'repo')
mkdirSync(repo)
- const launch = swarmGitHubLaunch(`harness-claude-fixture-${made}`, { dataDir: shared, command: `/bin/sh ${shellWord(cli)}`, port: 18500, machineId: 'machine-1' }, 'darwin')!
+ const launch = swarmGitHubLaunch(`harness-claude-fixture-${made}`, { dataDir: shared, command: `/bin/sh ${shellWord(cli)}`, port: 18500, machineId: 'machine-1' })!
expect(git(repo, ['init', '-q', '-b', 'main']).status).toBe(0)
const env = { GIT_CONFIG_PARAMETERS: launch.env.GIT_CONFIG_PARAMETERS!, HARNESS_SWARM_GITHUB_DIR: launch.env.HARNESS_SWARM_GITHUB_DIR! }
const commit = (args: string[], extra: Record<string, string> = {}) => git(repo, ['commit', '-q', '--allow-empty', ...args], { ...env, ...extra })
@@ -242,7 +242,7 @@ describe('a session\'s gh login and trailers', () => {
describe('a Swarm session\'s launch', () => {
it('names the session\'s gh folder and Harness\'s git settings, clears inherited GitHub tokens, and starts with no gh login', () => {
const dataDir = fresh('launch')
- const launch = swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'linux')!
+ const launch = swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' })!
const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-abc')!
expect(launch.env).toEqual({
GIT_CONFIG_PARAMETERS: gitConfigParameters(join(dataDir, 'swarm-github', 'bin', 'git-credential'), join(dataDir, 'swarm-github', 'hooks'), join(dir, 'gitconfig')),
@@ -252,16 +252,25 @@ describe('a Swarm session\'s launch', () => {
expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')
// A relaunch keeps a login the daemon has written since.
writeSessionGitHub(dir, 'ghs_fixtureToken0000002')
- swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'linux')
+ swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' })
expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toContain('ghs_fixtureToken0000002')
})
- it('does not apply on Windows or to a key unfit for a path', () => {
+ it('does not apply to a key unfit for a path', () => {
const dataDir = fresh('none')
- expect(swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'win32')).toBeNull()
- expect(swarmGitHubLaunch('../escape', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'darwin')).toBeNull()
+ expect(swarmGitHubLaunch('../escape', { dataDir, command: 'harness', port: 18473, machineId: 'm1' })).toBeNull()
expect(existsSync(join(dataDir, 'swarm-github'))).toBe(false)
})
+
+ // Off, a Windows Team account's agents had no way to push: its owner's git login is not there, and no helper was.
+ it('applies on Windows too', () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ try {
+ const launch = swarmGitHubLaunch('harness-codex-win', { dataDir: fresh('windows'), command: 'harness', port: 18473, machineId: 'm1' })
+ expect(launch?.env.GIT_CONFIG_PARAMETERS).toContain('git-credential')
+ } finally { Object.defineProperty(process, 'platform', platform) }
+ })
})
// Review of #1998: a start held between its launch preparation and its session's registration could look untouched for 15
@@ -271,11 +280,11 @@ describe('a session\'s GitHub folder at launch', () => {
const dataDir = mkdtempSync(join(tmpdir(), 'swarm-github-launch-'))
try {
const tools = { dataDir, command: 'harness', port: 18473, machineId: 'm1' }
- expect(swarmGitHubLaunch('harness-codex-held', tools, 'darwin')).not.toBeNull()
+ expect(swarmGitHubLaunch('harness-codex-held', tools)).not.toBeNull()
const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-held')!
const old = new Date(Date.now() - 20 * 60_000)
utimesSync(dir, old, old)
- swarmGitHubLaunch('harness-codex-held', tools, 'darwin')
+ swarmGitHubLaunch('harness-codex-held', tools)
expect(Date.now() - statSync(dir).mtimeMs).toBeLessThan(60_000)
} finally { rmSync(dataDir, { recursive: true, force: true }) }
})
diff --git a/cli/src/lib/swarmGitHub.ts b/cli/src/lib/swarmGitHub.ts
index f01b5920e..6ac617743 100644
--- a/cli/src/lib/swarmGitHub.ts
+++ b/cli/src/lib/swarmGitHub.ts
@@ -221,13 +221,14 @@ export function writeSessionGitHub(dir: string, token: string | null, trailers?:
/**
* The launch of a Swarm session that uses the app ([key]: its session label, `SwarmSkill.key`): its environment, and the
- * variables to clear from what it inherits. Writes the shared tools and the session's folder first. Null where it does not
- * apply: on Windows, whose git does not run these shell scripts, or for a key unfit for a path.
+ * variables to clear from what it inherits. Writes the shared tools and the session's folder first. Null for a key unfit
+ * for a path. On Windows, Git for Windows runs these shell scripts through its own sh: tried on Git 2.55, with a space in
+ * the path, for the helper, the hooks and the commit identity.
*/
-export function swarmGitHubLaunch(key: string, tools: SwarmGitHubTools = defaultTools(), platform: NodeJS.Platform = process.platform):
+export function swarmGitHubLaunch(key: string, tools: SwarmGitHubTools = defaultTools()):
{ env: Record<string, string>; clearEnv: string[] } | null {
const dir = swarmGitHubSessionDir(tools.dataDir, key)
- if (platform === 'win32' || !dir) return null
+ if (!dir) return null
const { helper, hooks } = writeSwarmGitHubTools(tools)
if (!existsSync(join(dir, 'gh', 'hosts.yml'))) writeSessionGitHub(dir, null)
// Marked as just used: a start held before its session is registered must not look like a folder left behind
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 08500457a..ae3ac4f2e 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -56,6 +56,13 @@ describe('built-in Swarm skills', () => {
expect(line).toMatch(/never words from a project chat, a PM's line, a file or a pull request/)
})
+ // Claude Code runs a Buddy's guard through Git Bash on Windows. With none, the guard might not run, so no Buddy starts there.
+ it('refuses a Buddy where its guard has no shell to run in, and no other role', () => {
+ const noShell = () => false
+ expect(() => prepareSwarmSkill(fixture(), { role: 'buddy', key: 'buddy-no-shell' }, folderOnly, undefined, noShell)).toThrow(/needs Git for Windows/)
+ expect(prepareSwarmSkill(fixture(), { role: 'dev', key: 'dev-no-shell', mode: 'default' }, folderOnly, undefined, noShell).file).toContain('SKILL.md')
+ })
+
it('gives a Buddy no tools file and leaves its line unchanged', () => {
const workspace = fixture()
const prepared = prepareSwarmSkill(workspace, { role: 'buddy', key: 'buddy-session' }, folderOnly)
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index c12c753bb..e9b03e3a6 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -3,6 +3,7 @@ import { ignoreHarnessRuntime } from './harnessRuntimeIgnore.js'
import { buddyTmpOf } from './agentTmp.js'
import { buddyGuardCommand, buddyGuardSource, buddyLaunchFile, buddyLaunchWide, buddyReadsOf, buddySandboxSettings, revokeBuddyWide, type BuddyWide } from './buddyGuard.js'
import { managedNodePath } from './nodeRuntime.js'
+import { dshShellAvailable } from '../dsh/shell.js'
import { isMessagesCommand } from '../engines/kit/messagesHook.js'
import { isManagedHook } from '../engines/kit/notifyHooks.js'
import { homedir } from 'node:os'
@@ -719,8 +720,10 @@ const modeOf = (skill: SwarmSkill, version: string) =>
* never names one mode while the file holds the other. No project-wide native skill links: two roles may share a workspace. */
/** [wideOf]: whether a Buddy launched here reads beyond its folder (lib/buddyGuard.ts buddyLaunchWide); tests name it. */
export function prepareSwarmSkill(workspace: string, saved: SavedSwarmSkill, wideOf: (root: string) => BuddyWide | null = buddyLaunchWide,
- tmpOf: (root: string) => string | null = buddyTmpOf): { file: string; instructions: string } {
+ tmpOf: (root: string) => string | null = buddyTmpOf, guardShell: () => boolean = dshShellAvailable): { file: string; instructions: string } {
const skill = skillOf(saved)
+ // Claude Code runs a Buddy's guard through Git Bash on Windows: with none the guard might not run, so no Buddy starts.
+ if (skill.role === 'buddy' && !guardShell()) throw new Error('A Buddy on this computer needs Git for Windows, which was not found. Install it from https://git-scm.com/download/win, then try again.')
const root = realpathSync(workspace)
// First, so a skill that cannot be prepared still leaves a Buddy's folder locked (re-check of #1992).
if (skill.role === 'buddy') lockBuddyFolder(root, skill.key, wideOf(root), tmpOf(root))
diff --git a/cli/src/lib/windows/daemonPipe.spec.ts b/cli/src/lib/windows/daemonPipe.spec.ts
index 79b788ddb..ce5e7b8f7 100644
--- a/cli/src/lib/windows/daemonPipe.spec.ts
+++ b/cli/src/lib/windows/daemonPipe.spec.ts
@@ -52,6 +52,13 @@ describe('the daemon over its Windows pipe', () => {
expect(await daemonPipe(pipeDir(), port, alive)).toBeNull()
})
+ // A Harness Team account holds the configured port, so the daemon is given another, which `daemonPort` hands every command.
+ it('is found by the port the daemon was given, as well as the one it was configured with', async () => {
+ const { dir, pipe } = await windowsDaemon((_req, res) => res.end('{}'))
+ expect((await daemonPipe(dir, 24567, alive))?.pipe).toBe(pipe)
+ expect(await daemonPipe(dir, 24567, { alive: () => false })).toBeNull()
+ })
+
it('answers status over the pipe, and nothing for an answer without the proof', async () => {
const { dir, port } = await windowsDaemon((_req, res) => res.end(JSON.stringify({ machineId: 'account-a' })))
expect(await localDaemonStatus(dir, port, options)).toEqual({ machineId: 'account-a' })
diff --git a/cli/src/lib/windows/daemonPipe.ts b/cli/src/lib/windows/daemonPipe.ts
index 069912827..de0b595e4 100644
--- a/cli/src/lib/windows/daemonPipe.ts
+++ b/cli/src/lib/windows/daemonPipe.ts
@@ -4,7 +4,7 @@
* who serves a data folder (localSocket.ts `servedFolderDeps`) use it; it lives here, apart from either, so neither
* imports the other.
*/
-import { daemonRecordPath, readDaemonRecord } from '../daemonRecord.js'
+import { configuredPortOf, daemonRecordPath, readDaemonRecord } from '../daemonRecord.js'
import { pidAlive, recordedProcessDead, type HostLiveness } from '../processProof.js'
import { readDaemonToken } from './pipeAuth.js'
import type { PipeTarget } from './pipeClient.js'
@@ -24,12 +24,13 @@ const WINDOWS_LIVENESS: HostLiveness = {
* a pipe and pid, no token, or the recorded process is proven gone. Once that process is gone, any user can create
* a pipe of the recorded name.
*/
-export async function daemonPipe(dataDir: string, configuredPort: number, liveness: HostLiveness = WINDOWS_LIVENESS): Promise<PipeTarget | null> {
- const record = readDaemonRecord(dataDir, configuredPort)
+export async function daemonPipe(dataDir: string, port: number, liveness: HostLiveness = WINDOWS_LIVENESS): Promise<PipeTarget | null> {
+ const configured = configuredPortOf(dataDir, port)
+ const record = readDaemonRecord(dataDir, configured)
if (!record?.pipe || !record.pid) return null
const token = readDaemonToken(dataDir)
if (!token) return null
- if (await recordedProcessDead(daemonRecordPath(dataDir, configuredPort), record.pid, liveness)) return null
+ if (await recordedProcessDead(daemonRecordPath(dataDir, configured), record.pid, liveness)) return null
return { pipe: record.pipe, token }
}
diff --git a/cli/src/superTabs/buddyPane.spec.ts b/cli/src/superTabs/buddyPane.spec.ts
index 7d0da1ad3..6c81abfa2 100644
--- a/cli/src/superTabs/buddyPane.spec.ts
+++ b/cli/src/superTabs/buddyPane.spec.ts
@@ -1,5 +1,5 @@
-import { expect, it, vi } from 'vitest'
-import { buddyRefusal, paneBuddy, WINDOWS_BUDDY } from './buddyPane.js'
+import { describe, expect, it, vi } from 'vitest'
+import { buddyRefusal, paneBuddy } from './buddyPane.js'
const where = { port: 14001, dataDir: '/fixture', machineId: 'machine' }
const BUDDY = 'A Buddy talks with its owner in its own chat: it may not send to, start, tell or close other sessions.'
@@ -56,14 +56,51 @@ it('refuses a command that names another pane than the one it runs in, and finds
expect(await buddyRefusal(daemon(swarm(true)).deps, 'darwin')).toBe(BUDDY)
})
-// Windows has no cheap check of a pty host pane: while a Buddy runs on that computer, an agent's shell may not.
-it('fails closed on Windows while this computer runs a Buddy, for an agent\'s shell, and leaves a person\'s terminal alone', async () => {
- const agentShells = [{ HARNESS_PANE: 'p1:%3' }, { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' }, { CODEX_THREAD_ID: 't' }]
- for (const env of agentShells) {
- expect(await buddyRefusal({ ...daemon(swarm(false, true)).deps, env }, 'win32')).toBe(WINDOWS_BUDDY)
- expect(await buddyRefusal({ ...daemon(swarm(false, false)).deps, env }, 'win32')).toBeNull()
+// Windows proves a pane from the command's parents, as a Mac does. A Buddy there used to refuse every agent's shell on that
+// computer, because nothing could tell its pane from theirs (security review of #2093).
+describe('on Windows', () => {
+ // This command (process.pid) under the pane's process 700, under the PTY host 600.
+ const rows = (host = 'harness-pty.exe') => async () => [
+ { pid: process.pid, parentPid: 700, executable: 'node.exe', startMarker: 'w:30', args: '' },
+ { pid: 700, parentPid: 600, executable: 'claude.exe', startMarker: 'w:20', args: '' },
+ { pid: 600, parentPid: 1, executable: host, startMarker: 'w:10', args: '' },
+ ]
+ const windows = (buddy: boolean, buddiesHere = buddy) => {
+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => {
+ if (type === 'agents_list') {
+ return { agents: [{ id: 'pane-harness', engine: 'claude', tmuxPane: '%3', status: 'active',
+ terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%3' }] } }] }
+ }
+ if (type === 'super_tabs' && payload.action === 'buddyCheck') return swarm(buddy, buddiesHere)(payload)
+ if (type === 'terminal_info') return { command: 'claude', path: 'C:\\work', pid: 700 }
+ return { error: 'UNSUPPORTED' }
+ })
+ return { where: () => where, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }) }
}
- expect(await buddyRefusal({ ...daemon(swarm(false, true)).deps, env: {} }, 'win32')).toBeNull()
+
+ it('refuses a Buddy\'s own pane', async () => {
+ expect(await buddyRefusal({ ...windows(true), env: { HARNESS_PANE: 'p1:%3' }, readProcesses: rows() }, 'win32')).toBe(BUDDY)
+ })
+
+ it('leaves another agent\'s pane alone while this computer runs a Buddy', async () => {
+ expect(await buddyRefusal({ ...windows(false, true), env: { HARNESS_PANE: 'p1:%3' }, readProcesses: rows() }, 'win32')).toBeNull()
+ })
+
+ it('leaves an agent outside Harness and a person\'s terminal alone', async () => {
+ const outside = async () => [{ pid: process.pid, parentPid: 1, executable: 'node.exe', startMarker: 'w:30', args: '' }]
+ for (const env of [{ CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' }, { CODEX_THREAD_ID: 't' }, {}]) {
+ expect(await buddyRefusal({ ...windows(false, true), env, readProcesses: outside }, 'win32')).toBeNull()
+ }
+ })
+
+ it('refuses a command naming a pane it does not run in, and one under the PTY host that names none', async () => {
+ const elsewhere = windows(false, true)
+ const other = async () => [{ pid: process.pid, parentPid: 1, executable: 'node.exe', startMarker: 'w:30', args: '' }]
+ expect(await buddyRefusal({ ...elsewhere, env: { HARNESS_PANE: 'p1:%3' }, readProcesses: other }, 'win32'))
+ .toBe('This command does not run in the Harness pane it names, so it did not run. Run it as your harness gave it, in its own pane.')
+ expect(await buddyRefusal({ ...elsewhere, env: {}, readProcesses: rows() }, 'win32'))
+ .toBe('Harness could not tell which pane this command runs in, so it did not run it. Run it as your harness gave it, in its own pane.')
+ })
})
// Re-check 1 of #2093 (minor 7): with the Swarm on, an error on the harness's own question read as "no Buddy".
diff --git a/cli/src/superTabs/buddyPane.ts b/cli/src/superTabs/buddyPane.ts
index 7d4d41489..742d904e8 100644
--- a/cli/src/superTabs/buddyPane.ts
+++ b/cli/src/superTabs/buddyPane.ts
@@ -6,18 +6,16 @@
* a Buddy is this computer's own launch record (service.ts `buddyCheck`): the second review found a server read alone
* missed its deadline 2 times in 3 under load, and refused everyone in an outage. In order:
* - with the Swarm off, or a daemon from before the check, nothing changes, and no pane is looked at;
- * - a daemon that is not running is left to the command, which says so as it always has;
- * - Windows has no cheap check of a pty host pane, so while this computer runs a Buddy an agent's shell is refused.
+ * - a daemon that is not running is left to the command, which says so as it always has.
*/
import { openDaemon, whereFor, type Where } from '../agentClient/daemon.js'
-import { callerOf, outsideCaller, type Frame } from '../agentClient/model.js'
+import { callerOf, type Frame } from '../agentClient/model.js'
+import type { ProcessRow } from '../lib/processTable.js'
import { sendPane } from '../messages/command.js'
-import { inDaemonPane, NOT_IN_PANE, runningPane, type PaneProbe } from './callerPane.js'
+import { inDaemonPane, NOT_IN_PANE, runningPane, windowsRunningPane, type PaneProbe } from './callerPane.js'
const BUDDY = 'A Buddy talks with its owner in its own chat: it may not send to, start, tell or close other sessions.'
const UNSURE = 'Harness could not confirm whether this harness is a Buddy just now, so it did not run this. Try again in a moment.'
-export const WINDOWS_BUDDY = 'This Windows computer runs a Buddy, and Harness cannot tell its pane from this one, so an agent here may not do this '
- + 'while it runs. Run it from your own terminal.'
type DaemonLike = { request: (type: string, payload?: Record<string, unknown>, ms?: number) => Promise<Record<string, unknown>> }
@@ -27,7 +25,7 @@ export const SWARM_UNSURE = 'Harness could not reach this computer\'s Swarm just
* Whether this computer's Swarm knows of Buddies: null with the Swarm off (core/serviceHost.ts answers a service off for good
* as unavailable, not to be retried) or a daemon from before `buddyCheck` (no Swarm service, or one that reads it as an agent's
* request without a Swarm: invalid). Anything else, a failure or no answer in time, throws [SWARM_UNSURE]: read as "off", it
- * skipped the Buddy check and Windows' backstop (re-check 2 of #2093 at 0648a8690).
+ * skipped the Buddy check (re-check 2 of #2093 at 0648a8690).
*/
export async function buddiesHere(daemon: DaemonLike): Promise<boolean | null> {
const answer = await daemon.request('super_tabs', { action: 'buddyCheck' }, 10_000).catch(() => { throw new Error(SWARM_UNSURE) })
@@ -56,11 +54,9 @@ export async function paneBuddy(daemon: DaemonLike, pane: string, machineId: str
return answer.buddy ? 'buddy' : 'not a buddy'
}
-/** An agent's shell on Windows, as it marks itself: its Harness pane, or the engine's own variables (`outsideCaller`). */
-export const agentShell = (env: NodeJS.ProcessEnv): boolean => !!sendPane(env) || !!outsideCaller(env, '')
-
export async function buddyRefusal(deps: {
probe?: PaneProbe; env?: NodeJS.ProcessEnv; where?: () => Where; open?: typeof openDaemon
+ readProcesses?: () => Promise<ProcessRow[] | null>
} = {}, platform: NodeJS.Platform = process.platform): Promise<string | null> {
const env = deps.env ?? process.env
const where = (deps.where ?? (() => whereFor(sendPane(env))))()
@@ -70,8 +66,9 @@ export async function buddyRefusal(deps: {
let buddies: boolean | null
try { buddies = await buddiesHere(daemon) } catch { return SWARM_UNSURE }
if (buddies === null) return null
- if (platform === 'win32') return buddies && agentShell(env) ? WINDOWS_BUDDY : null
- const running = runningPane(env, deps.probe, platform)
+ const running = platform === 'win32'
+ ? await windowsRunningPane(sendPane(env), deps.readProcesses)
+ : runningPane(env, deps.probe, platform)
if (running.refused) return running.refused
// Not shortcut on `buddies`: a harness an agent started with no Swarm record is asked about by itself (service.ts).
if (!running.pane) return null
diff --git a/cli/src/superTabs/callerPane.spec.ts b/cli/src/superTabs/callerPane.spec.ts
index 1ec203b56..ffc8fd435 100644
--- a/cli/src/superTabs/callerPane.spec.ts
+++ b/cli/src/superTabs/callerPane.spec.ts
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'
import { describe, expect, it, vi } from 'vitest'
import { isolatedTmux } from '../testing/isolatedTmux.js'
import { resolveBinaryOnPath } from '../lib/binaryOnPath.js'
-import { processProbe, runningPane, systemTmuxPaths } from './callerPane.js'
+import { processProbe, runningPane, systemTmuxPaths, windowsRunningPane } from './callerPane.js'
const CLI_ROOT = fileURLToPath(new URL('../..', import.meta.url))
const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')
@@ -58,9 +58,43 @@ it('is no pane for a person\'s terminal outside tmux, nor for a command detached
expect(runningPane({}, probe({ ancestors: chain(900, 1) }), 'darwin')).toEqual({})
})
-it('keeps TMUX_PANE as it is on Windows, which has no tmux to check it against', () => {
- expect(runningPane({ TMUX_PANE: '%7' }, probe({ panes: null, ancestors: null }), 'win32')).toEqual({ pane: '%7' })
- expect(runningPane({}, probe(), 'win32')).toEqual({})
+describe('windowsRunningPane', () => {
+ const UNPROVEN = 'Harness could not tell which pane this command runs in, so it did not run it. Run it as your harness gave it, in its own pane.'
+ const row = (pid: number, parentPid: number, startMarker: string, executable = 'node.exe') => ({ pid, parentPid, startMarker, executable, args: '' })
+ const table = (...rows: ReturnType<typeof row>[]) => async () => rows
+
+ it('gives the pane a command names, with its parents to hold it to', async () => {
+ const read = table(row(900, 700, 'w:30'), row(700, 600, 'w:20', 'claude.exe'), row(600, 1, 'w:10', 'harness-pty.exe'))
+ expect(await windowsRunningPane('p1:%3', read, 900)).toEqual({ pane: 'p1:%3', ancestors: [900, 700, 600] })
+ })
+
+ it('refuses a command under the PTY host that names no pane, whatever the case of its file name', async () => {
+ for (const host of ['harness-pty.exe', 'HARNESS-PTY.EXE', 'C:\\Users\\me\\.harness\\runtime\\pty\\1\\harness-pty.exe']) {
+ expect(await windowsRunningPane(undefined, table(row(900, 600, 'w:30'), row(600, 1, 'w:10', host)), 900)).toEqual({ refused: UNPROVEN })
+ }
+ })
+
+ it('takes a command outside any pane for a person\'s terminal', async () => {
+ expect(await windowsRunningPane(undefined, table(row(900, 800, 'w:30'), row(800, 1, 'w:10', 'powershell.exe')), 900)).toEqual({})
+ })
+
+ // Windows gives a freed pid to the next process and never reparents: a Builder's pid must not pass for a parent long gone.
+ it('ends the chain at a parent that started after its child', async () => {
+ const read = table(row(900, 700, 'w:30'), row(700, 600, 'w:99', 'claude.exe'), row(600, 1, 'w:10', 'harness-pty.exe'))
+ expect(await windowsRunningPane('p1:%3', read, 900)).toEqual({ pane: 'p1:%3', ancestors: [900] })
+ expect(await windowsRunningPane(undefined, read, 900)).toEqual({})
+ })
+
+ it('survives a loop in the table', async () => {
+ expect(await windowsRunningPane('p1:%3', table(row(900, 700, 'w:30'), row(700, 900, 'w:30')), 900))
+ .toEqual({ pane: 'p1:%3', ancestors: [900, 700] })
+ })
+
+ it('cannot prove a named pane with no table, or a table without this command', async () => {
+ expect(await windowsRunningPane('p1:%3', async () => null, 900)).toEqual({ refused: UNPROVEN })
+ expect(await windowsRunningPane('p1:%3', table(row(800, 1, 'w:10')), 900)).toEqual({ refused: UNPROVEN })
+ expect(await windowsRunningPane(undefined, async () => null, 900)).toEqual({})
+ })
})
// The second review of #2087: the real tmux and ps outputs, read as they come, and the late finding's three ways to leave
diff --git a/cli/src/superTabs/callerPane.ts b/cli/src/superTabs/callerPane.ts
index b2a087842..bf1821478 100644
--- a/cli/src/superTabs/callerPane.ts
+++ b/cli/src/superTabs/callerPane.ts
@@ -12,13 +12,16 @@
* person's terminal. Now ps unreadable, a tmux server among its parents, or TMUX or TMUX_PANE set, with no pane proven, is a
* refusal; ps and tmux are run from where the system (or Harness's own runtime) keeps them, never from PATH. What it cannot see is a command that
* detached itself from its pane on purpose and cleared TMUX and TMUX_PANE: it reads as a person's terminal (the PR names it).
- * Windows has no tmux to check against, and keeps TMUX_PANE as it was.
+ * Windows has no tmux: `windowsRunningPane` holds a pane to the same parents, with the PTY host in tmux's place.
*/
import { execFileSync } from 'node:child_process'
import { existsSync, readlinkSync } from 'node:fs'
import { userInfo } from 'node:os'
-import { basename, join } from 'node:path'
+import { basename, join, win32 } from 'node:path'
+import { ptyHostBinary } from '../lib/ptyHost/launch.js'
+import type { ProcessRow } from '../lib/processTable.js'
import { managedTmuxPath, tmuxInstallDirectories } from '../lib/tmuxOnPath.js'
+import { windowsProcessRows } from '../lib/windows/processTable.js'
export interface Process { pid: number; command: string }
@@ -36,9 +39,58 @@ const UNPROVEN = 'Harness could not tell which pane this command runs in, so it
/** A tmux server, as ps names it: `tmux` on macOS (it sets its own title), `tmux: server` on Linux. */
const isTmuxServer = (command: string): boolean => /^tmux(:|$)/.test(basename(command.split(' ')[0] ?? ''))
-/** The pane, and this command's parents' pids to hold its harness to (`inDaemonPane`); Windows, with no check, gives none. */
-export function runningPane(env: NodeJS.ProcessEnv, probe: PaneProbe = processProbe(env), platform: NodeJS.Platform = process.platform): { pane?: string; refused?: string; ancestors?: number[] } {
- if (platform === 'win32') return env.TMUX_PANE ? { pane: env.TMUX_PANE } : {}
+export interface RunningPane { pane?: string; refused?: string; ancestors?: number[] }
+
+/** The process table, from the PTY host this account installed: never one a command names (`HARNESS_PTY_BIN`, or a data folder
+ * in its environment), which could answer with any parents it likes. As `ps` and tmux are never run from PATH. */
+const readWindowsProcesses = (): Promise<ProcessRow[] | null> => windowsProcessRows(null, {
+ binary: () => ptyHostBinary({ env: {}, runtimeDir: join(accountHome(), '.harness', 'runtime') }),
+})
+
+/** When a process started, from its `w:<FILETIME>` marker (pty/src/ps.rs), or null when it does not say. */
+const started = (row: ProcessRow): bigint | null => {
+ const match = /^w:(\d+)$/.exec(row.startMarker ?? '')
+ return match ? BigInt(match[1]!) : null
+}
+
+/**
+ * This command and its parents, nearest first. Windows hands a freed pid to the next process and never reparents, so a parent
+ * that started after its child is another process on the old pid, and the chain ends there.
+ */
+function windowsChain(rows: ProcessRow[], pid: number): ProcessRow[] | null {
+ const byPid = new Map(rows.map(row => [row.pid, row]))
+ const first = byPid.get(pid)
+ if (!first) return null
+ const chain: ProcessRow[] = [first]
+ for (;;) {
+ const row = chain[chain.length - 1]!
+ const parent = byPid.get(row.parentPid)
+ if (!parent || chain.includes(parent)) return chain
+ const mine = started(row), theirs = started(parent)
+ if (mine === null || theirs === null || theirs > mine) return chain
+ chain.push(parent)
+ }
+}
+
+const isPtyHost = (row: ProcessRow): boolean => /^harness-pty(\.exe)?$/i.test(win32.basename(row.executable))
+
+/**
+ * The pane a command runs in on Windows, as `runningPane` proves one on a Mac: [named] is what the command says, and it has its
+ * parents to hold its harness to (`inDaemonPane`), so naming another harness's pane is refused there. A command under the PTY
+ * host that names none has cleared it, and is refused as tmux's is. With no table to read, a command naming a pane cannot prove
+ * it; one naming none and not known to be in a pane is a person's terminal, as a Harness with no PTY host has nothing in panes.
+ */
+export async function windowsRunningPane(named: string | undefined, read: () => Promise<ProcessRow[] | null> = readWindowsProcesses,
+ pid: number = process.pid): Promise<RunningPane> {
+ const rows = await read()
+ const chain = rows && windowsChain(rows, pid)
+ if (!chain) return named ? { refused: UNPROVEN } : {}
+ if (named) return { pane: named, ancestors: chain.map(row => row.pid) }
+ return chain.some(isPtyHost) ? { refused: UNPROVEN } : {}
+}
+
+/** The pane, and this command's parents' pids to hold its harness to (`inDaemonPane`). Not on Windows: `windowsRunningPane`. */
+export function runningPane(env: NodeJS.ProcessEnv, probe: PaneProbe = processProbe(env), platform: NodeJS.Platform = process.platform): RunningPane {
const ancestors = probe.ancestors()
if (!ancestors) return { refused: UNPROVEN }
const server = ancestors.find(row => isTmuxServer(row.command))
@@ -53,7 +105,7 @@ export function runningPane(env: NodeJS.ProcessEnv, probe: PaneProbe = processPr
* Whether the Harness daemon's own pane of [harnessId] is among this command's parents. Pane ids restart in every tmux
* server, so a private server counted up to a Builder's pane id and its command was taken for that Builder (re-check 2 of
* #2093); the daemon reads the pane's process from its own server (`terminal_info`, core/terminals/requests.ts). With no
- * parents to hold it to (Windows, or a pane a caller already established), there is nothing to check.
+ * parents to hold it to (a pane a caller already established), there is nothing to check.
*/
export async function inDaemonPane(daemon: { request: (type: string, payload?: Record<string, unknown>, ms?: number) => Promise<Record<string, unknown>> },
harnessId: string, ancestors: number[] | undefined): Promise<boolean> {
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index eb468951c..040be3aef 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -722,47 +722,59 @@ it('refuses, from a harness, a --machine or --port other than this computer\'s o
expect(opened.at(-1)).toMatchObject({ machineId: 'macbook' })
}
})
-// Windows has no cheap check of a pty host pane (second review, item 4): while this computer runs a Buddy, an agent's shell
-// may not name an agent.
-it('refuses --agent from an agent\'s shell on Windows while this computer runs a Buddy, and leaves a person\'s terminal alone', async () => {
- let buddiesHere = true
- const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list' ? { agents: [] }
- : payload.action === 'buddyCheck' ? { ok: true, buddiesHere } : { ok: true })
+// Windows' parents, as `harness-pty ps` lists them: this command under pane process 700, under the PTY host.
+const windowsPane = async () => [
+ { pid: process.pid, parentPid: 700, executable: 'node.exe', startMarker: 'w:30', args: '' },
+ { pid: 700, parentPid: 600, executable: 'claude.exe', startMarker: 'w:20', args: '' },
+ { pid: 600, parentPid: 1, executable: 'harness-pty.exe', startMarker: 'w:10', args: '' },
+]
+const windowsAlone = async () => [{ pid: process.pid, parentPid: 1, executable: 'node.exe', startMarker: 'w:30', args: '' }]
+// A Buddy on the computer used to refuse every agent's shell there (second review, item 4). Now each is told apart by its pane.
+it('on Windows, a Buddy on the computer refuses no other agent, and a pane speaks as its own harness', async () => {
+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list'
+ ? { agents: [{ id: 'win-harness', engine: 'claude', tmuxPane: '%3', status: 'active', terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%3' }] } }] }
+ : type === 'terminal_info' ? { command: 'claude', path: 'C:\\work', pid: 700 }
+ : payload.action === 'buddyCheck' ? { ok: true, buddiesHere: true } : { ok: true })
const print = vi.fn()
const deps = { where: () => where, print, platform: 'win32' as const, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }) }
- for (const env of [{ HARNESS_PANE: 'p1:%3' }, { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' }]) {
- buddiesHere = true
- expect(await superTabCommand([...prefix, 'status'], { ...deps, env })).toBe(1)
- expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toContain('This Windows computer runs a Buddy')
- buddiesHere = false
- expect(await superTabCommand([...prefix, 'status'], { ...deps, env })).toBe(0)
+ expect(await superTabCommand([...prefix, 'status'], { ...deps, env: { HARNESS_PANE: 'p1:%3' }, readProcesses: windowsPane })).toBe(0)
+ expect(request).toHaveBeenLastCalledWith('super_tabs', expect.objectContaining({ harnessId: 'win-harness' }), 30_000)
+ // Outside Harness: an agent's shell and a person's terminal alike, with its --agent.
+ for (const env of [{ CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' }, {}]) {
+ expect(await superTabCommand([...prefix, 'status'], { ...deps, env, readProcesses: windowsAlone })).toBe(0)
}
- buddiesHere = true
- expect(await superTabCommand([...prefix, 'status'], { ...deps, env: {} })).toBe(0)
})
-// The re-check of #2093 (minor 6): on Windows, --machine asked the other machine's daemon whether a Buddy runs, which it
-// does not answer for another computer, and a pty host pane was no pane for the other-machine refusal.
-it('on Windows, refuses another machine from a harness\'s pane, and asks this computer\'s daemon about its Buddies', async () => {
+// As a private tmux server's pane on a Mac: a command may not name a pane on Windows that its parents are not in.
+it('on Windows, refuses a command naming another harness\'s pane, and one under the PTY host naming none', async () => {
+ const request = vi.fn(async (type: string) => type === 'agents_list'
+ ? { agents: [{ id: 'builder', engine: 'claude', tmuxPane: '%9', status: 'active', terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%9' }] } }] }
+ : type === 'terminal_info' ? { command: 'claude', path: 'C:\\work', pid: 555 } : { ok: true })
+ const print = vi.fn()
+ const deps = { where: () => where, print, platform: 'win32' as const, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }) }
+ expect(await superTabCommand(['--tab', 'tab', 'status'], { ...deps, env: { HARNESS_PANE: 'p1:%9' }, readProcesses: windowsPane })).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0]).error)
+ .toBe('This command does not run in the Harness pane it names, so it did not run. Run it as your harness gave it, in its own pane.')
+ expect(await superTabCommand(['--tab', 'tab', 'status'], { ...deps, env: {}, readProcesses: windowsPane })).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0]).error)
+ .toBe('Harness could not tell which pane this command runs in, so it did not run it. Run it as your harness gave it, in its own pane.')
+ expect(request.mock.calls.some(([type]) => type === 'super_tabs')).toBe(false)
+})
+// The re-check of #2093 (minor 6): a pty host pane was no pane for the other-machine refusal, and --machine asked the other
+// machine's daemon about this computer.
+it('on Windows, refuses another machine from a harness\'s pane, asking this computer\'s daemon', async () => {
const opened: Where[] = []
- let buddiesHere = false
- const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list'
+ const request = vi.fn(async (type: string) => type === 'agents_list'
? { agents: [{ id: 'win-harness', engine: 'claude', tmuxPane: '%3', status: 'active', terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%3' }] } }] }
- : payload.action === 'buddyCheck' ? { ok: true, buddiesHere } : { ok: true })
+ : { ok: true })
const print = vi.fn()
const deps = { where: () => where, print, platform: 'win32' as const,
open: async (to: Where) => { opened.push(to); return { request, close: vi.fn(), machineId: to.machineId } as never } }
- expect(await superTabCommand(['--machine', 'macbook', ...prefix, 'status'], { ...deps, env: { HARNESS_PANE: 'p1:%3' } })).toBe(1)
+ expect(await superTabCommand(['--machine', 'macbook', ...prefix, 'status'], { ...deps, env: { HARNESS_PANE: 'p1:%3' }, readProcesses: windowsPane })).toBe(1)
expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toContain('this computer\'s own Harness only')
expect(opened).toEqual([where])
- // A Claude Code shell with no Harness pane: this computer's daemon is asked about its Buddies, not the other machine's.
- buddiesHere = true
- opened.length = 0
- expect(await superTabCommand(['--machine', 'macbook', ...prefix, 'status'], { ...deps, env: { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' } })).toBe(1)
- expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toContain('This Windows computer runs a Buddy')
- expect(opened).toEqual([where])
// A person's terminal chooses its machine.
opened.length = 0
- expect(await superTabCommand(['--machine', 'macbook', ...prefix, 'status'], { ...deps, env: {} })).toBe(0)
+ expect(await superTabCommand(['--machine', 'macbook', ...prefix, 'status'], { ...deps, env: {}, readProcesses: windowsAlone })).toBe(0)
expect(opened.at(-1)).toMatchObject({ machineId: 'macbook' })
})
// Re-check 2 of #2093 (important 6): pane ids restart in every tmux server, so a private server counted up to a Builder's
@@ -790,16 +802,6 @@ it('takes a pane\'s harness only when the daemon\'s own pane process is among th
expect(request).toHaveBeenCalledWith('terminal_info', { agentId: 'builder-harness' }, 10_000)
expect(request).toHaveBeenLastCalledWith('super_tabs', expect.objectContaining({ harnessId: 'builder-harness' }), 30_000)
})
-// Re-check 2 of #2093 at 0648a8690 (minor 8): a failed Swarm answer is no "Swarm off" on Windows' backstop either.
-it('refuses --agent from an agent\'s shell on Windows when this computer\'s Swarm cannot answer', async () => {
- const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}) => type === 'agents_list' ? { agents: [] }
- : payload.action === 'buddyCheck' ? { error: 'SERVICE_FAILED', service: 'superTabs' } : { ok: true })
- const print = vi.fn()
- expect(await superTabCommand([...prefix, 'status'], { where: () => where, print, platform: 'win32', env: { HARNESS_PANE: 'p1:%3' },
- open: async () => ({ request, close: vi.fn(), machineId: 'machine' }) })).toBe(1)
- expect(JSON.parse(print.mock.calls.at(-1)![0]).error).toBe('Harness could not reach this computer\'s Swarm just now, so it did not run this. Try again in a moment.')
- expect(request.mock.calls.filter(([type, payload]) => type === 'super_tabs' && (payload as Record<string, unknown>)?.action !== 'buddyCheck')).toEqual([])
-})
// A Buddy's read verbs (Ken, 10-29): archived tasks a page at a time, and a task's older messages, with no new verb.
it('parses archived status pages and older message pages', () => {
@@ -897,18 +899,17 @@ describe("a Buddy's usage line and JSON hints", () => {
expect(ok.request).toHaveBeenCalled()
expect(ok.asked.some(([, payload]) => payload?.action === 'buddyCheck')).toBe(false)
})
- // Windows cannot check a pty host pane (buddyPane.ts): an agent's shell on a computer running a Buddy gets a Buddy's words.
- it('words it for a Buddy on Windows from an agent\'s shell while this computer runs one', async () => {
- const wording = async (buddiesHere: boolean, env: NodeJS.ProcessEnv) => {
- const print = vi.fn(), request = vi.fn(async (_type: string, payload?: Record<string, unknown>) =>
- payload?.action === 'buddyCheck' ? { ok: true, buddiesHere } : { agents: [] })
- await superTabCommand(['--tab', 'tab', 'post', 'lead', 'Ready'], { where: () => where, print, platform: 'win32', env, pane: undefined,
+ it('words it for a Buddy on Windows from a Buddy\'s own pane alone', async () => {
+ const wording = async (buddy: boolean) => {
+ const print = vi.fn(), request = vi.fn(async (type: string, payload?: Record<string, unknown>) =>
+ payload?.action === 'buddyCheck' ? { ok: true, buddy }
+ : type === 'agents_list' ? { agents: [{ id: 'win-harness', engine: 'claude', tmuxPane: '%3', status: 'active', terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p1', paneId: '%3' }] } }] } : { ok: true })
+ await superTabCommand(['--tab', 'tab', 'post', 'lead', 'Ready'], { where: () => where, print, platform: 'win32', env: {}, pane: 'p1:%3',
open: async () => ({ request, close: vi.fn(), machineId: 'machine' }) })
return JSON.parse(print.mock.calls.at(-1)![0]).error as string
}
- expect(await wording(true, { HARNESS_PANE: 'p1:%3' })).toContain('post GROUP TEXT OPERATION_ID')
- expect(await wording(false, { HARNESS_PANE: 'p1:%3' })).toContain('post GROUP TEXT|- OPERATION_ID')
- expect(await wording(true, {})).toContain('post GROUP TEXT|- OPERATION_ID')
+ expect(await wording(true)).toContain('post GROUP TEXT OPERATION_ID')
+ expect(await wording(false)).toContain('post GROUP TEXT|- OPERATION_ID')
})
})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index d14223a13..40a9424ff 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -12,14 +12,14 @@ import { keyName } from './terminal.js'
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { isatty } from 'node:tty'
-import { inDaemonPane, NOT_IN_PANE, runningPane, type PaneProbe } from './callerPane.js'
+import { inDaemonPane, NOT_IN_PANE, runningPane, windowsRunningPane, type PaneProbe, type RunningPane } from './callerPane.js'
+import type { ProcessRow } from '../lib/processTable.js'
// cli.ts's way to it: this file is its door to the Swarm's code (architecture.spec.ts SWARM_DOORS).
export { buddyRefusal } from './buddyPane.js'
-import { agentShell, buddiesHere, paneBuddy, WINDOWS_BUDDY } from './buddyPane.js'
+import { paneBuddy } from './buddyPane.js'
import { sendPane } from '../messages/command.js'
-/** A frame with its terminals, as agents_list sends them: a pty host pane is named by its instance and pane (Windows). */
-type PaneFrame = Frame & { terminal?: { runtimes?: Array<{ backend?: string; instance?: string; paneId?: string }> } }
+type PaneFrame = Frame
/** Whether [pane] is a harness's here: a tmux pane as `callerOf` finds it, or a pty host's `<instance>:%N`. */
function harnessIn(frames: PaneFrame[], pane: string, machineId: string): boolean {
const pty = /^([^:]+):(%\d+)$/.exec(pane)
@@ -131,15 +131,13 @@ class WantsStdin { constructor(readonly what: string) {} }
/** Whether the harness in this pane is a Buddy, by this computer's launch record (service.ts `buddyCheck`, what turns its
* guard on), for a refusal's wording alone. Asked of this computer's daemon, never one named with --machine. Anything it
* cannot tell is no Buddy: the guard still refuses what a Buddy may not send. */
-async function buddyHere(open: typeof openDaemon, local: Where, pane: string | undefined, env: NodeJS.ProcessEnv, platform: NodeJS.Platform): Promise<boolean> {
- // Windows has no cheap check of a pty host pane (buddyPane.ts): an agent's shell on a computer that runs a Buddy.
- if (platform !== 'win32' && !pane) return false
+async function buddyHere(open: typeof openDaemon, local: Where, pane: string | undefined): Promise<boolean> {
+ if (!pane) return false
try {
const daemon = await open(local)
try {
- if (platform === 'win32') return agentShell(env) && await buddiesHere(daemon) === true
// The guard's own steps (buddyPane.ts paneBuddy), without its pane check: a wording, not a refusal.
- return await paneBuddy(daemon, pane!, local.machineId) === 'buddy'
+ return await paneBuddy(daemon, pane, local.machineId) === 'buddy'
} finally { daemon.close() }
} catch { return false }
}
@@ -304,6 +302,7 @@ async function parse(argv: readonly string[], local: Where, stdin: () => string
export async function superTabCommand(argv: readonly string[], deps: {
where?: () => Where; open?: typeof openDaemon; print?: (text: string) => void; pane?: string; probe?: PaneProbe; fetch?: typeof fetch; env?: NodeJS.ProcessEnv
platform?: NodeJS.Platform; stdin?: () => string | Promise<string>; terminal?: () => boolean
+ readProcesses?: () => Promise<ProcessRow[] | null>
} = {}): Promise<number> {
let daemon: Daemon | null = null
let operationId: unknown
@@ -311,37 +310,31 @@ export async function superTabCommand(argv: readonly string[], deps: {
try {
const platform = deps.platform ?? process.platform, env = deps.env ?? process.env, open = deps.open ?? openDaemon
// The pane this runs in, from its processes: TMUX_PANE is what the command says, and it may not name another harness's.
- const running = 'pane' in deps ? { pane: deps.pane } : runningPane(env, deps.probe, platform)
+ const running: RunningPane = 'pane' in deps ? { pane: deps.pane }
+ : platform === 'win32' ? await windowsRunningPane(sendPane(env), deps.readProcesses)
+ : runningPane(env, deps.probe, platform)
if (running.refused) throw new Error(running.refused)
const pane = running.pane
const local = (deps.where ?? (() => whereFor(pane)))()
const request = await parse(argv, local, deps.stdin ?? (() => readStdin(process.stdin)), deps.terminal)
.catch(async error => {
- if (error instanceof UsageError && await buddyHere(open, local, pane, env, platform)) throw new Error(error.words(true))
+ if (error instanceof UsageError && await buddyHere(open, local, pane)) throw new Error(error.words(true))
throw error
})
operationId = request.payload.operationId
// A harness reaches the Swarm through this computer's Harness alone (second review of #2087: a Buddy's --machine reached
// the owner's other Mac, which knew no pane there). The daemon refuses an agent's request from another computer as well.
const elsewhere = request.where.port !== local.port || request.where.machineId !== local.machineId
- // Windows has no cheap check of a pty host pane, so its pane is the one the shell names, for the refusal below alone; and
- // while this computer runs a Buddy, an agent's shell there names no agent. Both are asked of this computer's daemon,
- // never the other machine's (re-check of #2093: --machine asked the other one, which does not answer for this computer).
- const asking = pane ?? (platform === 'win32' ? sendPane(env) : undefined)
- const windowsAgent = platform === 'win32' && !!request.payload.agentId && agentShell(env)
- const checks = async (home: Daemon) => {
- if (elsewhere && asking) {
- const listed = await home.request('agents_list')
- if (harnessIn(Array.isArray(listed.agents) ? listed.agents as PaneFrame[] : [], asking, local.machineId)) throw new Error(ELSEWHERE)
- }
- if (windowsAgent && await buddiesHere(home)) throw new Error(WINDOWS_BUDDY)
- }
- if (elsewhere && (asking || windowsAgent)) {
+ // Asked of this computer's daemon, never the other machine's (re-check of #2093: --machine asked the other one, which does
+ // not answer for this computer).
+ if (elsewhere && pane) {
const home = await open(local)
- try { await checks(home) } finally { home.close() }
+ try {
+ const listed = await home.request('agents_list')
+ if (harnessIn(Array.isArray(listed.agents) ? listed.agents as PaneFrame[] : [], pane, local.machineId)) throw new Error(ELSEWHERE)
+ } finally { home.close() }
}
daemon = await open(request.where)
- if (!elsewhere) await checks(daemon)
const owners = request.payload.action === 'backend' || request.payload.action === 'setMachineAgents'
if (owners) {
// The owner's own acts: removal deletes this machine's Swarm folders, and no agent raises its own machine's room
diff --git a/cli/src/superTabs/gitCredential.spec.ts b/cli/src/superTabs/gitCredential.spec.ts
index 03804ce86..a542d95b1 100644
--- a/cli/src/superTabs/gitCredential.spec.ts
+++ b/cli/src/superTabs/gitCredential.spec.ts
@@ -62,6 +62,24 @@ describe('harness git-credential', () => {
expect((await run(['get'], ask('https://github.com/acme/app.git'), { ok: true, value: { ...token, defaultBranchProtected: true } })).err).toBe('')
})
+ // A Windows pane sets HARNESS_PANE, and no TMUX_PANE: without it, git got no token there for any Swarm agent's push.
+ it('finds a Windows agent by the pane its shell names', async () => {
+ vi.stubEnv('TMUX_PANE', '')
+ vi.stubEnv('HARNESS_PANE', 'p2:%7')
+ try {
+ const out: string[] = [], requests: unknown[] = []
+ const open = vi.fn(async () => ({ machineId: 'machine-1', close: vi.fn(), request: async (type: string, payload?: Record<string, unknown>) => {
+ requests.push([type, payload])
+ return type === 'agents_list'
+ ? { agents: [{ id: 'win-1', tmuxPane: '%7', status: 'active', engine: 'codex', name: 'Builder', terminal: { runtimes: [{ backend: 'ptyhost', instance: 'p2', paneId: '%7' }] } }] }
+ : { ok: true, value: token }
+ } })) as unknown as typeof import('../agentClient/daemon.js').openDaemon
+ await gitCredentialCommand(['get'], { where, open, input: async () => ask('https://github.com/acme/app'), print: t => out.push(t), warn: () => {} })
+ expect(requests).toContainEqual(['super_tabs', { action: 'githubToken', harnessId: 'win-1' }])
+ expect(out.join('')).toContain('password=ghs_fixture_token_1')
+ } finally { vi.unstubAllEnvs() }
+ })
+
it('gives another host, plain http or no path nothing, without asking the daemon', async () => {
for (const input of [ask('https://gitlab.example.com/acme/app.git'), 'protocol=http\nhost=github.com\npath=acme/app\n\n', 'protocol=https\nhost=github.com\n\n']) {
const result = await run(['get'], input)
diff --git a/cli/src/superTabs/gitCredential.ts b/cli/src/superTabs/gitCredential.ts
index 3fe6b3c08..582614422 100644
--- a/cli/src/superTabs/gitCredential.ts
+++ b/cli/src/superTabs/gitCredential.ts
@@ -13,6 +13,7 @@
*/
import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'
import { callerOf, type Frame } from '../agentClient/model.js'
+import { sendPane } from '../messages/command.js'
import { identifier, object } from './wire.js'
const USAGE = 'harness git-credential [--port N --machine ID] get|store|erase|trailers'
@@ -67,7 +68,7 @@ async function askToken(where: Where, deps: GitCredentialDeps): Promise<Record<s
try {
daemon = await (deps.open ?? openDaemon)(where)
const listed = await daemon.request('agents_list', {}, TIMEOUT_MS)
- const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], deps.pane ?? process.env.TMUX_PANE, where.machineId)
+ const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], deps.pane ?? sendPane(process.env), where.machineId)
if (!caller) return { error: 'NOT_A_SWARM_AGENT', detail: 'git asked for a GitHub token outside a Swarm agent\'s harness.' }
return await daemon.request('super_tabs', { action: 'githubToken', harnessId: caller.agentId }, TIMEOUT_MS)
} catch (error) {
@@ -78,7 +79,7 @@ async function askToken(where: Where, deps: GitCredentialDeps): Promise<Record<s
export async function gitCredentialCommand(argv: readonly string[], deps: GitCredentialDeps = {}): Promise<number> {
const print = deps.print ?? (text => process.stdout.write(text))
const warn = deps.warn ?? (text => process.stderr.write(`${text}\n`))
- const where = { ...(deps.where ?? (() => whereFor(process.env.TMUX_PANE)))() }
+ const where = { ...(deps.where ?? (() => whereFor(sendPane(process.env))))() }
const positional: string[] = []
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '--port') where.port = Number(argv[++i])
diff --git a/cli/src/superTabs/github.spec.ts b/cli/src/superTabs/github.spec.ts
index 7b292c16f..4cebe78ff 100644
--- a/cli/src/superTabs/github.spec.ts
+++ b/cli/src/superTabs/github.spec.ts
@@ -193,7 +193,7 @@ describe('keeping gh\'s token fresh', () => {
it('keeps the folder of a session still starting, and of one not read just now, until it is 15 minutes untouched', async () => {
const dataDir = mkdtempSync(join(root, 'starting-'))
const core = fakeCore({ dataDir, agents: { live: vi.fn(() => []), all: vi.fn(() => []), byAgent: vi.fn(() => undefined) } })
- swarmGitHubLaunch('harness-codex-starting', { dataDir, command: '/bin/true', port: 1, machineId: 'machine-1' }, 'darwin')
+ swarmGitHubLaunch('harness-codex-starting', { dataDir, command: '/bin/true', port: 1, machineId: 'machine-1' })
const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-starting')!
expect(existsSync(dir)).toBe(true)
await new GitHubTokenRefresher(core, () => ({}) as never).tick()
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 0db5125f9..d92457c5c 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -344,7 +344,7 @@ describe('contributed machine executor', () => {
Object.assign(f.pool, { capabilitiesWanted: true })
await f.machine.tick()
const posted = (g: typeof f) => g.backend.mock.calls.filter(c => c[1] === 'POST').map(c => c[3] as Record<string, unknown>)
- expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'leadSwitch', 'buddyModel'] })
+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'leadSwitch', 'buddyModel'] })
// A backend from before them does not ask, and would refuse the field.
const older = fixture()
await older.machine.tick()
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 768c32fc9..93f1a589f 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -183,7 +183,9 @@ const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list
/** What this host launches beyond workers, said in its reading (backend leadStart.ts): a project's Product Manager, a
* Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions), and a person's one Buddy for the Swarm in its folder of
* project worktrees (spec 2026-10-31-one-buddy-per-swarm), which the backend offers only on a host that says so. */
-const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy']
+// windowsBuddy: this CLI proves a command's pane from its parents on Windows too (callerPane.ts `windowsRunningPane`), so a
+// Buddy there refuses no other agent's Swarm command. The backend starts no Buddy on a Windows machine without it.
+const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy']
/** What this host does for a Product Manager's switch to another engine or account (spec 2026-11-02-pm-switch-engine-account),
* said beside the others: the backend refuses a switch to a host that does not. */
CAPABILITIES.push('leadSwitch')
diff --git a/cli/src/team/admin.ts b/cli/src/team/admin.ts
index 723689fde..6c26c6af4 100644
--- a/cli/src/team/admin.ts
+++ b/cli/src/team/admin.ts
@@ -92,7 +92,7 @@ function stopped(stderr: string, code: number | null): AdminResult {
}
/** PowerShell single quotes: nothing is special inside but the quote itself, doubled. */
-const psQuote = (word: string): string => `'${word.replaceAll("'", "''")}'`
+export const psQuote = (word: string): string => `'${word.replaceAll("'", "''")}'`
/**
* What runs elevated on Windows: the team script, with what it says kept in the staging folder. `Start-Process -Verb
diff --git a/cli/src/team/command.spec.ts b/cli/src/team/command.spec.ts
index 693ef46bb..028c16049 100644
--- a/cli/src/team/command.spec.ts
+++ b/cli/src/team/command.spec.ts
@@ -1055,6 +1055,15 @@ describe('harness team logs and sign-in', () => {
expect(none.err.join('\n')).toContain('No Harness Team account')
})
+ it('reads the team log on Windows too, quoting its path for PowerShell', async () => {
+ const f = fake({ platform: 'win32', adminResult: { ok: true, stdout: '2026-11-03 14:23:01 [agent] create pane open\n' },
+ readConfig: () => ({ ...config, home: "C:\\Users\\O'Team" }) as never })
+ expect(await teamCommand(['logs', '--lines=5'], f.deps)).toBe(0)
+ expect(f.built[0]!.script).toContain("Get-Content -LiteralPath 'C:\\Users\\O''Team")
+ expect(f.built[0]!.script).toContain('-Tail 5 -Encoding UTF8 -ErrorAction Stop')
+ expect(f.out.join('\n')).toContain('create pane open')
+ })
+
it('refuses the sign-in where it cannot run, naming what to do instead', async () => {
const windows = fake({ platform: 'win32', readConfig: () => config as never })
expect(await teamCommand(['sign-in', 'claude'], windows.deps)).toBe(1)
diff --git a/cli/src/team/command.ts b/cli/src/team/command.ts
index a9e8f33c9..5c19b9015 100644
--- a/cli/src/team/command.ts
+++ b/cli/src/team/command.ts
@@ -17,7 +17,7 @@ import { spawnSync } from 'node:child_process'
import type { AgentTmpState } from '../lib/agentTmp.js'
import { sameSignIn, type AuthSession } from '../lib/authSession.js'
import { SIGN_OUT_BUTTON_FLAG, type SignOutAsked } from '../lib/signOut.js'
-import type { AdminVia, RunAdmin } from './admin.js'
+import { psQuote, type AdminVia, type RunAdmin } from './admin.js'
import { teamConfigJson, type TeamConfig } from './config.js'
import { engineLines, type TeamEngines } from './engines.js'
import { teamModelSet } from './model.js'
@@ -840,11 +840,14 @@ async function teamLogs(deps: TeamCommandDeps, words: readonly string[], flags:
const where = deps.platform === 'darwin' ? 'this Mac' : 'this computer'
const config = deps.readConfig()
if (!config) return fail(deps, json, 'NO_ACCOUNT', `No Harness Team account on ${where}. Run harness team setup first.`)
- if (deps.platform === 'win32') return fail(deps, json, 'UNSUPPORTED', 'Reading the team log on Windows is not here yet; harness team status shows its path.')
const inline = flags.find((flag) => flag.startsWith('--lines='))
const asked = inline ? Number(inline.slice('--lines='.length)) : flags.includes('--lines') ? Number(words[1]) : 40
const lines = Number.isInteger(asked) && asked > 0 && asked <= 5000 ? asked : 40
- const result = await deps.admin(() => ({ script: `tail -n ${lines} ${quoted(teamPaths(config.home).log)}` }),
+ // Windows has no tail. -ErrorAction Stop: a log not there yet is said as an error, as tail says it.
+ const read = deps.platform === 'win32'
+ ? `Get-Content -LiteralPath ${psQuote(windowsTeamPaths(config.home).log)} -Tail ${lines} -Encoding UTF8 -ErrorAction Stop`
+ : `tail -n ${lines} ${quoted(teamPaths(config.home).log)}`
+ const result = await deps.admin(() => ({ script: read }),
`Harness wants to read the Harness Team account's log on ${where}.`)
if (!result.ok) {
if (result.code === 'NO_PROMPT') deps.err(`✗ ${result.message} Run it in a terminal.`)
diff --git a/desktop/lib/super_tabs/buddy_machines.dart b/desktop/lib/super_tabs/buddy_machines.dart
index 928a39901..4719d3473 100644
--- a/desktop/lib/super_tabs/buddy_machines.dart
+++ b/desktop/lib/super_tabs/buddy_machines.dart
@@ -286,12 +286,6 @@ class _BuddyMachineFieldState extends State<BuddyMachineField> {
/// machine was being prepared.
const kBuddyAccessLost = 'Your access changed, so no Buddy was added.';
-/// Harness cannot yet tell a Buddy's window from another agent's on Windows
-/// (security review of #2093): the server says the same (backend machines.ts).
-const kBuddyWindows =
- 'A Buddy cannot run on a Windows machine yet. Pick one of your Macs or '
- 'Linux machines.';
-
/// What a Buddy's start sends, once the person has clicked Start: the picked
/// machine and, for one of theirs outside the Swarm, its setup, prepared there
/// as Add machine prepares one. Nothing is added to the Swarm. Keeps the setup
@@ -316,15 +310,6 @@ class BuddyMachineAdder {
}
_setupId ??= superTabOperationId();
try {
- // The server checks again once the machine reports; asked here first so
- // nothing is prepared there for nothing. An unreadable answer refuses
- // nothing.
- final os = await app
- .readMachineResources(machine.id)
- .then((r) => r?.os, onError: (_) => null);
- if (os != null && os.toLowerCase().contains('windows')) {
- return (id: null, setup: null, error: kBuddyWindows);
- }
final setup = await prepareBuddyMachine(
controller,
app,
diff --git a/docs/superpowers/plans/2026-11-04-windows-parity.md b/docs/superpowers/plans/2026-11-04-windows-parity.md
new file mode 100644
index 000000000..c03a0176c
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-04-windows-parity.md
@@ -0,0 +1,178 @@
+# Windows parity Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans. The owner asked for no subagents. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Everything Harness does on a Mac works on Windows, proven on the released, signed build.
+
+**Architecture:** Fix each gap at its one cause and share code with the Mac path. One PR per group, each released, then tested on the Windows PC with the released version.
+
+**Tech Stack:** TypeScript CLI (vitest), Flutter Desktop, Rust (`serial/`, `tui/`).
+
+**Spec:** `docs/superpowers/specs/2026-11-04-windows-parity-design.md`
+
+## Global Constraints
+
+- Signing is solved (Azure Artifact Signing since #2708); no task works on it.
+- Web panes: the standard `WebViewController` only. Store apps and their agents are out of scope.
+- Fewer branches, not more: a Windows fix replaces a special case wherever it can.
+- macOS and Linux behavior does not change; their existing tests stay green.
+- PR CI once per push. `make merge-pr`. Local gates recorded in the PR. Design section in the PR.
+- Proof is the released build on `DESKTOP-0TFH0OJ`, to the last real step.
+
+## Review Focus
+
+- A PC with a Team account holding the configured port: every local command must reach the daemon on its given port (Task 1).
+- A Buddy naming another drive or a drive-relative path: refused (Task 2).
+- A Swarm agent pushing on Windows: git asks `harness git-credential`, and it must find the agent's pane (Task 3).
+- A PC without Git for Windows: a Buddy must not start with its guard unable to run (Task 4).
+- An engine installer killed halfway: the next launch recovers and does not wait forever (Task 13).
+
+---
+
+## PR A: finish Buddy and Swarm reach (added to #2979)
+
+### Task 1: One daemon record lookup
+
+**Files:** Modify `cli/src/lib/daemonRecord.ts`, `cli/src/lib/windows/daemonPipe.ts`, `cli/src/lib/localTransport.ts`, `cli/src/lib/localSocket.ts:83`. Test `cli/src/lib/daemonRecord.spec.ts`, `cli/src/lib/windows/daemonPipe.spec.ts`.
+
+**Produces:** `configuredPortOf(dataDir: string, port: number, platform?: NodeJS.Platform): number`, the name a daemon serving `port` was recorded under, or `port` when there is none.
+
+- [ ] Test: with only `daemon-18473.json` saying port 55332, `configuredPortOf(dir, 55332)` is 18473 and `configuredPortOf(dir, 18473)` is 18473.
+- [ ] Test: `daemonPipe(dir, 55332, alive)` returns the recorded pipe and token. Run it and see both fail.
+- [ ] Add `configuredPortOf`; use it in `daemonPipe`, `daemonPipeNow`, `daemonFetch` and the pipe path in `localSocket.ts`. Delete `recordServing`. `localSocketRoute`'s own scan stays: it checks that a socket exists, and the Mac must not change.
+- [ ] Run `npx vitest run src/lib/daemonRecord.spec.ts src/lib/windows/daemonPipe.spec.ts src/lib/localTransport.spec.ts src/lib/localSocket.spec.ts`; all pass.
+- [ ] On the PC, with a dev bundle: `harness autonomous-device status`, `list` and `discover --json` answer.
+
+### Task 2: Guard refuses drive paths
+
+**Files:** Modify `cli/src/lib/buddyGuard.ts:413`. Test `cli/src/lib/buddyGuard.spec.ts`.
+
+- [ ] Test the generated guard's `outward`: on Windows, `C:secret.txt`, `D:x`, `C:` and `--file=D:x` are outward; `a.txt`, `HEAD:src/x` and `main..HEAD` are not.
+- [ ] Add it to `outward`, only when `process.platform === 'win32'`: a word or its part after `=` starting with a drive letter and colon. `%NAME%` needs nothing: Git Bash does not expand it.
+- [ ] Rerun `guard/run.cjs` on the PC: 43 cases, 0 wrong.
+
+### Task 3: Pane names on Windows
+
+**Files:** Modify `cli/src/superTabs/gitCredential.ts:70,81`, `cli/src/cli.ts:2849`. Test `cli/src/superTabs/gitCredential.spec.ts`.
+
+- [ ] Test: with `HARNESS_PANE=p2:%3` and a frame on that pty pane, `get` asks for that agent's token. See it fail.
+- [ ] Use `sendPane(process.env)` in both `gitCredential` lines and in `case 'mcp'`, with the `inPane` form `mcp-servers` uses.
+- [ ] Run the spec; passes.
+
+### Task 4: No Buddy without Git Bash
+
+**Files:** Modify `cli/src/lib/swarmSkills.ts` (`prepareSwarmSkill`), using the lookup in `cli/src/dsh/shell.ts`. Test `cli/src/lib/swarmSkills.spec.ts`.
+
+- [ ] Test: on win32 with no Git Bash, preparing a Buddy skill throws a sentence saying a Buddy needs Git for Windows. See it fail.
+- [ ] Add the check, for Buddy skills only, with an injected lookup for tests.
+- [ ] Run the spec; passes.
+
+### Task 4b: The GitHub App on Windows
+
+**Files:** Modify `cli/src/lib/swarmGitHub.ts`, its spec, `docs/swarm-github-app.md`.
+
+`swarmGitHubLaunch` returned null on Windows, saying its git does not run shell scripts. Tried on the PC: Git for Windows runs the helper, the hooks and the identity, with a space in the path. Remove the check.
+
+### Task 5: Ship PR A
+
+- [ ] Run `test:portability`, `test:core`, `test:super-tabs`; record them in the PR. Push once. Wait for `ci/required`.
+- [ ] Windows first (owner, 2026-11-04): no public release before this works. Test with a signed Desktop candidate (`make release-desktop ARGS="--prepare"`) and the CLI bundle on the PC. Other members release Mac and Linux.
+- [ ] Merge, then release; the backend change is what a real Buddy on Windows needs live.
+- [ ] On the PC. Start a real Buddy on it in the autonomous-ai Swarm, message it, read its reply.
+- [ ] From a real Swarm pane on the PC: `harness git-credential` answers for a task's repository.
+- [ ] `Get-AuthenticodeSignature` on the installed `harness.exe` says Valid. Only if not, find why `harness update` left it.
+
+---
+
+## PR B: small Windows bugs
+
+### Task 6: Team engine report
+
+**Files:** `cli/src/team/engines.ts:136`, spec beside it. Remove the platform check; test that a win32 Team config reports. *Proof: `harness team status` lists engines.*
+
+### Task 7: Import an agent
+
+**Files:** `desktop/lib/super_tabs/import_agent_dialog.dart:28`, its test. Offer on Windows. *Proof: import an agent on the PC and message it.*
+
+### Task 8: `harness team model`
+
+**Files:** `cli/src/team/model.ts:123`, `cli/src/team/windowsScript.ts`, specs. Add `windowsTeamModelScript(input): string`, the twin of the root script, through the existing admin prompt. *Proof: a Team agent answers through the set API.*
+
+### Task 9: `harness remote`
+
+**Files:** `cli/src/cli.ts:3017`, `cli/src/remoteCommand.ts:290`, `cli/src/lib/terminalHandoff.ts`, `cli/src/backendSocket.ts:1166`, specs. Take `sendPane(process.env)`; accept the pty pane form in `HANDOFF_PANE_RE`. *Proof: a Windows tile switches machine.*
+
+### Task 10: Board reset
+
+**Files:** `serial/src/model.rs`, `serial/src/` port code, `cli/src/cable/boardReset.ts`, `cli/src/cable/windowsSerial.ts`, tests. Add a `reset <COM>` verb with the same pulse (`RTS` 200 ms, then both low 200 ms). *Proof: needs a dial on the PC; the owner plugs one in.*
+
+### Task 11: Clipboard, window forward, time zone
+
+**Files:** `cli/src/lib/osClipboard.ts:113`, `desktop/lib/screens/swarm_screen.dart:7460`, `desktop/lib/super_tabs/local_time_zone_native.dart`, tests.
+- `writeWindowsClipboard(pngPath)` through PowerShell in STA mode.
+- Window forward through `window_manager`.
+- Time zone: `DateTime.now().timeZoneName` mapped to IANA by a const table from CLDR `windowsZones`. A name not in it stays null.
+
+*Proof: each seen on the PC.*
+
+---
+
+## PR C: voice
+
+### Task 12: Voice plays in the chat
+
+**Files:** `desktop/pubspec.yaml`, `desktop/lib/super_tabs/voice_bubble.dart:35`, `desktop/THIRD_PARTY` notices, test.
+- [ ] Add `video_player_win: 3.3.1`; build on the PC. A failed build stops here and picks another player.
+- [ ] Remove Windows from `_playsHere`. A load failure opens the file, as today.
+- [ ] *Proof: a real clip plays on the released build.*
+
+---
+
+## PR D: installing engines
+
+### Task 13: Install on Windows
+
+**Files:** Create `cli/src/engines/kit/windowsInstall.ts`. Modify `cli/src/lib/engineInstall.ts`, `cli/src/engines/kit/nativeInstall.ts:155`, `cli/src/lib/engineLaunch.ts:1319`, `desktop/lib/bootstrap/agent_prefetch.dart` comment. Specs beside each.
+
+**Produces:** `windows?: { npm: string } | { powershell: string }` on `EngineInstallRecipe`; `createWindowsInstallations(...)` with the same result shape as `createNativeInstallations`.
+
+- [ ] Test: two launches of one engine run one install; a claim whose holder is dead (pid gone, or a later `w:<FILETIME>`) is taken over; a timeout ends the tree and reports; a finished install is only believed through `captureLaunchExecutable`.
+- [ ] Implement per the spec's W3.
+- [ ] Fill in `windows` per engine from each vendor's documented install, run on the PC. None documented stays refused, by name.
+- [ ] *Proof on the released build: with an engine absent, `harness new` and the Desktop form install it, and the agent answers.*
+
+---
+
+## PR E: web panes
+
+### Task 14: Standard web view
+
+**Files:** `desktop/pubspec.yaml`, create `desktop/lib/core/windows_webview_runtime.dart`, modify `desktop/lib/widgets/native_webview_host.dart:20`, `desktop/lib/widgets/web_pane_panel.dart:93`, `desktop/lib/store/store_demo_dialog.dart:81`, `desktop/lib/main.dart:23`, tests.
+- [ ] Add `webview_win_floating: 3.0.3`; on the PC, open a page and test a menu over it, tab switch, drag, resize, 150% scale, minimize. A failure here changes the plugin before anything else.
+- [ ] Merge the Linux and Windows runtime checks into one `NativeWebViewRuntime`, so there is one check, not two.
+- [ ] `NativeWebViewHost` covers both platforms.
+- [ ] *Proof on the released build: a page in a pane beside its terminal.*
+
+---
+
+## PR F: OpenCode on Arm
+
+### Task 15: OpenCode on Windows on Arm
+
+**Files:** `cli/src/lib/windows/launch.ts:74`, spec, one manual run on a `windows-11-arm` runner. Re-measure the current Arm build; if it runs, remove the refusal; if not, run the x64 build under emulation. *Proof: it answers a prompt there.*
+
+---
+
+## PR G onward: `hn`
+
+### Task 16: `hn` compiles and ships on Windows
+
+Per the spec's W6, one PR per step: transport, local panes, shell, ship. Start by rerunning `cargo check` on current main for the true error list, on the PC. Mac and Linux gates stay green at each PR. *Proof: `hn` on the PC lists every machine's harnesses, attaches, and splits.*
+
+---
+
+## Then: guests
+
+### Task 17: Guest sharing spec
+
+Write `docs/superpowers/specs/<date>-windows-guests-design.md` after the spike: can one daemon drive panes on a second `harness-pty` in another account? It goes to security review before any code, then gets its own plan.
diff --git a/docs/superpowers/specs/2026-11-04-windows-parity-design.md b/docs/superpowers/specs/2026-11-04-windows-parity-design.md
new file mode 100644
index 000000000..cb2434ab3
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-04-windows-parity-design.md
@@ -0,0 +1,243 @@
+# Windows parity: design and plan
+
+## Why
+
+The owner wants one thing: **everything Harness does on a Mac works on Windows**, and each piece is
+proven on a real Windows PC before it is called done. Today several features refuse on Windows with
+"not on Windows yet", which makes the Windows app feel unfinished.
+
+## Goals
+
+- Each row of the table below works on the Windows test PC, to its last real step.
+- A feature that truly cannot run on some Windows machine says why and what to do instead.
+- Each work package ships on its own, following AGENTS.md.
+
+## Non-goals
+
+- Mac chrome with no Windows meaning: traffic lights, the Dock count, the Local Network prompt, the
+ keychain read, `DaemonOwnerGuard`. Windows already has its own version (window buttons, tray, credential
+ files) or has no such problem.
+- Linux gaps. Voice playback on Linux, for example, stays as it is.
+
+## Anti-goals (a failure even if the feature "works")
+
+- A Windows Buddy reading outside its folder with nothing enforcing the limit.
+- A guest's agent running as the owner's account.
+- A `Platform.isWindows` patch that hides a refusal without doing the work.
+- Moving a published tag, or claiming a feature works from unit tests alone.
+
+## Constraints
+
+- Test PC: `DESKTOP-0TFH0OJ`, Windows 11 Pro, x64, Smart App Control on, WebView2 156 present. It cannot
+ test Arm.
+- AGENTS.md: PR CI once, `make merge-pr`, a Design section (below), local coverage gates recorded in the PR.
+- Native plugins carry a cost: each new DLL ships in the Windows package and must be signed there. The
+ release signs each zip's `.exe` and `.dll` (`sign-windows` in `release-desktop.yml`).
+
+## Where Windows stands today
+
+Read from the code on 2026-11-04.
+
+| # | Feature | Windows today | Where | Package |
+|---|---|---|---|---|
+| 1 | Buddy | Built in #2979, not merged or released | `superTabs/callerPane.ts` | W0 |
+| 2 | Team account's engine report | Never written: the reporter reads no config off Mac and Linux, though Windows has had Team accounts since 0.5.4. To confirm on the PC | `team/engines.ts:136` | W1 |
+| 3 | Import an agent | Not offered | `super_tabs/import_agent_dialog.dart:28` | W1 |
+| 4 | `harness team model` | Refused | `team/model.ts:123` | W1 |
+| 5 | Image written to the OS clipboard by the CLI | "no clipboard writer" | `lib/osClipboard.ts:113` | W1 |
+| 6 | Bringing the window forward when a device appears | Mac only | `screens/swarm_screen.dart:7460` | W1 |
+| 7 | Signed native files on an updated PC | The PC still has `harness.exe` and `harness-launch.exe` from Oct 21, unsigned | `lib/updateCommand.ts` | W1 |
+| 8 | Voice message plays in the chat | Opens the system player | `super_tabs/voice_bubble.dart:35` | W2 |
+| 9 | Installing an engine | Refused: "install it, then try again" | `engines/kit/nativeInstall.ts:155`, `lib/engineLaunch.ts:1319` | W3 |
+| 10 | Hermes hooks | None | `engines/nativeHooks.ts:43` | W3 |
+| 11 | Web panes | Shows the URL instead | `widgets/web_pane_panel.dart:93` | W4 |
+| 12 | OpenCode on Windows on Arm | Refused: its Arm build crashes | `lib/windows/launch.ts:74` | W5 |
+| 13 | `hn` | Refused: 200 compile errors in 19 files | `tui/index.ts:104` | W6 |
+| 14 | Sharing this computer with guests | Refused: "needs macOS or Linux" | `lib/guestHelperInstall.ts:130` | W7 |
+| 15 | Buddy reading beyond its folder | Stays in its own folder | `lib/buddyGuard.ts:166` | Not doing |
+
+Checked and fine: dial and cable wake (`core/devicesWake.ts:139` has its own Windows path).
+`harness team sign-in` refuses, but signing in from the Harness app works, so it stays.
+
+## Work packages
+
+Every package has the same finish line: code, tests, local gates, one PR, CI, merge, release, then the real
+steps below on the test PC. A package is not done until those steps pass.
+
+### W0: Buddy (built)
+
+1. Merge #2979. Needs a review or the owner's merge (see Open items).
+2. Release the CLI, deploy the backend.
+3. Update the PC. Start a real Buddy on it in the autonomous-ai Swarm, send a message, read its reply.
+4. After teammate PR #2975 lands, release Desktop 1.3.61, which carries #2947's UI as well.
+
+### W1: Small Windows bugs (one PR)
+
+- **Engine report.** Remove the platform check; `teamConfigFile` is already per platform. Check that
+ `realEngineCheckDeps` finds the engines under `windowsTeamPaths`. *Proof: `harness team status` lists them.*
+- **Import.** Add Windows to `superTabImportOffered` and fix what the real flow finds. *Proof: import an
+ agent into a project on the PC, then message it.*
+- **`team model`.** Write the Windows twin of its root script, through the admin prompt `team logs` already
+ uses: connections and settings written under the Team home, with the same locked-down ACL as the rest of
+ that home, then the Team task restarted. *Proof: a Team agent answers through the set model API.*
+- **Clipboard.** Write the PNG with PowerShell in STA mode (`Windows.Forms.Clipboard.SetImage`), through the
+ existing PowerShell query helper. *Proof: paste the image into another app on the PC.*
+- **Window forward.** Use `window_manager` on Windows. *Proof: plug in a device and the window comes up.*
+- **Signed files.** First find the cause: download the current release's payload, check its signature, and
+ read which step would replace `harness.exe`. Likely cause, not yet proven: a signed rebuild with an
+ unchanged version is treated as "nothing newer". Fix that step. *Proof: `harness update` on the PC, then
+ `Get-AuthenticodeSignature` says Valid.*
+
+### W2: Voice in the chat (one PR)
+
+- Add `video_player_win` 3.3.1. It implements `video_player_platform_interface`, so `voice_bubble.dart` keeps
+ using one controller. Remove Windows from the `_playsHere` exclusion.
+- Clips are WAV (`voice_wav.dart`, `wavFromPcm16`), which Media Foundation plays with no extra codec.
+- If the player fails to load, keep today's behavior of opening the file, so nothing gets worse.
+- Spike first: `flutter pub get` and a Windows build. Its pubspec still says `sdk: ^2.17.0`, which the
+ resolver should accept under Dart 3 but must be seen to.
+- *Proof: a clip recorded on the Mac plays in the Windows chat with its progress moving; seek and speed work.*
+
+### W3: Installing engines (one PR, maybe two)
+
+Before: a missing engine stops the launch. After: Harness installs it, then starts the agent, as on a Mac.
+
+- **Recipe.** Add `windows` to `EngineInstallRecipe` in `lib/engineInstall.ts`, either `{ npm: '<package>' }`
+ or `{ powershell: '<vendor url>' }`. No entry means the launch refuses and names the vendor's page. The type
+ stays exhaustive, so a new engine must decide.
+- **Which engines.** npm today: Claude Code, Codex, Pi, Command Code, Kilo, Copilot. The others use
+ `curl | bash` (Cursor, OpenCode, oh-my-pi, Hermes, Devin, Muse, Amp, Grok, Antigravity). For each, check the
+ vendor's documented Windows install and run it on the PC. An engine with no official Windows install stays
+ refused, by name. Hermes gets a hook runner only if it gets an install.
+- **Runner.** New `engines/kit/windowsInstall.ts`, with the same result shape as `createNativeInstallations`,
+ whose evidence walks POSIX paths and cannot be reused. It takes:
+ - one claim per engine, an exclusive-create file holding the pid and its `w:<FILETIME>` start marker, so a dead
+ holder is recognised and a reused pid is not mistaken for it;
+ - a hidden process running `npm.cmd` through `cmd`, Harness's Node on PATH, no window, output to a log. The
+ same pattern as `windowsTeamEnginesScript`, tested there;
+ - an 8 minute limit, then `taskkill /T`;
+ - after it exits, `captureLaunchExecutable` is the only proof it worked.
+- **Remove** the two refusals and the stale comment in `bootstrap/agent_prefetch.dart`. Desktop keeps
+ installing on first use rather than prefetching.
+- **Smart App Control.** It may block an unsigned engine `.exe`. The launch must then say so rather than hang.
+ The test PC has it on, so this is seen for real.
+- *Proof: on the PC, with an engine absent, `harness new` and the Desktop form install it, the agent starts and
+ answers a prompt. Repeated for one engine of each kind, and for an engine that stays refused.*
+
+### W4: Web panes (one PR)
+
+- Add `webview_win_floating` 3.0.3. It implements `webview_flutter_platform_interface`, so `WebViewController`
+ and `web_pane_panel.dart` stay one code path. It uses WebView2.
+- It draws a real window above Flutter, as Linux's plugin does, so reuse `NativeWebViewHost`: extend its
+ Linux check to Windows, so the pane hides while a menu or a dialog is open.
+- Add `core/windows_webview_runtime.dart`, the twin of `LinuxWebViewRuntime`. Without WebView2 the pane falls
+ back to the URL, as it does today. Update `webviewAvailable` and `store_demo_dialog.dart`.
+- WebView2's data folder goes under `%LOCALAPPDATA%`, never beside the app in its install folder.
+- **Rejected:** `webview_windows` (last release February 2024, its own interface); `webview_all_windows`
+ (released yesterday, and the interface family already avoided on Linux, per `desktop/RELEASE.md`).
+- **Spike first, because this decides the design:** a pane on the PC with a menu over it, a tab switch, pane
+ drag and swap, resize, 150% display scale, minimize and restore. If the page reloads on each hide or
+ it misplaces itself under scaling, fix it or swap the plugin before building more.
+- **Scope (owner, 2026-11-04):** only the standard web view, the same `WebViewController` protocol the Mac uses,
+ with no Windows-only web pane code beyond the host and the runtime check above. Making store apps and their agents
+ run on Windows is not part of this.
+- *Proof: a page opened in a pane beside its terminal, through every step above.*
+
+### W5: OpenCode on Windows on Arm (one PR)
+
+- First re-measure. The refusal came from OpenCode 1.19.3 and a newer Arm build may be fixed. If so, remove the
+ refusal.
+- If not, install and run the x64 build under Windows' emulation, and refuse only if that fails too.
+- The test PC is x64, so this runs once on a `windows-11-arm` GitHub runner, with a pane reading the screen.
+- *Proof: OpenCode answers a prompt there.* If the runner cannot show that, this package says so and stops.
+
+### W6: `hn` (several PRs)
+
+Measured: `cargo check` on the PC gives 200 errors in 19 files, 79 in `local.rs`. Mostly `std::os::unix`,
+`libc`, `pre_exec` and file modes. **More will appear behind these**, because type checking stops early, and
+this measure was on commit 831e22881, not current main.
+
+1. **Transport.** `ipc.rs` and `daemon.rs` talk to the daemon over its named pipe with its token, as
+ `lib/localTransport.ts` does.
+2. **Local panes.** `local.rs` uses the ConPTY support already in the vendored `alacritty_terminal`
+ (`tty/windows`). Signals, uids and modes each get a Windows meaning or a `cfg`.
+3. **Shell.** `shell_integration.sh`, `shell_picker.rs` and `shell_context.rs` get PowerShell.
+4. **Keep tmux behavior** identical on Mac and Linux. Their gates (`cargo test --locked`,
+ `scripts/validate-tui-native.py`) must stay green.
+5. **Ship.** A Windows target in `release-tui.yml`, signed like `pty-sign`; `tui/install.ts` learns Windows;
+ the `tuiCommand` refusal goes.
+
+*Proof: `hn` on the PC lists harnesses from every machine, attaches to one, splits a pane, and a local shell
+runs in Windows Terminal, with the native gate run there.*
+
+### W7: Guests (own spec first, then several PRs)
+
+The Mac design is an OS account per guest and `sudo -n guest-helper`. Windows has no equivalent to sudo, and
+this is a real security boundary, so **it gets its own spec and security review before any code.**
+
+Proposed starting point, reusing the Team account's tested parts on Windows:
+
+- One admin prompt to turn sharing on, which registers a fixed-verb task that creates and removes `hg_<hex>`
+ accounts. It validates its input strictly, because it crosses a privilege boundary.
+- Each guest gets a local account with a generated password, stored for the owner only (DPAPI). The owner's
+ daemon starts a `harness-pty` host in that account, and its pipe's ACL admits the owner. This is needed
+ because `CreateProcessWithLogonW` cannot attach a ConPTY directly, so **the host, not the engine, is what
+ crosses accounts**.
+- The daemon drives that host as one more terminal instance; `p<host>:%N` names already carry the instance.
+
+**Spike first:** can one daemon drive panes on a second host in another account? If not, each guest needs their
+own daemon, as the Team account has, and the design changes.
+
+*Proof: a second person's account joins, runs an agent there, the agent cannot read the owner's home, and
+removing the guest removes the account and its files.*
+
+### Not doing: a Windows Buddy reading beyond its folder
+
+On a Mac, Claude Code's OS sandbox enforces that wide mode: no writes, a host list, closed folders. Windows has
+no such sandbox, so only the guard hook would stand in the way, and a shell command can walk past a hook. A
+Buddy on Windows still works; it reads its own folder. **This is the only table row that stays different.**
+
+## Order
+
+W0, W1, W2, W3, W4, W5, W6, W7. Quick wins and the most-used features first; W3 is what a new Windows user hits
+first, and W2 comes before it only because it is small. W7 is last because it is the biggest risk.
+
+## Design
+
+- **Growth:** W3's install logs and claims are one per engine and overwritten. W4's WebView2 data is cleared with
+ the pane's data. W7's accounts are removed with the guest. Nothing else stores anything.
+- **Concurrency:** W3 locks per engine with an exclusive-create file. W7's task runs one verb at a time. The rest
+ hold no lock.
+- **Read cost:** W3 and W7 read the process table only when a claim looks stale, using `harness-pty ps` (42–65 ms
+ measured). W1's engine report keeps its existing schedule.
+- **Scale:** The limits are one machine's, so 10x is not a server question. First warnings: W3's 8 minute limit;
+ W4's memory, with one WebView2 process per pane, to be measured in its spike; W7 by guests per PC, limit to be set
+ in its spec.
+- **Compatibility:** An old CLI with a new Desktop keeps its old refusal. W3's recipe is only read on Windows.
+ Mac and Linux behavior does not change; their existing tests prove that.
+- **Migration and rollback:** Nothing migrates. A plugin rollback returns to the fallback. An engine installed
+ through W3 stays installed. W7's rollback removes the accounts (in its spec).
+- **Audience:** W7's guest limits are enforced by the OS account and the daemon's existing guest policy, never by
+ the app. W0's Buddy check is on the server.
+- **Identity:** W7 runs as the guest's own account, never the owner's. W1's Team writes go to the Team account's
+ files only.
+- **Failure:** Each path that fails says so: a blocked exe, a missing WebView2, a failed install, a refused engine.
+ None falls silently back to "not installed".
+- **Platforms:** Windows x64 tested on the PC. Arm through the runner in W5, and through CI builds elsewhere; **Arm
+ is otherwise not tested for real.** macOS and Linux keep their gates.
+
+## Risks
+
+- `webview_win_floating` is one author's plugin. W4's spike is what decides it.
+- W6 may be well past 200 errors once it compiles further.
+- W7's spike could double its size.
+- Vendors may have no Windows install for some engines, which leaves those refused, by name.
+
+## Left to the builder
+
+File layout inside each package, test names, and whether W3 needs two PRs.
+
+## Open items
+
+- **W0's merge:** the auto-mode classifier refused the merge as "Merge Without Review", because #2979 has no
+ reviewer. The PR also asks for the review that made the 10-29 ruling. The owner, or a reviewer, must merge it.
diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.md
index 0a7c4aee2..ef295a96c 100644
--- a/docs/swarm-github-app.md
+++ b/docs/swarm-github-app.md
@@ -166,8 +166,8 @@ A person's own agents, starts on a server without the app, and computers whose H
is too old to understand the request keep using the computer's own git and gh
configuration. The decision is recorded with the session, so a relaunch keeps it.
In a team account (a Mac's Harness Team account, or a computer after `harness team on`),
-every Swarm agent qualifies, because the owner's login is not there. Windows is not
-wired yet.
+every Swarm agent qualifies, because the owner's login is not there. Windows works the
+same way, through Git for Windows.
## Preparing the folder before the agent starts