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.

CLI host: a Member sets its project up once, and helpers start from that ready setup (#4698) (#3579)

0xken15a00070a3fc75
diff --git a/cli/src/superTabs/crew.spec.ts b/cli/src/superTabs/crew.spec.ts
index d3e5d55a7..a291a9d55 100644
--- a/cli/src/superTabs/crew.spec.ts
+++ b/cli/src/superTabs/crew.spec.ts
@@ -58,6 +58,14 @@ describe('which roster rows are crew this host keeps alive', () => {
expect(isCrewRow(row({}, { movedTo: 'a2' }))).toBe(false)
expect(isCrewRow({})).toBe(false)
})
+
+ // Task #4698: a Member and its helpers are kept as crew is: reopened in place, told to continue, never while asleep.
+ it('is a Member\'s or a helper\'s row too, while awake', () => {
+ expect(isCrewRow(row({}, { crew: undefined, member: { projectId: 'p1' } }))).toBe(true)
+ expect(isCrewRow(row({}, { crew: undefined, helperOf: { agentId: 'a1', harnessId: 'h1' } }))).toBe(true)
+ expect(isCrewRow(row({}, { crew: undefined, member: { projectId: 'p1' }, asleep: { since: 5 } }))).toBe(false)
+ expect(isCrewRow(row({}, { crew: undefined, member: {} }))).toBe(false)
+ })
})
describe('a frozen crew session', () => {
diff --git a/cli/src/superTabs/crew.ts b/cli/src/superTabs/crew.ts
index 5f9512ab1..32895ef09 100644
--- a/cli/src/superTabs/crew.ts
+++ b/cli/src/superTabs/crew.ts
@@ -24,7 +24,9 @@ export const CREW_CONTINUE_TRIES = 5
* on purpose by crew sleep, task #3398) and not moved to another machine (`movedTo`, task #3398), which is gone here. */
export function isCrewRow(row: unknown): boolean {
const agent = object(object(row).agent), role = object(agent.crew).role
- return typeof role === 'string' && role.length > 0 && !agent.asleep && !agent.movedTo
+ // A Member and its helpers (task #4698) work their project's tasks one at a time as crew does, so they are kept the same way.
+ const member = identifier(object(agent.member).projectId) || identifier(object(agent.helperOf).harnessId)
+ return (typeof role === 'string' && role.length > 0 || member) && !agent.asleep && !agent.movedTo
}
/** Whether this machine's assignment rows name a task running in session [harnessId] (host.ts reads its feed). */
diff --git a/cli/src/superTabs/crewFolders.ts b/cli/src/superTabs/crewFolders.ts
index c3b3b0c1c..a33d45d3e 100644
--- a/cli/src/superTabs/crewFolders.ts
+++ b/cli/src/superTabs/crewFolders.ts
@@ -10,12 +10,14 @@
* clone's other branches (a person's, other agents') are never touched (security reviews of #3229).
*/
import { execFile } from 'node:child_process'
+import { ownProcessGroup } from '../lib/windows/noWindow.js'
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { dirname, isAbsolute, join } from 'node:path'
import { promisify } from 'node:util'
const run = promisify(execFile)
-const git = async (cwd: string, ...args: string[]) => (await run('git', args, { cwd, timeout: 60_000, maxBuffer: 4 * 1024 * 1024 })).stdout.trim()
+// No window on Windows (docs/windows-rules.md): a woken Member's folder comes back through here (task #4698).
+const git = async (cwd: string, ...args: string[]) => (await run('git', args, { cwd, timeout: 60_000, maxBuffer: 4 * 1024 * 1024, ...ownProcessGroup() })).stdout.trim()
/** What a crew row asks of its host, from its agent record: close it to sleep (folder kept), close it and drop its folder, or
* close it because it moves elsewhere. Null for an awake member. */
diff --git a/cli/src/superTabs/crewFolders.windows.spec.ts b/cli/src/superTabs/crewFolders.windows.spec.ts
new file mode 100644
index 000000000..43b598665
--- /dev/null
+++ b/cli/src/superTabs/crewFolders.windows.spec.ts
@@ -0,0 +1,28 @@
+// A Member's or crew member's folder on a Windows machine (task #4698): git runs with no window, ever (docs/windows-rules.md).
+// The host is a hidden process, so a console program it starts without windowsHide opens a console of its own and flashes.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const calls = vi.hoisted(() => [] as Array<Record<string, unknown>>)
+vi.mock('node:child_process', async (original) => ({
+ ...await original<typeof import('node:child_process')>(),
+ execFile: (_file: string, _args: string[], options: Record<string, unknown>, done: (error: Error | null, out: { stdout: string; stderr: string }) => void) => {
+ calls.push(options)
+ done(null, { stdout: '', stderr: '' })
+ },
+}))
+const { pruneBranches } = await import('./crewFolders.js')
+
+describe('a crew folder\'s git on Windows', () => {
+ const platform = process.platform
+ beforeEach(() => { calls.length = 0; Object.defineProperty(process, 'platform', { value: 'win32' }) })
+ afterEach(() => { Object.defineProperty(process, 'platform', { value: platform }) })
+
+ it('runs every git call hidden and never detached', async () => {
+ await pruneBranches('C:\\Users\\dev\\harnesses\\worktrees\\project\\member')
+ expect(calls.length).toBeGreaterThan(0)
+ for (const options of calls) {
+ expect(options.windowsHide).toBe(true)
+ expect(options.detached).toBeUndefined()
+ }
+ })
+})
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index ba3b2d62c..d7022e5e0 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -4386,6 +4386,24 @@ describe('keeping a crew member alive', () => {
expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)
})
+ // Task #4698: a Member sleeps between tasks with its folder kept; woken, it is reopened in that folder as crew is.
+ it('reopens a woken Member in place, and closes it while it sleeps', async () => {
+ const rows = [crewRow({ crew: undefined, member: { projectId: 'project-1' }, asleep: { since: 1 } })]
+ const t = lifeFixture(rows)
+ withTask(t, rows)
+ t.keepLeadAlive.mockResolvedValue({ ok: true })
+ t.live(true)
+ await t.poll()
+ expect(t.closeMember).toHaveBeenCalledWith('harness')
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ rows[0] = crewRow({ crew: undefined, member: { projectId: 'project-1' } })
+ t.live(false)
+ // Its folder is checked first (a dropped one comes back), then it is reopened, as a crew member's is.
+ await t.poll(1_000)
+ await t.poll(1_000)
+ expect(t.keepLeadAlive).toHaveBeenCalledWith('harness')
+ })
+
it('reopens no ordinary agent, nor a crew member asleep or moved', async () => {
for (const row of [crewRow({ crew: undefined }), crewRow({ asleep: { since: 1 } }), crewRow({ movedTo: 'agent-2' })]) {
const t = lifeFixture([row])
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index dca361325..41e53bc3c 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -417,7 +417,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', 'windowsBuddy', 'regularAgent', 'leadSwitch', 'buddyModel', 'buddyEngine', 'turnInbox'] })
+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'regularAgent', 'memberSetUp', 'leadSwitch', 'buddyModel', 'buddyEngine', 'turnInbox'] })
// A backend from before them does not ask, and would refuse the field.
const older = fixture()
await older.machine.tick()
@@ -2739,6 +2739,107 @@ describe('removed machine cleanup', () => {
expect(backend.mock.calls.some(c => JSON.stringify(c[3] ?? '').includes('agent.startSettled'))).toBe(true)
})
+ // Task #4698: a helper starts from its Member's ready setup on this computer, found by the Swarm's own worktree record.
+ it('readies a helper from its Member\'s setup here, and says when that setup is not on this computer', async () => {
+ for (const memberHere of [true, false]) {
+ const root = mkdtempSync(join(tmpdir(), 'swarm-helper-')); roots.push(root)
+ if (memberHere) {
+ mkdirSync(join(root, 'super-tabs'), { recursive: true })
+ writeFileSync(swarmWorktreesFile(root, 'host'), JSON.stringify({ version: 1, worktrees: [
+ { tabId: 'tab', startId: 'member-start', harnessId: 'member-harness', source: '/clone', path: '/worktrees/project/member' }] }))
+ }
+ const core = fakeCore({ dataDir: root, agents: { byAgent: vi.fn(id => id === 'h-new' ? session('h-new', '/worktrees/project/new', 'agent') : undefined) } })
+ const pool = { tabId: 'tab', machine: { machineId: 'host', generation: 'grant', cwd: '/repo', engines: ['claude'], paused: false },
+ harnessIds: [], starts: [{ id: 'new', dispatched: true, request: { worktree: true, cwd: '/clone', helperOf: { agentId: 'member', harnessId: 'member-harness' } } }], paused: false }
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string, _body?: unknown): Promise<unknown> => path.includes('/hosts/host/changes') ? hostForm([], { pools: [pool] }) : { revision: 1 })
+ const open = vi.fn(async () => ({ machineId: 'host', request: vi.fn(async () => ({})), close: vi.fn() }))
+ const start = vi.fn(async (input: Record<string, unknown>) => {
+ expect(input.memberHere).toBe(memberHere)
+ await (input.beforeJoin as (harnessId: string) => Promise<void>)('h-new')
+ return { ok: true, harnessId: 'h-new' }
+ })
+ const readySetup = vi.fn(async () => ({ copied: ['node_modules', 'build'] }))
+ const log = vi.fn()
+ await new ContributedMachines(core, 'host', { backend, open, start, now: () => 0, log, readySetup,
+ capabilities: vi.fn(async () => ({ ok: true, resources: {}, tools: {} })) } as never).tick()
+ if (memberHere) {
+ expect(readySetup).toHaveBeenCalledWith('/worktrees/project/member', '/worktrees/project/new')
+ expect(log).toHaveBeenCalledWith('Readied a helper from its Member\'s setup: 2 folders copied')
+ } else {
+ expect(readySetup).not.toHaveBeenCalled()
+ expect(log).toHaveBeenCalledWith('Started a helper without its Member\'s setup: HELPER_SETUP_NOT_HERE')
+ }
+ }
+ })
+
+ // Security review 2 of #3579: the copy writes only into the helper's own new worktree, never a person's or the Member's folder.
+ it('copies into no folder but a helper\'s own new worktree', async () => {
+ for (const [request, cwd] of [
+ [{ worktree: false, cwd: '/clone' }, '/clone'],
+ [{ cwd: '/clone' }, '/somewhere'],
+ [{ worktree: true, cwd: '/clone' }, '/clone'],
+ [{ worktree: true, cwd: '/clone' }, '/worktrees/project/member'],
+ [{ worktree: true, cwd: '/clone' }, '/worktrees/project/member/inner'],
+ ] as const) {
+ const root = mkdtempSync(join(tmpdir(), 'swarm-helper-')); roots.push(root)
+ mkdirSync(join(root, 'super-tabs'), { recursive: true })
+ writeFileSync(swarmWorktreesFile(root, 'host'), JSON.stringify({ version: 1, worktrees: [
+ { tabId: 'tab', startId: 'member-start', harnessId: 'member-harness', source: '/clone', path: '/worktrees/project/member' }] }))
+ const core = fakeCore({ dataDir: root, agents: { byAgent: vi.fn(id => id === 'h-new' ? session('h-new', cwd, 'agent') : undefined) } })
+ const pool = { tabId: 'tab', machine: { machineId: 'host', generation: 'grant', cwd: '/repo', engines: ['claude'], paused: false },
+ harnessIds: [], starts: [{ id: 'new', dispatched: true, request: { ...request, helperOf: { agentId: 'member', harnessId: 'member-harness' } } }], paused: false }
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string, _body?: unknown): Promise<unknown> => path.includes('/hosts/host/changes') ? hostForm([], { pools: [pool] }) : { revision: 1 })
+ const open = vi.fn(async () => ({ machineId: 'host', request: vi.fn(async () => ({})), close: vi.fn() }))
+ const start = vi.fn(async (input: Record<string, unknown>) => {
+ // Its Member's commands only for a start that makes the helper a worktree of its own.
+ expect(input.memberHere).toBe(request.worktree === true)
+ await (input.beforeJoin as (harnessId: string) => Promise<void>)('h-new')
+ return { ok: true, harnessId: 'h-new' }
+ })
+ const readySetup = vi.fn(async () => ({ copied: [] }))
+ const log = vi.fn()
+ await new ContributedMachines(core, 'host', { backend, open, start, now: () => 0, log, readySetup,
+ capabilities: vi.fn(async () => ({ ok: true, resources: {}, tools: {} })) } as never).tick()
+ expect(readySetup).not.toHaveBeenCalled()
+ expect(log).toHaveBeenCalledWith('Started a helper without its Member\'s setup: HELPER_FOLDER_NOT_OWN')
+ }
+ })
+
+ it('says so when readying a helper fails, and never fails its start', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'swarm-helper-')); roots.push(root)
+ mkdirSync(join(root, 'super-tabs'), { recursive: true })
+ writeFileSync(swarmWorktreesFile(root, 'host'), JSON.stringify({ version: 1, worktrees: [
+ { tabId: 'tab', startId: 'member-start', harnessId: 'member-harness', source: '/clone', path: '/worktrees/project/member' }] }))
+ const core = fakeCore({ dataDir: root, agents: { byAgent: vi.fn(id => id === 'h-new' ? session('h-new', '/worktrees/project/new', 'agent') : undefined) } })
+ const pool = { tabId: 'tab', machine: { machineId: 'host', generation: 'grant', cwd: '/repo', engines: ['claude'], paused: false },
+ harnessIds: [], starts: [{ id: 'new', dispatched: true, request: { worktree: true, cwd: '/clone', helperOf: { agentId: 'member', harnessId: 'member-harness' } } }], paused: false }
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string, _body?: unknown): Promise<unknown> => path.includes('/hosts/host/changes') ? hostForm([], { pools: [pool] }) : { revision: 1 })
+ const open = vi.fn(async () => ({ machineId: 'host', request: vi.fn(async () => ({})), close: vi.fn() }))
+ let readied: unknown = 'not called'
+ const start = vi.fn(async (input: Record<string, unknown>) => {
+ readied = await (input.beforeJoin as (harnessId: string) => Promise<void>)('h-new').then(() => 'resolved', () => 'rejected')
+ return { ok: true, harnessId: 'h-new' }
+ })
+ const log = vi.fn()
+ await new ContributedMachines(core, 'host', { backend, open, start, now: () => 0, log, readySetup: vi.fn(async () => { throw new Error('/secret/path') }),
+ capabilities: vi.fn(async () => ({ ok: true, resources: {}, tools: {} })) } as never).tick()
+ expect(readied).toBe('resolved')
+ expect(log).toHaveBeenCalledWith('Started a helper without its Member\'s setup: HELPER_SETUP_FAILED')
+ })
+
+ it('gives no readying step to a start that is not a helper\'s', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'swarm-helper-')); roots.push(root)
+ const core = fakeCore({ dataDir: root, agents: { byAgent: vi.fn(() => undefined) } })
+ const pool = { tabId: 'tab', machine: { machineId: 'host', generation: 'grant', cwd: '/repo', engines: ['claude'], paused: false },
+ harnessIds: [], starts: [{ id: 'new', dispatched: true, request: { worktree: true, cwd: '/clone', member: { projectId: 'project-1' } } }], paused: false }
+ const backend = vi.fn(async (_core: unknown, _method: string, path: string, _body?: unknown): Promise<unknown> => path.includes('/hosts/host/changes') ? hostForm([], { pools: [pool] }) : { revision: 1 })
+ const open = vi.fn(async () => ({ machineId: 'host', request: vi.fn(async () => ({})), close: vi.fn() }))
+ const start = vi.fn(async (_input: Record<string, unknown>) => ({ ok: true, harnessId: 'h-new' }))
+ await new ContributedMachines(core, 'host', { backend, open, start, now: () => 0,
+ capabilities: vi.fn(async () => ({ ok: true, resources: {}, tools: {} })) } as never).tick()
+ expect(start.mock.calls[0]![0]).not.toHaveProperty('beforeJoin')
+ })
+
// Task #4353: its removal clears the trust a Team-written start saved, so the record says which start it was.
it('marks the worktree of a Team-written start', async () => {
const root = mkdtempSync(join(tmpdir(), 'swarm-record-')); roots.push(root)
diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.ts
index 84e6e9837..1bbdc1e12 100644
--- a/cli/src/superTabs/machines.ts
+++ b/cli/src/superTabs/machines.ts
@@ -15,6 +15,7 @@ import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
import { readCapabilities, quotaOf, meteredEngine, quotaUnknownReason } from './capacity.js'
import { startAgent, type ScopedRequest } from './start.js'
+import { copySetup } from './memberSetup.js'
import { settleHiddenScreen } from './startScreen.js'
import { PrepareRetryError, prepareSwarmStart } from './projectFolder.js'
import { readAuthSession } from '../lib/authSession.js'
@@ -161,6 +162,8 @@ export interface MachineDeps {
/** The Claude and Codex profile folders this machine offers ([listClaudeProfiles], [listCodexProfiles]). */
claudeProfiles?: (machineId: string) => Array<{ id: string; path: string; reportLabel: string; offered: boolean; default?: true }>
codexProfiles?: () => Array<{ path: string; offered?: boolean }>
+ /** Copies a Member's set-up folders into its helper's new worktree ([copySetup], task #4698). */
+ readySetup?: typeof copySetup
}
const MACHINE_DEPS = { claudeProfiles: (machineId: string) => listClaudeProfiles([], { machineId }), codexProfiles: () => listCodexProfiles(), backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }
/** A start's folder preparation can clone a whole repository; past this, its cleanup gives up and tries again later. */
@@ -193,7 +196,9 @@ const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list
// 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.
// `regularAgent`: it launches a Regular agent's start, sent apart as `regularStarts` (backend agent.new, task #4116).
-const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'regularAgent']
+// `memberSetUp`: a Member's start tells it to set its project up once and report agent.setUp, and a helper's start gets its
+// Member's set-up folders (memberSetup.ts, task #4698). The backend waits for that report only from a host that says this.
+const CAPABILITIES = ['leadStart', 'buddySessions', 'swarmBuddy', 'windowsBuddy', 'regularAgent', 'memberSetUp']
/** 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')
@@ -798,7 +803,13 @@ export class ContributedMachines {
// A Buddy launches only where the account signed in here is its owner's (superTabs/start.ts buddyOnOwnMachine): read
// at each start, as the start itself says whether it is a Buddy's. One that cannot be read is none: a Buddy refuses.
const signedIn = await Promise.resolve().then(() => this.core.account.identity()).then(identity => identity?.accountId ?? null, () => null)
- const result = await this.deps.start({ tabId: row.tabId, startId: start.id, hostDispatch: true, signedIn, ...(github ? { github } : {}) },
+ const helperOf = object(object(start.request).helperOf)
+ const helperRequest = object(start.request)
+ const beforeJoin = identifier(helperOf.harnessId) ? (harnessId: string) => this.readyHelper(String(row.tabId), String(helperOf.harnessId), harnessId, helperRequest) : null
+ // Its Member's commands reach a helper only from a Member this machine's Swarm started here (security review 1 of #3579),
+ // and only in a worktree of its own.
+ const memberHere = beforeJoin ? helperRequest.worktree === true && !!this.worktreeOf(String(row.tabId), String(helperOf.harnessId)) : null
+ const result = await this.deps.start({ tabId: row.tabId, startId: start.id, hostDispatch: true, signedIn, ...(github ? { github } : {}), ...(beforeJoin ? { beforeJoin, memberHere } : {}) },
scoped, where, this.deps.open)
this.refused.delete(String(start.id))
const refused = result.ok !== true && !start.dispatched && !NOT_REFUSED.has(String(result.error))
@@ -1160,6 +1171,29 @@ export class ContributedMachines {
return record ? { path: record.path, source: record.source } : null
}
+ /** A helper's new worktree gets its Member's set-up folders (task #4698), from the Member's worktree this machine's Swarm made.
+ * A Member set up elsewhere, or a copy this disk cannot make, leaves the helper to install itself; the log says which,
+ * with no path. */
+ private async readyHelper(tabId: string, memberHarnessId: string, harnessId: string, request: Record<string, unknown>): Promise<void> {
+ try {
+ const member = this.worktreeOf(tabId, memberHarnessId)?.path, helper = this.core.agents.byAgent(harnessId)?.cwd
+ if (!member || !helper) { this.log('Started a helper without its Member\'s setup: HELPER_SETUP_NOT_HERE'); return }
+ // Only into the new worktree its own start made: never the Member's folder, nor the checkout it came from, which may be a
+ // person's own (security review 2 of #3579).
+ const source = typeof request.cwd === 'string' ? request.cwd : null
+ const shared = (a: string, b: string) => within(a, b) || within(b, a)
+ if (request.worktree !== true || !source || shared(helper, member) || shared(helper, source)) {
+ this.log('Started a helper without its Member\'s setup: HELPER_FOLDER_NOT_OWN'); return
+ }
+ const copy = await (this.deps.readySetup ?? copySetup)(member, helper)
+ this.log(copy.skipped ? `Started a helper without its Member's setup: ${copy.skipped}`
+ : `Readied a helper from its Member's setup: ${copy.copied.length} folder${copy.copied.length === 1 ? '' : 's'} copied`)
+ } catch {
+ // Its own name only: an error's words can carry a path.
+ this.log('Started a helper without its Member\'s setup: HELPER_SETUP_FAILED')
+ }
+ }
+
removeStoppedWorktree(tabId: string, harnessId: string): Promise<void> {
// Lead, 10-30: an ended session (host.ts endSession) and a stopped worker (releaseWorker) can ask at the same moment.
// Each waits for the one before it and then checks for itself: after a removal it finds no record; after one that
diff --git a/cli/src/superTabs/memberSetup.spec.ts b/cli/src/superTabs/memberSetup.spec.ts
new file mode 100644
index 000000000..4920bd22f
--- /dev/null
+++ b/cli/src/superTabs/memberSetup.spec.ts
@@ -0,0 +1,129 @@
+import { execFileSync } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { sweepOne } from '../lib/worktreeSweep.js'
+import { copySetup, helperLine, memberLine, setUpSteps } from './memberSetup.js'
+
+const roots: string[] = []
+const root = () => { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'member-setup-'))); roots.push(dir); return dir }
+afterEach(() => { for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=T', '-c', 'commit.gpgsign=false', ...args],
+ { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
+
+/** A project clone, its Member's set-up worktree (installed packages, a build, a secret file, all ignored) and a helper's new one. */
+function project() {
+ const dir = root(), clone = join(dir, 'clone'), member = join(dir, 'worktrees', 'member'), helper = join(dir, 'worktrees', 'helper')
+ mkdirSync(clone)
+ git(clone, 'init', '-b', 'main')
+ writeFileSync(join(clone, '.gitignore'), 'node_modules/\nbuild/\n.env\n')
+ mkdirSync(join(clone, 'cli'))
+ writeFileSync(join(clone, 'cli', 'index.ts'), 'export {}\n')
+ git(clone, 'add', '.'); git(clone, 'commit', '-m', 'first')
+ git(clone, 'worktree', 'add', '-b', 'super-tab/member', member, 'main')
+ git(clone, 'worktree', 'add', '-b', 'super-tab/helper', helper, 'main')
+ for (const folder of ['node_modules/left-pad', 'cli/node_modules/tiny', 'build']) mkdirSync(join(member, folder), { recursive: true })
+ writeFileSync(join(member, 'node_modules', 'left-pad', 'index.js'), 'module.exports = 1\n')
+ writeFileSync(join(member, 'cli', 'node_modules', 'tiny', 'index.js'), 'module.exports = 2\n')
+ writeFileSync(join(member, 'build', 'out.js'), 'built\n')
+ writeFileSync(join(member, '.env'), 'TOKEN=not-for-helpers\n')
+ return { clone, member, helper }
+}
+
+describe('a helper starts from its Member\'s ready setup', () => {
+ it('gets the installed and built folders as copies of the Member\'s, never its other ignored files', async () => {
+ const p = project()
+ const result = await copySetup(p.member, p.helper, async (from, to) => { mkdirSync(to, { recursive: true }); execFileSync('cp', ['-R', `${from}/.`, to]) })
+ expect(result).toEqual({ copied: ['build', 'cli/node_modules', 'node_modules'] })
+ expect(readFileSync(join(p.helper, 'node_modules', 'left-pad', 'index.js'), 'utf8')).toBe('module.exports = 1\n')
+ expect(readFileSync(join(p.helper, 'cli', 'node_modules', 'tiny', 'index.js'), 'utf8')).toBe('module.exports = 2\n')
+ expect(existsSync(join(p.helper, '.env'))).toBe(false)
+ // A copy, not a link: the helper's install never changes the Member's.
+ writeFileSync(join(p.helper, 'node_modules', 'left-pad', 'index.js'), 'changed\n')
+ expect(readFileSync(join(p.member, 'node_modules', 'left-pad', 'index.js'), 'utf8')).toBe('module.exports = 1\n')
+ })
+
+ it('copies by the disk\'s clone where it has one, and otherwise copies nothing and says so', async () => {
+ const p = project()
+ const result = await copySetup(p.member, p.helper)
+ if (result.skipped) {
+ expect(result).toEqual({ copied: [], skipped: 'CLONE_UNSUPPORTED' })
+ expect(existsSync(join(p.helper, 'node_modules'))).toBe(false)
+ } else expect(readFileSync(join(p.helper, 'node_modules', 'left-pad', 'index.js'), 'utf8')).toBe('module.exports = 1\n')
+ })
+
+ it('leaves no half-copied folder when a copy fails part-way', async () => {
+ const p = project()
+ const result = await copySetup(p.member, p.helper, async (_from, to) => {
+ mkdirSync(join(to, 'partial'), { recursive: true })
+ throw Object.assign(new Error('disk full'), { code: 'ENOSPC' })
+ })
+ expect(result).toEqual({ copied: [], skipped: 'COPY_FAILED' })
+ expect(existsSync(join(p.helper, 'build'))).toBe(false)
+ expect(git(p.helper, 'status', '--porcelain', '--ignored')).toBe('')
+ })
+
+ // Security reviews of #3579: a helper's checkout may hold a tracked link where the Member has a folder.
+ it('never copies through a link in the helper\'s checkout, so nothing lands outside its folder', async () => {
+ const p = project(), outside = root()
+ rmSync(join(p.helper, 'cli'), { recursive: true })
+ symlinkSync(outside, join(p.helper, 'cli'))
+ symlinkSync(join(outside, 'missing'), join(p.helper, 'build'))
+ const result = await copySetup(p.member, p.helper, async (from, to) => { mkdirSync(to, { recursive: true }); execFileSync('cp', ['-R', `${from}/.`, to]) })
+ expect(result).toEqual({ copied: ['node_modules'] })
+ expect(readdirSync(outside)).toEqual([])
+ })
+
+ // Security review 2 of #3579: taking back a failed copy removes only what the copy made.
+ it('leaves a folder that appeared during the copy, and takes back only its own', async () => {
+ const p = project()
+ const result = await copySetup(p.member, p.helper, async (from, to) => {
+ if (to === join(p.helper, 'node_modules')) {
+ mkdirSync(join(to, 'theirs'), { recursive: true })
+ throw Object.assign(new Error('exists'), { code: 'ERR_FS_CP_EEXIST' })
+ }
+ mkdirSync(to, { recursive: true }); execFileSync('cp', ['-R', `${from}/.`, to])
+ })
+ expect(result).toEqual({ copied: [], skipped: 'COPY_FAILED' })
+ expect(existsSync(join(p.helper, 'node_modules', 'theirs'))).toBe(true)
+ expect(existsSync(join(p.helper, 'build'))).toBe(false)
+ expect(existsSync(join(p.helper, 'cli', 'node_modules'))).toBe(false)
+ })
+
+ it('copies nothing from a Member folder that is gone, and starts the helper anyway', async () => {
+ const p = project()
+ rmSync(p.member, { recursive: true, force: true })
+ expect(await copySetup(p.member, p.helper)).toEqual({ copied: [], skipped: 'NOT_READ' })
+ })
+
+ it('leaves nothing on disk when it ends: its worktree goes with the copied folders in it', async () => {
+ const p = project()
+ await copySetup(p.member, p.helper, async (from, to) => { mkdirSync(to, { recursive: true }); execFileSync('cp', ['-R', `${from}/.`, to]) })
+ expect(await sweepOne(p.helper, Date.now(), 0)).toBe(true)
+ expect(existsSync(p.helper)).toBe(false)
+ expect(existsSync(join(p.member, 'node_modules', 'left-pad', 'index.js'))).toBe(true)
+ })
+})
+
+describe('what a Member and a helper are told at their start', () => {
+ it('tells a Member to set its project up once, here, and to report it', () => {
+ const line = memberLine('tab-1', 'project-1')
+ expect(line).toContain('set the project up once')
+ expect(line).toContain('harness super-tab --tab tab-1 command OPERATION_ID - <<\'JSON\'')
+ expect(line).toContain('{"type":"agent.setUp","projectId":"project-1","ok":true,"steps":[')
+ expect(line).toContain('"ok":false')
+ })
+
+ it('gives a helper its Member\'s steps as quoted data, one per line', () => {
+ expect(helperLine(['npm ci', 'npm run build'])).toContain('\n> npm ci\n> npm run build')
+ expect(helperLine([])).not.toContain('\n>')
+ })
+
+ it('takes at most ten steps, each one plain line of 300 characters or fewer', () => {
+ expect(setUpSteps(['npm ci', 'npm run build'])).toEqual(['npm ci', 'npm run build'])
+ expect(setUpSteps(['npm ci\nrm -rf /', 'x'.repeat(301), 7, 'ok'])).toEqual(['ok'])
+ expect(setUpSteps(Array.from({ length: 12 }, (_, i) => `step ${i}`))).toHaveLength(10)
+ expect(setUpSteps('npm ci')).toEqual([])
+ })
+})
diff --git a/cli/src/superTabs/memberSetup.ts b/cli/src/superTabs/memberSetup.ts
new file mode 100644
index 000000000..cbf4f8da5
--- /dev/null
+++ b/cli/src/superTabs/memberSetup.ts
@@ -0,0 +1,97 @@
+/**
+ * A Member sets its project up once on its person's computer, and its helpers start from that setup (anh Dee's agent model,
+ * task #4693, part B #4698). How to install and build a project is judgment, so the Member's engine does it, as the project's
+ * own docs say, and reports the commands it ran. What a helper reuses is code: its worktree gets copies of the Member's
+ * installed and built folders, and its start note carries the Member's commands for whatever is still missing.
+ */
+import { execFile } from 'node:child_process'
+import { constants } from 'node:fs'
+import { cp, lstat, rm } from 'node:fs/promises'
+import { join, posix } from 'node:path'
+import { promisify } from 'node:util'
+import { ownProcessGroup } from '../lib/windows/noWindow.js'
+
+const run = promisify(execFile)
+
+/** Folders an install or a build makes, which git ignores. Only these are copied: an ignored `.env` or key file is the
+ * Member's, and a helper is told its own way to get what it needs. */
+const SETUP_FOLDERS = new Set(['node_modules', '.dart_tool', '.venv', 'venv', '.gradle', 'Pods', 'target', 'build', 'dist'])
+/** A repository with more set-up folders than this is copied only this far; the helper installs the rest. */
+const MAX_FOLDERS = 100
+/** What a disk without its own clone (NTFS, ext4) answers a forced clone: the copy is skipped, never made byte by byte, so a
+ * helper never doubles a Member's disk use. */
+const CLONE_UNSUPPORTED = new Set(['ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV', 'EINVAL'])
+
+/** What a copy says when something is already where it writes. */
+const EXISTED = new Set(['EEXIST', 'ERR_FS_CP_EEXIST', 'ERR_FS_CP_DIR_TO_NON_DIR', 'ERR_FS_CP_NON_DIR_TO_DIR'])
+
+export type SetupCopy = { copied: string[]; skipped?: 'CLONE_UNSUPPORTED' | 'COPY_FAILED' | 'NOT_READ' }
+export type CloneFolder = (from: string, to: string) => Promise<void>
+
+/** The disk's own clone (APFS clonefile, Btrfs and XFS reflinks): a copy that costs no disk until either side changes it. */
+const cloneFolder: CloneFolder = (from, to) => cp(from, to, { recursive: true, mode: constants.COPYFILE_FICLONE_FORCE, verbatimSymlinks: true, errorOnExist: true, force: false })
+
+/** Copies the Member's set-up folders in [from] into a helper's new worktree [to]. All of them or none: one that fails
+ * takes back the ones before it, so a helper never starts on half a setup. Never throws: a helper whose copy is skipped
+ * starts anyway and runs its Member's steps. */
+export async function copySetup(from: string, to: string, clone: CloneFolder = cloneFolder): Promise<SetupCopy> {
+ let listed: string
+ try {
+ listed = (await run('git', ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'],
+ { cwd: from, timeout: 30_000, maxBuffer: 16 * 1024 * 1024, ...ownProcessGroup() })).stdout
+ } catch { return { copied: [], skipped: 'NOT_READ' } }
+ const folders = listed.split('\0').filter(path => path.endsWith('/')).map(path => path.slice(0, -1))
+ .filter(path => SETUP_FOLDERS.has(posix.basename(path)) && !path.split('/').includes('..')).sort().slice(0, MAX_FOLDERS)
+ const copied: string[] = []
+ for (const folder of folders) {
+ // Only into a plain folder of the helper's own: one its checkout already has (a tracked `build/`) stays the checkout's, and a
+ // link anywhere on the way (a tracked symlink, dangling or not) is never followed out of its folder (security reviews of #3579).
+ if (!await freshInside(to, folder)) continue
+ try {
+ await clone(join(from, folder), join(to, folder))
+ copied.push(folder)
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code ?? ''
+ // Only what this copy made goes: a folder there that the copy found in its way (made meanwhile) is someone else's
+ // (security review 2 of #3579). The failed one was not there before it, so anything else left of it is the copy's.
+ const mine = EXISTED.has(code) ? copied : [...copied, folder]
+ for (const made of mine) await rm(join(to, made), { recursive: true, force: true }).catch(() => {})
+ return { copied: [], skipped: !copied.length && CLONE_UNSUPPORTED.has(code) ? 'CLONE_UNSUPPORTED' : 'COPY_FAILED' }
+ }
+ }
+ return { copied }
+}
+
+/** Whether [folder] (a relative path from git) is not in [root] yet and every folder on its way is a real one, not a link. */
+async function freshInside(root: string, folder: string): Promise<boolean> {
+ const parts = folder.split('/')
+ for (let i = 0; i < parts.length; i++) {
+ const info = await lstat(join(root, ...parts.slice(0, i + 1))).catch((error: NodeJS.ErrnoException) => error.code === 'ENOENT' ? null : error)
+ if (info instanceof Error) return false
+ if (i === parts.length - 1) return info === null
+ // A missing folder on the way is made by the copy itself, inside [root].
+ if (info && (info.isSymbolicLink() || !info.isDirectory())) return false
+ if (!info) return true
+ }
+ return false
+}
+
+/** A Member's start note: set up once, here, and say so with the commands it ran. */
+export function memberLine(tabId: string, projectId: string): string {
+ return `You are your person's Member for this project: you set the project up once in this folder, then do its tasks here, one at a time. Before your first task, set the project up once as its own docs say (README, AGENTS.md, CONTRIBUTING): install its dependencies and build it in this folder. Then report it once with harness super-tab --tab ${tabId} command OPERATION_ID - <<'JSON' and this JSON, naming each command you ran: {"type":"agent.setUp","projectId":"${projectId}","ok":true,"steps":["…"]}. If it cannot be set up, send {"type":"agent.setUp","projectId":"${projectId}","ok":false,"reason":"…"} with the reason in one line. Start each task on a new branch from the default branch, in this same folder.`
+}
+
+/** A helper's start note: its folder came from its Member's setup, and these are the commands that made it, quoted as data. Null
+ * [steps]: its Member is not this computer's own, so its words are not run here (security review 1 of #3579); it sets up itself. */
+export function helperLine(steps: string[] | null): string {
+ if (!steps) return 'You are a helper: before your task, set the project up in this folder as its own docs say (README, AGENTS.md, CONTRIBUTING). You end when no task waits, so leave nothing running.'
+ const listed = steps.length ? ` Your Member set the project up with these commands; run only the ones still needed:\n${steps.map(step => `> ${step}`).join('\n')}\n` : ' '
+ return `You are a helper: your folder was made from your Member's set-up copy of this project, with its installed folders copied where this computer could.${listed}You end when no task waits, so leave nothing running.`
+}
+
+/** The Member's reported commands, as the server keeps them: at most ten, each one plain line of 300 characters or fewer. */
+export function setUpSteps(value: unknown): string[] {
+ if (!Array.isArray(value)) return []
+ return value.filter((step): step is string => typeof step === 'string' && !!step.trim() && step.length <= 300
+ && !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(step)).slice(0, 10)
+}
diff --git a/cli/src/superTabs/projectFolder.spec.ts b/cli/src/superTabs/projectFolder.spec.ts
index cfb8a7da7..b3db0621c 100644
--- a/cli/src/superTabs/projectFolder.spec.ts
+++ b/cli/src/superTabs/projectFolder.spec.ts
@@ -49,6 +49,16 @@ describe('per-project checkouts on a contributed swarm machine', () => {
await expect(f.run()).rejects.toThrow('no authorized project')
expect(f.prepare).toHaveBeenCalledOnce()
})
+ // Task #4698: a Member starts in its person's own chat, which is in no project's list, and names the project it sets up.
+ it('finds a Member\'s project by the project its start names, and only one this machine was told of', async () => {
+ const f = fixture()
+ Object.assign(f.start.request, { conversationId: 'person-chat', member: { projectId: 'project-a' } })
+ await f.run()
+ expect(f.prepare).toHaveBeenCalledOnce()
+ Object.assign(f.start.request, { member: { projectId: 'project-b' } })
+ await expect(f.run()).rejects.toThrow('no authorized project')
+ expect(f.prepare).toHaveBeenCalledOnce()
+ })
it('does not widen a legacy contribution or substitute a different filesystem path', async () => {
const f = fixture()
f.row.machine.scope = ''
@@ -217,6 +227,15 @@ describe('preparing another person\'s start with the Harness GitHub App', () =>
expect(app.fetch).not.toHaveBeenCalled()
})
+ // Task #4698: a Member's start is a Regular agent's in its person's chat, but it sets a project up: cloned, and fetched.
+ it('prepares a Member\'s project though its start is a Regular agent\'s', async () => {
+ const app = hosted()
+ Object.assign(app.start.request, { regular: true, conversationId: 'person-chat', member: { projectId: 'project-a' } })
+ expect(await app.ready()).toEqual({ requester: '[email protected]' })
+ expect(app.prepare).toHaveBeenCalledOnce()
+ expect(app.fetch).toHaveBeenCalledOnce()
+ })
+
it('in a team account, always asks for a token, and fails without one rather than using any other login', async () => {
const team = hosted()
expect(await team.ready(true)).toEqual({ requester: '[email protected]' })
diff --git a/cli/src/superTabs/projectFolder.ts b/cli/src/superTabs/projectFolder.ts
index 9cc76d37a..5574dadaa 100644
--- a/cli/src/superTabs/projectFolder.ts
+++ b/cli/src/superTabs/projectFolder.ts
@@ -83,8 +83,9 @@ export async function prepareSwarmStart(core: CoreApi, row: Json, start: Json,
// A person's one Buddy has no project: its launch makes its folder from the checkouts already here and fetches nothing
// (buddyHome.ts). Asking for a token anyway was refused with a 404, which failed every such start (2026-11-02).
if (request.buddyScope === 'swarm') return null
- // Nor does a Regular agent (backend agent.new, task #4116): it starts in no project, in a folder of its own (start.ts).
- if (request.regular === true) return null
+ // Nor does a Regular agent (backend agent.new, task #4116): it starts in no project, in a folder of its own (start.ts). A
+ // Member's start is a Regular agent's in its person's chat, but it sets its project up there (task #4698), so it is prepared.
+ if (request.regular === true && !memberProject(request)) return null
// Nor does a project with no repository address (task #3211): there is nothing to clone, and the server refuses a token
// for it. Its work starts in a folder of its own, made without any login (prepareSwarmProject).
const project = startProject(row, request)
@@ -114,12 +115,18 @@ function sameFolder(requested: unknown, folder: unknown): boolean {
return typeof requested === 'string' && typeof folder === 'string' && isAbsolute(requested) && resolve(requested) === resolve(folder)
}
-/** The project a queued start is for, of those this machine was told of. A project session of a person's one Buddy chat
- * names its project: that chat is in no project's list (backend hostRows.ts). */
+/** The project a Member's start sets up (task #4698): its person's chat is in no project's list, so the start names it. */
+const memberProject = (request: Json): string | undefined => {
+ const id = object(request.member).projectId
+ return typeof id === 'string' && id ? id : undefined
+}
+
+/** The project a queued start is for, of those this machine was told of. A project session of a person's one Buddy chat and a
+ * Member's start name their project: those chats are in no project's list (backend hostRows.ts). */
function startProject(row: Json, request: Json): Json | undefined {
- const session = object(request.buddySession).projectId
+ const named = object(request.buddySession).projectId ?? memberProject(request)
return (Array.isArray(row.projects) ? row.projects.map(object) : [])
- .find(p => session ? p.id === session : Array.isArray(p.conversationIds) && p.conversationIds.includes(request.conversationId))
+ .find(p => named ? p.id === named : Array.isArray(p.conversationIds) && p.conversationIds.includes(request.conversationId))
}
const NOT_OWN_FOLDER = 'This machine has something that is not this project\'s own folder where its folder goes. Its owner can move it aside, then start again.'
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index a8a6f69d0..c04dc3fac 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -1787,3 +1787,56 @@ describe('neutral start prompts', () => {
expect(String(payload.prompt)).not.toContain('Tester')
})
})
+
+// Task #4698: a Member sets its project up once on its person's computer; a helper starts from that ready setup.
+describe('a Member and its helpers', () => {
+ it('tells a Member to set its project up once in its folder and report it', async () => {
+ const f = fixture()
+ f.start.request = { ...f.start.request, member: { projectId: 'project-1' } } as typeof f.start.request
+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'member-prompt', request: f.start.request }, f.scoped, where, f.open)
+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
+ expect(payload.prompt).toContain('set the project up once')
+ expect(payload.prompt).toContain('"type":"agent.setUp","projectId":"project-1"')
+ expect(payload).toMatchObject({ projectSource: 'worktree', gitSource: '/repo' })
+ })
+
+ it('readies a helper\'s folder from its Member\'s setup before it joins, and gives it the Member\'s steps', async () => {
+ const f = fixture()
+ f.start.request = { ...f.start.request, helperOf: { agentId: 'member', harnessId: 'member-harness' }, setUpSteps: ['npm ci', 'npm run build\nrm -rf /'] } as typeof f.start.request
+ const order: string[] = []
+ const scoped = vi.fn(async (payload: Record<string, unknown>) => {
+ if ((payload.command as { type?: string } | undefined)?.type === 'agent.started') order.push('joined')
+ return f.scoped(payload)
+ })
+ const beforeJoin = vi.fn(async (harnessId: string) => { order.push(`readied ${harnessId}`) })
+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'helper-prompt', request: f.start.request, beforeJoin, memberHere: true }, scoped, where, f.open)
+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
+ expect(payload.prompt).toContain('You are a helper')
+ expect(payload.prompt).toContain('\n> npm ci\n')
+ expect(payload.prompt).not.toContain('rm -rf')
+ expect(order).toEqual(['readied native', 'joined'])
+ })
+
+ // Security review 1 of #3579: the Member's commands are another agent's words, run only when that Member is this computer's own.
+ it('gives a helper no Member commands unless its host found that Member on this computer', async () => {
+ for (const memberHere of [false, undefined]) {
+ const f = fixture()
+ f.start.request = { ...f.start.request, helperOf: { agentId: 'member', harnessId: 'member-harness' }, setUpSteps: ['npm ci'] } as typeof f.start.request
+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'helper-elsewhere', request: f.start.request, ...(memberHere === undefined ? {} : { memberHere }) }, f.scoped, where, f.open)
+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
+ expect(payload.prompt).toContain('You are a helper')
+ expect(payload.prompt).not.toContain('npm ci')
+ expect(payload.prompt).not.toContain('set-up copy')
+ }
+ })
+
+ it('starts a helper whose folder could not be readied, as a helper still', async () => {
+ const f = fixture()
+ f.start.request = { ...f.start.request, helperOf: { agentId: 'member', harnessId: 'member-harness' } } as typeof f.start.request
+ const beforeJoin = vi.fn(async () => { throw new Error('gone') })
+ const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'helper-unready', request: f.start.request, beforeJoin }, f.scoped, where, f.open)
+ expect(beforeJoin).toHaveBeenCalledWith('native')
+ expect(f.scoped.mock.calls.some(([payload]) => (payload.command as { type?: string } | undefined)?.type === 'agent.started')).toBe(true)
+ expect(result).not.toHaveProperty('error')
+ })
+})
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index df1c99ba4..109ed6480 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -14,6 +14,7 @@ import { projectsRoot } from '../lib/projectFolder.js'
import { worktreeFolderName } from '../lib/agentNames.js'
import { join as joinPath } from 'node:path'
import { markBuddyOwner } from '../lib/buddyGuard.js'
+import { helperLine, memberLine, setUpSteps } from './memberSetup.js'
import { engineAccount } from '../lib/engineAccount.js'
type Json = Record<string, unknown>
@@ -465,6 +466,11 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
const github = buddy ? null : hosted ? (typeof hosted.requester === 'string' && hosted.requester ? { requester: hosted.requester } : null) : facts?.github ?? null
// The role's name from the project's document, when the backend's start request has it; one line, bounded.
const roleName = typeof request.roleName === 'string' ? request.roleName.replace(/\s+/g, ' ').trim().slice(0, 80) : ''
+ // Anh Dee's agent model (task #4698): a Member sets its project up once in its folder; a helper starts from that setup.
+ // A helper's Member's commands only when its host found that Member on this computer (machines.ts `memberHere`).
+ const memberProject = !buddy && !lead ? text(object(request.member).projectId) : null
+ const helper = !buddy && !lead && identifier(object(request.helperOf).harnessId)
+ const setUpLine = memberProject && identifier(memberProject) ? ` ${memberLine(String(input.tabId), memberProject)}` : helper ? ` ${helperLine(input.memberHere === true ? setUpSteps(request.setUpSteps) : null)}` : ''
// Swarm v3 (task #4215): a PM, an agent and a Buddy start with their owner's own permission settings: no mode, so the
// engine opens in the person's own default. Forced full mode turned off every check on people's own computers, where
// Anthropic says to use it only in isolated environments. Team-written work keeps its barrier against the branch's own
@@ -478,7 +484,7 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
: buddySessionPrompt(String(input.tabId), String(request.conversationId), session, mode)
: home ? swarmBuddyPrompt(String(input.tabId), String(request.conversationId), home, mode)
: buddyPrompt(String(input.tabId), String(request.conversationId), mode))
- : `${lead ? leadPrompt(String(input.tabId), String(request.conversationId), roleName) : workerPrompt(String(input.tabId), String(request.conversationId), roleName)}${github ? ` ${githubPromptLine()}` : ''}${handoffPrompt}`,
+ : `${lead ? leadPrompt(String(input.tabId), String(request.conversationId), roleName) : workerPrompt(String(input.tabId), String(request.conversationId), roleName)}${setUpLine}${github ? ` ${githubPromptLine()}` : ''}${handoffPrompt}`,
...(homeFolder ? { cwd: homeFolder } : agentFolder ? { cwd: agentFolder } : request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`,
// No branch named: the repository's default branch, fetched, not the host checkout's old HEAD.
...(request.branchRef ? { branchRef: request.branchRef } : { branchBase: 'default' }) } : { cwd: request.cwd }),
@@ -595,6 +601,11 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
const configuration = { engine, model: matched?.model ?? null,
effort: matched?.effort === 'auto' && launchedEffort ? launchedEffort : matched?.effort ?? null,
contextWindow: number(seenFrame.contextWindow), engineVersion: text(seenFrame.engineVersion) }
+ // A helper's folder gets its Member's set-up copy before it joins: the server gives it its task only once it has, so the copy
+ // never races its work. The host's own step logs what it did; a helper it could not ready still starts, and installs itself.
+ if (!start.harnessId && typeof input.beforeJoin === 'function' && identifier(object(request.helperOf).harnessId)) {
+ await (input.beforeJoin as (harnessId: string) => Promise<void>)(nativeId).catch(() => {})
+ }
const join = { type: 'agent.started', startId, harnessId: nativeId, configuration }
let joined: Json = { result: {} }
if (!start.harnessId) {