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.

fix(swarm): trust contributed clones and repair existing worktrees (#1531)

0xken150b41b9187a67
diff --git a/cli/src/engines/kit/folderTrust.ts b/cli/src/engines/kit/folderTrust.ts
index 9235252d4..0b50e77f0 100644
--- a/cli/src/engines/kit/folderTrust.ts
+++ b/cli/src/engines/kit/folderTrust.ts
@@ -5,8 +5,11 @@
* Moved from lib/claudeTrust.ts, whose every write it reproduces (engines/launchPrep.golden.spec.ts).
*
* ⚠️ Never for a folder with content the person has not been asked about (a clone, their own repo, a worktree
- * of one): that answer is theirs. The callers decide (core/agents/create.ts, launches.ts). A worktree only
- * inherits the answer its source repo already has.
+ * of one): that answer is theirs. One consented exception is a Swarm's own project clones: clicking Add
+ * machine authorizes those checkouts and their Swarm agent worktrees (superTabs/cloneTrust.ts), including
+ * earlier contributions repaired after an update. It never authorizes the person's other repositories.
+ * The callers decide (core/agents/create.ts, launches.ts). A worktree only inherits the answer its source
+ * repo already has.
*
* Only ever ADDS trust, never removes anything, and does nothing when the engine has never run here (no
* file), when the file does not parse, or when it already says yes.
diff --git a/cli/src/superTabs/cloneTrust.spec.ts b/cli/src/superTabs/cloneTrust.spec.ts
new file mode 100644
index 000000000..d5dc9cb42
--- /dev/null
+++ b/cli/src/superTabs/cloneTrust.spec.ts
@@ -0,0 +1,402 @@
+import { execFileSync } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { lstat } from 'node:fs/promises'
+import { homedir, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import { folderTrust } from '../engines/launchPrep.js'
+import { launchEnvironment } from '../engines/kit/launchExecutable.js'
+import { readGitProject } from '../lib/gitProject.js'
+import { recordTrustIn } from '../engines/kit/folderTrust.js'
+import { prepareContribution } from './contribution.js'
+import { prepareSwarmProject } from './projectFolder.js'
+import { ContributedMachines } from './machines.js'
+
+// Never read the person's login profile: the fixture owns the engine locations.
+vi.mock('../engines/kit/launchExecutable.js', () => ({ launchEnvironment: vi.fn(async () => ({ ...process.env })) }))
+vi.mock('../lib/gitProject.js', async original => {
+ const real = await original<typeof import('../lib/gitProject.js')>()
+ return { ...real, readGitProject: vi.fn(real.readGitProject) }
+})
+vi.mock('../engines/kit/folderTrust.js', async original => {
+ const real = await original<typeof import('../engines/kit/folderTrust.js')>()
+ return { ...real, recordTrustIn: vi.fn(real.recordTrustIn) }
+})
+vi.mock('node:fs/promises', async original => {
+ const real = await original<typeof import('node:fs/promises')>()
+ return { ...real, lstat: vi.fn(real.lstat) }
+})
+let home = ''
+beforeEach(() => {
+ vi.clearAllMocks()
+ home = mkdtempSync(join(tmpdir(), 'swarm-clone-trust-'))
+ vi.stubEnv('HOME', home); vi.stubEnv('USERPROFILE', home)
+ vi.stubEnv('CLAUDE_CONFIG_DIR', join(home, 'claude')); vi.stubEnv('CODEX_HOME', join(home, 'codex'))
+ mkdirSync(process.env.CLAUDE_CONFIG_DIR!, { recursive: true }); mkdirSync(process.env.CODEX_HOME!, { recursive: true })
+ writeFileSync(join(process.env.CLAUDE_CONFIG_DIR!, '.claude.json'), JSON.stringify({ theme: 'dark', projects: {} }))
+ writeFileSync(join(process.env.CODEX_HOME!, 'config.toml'), 'model = "unchanged"\n')
+})
+afterEach(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) })
+function git(cwd: string, ...args: string[]) {
+ return execFileSync('git', ['-c', 'user.name=Fixture', '-c', '[email protected]', '-C', cwd, ...args], {
+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0' }, encoding: 'utf8',
+ }).trim()
+}
+function clone(path: string) {
+ mkdirSync(path, { recursive: true }); git(path, 'init', '-q', '-b', 'main'); git(path, 'commit', '-qm', 'fixture', '--allow-empty')
+ return path
+}
+function fixture(legacy = false) {
+ const core = fakeCore({ dataDir: join(home, 'data') })
+ const root = join(home, 'harnesses', 'swarms', 'tab'), oldRoot = join(core.dataDir, 'swarm-projects', 'tab'), cwd = legacy ? oldRoot : root
+ const row = { tabId: 'tab', machine: { machineId: core.daemon.machineId(), generation: 'grant', scope: 'swarm', cwd, engines: ['claude', 'codex'] },
+ projects: [{ id: 'project', repository: { machineId: 'another', repositoryUrl: 'https://github.com/example/project' }, conversationIds: ['work'] }], starts: [], harnessIds: [] }
+ const deps = { backend: vi.fn(async () => ({ state: { projects: row.projects, machines: [row.machine] } })),
+ open: vi.fn(async () => ({ request: vi.fn(async () => ({ engines: [{ engine: 'codex', installed: true, signedIn: true }] })), close: vi.fn() })),
+ prepare: vi.fn(async () => join(cwd, 'project')),
+ capacity: vi.fn(async () => ({ ok: true, resources: { projectDiskFreeBytes: 1, memoryTotalBytes: 8 * 1024 ** 3, memoryUsedBytes: 0 } })) }
+ return { core, root, oldRoot, cwd, row, deps }
+}
+function expectTrusted(path: string, trusted = true) {
+ for (const engine of ['claude', 'codex'] as const) expect(folderTrust(engine)!.trusts(path), engine + ': ' + path).toBe(trusted)
+}
+
+describe('consented Swarm clones', () => {
+ it('places new contributions in the visible Swarm root and preserves earlier roots', async () => {
+ const f = fixture()
+ f.deps.backend.mockResolvedValueOnce({ state: { projects: f.row.projects } } as never)
+ expect((await prepareContribution(f.core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)).cwd).toBe(f.root)
+ expect(existsSync(f.root)).toBe(true)
+ f.row.machine.cwd = f.oldRoot
+ expect((await prepareContribution(f.core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)).cwd).toBe(f.oldRoot)
+ })
+ it('adding or configuring trusts clones in both roots, never another repo or the parent', async () => {
+ const f = fixture(true), current = clone(join(f.root, 'project')), earlier = clone(join(f.oldRoot, 'earlier'))
+ const personal = clone(join(home, 'personal')), otherSwarm = clone(join(home, 'harnesses', 'swarms', 'other', 'project'))
+ symlinkSync(personal, join(f.oldRoot, 'linked-personal'), 'dir'); mkdirSync(join(f.oldRoot, 'not-a-clone'))
+ await prepareContribution(f.core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)
+ expectTrusted(current); expectTrusted(earlier)
+ for (const path of [personal, otherSwarm, f.root, f.oldRoot, join(f.oldRoot, 'not-a-clone')]) expectTrusted(path, false)
+ const claude = join(process.env.CLAUDE_CONFIG_DIR!, '.claude.json'), codex = join(process.env.CODEX_HOME!, 'config.toml')
+ const before = [readFileSync(claude, 'utf8'), readFileSync(codex, 'utf8')]
+ await prepareContribution(f.core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)
+ expect([readFileSync(claude, 'utf8'), readFileSync(codex, 'utf8')]).toEqual(before)
+ for (const engine of ['claude', 'codex'] as const) expect(folderTrust(engine)!.record(current)).toBe('already')
+ expect(JSON.parse(before[0]!).theme).toBe('dark'); expect(before[1]).toContain('model = "unchanged"')
+ expect(homedir()).toBe(home)
+ })
+ it('trusts the exact prepared clone before native worktree launch for both engines', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ await prepareSwarmProject(f.core, f.row, { request: { conversationId: 'work', cwd: source }, dispatched: false }, async () => source)
+ expectTrusted(source)
+ })
+ it('repairs an earlier contribution and its Swarm worktrees on a tick without pending starts', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), current = clone(join(f.root, 'project'))
+ const tree = join(home, 'harnesses', 'worktrees', 'project', 'worker'), unrelated = join(home, 'harnesses', 'worktrees', 'project', 'personal')
+ git(source, 'worktree', 'add', '-q', '-b', 'super-tab/worker', tree); git(source, 'worktree', 'add', '-q', '-b', 'personal', unrelated)
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const start = vi.fn(), close = vi.fn()
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close }), capabilities: f.deps.capacity, start, now: () => 1 } as never)
+ await machine.tick()
+ expectTrusted(source); expectTrusted(current); expectTrusted(tree); expectTrusted(unrelated, false)
+ expect(start).not.toHaveBeenCalled(); expect(close).toHaveBeenCalledOnce(); machine.stop()
+ })
+ it('repairs a renamed Swarm worktree in the agent profile while preserving unrelated worktrees', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ const tree = join(home, 'harnesses', 'worktrees', 'project', 'worker')
+ git(source, 'worktree', 'add', '-q', '-b', 'super-tab/worker', tree)
+ git(tree, 'branch', '-m', 'fix-renamed-by-session')
+ const profile = join(home, 'profile')
+ mkdirSync(profile); writeFileSync(join(profile, 'config.toml'), '')
+ Object.assign(f.row, { harnessIds: ['worker'] })
+ vi.mocked(f.core.agents.all).mockReturnValue([{ agentId: 'worker', engine: 'codex', cwd: tree, codexHome: profile }] as never)
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => 1 } as never)
+ await machine.tick()
+ expectTrusted(tree)
+ expect(folderTrust('codex', profile)!.trusts(source)).toBe(true)
+ expect(folderTrust('codex', profile)!.trusts(tree)).toBe(true)
+ machine.stop()
+ })
+ it('does not follow a Swarm root symlink into the owner repository', async () => {
+ const f = fixture(true), personal = clone(join(home, 'personal'))
+ mkdirSync(join(home, 'harnesses', 'swarms'), { recursive: true })
+ symlinkSync(home, f.root, 'dir')
+ mkdirSync(f.oldRoot, { recursive: true })
+ await prepareContribution(f.core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)
+ expectTrusted(personal, false)
+ })
+ it('an unreadable engine config does not starve the other engine or machine observation', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ const config = join(process.env.CODEX_HOME!, 'config.toml')
+ rmSync(config); mkdirSync(config)
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => 1 } as never)
+ await machine.tick()
+ expect(folderTrust('claude')!.trusts(source)).toBe(true)
+ expect(f.deps.capacity).toHaveBeenCalledOnce()
+ expect(backend.mock.calls.some(call => call[1] === 'POST')).toBe(true)
+ machine.stop()
+ })
+ it('records the authorized legacy spelling as well as its physical path for worktree inheritance', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ const alias = join(home, 'data-alias')
+ symlinkSync(f.core.dataDir, alias, 'dir')
+ const core = fakeCore({ dataDir: alias }), root = join(alias, 'swarm-projects', 'tab'), lexical = join(root, 'project')
+ f.row.machine.cwd = root
+ await prepareSwarmProject(core, f.row, { request: { conversationId: 'work', cwd: lexical }, dispatched: false }, async () => lexical)
+ expectTrusted(source); expectTrusted(lexical)
+ })
+ it('uses the native home when the login shell unsets an inherited CODEX_HOME', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ const nativeHome = join(home, 'native'), codexHome = join(nativeHome, '.codex')
+ mkdirSync(codexHome, { recursive: true }); writeFileSync(join(codexHome, 'config.toml'), '')
+ vi.mocked(launchEnvironment).mockResolvedValueOnce({ HOME: nativeHome })
+ await prepareSwarmProject(f.core, f.row, { request: { conversationId: 'work', cwd: source }, dispatched: false }, async () => source)
+ expect(folderTrust('codex', codexHome)!.trusts(source)).toBe(true)
+ expect(folderTrust('codex')!.trusts(source)).toBe(false)
+ })
+ it('publishes observations before repair and does no trust work on a second successful tick', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ await machine.tick()
+ expectTrusted(source)
+ const work = () => [vi.mocked(readGitProject).mock.calls.length, vi.mocked(launchEnvironment).mock.calls.length, vi.mocked(recordTrustIn).mock.calls.length]
+ const before = work()
+ const observation = backend.mock.calls.findIndex(call => call[1] === 'POST')
+ expect(backend.mock.invocationCallOrder[observation]).toBeLessThan(vi.mocked(readGitProject).mock.invocationCallOrder[0]!)
+ now += 16_000
+ await machine.tick()
+ expect(work()).toEqual(before)
+ expect(f.deps.capacity).toHaveBeenCalledTimes(2)
+ f.row.machine.generation = 'new-grant'
+ const added = clone(join(f.root, 'another-project'))
+ now += 16_000
+ await machine.tick()
+ expectTrusted(added)
+ expect(vi.mocked(readGitProject).mock.calls.length).toBeGreaterThan(before[0]!)
+ machine.stop()
+ })
+ it('retries only failed settings after migration without rediscovering clones or a shell', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), file = join(process.env.CODEX_HOME!, 'config.toml')
+ rmSync(file); mkdirSync(file)
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ await machine.tick()
+ const reads = vi.mocked(readGitProject).mock.calls.length, shells = vi.mocked(launchEnvironment).mock.calls.length
+ const claudeWrites = () => vi.mocked(recordTrustIn).mock.calls.filter(call => call[0].format === 'json').length
+ const before = claudeWrites()
+ rmSync(file, { recursive: true }); writeFileSync(file, '')
+ now += 16_000
+ await machine.tick()
+ expectTrusted(source)
+ expect(vi.mocked(readGitProject)).toHaveBeenCalledTimes(reads)
+ expect(vi.mocked(launchEnvironment)).toHaveBeenCalledTimes(shells)
+ expect(claudeWrites()).toBe(before)
+ machine.stop()
+ })
+ it('does not write a backend-selected Codex home that no local agent uses', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), home = join(process.env.HOME!, '.cargo')
+ mkdirSync(home)
+ const file = join(home, 'config.toml'), original = '[build]\ntarget = "unchanged"\n'
+ writeFileSync(file, original)
+ await prepareSwarmProject(f.core, f.row, { request: { conversationId: 'work', cwd: source, codexHome: home }, dispatched: false }, async () => source)
+ expect(readFileSync(file, 'utf8')).toBe(original)
+ expectTrusted(source)
+ })
+ it('accepts a selected Codex profile already used by a local Codex agent', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), profile = join(home, 'local-codex-profile')
+ mkdirSync(profile); writeFileSync(join(profile, 'config.toml'), '')
+ vi.mocked(f.core.agents.all).mockReturnValue([{ agentId: 'local', engine: 'codex', codexHome: profile }] as never)
+ await prepareSwarmProject(f.core, f.row, { request: { conversationId: 'work', cwd: source, codexHome: profile }, dispatched: false }, async () => source)
+ expect(folderTrust('codex', profile)!.trusts(source)).toBe(true)
+ })
+ it('retries failed discovery without rescanning another successfully discovered clone', async () => {
+ const f = fixture(true), failed = clone(join(f.oldRoot, 'project')), ready = clone(join(f.root, 'ready'))
+ const actual = await vi.importActual<typeof import('../lib/gitProject.js')>('../lib/gitProject.js')
+ let unavailable = true, now = 1
+ vi.mocked(readGitProject).mockImplementation(async (path, options) => path === failed && unavailable ? { error: 'GIT_UNAVAILABLE' } : actual.readGitProject(path, options))
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ try {
+ await machine.tick()
+ expectTrusted(ready); expectTrusted(failed, false)
+ const readyReads = vi.mocked(readGitProject).mock.calls.filter(call => call[0] === ready).length
+ unavailable = false; now += 16_000
+ await machine.tick()
+ expectTrusted(failed)
+ expect(vi.mocked(readGitProject).mock.calls.filter(call => call[0] === ready)).toHaveLength(readyReads)
+ } finally { vi.mocked(readGitProject).mockImplementation(actual.readGitProject); machine.stop() }
+ })
+ it('does not reuse a pending write authorization after the clone becomes an escaping symlink', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), personal = clone(join(home, 'personal'))
+ const claude = join(process.env.CLAUDE_CONFIG_DIR!, '.claude.json'), codex = join(process.env.CODEX_HOME!, 'config.toml')
+ writeFileSync(claude, 'invalid JSON'); rmSync(codex); mkdirSync(codex)
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ await machine.tick()
+ expect(folderTrust('claude')!.trusts(source)).toBe(false)
+ renameSync(source, join(home, 'old-clone')); symlinkSync(personal, source, 'dir')
+ writeFileSync(claude, '{}'); rmSync(codex, { recursive: true }); writeFileSync(codex, '')
+ now += 300_000
+ await machine.tick()
+ expectTrusted(source, false); expectTrusted(personal, false)
+ machine.stop()
+ })
+ it('backs off unavailable login shells while five-second polls still dispatch starts', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ Object.assign(f.row, { starts: [{ id: 'start', dispatched: true }] })
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const start = vi.fn(async () => ({ ok: false }))
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start, now: () => now } as never)
+ vi.mocked(launchEnvironment).mockResolvedValue(null)
+ try {
+ await machine.tick()
+ expect(start).toHaveBeenCalledTimes(1)
+ expect(launchEnvironment).toHaveBeenCalledTimes(1)
+ now = 5_001; await machine.tick()
+ expect(start).toHaveBeenCalledTimes(2)
+ expect(launchEnvironment).toHaveBeenCalledTimes(1)
+ // Failures wait 15, 30, 60, 120, 240 seconds, then at most five minutes.
+ for (const [at, calls] of [[15_001, 2], [40_001, 2], [45_001, 3], [100_001, 3],
+ [105_001, 4], [225_001, 5], [465_001, 6], [760_001, 6], [765_001, 7]]) {
+ now = at!; await machine.tick()
+ expect(launchEnvironment).toHaveBeenCalledTimes(calls!)
+ }
+ vi.mocked(launchEnvironment).mockResolvedValue({ ...process.env })
+ now = 1_065_001; await machine.tick()
+ expectTrusted(source)
+ } finally { vi.mocked(launchEnvironment).mockImplementation(async () => ({ ...process.env })); machine.stop() }
+ })
+ it('defers skipped configs without repeated trust path checks and repairs them on the slow recheck', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), codex = join(process.env.CODEX_HOME!, 'config.toml')
+ rmSync(codex)
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ try {
+ await machine.tick()
+ expect(existsSync(codex)).toBe(false)
+ const stats = vi.mocked(lstat).mock.calls.length, records = vi.mocked(recordTrustIn).mock.calls.length
+ now = 5_001; await machine.tick()
+ expect(lstat).toHaveBeenCalledTimes(stats)
+ expect(recordTrustIn).toHaveBeenCalledTimes(records)
+ expect(backend.mock.calls.filter(call => call[1] === 'POST')).toHaveLength(1)
+ writeFileSync(codex, '')
+ now = 300_001; await machine.tick()
+ expectTrusted(source)
+ } finally { machine.stop() }
+ })
+ it('repairs a newly registered Codex profile and worktree before the next observation is due', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ try {
+ await machine.tick()
+ const profile = join(home, 'later-profile'), tree = join(home, 'harnesses', 'worktrees', 'project', 'worker')
+ mkdirSync(profile); writeFileSync(join(profile, 'config.toml'), '')
+ git(source, 'worktree', 'add', '-qb', 'super-tab/later', tree)
+ Object.assign(f.row, { harnessIds: ['worker'] })
+ vi.mocked(f.core.agents.all).mockReturnValue([{ agentId: 'worker', engine: 'codex', cwd: tree, codexHome: profile }] as never)
+ now = 5_001; await machine.tick()
+ expect(folderTrust('codex', profile)!.trusts(source)).toBe(true)
+ expect(folderTrust('codex', profile)!.trusts(tree)).toBe(true)
+ expect(f.deps.capacity).toHaveBeenCalledTimes(1)
+ } finally { machine.stop() }
+ })
+ it.each([
+ { existing: false, failure: 'shell' }, { existing: true, failure: 'shell' },
+ { existing: false, failure: 'config' }, { existing: true, failure: 'config' },
+ ])('discovers a later clone after one-shot $failure failure (existing=$existing)', async ({ existing, failure }) => {
+ const f = fixture(true), earlier = existing ? clone(join(f.oldRoot, 'earlier')) : undefined
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ try {
+ await machine.tick()
+ const earlierReads = vi.mocked(readGitProject).mock.calls.filter(call => call[0] === earlier).length
+ const source = clone(join(f.oldRoot, 'project')), codex = join(process.env.CODEX_HOME!, 'config.toml')
+ if (failure === 'shell') vi.mocked(launchEnvironment).mockResolvedValueOnce(null)
+ else { rmSync(codex); mkdirSync(codex) }
+ await prepareSwarmProject(f.core, f.row, { request: { conversationId: 'work', cwd: source }, dispatched: false }, async () => source)
+ if (failure === 'config') { rmSync(codex, { recursive: true }); writeFileSync(codex, '') }
+ expect(folderTrust('codex')!.trusts(source)).toBe(false)
+ const readsAfterPreparation = vi.mocked(readGitProject).mock.calls.filter(call => call[0] === earlier).length
+ now = 5_001; await machine.tick()
+ expectTrusted(source)
+ // The one-shot scan may revisit it; the periodic pass must reuse successful Git discovery.
+ expect(vi.mocked(readGitProject).mock.calls.filter(call => call[0] === earlier)).toHaveLength(readsAfterPreparation)
+ if (existing) expect(earlierReads).toBe(1)
+ } finally { machine.stop() }
+ })
+ it('retries a clone directory first seen before git initialization completes', async () => {
+ const f = fixture(true), source = join(f.oldRoot, 'project')
+ mkdirSync(source, { recursive: true })
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ try {
+ await machine.tick()
+ clone(source)
+ now = 15_001; await machine.tick()
+ expectTrusted(source)
+ } finally { machine.stop() }
+ })
+ it('dispatches starts and backs off even when repair throws', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project'))
+ Object.assign(f.row, { starts: [{ id: 'start', dispatched: true }] })
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const start = vi.fn(async () => ({ ok: false }))
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start, now: () => now } as never)
+ vi.mocked(launchEnvironment).mockRejectedValueOnce(new Error('temporary repair failure'))
+ try {
+ await machine.tick()
+ expect(start).toHaveBeenCalledTimes(1)
+ now = 5_001; await machine.tick()
+ expect(start).toHaveBeenCalledTimes(2)
+ expect(launchEnvironment).toHaveBeenCalledTimes(1)
+ now = 15_001; await machine.tick()
+ expectTrusted(source)
+ } finally { machine.stop() }
+ })
+ it('settles an existing untrusted Codex entry without rewriting or retrying it', async () => {
+ const f = fixture(true), source = clone(join(f.oldRoot, 'project')), codex = join(process.env.CODEX_HOME!, 'config.toml')
+ const original = `[projects.${JSON.stringify(source)}]\ntrust_level = "untrusted"\n`
+ writeFileSync(codex, original)
+ let now = 1
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string) => path.endsWith('/pools') ? [f.row] : {})
+ const machine = new ContributedMachines(f.core, f.core.daemon.machineId(), { backend,
+ open: async () => ({ request: async () => ({}), close: vi.fn() }), capabilities: f.deps.capacity, start: vi.fn(), now: () => now } as never)
+ try {
+ await machine.tick()
+ expect(folderTrust('codex')!.trusts(source)).toBe(false)
+ const stats = vi.mocked(lstat).mock.calls.length, records = vi.mocked(recordTrustIn).mock.calls.length
+ now = 300_001; await machine.tick()
+ expect(lstat).toHaveBeenCalledTimes(stats)
+ expect(recordTrustIn).toHaveBeenCalledTimes(records)
+ expect(readFileSync(codex, 'utf8')).toBe(original)
+ } finally { machine.stop() }
+ })
+
+})
diff --git a/cli/src/superTabs/cloneTrust.ts b/cli/src/superTabs/cloneTrust.ts
new file mode 100644
index 000000000..e5f6156e8
--- /dev/null
+++ b/cli/src/superTabs/cloneTrust.ts
@@ -0,0 +1,255 @@
+import { lstat, readdir, realpath } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { isAbsolute, join, relative, resolve, sep } from 'node:path'
+import type { CoreApi } from '../core/api.js'
+import { folderTrust } from '../engines/launchPrep.js'
+import { launchEnvironment } from '../engines/kit/launchExecutable.js'
+import { readGitProject } from '../lib/gitProject.js'
+import { identifier, object } from './wire.js'
+
+type Json = Record<string, unknown>
+interface PathProof { physical: string; identity: string; git: string }
+interface ClonePaths { source: string; paths: string[]; proofs: Map<string, PathProof> }
+interface DiscoverySnapshot {
+ roots: Map<string, Array<{ source: string; lexical: string }>>
+ clones: Map<string, ClonePaths | null>
+}
+
+const identity = (info: { dev: number; ino: number }) => `${info.dev}:${info.ino}`
+async function pathProof(physical: string): Promise<PathProof> {
+ const folder = await lstat(physical), git = await lstat(join(physical, '.git'))
+ if (!folder.isDirectory() || (!git.isDirectory() && !git.isFile())) throw new Error('Workspace changed during trust repair')
+ // A worktree's .git file is its backlink. Keep its version too; ordinary edits within a directory
+ // do not change that directory's identity and must not invalidate a pending settings retry.
+ return { physical, identity: identity(folder), git: git.isDirectory() ? identity(git)
+ : `${identity(git)}:${git.size}:${git.mtimeMs}:${git.ctimeMs}` }
+}
+async function stillMatches(cwd: string, proof: PathProof): Promise<boolean> {
+ try {
+ if (await realpath(cwd) !== proof.physical) return false
+ const current = await pathProof(proof.physical)
+ return current.identity === proof.identity && current.git === proof.git
+ } catch { return false }
+}
+const within = (root: string, path: string): boolean => {
+ const rel = relative(root, path)
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
+}
+
+/** New contributions are visible beside worktrees; existing Git common directories must never move. */
+export const swarmCloneRoots = (dataDir: string, tabId: string): string[] => [
+ join(homedir(), 'harnesses', 'swarms', tabId), join(dataDir, 'swarm-projects', tabId),
+]
+
+export function swarmCloneRoot(dataDir: string, tabId: string, cwd: unknown): string | undefined {
+ return typeof cwd === 'string' && isAbsolute(cwd)
+ ? swarmCloneRoots(dataDir, tabId).find(root => resolve(root) === resolve(cwd)) : undefined
+}
+
+/** Add machine consents to these clones, not arbitrary paths in backend metadata. Resolve from an
+ * existing trusted base so a symlink at the tab, project or worktree cannot extend that consent. */
+async function physicalRoot(base: string, ...parts: string[]): Promise<string | null> {
+ try {
+ const expected = join(await realpath(base), ...parts)
+ return await realpath(join(base, ...parts)) === expected ? expected : null
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ }
+}
+
+/** Folder names are cheap to reread; a clone can arrive after a completely successful or empty pass.
+ * Keep the Git/worktree results separate so steady polling never repeats that expensive discovery. */
+async function cloneFolders(core: CoreApi, tabId: string): Promise<DiscoverySnapshot['roots']> {
+ const roots: DiscoverySnapshot['roots'] = new Map()
+ for (const [index, lexicalRoot] of swarmCloneRoots(core.dataDir, tabId).entries()) {
+ try {
+ const root = index === 0 ? await physicalRoot(homedir(), 'harnesses', 'swarms', tabId)
+ : await physicalRoot(core.dataDir, 'swarm-projects', tabId)
+ const entries = root ? (await readdir(root, { withFileTypes: true }))
+ .filter(entry => entry.isDirectory() && identifier(entry.name))
+ .map(entry => ({ source: join(root, entry.name), lexical: join(lexicalRoot, entry.name) }))
+ .sort((a, b) => a.source.localeCompare(b.source)) : []
+ roots.set(lexicalRoot, entries)
+ } catch { /* A missing reading stays incomplete so discovery retries after backoff. */ }
+ }
+ return roots
+}
+
+async function discoverClones(core: CoreApi, row: Json, tabId: string, snapshot: DiscoverySnapshot): Promise<{ clones: ClonePaths[]; complete: boolean }> {
+ const clones: ClonePaths[] = []
+ let complete = snapshot.roots.size === swarmCloneRoots(core.dataDir, tabId).length
+ const ids = new Set(Array.isArray(row.harnessIds) ? row.harnessIds.filter(identifier) : [])
+ const agents = core.agents.all().filter(agent => ids.has(agent.agentId))
+ const agentFolders = await Promise.all(agents.map(agent => agent.cwd ? realpath(agent.cwd).catch(() => null) : null))
+ let worktrees: string | null
+ try { worktrees = await physicalRoot(homedir(), 'harnesses', 'worktrees') }
+ catch { return { clones, complete: false } }
+ for (const [lexicalRoot, entries] of snapshot.roots) {
+ for (const { source, lexical } of entries) {
+ if (snapshot.clones.has(source)) {
+ const known = snapshot.clones.get(source)
+ if (known) clones.push(known)
+ continue
+ }
+ try {
+ if (await realpath(source) !== source) throw new Error('Clone path changed')
+ const git = await lstat(join(source, '.git')).catch(error => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ })
+ // A clone owns its .git directory; a link or a worktree is not another consented clone.
+ if (!git) { complete = false; continue } // A clone may still be initializing its .git directory.
+ if (!git.isDirectory()) { snapshot.clones.set(source, null); continue }
+ const project = await readGitProject(source, { knownRoots: [lexicalRoot] })
+ if ('error' in project) throw new Error('Clone discovery unavailable')
+ if (!('root' in project) || resolve(project.root) !== source || 'mainFolder' in project) {
+ snapshot.clones.set(source, null); continue
+ }
+ // Core checks the stored source spelling. Keep an alias only with its verified physical target.
+ const targets = new Map([[source, source], [lexical, source]])
+ for (const branch of project.branches) {
+ if (!worktrees || !branch.worktree) continue
+ const tree = await realpath(branch.worktree).catch(error => {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ })
+ if (!tree || !within(worktrees, tree) || tree === worktrees) continue
+ // A renamed branch is still this Swarm's workspace when its local registry row says so.
+ const belongs = branch.ref.startsWith('refs/heads/super-tab/') || agentFolders.some(cwd => cwd && within(tree, cwd))
+ if (!belongs) continue
+ const linked = await readGitProject(tree)
+ if ('error' in linked) throw new Error('Worktree discovery unavailable')
+ if ('mainFolder' in linked && await realpath(linked.mainFolder) === source && resolve(linked.root) === tree) {
+ targets.set(tree, tree)
+ targets.set(join(homedir(), 'harnesses', 'worktrees', relative(worktrees, tree)), tree)
+ }
+ }
+ const proofs = new Map<string, PathProof>()
+ for (const [cwd, physical] of targets) proofs.set(cwd, await pathProof(physical))
+ const found = { source, paths: [...targets.keys()], proofs }
+ snapshot.clones.set(source, found)
+ clones.push(found)
+ } catch { complete = false /* Only this failed clone is rediscovered on the next tick. */ }
+ }
+ }
+ return { clones, complete }
+}
+
+/** No durable marker: a service restart or a new contribution generation retries migration. */
+interface RepairSnapshot {
+ discovery?: DiscoverySnapshot
+ environment?: NodeJS.ProcessEnv
+ recorded: Set<string>
+ complete?: boolean
+ slowRetry?: boolean
+}
+
+/** The host owns this cache. A steady pool does no shell/Git/config work after successful repair. */
+export function createSwarmCloneTrustRepair(core: CoreApi, now: () => number = Date.now): (row: Json) => Promise<void> {
+ const repairs = new Map<string, { generation: unknown; homes: string; folders: string; snapshot: RepairSnapshot; failures: number; next: number }>()
+ return async row => {
+ if (!identifier(row.tabId)) return
+ const pool = object(row.machine)
+ if (pool.scope !== 'swarm' || !swarmCloneRoot(core.dataDir, row.tabId, pool.cwd)) return
+ const generation = pool.generation
+ const roots = await cloneFolders(core, row.tabId)
+ const folders = JSON.stringify([...roots])
+ const homes = JSON.stringify([...new Set(core.agents.all().filter(agent => agent.engine === 'codex' && agent.codexHome)
+ .map(agent => resolve(agent.codexHome!)))].sort())
+ let repair = repairs.get(row.tabId)
+ if (!repair || repair.generation !== generation) {
+ repair = { generation, homes, folders, snapshot: { recorded: new Set() }, failures: 0, next: 0 }
+ repairs.set(row.tabId, repair)
+ } else if (repair.homes !== homes) {
+ // A newly registered profile may already have a worktree. Discover it even without a new grant.
+ repair.homes = homes
+ repair.snapshot.discovery = undefined
+ repair.snapshot.complete = false
+ repair.failures = 0
+ repair.next = 0
+ }
+ if (repair.folders !== folders) {
+ repair.folders = folders
+ repair.snapshot.complete = false
+ repair.failures = 0
+ repair.next = 0
+ }
+ const discovery = repair.snapshot.discovery ??= { roots, clones: new Map() }
+ discovery.roots = roots
+ if (repair.snapshot.complete || now() < repair.next) return
+ try { await repairSwarmCloneTrust(core, row, undefined, repair.snapshot) }
+ finally {
+ if (!repair.snapshot.complete) {
+ // Five-second start pickup must not run a broken login shell or unavailable config each pass.
+ // Engines that have never run have no config yet; look again slowly without creating one.
+ const delay = repair.snapshot.slowRetry ? 300_000 : Math.min(15_000 * 2 ** repair.failures, 300_000)
+ repair.failures = Math.min(repair.failures + 1, 5)
+ repair.next = now() + delay
+ }
+ }
+ }
+}
+
+/** Explicit setup/project preparation gets a fresh scan; periodic migration keeps its successful paths
+ * in the host's snapshot. Missing or locked settings retry without another Git scan or login shell. */
+export async function repairSwarmCloneTrust(core: CoreApi, row: Json, profile?: string,
+ snapshot: RepairSnapshot = { recorded: new Set() }): Promise<void> {
+ const pool = object(row.machine)
+ if (pool.scope !== 'swarm' || !identifier(row.tabId) || !swarmCloneRoot(core.dataDir, row.tabId, pool.cwd) || snapshot.complete) return
+ snapshot.slowRetry = false
+ const discovery = snapshot.discovery ??= { roots: await cloneFolders(core, row.tabId), clones: new Map() }
+ const { clones, complete: discovered } = await discoverClones(core, row, row.tabId, discovery)
+ if (!clones.length) { snapshot.complete = discovered; return }
+ const local = core.agents.all()
+ const ids = new Set(Array.isArray(row.harnessIds) ? row.harnessIds.filter(identifier) : [])
+ const agents = local.filter(agent => ids.has(agent.agentId))
+ // A backend-selected path is not authority to edit a local config file. Only a Codex profile a
+ // locally registered Codex agent already uses can select another config.toml for this consent.
+ const known = profile && isAbsolute(profile) ? local.find(agent => agent.engine === 'codex'
+ && agent.codexHome && resolve(agent.codexHome) === resolve(profile)) : undefined
+ let complete = discovered
+ // The service has a separate shell cache from core. Use the same captured locations as native launch.
+ const environment = snapshot.environment ?? await launchEnvironment()
+ if (!environment) return
+ snapshot.environment = environment
+ // Native launch treats an unset CODEX_HOME as HOME/.codex, not the daemon's cached default.
+ const codexHome = environment.CODEX_HOME || join(environment.HOME || homedir(), '.codex')
+ const record = async (engine: 'claude' | 'codex', clone: ClonePaths, profile?: string) => {
+ const home = engine === 'codex' ? profile || codexHome : undefined
+ if (home && !isAbsolute(home)) { complete = false; return }
+ const trust = folderTrust(engine, home, environment)
+ for (const cwd of clone.paths) {
+ const key = JSON.stringify([engine, home, cwd])
+ if (snapshot.recorded.has(key)) continue
+ // Failed settings retry against the original physical identity, never an alias that now escapes.
+ if (!await stillMatches(clone.source, clone.proofs.get(clone.source)!) || !await stillMatches(cwd, clone.proofs.get(cwd)!)) {
+ snapshot.discovery?.clones.delete(clone.source)
+ complete = false; continue
+ }
+ try {
+ const result = trust?.record(cwd)
+ if (result === 'skipped') snapshot.slowRetry = true
+ // Codex also returns already for an explicit refusal. Keep that answer and stop retrying it.
+ if (result === 'trusted' || result === 'already') snapshot.recorded.add(key)
+ else complete = false
+ } catch { complete = false /* Retry only this setting; another engine and the pool still proceed. */ }
+ }
+ }
+ for (const clone of clones) {
+ const { paths } = clone
+ for (const engine of ['claude', 'codex'] as const) await record(engine, clone)
+ // A selected Codex profile reads its own config; it needs the source answer before core prepares
+ // a new worktree. Existing agents' profiles also repair automatically, without a Configure action.
+ const profiles = new Set(known?.codexHome ? [known.codexHome] : [])
+ for (const agent of agents) {
+ if (agent.engine !== 'codex' || !agent.codexHome || !agent.cwd) continue
+ const cwd = await realpath(agent.cwd).catch(() => null)
+ if (cwd && paths.some(path => within(path, cwd))) profiles.add(agent.codexHome)
+ }
+ for (const codexHome of profiles) {
+ await record('codex', clone, codexHome)
+ }
+ }
+ snapshot.complete = complete
+}
diff --git a/cli/src/superTabs/contribution.spec.ts b/cli/src/superTabs/contribution.spec.ts
index be3303397..6028b50b8 100644
--- a/cli/src/superTabs/contribution.spec.ts
+++ b/cli/src/superTabs/contribution.spec.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { ContributionPreparations, prepareContribution } from './contribution.js'
import { mkdtemp, rm, stat } from 'node:fs/promises'
-import { tmpdir } from 'node:os'
+import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
const GiB = 1024 ** 3
@@ -33,12 +33,15 @@ describe('one-field machine preparation', () => {
delete f.state.project
const core = fakeCore({ dataDir })
const result = await prepareContribution(core, { tabId: 'tab', scope: 'swarm' }, f.deps as never)
- const cwd = join(dataDir, 'swarm-projects', 'tab')
+ const cwd = join(homedir(), 'harnesses', 'swarms', 'tab')
expect(result).toMatchObject({ scope: 'swarm', cwd, engines: ['claude', 'pi'] })
expect((await stat(cwd)).isDirectory()).toBe(true)
expect(f.deps.prepare).not.toHaveBeenCalled()
expect(f.deps.capacity).toHaveBeenCalledWith({ cwd, tools: ['git'], devices: [] })
- } finally { await rm(dataDir, { recursive: true, force: true }) }
+ } finally {
+ await rm(join(homedir(), 'harnesses', 'swarms', 'tab'), { recursive: true, force: true })
+ await rm(dataDir, { recursive: true, force: true })
+ }
})
it('uses the lead project on its host and probes all engines without inventing authentication', async () => {
const f = fixture()
diff --git a/cli/src/superTabs/contribution.ts b/cli/src/superTabs/contribution.ts
index 50ec514e2..c193530a8 100644
--- a/cli/src/superTabs/contribution.ts
+++ b/cli/src/superTabs/contribution.ts
@@ -4,7 +4,7 @@ import { parseProjectFolder, prepareProjectFolder } from '../lib/projectFolder.j
import { readCapabilities, START_REQUIREMENTS } from './capacity.js'
import { backend, identifier, object } from './host.js'
import { mkdir } from 'node:fs/promises'
-import { join } from 'node:path'
+import { repairSwarmCloneTrust, swarmCloneRoot, swarmCloneRoots } from './cloneTrust.js'
type Json = Record<string, unknown>
@@ -19,8 +19,11 @@ export async function prepareContribution(core: CoreApi, input: Json, deps = {
const machineId = core.daemon.machineId()
const existing = (Array.isArray(state.machines) ? state.machines.map(object) : []).find(m => m.machineId === machineId)
const swarm = input.scope === 'swarm' || Array.isArray(state.projects)
- let cwd = swarm ? join(core.dataDir, 'swarm-projects', input.tabId) : existing?.cwd
- if (swarm) await mkdir(cwd as string, { recursive: true })
+ let cwd = swarm ? swarmCloneRoot(core.dataDir, input.tabId, existing?.cwd) ?? swarmCloneRoots(core.dataDir, input.tabId)[0] : existing?.cwd
+ if (swarm) {
+ await mkdir(cwd as string, { recursive: true })
+ await repairSwarmCloneTrust(core, { tabId: input.tabId, machine: { scope: 'swarm', cwd } })
+ }
if (typeof cwd !== 'string') {
if (project.machineId === machineId && typeof project.cwd === 'string') cwd = project.cwd
else {
diff --git a/cli/src/superTabs/contribution.windows.spec.ts b/cli/src/superTabs/contribution.windows.spec.ts
index d89d80a23..49e8f1b0c 100644
--- a/cli/src/superTabs/contribution.windows.spec.ts
+++ b/cli/src/superTabs/contribution.windows.spec.ts
@@ -1,7 +1,8 @@
-// What Add machine sends from a Windows daemon: node:path is win32's, as it is there, so the swarm workspace is a
-// drive path (C:\…) that the backend accepts for machine.contribute.cwd.
+// What Add machine sends from a Windows daemon: both node:path and the home folder are Windows-shaped,
+// so new and earlier Swarm workspace paths remain drive paths the backend accepts for machine.contribute.cwd.
import * as nodePath from 'node:path'
-import { describe, expect, it, vi } from 'vitest'
+import { mkdir } from 'node:fs/promises'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { prepareContribution } from './contribution.js'
@@ -9,16 +10,34 @@ vi.mock('node:path', async (original) => {
const real = await original<typeof nodePath>()
return { ...real, ...real.win32, default: real.win32, win32: real.win32, posix: real.posix }
})
+vi.mock('node:os', async (original) => ({ ...await original<typeof import('node:os')>(), homedir: () => 'C:\\Users\\dev' }))
vi.mock('node:fs/promises', async (original) => ({ ...await original<object>(), mkdir: vi.fn(async () => undefined) }))
+beforeEach(() => vi.clearAllMocks())
+
+function fixture(existing?: string) {
+ const core = fakeCore({ dataDir: 'C:\\Users\\dev\\.harness\\cli\\data' })
+ const request = vi.fn(async () => ({ engines: [{ engine: 'claude', installed: true, signedIn: true }] }))
+ const close = vi.fn()
+ const machines = existing ? [{ machineId: core.daemon.machineId(), cwd: existing }] : []
+ const deps = { backend: vi.fn(async () => ({ state: { machines } })), open: vi.fn(async () => ({ request, close })), prepare: vi.fn(),
+ capacity: vi.fn(async () => ({ ok: true, resources: { memoryTotalBytes: 8 * 1024 ** 3, memoryUsedBytes: 0, projectDiskFreeBytes: 1e11 } })) }
+ return { core, deps, close }
+}
describe('contributing a Windows machine to a swarm', () => {
- it('offers the swarm workspace as a drive path under the daemon data folder', async () => {
- const core = fakeCore({ dataDir: 'C:\\Users\\dev\\.harness\\cli\\data' })
- const request = vi.fn(async () => ({ engines: [{ engine: 'claude', installed: true, signedIn: true }] }))
- const deps = { backend: vi.fn(async () => ({ state: {} })), open: vi.fn(async () => ({ request, close: vi.fn() })), prepare: vi.fn(),
- capacity: vi.fn(async () => ({ ok: true, resources: { memoryTotalBytes: 8 * 1024 ** 3, memoryUsedBytes: 0, projectDiskFreeBytes: 1e11 } })) }
+ it.each([
+ { name: 'offers a drive path under the visible Swarm root for a new contribution', existing: undefined,
+ cwd: 'C:\\Users\\dev\\harnesses\\swarms\\tab' },
+ { name: 'keeps an earlier contribution drive path under the daemon data folder',
+ existing: 'C:\\Users\\dev\\.harness\\cli\\data\\swarm-projects\\tab',
+ cwd: 'C:\\Users\\dev\\.harness\\cli\\data\\swarm-projects\\tab' },
+ ])('$name', async ({ existing, cwd }) => {
+ const { core, deps, close } = fixture(existing)
const result = await prepareContribution(core, { tabId: 'tab', scope: 'swarm' }, deps as never)
- expect(result).toMatchObject({ scope: 'swarm', cwd: 'C:\\Users\\dev\\.harness\\cli\\data\\swarm-projects\\tab' })
+ expect(result).toEqual({ ok: true, state: 'ready', scope: 'swarm', cwd, engines: ['claude'], maxAgents: 4 })
+ expect(mkdir).toHaveBeenCalledExactlyOnceWith(cwd, { recursive: true })
+ expect(deps.capacity).toHaveBeenCalledExactlyOnceWith({ cwd, tools: ['git'], devices: [] })
expect(deps.prepare).not.toHaveBeenCalled()
+ expect(close).toHaveBeenCalledOnce()
})
})
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 6abeea4b0..946071831 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -5,6 +5,7 @@ import { identifier, object } from './wire.js'
import { readCapabilities, quotaOf } from './capacity.js'
import { startAgent, type ScopedRequest } from './start.js'
import { prepareSwarmProject } from './projectFolder.js'
+import { createSwarmCloneTrustRepair } from './cloneTrust.js'
const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : null
const list = (v: unknown) => Array.isArray(v) ? v.map(object) : []
@@ -26,6 +27,7 @@ export class ContributedMachines {
/** A pass or one of its publishes failed: the next one waits a whole beat, as every pass once did. */
private failed = false
private readonly cursors = new Map<string, number>()
+ private repairTrust?: ReturnType<typeof createSwarmCloneTrustRepair>
/** Per tab, when its observation was last sent and what it said that matters to a reader: the harnesses
* running and stopped, whether new work is paused, and which starts are waiting. A change in any of them is
* sent at once; otherwise the heartbeat keeps the reading fresh. */
@@ -94,6 +96,9 @@ export class ContributedMachines {
this.published.set(String(row.tabId), { at: began, signature })
} catch (error) { this.failed = true; throw error }
}
+ this.repairTrust ??= createSwarmCloneTrustRepair(this.core, this.deps.now)
+ try { await this.repairTrust(row) }
+ catch { /* Trust migration cannot prevent this pass from picking up pending starts. */ }
// Two launches per pass bounds expensive native work. Pending starts
// keep their original receipt across network failures and host restarts.
const cursor = this.cursors.get(String(row.tabId)) ?? 0
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
index bf4ced6d3..b56fd6a73 100644
--- a/cli/src/superTabs/projectFolder.ts
+++ b/cli/src/superTabs/projectFolder.ts
@@ -2,6 +2,7 @@ import { isAbsolute, join, resolve } from 'node:path'
import type { CoreApi } from '../core/api.js'
import { otherGitHubTransport, parseProjectFolder, prepareProjectFolder, ProjectFolderError, RepositoryAccessError } from '../lib/projectFolder.js'
import { identifier, object } from './wire.js'
+import { repairSwarmCloneTrust, swarmCloneRoot } from './cloneTrust.js'
type Json = Record<string, unknown>
@@ -22,8 +23,8 @@ export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json,
.find(p => Array.isArray(p.conversationIds) && p.conversationIds.includes(request.conversationId))
if (!project || !identifier(project.id) || !identifier(row.tabId)) throw new Error('This start has no authorized project.')
const repository = object(project.repository)
- const expectedRoot = join(core.dataDir, 'swarm-projects', row.tabId)
- if (typeof pool.cwd !== 'string' || resolve(pool.cwd) !== resolve(expectedRoot)) throw new Error('Add this machine again to authorize its swarm workspace.')
+ const expectedRoot = swarmCloneRoot(core.dataDir, row.tabId, pool.cwd)
+ if (!expectedRoot) throw new Error('Add this machine again to authorize its swarm workspace.')
if (repository.machineId === core.daemon.machineId() && sameFolder(request.cwd, repository.cwd)) return
const expected = join(expectedRoot, project.id)
if (!sameFolder(request.cwd, expected)) throw new Error('The requested folder is outside this project.')
@@ -45,4 +46,5 @@ export async function prepareSwarmProject(core: CoreApi, row: Json, start: Json,
}
}
if (cwd !== expected) throw new Error('The prepared checkout does not match the authorized project.')
+ await repairSwarmCloneTrust(core, row, typeof request.codexHome === 'string' ? request.codexHome : undefined)
}
diff --git a/cli/src/superTabs/projectFolder.windows.spec.ts b/cli/src/superTabs/projectFolder.windows.spec.ts
index 6ddf580f4..9ea8415a2 100644
--- a/cli/src/superTabs/projectFolder.windows.spec.ts
+++ b/cli/src/superTabs/projectFolder.windows.spec.ts
@@ -10,6 +10,7 @@ vi.mock('node:path', async (original) => {
const real = await original<typeof nodePath>()
return { ...real, ...real.win32, default: real.win32, win32: real.win32, posix: real.posix }
})
+vi.mock('node:os', async (original) => ({ ...await original<typeof import('node:os')>(), homedir: () => 'C:\\Users\\dev' }))
function fixture() {
const core = fakeCore({ dataDir: 'C:\\Users\\dev\\.harness\\cli\\data' })
@@ -30,6 +31,14 @@ describe('per-project checkouts on a contributed Windows swarm machine', () => {
source: 'remote', repositoryUrl: 'https://github.com/example/project.git', name: 'project-a',
}, { root: f.root })
})
+ it('accepts the visible Swarm root with mixed Windows separators', async () => {
+ const f = fixture(), root = 'C:\\Users\\dev\\harnesses\\swarms\\tab'
+ f.row.machine.cwd = root
+ f.start.request.cwd = `${root}/project-a`
+ f.prepare.mockResolvedValueOnce(`${root}\\project-a`)
+ await f.run()
+ expect(f.prepare).toHaveBeenCalledWith(expect.anything(), { root })
+ })
it('accepts a repository already on this host however its separators are written', async () => {
const f = fixture()
f.repository.machineId = f.core.daemon.machineId()
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 8a25af8a3..1ae021b15 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -531,17 +531,22 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
style: DesktopChrome.text(),
),
const SizedBox(height: 16),
- if (own.isNotEmpty)
+ if (own.isNotEmpty) ...[
Text(
'Let the product manager run agents here using this machine’s signed-in accounts.',
style: DesktopChrome.text(),
),
- if (own.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
'Agents the Swarm starts on this machine run without asking for permission.',
style: DesktopChrome.text(),
),
+ const SizedBox(height: 12),
+ Text(
+ 'Harness clones each project into ~/harnesses/swarms and lets '
+ "the Swarm's agents work in it.",
+ style: DesktopChrome.text(),
+ ),
] else ...[
Text(
'To add another computer, install Harness on it and sign in with '
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index d780a9736..f3fa84124 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -1357,6 +1357,16 @@ void main() {
);
expect(find.byType(Checkbox), findsNothing);
expect(find.text('Choose project folder'), findsNothing);
+ expect(
+ find.descendant(
+ of: find.byType(AlertDialog),
+ matching: find.text(
+ 'Harness clones each project into ~/harnesses/swarms and lets '
+ "the Swarm's agents work in it.",
+ ),
+ ),
+ findsOneWidget,
+ );
await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
diff --git a/docs/plans/2026-10-22-swarm-clone-trust.md b/docs/plans/2026-10-22-swarm-clone-trust.md
new file mode 100644
index 000000000..e895793c7
--- /dev/null
+++ b/docs/plans/2026-10-22-swarm-clone-trust.md
@@ -0,0 +1,91 @@
+# Swarm clone trust
+
+## Approved brief
+
+GOAL: a new Codex or Claude Code agent started by a Swarm on a contributed machine never stops at the engine's "Do you trust this directory?" screen. On 2026-10-22 two Codex agents on MacBookPro2021 sat on that screen and never got the Lead's work; only the machine owner could answer.
+
+WHY: contributing a machine clones the project into the Harness data folder (cli/src/superTabs/contribution.ts:22, `join(core.dataDir, 'swarm-projects', tabId)`; projectFolder.ts:25), but nothing records engine trust for that clone. Trust is recorded only for folders Harness made empty (cli/src/engines/kit/folderTrust.ts, callers core/agents/create.ts:231/290, launches.ts), and its header forbids it for a clone "the person has not been asked about". Owner decision: clicking Add machine IS that answer for the Swarm's clone.
+
+CHANGES:
+1. When a machine is added or configured for a Swarm (prepareContribution), record trust for the Swarm's project clone(s) for Claude Code and Codex with the existing folderTrust/recordTrustIn (engine trust contracts, atomic write through symlinks, only ever adds). Also record it once for clones that already exist from earlier contributions (at the next host tick or contribution read). Only the Swarm's own clone folders, never any other folder of the owner. Update the folderTrust.ts header to name this one consented exception and why.
+2. Make sure the agents' worktrees made from that clone are trusted too (check how Codex/Claude resolve trust for a git worktree; if a worktree does not inherit, record trust for the worktree folder the Swarm start creates, same rule).
+3. New contributions clone into ~/harnesses/swarms/<tabId>/<projectId> (beside ~/harnesses/worktrees/, where owners already look) instead of the hidden data folder. Machines contributed before keep their existing clone path (moving it would break worktrees that use it); projectFolder.ts expectations must accept both roots.
+4. Add machine dialog (desktop/lib/super_tabs/machines.dart) says plainly: "Harness clones each project into ~/harnesses/swarms and lets the Swarm's agents work in it."
+
+NOT NOW: Harness answering engine screens on its own; a separate change will make the Swarm chat name the machine owner when an agent is blocked by an on-screen question.
+
+CONSTRAINTS: never trust a folder outside the Swarm clone roots; never remove trust; Windows paths work (projectFolder.windows.spec.ts); old contributions untouched except the added trust. No new dependencies.
+
+OWNS: cli/src/superTabs/contribution.ts, cli/src/superTabs/projectFolder.ts, cli/src/engines/kit/folderTrust.ts (header + any small export needed), the Swarm start's worktree trust if needed (cli/src/superTabs/start.ts), desktop/lib/super_tabs/machines.dart (dialog copy).
+
+OWNER CLARIFICATION (2026-10-22): "machines are already added; Harness must fix access to ~/harnesses/swarms by itself". So machines contributed before this change get fixed automatically with no owner action: on the machine's next Swarm host tick after updating, record Claude and Codex trust for every existing Swarm clone it has (old data-folder path) and for the clones under ~/harnesses/swarms, and their agent worktrees. Re-Add or Configure must not be required. Existing clones still stay where they are.
+
+Repo: github.com/autonomous-ai/openharness, branch from current origin/main. Read AGENTS.md, cli/AGENTS.md, docs/naming-system.md. Push a branch and open a DRAFT PR; do not mark ready, merge or release. Put this brief as docs/plans/2026-10-22-swarm-clone-trust.md in the PR. Tests never touch port 18473, ~/.harness, ~/.claude, ~/.codex, ~/harnesses or the real tmux (use a temp HOME). CLI on Node 24. Run and record in the PR: cli npm run typecheck, npm run test:super-tabs, npm run test:core if core files change, the folderTrust/launchPrep golden specs, projectFolder specs incl. windows; desktop flutter analyze + affected tests. Comments say why; no dead code.
+
+Acceptance checks:
+- CLI tests with a temp HOME: adding/configuring a machine records Claude and Codex trust for exactly the Swarm clone (and an earlier clone), nothing else; repeated runs say already
+- A Swarm agent worktree from that clone is trusted by both engines (test or documented engine behaviour with evidence)
+- New contributions clone under ~/harnesses/swarms/<tab>/<project>; existing contributions keep their path; projectFolder specs incl. Windows pass
+- Add machine dialog shows the new sentence (desktop test); all listed suites pass; draft PR link with exact commands and results
+- A machine contributed before the change gets its existing clone(s) trusted automatically on the next host tick, with no re-Add or Configure (test)
+
+## Implementation plan
+
+1. Reproduce missing trust and path behavior under a temporary HOME. Keep the existing engine trust contracts and atomic writers. Centralize the two authorized clone roots, validate physical clone containment, and add trust for Claude Code and Codex only for actual Swarm clones. Preserve stored legacy paths.
+2. Wire idempotent repair into contribution preparation, project preparation and each contributed-machine poll (including pools with no pending starts). Inspect linked Git worktrees and trust only Swarm agent worktrees belonging to a verified clone. New worktrees inherit via the existing core launch preparation; no core behavior change is planned.
+3. Add the exact Add machine sentence and a widget regression. Validate the narrow trust boundary, both roots, symlinks, existing files/config preservation, repeated runs, late configs, and Windows path separators.
+4. Run Node24 typecheck, Super Tab coverage gate, all affected Super Tab specs, folderTrust and launchPrep golden specs, existing worktree launch trust specs, and Desktop analysis/affected tests. Run core coverage only if core source/tests change. Independent review before publication; push a branch and open a draft PR with exact results. No ready, merge or release.
+
+## Validation scope
+
+CLI source/toolchain: changed Super Tab modules and transitive engine trust, Git project and engine-home helpers; Node24.22.0, current lockfile, isolated temporary HOME/TMPDIR. No production daemon, real tmux or personal engine files. Existing launch preparation specs pin worktree inheritance. Desktop: machines.dart and its widget suite on installed Flutter/macOS. Use the named affected suites rather than the unrelated full CLI suite; the trust operation is restricted to the new consent path and changes no engine trust format or launch protocol.
+
+## Review focus
+
+- Legacy contributions repair on a tick with zero pending starts and no owner action.
+- Symlink escape, malformed roots and another owner's repository never gain trust.
+- Only the correct clone's Swarm worktrees inherit; unrelated linked worktrees remain unchanged.
+- Missing/unreadable/malformed configs retain existing safe writer behavior; repeated repairs can retry.
+- Windows mixed separators and old clone locations remain compatible.
+
+## Review follow-ups
+
+- Publish each machine observation before trust repair. Cache clone/worktree discovery, captured native
+ locations and successful trust records in the host process for each contribution generation. A second
+ successful tick must perform no Git discovery, login-shell capture or trust-config work. Failed settings
+ retry against the retained paths/environment; a new generation or service process starts a fresh repair.
+- Cache successful discovery separately from failed discovery so a temporary Git/filesystem failure
+ retries without rescanning successful clones. Before retrying a failed settings write, verify the
+ original physical directory and Git metadata identities; a replaced path must not inherit consent.
+- Explicit contribution/project preparation still scans freshly so a new clone is trusted before launch.
+- A backend-selected Codex home may select a config only when a locally registered Codex agent already
+ uses that normalized path. Use the local row's path; an arbitrary backend path must never select a file
+ such as the owner's Cargo config. Preserve known local profile support and automatic worktree repair.
+
+### Machines freshness rebase and failure scheduling
+
+- Rebase onto current main preserves the five-second start pickup and publishes readings only on
+ change or each 15-second heartbeat. Trust repair stays after the publish block, outside its condition.
+- Per-tab failed repairs wait 15, 30, 60, 120 and 240 seconds, capped at five minutes. Unavailable
+ native login-shell capture therefore cannot delay pending starts on every five-second pass.
+- Skipped engine configs (including a machine where the engine has never run) are checked every five
+ minutes without creating a config. Successful engine/path records remain cached.
+- A changed set of local Codex homes restarts discovery and scheduling, including any new worktree,
+ while retaining completed trust records. An arbitrary backend-selected config remains refused.
+- RED first: shell capture repeats at five seconds; missing config repeats lstat; a later local
+ profile misses source/worktree trust. All three new regressions failed before these fixes.
+
+### Later clones and migration isolation
+
+- Refresh the two consented root folder listings on every periodic pass, including after an empty or
+ fully settled repair. New folder names reopen repair while successful Git discovery and settings
+ records stay cached; steady polls only reread the directory names and retain failure backoff.
+- Do not cache a missing .git directory as permanent rejection: a clone can be observed before Git
+ initialization completes. A changed pending path also drops that clone's discovery for a fresh check.
+- Catch migration exceptions before start pickup and preserve backoff even when repair throws.
+- A Codex table already present settles that path, including explicit untrusted. Preserve the person's
+ decision and stop polling its config; missing/malformed settings retain the slow retry.
+- RED first: four later-clone cases (empty/previously repaired, failed one-shot shell/config), an
+ initializing clone, thrown repair and explicit untrusted retry. All seven regressions failed before
+ implementation and pass afterward.
+- Lead explicitly authorized marking #1531 ready after the final push so automatic CLI CI runs.