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): start Builders from the fetched origin default branch; name what an OUTSIDE_CONTRIBUTION refusal refused

tony0fabcecf822b
diff --git a/backend/src/superTabs/machines.test.ts b/backend/src/superTabs/machines.test.ts
new file mode 100644
index 000000000..d6797fc1f
--- /dev/null
+++ b/backend/src/superTabs/machines.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest'
+import { createSuperTab, SuperTabError, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'
+import { admitMachineStart, type ContributedMachine } from './machines.js'
+
+const NOW = 1_000_000
+const requirements = { memoryBytes: 1, diskBytes: 1, maxCpuPercent: 50, tools: ['git'], devices: [], quotaRequired: false }
+const observation = { generation: 'o', receivedAt: NOW, resources: { cpuPercent: 1, memoryTotalBytes: 1, memoryUsedBytes: 1, diskFreeBytes: 1, diskTotalBytes: 1,
+ projectDiskFreeBytes: 1, deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] }
+
+function setup(machine: Partial<ContributedMachine> = {}) {
+ const state: SuperTabState = createSuperTab('tab', 'Team', { id: 'owner', email: '[email protected]' }, 'test')
+ state.machines = [{ machineId: 'host', name: 'Studio Mac', contributorId: 'owner', membershipGeneration: 'tab', generation: 'g1',
+ cwd: '/data/swarm-projects/tab', scope: 'swarm', engines: ['claude', 'codex'], maxAgents: 2, paused: false, observation, ...machine }]
+ const request = (extra: Partial<AgentStartRequest> = {}): AgentStartRequest => ({ conversationId: 'lead', machineId: 'host', engine: 'claude',
+ name: 'Builder', cwd: '/data/swarm-projects/tab/lead', worktree: true, requirements, ...extra })
+ return { state, request }
+}
+/** The refusal a start meets, or null when it is admitted. */
+function refusal(state: SuperTabState, request: AgentStartRequest, start?: AgentStart): SuperTabError | null {
+ try { admitMachineStart(state, request, NOW, start); return null }
+ catch (error) { if (error instanceof SuperTabError) return error; throw error }
+}
+
+/** What the refusal lists as refused, after its opening sentence. */
+const refused = (error: SuperTabError) => error.message.split('Refused: ')[1] ?? ''
+
+describe('a start on a contributed machine', () => {
+ it('is admitted inside the contribution: its project folder, one of its engines, no account settings', () => {
+ const f = setup()
+ expect(refusal(f.state, f.request())).toBeNull()
+ expect(refusal(f.state, f.request({ engine: 'codex' }))).toBeNull()
+ })
+
+ it('names the folder this project uses when the start asks for another', () => {
+ const f = setup()
+ const error = refusal(f.state, f.request({ cwd: '/Users/lead/work/repo' }))!
+ expect(error).toMatchObject({ code: 'OUTSIDE_CONTRIBUTION', status: 403 })
+ expect(error.message).toContain('Studio Mac')
+ expect(error.message).toContain('Refused: cwd (this project uses /data/swarm-projects/tab/lead on it).')
+ expect(refused(error)).not.toContain('engine')
+ expect(error.message).not.toContain('/Users/lead/work/repo')
+ })
+
+ it('names the project\'s own checkout when the lead\'s machine is the one contributed', () => {
+ const f = setup()
+ f.state.project = { machineId: 'host', cwd: '/Users/lead/work/repo', repositoryUrl: null }
+ expect(refusal(f.state, f.request({ cwd: '/data/swarm-projects/tab/lead' }))!.message).toContain('this project uses /Users/lead/work/repo on it')
+ expect(refusal(f.state, f.request({ cwd: '/Users/lead/work/repo' }))).toBeNull()
+ })
+
+ it('lists the engines the machine contributes when the start asks for another', () => {
+ const f = setup()
+ const error = refusal(f.state, f.request({ engine: 'opencode' }))!
+ expect(error).toMatchObject({ code: 'OUTSIDE_CONTRIBUTION', status: 403 })
+ expect(error.message).toContain('Refused: engine (it contributes claude, codex).')
+ expect(refused(error)).not.toContain('cwd')
+ expect(error.message).not.toContain('opencode')
+ f.state.machines![0]!.engines = []
+ expect(refusal(f.state, f.request())!.message).toContain('it contributes no engines')
+ })
+
+ it.each(['codexHome', 'gridModel', 'gridName', 'permissionMode'] as const)('names %s as the refused account setting, and not its value', field => {
+ const f = setup()
+ const error = refusal(f.state, f.request({ [field]: '/Users/lead/.secret-profile' }))!
+ expect(error).toMatchObject({ code: 'OUTSIDE_CONTRIBUTION', status: 403 })
+ expect(error.message).toContain(`Refused: ${field} (it runs with its own default account settings, so leave it out).`)
+ for (const other of ['cwd', 'engine', ...['codexHome', 'gridModel', 'gridName', 'permissionMode'].filter(name => name !== field)]) {
+ expect(refused(error)).not.toContain(other)
+ }
+ expect(error.message).not.toContain('secret-profile')
+ })
+
+ it('names every refused field at once', () => {
+ const f = setup()
+ const error = refusal(f.state, f.request({ cwd: '/elsewhere', engine: 'opencode', codexHome: '/h', permissionMode: 'bypass' }))!
+ expect(error.message).toContain('cwd (this project uses /data/swarm-projects/tab/lead on it)')
+ expect(error.message).toContain('engine (it contributes claude, codex)')
+ expect(error.message).toContain('codexHome, permissionMode (it runs with its own default account settings, so leave them out)')
+ })
+
+ it('says nothing of other projects or machines', () => {
+ const f = setup()
+ f.state.projects = [
+ { id: 'lead', name: 'Team', ownerId: 'owner', leadConversationId: 'lead', visibility: 'public', members: [], updateMinutes: 5 },
+ { id: 'other', name: 'Private', ownerId: 'owner', leadConversationId: 'other', visibility: 'private', members: [], updateMinutes: 5,
+ repository: { machineId: 'host', cwd: '/Users/someone-else/private-repo', repositoryUrl: null } },
+ ]
+ f.state.machines!.push({ ...f.state.machines![0]!, machineId: 'laptop', name: 'Someone else\'s laptop', cwd: '/Users/someone-else/.harness/swarm-projects/tab' })
+ const error = refusal(f.state, f.request({ cwd: '/elsewhere', codexHome: '/h' }))!
+ expect(error.message).not.toContain('someone-else')
+ expect(error.message).not.toContain('private-repo')
+ expect(error.message).not.toContain('laptop')
+ })
+
+ it('gives the same answer when the start is checked again before it is dispatched', () => {
+ const f = setup()
+ const start = { poolGeneration: 'g1' } as AgentStart
+ expect(refusal(f.state, f.request({ permissionMode: 'bypass' }), start)!.message).toContain('Refused: permissionMode')
+ expect(refusal(f.state, f.request(), start)).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index fe3c25812..162376781 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -71,9 +71,15 @@ export function admitMachineStart(state: SuperTabState, request: AgentStartReque
const cwd = pool.scope === 'swarm'
? project.repository?.machineId === pool.machineId ? project.repository.cwd : `${pool.cwd.replace(/\/+$/, '')}/${project.id}`
: pool.cwd
- if (request.cwd !== cwd || !pool.engines.includes(request.engine)
- || request.codexHome || request.gridModel || request.gridName || request.permissionMode) {
- fail('OUTSIDE_CONTRIBUTION', 'Use the contributed project, engine and default account settings.', 403)
+ // Every refused field is named, with what the machine does accept. Values the caller sent are not echoed: an account
+ // setting can be a path or a name of the caller's own.
+ const refused: string[] = []
+ if (request.cwd !== cwd) refused.push(`cwd (this project uses ${cwd} on it)`)
+ if (!pool.engines.includes(request.engine)) refused.push(`engine (it contributes ${pool.engines.join(', ') || 'no engines'})`)
+ const settings = (['codexHome', 'gridModel', 'gridName', 'permissionMode'] as const).filter(key => request[key])
+ if (settings.length) refused.push(`${settings.join(', ')} (it runs with its own default account settings, so leave ${settings.length > 1 ? 'them' : 'it'} out)`)
+ if (refused.length) {
+ fail('OUTSIDE_CONTRIBUTION', `${pool.name} accepts only its contributed project folder, engines and default account settings. Refused: ${refused.join('; ')}.`, 403)
}
if (!pool.observation || now - pool.observation.receivedAt > 45_000) {
fail('MACHINE_OFFLINE', 'Wait for a fresh reading from the contributed machine.')
diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.ts
index 8f0464f23..330a31de7 100644
--- a/cli/src/lib/gitProject.spec.ts
+++ b/cli/src/lib/gitProject.spec.ts
@@ -357,6 +357,94 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
expect((await exec('git', ['-C', tracking, 'rev-parse', '--abbrev-ref', '@{upstream}'])).stdout.trim()).toBe('origin/fix/typo')
})
+ describe('a Swarm start that names no branch', () => {
+ // A Swarm host clones a project once and reuses that checkout for every Builder, so its HEAD falls behind the
+ // remote. `branchBase: 'default'` is what a Swarm start without `branchRef` asks for.
+ let origin: string, managed: string
+ const identity = ['-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null']
+ const inClone = (...args: string[]) => exec('git', ['-C', managed, ...args]).then(out => out.stdout.trim())
+ /** What the worktree a Swarm start made shows of `src/value`. */
+ const swarmStart = async (extra: Record<string, unknown> = {}, path = managed) =>
+ readFile(join(await prepareProjectFolder(parseProjectFolder({ projectSource: 'worktree', gitSource: path, branchName: 'super-tab/start-1',
+ branchBase: 'default', ...extra })!, options()), 'src', 'value'), 'utf8')
+ beforeEach(async () => {
+ origin = join(root, 'origin.git'); managed = join(root, 'managed')
+ await exec('git', ['clone', '--quiet', '--bare', repo, origin])
+ await exec('git', ['clone', '--quiet', origin, managed])
+ })
+ /** Someone pushes to the remote's default branch after the managed clone was made. */
+ const pushToOrigin = async (value: string) => {
+ const pusher = join(root, 'pusher')
+ await exec('git', ['clone', '--quiet', origin, pusher])
+ await writeFile(join(pusher, 'src', 'value'), value)
+ await exec('git', ['-C', pusher, ...identity, 'commit', '-qam', value])
+ await exec('git', ['-C', pusher, 'push', '--quiet', 'origin', 'main'])
+ }
+
+ it('starts from the remote default branch, fetched first, and leaves the checkout\'s own branch where it was', async () => {
+ const before = await inClone('rev-parse', 'HEAD')
+ await pushToOrigin('pushed')
+ expect(await swarmStart()).toBe('pushed')
+ expect(await inClone('rev-parse', 'HEAD')).toBe(before)
+ expect(await inClone('rev-parse', 'refs/remotes/origin/main')).not.toBe(before)
+ })
+
+ it('starts from what the checkout has when the fetch fails', async () => {
+ await pushToOrigin('pushed')
+ await inClone('remote', 'set-url', 'origin', join(root, 'gone.git'))
+ expect(await swarmStart()).toBe('main')
+ })
+
+ it('starts from HEAD in a repository with no remote default branch', async () => {
+ const local = join(root, 'local-only')
+ await mkdir(local)
+ await exec('git', ['-C', local, 'init', '-q', '-b', 'trunk'])
+ await mkdir(join(local, 'src'))
+ await writeFile(join(local, 'src', 'value'), 'trunk')
+ await exec('git', ['-C', local, 'add', '.'])
+ await exec('git', ['-C', local, ...identity, 'commit', '-qm', 'initial'])
+ expect(await swarmStart({}, local)).toBe('trunk')
+ })
+
+ it('names the default branch when the remote has no origin/HEAD but has main', async () => {
+ await pushToOrigin('pushed')
+ await inClone('remote', 'set-head', 'origin', '--delete')
+ expect(await swarmStart()).toBe('pushed')
+ })
+
+ it('starts from the branch it is given, not the default one', async () => {
+ await pushToOrigin('pushed')
+ expect(await swarmStart({ branchBase: undefined, branchRef: 'refs/remotes/origin/feature' })).toBe('feature')
+ })
+
+ it('is not what a start from Desktop or the CLI does: without the flag the checkout\'s HEAD is used and nothing is fetched', async () => {
+ const before = await inClone('rev-parse', 'refs/remotes/origin/main')
+ await pushToOrigin('pushed')
+ expect(await swarmStart({ branchBase: undefined })).toBe('main')
+ expect(await inClone('rev-parse', 'refs/remotes/origin/main')).toBe(before)
+ })
+
+ it('is accepted only for a worktree that names no branch', () => {
+ const parse = (extra: Record<string, unknown>) => () => parseProjectFolder({ projectSource: 'worktree', gitSource: managed,
+ branchName: 'super-tab/start-1', ...extra })
+ expect(parse({ branchBase: 'default' })()).toMatchObject({ source: 'worktree', fromDefaultBranch: true })
+ expect(parseProjectFolder({ projectSource: 'worktree', gitSource: managed, branchBase: 'default' })).toMatchObject({ fromDefaultBranch: true })
+ expect(parse({})()).not.toHaveProperty('fromDefaultBranch')
+ expect(parse({ branchBase: 'default', branchRef: 'refs/remotes/origin/main' })).toThrow()
+ expect(parse({ branchBase: 'main' })).toThrow()
+ expect(parse({ branchBase: true })).toThrow()
+ expect(() => parseProjectFolder({ projectSource: 'branch', gitSource: managed, branchRef: 'refs/heads/main', branchBase: 'default' })).toThrow()
+ })
+
+ it('does not change a direct prepareGitProject call', async () => {
+ await pushToOrigin('pushed')
+ const path = await prepareGitProject(managed, { root: join(root, 'harnesses'), worktree: true, branchName: 'plain' })
+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')
+ const asked = await prepareGitProject(managed, { root: join(root, 'harnesses'), worktree: true, branchName: 'asked', fromDefaultBranch: true })
+ expect(await readFile(join(asked, 'src', 'value'), 'utf8')).toBe('pushed')
+ })
+ })
+
it('copies ignored files named in .worktreeinclude into new worktrees', async () => {
await writeFile(join(repo, '.gitignore'), '.env\n*.log\nlocal/\n')
await writeFile(join(repo, '.worktreeinclude'), '.env\nlocal/\n')
diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.ts
index eff5889ce..cfecf17d5 100644
--- a/cli/src/lib/gitProject.ts
+++ b/cli/src/lib/gitProject.ts
@@ -191,11 +191,25 @@ function remoteBranch(ref: string | undefined): { remote: string; branch: string
return { remote: match[1]!, branch: match[2]!, refspec: `+refs/heads/${match[2]}:refs/remotes/${match[1]}/${match[2]}` }
}
+/** The remote's default branch as the ref a clone keeps it in: `origin/HEAD`, else `origin/main` or
+ * `origin/master`, as `readGitProject` offers it. Null when the repository has no such ref. */
+async function originDefaultRef(path: string): Promise<string | null> {
+ const head = await git(path, ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']).catch(() => null)
+ for (const ref of [head, 'refs/remotes/origin/main', 'refs/remotes/origin/master']) {
+ if (ref && await git(path, ['show-ref', '--verify', '--quiet', '--', ref]).then(() => true, () => false)) return ref
+ }
+ return null
+}
+
export type GitProjectOptions = {
root: string
worktree: boolean
/** Worktree on: what a new branch starts from. Worktree off: the branch the folder is on. */
ref?: string
+ /** Worktree on, a new branch, no `ref`: start from the remote's default branch, fetched first, rather than
+ * from wherever `HEAD` is. A checkout nobody works in (a Swarm host's clone) stays where it was cloned, days
+ * behind. Only a Swarm start asks for it; a repository with no `origin` default branch starts from `HEAD`. */
+ fromDefaultBranch?: boolean
/** The worktree's branch: created from `ref`, or with `existingBranch` checked out as it is. */
branchName?: string
existingBranch?: boolean
@@ -206,7 +220,8 @@ export type GitProjectOptions = {
/** Worktree on: a new worktree under `<root>/worktrees/<repository>`, on `branchName` — created from
* `ref`, or with `existingBranch` an existing local branch checked out as it is. Without a name one
- * is made up (`harness/brave-otter`). A remote base is fetched first, briefly.
+ * is made up (`harness/brave-otter`). A remote base is fetched first, briefly: so is the default branch
+ * with `fromDefaultBranch`, when there is no `ref`.
*
* Worktree off: the folder on the local `ref`. A branch that already has a worktree opens there; any
* other is switched to, only in a folder with nothing uncommitted. With `branchName` the folder moves
@@ -222,25 +237,28 @@ export async function prepareGitProject(source: string, options: GitProjectOptio
let root: string, head: string, prefix: string
try {
root = await git(source, ['rev-parse', '--show-toplevel'])
- if (options.ref && !creating) {
- if (!/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(options.ref)) throw new Error('Invalid branch')
+ // The default branch is only ever a remote one, so it is fetched like any other remote base below.
+ const ref = options.ref ?? (options.fromDefaultBranch && options.worktree && !existing && !creating
+ ? await originDefaultRef(source) ?? undefined : undefined)
+ if (ref && !creating) {
+ if (!/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(ref)) throw new Error('Invalid branch')
// A freshly discovered remote branch may not have been fetched yet.
- if (!(options.worktree && !existing && remoteBranch(options.ref))) {
- await git(source, ['show-ref', '--verify', '--hash', '--', options.ref])
+ if (!(options.worktree && !existing && remoteBranch(ref))) {
+ await git(source, ['show-ref', '--verify', '--hash', '--', ref])
}
}
// New work starts from where its branch is now, not from the last fetch: a remote branch is
// fetched; a local one is fetched against its upstream and the newer of the two taken, so nothing
// only the local one has is lost. Offline, slow or refused, it starts from what is here.
- let start = existing ? `refs/heads/${options.branchName}` : creating ? 'HEAD' : options.ref ?? 'HEAD'
- const remote = options.worktree && !existing ? remoteBranch(options.ref) : null
- const upstream = options.worktree && !existing && !remote && options.ref
- ? await git(source, ['for-each-ref', '--format=%(upstream)', options.ref]).then(ref => remoteBranch(ref) ? ref : null, () => null)
+ let start = existing ? `refs/heads/${options.branchName}` : creating ? 'HEAD' : ref ?? 'HEAD'
+ const remote = options.worktree && !existing ? remoteBranch(ref) : null
+ const upstream = options.worktree && !existing && !remote && ref
+ ? await git(source, ['for-each-ref', '--format=%(upstream)', ref]).then(found => remoteBranch(found) ? found : null, () => null)
: null
const fetch = remote ?? remoteBranch(upstream ?? undefined)
if (fetch) await git(source, ['fetch', '--quiet', '--no-tags', fetch.remote, fetch.refspec], 10_000).catch(() => '')
// Behind or level with its upstream: the upstream is the newer.
- if (upstream && options.ref && await git(source, ['merge-base', '--is-ancestor', options.ref, upstream]).then(() => true, () => false)) {
+ if (upstream && ref && await git(source, ['merge-base', '--is-ancestor', ref, upstream]).then(() => true, () => false)) {
start = upstream
}
head = await git(source, ['rev-parse', '--verify', '--end-of-options', `${start}^{commit}`])
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index 8ceb4af31..bc2232fc9 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -12,7 +12,7 @@ import type { ScmLaunchRecord } from '../scm/types.js'
* harness and the time. `suggested` marks a name the app made up (from the first task — the phone has
* no name field), which is numbered past a folder that exists rather than refused. */
export type ProjectFolder = { source: 'new'; name?: string; suggested?: boolean } | { source: 'remote'; repositoryUrl: string; name: string }
- | { source: 'worktree'; gitSource: string; branchRef?: string; branchName?: string; existingBranch?: boolean; placeholder?: boolean }
+ | { source: 'worktree'; gitSource: string; branchRef?: string; branchName?: string; existingBranch?: boolean; placeholder?: boolean; fromDefaultBranch?: boolean }
| { source: 'branch'; gitSource: string; branchRef?: string; branchName?: string }
/** Where this daemon and the desktop app put the workspaces they make. A folder directly inside it is
@@ -33,8 +33,12 @@ export function parseProjectFolder(payload: Record<string, unknown>): ProjectFol
if (payload.projectSource === undefined) return null
if (payload.projectSource === 'worktree' || payload.projectSource === 'branch') {
const ref = payload.branchRef
+ // `branchBase: 'default'` starts a new worktree from the remote's default branch rather than from `HEAD`; it
+ // is for a start that names no branch, and for a worktree.
+ const base = payload.branchBase
if (!validGitPath(payload.gitSource) || payload.repositoryUrl !== undefined ||
(ref !== undefined && (typeof ref !== 'string' || ref.length > 1024 || !/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(ref))) ||
+ (base !== undefined && (base !== 'default' || ref !== undefined || payload.projectSource !== 'worktree')) ||
(payload.projectSource === 'branch' && (typeof ref !== 'string' || !ref.startsWith('refs/heads/')))) {
throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a Git project and branch.')
}
@@ -45,7 +49,8 @@ export function parseProjectFolder(payload: Record<string, unknown>): ProjectFol
}
return { source: 'worktree', gitSource: payload.gitSource, ...(typeof ref === 'string' ? { branchRef: ref } : {}),
branchName: name, ...(payload.branchMode === 'existing' ? { existingBranch: true } : {}),
- ...(payload.branchMode === 'placeholder' ? { placeholder: true } : {}) }
+ ...(payload.branchMode === 'placeholder' ? { placeholder: true } : {}),
+ ...(base === 'default' ? { fromDefaultBranch: true } : {}) }
}
// A new branch for the folder itself, named by `branchRef` too.
if (payload.projectSource === 'branch' && name !== undefined) {
@@ -54,7 +59,8 @@ export function parseProjectFolder(payload: Record<string, unknown>): ProjectFol
}
return { source: 'branch', gitSource: payload.gitSource, branchRef: ref, branchName: name }
}
- return { source: payload.projectSource, gitSource: payload.gitSource, ...(typeof ref === 'string' ? { branchRef: ref } : {}) }
+ return { source: payload.projectSource, gitSource: payload.gitSource, ...(typeof ref === 'string' ? { branchRef: ref } : {}),
+ ...(base === 'default' ? { fromDefaultBranch: true } : {}) }
}
if (payload.projectSource === 'new' && payload.repositoryUrl === undefined) {
// Slugged again here: the name becomes a path segment, so it is never taken on trust.
@@ -167,7 +173,7 @@ export async function prepareProjectFolder(
// The isolated-workspace path, through the SCM seam. The git implementation makes exactly the
// prepareGitProject call this used to make.
const { cwd, launchRecord } = await scmByKind('git')!.prepareIsolated(project.gitSource, {
- root, base: project.branchRef,
+ root, base: project.branchRef, ...(project.fromDefaultBranch ? { fromDefaultBranch: true } : {}),
...(project.branchName ? { name: project.branchName, existing: project.existingBranch === true, placeholder: project.placeholder === true } : {}),
})
options.onPrepared?.({ cwd, scmLaunchRecord: launchRecord })
diff --git a/cli/src/scm/gitScmProject.ts b/cli/src/scm/gitScmProject.ts
index a799d720d..105e50c03 100644
--- a/cli/src/scm/gitScmProject.ts
+++ b/cli/src/scm/gitScmProject.ts
@@ -29,6 +29,7 @@ export class GitScmProject implements ScmProject {
async prepareIsolated(source: string, options: PrepareOptions): Promise<{ cwd: string; launchRecord: ScmLaunchRecord }> {
const cwd = await prepareGitProject(source, {
root: options.root, worktree: true, ref: options.base,
+ ...(options.fromDefaultBranch ? { fromDefaultBranch: true } : {}),
...(options.name !== undefined ? {
branchName: options.name, existingBranch: options.existing === true, placeholder: options.placeholder === true,
} : {}),
diff --git a/cli/src/scm/types.ts b/cli/src/scm/types.ts
index 6302de1e5..6b8816310 100644
--- a/cli/src/scm/types.ts
+++ b/cli/src/scm/types.ts
@@ -67,6 +67,9 @@ export interface PrepareOptions {
/** What the workspace's work starts from — git: a `refs/heads/…` or `refs/remotes/…` ref.
* Absent: the SCM's own default (git: `HEAD`). */
base?: string
+ /** No `base` was named: start from the remote's default branch, brought up to date first, instead of from where
+ * the source checkout is (git: `origin`'s default branch, fetched). Absent: the SCM's own default. */
+ fromDefaultBranch?: boolean
/** The name the workspace's line of work takes — git: its branch. Absent: made up. */
name?: string
/** `name` exists already and is taken as it is, rather than created from `base`. */
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 75c064996..c62aa3cc8 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -90,6 +90,9 @@ describe('routeTask', () => {
const fresh = await routeTask({ ...input, assessment: { ...input.assessment, difficulty: 'high' } }, scoped({ jev: { ok: true, value: { unavailable: 'BUSY' } } }), where as never, opener(), () => 'op')
expect(fresh).toMatchObject({ pick: { kind: 'new', engine: 'claude', model: 'opus', effort: 'high' } })
expect(fresh.next).toContain('"engine":"claude","model":"opus","effort":"high","routeDecisionId":"d1"')
+ // Without a branch the agent starts from the default one, and the hint says how to choose another.
+ expect(fresh.next).toContain('"branchRef":"refs/remotes/origin/BRANCH"')
+ expect(fresh.next).toContain('default branch, fetched first')
// A complete start: every field its schema requires, with the defaults the help gives.
const hint = JSON.parse(/start OPERATION_ID (\{.*\}), then/.exec(fresh.next as string)![1]!)
expect(hint).toEqual({ conversationId: 'g1', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true,
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index e8cbf5267..8a6e8c002 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -191,7 +191,7 @@ export async function routeTask(input: { tabId: string; conversationId: string;
? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}"${decision}}`
: `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: 'Builder', cwd: text(machines.get(verdict.pick.machineId)?.pool?.cwd) ?? assessment.needs.cwd ?? '/absolute/repo/on/that/machine',
worktree: true, requirements: startRequirements(assessment.needs), machineId: verdict.pick.machineId, engine: verdict.pick.engine, model: verdict.pick.model,
- effort: verdict.pick.effort, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : {}) })}, then assign the started agent${decision ? ' with the same routeDecisionId' : ''}.`,
+ effort: verdict.pick.effort, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : {}) })}, then assign the started agent${decision ? ' with the same routeDecisionId' : ''}. It starts from the repository's default branch, fetched first; add "branchRef":"refs/remotes/origin/BRANCH" to start from another branch.`,
}
}
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 37d2f6460..e9f8eb7f0 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -71,6 +71,14 @@ it('resolves a native caller to its exact contribution and rechecks it before ev
expect(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
})
+it('tells the Lead which branch a started agent works from, and how to choose another', async () => {
+ const t = setup()
+ const help = (await t.ask({ action: 'help' }, owner)).help as { start: string; startRequest: Record<string, unknown> }
+ expect(help.start).toContain('default branch, fetched first')
+ expect(help.start).toContain('branchRef')
+ expect(help.startRequest).toMatchObject({ worktree: true, branchRef: 'refs/remotes/origin/BASE_BRANCH' })
+})
+
it('keeps host capacity separate from account authority and closes it on disconnect or identity change', async () => {
const core = fakeCore()
const reserve = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id' }))
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 4aa04f608..70b65c190 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -16,11 +16,11 @@ const HELP = {
messages: 'messages GROUP: read recent messages in a conversation.',
message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]...: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.',
- start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine you can access. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work.',
+ start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine you can access. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',
capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',
- startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, requirements: START_REQUIREMENTS,
+ startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, branchRef: 'refs/remotes/origin/BASE_BRANCH', requirements: START_REQUIREMENTS,
model: 'opus', effort: 'high', routeDecisionId: 'DECISION' },
command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request.',
commands: [
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index 63e8e6e4b..4d1fd7b4e 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -72,6 +72,29 @@ it('uses one native creation receipt and joins its captured group after a lost j
expect(commands.find(c => c.type === 'agent.started')).toMatchObject({ startId: 'start', harnessId: 'native', configuration: { engine: 'claude', model: 'fixture-model', effort: 'high' } })
expect(commands.some(c => c.type === 'work.assign')).toBe(false)
})
+describe('which branch a worktree starts from', () => {
+ const created = async (change: (request: Record<string, unknown>) => void) => {
+ const f = fixture(); change(f.start.request)
+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'op', request: f.start.request }, f.scoped, where, f.open)
+ return f.request.mock.calls.filter(c => c[0] === 'agent_create').map(c => c[1])
+ }
+ it('is the repository\'s default branch when the start names none', async () => {
+ const [payload] = await created(() => {})
+ expect(payload).toMatchObject({ projectSource: 'worktree', gitSource: '/repo', branchName: 'super-tab/start', branchBase: 'default' })
+ expect(payload).not.toHaveProperty('branchRef')
+ })
+ it('is the branch the start names, unchanged', async () => {
+ const [payload] = await created(request => { request.branchRef = 'refs/remotes/origin/feat/mobile' })
+ expect(payload).toMatchObject({ projectSource: 'worktree', branchRef: 'refs/remotes/origin/feat/mobile' })
+ expect(payload).not.toHaveProperty('branchBase')
+ })
+ it('is not asked for when the agent works in the folder itself', async () => {
+ const [payload] = await created(request => { request.worktree = false })
+ expect(payload).toMatchObject({ cwd: '/repo' })
+ expect(payload).not.toHaveProperty('branchBase')
+ expect(payload).not.toHaveProperty('projectSource')
+ })
+})
it('does not recreate when a previously dispatched start loses its native receipt', async () => {
const f = fixture(); f.start.dispatched = true
expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ error: 'START_UNCERTAIN', creationId: 'super-native-receipt' })
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index 9b0c6efa9..f23bc0692 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -121,7 +121,9 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
command: { type: 'agent.startDispatch', startId } }))
const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent',
prompt: `You are joining a shared Super Tab. Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. Do not begin project work yet. Your lead will assign work in conversation ${request.conversationId}. Reply in that conversation using harness super-tab --tab ${input.tabId} post ${request.conversationId} 'your message' UNIQUE_OPERATION_ID. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`,
- ...(request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`, ...(request.branchRef ? { branchRef: request.branchRef } : {}) } : { cwd: request.cwd }),
+ ...(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 }),
}
for (const key of ['permissionMode', 'codexHome', 'gridModel', 'gridName']) if (request[key] !== undefined) payload[key] = request[key]
// The routed model goes on the command line of this session alone. Typing /model into the pane afterwards saves
diff --git a/docs/swarms.md b/docs/swarms.md
index 2ad51a88e..b53897a4d 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -51,6 +51,29 @@ tries the other transport (HTTPS or SSH) once. For a private repository, every
contributing owner needs access to it on that machine, either through
`gh auth login` and `gh auth setup-git` or through an SSH key.
+A Builder starts in a new worktree of the project's checkout on that machine.
+The host clones a project once and reuses the checkout, so it is not kept up to
+date. A start that names no `branchRef` therefore bases its worktree on the
+repository's default branch (`origin/HEAD`, else `origin/main` or
+`origin/master`), fetched first, rather than on whatever commit the checkout was
+left on. If the fetch fails (offline, access refused), the worktree starts from
+the copy of that branch the checkout already has; a repository with no `origin`
+default branch starts from the checkout's current commit, as before. The lead
+passes `branchRef` (`refs/remotes/origin/BRANCH`, fetched first, or
+`refs/heads/BRANCH`) to start from another branch, such as the integration
+branch the work builds on. This is the Swarm start only: New Harness in Desktop
+and the CLI still starts from the folder's current commit unless a branch is
+chosen. On the lead's own machine the same rule applies, so work that is only in
+the lead's checkout (unpushed commits) reaches a Builder through `branchRef`.
+
+A machine contribution accepts a start in the folder this project uses on that
+machine, with one of the engines its owner contributed and the owner's default
+account settings. Any other start is refused as `OUTSIDE_CONTRIBUTION`. The
+refusal names each refused field (`cwd`, `engine`, or any of `codexHome`,
+`gridModel`, `gridName`, `permissionMode`) with what the machine accepts: the
+folder this project uses there and the engines it contributes. It does not
+repeat the values the start sent.
+
Ordinary guest machine sharing does not authorize Swarm controls under the
owner's account. The owner contributes the machine or an agent. The lead's
routing policy still determines eligible engines, capacity and model choices.
@@ -103,7 +126,8 @@ Use the matching backend, CLI and Desktop versions together for this feature:
1. Generate the backend Prisma client and apply its additive schema, including
`SuperTabSessionScope`, before serving the new project commands.
2. Update participating hosts to the CLI with Swarm-scoped contributions and
- project checkout preparation.
+ project checkout preparation. A host on an older CLI ignores the request for
+ the default branch and starts Builders from its checkout's current commit.
3. Install the Desktop build with the project sidebar and Cmd-S entry point.
A signed internal Desktop artifact alone does not update the backend or host