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.

Swarm skill modes: CLI skill text by mode and reload on change (#1602)

0xken15cd82bbe375ea
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index a9b1286ad..568efaea0 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -160,6 +160,8 @@ export class BackendSocket {
prompt: string | null
/** Session-scoped built-in instructions for a newly launched Swarm agent. */
swarmRole?: import('./lib/swarmSkills.js').SwarmRole
+ /** The skills of the Swarm project it joins; absent from a start before modes, which launches on orchestration. */
+ swarmSkillMode?: import('./lib/swarmSkills.js').SwarmSkillMode
/** 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; opencode
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index d95bfc0fe..da60f0ada 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -1,4 +1,4 @@
-import { chmodSync, mkdirSync, mkdtempSync, opendirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, mkdtempSync, opendirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { readdir } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -177,6 +177,17 @@ describe('creating an agent', () => {
}
})
+ it.each(['default', 'orchestration'] as const)('writes the %s skill text and its prompt line for the project\'s mode', async mode => {
+ const cwd = folder()
+ await setup().create(request({ cwd, swarmRole: 'dev', swarmSkillMode: mode }))
+ const pane = vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0]
+ expect(pane.swarmSkill).toEqual({ role: 'dev', key: pane.sessionLabel, mode })
+ const place = vi.mocked(agentLaunchArgs).mock.calls.at(-1)![2]
+ const file = JSON.parse(/read (".*") with/.exec(place.swarmInstructions!)![1]!)
+ expect(readFileSync(file, 'utf8').includes('Work otherwise the way you normally do.')).toBe(mode === 'default')
+ expect(place.swarmInstructions!.startsWith(mode === 'default' ? 'Use the swarm-dev skill for this session: the team process' : 'Use the built-in swarm-dev skill')).toBe(true)
+ })
+
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 })
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index e7db88670..d749bf509 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -337,7 +337,7 @@ 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 swarmSkill = input.swarmRole ? { role: input.swarmRole, key: label } : undefined
+ const swarmSkill = input.swarmRole ? { role: input.swarmRole, key: label, ...(input.swarmSkillMode ? { mode: input.swarmSkillMode } : {}) } : undefined
let swarmInstructions: string | undefined
if (swarmSkill) {
try { swarmInstructions = prepareSwarmSkill(cwd, swarmSkill).instructions }
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 5e02915e3..31a55dd97 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -275,6 +275,22 @@ describe('agent_create, refused before any pane exists', () => {
expect(await ask({ engine: 'codex', cwd: '/w', swarmRole: 'dev', resumeSessionId: 'old-session' })).toMatchObject({ error: 'INVALID_SESSION' })
})
+ it('passes the project\'s skill mode with a Swarm role, and refuses one it does not know before dispatch', async () => {
+ const { ask, create } = setup()
+ for (const swarmSkillMode of ['default', 'orchestration']) {
+ await ask({ engine: 'claude', cwd: '/w', swarmRole: 'dev', swarmSkillMode })
+ expect(vi.mocked(create!).mock.calls.at(-1)![0]).toMatchObject({ swarmRole: 'dev', swarmSkillMode })
+ }
+ // From a start before modes: the session launches as it did then.
+ await ask({ engine: 'claude', cwd: '/w', swarmRole: 'dev' })
+ expect(vi.mocked(create!).mock.calls.at(-1)![0]).not.toHaveProperty('swarmSkillMode')
+ const calls = vi.mocked(create!).mock.calls.length
+ for (const swarmSkillMode of ['light', 7, null]) {
+ expect(await ask({ engine: 'claude', cwd: '/w', swarmRole: 'dev', swarmSkillMode })).toMatchObject({ error: 'INVALID_SWARM_ROLE' })
+ }
+ expect(vi.mocked(create!).mock.calls).toHaveLength(calls)
+ })
+
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.ts
index 60519932d..4837b3112 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -22,7 +22,7 @@ import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types
import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationOutcome, type AgentCreationReceipts, type AgentCreationStatus, type CreationAuthority } from '../../lib/agentCreationReceipt.js'
import type { AgentFrame } from '../../lib/agentFrame.js'
import { engineLabel } from '../../lib/agentNames.js'
-import { isSwarmRole } from '../../lib/swarmSkills.js'
+import { isSwarmRole, isSwarmSkillMode } from '../../lib/swarmSkills.js'
import {
AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves,
permissionModeFlags, supportsFirstPrompt, supportsNamedAgent, unsupportedLaunchModelFlag,
@@ -397,6 +397,11 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
(!isSwarmRole(swarmRole) || (engine !== 'claude' && engine !== 'codex'))) {
reply({ error: 'INVALID_SWARM_ROLE', detail: 'A Swarm role is lead, dev or review, for Claude Code or Codex.' }); return
}
+ // The skills of the project the agent joins (superTabs/start.ts); a start from before modes sends none.
+ const swarmSkillMode = payload.swarmSkillMode
+ if (swarmSkillMode !== undefined && !isSwarmSkillMode(swarmSkillMode)) {
+ reply({ error: 'INVALID_SWARM_ROLE', detail: 'A Swarm skill mode is default or orchestration.' }); 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
@@ -465,7 +470,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
codexHome,
dsh,
prompt,
- ...(isSwarmRole(swarmRole) ? { swarmRole } : {}),
+ ...(isSwarmRole(swarmRole) ? { swarmRole, ...(swarmSkillMode ? { swarmSkillMode } : {}) } : {}),
name,
agent,
resumeSessionId,
diff --git a/cli/src/core/agents/swarmSkills.spec.ts b/cli/src/core/agents/swarmSkills.spec.ts
index 9d26f49b0..4e860649c 100644
--- a/cli/src/core/agents/swarmSkills.spec.ts
+++ b/cli/src/core/agents/swarmSkills.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../../lib/registry.js'
-import type { SwarmRole } from '../../lib/swarmSkills.js'
+import type { SwarmSkillGrant } from '../../lib/swarmSkills.js'
import { createLaunchAuthority } from './launchAuthority.js'
import { createSwarmSkillAdoption } from './swarmSkills.js'
@@ -9,7 +9,7 @@ const row = (over: Partial<RegisteredSession> = {}) => ({ agentId: 'old-session'
function setup(saved = row(), live: RegisteredSession | null = saved) {
let current = true
- const role = vi.fn(async (): Promise<SwarmRole | null | undefined> => 'lead')
+ const role = vi.fn(async (): Promise<SwarmSkillGrant | null | undefined> => ({ role: 'lead' }))
const save = (id: string, skill: NonNullable<RegisteredSession['swarmSkill']>) => {
if (!live || live.agentId !== id) return false
live.swarmSkill = skill; return true
@@ -22,11 +22,16 @@ function setup(saved = row(), live: RegisteredSession | null = saved) {
describe('old Swarm role adoption', () => {
it.each(['claude', 'codex'] as const)('adopts each role for old %s sessions and persists it before launch', async engine => {
for (const role of ['lead', 'dev', 'review'] as const) {
- const t = setup(row({ engine })); t.role.mockResolvedValue(role)
+ const t = setup(row({ engine })); t.role.mockResolvedValue({ role })
expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role, key: 'old-session' } })
expect(t.saved.swarmSkill).toEqual({ role, key: 'old-session' })
}
})
+ it('adopts the role with its project\'s skill mode, so the restarted session launches on that text', async () => {
+ const t = setup(); t.role.mockResolvedValue({ role: 'lead', mode: 'default' })
+ expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role: 'lead', key: 'old-session', mode: 'default' } })
+ expect(t.saved.swarmSkill).toEqual({ role: 'lead', key: 'old-session', mode: 'default' })
+ })
it('carries metadata into a stopped resume without requiring a live registry row', async () => {
const t = setup(row(), null)
expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role: 'lead', key: 'old-session' } })
@@ -64,7 +69,7 @@ describe('old Swarm role adoption', () => {
const t = setup()
if (unavailable === 'offline') t.role.mockRejectedValueOnce(new Error('Offline'))
else t.role.mockResolvedValueOnce(undefined)
- t.role.mockResolvedValueOnce('dev')
+ t.role.mockResolvedValueOnce({ role: 'dev' })
expect(await t.adopt(t.saved, t.current)).toBe(t.saved)
expect(await t.adopt(t.saved, t.current)).toMatchObject({ swarmSkill: { role: 'dev' } })
expect(t.role).toHaveBeenCalledTimes(2)
@@ -92,7 +97,7 @@ describe('old Swarm role adoption', () => {
})
it.each(['cancel', 'rebind'] as const)('does not adopt after %s while the roster is being read', async change => {
const t = setup()
- t.role.mockImplementation(async () => { if (change === 'cancel') t.cancel(); else t.change(); return 'lead' })
+ t.role.mockImplementation(async () => { if (change === 'cancel') t.cancel(); else t.change(); return { role: 'lead' as const } })
expect(await t.adopt(t.saved, t.current)).toBeNull()
expect(t.saved.swarmSkill).toBeUndefined()
})
diff --git a/cli/src/core/agents/swarmSkills.ts b/cli/src/core/agents/swarmSkills.ts
index 083396ac0..8ec93a439 100644
--- a/cli/src/core/agents/swarmSkills.ts
+++ b/cli/src/core/agents/swarmSkills.ts
@@ -1,12 +1,12 @@
/** Older Swarm sessions predate role metadata. Adopt only at restart/resume, from current membership,
* before native launch authority is captured; changing the live row later would revoke that launch. */
import type { RegisteredSession, registry } from '../../lib/registry.js'
-import type { SwarmRole } from '../../lib/swarmSkills.js'
+import type { SwarmSkillGrant } from '../../lib/swarmSkills.js'
export type AdoptSwarmSkill = (session: RegisteredSession, current: () => boolean) => Promise<RegisteredSession | null>
export function createSwarmSkillAdoption(deps: {
- role(harnessId: string): Promise<SwarmRole | null | undefined>
+ role(harnessId: string): Promise<SwarmSkillGrant | null | undefined>
candidate(harnessId: string): boolean
authority(agentId: string): () => boolean
save: typeof registry.setSwarmSkill
@@ -20,16 +20,17 @@ export function createSwarmSkillAdoption(deps: {
try { if (!deps.candidate(session.agentId)) return session } catch { return session }
const owns = deps.authority(session.agentId)
const saved = structuredClone(session)
- let role: SwarmRole | null | undefined
- try { role = await deps.role(saved.agentId) } catch { /* An unreadable roster grants no skill. */ }
+ let grant: SwarmSkillGrant | null | undefined
+ try { grant = await deps.role(saved.agentId) } catch { /* An unreadable roster grants no skill. */ }
if (!current()) return null
- if (role === undefined) return session
- if (role === null) {
+ if (grant === undefined) return session
+ if (grant === null) {
noRole.add(saved.agentId)
return session
}
if (!owns()) return null
- const swarmSkill = { role, key: saved.agentId }
+ // With its project's mode, so the relaunch writes that text and the host owes it no reload.
+ const swarmSkill = { ...grant, key: saved.agentId }
// A stopped row is not live yet: resumePendingAgent persists the returned copy when dispatch allocates its pane.
deps.save(saved.agentId, swarmSkill)
return { ...saved, swarmSkill }
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index 71ee0878b..b4746a2e5 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -652,7 +652,7 @@ export const MEMORY_REQUESTS = ['memory_snapshot', 'memory_about_put', 'memory_d
* the client that asks, which acts on it. */
export const ROUTER_REQUESTS = ['route_decide'] as const
export const SUPER_TAB_REQUESTS = ['super_tabs'] as const
-export interface SuperTabsPort { connected(): void; disconnected(): void; stop(): void; swarmRole(harnessId: string): Promise<import('../lib/swarmSkills.js').SwarmRole | null | undefined> }
+export interface SuperTabsPort { connected(): void; disconnected(): void; stop(): void; swarmRole(harnessId: string): Promise<import('../lib/swarmSkills.js').SwarmSkillGrant | null | undefined> }
export const SUPER_TAB_FALLBACKS: PortFallbacks<SuperTabsPort> = { connected: undefined, disconnected: undefined, stop: undefined, swarmRole: later(undefined) }
/** The project and folder readers (services/projects.ts). */
export const PROJECTS_REQUESTS = ['git_pull_request', 'git_pull_requests_status', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const
diff --git a/cli/src/core/superTabSkills.spec.ts b/cli/src/core/superTabSkills.spec.ts
index 842cf1da8..19438060b 100644
--- a/cli/src/core/superTabSkills.spec.ts
+++ b/cli/src/core/superTabSkills.spec.ts
@@ -1,13 +1,15 @@
import { expect, it, vi } from 'vitest'
import { swarmRoleThrough } from './superTabSkills.js'
-it('reads only validated role answers through the Super Tab process', async () => {
- const answers = [{ ok: true, role: 'lead' }, { ok: true, role: 'dev' }, { ok: true, role: 'review' }, { ok: true, role: null }, { role: 'lead' }, { ok: true, role: 'owner' }, { error: 'SERVICE_UNAVAILABLE' }]
+it('reads only validated role answers, with their project\'s skill mode, through the Super Tab process', async () => {
+ const answers = [{ ok: true, role: 'lead', mode: 'default' }, { ok: true, role: 'dev', mode: 'orchestration' }, { ok: true, role: 'review', mode: 'light' },
+ { ok: true, role: null }, { role: 'lead' }, { ok: true, role: 'owner' }, { error: 'SERVICE_UNAVAILABLE' }]
const call = vi.fn(async () => answers.shift()!)
const read = swarmRoleThrough(call)
- expect(await read('native')).toBe('lead')
- expect(await read('native')).toBe('dev')
- expect(await read('native')).toBe('review')
+ expect(await read('native')).toEqual({ role: 'lead', mode: 'default' })
+ expect(await read('native')).toEqual({ role: 'dev', mode: 'orchestration' })
+ // An older Super Tab process sends no mode, and an unknown one is not trusted: the session launches as before modes.
+ expect(await read('native')).toEqual({ role: 'review' })
expect(await read('native')).toBeNull()
for (let i = 0; i < 3; i++) expect(await read('native')).toBeUndefined()
expect(call).toHaveBeenCalledWith('super_tabs', { action: 'swarmRole', harnessId: 'native' })
diff --git a/cli/src/core/superTabSkills.ts b/cli/src/core/superTabSkills.ts
index f4fbdd2d7..365d10b41 100644
--- a/cli/src/core/superTabSkills.ts
+++ b/cli/src/core/superTabSkills.ts
@@ -1,11 +1,11 @@
/** The same role lookup in a separate Super Tab process. Missing/older services grant no skill. */
-import { isSwarmRole, type SwarmRole } from '../lib/swarmSkills.js'
+import { isSwarmRole, isSwarmSkillMode, type SwarmSkillGrant } from '../lib/swarmSkills.js'
export function swarmRoleThrough(call: (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>) {
- return async (harnessId: string): Promise<SwarmRole | null | undefined> => {
+ return async (harnessId: string): Promise<SwarmSkillGrant | null | undefined> => {
const answer = await call('super_tabs', { action: 'swarmRole', harnessId })
if (answer.ok !== true) return undefined
if (answer.role === null) return null
- return isSwarmRole(answer.role) ? answer.role : undefined
+ return isSwarmRole(answer.role) ? { role: answer.role, ...(isSwarmSkillMode(answer.mode) ? { mode: answer.mode } : {}) } : undefined
}
}
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index d8352aa08..d890fc1cd 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -39,18 +39,38 @@ describe('built-in Swarm skills', () => {
expect(readdirSync(data)).toEqual([])
})
- // The owner's approved text (2026-10-22), with Lead recovery guidance agreed on 2026-10-23.
+ // The owner's approved text (2026-10-22, with the Lead recovery guidance of 2026-10-23), byte for byte; the Lead's gains only the approved 2-hour line (2026-10-23).
+ const sha = (text: string) => createHash('sha256').update(text).digest('hex')
+ const twoHours = '- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).\n'
it.each([
['lead', '5fc83d8c43b66b44cdab27b48235dbc86b7ab11a57153edc1ae7e92831642a8e'],
['dev', '86caf697c83365f000317845b0aaa929947a9591d637ab2bd0f8536da8e86763'],
['review', '424dc9db5642ed7093128525f30877ffc301eb6957b33e8234916de0f0eaa208'],
- ] as const)('writes the owner\'s %s skill byte for byte', (role, sha256) => {
+ ] as const)('writes the owner\'s Harness orchestration %s skill byte for byte', (role, sha256) => {
expect(parseSwarmSkill({ role, key: 'session' })).toEqual({ role, key: 'session' })
- const prepared = prepareSwarmSkill(fixture(), { role, key: 'session' })
- expect(prepared.instructions).toContain(`swarm-${role} skill`)
- const text = readFileSync(prepared.file, 'utf8')
- expect(text.startsWith(`---\nname: swarm-${role}\n`)).toBe(true)
- expect(createHash('sha256').update(text).digest('hex')).toBe(sha256)
+ for (const mode of [undefined, 'orchestration'] as const) {
+ const prepared = prepareSwarmSkill(fixture(), { role, key: 'session', ...(mode ? { mode } : {}) })
+ expect(prepared.instructions).toBe(`Use the built-in swarm-${role} skill for this session. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)
+ const text = readFileSync(prepared.file, 'utf8')
+ expect(text.startsWith(`---\nname: swarm-${role}\n`)).toBe(true)
+ expect(text.split(twoHours)).toHaveLength(role === 'lead' ? 2 : 1)
+ expect(sha(text.replace(twoHours, ''))).toBe(sha256)
+ }
+ })
+ it('adds the 2-hour line to section 7 right after the 6-hour rule', () => {
+ const text = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')
+ expect(text).toContain(`reassign work that has not moved for 6 hours; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.\n${twoHours}- Keep each worker supplied`)
+ })
+ // The owner's approved Default texts (attached to the spec, 2026-10-23), byte for byte.
+ it.each([
+ ['lead', 'a7b8aed240f38edda8a461d87ce83499696588b2da41ed261821985caa63e415'],
+ ['dev', '9294ae0dfe48a5c9185638ecb8f7cb2c2903253e5e823eb69592f3eb85455f12'],
+ ['review', '56c1a9bfbe7cf2ff9ded4c83cebe9e801f8846250ec80849aa6afe41685db7d9'],
+ ] as const)('writes the owner\'s Default %s skill byte for byte, with a prompt line that fits it', (role, sha256) => {
+ expect(parseSwarmSkill({ role, key: 'session', mode: 'default' })).toEqual({ role, key: 'session', mode: 'default' })
+ const prepared = prepareSwarmSkill(fixture(), { role, key: 'session', mode: 'default' })
+ expect(sha(readFileSync(prepared.file, 'utf8'))).toBe(sha256)
+ expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)
})
describe('a running session after a CLI update', () => {
@@ -66,35 +86,105 @@ describe('built-in Swarm skills', () => {
}
it.each([false, true])('rewrites an older skill file and owes one notice until it is recorded (recorded before: %s)', recorded => {
const workspace = fixture(), file = older(workspace, recorded)
- const sync = refreshSwarmSkill(workspace, skill)!
+ const sync = refreshSwarmSkill(workspace, skill, 'orchestration')!
expect(sync).toMatchObject({ file, owed: true })
expect(readFileSync(file, 'utf8')).toBe(readFileSync(prepareSwarmSkill(fixture(), skill).file, 'utf8'))
// Not yet recorded: a later pass, or another daemon, still owes the same notice for the same text.
- expect(refreshSwarmSkill(workspace, skill)).toEqual(sync)
- recordSwarmSkillNotice(workspace, skill, sync.version)
- expect(refreshSwarmSkill(workspace, skill)).toMatchObject({ file, owed: false })
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toEqual(sync)
+ recordSwarmSkillNotice(workspace, skill, sync)
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ file, owed: false })
// The agent's own edits after the update are its own: the record says the file already holds this text.
writeFileSync(file, 'edited')
- expect(refreshSwarmSkill(workspace, skill)).toMatchObject({ owed: false })
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ owed: false })
expect(readFileSync(file, 'utf8')).toBe('edited')
})
it('owes nothing for a file already on the built-in text, new or from before records', () => {
const fresh = fixture()
prepareSwarmSkill(fresh, skill)
- expect(refreshSwarmSkill(fresh, skill)).toMatchObject({ owed: false })
+ expect(refreshSwarmSkill(fresh, skill, 'orchestration')).toMatchObject({ owed: false })
const legacy = fixture(), { file } = prepareSwarmSkill(legacy, skill)
rmSync(join(dirname(file), 'version.json'))
- expect(refreshSwarmSkill(legacy, skill)).toMatchObject({ owed: false })
+ expect(refreshSwarmSkill(legacy, skill, 'orchestration')).toMatchObject({ owed: false })
+ })
+ it('tells the agent what changed: a new release of its skill, in the words of its mode', () => {
+ const workspace = fixture(), file = older(workspace, true)
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ owed: true, change: 1,
+ notice: `Harness updated your built-in swarm-dev skill. Before your next step, read ${JSON.stringify(file)} again with your file or shell tool and follow the new version.` })
+ const other = fixture(), { file: mine } = prepareSwarmSkill(other, { ...skill, mode: 'default' })
+ writeFileSync(mine, 'An older release of the Default skill.')
+ writeFileSync(join(dirname(mine), 'version.json'), JSON.stringify({ text: 'older', notified: 'older', mode: 'default', told: 'default' }))
+ expect(refreshSwarmSkill(other, skill, 'default')).toMatchObject({ owed: true,
+ notice: `Harness updated your swarm-dev skill. Before your next step, read ${JSON.stringify(mine)} again with your file or shell tool and follow the new version.` })
+ })
+ it('moves a running session to the project\'s new mode, and owes a new notice each time, also when it switches back', () => {
+ const workspace = fixture(), { file } = prepareSwarmSkill(workspace, { ...skill, mode: 'default' })
+ const defaultText = readFileSync(file, 'utf8')
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: false })
+ const toOrchestration = refreshSwarmSkill(workspace, skill, 'orchestration')!
+ expect(toOrchestration).toMatchObject({ file, owed: true, change: 1,
+ notice: `This project now uses the Harness orchestration skills. Before your next step, read ${JSON.stringify(file)} again with your file or shell tool and follow it in place of your earlier swarm-dev skill.` })
+ expect(readFileSync(file, 'utf8')).toBe(readFileSync(prepareSwarmSkill(fixture(), skill).file, 'utf8'))
+ recordSwarmSkillNotice(workspace, skill, toOrchestration)
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ owed: false, change: 1 })
+ const back = refreshSwarmSkill(workspace, skill, 'default')!
+ expect(back).toMatchObject({ owed: true, change: 2,
+ notice: `This project now uses the Default skills. Before your next step, read ${JSON.stringify(file)} again with your file or shell tool and follow it in place of your earlier swarm-dev skill.` })
+ expect(readFileSync(file, 'utf8')).toBe(defaultText)
+ // The same text as at launch, but a new change: its notice is not the launch's (there was none) nor a retry of another.
+ recordSwarmSkillNotice(workspace, skill, back)
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: false, change: 2 })
+ // A relaunch keeps the file and says what it holds, whatever mode the session was first started in.
+ refreshSwarmSkill(workspace, skill, 'orchestration')
+ expect(prepareSwarmSkill(workspace, { ...skill, mode: 'default' }).instructions)
+ .toBe(`Use the built-in swarm-dev skill for this session. Before working, read ${JSON.stringify(file)} with your file or shell tool.`)
+ })
+ it('puts back the mode\'s text when a switch was cut off after its file and before its record', () => {
+ const workspace = fixture(), { file } = prepareSwarmSkill(workspace, { ...skill, mode: 'default' })
+ const defaultText = readFileSync(file, 'utf8'), record = join(dirname(file), 'version.json'), before = readFileSync(record, 'utf8')
+ refreshSwarmSkill(workspace, skill, 'orchestration')
+ // The pass stopped after replacing SKILL.md: the record still says Default, the file holds orchestration.
+ writeFileSync(record, before)
+ expect(readFileSync(file, 'utf8')).not.toBe(defaultText)
+ // The project switched back before the retry: the file is Default again, and the agent, never told, owes nothing.
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: false })
+ expect(readFileSync(file, 'utf8')).toBe(defaultText)
+ // The same retry without a switch back finishes the switch and owes its notice.
+ refreshSwarmSkill(workspace, skill, 'orchestration'); writeFileSync(record, before)
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ owed: true,
+ notice: expect.stringMatching(/^This project now uses the Harness orchestration skills\./) })
+ })
+ it('tells the agent again when it switches back after a notice that was sent but never recorded', () => {
+ const workspace = fixture(), { file } = prepareSwarmSkill(workspace, { ...skill, mode: 'default' })
+ // Sent, then the daemon stopped before recordSwarmSkillNotice: the agent may be following the orchestration text.
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ owed: true, change: 1 })
+ const back = refreshSwarmSkill(workspace, skill, 'default')!
+ expect(back).toMatchObject({ owed: true, change: 2,
+ notice: `This project now uses the Default skills. Before your next step, read ${JSON.stringify(file)} again with your file or shell tool and follow it in place of your earlier swarm-dev skill.` })
+ // Recording an earlier rewrite's notice does not cover this one.
+ recordSwarmSkillNotice(workspace, skill, { version: 'any', change: 1 })
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: true, change: 2 })
+ recordSwarmSkillNotice(workspace, skill, back)
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: false, change: 2 })
+ })
+ it('tells an agent with a record from before modes again when it switches back after an unrecorded notice', () => {
+ const workspace = fixture(), { file } = prepareSwarmSkill(workspace, skill), text = readFileSync(file, 'utf8')
+ // What #1585 left: the orchestration text, told, with no rewrite count.
+ writeFileSync(join(dirname(file), 'version.json'), JSON.stringify({ text: sha(text), notified: sha(text) }))
+ // Switched to Default and its notice sent, then the daemon stopped before recording it.
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: true })
+ expect(refreshSwarmSkill(workspace, skill, 'orchestration')).toMatchObject({ owed: true,
+ notice: expect.stringMatching(/^This project now uses the Harness orchestration skills\./) })
+ expect(readFileSync(file, 'utf8')).toBe(text)
})
it('does nothing for a session whose skill was never prepared in this workspace', () => {
- expect(refreshSwarmSkill(fixture(), skill)).toBeNull()
- expect(refreshSwarmSkill(join(fixture(), 'removed-worktree'), skill)).toBeNull()
+ expect(refreshSwarmSkill(fixture(), skill, 'orchestration')).toBeNull()
+ expect(refreshSwarmSkill(join(fixture(), 'removed-worktree'), skill, 'orchestration')).toBeNull()
})
it('never writes through a redirected skill file', () => {
const workspace = fixture(), file = older(workspace, false), target = join(fixture(), 'elsewhere.md')
writeFileSync(target, 'kept')
rmSync(file); symlinkSync(target, file)
- expect(() => refreshSwarmSkill(workspace, skill)).toThrow('plain file')
+ expect(() => refreshSwarmSkill(workspace, skill, 'orchestration')).toThrow('plain file')
expect(readFileSync(target, 'utf8')).toBe('kept')
})
})
@@ -153,6 +243,9 @@ describe('built-in Swarm skills', () => {
it('validates persisted role metadata and refuses an empty key', () => {
for (const value of [null, undefined, {}, { role: 'builder', key: 'x' }, { role: 'dev', key: '' }, { role: 'lead', key: 7 }]) expect(parseSwarmSkill(value)).toBeUndefined()
expect(parseSwarmSkill({ role: 'dev', key: 'x' })).toEqual({ role: 'dev', key: 'x' })
+ // An unknown mode is dropped, not refused: the session keeps its role and launches as before modes.
+ expect(parseSwarmSkill({ role: 'dev', key: 'x', mode: 'light' })).toEqual({ role: 'dev', key: 'x' })
+ expect(parseSwarmSkill({ role: 'dev', key: 'x', mode: 'orchestration' })).toEqual({ role: 'dev', key: 'x', mode: 'orchestration' })
expect(() => prepareSwarmSkill(fixture(), { role: 'lead', key: '' })).toThrow()
})
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 6623f60cf..5c1730e5a 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -5,16 +5,23 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSyn
import { join, relative, sep } from 'node:path'
export type SwarmRole = 'lead' | 'dev' | 'review'
-export interface SwarmSkill { role: SwarmRole; key: string }
+/** A Swarm project's skill set, which its owner chooses (2026-10-23): Default is the team process alone, Harness orchestration
+ * adds Harness practices. A session saved without one launched before modes, on the orchestration text. */
+export type SwarmSkillMode = 'default' | 'orchestration'
+export interface SwarmSkill { role: SwarmRole; key: string; mode?: SwarmSkillMode }
+/** What a session's current Swarm membership grants it, before it has a key. */
+export type SwarmSkillGrant = Omit<SwarmSkill, 'key'>
export const isSwarmRole = (value: unknown): value is SwarmRole => value === 'lead' || value === 'dev' || value === 'review'
+export const isSwarmSkillMode = (value: unknown): value is SwarmSkillMode => value === 'default' || value === 'orchestration'
export function parseSwarmSkill(value: unknown): SwarmSkill | undefined {
if (!value || typeof value !== 'object') return undefined
- const { role, key } = value as Partial<SwarmSkill>
- return isSwarmRole(role) && typeof key === 'string' && key.length > 0 ? { role, key } : undefined
+ const { role, key, mode } = value as Partial<SwarmSkill>
+ return isSwarmRole(role) && typeof key === 'string' && key.length > 0 ? { role, key, ...(isSwarmSkillMode(mode) ? { mode } : {}) } : undefined
}
-const skills: Record<SwarmRole, string> = {
+/** The owner's texts, used verbatim. */
+const orchestration: Record<SwarmRole, string> = {
lead: `---
name: swarm-lead
description: Use when coordinating a Harness Swarm project as its Lead (shown as Product Manager), before discussing, specifying, splitting, routing, assigning, reviewing or closing work.
@@ -109,6 +116,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc
- Blocked: change something. Give more context, re-route to a stronger model, cut the work smaller, or fix the plan. Never resend the same thing to the same model.
- Rulings, not stalls: when a Builder hits an ambiguity you can settle, settle it and record "Ruling: what — why — cost if wrong". Ask the person only what changes what gets built.
- Each time you are woken, look at active work. Ask a worker with active work that has said nothing for 20 minutes; reassign work that has not moved for 6 hours; report on-screen trust, sign-in or permission questions in chat, naming the machine owner who can answer.
+- A Builder or Reviewer that has been down for 2 hours (machine offline, session gone or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
- Keep each worker supplied: have its next group ready before it finishes, so nobody waits for you.
- Cancel a duplicate, obsolete or wrong task with a reason.
- When a worker finishes: reuse, keep or stop. Prefer stop unless more work is coming soon.
@@ -336,37 +344,198 @@ Mark your review assignment done with the verdict and revision. Print little.
`,
}
+const defaults: Record<SwarmRole, string> = {
+ lead: `---
+name: swarm-lead
+description: Use when coordinating a Harness Swarm project as its Lead (shown as Product Manager): taking requests, splitting work into groups, assigning, tracking and closing them.
+---
+# Lead a Swarm project
+
+You own the task list, the order and the answers. People bring requests to the project chat; Builders do the work in groups; Reviewers check it. Work otherwise the way you normally do.
+
+## Core rules
+1. Only you open tasks, choose owners and set the order. Builders propose; you answer once: yes, yes as a task, no, or yes but…
+2. Multi-part work, or work over about 15 minutes, goes to a group. Answers, lookups and quick fixes you do yourself.
+3. Route every new agent and every assignment; use the pick or give a reason.
+4. Done means shown: merged and tried where it runs. A report is not evidence.
+5. The owner still decides credentials, spending, deleting data, publishing outside the repo, releases, and loosening privacy or safety. Merging and opening a PR follow the owner's standing instructions.
+6. Project instructions (AGENTS.md, CLAUDE.md, CONTRIBUTING) and the owner's words outrank this skill.
+
+## 1. Take a request
+- Read the project and the chat first; don't ask what they already answer.
+- Restate the request in a sentence or two, mark guesses, and ask only what changes what gets built.
+- Size it: quick (do it), one group (short description, owner's ok, then assign), several groups (a short written plan, owner's ok, then assign).
+
+## 2. Write each task
+Every group carries:
+- Why: the reason, in one or two sentences.
+- Wanted: what changes, with exact names, values and visible copy.
+- Owned code, and what is off limits. No two groups own the same code.
+- Hand back: what the Builder returns (branch, PR, revision, evidence, links).
+- Checks: observable evidence that it works.
+- Most likely wrong: the cases nobody checks, most likely first, each with what a user would expect.
+- Needs: nothing, a machine, test input, a person's hands, or a real user.
+
+Keep each Builder's list a few tasks deep; do the easy, self-contained parts first. Run groups in parallel only when they don't share code, machines or data.
+
+## 3. Route, start, assign
+- Route each group; reuse an idle agent before starting one; start only on the Swarm's machines.
+- The brief is all a Builder gets; never rely on chat history.
+
+## 4. Keep work moving
+- Each time you are woken, look at active work.
+- A worker with active work that has said nothing for 20 minutes: ask it.
+- A Builder or Reviewer that has been down for 2 hours (its machine offline, its session gone, or stopped): cancel its task with the reason, route it, and assign it to another agent with what the first one left (branch, last revision, last report).
+- Work with no progress for 6 hours goes back to you: reassign it or cut it smaller.
+- Needs a person: get the decision now. Blocked: change something (context, model, size or plan); never resend the same thing.
+- Settle ambiguities you can and record "Ruling: what — why — cost if wrong".
+- When a worker finishes: reuse, keep or stop. Prefer stop.
+
+## 5. Review and accept
+- Work that will be merged, or carries medium risk or more, gets a Reviewer: create "Review: <group>", route it, assign it, and add the Reviewer to the Builder's group.
+- Findings go back to the Builder; you rule on disagreements.
+- Accept only when the reviewed revision is the handed-off revision, its checks have evidence, and CI is green on it.
+- Close the task saying what was and was not delivered.
+
+## 6. Skills for this project
+When the project owner asks in chat to switch this project's skills (Default or Harness orchestration), change it with the project skills command, quoting their message. Only the project owner's own chat message counts.
+
+## 7. Keep people informed
+- At the project's cadence, post a scored table: one row per group, 0 to 1, its owner and what it waits on. Only merged and tried scores 1.0. If nothing changed, post nothing.
+- Answer questions, blockers and completions at once.
+- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.
+- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.
+`,
+ dev: `---
+name: swarm-dev
+description: Use when you are a Harness Swarm Builder (shown as Engineer) taking, doing or handing off an assigned group.
+---
+# Build an assigned group
+
+You finish one group's work completely, inside its brief, as if nobody will come back to help. Work otherwise the way you normally do.
+
+## Core rules
+1. Stay inside your brief and owned code. Never touch another group's code or another Builder's branch.
+2. No claim without showing it: say what ran, where, on which revision, and what was not shown. A local result is not a result on the real machine or device.
+3. Push only your own work branch. No merge, release or force-push unless told.
+4. Project instructions (AGENTS.md, CLAUDE.md, CONTRIBUTING) outrank this skill.
+
+## 1. Take the assignment
+- Say in the group that you took it and what you will do first; mark it working.
+- Read the whole brief: why, wanted, owned code, hand back, checks, most likely wrong, needs.
+- Read how the code behaves today before changing it.
+- If the brief needs a machine, device or person, check it is available; if not, post a "Needs:" line and do the parts that don't depend on it.
+- Harness already created your worktree; work there.
+
+## 2. Do the work
+- Build each piece completely. Test everything that can be tested without the device or person, and keep any remaining manual step to one command or one action.
+- A fix comes with a test that fails before it and passes after.
+- Name a known flaky test instead of letting it block you.
+- Have something to show at least every 20 minutes: a push or a short progress line.
+- When an answer is unclear, take its narrowest safe reading and say so. Keep working on whatever doesn't depend on a question, and don't ask twice.
+- To split the work or take more, ask the Lead. You may propose new work; the Lead decides.
+
+## 3. Blocked
+- A person's decision: mark needs-human with one short question.
+- Can't go on: mark blocked with why and what would unblock you, then do the independent parts.
+- Stop and ask before anything irreversible, security-sensitive, outside your worktree, visible or audible on a real device, or moving hardware.
+
+## 4. Hand off
+- Ready means: your branch pushed, a PR when the project uses PRs, and green CI on it.
+- The handoff opens "Ready: yes" or "Ready: no", then: revision, what you checked (command and result), what is not shown yet, the one command or action left for the real device or person if any, and "most likely wrong here".
+- Mark ready for review when the group has a Reviewer; otherwise mark done.
+
+## 5. Review findings
+- Check each finding against the code; push back with evidence when it is wrong.
+- Fix the real ones, rerun the checks, and reply with what you changed and the result.
+- Mark ready again with the new revision.
+
+## 6. Talk
+- Keep posts short: one result line and the command, no logs, short revision hashes.
+- Every post carries a result, a question, or a fault; never an acknowledgement alone.
+- Write to people in their language, without commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.
+`,
+ review: `---
+name: swarm-review
+description: Use when you are a Harness Swarm Reviewer checking another agent's group work before the Lead accepts it.
+---
+# Review a group's work
+
+You give an independent verdict on one revision. Work otherwise the way you normally do.
+
+## Core rules
+1. Read only. Never edit, commit or push the Builder's work, and never merge your own review target.
+2. Read everything before judging: the brief, the handoff, the diff and the last comments.
+3. Every verdict names the revision it covers.
+4. Project instructions (AGENTS.md, CLAUDE.md, CONTRIBUTING) outrank this skill.
+
+## 1. When
+Start within 30 minutes of being asked; oldest ready work first. If you cannot, tell the Lead.
+
+## 2. What to look for
+- Wrong behaviour, missed cases, and what the brief asked for but is missing.
+- A switch that is not really off, a default that changed, a test that cannot fail.
+- A doc or comment that disagrees with the code; a number nobody measured.
+- Evidence: does the handoff show what it claims, on this revision? Run the project's checks yourself when the handoff's evidence does not cover a doubt.
+
+## 3. Report in the Builder's group
+- Findings P1 (must fix), P2 (fix before accepting), P3 (later), each with file:line, what is wrong and the fix.
+- Verdict: "No finding on <rev>", or "Hold — <rev>" with the findings. A re-review covers only the new changes.
+- Pass or fail the independent check with the revision and verdict.
+- Tell the Lead at once about privacy, interface breaks, default-on changes to safety or updates, and device behaviour nobody could show.
+- Keep posts short, in the people's language, without commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.
+
+## 4. Finish
+Mark your review done with the verdict and revision.
+`,
+}
+const skills: Record<SwarmSkillMode, Record<SwarmRole, string>> = { default: defaults, orchestration }
+
+/** What a session is told to use, in its mode's words: a Default agent otherwise works its usual way. */
+export function swarmSkillUse(role: SwarmRole, mode: SwarmSkillMode): string {
+ return mode === 'default' ? `Use the swarm-${role} skill for this session: the team process; otherwise work your usual way.`
+ : `Use the built-in swarm-${role} skill for this session.`
+}
+const MODE_NAMES: Record<SwarmSkillMode, string> = { default: 'Default', orchestration: 'Harness orchestration' }
+/** The mode whose current text this is; null for any other text (an older release, or the agent's own edits). */
+const modeOf = (role: SwarmRole, version: string) =>
+ (['default', 'orchestration'] as const).find(mode => textVersion(skills[mode][role]) === version) ?? null
+
/** Launch and relaunch keep a session's saved bytes; only refreshSwarmSkill moves a running session to new built-in text.
- * No project-wide native skill links: two roles may share a workspace. */
+ * A new file holds the text of the session's saved mode; a kept one is described by the text it holds, so the prompt line
+ * never names one mode while the file holds the other. 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 = skillDirectory(root, saved, true)!
ignoreHarnessRuntime(root)
const file = join(dir, 'SKILL.md')
+ let mode = saved.mode ?? 'orchestration'
if (existsSync(file)) {
plainFile(file)
// Read now so an unreadable saved skill refuses launch, rather than silently dropping the role.
- readFileSync(file, 'utf8')
+ mode = modeOf(saved.role, textVersion(readFileSync(file, 'utf8'))) ?? mode
} else {
- writeFileSync(file, skills[saved.role], { flag: 'wx', mode: 0o600 })
- const version = textVersion(skills[saved.role])
- writeRecord(dir, { text: version, notified: version })
+ const text = skills[mode][saved.role], version = textVersion(text)
+ writeFileSync(file, text, { flag: 'wx', mode: 0o600 })
+ writeRecord(dir, { text: version, notified: version, mode, told: mode, change: 0, toldChange: 0 })
}
- 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.` }
+ return { file, instructions: `${swarmSkillUse(saved.role, mode)} Before working, read ${JSON.stringify(file)} with your file or shell tool.` }
}
-/** Which built-in text a session's skill file holds, and which text its agent was last told to re-read. A file from before
- * this record counts as holding its own content, already told. */
-interface SkillRecord { text: string; notified: string }
-export interface SkillRefresh { file: string; version: string; owed: boolean }
-
-/** A CLI update ships new skill text while Swarm sessions run (owner, 2026-10-22). Rewrite a session's file to the
- * built-in text and say whether its agent still owes a re-read notice for it; recordSwarmSkillNotice clears that once
- * the notice is sent. A file from before records gets its record first, and the record moves to the new text only after
- * the file is replaced, so an interrupted pass rewrites again and the notice stays owed until it is recorded. Null when
- * this workspace never prepared the session's skill. */
-export function refreshSwarmSkill(workspace: string, saved: SwarmSkill): SkillRefresh | null {
+/** Which built-in text a session's skill file holds and of which mode, how many times the file was rewritten, and the text,
+ * mode and rewrite its agent was last confirmed told about (the launch prompt is rewrite 0). A file from before this record
+ * counts as holding its own content, already told; one from before modes, as orchestration. */
+interface SkillRecord { text: string; notified: string; change?: number; mode?: SwarmSkillMode; told?: SwarmSkillMode; toldChange?: number }
+/** `change` counts rewrites, so a notice for a switch back to an earlier mode's text is a new notice, not a repeat. */
+export interface SkillRefresh { file: string; version: string; owed: boolean; change: number; notice: string }
+
+/** A CLI update ships new skill text while Swarm sessions run (owner, 2026-10-22), and the project's owner may switch its
+ * mode (2026-10-23). Rewrite a session's file to the mode's built-in text and say whether its agent still owes a re-read
+ * notice for it; recordSwarmSkillNotice clears that once the notice is sent. A file from before records gets its record
+ * first, and the record moves to the new text only after the file is replaced, so an interrupted pass rewrites again and
+ * the notice stays owed until it is recorded. Null when this workspace never prepared the session's skill. */
+export function refreshSwarmSkill(workspace: string, saved: SwarmSkill, mode: SwarmSkillMode): SkillRefresh | null {
if (!parseSwarmSkill(saved)) throw new Error('A Swarm skill needs a role and session key')
// A removed worktree has nothing to refresh; the host would otherwise retry and log it every minute.
if (!existsSync(workspace)) return null
@@ -374,24 +543,41 @@ export function refreshSwarmSkill(workspace: string, saved: SwarmSkill): SkillRe
const file = dir && join(dir, 'SKILL.md')
if (!dir || !file || !existsSync(file)) return null
plainFile(file)
- const text = skills[saved.role], version = textVersion(text)
- let record = readRecord(dir)
- if (!record) {
- const held = textVersion(readFileSync(file, 'utf8'))
- record = { text: held, notified: held }
- if (held !== version) writeRecord(dir, record)
+ const text = skills[mode][saved.role], version = textVersion(text)
+ const held = textVersion(readFileSync(file, 'utf8'))
+ let record = readRecord(dir) ?? { text: held, notified: held }
+ if (record.toldChange === undefined) {
+ // A record from before rewrite counts (#1585) gets its baseline first, so a rewrite after it is owed by count, never by
+ // comparing texts: a switch away and back would otherwise match the text last told and leave the agent on the other.
+ const change = record.change ?? 0
+ record = { ...record, change, toldChange: record.notified === record.text ? change : change - 1 }
+ writeRecord(dir, record)
}
if (record.text !== version) {
replaceFile(file, text)
- record = { ...record, text: version }
+ record = { ...record, text: version, mode, change: (record.change ?? 0) + 1 }
writeRecord(dir, record)
+ } else if (held !== version && modeOf(saved.role, held)) {
+ // A switch stopped after replacing the file and before its record, and the project switched back: the record already
+ // describes this text and no notice went out for the other, so only the file is put back. The agent's own edits are
+ // no built-in text and stay.
+ replaceFile(file, text)
}
- return { file, version, owed: record.notified !== version }
+ const change = record.change ?? 0
+ // A notice counts once it is recorded: one sent whose record was lost may have moved the agent to another text, so a
+ // later rewrite is owed even when it brings back the text last confirmed.
+ const owed = record.toldChange !== change
+ const switched = (record.told ?? 'orchestration') !== mode || owed && record.notified === version
+ const reread = `Before your next step, read ${JSON.stringify(file)} again with your file or shell tool and follow`
+ return { file, version, owed, change,
+ notice: switched ? `This project now uses the ${MODE_NAMES[mode]} skills. ${reread} it in place of your earlier swarm-${saved.role} skill.`
+ : `Harness updated your ${mode === 'default' ? '' : 'built-in '}swarm-${saved.role} skill. ${reread} the new version.` }
}
-export function recordSwarmSkillNotice(workspace: string, saved: SwarmSkill, version: string): void {
+/** The notice for that refresh's rewrite was sent. A later rewrite since then stays owed. */
+export function recordSwarmSkillNotice(workspace: string, saved: SwarmSkill, sent: Pick<SkillRefresh, 'version' | 'change'>): void {
const dir = skillDirectory(realpathSync(workspace), saved, false)
const record = dir && readRecord(dir)
- if (dir && record) writeRecord(dir, { ...record, notified: version })
+ if (dir && record) writeRecord(dir, { ...record, notified: sent.version, toldChange: sent.change, told: modeOf(saved.role, sent.version) ?? record.told })
}
const textVersion = (text: string) => createHash('sha256').update(text).digest('hex')
@@ -421,7 +607,10 @@ function readRecord(dir: string): SkillRecord | null {
if (!existsSync(file)) return null
plainFile(file)
const record = JSON.parse(readFileSync(file, 'utf8')) as Partial<SkillRecord>
- return typeof record.text === 'string' && typeof record.notified === 'string' ? { text: record.text, notified: record.notified } : null
+ return typeof record.text === 'string' && typeof record.notified === 'string'
+ ? { text: record.text, notified: record.notified, ...(typeof record.change === 'number' ? { change: record.change } : {}),
+ ...(isSwarmSkillMode(record.mode) ? { mode: record.mode } : {}), ...(isSwarmSkillMode(record.told) ? { told: record.told } : {}),
+ ...(typeof record.toldChange === 'number' ? { toldChange: record.toldChange } : {}) } : null
}
function writeRecord(dir: string, record: SkillRecord): void {
replaceFile(join(dir, 'version.json'), JSON.stringify(record))
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index c1c4dfbd2..cbe8b5c87 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -55,7 +55,7 @@ describe('current Swarm role lookup', () => {
let groups = [{ leadId: 'other', agentIds: ['agent'] }]
vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data:
path.includes('/hosts/') ? [{ tabId: 'tab', agent }] : { state: { agents: [agent], conversations: groups } } } }))
- expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBe('review')
+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toEqual({ role: 'review', mode: 'orchestration' })
groups = []
expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBeNull()
})
@@ -66,9 +66,23 @@ describe('current Swarm role lookup', () => {
assignment: kind === 'assigned' ? { agentId: 'agent', execution: { machineId: 'machine-1' } } : null }
vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data:
path.includes('/hosts/') ? [{ tabId: 'tab', agent }] : { state: { agents: [agent], conversations: [group] } } } }))
- expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBe(kind === 'lead' ? 'lead' : 'dev')
+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toEqual({ role: kind === 'lead' ? 'lead' : 'dev', mode: 'orchestration' })
expect(await swarmRoleFor(t.core, 'machine-1', 'personal')).toBeNull()
})
+ it('gives the mode of the project whose group made the role, Lead first', async () => {
+ const t = setup()
+ const agent = { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }
+ const projects = [{ id: 'lead', skillMode: 'default' }, { id: 'p2', skillMode: 'orchestration' }, { id: 'p3', skillMode: 'default' }]
+ let conversations: unknown[] = [{ projectId: 'p2', leadId: 'other', agentIds: ['agent'] }, { projectId: 'p3', leadId: 'agent', agentIds: [] }]
+ vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data:
+ path.includes('/hosts/') ? [{ tabId: 'tab', agent }] : { state: { agents: [agent], conversations, projects } } } }))
+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toEqual({ role: 'lead', mode: 'default' })
+ conversations = [{ projectId: 'p2', leadId: 'other', agentIds: ['agent'] }]
+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toEqual({ role: 'dev', mode: 'orchestration' })
+ // A group from before projects is in the first project.
+ conversations = [{ leadId: 'other', agentIds: ['agent'] }]
+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toEqual({ role: 'dev', mode: 'default' })
+ })
it.each(['removed-roster', 'foreign', 'removed-state', 'archived', 'released', 'none', 'malformed'] as const)
('never adopts a session whose membership is %s', async kind => {
const t = setup()
@@ -85,7 +99,7 @@ describe('current Swarm role lookup', () => {
vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data: path.includes('/hosts/')
? present ? [{ tabId: 'tab', agent }] : []
: { state: { agents: [agent], conversations: [{ agentIds: ['agent'] }, { leadId: 'agent' }] } } } }))
- expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBe('lead')
+ expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toEqual({ role: 'lead', mode: 'orchestration' })
present = false
expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBeNull()
expect(await swarmRoleFor(t.core, 'machine-1', 'harness')).toBeNull()
@@ -975,14 +989,15 @@ describe('adding the machine its own Lead runs on to the Swarm', () => {
describe('built-in skill text after a CLI update', () => {
const older = '---\nname: swarm-dev\n---\nAn older release of this skill.\n'
- function syncFixture(stale = true) {
+ function syncFixture(stale = true, mode?: 'default' | 'orchestration') {
+ let skillMode = mode
const t = setup(), workspace = mkdtempSync(join(tmpdir(), 'super-tab-skills-')); roots.push(workspace)
const roles = { lead: 'lead', builder: 'dev', reviewer: 'review' } as const
const sessions = Object.fromEntries([...Object.entries(roles).map(([name, role]) => [`h-${name}`,
{ agentId: `h-${name}`, cwd: workspace, swarmSkill: { role, key: `key-${name}` } }]),
['h-personal', { agentId: 'h-personal', cwd: workspace }]])
const files = Object.fromEntries(Object.entries(roles).map(([name, role]) => {
- const { file } = prepareSwarmSkill(workspace, { role, key: `key-${name}` })
+ const { file } = prepareSwarmSkill(workspace, { role, key: `key-${name}`, ...(mode ? { mode } : {}) })
// What an older CLI left: its own text and no record of which text it was.
if (stale) { writeFileSync(file, older); rmSync(join(dirname(file), 'version.json')) }
return [name, file]
@@ -1002,7 +1017,7 @@ describe('built-in skill text after a CLI update', () => {
await Promise.resolve()
inFlight--
const request = body as any
- if (path.includes('/hosts/')) return { status: 200, body: { data: agents.map(agent => ({ tabId: 'tab', agent })) } }
+ if (path.includes('/hosts/')) return { status: 200, body: { data: agents.map(agent => ({ tabId: 'tab', agent, ...(skillMode ? { skillMode } : {}) })) } }
if (path.endsWith('/deliveries')) return { status: 200, body: { data: [] } }
if (request?.command?.type === 'message.send') {
// As the backend does: a repeated operation gets its first receipt; the same id for a different request is refused.
@@ -1019,7 +1034,7 @@ describe('built-in skill text after a CLI update', () => {
for (let idle = 0; idle < 3;) { await new Promise(resolve => setImmediate(resolve)); idle = inFlight ? 0 : idle + 1 }
return host
}
- return { t, files, sent, pass, setGroups: (next: typeof groups) => { groups = next } }
+ return { t, files, sent, pass, setGroups: (next: typeof groups) => { groups = next }, setMode: (next: typeof mode) => { skillMode = next } }
}
it('rewrites each running Lead, Builder and Reviewer skill once and tells each agent once, never a personal session', async () => {
@@ -1041,10 +1056,10 @@ describe('built-in skill text after a CLI update', () => {
await f.pass()
const lead = join(dirname(f.files.lead!), 'version.json'), record = JSON.parse(readFileSync(lead, 'utf8'))
// The send succeeded, the record did not survive, and the Lead's group was archived meanwhile.
- writeFileSync(lead, JSON.stringify({ ...record, notified: 'older' }))
+ writeFileSync(lead, JSON.stringify({ ...record, notified: 'older', toldChange: undefined }))
f.setGroups([{ id: 'lead-group', archived: true, leadId: 'a-lead', agentIds: ['a-lead'] }, { id: 'next', leadId: 'a-lead', agentIds: ['a-lead'] }])
await f.pass()
- expect(JSON.parse(readFileSync(lead, 'utf8')).notified).toBe(record.notified)
+ expect(JSON.parse(readFileSync(lead, 'utf8'))).toMatchObject({ notified: record.notified, toldChange: record.toldChange })
expect(f.t.log).not.toHaveBeenCalled()
const calls = vi.mocked(f.t.core.account.backend).mock.calls.length
await f.pass()
@@ -1052,6 +1067,41 @@ describe('built-in skill text after a CLI update', () => {
expect(f.sent).toHaveLength(3)
})
+ it('moves running agents to the project\'s new mode at once, tells each once, and again when it switches back', async () => {
+ const f = syncFixture(false, 'default')
+ const defaults = Object.fromEntries(Object.entries(f.files).map(([name, file]) => [name, readFileSync(file, 'utf8')]))
+ // A new Default agent started with its mode's text: nothing to rewrite or tell.
+ const host = await f.pass()
+ expect(f.sent).toEqual([])
+ f.setMode('orchestration')
+ await f.pass(host, 1_000)
+ expect(f.sent.map(s => s.asAgentId).sort()).toEqual(['a-builder', 'a-lead', 'a-reviewer'])
+ for (const s of f.sent) expect(s.command.text).toBe(`This project now uses the Harness orchestration skills. Before your next step, read ${JSON.stringify(f.files[s.asAgentId.slice(2)])} again with your file or shell tool and follow it in place of your earlier swarm-${({ lead: 'lead', builder: 'dev', reviewer: 'review' } as Record<string, string>)[s.asAgentId.slice(2)]} skill.`)
+ expect(readFileSync(f.files.builder!, 'utf8')).toContain('No production code without a failing test first.')
+ await f.pass(host, 1_000)
+ expect(f.sent).toHaveLength(3)
+ f.setMode('default')
+ await f.pass(host, 1_000)
+ expect(f.sent).toHaveLength(6)
+ expect(new Set(f.sent.map(s => s.operationId)).size).toBe(6)
+ expect(f.sent.slice(3).every(s => s.command.text.startsWith('This project now uses the Default skills.'))).toBe(true)
+ for (const [name, file] of Object.entries(f.files)) expect(readFileSync(file, 'utf8')).toBe(defaults[name])
+ await f.pass(host, 1_000)
+ await f.pass()
+ expect(f.sent).toHaveLength(6)
+ })
+
+ it('reads a roster row without a mode, or with one it does not know, as Harness orchestration', async () => {
+ const f = syncFixture(false, 'default')
+ f.setMode(undefined)
+ await f.pass()
+ expect(f.sent.map(s => s.command.text.split('.')[0])).toEqual(Array(3).fill('This project now uses the Harness orchestration skills'))
+ const g = syncFixture(false)
+ g.setMode('light' as never)
+ await g.pass()
+ expect(g.sent).toEqual([])
+ })
+
it('says nothing when the skill files already hold the built-in text', async () => {
const f = syncFixture(false)
await f.pass()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index d59f29c7c..2920de9fe 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -24,7 +24,7 @@ export class SuperTabHostError extends Error {
}
export { identifier, object } from './wire.js'
import { ENDED_WORK, identifier, object } from './wire.js'
-import { recordSwarmSkillNotice, refreshSwarmSkill, type SwarmRole, type SwarmSkill } from '../lib/swarmSkills.js'
+import { recordSwarmSkillNotice, refreshSwarmSkill, type SkillRefresh, type SwarmSkillGrant, type SwarmSkillMode } from '../lib/swarmSkills.js'
/** The core signs each request. Neither the service nor its journal holds an account credential. */
export async function backend(core: CoreApi, method: string, path: string, body?: unknown): Promise<unknown> {
@@ -37,13 +37,20 @@ export async function backend(core: CoreApi, method: string, path: string, body?
return reply.body.data
}
+/** The skills of a group's project in a tab state: a group from before projects is in the first, and a project from before
+ * modes, or a Swarm from before projects, is orchestration. */
+export function groupSkillMode(state: Record<string, unknown>, group: Record<string, unknown> | undefined): SwarmSkillMode {
+ const project = group && (Array.isArray(state.projects) ? state.projects.map(object) : []).find(p => p.id === (group.projectId ?? 'lead'))
+ return project?.skillMode === 'default' ? 'default' : 'orchestration'
+}
+
/** Restart/resume can include stopped harnesses, so the live process list is not membership proof.
* Re-read the exact machine roster and its groups; a removed contribution must never adopt a skill. */
-export async function swarmRoleFor(core: CoreApi, machineId: string, harnessId: string): Promise<SwarmRole | null> {
+export async function swarmRoleFor(core: CoreApi, machineId: string, harnessId: string): Promise<SwarmSkillGrant | null> {
if (!identifier(machineId) || !identifier(harnessId)) return null
const rows = await backend(core, 'GET', `/api/super-tabs/hosts/${machineId}`)
if (!Array.isArray(rows)) return null
- const roles = await Promise.all(rows.map(object).filter(row => {
+ const grants = await Promise.all(rows.map(object).filter(row => {
const agent = object(row.agent)
return identifier(row.tabId) && identifier(agent.id) && agent.machineId === machineId
&& agent.harnessId === harnessId && row.stopRequested !== true
@@ -55,12 +62,13 @@ export async function swarmRoleFor(core: CoreApi, machineId: string, harnessId:
&& agent.harnessId === harnessId && agent.machineId === machineId && agent.workDecision !== 'stop')
if (!agent) return null
const groups = (Array.isArray(state.conversations) ? state.conversations.map(object) : []).filter(group => group.archived !== true)
- if (groups.some(group => group.leadId === target.id)) return 'lead'
- return groups.some(group => Array.isArray(group.agentIds) && group.agentIds.includes(target.id)
+ const led = groups.find(group => group.leadId === target.id)
+ if (led) return { role: 'lead' as const, mode: groupSkillMode(state, led) }
+ const member = groups.find(group => Array.isArray(group.agentIds) && group.agentIds.includes(target.id)
|| object(group.assignment).agentId === target.id && object(object(group.assignment).execution).machineId === machineId)
- ? agent.role === 'reviewer' ? 'review' : 'dev' : null
+ return member ? { role: agent.role === 'reviewer' ? 'review' as const : 'dev' as const, mode: groupSkillMode(state, member) } : null
}))
- return (['lead', 'dev', 'review'] as const).find(role => roles.includes(role)) ?? null
+ return (['lead', 'dev', 'review'] as const).map(role => grants.find(grant => grant?.role === role)).find(Boolean) ?? null
}
interface Entry {
@@ -73,7 +81,8 @@ interface Entry {
receipt?: string
}
interface Journal { version: 1; machineId: string; entries: Record<string, Entry> }
-interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string; releaseId?: string } }
+/** `skillMode` is the agent's project's skills; a row without it (an older backend, a project from before modes) is orchestration. */
+interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string; releaseId?: string }; skillMode?: unknown }
export interface SuperTabHostOptions {
now?: () => number
write?: (file: string, journal: Journal) => void
@@ -166,6 +175,8 @@ export class SuperTabHost {
/** When each running Swarm session's skill is next compared with the built-in text: once per host, and again while
* its re-read notice is still owed. */
private readonly skillChecks = new Map<string, number>()
+ /** The mode each session's skill was last compared with: a change makes it due again at once. */
+ private readonly skillModes = new Map<string, SwarmSkillMode>()
private skillsRunning: Promise<void> | null = null
private missing = new Map<string, number>()
@@ -524,20 +535,26 @@ export class SuperTabHost {
private async refreshSkill(target: HostAgent): Promise<void> {
const session = this.core.agents.byAgent(target.agent.harnessId)
const skill = session?.swarmSkill
+ const mode: SwarmSkillMode = target.skillMode === 'default' ? 'default' : 'orchestration'
+ // A checked session waits for the next host (Infinity); the project's owner switching its skills must reach it now.
+ if (this.skillModes.get(target.agent.harnessId) !== mode) {
+ this.skillModes.set(target.agent.harnessId, mode)
+ this.skillChecks.delete(target.agent.harnessId)
+ }
const due = this.skillChecks.get(target.agent.harnessId) ?? 0
if (!skill || !session.cwd || this.now() < due) return
this.skillChecks.set(target.agent.harnessId, Infinity)
try {
- const refresh = refreshSwarmSkill(session.cwd, skill)
+ const refresh = refreshSwarmSkill(session.cwd, skill, mode)
if (!refresh?.owed) return
- if (await this.tellSkill(target, skill, refresh)) recordSwarmSkillNotice(session.cwd, skill, refresh.version)
+ if (await this.tellSkill(target, refresh)) recordSwarmSkillNotice(session.cwd, skill, refresh)
else this.skillChecks.set(target.agent.harnessId, this.now() + SKILL_RETRY_MS)
} catch (error) {
this.log(error instanceof Error ? error.message : String(error))
this.skillChecks.set(target.agent.harnessId, this.now() + SKILL_RETRY_MS)
}
}
- private async tellSkill(target: HostAgent, skill: SwarmSkill, refresh: { file: string; version: string }): Promise<boolean> {
+ private async tellSkill(target: HostAgent, refresh: SkillRefresh): Promise<boolean> {
const id = target.agent.id
const answer = object(await backend(this.core, 'GET', `/api/super-tabs/${target.tabId}?asAgentId=${id}`))
const groups = (Array.isArray(object(answer.state).conversations) ? object(answer.state).conversations as unknown[] : []).map(object)
@@ -546,9 +563,9 @@ export class SuperTabHost {
if (!group) return false
try {
await backend(this.core, 'POST', `/api/super-tabs/${target.tabId}/commands`, {
- operationId: `skill-${id}-${refresh.version.slice(0, 32)}`, asAgentId: id,
- command: { type: 'message.send', conversationId: group.id, replyTo: null, recipientIds: [id],
- text: `Harness updated your built-in swarm-${skill.role} skill. Before your next step, read ${JSON.stringify(refresh.file)} again with your file or shell tool and follow the new version.` },
+ // A switch back to an earlier mode's text is a new rewrite, so its count keeps it from reusing that text's id.
+ operationId: `skill-${id}-${refresh.version.slice(0, 32)}${refresh.change ? `-${refresh.change}` : ''}`, asAgentId: id,
+ command: { type: 'message.send', conversationId: group.id, replyTo: null, recipientIds: [id], text: refresh.notice },
})
} catch (error) {
// The notice was sent, but its record was lost (a crash, a restart, another daemon) and its group has changed since:
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 6fac3c599..1faa4cf9d 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -21,6 +21,7 @@ describe('restart role lookup through the service', () => {
const core = fakeCore({ account: { backend: vi.fn(async () => ({ status: 200, body: { data: [] } })) } })
const service = superTabService(core, { host })
expect(await service.port.swarmRole('personal')).toBeNull()
+ expect(await service.requests.super_tabs({ action: 'swarmRole', harnessId: 'personal' }, owner)).toEqual({ ok: true, role: null })
expect(host).not.toHaveBeenCalled()
service.port.stop()
})
@@ -29,8 +30,8 @@ describe('restart role lookup through the service', () => {
const call = vi.fn<CoreApi['account']['backend']>(async (_method, path) => ({ status: 200, body: { data:
path.includes('/hosts/') ? [{ tabId: 'tab', agent }] : { state: { agents: [agent], conversations: [{ leadId: 'agent' }] } } } }))
const service = superTabService(fakeCore({ account: { backend: call } }))
- expect(await service.port.swarmRole('old-native')).toBe('lead')
- expect(await service.requests.super_tabs({ action: 'swarmRole', harnessId: 'old-native' }, owner)).toEqual({ ok: true, role: 'lead' })
+ expect(await service.port.swarmRole('old-native')).toEqual({ role: 'lead', mode: 'orchestration' })
+ expect(await service.requests.super_tabs({ action: 'swarmRole', harnessId: 'old-native' }, owner)).toEqual({ ok: true, role: 'lead', mode: 'orchestration' })
expect(await service.requests.super_tabs({ action: 'swarmRole', harnessId: 'old-native' }, visitor)).toMatchObject({ error: 'OWNER_REQUIRED' })
call.mockRejectedValueOnce(new Error('Offline'))
expect(await service.port.swarmRole('old-native')).toBeUndefined()
@@ -176,6 +177,13 @@ it('documents how a lead shares its project repository for other machines', asyn
const answer = await t.ask({ action: 'help' }, owner) as { help: { commands: Array<Record<string, unknown>> } }
expect(answer.help.commands).toContainEqual({ type: 'project.repository', projectId: 'PROJECT', repositoryUrl: 'https://github.com/OWNER/REPOSITORY' })
})
+it('tells the Lead how to switch a project\'s skills on its owner\'s own request', async () => {
+ const t = setup()
+ const answer = await t.ask({ action: 'help' }, owner) as { help: { command: string; commands: Array<Record<string, unknown>> } }
+ expect(answer.help.commands).toContainEqual({ type: 'project.skills', projectId: 'PROJECT', mode: 'default|orchestration',
+ askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } })
+ expect(answer.help.command).toContain('project.skills switches a project between the Default and Harness orchestration skills: only its project owner does, or its Lead passing on that owner\'s own chat message, with askedIn naming it.')
+})
it('tells the Lead that start works only on a machine in the Swarm\'s Machines list', async () => {
const t = setup()
const answer = await t.ask({ action: 'help' }, owner) as { help: { start: string } }
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index d51155651..e686f0b87 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -23,10 +23,11 @@ const HELP = {
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, 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. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. rule.set and rule.remove change one project\'s routing rules: only the project owner does (naming projectId), or that project\'s Lead passing on the project owner\'s request, with askedIn naming the project owner\'s message in that project\'s chat. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine and preferIdle only rank.',
+ command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request. When your assignment needs a person to decide, set work.status needs_human; when you cannot go on, blocked. Set working again once it moves. rule.set and rule.remove change one project\'s routing rules: only the project owner does (naming projectId), or that project\'s Lead passing on the project owner\'s request, with askedIn naming the project owner\'s message in that project\'s chat. project.skills switches a project between the Default and Harness orchestration skills: only its project owner does, or its Lead passing on that owner\'s own chat message, with askedIn naming it. A start, assignment or route that breaks a hard rule (forbidModel, machines, minEffort) is refused for agents; preferEngine and preferIdle only rank.',
commands: [
{ type: 'project.report', projectId: 'PROJECT', throughRevision: 123, text: 'What changed, what is blocked, and what comes next. Use null when nothing merits repeating.' },
{ type: 'project.repository', projectId: 'PROJECT', repositoryUrl: 'https://github.com/OWNER/REPOSITORY' },
+ { type: 'project.skills', projectId: 'PROJECT', mode: 'default|orchestration', askedIn: { conversationId: 'GROUP', messageId: 'OWNER_MESSAGE' } },
{ type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },
{ type: 'conversation.create', title: 'Outcome', task: { goal: 'An independently assignable result', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'] }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },
{ type: 'conversation.create', title: 'Review: Outcome', reviewOf: 'GROUP', task: { goal: 'An independent verdict on the Builder\'s revision', changes: 'None: read only', constraints: 'The reviewed group\'s constraints', owns: ['The reviewed group\'s owned code, read only'] }, checks: [{ description: 'Verdict with the reviewed revision', independent: false }] },
@@ -128,7 +129,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
},
disconnected: disconnect,
stop: disconnect,
- swarmRole: async (harnessId: string) => (await within(swarmRoleFor(core, core.daemon.machineId(), harnessId).then(role => ({ role }))))?.role,
+ swarmRole: async (harnessId: string) => (await within(swarmRoleFor(core, core.daemon.machineId(), harnessId).then(grant => ({ grant }))))?.grant,
}
const requests: ServiceRequests = {
super_tabs: async (payload, asker, closed) => {
@@ -147,7 +148,10 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
return await wake().prepareNative(payload.tabId, payload.contextId, payload.action === 'renewNative', closed)
}
if (!asker.owner || (!asker.local && asker.accountOwner !== true)) return { error: 'OWNER_REQUIRED' }
- if (payload.action === 'swarmRole') return { ok: true, role: await port.swarmRole(String(payload.harnessId ?? '')) }
+ if (payload.action === 'swarmRole') {
+ const grant = await port.swarmRole(String(payload.harnessId ?? ''))
+ return { ok: true, role: grant ? grant.role : grant, ...(grant ? { mode: grant.mode } : {}) }
+ }
if (payload.action === 'prepareContribution') return preparations.read(payload)
// The devices' (core/devicesLink.ts): a Harness Pro that shows the Swarm cards is attached or gone, wants a Lead's recap, or
// has one open. They read the account's Swarms as the person, and need no agent.
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index a7ff0032f..80932b420 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -9,12 +9,16 @@ import type { RegisteredSession } from '../lib/registry.js'
import type { AgentFrame } from '../lib/agentFrame.js'
import { buildEngineCommandArgv } from '../lib/engineLaunch.js'
const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }
-function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
+function fixture(options: { state?: Record<string, unknown> | Error; refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
const start = { creationId: 'super-native-receipt', error: null as string | null, request: { machineId: 'target', conversationId: 'group', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }, dispatched: false }
let nativeState = 'missing', lostJoin = false
const scoped = vi.fn(async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
if (payload.action === 'startStatus') return { ok: true, value: structuredClone(start) }
+ if (payload.action === 'status') {
+ if (options.state instanceof Error) throw options.state
+ return { ok: true, value: { revision: 1, state: options.state ?? { conversations: [{ id: 'group' }] } } }
+ }
const cmd = payload.command as Record<string, unknown>
if (cmd.type === 'agent.startDispatch') start.dispatched = true
if (cmd.type === 'agent.startFailed') {
@@ -225,6 +229,36 @@ it.each(['claude', 'codex'])('starts a %s Reviewer with the built-in swarm-revie
expect(payload.prompt).not.toContain('swarm-dev')
})
+describe('the skills of the project the agent joins', () => {
+ const projects = (skillMode?: string) => ({ conversations: [{ id: 'other', projectId: 'p1' }, { id: 'group', projectId: 'p2' }],
+ projects: [{ id: 'p1', skillMode: 'default' }, { id: 'p2', ...(skillMode ? { skillMode } : {}) }] })
+ const started = async (state: Record<string, unknown> | Error, role?: string) => {
+ const f = fixture({ state })
+ if (role) f.start.request = { ...f.start.request, role } as typeof f.start.request
+ expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'mode', request: f.start.request }, f.scoped, where, f.open)).toMatchObject({ ok: true })
+ return f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!
+ }
+ it.each([undefined, 'reviewer'])('starts a Default project\'s agent (role %s) with the Default text and a prompt line that fits it', async role => {
+ const payload = await started(projects('default'), role), skill = role ? 'review' : 'dev'
+ expect(payload).toMatchObject({ swarmRole: skill, swarmSkillMode: 'default' })
+ expect(payload.prompt).toContain(`Use the swarm-${skill} skill for this session: the team process; otherwise work your usual way. Run harness`)
+ expect(payload.prompt).not.toContain('built-in')
+ })
+ it('starts a Harness orchestration project\'s agent with the built-in text', async () => {
+ const payload = await started(projects('orchestration'))
+ expect(payload).toMatchObject({ swarmRole: 'dev', swarmSkillMode: 'orchestration' })
+ expect(payload.prompt).toContain('Use the built-in swarm-dev skill for this session. Run harness')
+ })
+ it.each([
+ ['a project from before modes', projects()],
+ ['a Swarm from before projects', { conversations: [{ id: 'group' }] }],
+ ['a group it cannot see', { conversations: [], projects: [{ id: 'lead', skillMode: 'default' }] }],
+ ['a state it cannot read', new Error('offline')],
+ ])('reads %s as Harness orchestration', async (_name, state) => {
+ expect(await started(state)).toMatchObject({ swarmSkillMode: 'orchestration' })
+ })
+})
+
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))
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index 73ded42ca..1bd751303 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -3,9 +3,10 @@ import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'
import { randomUUID } from 'node:crypto'
import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
import { admission, quotaOf, type Requirements } from './capacity.js'
-import { identifier, object } from './host.js'
+import { groupSkillMode, identifier, object } from './host.js'
import { permissionModeFlags } from '../lib/engineLaunch.js'
import type { AgentEngine } from '../engines/types.js'
+import { swarmSkillUse, type SwarmSkillMode } from '../lib/swarmSkills.js'
type Json = Record<string, unknown>
export type ScopedRequest = (payload: Json) => Promise<Json>
@@ -50,6 +51,14 @@ export async function inspectCapacity(target: Daemon, request: Json) {
return { capacity, engine, quota, ...admission(capacity, engine, quota, requirements, !!request.codexHome || !!request.gridModel) }
}
+/** The skills of the project whose group the agent joins, so it starts on that text and is never moved to it at once. A
+ * project from before modes, or a state this start cannot read, is orchestration; the host moves a running agent to its
+ * project's mode (superTabs/host.ts) if that guess is wrong. */
+async function projectSkillMode(scoped: ScopedRequest, conversationId: unknown): Promise<SwarmSkillMode> {
+ const state = object(object(object(await scoped({ action: 'status' }).catch(() => ({}))).value).state)
+ return groupSkillMode(state, (Array.isArray(state.conversations) ? state.conversations.map(object) : []).find(group => group.id === conversationId))
+}
+
/** Whether the machine launches `engine` with a model of its own for that session (lib/launchModel.ts). A daemon from
* before the flags does not name the field, and agent_create would silently drop a model it does not know. */
const launchesWithModel = (capacity: Json, engine: unknown) => Array.isArray(capacity.launchModel) && capacity.launchModel.includes(engine)
@@ -143,10 +152,11 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
// Engines without a full mode retain their existing approving launch flags.
// The backend starts a Reviewer only on Claude Code or Codex, the engines with built-in Swarm skills.
const skilled = ['claude', 'codex'].includes(String(request.engine)), reviewer = request.role === 'reviewer'
+ const role = reviewer ? 'review' : 'dev', mode = skilled ? await projectSkillMode(scoped, request.conversationId) : null
const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: true,
...(permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
- ...(skilled ? { swarmRole: reviewer ? 'review' : 'dev' } : {}),
- prompt: `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${skilled ? `Use the built-in swarm-${reviewer ? 'review' : 'dev'} skill. ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer
+ ...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),
+ prompt: `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer
? `Do not review yet. You review work in conversation ${request.conversationId} when it is ready for review.`
: `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}`,