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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(swarm): attach built-in Lead and DEV skills per session (#1533)
0xken15b0c02f3eb02c
diff --git a/cli/e2e/swarmSkills.e2e.ts b/cli/e2e/swarmSkills.e2e.tsnew file mode 100644index 000000000..65fde8f3f--- /dev/null+++ b/cli/e2e/swarmSkills.e2e.ts@@ -0,0 +1,59 @@+/** Real native launch path, with private tmux, throwaway homes and fake engines. */+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, expect, it, onTestFailed } from 'vitest'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'++let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })++it('attaches and restores only the selected Swarm skill for both engines, without native-home skill writes', async () => {+ const d = await IsolatedDaemon.create({ env: { ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential' } })+ daemon = d+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))+ onTestFailed(() => console.log(d.log().split('\n').slice(-100).join('\n')))+ await d.start()+ const c = await LocalClient.connect(d); client = c+ const cwd = join(d.projectsDir, 'shared'); mkdirSync(cwd)+ writeFileSync(join(cwd, 'AGENTS.md'), 'Shared project rules\n')+ const launches = (): Array<{ engine: string; args: string[] }> => {+ try { return readFileSync(join(d.root, 'launch-argv'), 'utf8').trim().split('\n').map(line => JSON.parse(line)) }+ catch { return [] }+ }+ const originals: Array<{ id: string; engine: string; role: string; pointer: string }> = []+ for (const engine of ['claude', 'codex']) for (const role of ['lead', 'dev']) {+ const before = launches().length+ const created = await c.request('agent_create', { engine, cwd, swarmRole: role, permissionMode: 'full', bypassPermission: true, prompt: 'hello' }, 90_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const row = await until('engine to receive its skill pointer', () => launches().slice(before).find(row => row.engine === engine) ?? null, 30_000)+ const args = row.args.join(' ')+ expect(row.args).toContain(engine === 'claude' ? '--dangerously-skip-permissions' : '--dangerously-bypass-approvals-and-sandbox')+ expect(args).toContain(`swarm-${role}/SKILL.md`)+ expect(args).not.toContain(`swarm-${role === 'lead' ? 'dev' : 'lead'}/SKILL.md`)+ const registry = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')) as Array<Record<string, any>>+ const saved = registry.find(row => row.agentId === created.agent.id)!+ expect(saved.permissionMode).toBe('full')+ expect(saved.swarmSkill).toMatchObject({ role, key: expect.any(String) })+ originals.push({ id: created.agent.id, engine, role, pointer: saved.swarmSkill.key })+ await until('engine to bind its conversation', async () => {+ const listed = await c.request('agents_list', {})+ return listed.agents?.some((row: Record<string, any>) => row.id === created.agent.id && row.sessionId) || null+ }, 30_000)+ }+ const restarted = originals[0]!+ const before = launches().length+ const answer = await c.request('agent_restart', { agentId: restarted.id }, 90_000)+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()+ const row = await until('restart to retain the Lead skill', () => launches().slice(before).find(row => row.engine === restarted.engine) ?? null, 30_000)+ expect(row.args.join(' ')).toContain('swarm-lead/SKILL.md')+ expect(readdirSync(join(cwd, '.harness', 'runtime'))).toHaveLength(4)+ expect(readFileSync(join(cwd, 'AGENTS.md'), 'utf8')).toBe('Shared project rules\n')+ const registry = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')) as Array<Record<string, any>>+ for (const original of originals) expect(registry.find(row => row.agentId === original.id)?.swarmSkill).toEqual({ role: original.role, key: original.pointer })+ // Only the project runtime carries these skills, including when engines use their own native homes.+ for (const home of [d.engineConfig.codexHome, join(d.root, 'home', '.claude')]) {+ const files = readdirSync(home, { recursive: true }).map(String)+ expect(files.some(file => file.includes('swarm-lead') || file.includes('swarm-dev'))).toBe(false)+ }+})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 22c0af52b..8f95ab9de 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -158,6 +158,8 @@ export class BackendSocket {* null when the pane opens on an empty input. Validated here — length, and that the engine has a* contract for it — so cli.ts never sees one it cannot hand over. Never logged. */prompt: string | null+ /** Session-scoped built-in instructions for a newly launched Swarm agent. */+ swarmRole?: 'lead' | 'dev'/** The name the pane opens under, instead of the next `agent-N`; null to number it. */name: string | null/** The engine's named agent the pane opens AS (`NAMED_AGENT_ARGS` in engineLaunch.ts; opencodediff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 460a259e3..d95bfc0fe 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -166,6 +166,32 @@ describe('creating an agent', () => {})afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })+ it.each(['claude', 'codex'] as const)('attaches each Swarm role before %s pane dispatch', async engine => {+ for (const role of ['lead', 'dev'] as const) {+ const cwd = folder()+ await setup().create(request({ cwd, engine, swarmRole: role }))+ const pane = vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0]+ expect(pane.swarmSkill).toEqual({ role, key: pane.sessionLabel })+ const place = vi.mocked(agentLaunchArgs).mock.calls.at(-1)![2]+ expect(place.swarmInstructions).toContain(`swarm-${role}/SKILL.md`)+ }+ })++ it('keeps a selected Store harness when attaching a Swarm skill', async () => {+ vi.mocked(installedDsh).mockReturnValueOnce(installed() as never).mockReturnValueOnce(installed() as never)+ expect(await setup().create(request({ dsh: 'blender', swarmRole: 'dev' }))).toMatchObject({ ok: true })+ expect(vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0]).toMatchObject({+ dsh: 'blender', swarmSkill: { role: 'dev' }, env: expect.objectContaining({ HARNESS_DSH: 'blender' }),+ })+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1]?.extraArgs).toContain('--dsh')+ })++ it('refuses an unsafe Swarm runtime before opening a pane', async () => {+ const cwd = folder(['.harness'])+ expect(await setup().create(request({ cwd, swarmRole: 'dev' }))).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })+ expect(createAndRegisterPane).not.toHaveBeenCalled()+ })+it.each(['local', 'remote', 'nonempty', 'unreadable', 'unreadable before trust', 'revoked', 'revoked before trust', 'changed contents', 'replaced workspace', 'changed after enumeration', 'redirected during enumeration', 'error', 'thrown text', 'no trust contract', 'legacy'] as const)('decides local trust before workspace preparation and writes it before final proof: %s', async mode => {const parent = mode === 'redirected during enumeration' ? folder() : rootdiff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 4f365f31e..e7db88670 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -1,3 +1,4 @@+import { prepareSwarmSkill } from '../../lib/swarmSkills.js'import type { NativeLaunch, NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'/*** Creating an agent (`agent_create`): open a fresh pane running the chosen engine in the chosen@@ -336,7 +337,13 @@ export function createAgentCreator({// A harness another agent started says so in the pull requests it opens (lib/agentAttribution.ts), last, as every// relaunch appends it (`buildLaunchOverrides`), and read from the person's settings where this launch reads them.// What Harness tells the agent (its instructions, and the pull request line for one another agent started), last.- const told = agentLaunchArgs(engine, startedBy, { cwd, profile: codexHome, environment: native?.environment })+ const swarmSkill = input.swarmRole ? { role: input.swarmRole, key: label } : undefined+ let swarmInstructions: string | undefined+ if (swarmSkill) {+ try { swarmInstructions = prepareSwarmSkill(cwd, swarmSkill).instructions }+ catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }+ }+ const told = agentLaunchArgs(engine, startedBy, { cwd, profile: codexHome, environment: native?.environment, ...(swarmInstructions ? { swarmInstructions } : {}) })const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...told])// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).@@ -385,6 +392,7 @@ export function createAgentCreator({codexHome,dsh,dshRuntime: dsh ? label : null,+ ...(swarmSkill ? { swarmSkill } : {}),agent,bypassPermission,permissionMode,diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.tsindex 269ee5cf1..0da0b9359 100644--- a/cli/src/core/agents/launch.ts+++ b/cli/src/core/agents/launch.ts@@ -58,7 +58,7 @@ export function createLaunchHelpers({ authority, prepareApiTools, launchOverridesession = structuredClone(session)const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as constif (!current()) return changed- const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, startedBy: session.startedBy ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, configKey, current, native)+ const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, swarmSkill: session.swarmSkill, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, startedBy: session.startedBy ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, configKey, current, native)if (!current()) return changedif (!result.ok && (result.unavailable || result.error === 'AGENT_CHANGED')) return result// Saved-API instructions remain available after an ordinary semantic refusal, as before.diff --git a/cli/src/core/agents/launchAuthority.spec.ts b/cli/src/core/agents/launchAuthority.spec.tsindex b4c88f203..99cddb0bd 100644--- a/cli/src/core/agents/launchAuthority.spec.ts+++ b/cli/src/core/agents/launchAuthority.spec.ts@@ -23,7 +23,7 @@ describe('launch preparation authority', () => {{ cwd: '/replacement' }, { engine: 'codex' }, { sessionId: 'replacement' }, { registeredAt: 3 },{ boundAt: 3 }, { processIdentity: { pid: 42, startMarker: 'replacement' } },{ runtimes: [{ backend: 'tmux', paneId: '%8' }] }, { codexHome: '/profile' },- { dsh: 'fixture/other' }, { dshRuntime: 'other' }, { agent: 'other' },+ { dsh: 'fixture/other' }, { dshRuntime: 'other' }, { swarmSkill: { role: 'dev', key: 'other' } }, { agent: 'other' },{ gridLaunch: { model: 'replacement' } }, { scmLaunch: { kind: 'fixture' } },{ subscriptionModel: 'replacement' }, { permissionMode: 'auto' }, { bypassPermission: true },{ active: false }, { launch: { state: 'held', service: 'store' } }, { externalResume: { token: 'other' } },diff --git a/cli/src/core/agents/launchAuthority.ts b/cli/src/core/agents/launchAuthority.tsindex 3e7014dd7..f898c875b 100644--- a/cli/src/core/agents/launchAuthority.ts+++ b/cli/src/core/agents/launchAuthority.ts@@ -4,7 +4,7 @@ import { terminalRouteKey } from '../../lib/terminalRuntime.js'const identity = (row: RegisteredSession | undefined) => row && JSON.stringify([row.registeredAt, row.boundAt, row.sessionId, row.engine, row.cwd, row.processIdentity,- row.codexHome, row.dsh, row.dshRuntime, row.agent, row.gridLaunch, row.scmLaunch,+ row.codexHome, row.dsh, row.dshRuntime, row.swarmSkill, row.agent, row.gridLaunch, row.scmLaunch,row.subscriptionModel, row.permissionMode, row.bypassPermission, row.active,row.runtimes.map(terminalRouteKey).sort(), row.launch, row.externalResume,])diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 014370a13..bae28567d 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -262,6 +262,19 @@ describe('agent_create, refused before any pane exists', () => {expect(create).not.toHaveBeenCalled()})+ it('passes explicit Swarm roles and refuses invalid role metadata before dispatch', async () => {+ const { ask, create } = setup()+ for (const engine of ['claude', 'codex']) for (const swarmRole of ['lead', 'dev']) {+ await ask({ engine, cwd: '/w', swarmRole })+ expect(vi.mocked(create!).mock.calls.at(-1)![0]).toMatchObject({ engine, swarmRole })+ }+ for (const swarmRole of [7, '', 'reviewer']) {+ expect(await ask({ engine: 'claude', cwd: '/w', swarmRole })).toMatchObject({ error: 'INVALID_SWARM_ROLE' })+ }+ expect(await ask({ engine: 'terminal', cwd: '/w', swarmRole: 'dev' })).toMatchObject({ error: 'INVALID_SWARM_ROLE' })+ expect(await ask({ engine: 'codex', cwd: '/w', swarmRole: 'dev', resumeSessionId: 'old-session' })).toMatchObject({ error: 'INVALID_SESSION' })+ })+it('a first prompt that is not text, too long, or for an engine that cannot take one', async () => {const { ask, create } = setup()expect(await ask({ engine: 'claude', cwd: '/w', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' })diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex 1a77ccf25..ec50af5fe 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -391,6 +391,11 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre}prompt = trimmed || null}+ const swarmRole = payload.swarmRole+ if (swarmRole !== undefined && swarmRole !== null &&+ ((swarmRole !== 'lead' && swarmRole !== 'dev') || (engine !== 'claude' && engine !== 'codex'))) {+ reply({ error: 'INVALID_SWARM_ROLE', detail: 'A Swarm role is lead or dev, for Claude Code or Codex.' }); return+ }// Blank is "number it", the same as absent — a client that sends an empty field is not// asking for an agent with no name.const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null@@ -423,7 +428,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, preif (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{1,127}$/.test(payload.resumeSessionId)) {reply({ error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return}- if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || launchModel.state === 'ok' || dsh || prompt || agent) {+ if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || launchModel.state === 'ok' || dsh || prompt || agent || swarmRole) {reply({ error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }); return}resumeSessionId = payload.resumeSessionId@@ -449,7 +454,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, preif (!parentAgentId) { reply({ error: 'INVALID_STARTED_BY', detail: 'parentAgentId is the agent id of the harness that started it, with startedBy agent' }); return }if (!byAgent(parentAgentId)) parentAgentId = null}- const input = {+ const input: Parameters<CreateAgent>[0] = {engine,cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',// On unless a client says otherwise: a harness works without stopping to ask for each command.@@ -459,6 +464,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, precodexHome,dsh,prompt,+ ...(swarmRole === 'lead' || swarmRole === 'dev' ? { swarmRole } : {}),name,agent,resumeSessionId,diff --git a/cli/src/dsh/runtime.ts b/cli/src/dsh/runtime.tsindex 3950f0099..81f237d25 100644--- a/cli/src/dsh/runtime.ts+++ b/cli/src/dsh/runtime.ts@@ -2,6 +2,7 @@* Create snapshots instructions/env/argv; resume reads that snapshot; fork copies it under a new* key. Toolchains and skill assets stay at their installed package paths, as in spec 1.*/+import { ignoreHarnessRuntime } from '../lib/harnessRuntimeIgnore.js'import { createHash, randomUUID } from 'node:crypto'import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'import { basename, join, resolve } from 'node:path'@@ -160,10 +161,7 @@ export function prepareHarnessLaunch(dsh: InstalledDsh, workspace: string, enginconst ws = realpathSync(workspace)const dir = harnessRuntimeDir(ws, key)ensureRuntimeDir(ws, dir)- const ignoreFile = join(ws, '.harness', '.gitignore')- const ignored = existsSync(ignoreFile) ? readFileSync(ignoreFile, 'utf8') : ''- const ignoreRules = ['runtime/', 'legacy-AGENTS.md'].filter(rule => !ignored.split('\n').includes(rule))- if (ignoreRules.length) writeManagedFile(ignoreFile, `${ignored}${ignored && !ignored.endsWith('\n') ? '\n' : ''}${ignoreRules.join('\n')}\n`)+ ignoreHarnessRuntime(ws)const file = join(dir, 'runtime.json')const from = sourceKey ? join(harnessRuntimeDir(ws, sourceKey), 'runtime.json') : fileif (sourceKey) {diff --git a/cli/src/lib/agentAttribution.spec.ts b/cli/src/lib/agentAttribution.spec.tsindex 925e657f3..efe2dbb58 100644--- a/cli/src/lib/agentAttribution.spec.ts+++ b/cli/src/lib/agentAttribution.spec.ts@@ -68,6 +68,15 @@ describe('what Harness tells an agent as it starts', () => {expect(agentLaunchArgs('codex', null, said, dataDir)).toEqual([])})+ it('keeps Swarm role instructions when generic agent spawning is enabled', () => {+ setAgentSettingsForTest(dataDir, { agentsStartAgents: true })+ for (const engine of ['claude', 'codex']) {+ const args = agentLaunchArgs(engine, null, { cwd: '/w', read: () => null, swarmInstructions: 'Read the swarm-dev skill.' }, dataDir)+ expect(args.join(' ')).toContain('Read the swarm-dev skill.')+ expect(args.join(' ')).not.toContain(HARNESS_INSTRUCTIONS)+ }+ })+it('joins every appended system prompt into one, for Claude Code; leaves other engines\' arguments alone', () => {expect(joinedInstructions('claude', ['--system-prompt-snapshot', 'off', '--append-system-prompt', 'grid', '--agent', 'x', '--append-system-prompt', 'ours'])).toEqual(['--system-prompt-snapshot', 'off', '--agent', 'x', '--append-system-prompt', 'grid\n\nours'])diff --git a/cli/src/lib/agentAttribution.ts b/cli/src/lib/agentAttribution.tsindex 397b68e5e..289d11be4 100644--- a/cli/src/lib/agentAttribution.ts+++ b/cli/src/lib/agentAttribution.ts@@ -28,11 +28,12 @@ export const HARNESS_INSTRUCTIONS = 'You are running in Harness, and the person* A launch’s argv for legacy agent-spawn instructions, read at each launch.* The retired PR branding preference never changes a new launch.*/-export function agentLaunchArgs(engine: string, _startedBy: StartedBy | null | undefined, place: AttributionPlace,+export function agentLaunchArgs(engine: string, _startedBy: StartedBy | null | undefined, place: AttributionPlace & { swarmInstructions?: string },dataDir: string = env.ADAPTER_DATA_DIR): string[] {- const settings = readAgentSettings(dataDir)+ // Swarm roles route through their Lead; generic spawning advice would invite private worker teams.+ const instructions = place.swarmInstructions ?? (readAgentSettings(dataDir).agentsStartAgents ? HARNESS_INSTRUCTIONS : null)return agentInstructionArgs(engine, {- instructions: settings.agentsStartAgents ? HARNESS_INSTRUCTIONS : null,+ instructions,prLine: null,}, place)}diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 42a9cf9cd..761fd2644 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -1,3 +1,4 @@+import type { SwarmSkill } from './swarmSkills.js'/*** Open a tmux pane for a new agent and claim it in the registry, retrying the claim up to* `maxAttempts` times.@@ -38,6 +39,7 @@ export interface CreateAgentPaneDeps<Ref extends TerminalRuntimeRef = TerminalRuscmLaunchRecord?: ScmLaunchRecord | nullcodexHome?: string | nulldsh?: string | null+ swarmSkill?: SwarmSkilldshRuntime?: string | nullagent?: string | nullbypassPermission?: boolean@@ -80,6 +82,7 @@ export interface CreateAgentPaneDeps<Ref extends TerminalRuntimeRef = TerminalRucodexHome?: string | null/** The domain-specific harness this agent is created as, if any. */dsh?: string | null+ swarmSkill?: SwarmSkilldshRuntime?: string | null/** The engine's named agent the pane opens as (`agent_create`'s `agent`); kept on the row so a* relaunch opens as it again. Already in `argv` — this is the record, not the launch. */@@ -140,6 +143,7 @@ export async function createAndRegisterPane<Ref extends TerminalRuntimeRef = TercodexHome: deps.codexHome,dsh: deps.dsh,dshRuntime: deps.dshRuntime,+ ...(deps.swarmSkill ? { swarmSkill: deps.swarmSkill } : {}),agent: deps.agent,bypassPermission: deps.bypassPermission,permissionMode: deps.permissionMode,diff --git a/cli/src/lib/harnessRuntimeIgnore.ts b/cli/src/lib/harnessRuntimeIgnore.tsnew file mode 100644index 000000000..e504cabc1--- /dev/null+++ b/cli/src/lib/harnessRuntimeIgnore.ts@@ -0,0 +1,28 @@+/** Shared by Store and Swarm launches so session files never become project source. */+import { randomUUID } from 'node:crypto'+import { closeSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'++/** Call after validating the workspace's runtime directories as plain directories. */+export function ignoreHarnessRuntime(workspace: string): void {+ const file = join(workspace, '.harness', '.gitignore')+ let mode = 0o600, before = ''+ try {+ const stat = lstatSync(file)+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Harness ignore file is not a plain file: ${file}`)+ mode = stat.mode & 0o777+ before = readFileSync(file, 'utf8')+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ }+ const missing = ['runtime/', 'legacy-AGENTS.md'].filter(rule => !before.split('\n').includes(rule))+ if (!missing.length) return+ // Publish whole bytes: a killed launch must not leave session files visible to Git.+ const temporary = `${file}.${randomUUID()}.tmp`+ const fd = openSync(temporary, 'wx', mode)+ try {+ try { writeFileSync(fd, `${before}${before && !before.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`); fsyncSync(fd) }+ finally { closeSync(fd) }+ renameSync(temporary, file)+ } finally { rmSync(temporary, { force: true }) }+}diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex e96a608b0..b8762d82d 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -1,3 +1,4 @@+import { prepareSwarmSkill, type SwarmSkill } from './swarmSkills.js'/*** What a pane has to be launched WITH, beyond the engine's own argv, for the engine to come back* where it was: on the same grid with the same credential, or under the same Codex profile.@@ -125,6 +126,7 @@ export interface LaunchSource extends NativeLaunchSource {dsh?: string | null/** The session-scoped runtime bundle. Older rows use their stable agent id. */dshRuntime?: string | null+ swarmSkill?: SwarmSkill/** The workspace, for the DSH's `${workspace}` — the registry row's `cwd`. */cwd?: string | null/**@@ -280,8 +282,15 @@ export async function prepareLaunchOverrides(}// What Harness tells the agent rides every relaunch, in the slot `agent_create` gave it: last. Read again each// time, with the person's switches and settings as they are now.+ let swarmInstructions: string | undefined+ if (source.swarmSkill) {+ try {+ if (!source.cwd) throw new Error('The Swarm session has no saved workspace')+ swarmInstructions = prepareSwarmSkill(source.cwd, source.swarmSkill).instructions+ } catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }+ }const told = agentLaunchArgs(engine, source.startedBy, {- cwd: source.cwd ?? null, profile: source.codexHome, environment: native?.environment, read: deps.readAttribution,+ cwd: source.cwd ?? null, profile: source.codexHome, environment: native?.environment, read: deps.readAttribution, ...(swarmInstructions ? { swarmInstructions } : {}),})if (told.length) overrides = { ...overrides, extraArgs: joinedInstructions(engine, [...overrides.extraArgs, ...told]) }return { ok: true, overrides: { ...overrides, ...(native ? { native, env: { ...overrides.env, ...native.environment } } : {}), clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.tsindex a6c5e5a75..ae8a0d326 100644--- a/cli/src/lib/productUsageSignals.ts+++ b/cli/src/lib/productUsageSignals.ts@@ -14,11 +14,11 @@ const actions = { agent_create: 'create', agent_resume: 'resume', agent_restart:} as constconst unmeasured = (..._args: unknown[]): void => {}const setup = new Set(['TMUX_UNAVAILABLE', 'PTY_HOST_UNAVAILABLE', 'TMUX_TOO_OLD_FOR_DSH', 'TMUX_TOO_OLD_FOR_GRID',- 'ENGINE_UNAVAILABLE', 'NATIVE_LAUNCH_HELD', 'DSH_MATERIALIZE_FAILED', 'SPAWN_FAILED', 'REGISTRATION_FAILED', 'GRID_CONFIG_FAILED'])+ 'ENGINE_UNAVAILABLE', 'NATIVE_LAUNCH_HELD', 'DSH_MATERIALIZE_FAILED', 'SWARM_SKILL_FAILED', 'SPAWN_FAILED', 'REGISTRATION_FAILED', 'GRID_CONFIG_FAILED'])const auth = new Set(['UNAUTHORIZED', 'AUTH_REQUIRED', 'LOGIN_REQUIRED', 'OWNER_REQUIRED', 'E2EE_REQUIRED'])const unavailable = new Set(['SERVICE_UNAVAILABLE', 'SERVICE_FAILED', 'GRID_UNAVAILABLE', 'API_UNAVAILABLE','UNSUPPORTED', 'UNSUPPORTED_ON_REMOTE', 'TIMEOUT', 'NATIVE_UNAVAILABLE'])-const invalid = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'CWD_NOT_FOUND', 'INVALID_GRID', 'INVALID_DSH',+const invalid = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'CWD_NOT_FOUND', 'INVALID_GRID', 'INVALID_DSH', 'INVALID_SWARM_ROLE','INVALID_MODEL', 'INVALID_PERMISSION_MODE', 'INVALID_CREATION_ID', 'INVALID_PROJECT_SOURCE', 'WORKTREE_BUSY'])const resumeReasons = new Map<string, ResumeReason>([['TMUX_UNAVAILABLE', 'runtime_unavailable'], ['NATIVE_LAUNCH_HELD', 'runtime_unavailable'],diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.tsindex f4762e7fe..a93a419d5 100644--- a/cli/src/lib/registry.spec.ts+++ b/cli/src/lib/registry.spec.ts@@ -1835,6 +1835,21 @@ describe('registry across a reboot and pane loss', () => {expect(bound?.entry.subscriptionModel).toBe('opus')})+ it('preserves Swarm role and runtime key across hooks and reload', async () => {+ const { registry } = await loadRegistryModule()+ registry.load()+ const swarmSkill = { role: 'dev' as const, key: 'harness-claude-worker' }+ const pending = registry.openPendingAgent({ engine: 'claude', cwd: dataDir,+ runtimes: [{ backend: 'tmux', paneId: '%21' }], swarmSkill })!+ const transcriptPath = join(dataDir, 'swarm.jsonl')+ writeFileSync(transcriptPath, '{}\n')+ expect(registry.register({ engine: 'claude', sessionId: 'swarm', transcriptPath, cwd: dataDir, tmuxPane: '%21' })?.entry.swarmSkill).toEqual(swarmSkill)+ const { registry: reloaded } = await loadRegistryModule()+ reloaded.load()+ expect(reloaded.byAgent(pending.agentId)?.swarmSkill).toEqual(swarmSkill)+ expect(reloaded.releaseEngine(pending.agentId, true)?.swarmSkill).toBeUndefined()+ })+it('keeps strict conversation resume after the engine binds and the daemon reloads', async () => {const transcriptPath = join(dataDir, 'session-resumed.jsonl')writeFileSync(transcriptPath, '{}\n')diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 6ba6d8d4a..b23b5034c 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -1,3 +1,4 @@+import { parseSwarmSkill, type SwarmSkill } from './swarmSkills.js'/*** Registry of process-owned AGENTS — one per supported top-level engine process in a tmux pane.*@@ -202,6 +203,8 @@ export interface RegisteredSession {dsh?: string | null/** Stable key of the session-scoped harness runtime; preserved by bind, restore and fork. */dshRuntime?: string | null+ /** Role and stable key of this Swarm session; absent for ordinary sessions. */+ swarmSkill?: SwarmSkill/*** The engine's own named agent this pane was opened as (`agent_create`'s `agent`; opencode* `--agent <name>`), or null for a general session. Chosen at creation and carried into every@@ -1319,6 +1322,7 @@ class Registry {...normalizedForkedFrom((raw as { forkedFrom?: unknown }).forkedFrom),dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),dshRuntime: typeof raw.dshRuntime === 'string' && raw.dshRuntime ? raw.dshRuntime : null,+ ...(parseSwarmSkill(raw.swarmSkill) ? { swarmSkill: parseSwarmSkill(raw.swarmSkill) } : {}),agent: normalizedAgentName((raw as { agent?: unknown }).agent),...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),...(rawGridLaunch ? { gridWebSearch: normalizedGridWebSearch(raw?.gridWebSearch) } : {}),@@ -1629,6 +1633,7 @@ class Registry {codexHome?: string | nulldsh?: string | nulldshRuntime?: string | null+ swarmSkill?: SwarmSkill/** The engine's named agent the pane was opened as (`agent_create`'s `agent`), validated upstream. */agent?: string | nullbypassPermission?: boolean@@ -1677,6 +1682,7 @@ class Registry {hermesHome: null,dsh: input.dsh ?? null,dshRuntime: input.dshRuntime ?? null,+ ...(input.swarmSkill ? { swarmSkill: input.swarmSkill } : {}),agent: normalizedAgentName(input.agent),...(input.bypassPermission ? { bypassPermission: true } : {}),...(permissionModeName(input.permissionMode) ? { permissionMode: input.permissionMode } : {}),@@ -2026,6 +2032,7 @@ class Registry {hermesHome: input.hermesHome ?? existing?.hermesHome ?? null,dsh: existing?.dsh ?? null,dshRuntime: existing?.dshRuntime ?? null,+ ...(existing?.swarmSkill ? { swarmSkill: existing.swarmSkill } : {}),agent: existing?.agent ?? null,// Carried forward like `agent`: dropped at the first hook, a restart of a harness another agent started came// back without its pull request line (found by e2e/agentClient.e2e.ts).@@ -2183,7 +2190,7 @@ class Registry {this.terminalAvailableAgents.delete(agentId)// The archived conversation owns the original Harness ID. Preserve the physical shell under// a new identity, without sending input, stopping processes or claiming its route twice.- const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, dshRuntime: null, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : original+ const entry = separateShell ? { ...original, agentId: randomUUID(), dsh: null, dshRuntime: null, swarmSkill: undefined, agent: null, defaultName: this.automaticName('Terminal', new Date()) } : original// The shell under a new identity is the person's, not a harness an agent started: kept, a window took the new id for// a new child and opened the shell beside the agent, even after the person had closed the child (review of #1217).if (separateShell) delete entry.parentAgentIddiff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsnew file mode 100644index 000000000..e19413ddd--- /dev/null+++ b/cli/src/lib/swarmSkills.spec.ts@@ -0,0 +1,115 @@+import { execFileSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { prepareSwarmSkill, parseSwarmSkill } from './swarmSkills.js'+import { agentLaunchArgs } from './agentAttribution.js'+import { buildLaunchOverrides } from './launchOverrides.js'+import { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'++const roots: string[] = []+const fixture = () => { const root = mkdtempSync(join(tmpdir(), 'swarm-skills-')); roots.push(root); return root }+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })++describe('built-in Swarm skills', () => {+ it.each(['claude', 'codex'] as const)('gives %s only its role skill in each session, preserving the shared project', engine => {+ const workspace = fixture(), data = fixture()+ writeFileSync(join(workspace, 'AGENTS.md'), 'Project rules\n')+ for (const role of ['lead', 'dev'] as const) {+ const skill = { role, key: `${engine}-${role}` }+ const prepared = prepareSwarmSkill(workspace, skill)+ expect(prepared.file.startsWith(join(realpathSync(workspace), '.harness', 'runtime'))).toBe(true)+ const text = readFileSync(prepared.file, 'utf8')+ expect(text).toContain(`name: swarm-${role}`)+ if (role === 'lead') expect(text).toContain('goal, changes, constraints, owned code and acceptance checks')+ else {+ expect(text).toContain('Needs:')+ expect(text).toContain("Do not touch other groups' code.")+ }+ expect(text).not.toContain(`name: swarm-${role === 'lead' ? 'dev' : 'lead'}`)+ expect(readdirSync(dirname(dirname(prepared.file)))).toEqual([`swarm-${role}`])+ const args = agentLaunchArgs(engine, null, { cwd: workspace, read: () => null, swarmInstructions: prepared.instructions }, data)+ expect(args.join(' ')).toContain(prepared.file)+ expect(args.join(' ')).not.toContain('harness new')+ }+ expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toBe('Project rules\n')+ expect(readdirSync(workspace).sort()).toEqual(['.harness', 'AGENTS.md'])+ expect(readdirSync(data)).toEqual([])+ })++ it('keeps standalone session skills out of Git, including git add -A', () => {+ const workspace = fixture()+ execFileSync('git', ['init', '-q', workspace])+ prepareSwarmSkill(workspace, { role: 'dev', key: 'standalone' })+ execFileSync('git', ['add', '-A'], { cwd: workspace })+ const staged = execFileSync('git', ['ls-files'], { cwd: workspace, encoding: 'utf8' })+ expect(staged).not.toContain('SKILL.md')+ expect(staged.trim()).toBe('.harness/.gitignore')+ })++ it('preserves custom ignore rules and adds the Store runtime rules only once', () => {+ const workspace = fixture(), saved = { role: 'lead' as const, key: 'one' }+ mkdirSync(join(workspace, '.harness'))+ const file = join(workspace, '.harness', '.gitignore')+ writeFileSync(file, '# Mine\nprivate-data')+ prepareSwarmSkill(workspace, saved)+ expect(readFileSync(file, 'utf8')).toBe('# Mine\nprivate-data\nruntime/\nlegacy-AGENTS.md\n')+ prepareSwarmSkill(workspace, saved)+ expect(readFileSync(file, 'utf8')).toBe('# Mine\nprivate-data\nruntime/\nlegacy-AGENTS.md\n')+ })++ it('refuses a redirected runtime ignore file without modifying its target', () => {+ const workspace = fixture(), target = join(fixture(), 'rules')+ mkdirSync(join(workspace, '.harness'))+ writeFileSync(target, 'Keep these rules')+ symlinkSync(target, join(workspace, '.harness', '.gitignore'))+ expect(() => prepareSwarmSkill(workspace, { role: 'dev', key: 'one' })).toThrow(/symlink|plain/i)+ expect(readFileSync(target, 'utf8')).toBe('Keep these rules')+ })++ it('keeps the session skill bytes on retry and isolates a different session', () => {+ const workspace = fixture(), saved = { role: 'lead' as const, key: 'first' }+ const first = prepareSwarmSkill(workspace, saved)+ writeFileSync(first.file, 'saved session instructions')+ expect(prepareSwarmSkill(workspace, saved)).toEqual(first)+ expect(readFileSync(first.file, 'utf8')).toBe('saved session instructions')+ const next = prepareSwarmSkill(workspace, { role: 'lead', key: 'second' })+ expect(next.file).not.toBe(first.file)+ expect(readFileSync(next.file, 'utf8')).toContain('name: swarm-lead')+ })++ it.each(['.harness', 'runtime', 'skill', 'file'])('refuses a redirected managed %s without writing through it', part => {+ const workspace = fixture(), outside = fixture(), saved = { role: 'dev' as const, key: 'one' }+ const first = prepareSwarmSkill(workspace, saved)+ const path = part === '.harness' ? join(workspace, '.harness') : part === 'runtime' ? join(workspace, '.harness', 'runtime') : part === 'skill' ? dirname(first.file) : first.file+ rmSync(path, { recursive: true, force: true })+ symlinkSync(outside, path)+ expect(() => prepareSwarmSkill(workspace, saved)).toThrow(/plain|symlink/i)+ expect(readdirSync(outside)).toEqual([])+ })++ it('validates persisted role metadata and refuses an empty key', () => {+ for (const value of [null, undefined, {}, { role: 'reviewer', key: 'x' }, { role: 'dev', key: '' }, { role: 'lead', key: 7 }]) expect(parseSwarmSkill(value)).toBeUndefined()+ expect(parseSwarmSkill({ role: 'dev', key: 'x' })).toEqual({ role: 'dev', key: 'x' })+ expect(() => prepareSwarmSkill(fixture(), { role: 'lead', key: '' })).toThrow()+ })++ it.each(['claude', 'codex'] as const)('restores %s skill on relaunch without overwriting the saved content', async engine => {+ const cwd = fixture(), swarmSkill = { role: 'dev' as const, key: 'original' }+ const first = prepareSwarmSkill(cwd, swarmSkill)+ const result = await buildLaunchOverrides({ capabilities: async () => ({ sessionEnv: true }), installCodexHooks: () => true, machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(),+ writeGridConfigDir: async () => '/unused', readCodexConfig: () => null, readAttribution: () => null }, engine, { cwd, swarmSkill }, 'new-registry-id')+ expect(result.ok).toBe(true)+ if (result.ok) expect(result.overrides?.extraArgs.join(' ')).toContain(first.file)+ expect(readdirSync(join(cwd, '.harness', 'runtime'))).toHaveLength(1)+ })++ it('refuses relaunch with a missing workspace or a redirected runtime', async () => {+ const cwd = fixture(), swarmSkill = { role: 'dev' as const, key: 'original' }+ symlinkSync(fixture(), join(cwd, '.harness'))+ const deps = { capabilities: async () => ({ sessionEnv: true }), installCodexHooks: () => true, machine: () => ({ hermesSystemManaged: false }), gridLaunch: gridLaunchInProcess(), writeGridConfigDir: async () => '/unused' }+ expect(await buildLaunchOverrides(deps, 'claude', { swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })+ expect(await buildLaunchOverrides(deps, 'claude', { cwd, swarmSkill }, 'a')).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })+ })+})diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsnew file mode 100644index 000000000..b171cc576--- /dev/null+++ b/cli/src/lib/swarmSkills.ts@@ -0,0 +1,72 @@+/** Built into the CLI so contributed machines need no separately installed plugin. */+import { ignoreHarnessRuntime } from './harnessRuntimeIgnore.js'+import { createHash } from 'node:crypto'+import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'+import { join, relative, sep } from 'node:path'++export type SwarmRole = 'lead' | 'dev'+export interface SwarmSkill { role: SwarmRole; key: string }++export function parseSwarmSkill(value: unknown): SwarmSkill | undefined {+ if (!value || typeof value !== 'object') return undefined+ const { role, key } = value as Partial<SwarmSkill>+ return (role === 'lead' || role === 'dev') && typeof key === 'string' && key.length > 0 ? { role, key } : undefined+}++const skills: Record<SwarmRole, string> = {+ lead: `---+name: swarm-lead+description: Use when coordinating a Harness Swarm project as its Lead or Product Manager, before discussing, splitting or assigning work.+---+# Coordinate a Swarm project++1. Restate the request briefly and mark guesses. Ask one question at a time in project chat, starting with what changes the approach: goal, scope, what must not be done, and what counts as done. State the size: small, medium, or large. Large work needs a written description.+2. Split only after the task giver or project owner clearly approves the description. Others' opinions and a vague “ok” do not replace that approval. A small, clear request (a question or one-spot fix) can be done immediately; say what you did. If told “just do it”, skip questions and state important choices.+3. Give numbered options, mark one default, and set a deadline. When it passes, record and use that default for choices already authorized. A deadline never supplies the approval required above.+4. Discuss → approved description → groups → route → assign. Every group carries goal, changes, constraints, owned code and acceptance checks. Multi-part work or work taking about 15 minutes or more goes to Swarm agents in groups. Coordinate it; your own subagents only read and look things up.+5. When a worker finishes, decide reuse, keep, or stop; prefer stop unless more work is coming soon. Never leave a worker idle without an explicit decision. Check workers silent too long and reassign work stalled too long. Report on-screen trust, sign-in or permission questions in chat immediately, naming the machine owner who can answer.+6. Summarize long threads once and record important decisions once. Keep the project chat informed of progress, blockers and next steps.+`,+ dev: `---+name: swarm-dev+description: Use when receiving or carrying out an assigned workgroup as a Harness Swarm engineer or worker, including review and handoff.+---+# Finish assigned work++1. Say in the group chat that you took the assignment and what you are doing.+2. Follow a multi-step plan in order. For changed behavior, write a test, watch it fail for the expected reason, implement the smallest fix, then verify it passes. Debug systematically: reproduce, inspect evidence, find the cause, test a hypothesis. Check each review finding against the code before changing it. Run relevant checks and read their results before saying done.+3. If blocked, post a “Needs:” line saying what you need, then continue independent parts. Interpret ambiguous answers in their narrowest safe sense and record that interpretation.+4. Work as if nobody will return to help: finish completely and test everything testable. Package any remaining person or device action as one clear step.+5. Every handoff includes “Ready: yes/no”, evidence, the revision and useful links, and what remains unverified. Distinguish local checks from runs in the real environment.+6. Ask the Lead to route work instead of opening your own subagents to split it. Do not touch other groups' code. Merge, push or open a PR only when told.+7. Print little to save quota; keep useful progress and blocker reports in the group chat.+`,+}++/** A session owns these bytes; retries and CLI upgrades cannot change a running session's skill.+ * No project-wide native skill links: two roles may share a workspace. */+export function prepareSwarmSkill(workspace: string, saved: SwarmSkill): { file: string; instructions: string } {+ if (!parseSwarmSkill(saved)) throw new Error('A Swarm skill needs a role and session key')+ const root = realpathSync(workspace)+ const dir = join(root, '.harness', 'runtime', createHash('sha256').update(saved.key).digest('hex'), 'swarm', 'skills', `swarm-${saved.role}`)+ let path = root+ for (const part of relative(root, dir).split(sep)) {+ path = join(path, part)+ try {+ const stat = lstatSync(path)+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Swarm skill directory is not a plain directory: ${path}`)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ mkdirSync(path, { mode: 0o700 })+ }+ }+ ignoreHarnessRuntime(root)+ const file = join(dir, 'SKILL.md')+ if (existsSync(file)) {+ const stat = lstatSync(file)+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Swarm skill is not a plain file: ${file}`)+ // Read now so an unreadable saved skill refuses launch, rather than silently dropping the role.+ readFileSync(file, 'utf8')+ } else writeFileSync(file, skills[saved.role], { flag: 'wx', mode: 0o600 })+ return { file, instructions: `Use the built-in swarm-${saved.role} skill for this session. Before working, read ${JSON.stringify(file)} with your file or shell tool.` }+}diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex bbe164692..0599969ba 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -83,6 +83,8 @@ describe('Super Tab native delivery handoff', () => {'In reply to message question-2. Read it before interpreting the answer:'), 'team:service:superTabs:delivery')expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('Message message from Collaborator:\nYes, keep them.')+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('On Claude Code or Codex, Leads use swarm-lead and workers use swarm-dev.')+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('Leads coordinate: assign multi-part or 15+ minute work to Swarm agent groups; do only answers, lookups and small fixes yourself; your subagents only read/look up.')})it('keeps a slow configuration observation out of the native delivery and lease path', async () => {diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex b2c1e6f96..5d10d33a4 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -529,7 +529,7 @@ export class SuperTabHost {return `You are participating in a shared Super Tab conversation (${group}). Other humans and agents see messages posted there.\n`+ `Read its state: ${command} status\nRead this conversation: ${command} messages ${shellQuote(group)}\n`+ `Reply there: ${command} post ${shellQuote(group)} 'your message' UNIQUE_OPERATION_ID --reply-to ${shellQuote(String(message.id))}\n`- + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Each task needs goal, changes, constraints, owned code and acceptance checks. Leads coordinate: multi-part work or work over about 15 minutes goes to Swarm agents in groups; a Lead does only small work itself and uses its own subagents only to read and look things up.\n`+ + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Each task needs goal, changes, constraints, owned code and acceptance checks. On Claude Code or Codex, Leads use swarm-lead and workers use swarm-dev. Leads coordinate: assign multi-part or 15+ minute work to Swarm agent groups; do only answers, lookups and small fixes yourself; your subagents only read/look up.\n`+ `Ask questions and post results in this conversation. ${SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`+ native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`+ (files ? `${message.text ? '\n\n' : ''}${files}` : '')diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex f0f5e45ca..704457ce8 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -62,7 +62,7 @@ describe('Swarm permission mode', () => {const result = await startAgent({ action: 'resume', tabId: 'tab', startId: 'start', hostDispatch }, f.scoped, where, f.open)expect(result).toMatchObject({ ok: true })const payload = f.request.mock.calls.find(c => c[0] === 'agent_create')![1]!- expect(payload.permissionMode).toBe('full')+ expect(payload).toMatchObject({ permissionMode: 'full', bypassPermission: true, swarmRole: 'dev' })const argv = buildEngineCommandArgv(engine, { permissionMode: String(payload.permissionMode) })expect(argv).toContain(engine === 'claude' ? '--dangerously-skip-permissions' : '--dangerously-bypass-approvals-and-sandbox')}@@ -201,6 +201,20 @@ const expectSwitchTo = (f: Parameters<typeof switchCall>[0], selectedModel: striexpect(call[2]).toBeGreaterThan(50_000)expect(call[2]).toBeLessThanOrEqual(60_000)}+it.each(['claude', 'codex', 'opencode'])('only tells supported %s workers to use their built-in skill', async engine => {+ const f = fixture()+ f.start.request.engine = engine+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'role-prompt', request: f.start.request }, f.scoped, where, f.open)+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!+ if (engine === 'claude' || engine === 'codex') {+ expect(payload.prompt).toContain('swarm-dev')+ expect(payload.swarmRole).toBe('dev')+ } else {+ expect(payload.prompt).not.toContain('swarm-dev')+ expect(payload.swarmRole).toBeUndefined()+ }+})+it('asks for an owner contribution instead of widening a guest machine connection', async () => {const f = fixture({ guest: true })expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'guest-start', request: f.start.request }, f.scoped, where, f.open))@@ -217,6 +231,7 @@ it('uses one native creation receipt and joins its captured group after a lost jexpect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ ok: true, harnessId: 'native', agentId: 'worker' })const launches = f.request.mock.calls.filter(c => c[0] === 'agent_create')expect(launches).toHaveLength(1)+ expect(launches[0][1]).toMatchObject({ swarmRole: 'dev' })expect(f.open).toHaveBeenCalledWith(where, 'target')const commands = f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).filter(Boolean)expect(commands.find(c => c.type === 'agent.started')).toMatchObject({ startId: 'start', harnessId: 'native', configuration: { engine: 'claude', model: 'fixture-model', effort: 'high' } })diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 1d731a9cf..f5af4c641 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -16,7 +16,7 @@ const number = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v :const PRE_DISPATCH_REFUSALS = new Set(['INVALID_ENGINE', 'INVALID_CWD', 'INVALID_PROJECT_SOURCE', 'INVALID_REPOSITORY','INVALID_GRID', 'INVALID_CODEX_HOME', 'INVALID_DSH', 'INVALID_PROMPT',- 'PROMPT_TOO_LONG', 'PROMPT_UNSUPPORTED', 'INVALID_AGENT', 'AGENT_UNSUPPORTED',+ 'INVALID_SWARM_ROLE', 'PROMPT_TOO_LONG', 'PROMPT_UNSUPPORTED', 'INVALID_AGENT', 'AGENT_UNSUPPORTED','INVALID_PERMISSION_MODE', 'INVALID_SESSION', 'INVALID_STARTED_BY', 'UNSUPPORTED_ON_REMOTE',])// A daemon that cannot take the launch model answers these before it makes a receipt, so the same creation id can be@@ -143,7 +143,8 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher// Engines without a full mode retain their existing approving launch flags.const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: true,...(permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),- 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.`,+ ...(['claude', 'codex'].includes(String(request.engine)) ? { swarmRole: 'dev' } : {}),+ prompt: `You are joining a shared Super Tab. ${['claude', 'codex'].includes(String(request.engine)) ? 'Use the built-in swarm-dev skill. ' : ''}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}`,// 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 }),diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 097864305..c32189591 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -13606,6 +13606,7 @@ class AppNotifier extends ChangeNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,@@ -13628,6 +13629,7 @@ class AppNotifier extends ChangeNotifier {// The harness this agent is created from. `engine` above is its BASE —// the machine refuses the pair when they disagree (`INVALID_DSH`).'dsh': ?dsh,+ if (engine == 'claude' || engine == 'codex') 'swarmRole': ?swarmRole,'gridModel': ?model?.id,'gridName': ?model?.grid,// A first message the engine is opened with, and the pane's name beforediff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dartindex a03dd00c5..ccab403b3 100644--- a/desktop/lib/state/harness_launch_integration.dart+++ b/desktop/lib/state/harness_launch_integration.dart@@ -19,8 +19,10 @@ class HarnessLaunchIntegration {this.initialTask,this.engines,this.forcedPermissionMode,+ this.swarmRole,});final String creationId, actionLabel;+ final String? swarmRole;// Restores the person's original request from a destination launch journal.final String? initialTask;// The only agents this destination may start, or null for any.diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex a691d2019..3ad8968ce 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -4077,6 +4077,7 @@ class NewHarnessController extends ChangeNotifier {: null,model: model,dsh: harness,+ swarmRole: integration?.swarmRole,// Sent exactly as written; an agent that cannot take one is never sent it.prompt: takesTask && files.isEmpty && launchMessage.isNotEmpty? launchMessagediff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex d4cb5bbb7..6ad532a4d 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -60,6 +60,7 @@ class SuperTabLaunch {forcedPermissionMode: 'full',creationId: saved['creationId'] as String? ?? superTabOperationId(),initialTask: saved['initialMessage'] as String?,+ swarmRole: saved['lead'] == true ? 'lead' : 'dev',actionLabel: saved['newProject'] == true? 'New Project': saved['lead'] == truediff --git a/desktop/lib/super_tabs/launch_prompt.dart b/desktop/lib/super_tabs/launch_prompt.dartindex 6959e5031..a5905b774 100644--- a/desktop/lib/super_tabs/launch_prompt.dart+++ b/desktop/lib/super_tabs/launch_prompt.dart@@ -7,16 +7,15 @@ String superTabLaunchPrompt({required bool lead,}) =>'Harness Swarm agent. '- '${lead ? 'You lead the project. Discuss first; build when authorized. ' : ''}'+ '${lead ? 'You lead this project. Discuss first; build when authorized. On Claude Code or Codex, use swarm-lead. Coordinate: assign multi-part or 15+ minute work to Swarm agent groups; do only answers, lookups and small fixes yourself; your subagents only read/look up. ' : 'On Claude Code or Codex, use swarm-dev. '}''Use `harness super-tab --tab $tabId` subcommands. ''First: `status`. Retry AGENT_UNAVAILABLE briefly; do not work or post before registration. ''Read `messages $conversationId` for the full request; if empty, ask what to work on. '- 'Reply there: `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. '+ 'Reply: `post GROUP "message" UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`. ''Use --reply-to for existing messages; answer each message once, do not post again. Retry lost replies with the same operation ID and text. '- 'Terminal output is not shared chat. If the sandbox blocks this command, request permission. Use `help` for syntax. '- '${lead ? 'Before work or assignment, use `route GROUP JSON` with difficulty, risk and size (small, medium or large); use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}'- '${lead ? 'Put multi-part or 15+ minute work in Swarm agent groups. Do only answers, lookups and small fixes yourself; your subagents only read and look up. ' : ''}'+ 'Terminal output is not shared chat. If sandbox blocks commands, request permission. Use `help` for syntax. '+ '${lead ? 'Before work/assignment, `route GROUP JSON` with difficulty, risk, size (small, medium or large); use routeDecisionId or explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}''Reuse agents and groups. Each task needs goal, changes, constraints, owned paths, checks. '"${lead ? 'When a worker finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. ' : ''}"- 'Write like a helpful colleague: answer first, in their language, under about 150 words unless asked. Hide commands, internal IDs and field names. Give results with revision/links. '- '${lead ? 'Update Lead chat: plan, progress, blockers, next steps. At the project cadence, read new reports and consolidate them. No per-turn summarizer. Answer questions, serious blockers and completion immediately. On scheduled requests use project.report for updates or text:null when nothing changed. Scope workgroups and sessions to this project.' : ''}';+ 'Be a helpful colleague: answer first, in their language, under 150 words unless asked. Hide commands, internal IDs and field names. Give results with revision/links. '+ '${lead ? 'Update Lead chat: plan, progress, blockers, next steps. At project cadence, read new reports and consolidate them. No per-turn summarizer. Answer questions, blockers and completion immediately. On scheduled requests use project.report for updates or text:null when nothing changed. Scope workgroups and sessions to this project.' : ''}';diff --git a/desktop/test/desktop_compact_launch_test.dart b/desktop/test/desktop_compact_launch_test.dartindex 93bbdb26a..b8e4d499b 100644--- a/desktop/test/desktop_compact_launch_test.dart+++ b/desktop/test/desktop_compact_launch_test.dart@@ -101,6 +101,7 @@ class _CompactApp extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/desktop_composer_layout_test.dart b/desktop/test/desktop_composer_layout_test.dartindex fe7655d67..bcf61db04 100644--- a/desktop/test/desktop_composer_layout_test.dart+++ b/desktop/test/desktop_composer_layout_test.dart@@ -122,6 +122,7 @@ class _ReviewApp extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/desktop_new_harness_edge_test.dart b/desktop/test/desktop_new_harness_edge_test.dartindex 4ddf1567d..76163442e 100644--- a/desktop/test/desktop_new_harness_edge_test.dart+++ b/desktop/test/desktop_new_harness_edge_test.dart@@ -135,6 +135,7 @@ class _App extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dartindex fa8aba3c3..8c15fea5e 100644--- a/desktop/test/first_workspace_test.dart+++ b/desktop/test/first_workspace_test.dart@@ -84,6 +84,7 @@ class _FirstUseApp extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_choices_layout_test.dart b/desktop/test/new_agent_choices_layout_test.dartindex 36b359be9..de2f4e6d5 100644--- a/desktop/test/new_agent_choices_layout_test.dart+++ b/desktop/test/new_agent_choices_layout_test.dart@@ -69,6 +69,7 @@ class _ChoicesApp extends AppNotifier {String? swarmId,PaneSplitRequest? split,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dartindex 57a0bb96b..431c80e4b 100644--- a/desktop/test/new_agent_codex_profile_test.dart+++ b/desktop/test/new_agent_codex_profile_test.dart@@ -133,6 +133,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_dsh_test.dart b/desktop/test/new_agent_dsh_test.dartindex e3693ff0c..43379ad3c 100644--- a/desktop/test/new_agent_dsh_test.dart+++ b/desktop/test/new_agent_dsh_test.dart@@ -113,6 +113,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dartindex a62b70dc1..475b116de 100644--- a/desktop/test/new_agent_engine_check_test.dart+++ b/desktop/test/new_agent_engine_check_test.dart@@ -317,6 +317,7 @@ class _RetryNotifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_permission_mode_test.dart b/desktop/test/new_agent_permission_mode_test.dartindex 094b96507..c3bf383ec 100644--- a/desktop/test/new_agent_permission_mode_test.dart+++ b/desktop/test/new_agent_permission_mode_test.dart@@ -59,6 +59,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dartindex 705e25fb4..7c2c1e9ed 100644--- a/desktop/test/new_agent_project_picker_test.dart+++ b/desktop/test/new_agent_project_picker_test.dart@@ -72,6 +72,7 @@ class _App extends AppNotifier {String? swarmId,PaneSplitRequest? split,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_rows_and_task_test.dart b/desktop/test/new_agent_rows_and_task_test.dartindex 0d08dbc97..30e35475f 100644--- a/desktop/test/new_agent_rows_and_task_test.dart+++ b/desktop/test/new_agent_rows_and_task_test.dart@@ -125,6 +125,7 @@ class _App extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_agent_terminal_test.dart b/desktop/test/new_agent_terminal_test.dartindex cb6db8ccf..30d76493e 100644--- a/desktop/test/new_agent_terminal_test.dart+++ b/desktop/test/new_agent_terminal_test.dart@@ -67,6 +67,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_harness_attachments_test.dart b/desktop/test/new_harness_attachments_test.dartindex ee0d0813e..a3fc41de6 100644--- a/desktop/test/new_harness_attachments_test.dart+++ b/desktop/test/new_harness_attachments_test.dart@@ -106,6 +106,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_harness_guest_test.dart b/desktop/test/new_harness_guest_test.dartindex 3d22a4b8e..d2f77980d 100644--- a/desktop/test/new_harness_guest_test.dart+++ b/desktop/test/new_harness_guest_test.dart@@ -86,6 +86,7 @@ class _GuestApp extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/new_harness_install_pane_test.dart b/desktop/test/new_harness_install_pane_test.dartindex e820c0766..85f44f24d 100644--- a/desktop/test/new_harness_install_pane_test.dart+++ b/desktop/test/new_harness_install_pane_test.dart@@ -145,6 +145,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dartindex 546836f0c..cb709a5d9 100644--- a/desktop/test/remote_folder_picker_test.dart+++ b/desktop/test/remote_folder_picker_test.dart@@ -52,6 +52,7 @@ class _Folders extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/store_showcase_test.dart b/desktop/test/store_showcase_test.dartindex dc888f34f..49fa3cc4f 100644--- a/desktop/test/store_showcase_test.dart+++ b/desktop/test/store_showcase_test.dart@@ -87,6 +87,7 @@ class _Notifier extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex 957465a60..73cd1232d 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -442,6 +442,7 @@ void main() {.firstWhere((c) => c.$1 == 'agent_create').$2;expect(request['permissionMode'], 'full');+ expect(request['swarmRole'], kind == 'member' ? 'dev' : 'lead');await Future<void>.delayed(Duration.zero);final ordinary = NewHarnessController(f.app,@@ -703,6 +704,12 @@ void main() {reason: box.error,);expect(f.connection.sentFiles.single, [1, 2, 3]);+ expect(+ f.connection.calls+ .firstWhere((c) => c.$1 == 'agent_create')+ .$2['swarmRole'],+ 'lead',+ );expect(f.connection.calls.firstWhere((c) => c.$1 == 'agent_create')@@ -839,6 +846,20 @@ void main() {},);+ for (final engine in ['claude', 'codex']) {+ test('a Desktop $engine Swarm worker gets the DEV role', () async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');+ final box = await f.box(engine: engine);+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ final create = f.connection.calls+ .firstWhere((c) => c.$1 == 'agent_create')+ .$2;+ expect(create['swarmRole'], 'dev');+ expect(create['prompt'], contains('swarm-dev'));+ });+ }+test('the lead prompt routes before starting or assigning work', () async {final f = SuperTabLaunchFixture()..connection.nativeName = 'hi';final box = await f.box(engine: 'claude');@@ -897,8 +918,8 @@ void main() {.firstWhere((c) => c.$1 == 'agent_create').$2['prompt']as String;- expect(prompt, contains('like a helpful colleague'));- expect(prompt, contains('under about 150 words'));+ expect(prompt, contains('helpful colleague'));+ expect(prompt, contains('under 150 words'));expect(prompt, contains('UNIQUE_OPERATION_ID [--reply-to MESSAGE_ID]`'));expect(prompt, contains('answer each message once'));expect(prompt, contains('do not post again'));diff --git a/desktop/test/super_tab_startup_recovery_test.dart b/desktop/test/super_tab_startup_recovery_test.dartindex 99ffdebde..ac4d45a5f 100644--- a/desktop/test/super_tab_startup_recovery_test.dart+++ b/desktop/test/super_tab_startup_recovery_test.dart@@ -49,8 +49,32 @@ void main() {expect(prompt.length,lessThanOrEqualTo(kFirstTaskMaxLength),- reason: '${lead ? 'Lead' : 'Worker'} bootstrap must fit native creation',+ reason:+ '${lead ? 'Lead' : 'Worker'} bootstrap must fit native creation',);+ expect(+ prompt,+ contains(+ lead+ ? 'On Claude Code or Codex, use swarm-lead.'+ : 'On Claude Code or Codex, use swarm-dev.',+ ),+ );+ if (lead) {+ expect(prompt, contains('Discuss first; build when authorized.'));+ expect(prompt, contains('Swarm agent groups'));+ expect(+ prompt,+ contains('do only answers, lookups and small fixes yourself'),+ );+ expect(prompt, contains('your subagents only read/look up'));+ expect(+ prompt,+ contains(+ 'Coordinate: assign multi-part or 15+ minute work to Swarm agent groups;',+ ),+ );+ }}});@@ -62,7 +86,10 @@ void main() {);expect(prompt, contains('read new reports'));expect(prompt, contains('No per-turn summarizer'));- expect(prompt, contains('When a worker finishes, decide reuse, keep or stop'));+ expect(+ prompt,+ contains('When a worker finishes, decide reuse, keep or stop'),+ );expect(prompt, contains('prefer stop unless more work is coming soon'));expect(prompt, contains('On scheduled requests use project.report'));expect(prompt, contains('text:null when nothing changed'));@@ -95,6 +122,7 @@ void main() {(create.$2['prompt'] as String).length,lessThanOrEqualTo(kFirstTaskMaxLength),);+ expect(create.$2['swarmRole'], 'lead');final messages = f.connection.server.messages;expect(messages, hasLength(task.trim().isEmpty ? 0 : 1));if (messages.isNotEmpty) {diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dartindex 0e0e900cb..56a3fc196 100644--- a/desktop/test/workspace_start_guide_test.dart+++ b/desktop/test/workspace_start_guide_test.dart@@ -104,6 +104,7 @@ class _FirstApp extends AppNotifier {String? permissionMode,String? codexHome,String? dsh,+ String? swarmRole,GridModel? model,String? prompt,String? name,diff --git a/docs/plans/2026-10-22-swarm-lead-dev-skills.md b/docs/plans/2026-10-22-swarm-lead-dev-skills.mdnew file mode 100644index 000000000..a511b014f--- /dev/null+++ b/docs/plans/2026-10-22-swarm-lead-dev-skills.md@@ -0,0 +1,144 @@+# Swarm Lead and DEV Skills Implementation Plan++**Goal:** Ship built-in Lead and DEV skills for Claude Code and Codex without requiring a plugin. Attach only the appropriate skill to each newly launched Swarm session.++**Architecture:** Carry an explicit optional Swarm role through native creation, prepare a role-specific skill beneath a session-keyed workspace runtime, and point the engine's session instructions to it. Preserve the role and runtime key for restarts. Sessions created before this change keep their current behavior and adopt the skill only on their next fresh Swarm launch (Lead confirmed this boundary on 2026-10-22). Ordinary coding sessions keep their current behavior. Use the existing engine instruction contracts, preserving the person's instructions.++**Tech stack:** TypeScript, Node 24, Vitest, Dart/Flutter.++## Approved brief++Owner-approved scope is skills and launch prompts only; no backend enforcement, progress board, stuck detection or Reviewer skill.++Lead skill, in short plain English:+- Restate the request and mark guesses. Ask one question at a time in project chat, prioritizing goal, scope, constraints and done criteria. State small/medium/large; large work needs a written description.+- Split only after the task giver or owner clearly approves that description. Others' opinions and vague acknowledgements do not replace approval. Small clear requests can be done immediately; “just do it” skips questions but records important choices.+- Ask with numbered options, a default and deadline. At the deadline record and use the default for choices already authorized; elapsed time does not grant required approval.+- Route multi-part or roughly 15+ minute work into groups with goal, changes, constraints, owned code and acceptance checks. Coordinate Swarm agents; private subagents only read/look up.+- Decide reuse/keep/stop after completion; check silent workers and reassign stalled work. Report on-screen trust, sign-in or permission blocks immediately, naming the machine owner.+- Summarize long threads and record important decisions once.++DEV skill:+- Acknowledge the group and the work in chat.+- Test first, debug systematically, follow the plan in order, verify before done, and check review findings before changing code.+- Report a blocker with a “Needs:” line, then continue independent parts. Interpret ambiguous answers narrowly and record that interpretation.+- Finish all testable work and package a needed person/device action into one clear step.+- Every handoff says “Ready: yes/no”, with evidence and unverified items; distinguish local checks from real-environment runs.+- Ask the Lead to route instead of splitting into private subagents; do not touch other groups' code; merge/push/open a PR only when told. Print little.++## Constraints and ownership++- CLI skill files and role attachment launch path; Desktop launch prompt; CLI delivery header text only.+- Both the owner's and contributed machines use the executing machine's session workspace. Never write skills into the owner's native engine directories.+- No dependency added; existing sessions adopt the skill only on a fresh Swarm launch, not a restore of their old native session. No change to ordinary coding sessions.+- Lead bootstrap stays within 2,000 UTF-16 units with 160-character identifiers.+- Tests use throwaway directories, mocked engines/core and private test state, never the live daemon, real tmux or native user homes.+- Rebase onto current main before delivery; other groups edit prompts too. Push a feature branch and open a draft PR only; do not mark ready, merge or release.++## Review focus++Role isolation in a shared workspace; skill preservation on retry/restart; symlinked managed directories; preserving existing engine instructions and selected Store harnesses; attachment even when the first prompt is delivered as a file.++## Task 1: Session skill launch++Files: new `cli/src/lib/swarmSkills.ts` and tests; `cli/src/lib/productUsageSignals.ts` classifies the two new launch refusals using its existing invalid/setup kinds; creation wire/core, pane registry and relaunch metadata; Desktop launch integration and creation payload; `cli/src/superTabs/start.ts`.++- [x] Write and run failing filesystem and launch tests for both engines and both roles, ordinary sessions, retries, restarts and symlink refusal.+- [x] Implement `prepareSwarmSkill(workspace, {role, key})` returning a session instruction pointing at the saved skill. Snapshot skills once per session; refuse unsafe filesystem paths. Bundle the small Markdown strings in the CLI module so single-file releases carry them.+- [x] Pass explicit `swarmRole` on Desktop and contributed worker launches. Validate it, record `{role,key}` with the pane and restore it on relaunch.+- [x] Combine the skill pointer with the existing engine instruction mechanism; preserve custom instructions and Store runtime.+- [x] Verify focused CLI tests before broad gates.++## Task 2: Prompts and delivery++Files: `desktop/lib/super_tabs/launch_prompt.dart`, its launch/startup tests, CLI host header and tests.++- [x] Add failing assertions for role skill pointers and long-ID prompt limits.+- [x] Replace duplicated coordination rules with skill pointers. Keep route syntax and reply guidance.+- [x] Run affected Flutter startup/launch tests and analysis on changed files.++## Validation and delivery++- [ ] CLI Node 24: `npm run typecheck`; `npm run test:super-tabs`; affected host/start/skill/attribution/registry/relaunch specs; `npm run test:core` because native creation changes. No dsh/runtime change is planned.+- [ ] Desktop: `flutter analyze` on changed files; `flutter test test/super_tab_launch_test.dart test/super_tab_startup_recovery_test.dart`.+- [ ] Inspect the diff, fetch/rebase current main, rerun only newly affected checks, commit/push, and open a draft PR with exact validation results and limitations.+- [ ] Report PR, head and “Ready: yes/no” to the group. Real-engine behavioral compliance remains unverified by deterministic launch tests.++## Validation record++Platform: macOS arm64, Node 24.3.0, Flutter 3.47.5 / Dart 3.13.4. CLI tests redirect all homes and data to throwaway directories. Native integration uses fake Claude Code/Codex engines and a private tmux socket, never the live daemon. Skill content is bundled as Markdown strings; the launch creates the session's SKILL.md. Current Store runtime uses a session-keyed skill directory rather than project-wide native discovery links, so this implementation also keeps skill pointers local to the session.++- Regression RED: CLI role propagation, attachment and missing skill checks failed before implementation; Flutter role metadata and skill-pointer checks failed before implementation.+- CLI typecheck passed. `npm run test:super-tabs` passed with 100% coverage.+- Affected CLI specs (skill files, registry/pane persistence, attribution, relaunch, host/start, existing dsh/runtime and architecture): 341 tests passed. Added coverage tests also exercise role persistence after hooks, reload and detached-shell release; filesystem tests cover shared-workspace isolation and redirected managed paths.+- `npm run test:core -- --maxWorkers=3`: 199 files / 2,946 tests passed; the gate fails solely on unchanged `src/services/osDevice.ts:181` (119/120 lines, 35/36 functions). An isolated run of its existing 20 tests reproduces that coverage gap. The Lead instructed this group to leave it alone; #1525 carries the missing test. All modified core files reached 100%.+- `E2E_BUNDLE=1 node_modules/.bin/vitest run --config vitest.e2e.config.ts e2e/swarmSkills.e2e.ts`: passed. Both roles and engines receive only their own skill, metadata survives native binding, restart retains the skill and no skills are written into native engine homes. Also passed against the source runner.+- Flutter launch/startup suites: 50 tests passed, including Desktop worker roles, attached first prompts and the 2,000-unit limit with maximum IDs.+- Flutter analysis: no errors or warnings; 12 existing informational curly-brace lints in unchanged statements of `app_state.dart`. Plain analyze reports these; `--no-fatal-infos` accepts that existing baseline.+- Existing legacy sessions require a fresh Swarm launch to adopt a role skill. No roster bridge is included, as confirmed by the Lead.+- Real-engine reasoning/compliance and contributed physical-machine runs are unverified. The native integration verifies transport, filesystem and argv behavior with isolated fake engines.++Input scopes for evidence reuse: CLI source/lockfile/Node toolchain for CLI checks; Desktop source/pubspec/toolchain for Flutter checks. Backend-only and OS Python-only rebases do not change these scopes. A new change in those scopes or a conflict resolution requires affected checks.++### Broad validation and final review++`npm test -- --maxWorkers=3` was stopped at its approximately ten-minute limit (04:49:38–04:59:45 UTC); this run is incomplete, not a passing full suite. Its launch-refusal enumeration guard found missing classification for the new role/skill errors; those now use the existing invalid/setup kinds. The guard and native creation tests then passed together (134 tests).++Thirteen failures from four unchanged files reproduce on a temporary archive of current main with the same Node/toolchain: `engines/nativeDescriptors.golden.spec.ts` (5), `messages/rpc.spec.ts` (1), `engines/kit/storePool.spec.ts` (1), `engines/kit/exactTranscript.spec.ts` (6). A Cursor fixture hit its five-second deadline under the broad run; its isolated rerun passed all 28 tests. The two native `sessionRepair.spec.ts` failures required the private Darwin helper; after building it with `scripts/build-process-images.py` and setting `HARNESS_PROCESS_IMAGES_ARTIFACT`, all 78 tests in that file passed. None of those baseline files were changed.++Review: author inspected the complete diff and exercised the native bundle; independent review is requested from the Lead's review workgroup. No private subagents were started. Approval deadlines in the Lead skill apply to authorized choices, not the explicit approval needed to split work.++Timing (UTC, overlapping implementation and validation): assignment go 04:35:54; implementation/first focused green checks by 04:43; validation 04:40–05:01; final rebase/publication recorded in the PR handoff. Merge and release are not authorized. Ready for merge: no, pending independent review and the documented baseline gates.++Final integration: rebased on #1517 after it merged. The shared host header and Desktop prompt had text conflicts; the resolution preserves its five-part task template alongside the role skill pointers, removing only the duplicated coordination prose. Revalidated the host/service tests, routing coverage gate, CLI typecheck, Flutter launch/startup suites and bundle integration on the combined source. Other deterministic evidence covers unchanged inputs; the broad suite is not repeated.++## Review fixes (2026-10-22)++- Aligned the Lead task template with #1517: goal, changes, constraints, owned code and acceptance checks. DEV wording now explicitly requires a “Needs:” line and forbids touching other groups' code.+- Extracted `lib/harnessRuntimeIgnore.ts` from the Store ignore handling and reused it in both launch paths. It preserves custom rules, adds runtime/legacy rules once, atomically publishes the ignore file, and refuses a redirected file. A fresh-repository test actually runs `git add -A` and checks that SKILL.md is never staged.+- Restored a compact inline coordination clause in both Lead-facing prompts for older sessions/CLIs. Desktop and delivery-header skill guidance is explicitly conditional on Claude Code or Codex; worker starts omit the skill instruction for other engines.+- RED: five CLI regressions and the Flutter bootstrap regression failed on the pre-fix source. GREEN: 174 affected CLI tests, 50 Flutter launch/startup tests, typecheck, the 111-test routing coverage gate (100%), and the bundled private-engine integration passed. No core launch code changed in this review fix; prior core evidence is retained. The Lead accepted the previously documented OS-device and reproduced broad-suite failures as baseline.++Final compatibility review: restored the unconditional “Discuss first; build when authorized.” sentence for Leads, alongside skill-qualified guidance and the inline coordination fallback. The startup recovery assertion failed without it, then passed with it. Claude/Codex worker starts on an older contributed CLI may still be told to use swarm-dev even though that CLI cannot attach it; this accepted limitation is documented in the PR. Native role attachment requires an updated execution CLI.++Final prompt-only verification: both Flutter launch/startup suites pass (50 tests), analysis of the changed prompt/test reports no issues, and maximum-ID Lead prompt length is 1,977/2,000 UTF-16 units. CLI inputs are unchanged from the prior reviewed receipt; no CLI or broad-suite checks were repeated.++## Full-permission integration (2026-10-22)++Rebased the reviewed branch onto `9142773b0` (#1532, after #1528). The two textual conflicts were in CLI worker dispatch and Desktop launch integration. Both resolutions retain full permission mode and role metadata; the core launch changes applied without textual conflicts. Added combined assertions for direct/contributed CLI worker starts, Desktop Lead/member launches, and both roles on both engines in the bundled private-daemon integration. The latter checks the actual full-mode argv and saved permission mode alongside the role skill.++Fresh validation on the integrated tree uses Node 24.3.0 and Flutter 3.47.5/Dart 3.13.4 on macOS arm64, with isolated fixture homes and engines:++- CLI typecheck passed.+- Ten affected CLI specs passed all 427 tests (skill runtime, Store runtime, registry/pane, relaunch, attribution, usage classification, host/start and architecture).+- Routing coverage passed all 111 tests with 100% in every gated file.+- Bundled native integration passed for both engines and roles, including restart and native-home isolation.+- Flutter launch/startup recovery passed all 57 tests. Maximum-ID Lead prompt remains 1,977/2,000 UTF-16 units.+- Analysis of seven changed Dart files passed with no errors/warnings; the same 12 existing informational style notices remain in app_state.dart.++The initial concurrent core/routing coverage runs collided because routing cleaned the parent coverage directory. That core attempt was interrupted, not passing evidence; core was rerun with its own reports directory.++Core rerun: `npm run test:core -- --maxWorkers=3 --coverage.reportsDirectory=/private/tmp/swarm-rebase-core-coverage` passed 199 files / 2,947 tests. All four changed core agent files have 100% statements, branches, functions and lines. The command exits nonzero only for the unchanged, Lead-accepted `services/osDevice.ts:181` coverage gap (same missing line/function/branch); that file has no diff from main. The broad CLI suite was not repeated; its previously accepted baseline evidence remains above.++Range review confirmed the rebase changes only the two shared launch boundaries, retaining #1532's permission retry/recovery behavior and this branch's role isolation, fallback guidance and discuss-first sentence. No merge or release was performed. Rebase, integration assertions and validation took about five minutes; push and CI waiting are tracked separately in the handoff.++## Desktop CI fixture correction (2026-10-22)++The automatic ready-PR run exposed 18 Desktop test subclasses overriding AppNotifier.createAgent without its new optional swarmRole argument. This is a branch regression, not an accepted baseline. Reproduced the compile failure locally in new_agent_permission_mode_test.dart before adding the optional parameter to every override. Production inputs are unchanged. All 18 affected files then passed together: 236 tests passed, one skipped; analysis of those 18 files found no issues. CLI/core/native and the 57 launch/startup receipts cover unchanged production inputs and are retained. The corrected push will run automatic CI once; no manual workflow or rerun was started.++## Worker-release integration (2026-10-22)++Started from the Lead's pushed clean rebase `40adc5099` on #1525, then rebased onto `591b056a3` (#1527). CLI host/start sources and tests applied cleanly, retaining full-mode starts, role metadata, original-native-launch protection, agent.release and host close/retry behavior. Resolved the Desktop prompt and startup recovery conflicts by retaining every rule from both sides: discuss first, supported-engine role skills, routing, group coordination, small self-work/read-only subagents, five-part tasks, worker reuse/keep/stop with stop preferred, reply-once, scheduled report reading and project scope.++The combined prompt is 1,990/2,000 UTF-16 units with both IDs at 160 characters. Compact wording preserves the rules, and startup recovery pins the coordination and worker-release clauses. The extra fallback assertions failed before the wording fix; the length test also caught the first oversized combined draft.++Fresh checks on Node 24.3.0 and Flutter 3.47.5/Dart 3.13.4, macOS arm64:++- `cd cli && node_modules/.bin/vitest run src/superTabs --maxWorkers=3`: 20 files / 386 tests passed, including worker release, host close, dispatch and skill instructions.+- `cd cli && npm run test:super-tabs -- --coverage.reportsDirectory=/private/tmp/swarm-release-routing-coverage`: 111 tests passed, 100% statements/branches/functions/lines.+- `cd cli && npm run typecheck`: passed.+- `cd desktop && flutter test --no-pub test/super_tab_launch_test.dart test/super_tab_startup_recovery_test.dart`: 58 tests passed.+- `cd desktop && flutter analyze --no-pub lib/super_tabs/launch_prompt.dart test/super_tab_launch_test.dart test/super_tab_startup_recovery_test.dart`: no issues.+- `git diff --check`: clean.++The branch's native/core role attachment and 18 Desktop fixture signatures are unchanged; earlier scoped evidence remains recorded above. The merge and release remain the Lead's; the separate old-session bridge is still waiting for this PR to merge. Integration and requested validation took about five minutes; publication and CI waiting are separate.