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.

Custom roles per project: CLI installs a role's skill, re-read on change, roles in help (#1660)

0xken15862882e8adb4
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 169cf9060..dc71e4bcd 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -94,6 +94,43 @@ describe('built-in Swarm skills', () => {
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.`)
})
+ // Custom roles and skills per project (spec 2026-10-23, call 14): a custom role's text is installed as the skill of its
+ // kind, under that kind's name, with the one front matter block Harness writes. Owners' texts may bring their own block.
+ describe('a project on its Custom skills', () => {
+ const skill = { role: 'lead' as const, key: 'custom' }
+ const head = (name: string) => `---\nname: swarm-lead\ndescription: ${JSON.stringify(`The ${name} role of this project's Custom skills.`)}\n---\n`
+ const shipped = () => readFileSync(prepareSwarmSkill(fixture(), { ...skill, mode: 'default' }).file, 'utf8')
+ it.each([
+ ['the shipped Default text', () => shipped(), () => shipped().replace(/^---\n[\s\S]*?\n---\n/, '')],
+ ['a text with its own front matter', () => '---\nname: my-pm\ntitle: Ours\n---\n# Our way\nShip small.\n', () => '# Our way\nShip small.\n'],
+ ['a text without front matter', () => '# Our way\n---\nShip small.\n', () => '# Our way\n---\nShip small.\n'],
+ ])('installs %s under the kind\'s skill name with one front matter block', (_case, text, body) => {
+ const workspace = fixture(), { file } = prepareSwarmSkill(workspace, { ...skill, mode: 'default' })
+ expect(refreshSwarmSkill(workspace, skill, 'default', { name: 'Planner', text: text() })).toMatchObject({ file, owed: true })
+ expect(file.endsWith(join('swarm', 'skills', 'swarm-lead', 'SKILL.md'))).toBe(true)
+ expect(readFileSync(file, 'utf8')).toBe(head('Planner') + body())
+ })
+ it('tells the agent its role\'s text once, then each time the owner changes it, overwriting its own edits', () => {
+ const workspace = fixture(), { file } = prepareSwarmSkill(workspace, { ...skill, mode: 'default' })
+ const reread = `Before your next step, read ${JSON.stringify(file)} again with your file or shell tool and follow`
+ const first = refreshSwarmSkill(workspace, skill, 'default', { name: 'Planner', text: 'Plan.\n' })!
+ expect(first).toMatchObject({ owed: true, change: 1,
+ notice: `This project now uses its Custom skills, as Planner. ${reread} it in place of your earlier swarm-lead skill.` })
+ recordSwarmSkillNotice(workspace, skill, first)
+ expect(refreshSwarmSkill(workspace, skill, 'default', { name: 'Planner', text: 'Plan.\n' })).toMatchObject({ owed: false, change: 1 })
+ writeFileSync(file, 'edited')
+ const edit = refreshSwarmSkill(workspace, skill, 'default', { name: 'Planner', text: 'Plan, then ship.\n' })!
+ expect(edit).toMatchObject({ owed: true, change: 2,
+ notice: `The project owner updated your Planner role. ${reread} the new version.` })
+ expect(readFileSync(file, 'utf8')).toBe(head('Planner') + 'Plan, then ship.\n')
+ recordSwarmSkillNotice(workspace, skill, edit)
+ // Back to a built-in set: told as a switch, not as an update.
+ expect(refreshSwarmSkill(workspace, skill, 'default')).toMatchObject({ owed: true, change: 3,
+ notice: `This project now uses the Default skills. ${reread} it in place of your earlier swarm-lead skill.` })
+ expect(readFileSync(file, 'utf8')).toBe(shipped())
+ })
+ })
+
describe('a running session after a CLI update', () => {
const skill = { role: 'dev' as const, key: 'running' }
// What an older CLI left: its own text, and either no record (before records) or a record of that text.
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 144015c22..c4021b118 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -501,6 +501,17 @@ export function swarmSkillUse(role: SwarmRole, mode: SwarmSkillMode): string {
: `Use the built-in swarm-${role} skill for this session.`
}
const MODE_NAMES: Record<SwarmSkillMode, string> = { default: 'Default', orchestration: 'Harness orchestration' }
+/** Which set a session's file was last written from: a built-in mode, or the project's Custom set (spec 2026-10-23). */
+type SkillSet = SwarmSkillMode | 'custom'
+const isSkillSet = (value: unknown): value is SkillSet => isSwarmSkillMode(value) || value === 'custom'
+/** A role of the project's Custom set, its text as the project owner wrote it. */
+export interface CustomSwarmRole { name: string; text: string }
+/** Installed under the kind's own skill name, with the one front matter block Harness writes: any block the owner's text
+ * starts with (the copied Default texts bring one) is dropped. */
+function customText(role: SwarmRole, custom: CustomSwarmRole): string {
+ const body = custom.text.replace(/^\uFEFF?---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/, '')
+ return `---\nname: swarm-${role}\ndescription: ${JSON.stringify(`The ${custom.name} role of this project's Custom skills.`)}\n---\n${body}`
+}
/** 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
@@ -530,16 +541,16 @@ export function prepareSwarmSkill(workspace: string, saved: SwarmSkill): { file:
/** 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 }
+interface SkillRecord { text: string; notified: string; change?: number; mode?: SkillSet; told?: SkillSet; 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 }
+export interface SkillRefresh { file: string; version: string; owed: boolean; change: number; notice: string; set?: SkillSet }
/** 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 {
+export function refreshSwarmSkill(workspace: string, saved: SwarmSkill, mode: SwarmSkillMode, custom?: CustomSwarmRole): 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
@@ -547,7 +558,9 @@ export function refreshSwarmSkill(workspace: string, saved: SwarmSkill, mode: Sw
const file = dir && join(dir, 'SKILL.md')
if (!dir || !file || !existsSync(file)) return null
plainFile(file)
- const text = skills[mode][saved.role], version = textVersion(text)
+ // A Custom role's file is overwritten on each new text (call 14): the agent's own edits are kept for built-in texts only.
+ const set: SkillSet = custom ? 'custom' : mode
+ const text = custom ? customText(saved.role, custom) : 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) {
@@ -559,7 +572,7 @@ export function refreshSwarmSkill(workspace: string, saved: SwarmSkill, mode: Sw
}
if (record.text !== version) {
replaceFile(file, text)
- record = { ...record, text: version, mode, change: (record.change ?? 0) + 1 }
+ record = { ...record, text: version, mode: set, 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
@@ -571,17 +584,19 @@ export function refreshSwarmSkill(workspace: string, saved: SwarmSkill, mode: Sw
// 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 switched = (record.told ?? 'orchestration') !== set || 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.` }
+ const instead = `${reread} it in place of your earlier swarm-${saved.role} skill.`
+ return { file, version, owed, change, set,
+ notice: custom ? switched ? `This project now uses its Custom skills, as ${custom.name}. ${instead}` : `The project owner updated your ${custom.name} role. ${reread} the new version.`
+ : switched ? `This project now uses the ${MODE_NAMES[mode]} skills. ${instead}`
+ : `Harness updated your ${mode === 'default' ? '' : 'built-in '}swarm-${saved.role} skill. ${reread} the new version.` }
}
/** 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 {
+export function recordSwarmSkillNotice(workspace: string, saved: SwarmSkill, sent: Pick<SkillRefresh, 'version' | 'change' | 'set'>): void {
const dir = skillDirectory(realpathSync(workspace), saved, false)
const record = dir && readRecord(dir)
- if (dir && record) writeRecord(dir, { ...record, notified: sent.version, toldChange: sent.change, told: modeOf(saved.role, sent.version) ?? record.told })
+ if (dir && record) writeRecord(dir, { ...record, notified: sent.version, toldChange: sent.change, told: sent.set ?? modeOf(saved.role, sent.version) ?? record.told })
}
const textVersion = (text: string) => createHash('sha256').update(text).digest('hex')
@@ -613,7 +628,7 @@ function readRecord(dir: string): SkillRecord | null {
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, ...(typeof record.change === 'number' ? { change: record.change } : {}),
- ...(isSwarmSkillMode(record.mode) ? { mode: record.mode } : {}), ...(isSwarmSkillMode(record.told) ? { told: record.told } : {}),
+ ...(isSkillSet(record.mode) ? { mode: record.mode } : {}), ...(isSkillSet(record.told) ? { told: record.told } : {}),
...(typeof record.toldChange === 'number' ? { toldChange: record.toldChange } : {}) } : null
}
function writeRecord(dir: string, record: SkillRecord): void {
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 293f72565..1f480a83e 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
@@ -1136,15 +1137,29 @@ describe('built-in skill text after a CLI update', () => {
]
const sent: Array<{ operationId: string; asAgentId: string; command: Record<string, any> }> = []
const receipts = new Map<string, string>()
+ /** On Custom, each agent's roster role (absent on a built-in set), and the role texts the backend serves. */
+ const rowRoles: Record<string, unknown> = {}
+ const texts: Record<string, { version: string; text: string }> = {}
+ const fetched: string[] = []
+ /** Backend calls held until the test releases them: the roster may change while the refresh waits on one. */
+ const holds: Array<{ match: (path: string, body: any) => boolean; until: Promise<void> }> = []
let inFlight = 0
t.core.agents.byAgent = vi.fn(id => sessions[id] as never)
t.core.agents.terminalAvailable = vi.fn(() => true)
t.core.account.backend = vi.fn(async (method, path, body) => {
+ const held = holds.findIndex(h => h.match(path, body))
+ if (held >= 0) await holds.splice(held, 1)[0]!.until
inFlight++
await Promise.resolve()
inFlight--
const request = body as any
- if (path.includes('/hosts/')) return { status: 200, body: { data: agents.map(agent => ({ tabId: 'tab', agent, ...(skillMode ? { skillMode } : {}) })) } }
+ if (path.includes('/hosts/')) return { status: 200, body: { data: agents.map(agent => ({ tabId: 'tab', agent, ...(skillMode ? { skillMode } : {}),
+ ...(agent.id in rowRoles ? { role: rowRoles[agent.id] } : {}) })) } }
+ const role = /^\/api\/super-tabs\/tab\/projects\/pilot\/roles\/([a-z0-9]+)$/.exec(path)?.[1]
+ if (role) {
+ fetched.push(role)
+ return texts[role] ? { status: 200, body: { data: texts[role] } } : { status: 404, body: { success: false, error: { code: 'NOT_FOUND', message: 'This role is unavailable.' } } }
+ }
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.
@@ -1161,9 +1176,126 @@ 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 }, setMode: (next: typeof mode) => { skillMode = next } }
+ const holdNext = (match: (path: string, body: any) => boolean) => {
+ let release!: () => void
+ holds.push({ match, until: new Promise<void>(resolve => { release = resolve }) })
+ return release
+ }
+ return { t, files, sent, pass, rowRoles, texts, fetched, holdNext, setGroups: (next: typeof groups) => { groups = next }, setMode: (next: typeof mode) => { skillMode = next } }
}
+ // Custom roles and skills per project (spec 2026-10-23): on Custom the roster names each agent's role and its text's
+ // version, never the text; the host fetches the text only when that version changes, installs it as the skill of the
+ // agent's kind, and tells the agent as any skill update.
+ describe('a project on its Custom skills', () => {
+ const version = (text: string) => createHash('sha256').update(text).digest('hex').slice(0, 16)
+ const custom = (f: ReturnType<typeof syncFixture>, text: string, name = 'Planner') => {
+ f.texts.lead = { version: version(text), text }
+ f.rowRoles['a-lead'] = { id: 'lead', name, kind: 'lead', version: version(text), projectId: 'pilot' }
+ }
+ it('installs the Lead\'s role under swarm-lead, fetches its text once while the version holds, and tells it once', async () => {
+ const f = syncFixture(false, 'default')
+ custom(f, '---\nname: swarm-lead\n---\nPlan the work.\n')
+ const host = await f.pass()
+ expect(readFileSync(f.files.lead!, 'utf8')).toBe(`---\nname: swarm-lead\ndescription: "The Planner role of this project's Custom skills."\n---\nPlan the work.\n`)
+ expect(f.files.lead!.endsWith(join('swarm-lead', 'SKILL.md'))).toBe(true)
+ expect(f.sent.map(s => [s.asAgentId, s.command.text])).toEqual([['a-lead', expect.stringMatching(/^This project now uses its Custom skills, as Planner\./)]])
+ for (let i = 1; i <= 3; i++) await f.pass(host, i * 120_000)
+ expect(f.fetched).toEqual(['lead'])
+ expect(f.sent).toHaveLength(1)
+ })
+ it('fetches again when the version changes, overwrites the file and tells the agent to re-read it', async () => {
+ const f = syncFixture(false, 'default')
+ custom(f, 'Plan the work.\n')
+ const host = await f.pass()
+ custom(f, 'Plan the work, then ship it.\n')
+ await f.pass(host, 1_000)
+ expect(f.fetched).toEqual(['lead', 'lead'])
+ expect(readFileSync(f.files.lead!, 'utf8')).toMatch(/\n---\nPlan the work, then ship it\.\n$/)
+ expect(f.sent.map(s => s.command.text)).toEqual([expect.stringMatching(/^This project now uses its Custom skills/),
+ `The project owner updated your Planner role. Before your next step, read ${JSON.stringify(f.files.lead)} again with your file or shell tool and follow the new version.`])
+ })
+ it('renames the role in the file when the owner renames it, without fetching its unchanged text again', async () => {
+ const f = syncFixture(false, 'default')
+ custom(f, 'Plan the work.\n')
+ const host = await f.pass()
+ custom(f, 'Plan the work.\n', 'Coordinator')
+ await f.pass(host, 1_000)
+ expect(f.fetched).toEqual(['lead'])
+ expect(readFileSync(f.files.lead!, 'utf8')).toContain('description: "The Coordinator role of this project\'s Custom skills."')
+ })
+ it('keeps the file and installs nothing when the text read back is not the roster\'s version, and tries again later', async () => {
+ const f = syncFixture(false, 'default')
+ custom(f, 'Plan the work.\n')
+ f.texts.lead = { version: 'another-version0', text: 'Something else.\n' }
+ const before = readFileSync(f.files.lead!, 'utf8')
+ const host = await f.pass()
+ expect(readFileSync(f.files.lead!, 'utf8')).toBe(before)
+ expect(f.sent).toEqual([])
+ expect(f.t.log).toHaveBeenCalledWith(expect.stringContaining('Planner'))
+ custom(f, 'Plan the work.\n')
+ await f.pass(host, 60_000)
+ expect(readFileSync(f.files.lead!, 'utf8')).toMatch(/\nPlan the work\.\n$/)
+ })
+ // The review of #1660: a refresh works from the roster it started with, across its fetch and its notice. A role gone
+ // meanwhile must not get its old text installed, nor a re-read notice after the backend's role-gone one.
+ it.each([
+ ['its text is fetched', (path: string) => path.includes('/roles/'), false],
+ ['its notice is about to be sent', (path: string, body: any) => path.includes('?asAgentId=a-lead') && !body, true],
+ ])('drops a refresh whose role is gone while %s', async (_case, match, installed) => {
+ const f = syncFixture(false, 'default')
+ custom(f, 'Plan the work.\n')
+ const before = readFileSync(f.files.lead!, 'utf8')
+ const release = f.holdNext(match)
+ const host = f.t.open()
+ await host.tick()
+ await vi.waitFor(() => expect(vi.mocked(f.t.core.account.backend).mock.calls.some(([, path, body]) => match(path, body))).toBe(true))
+ f.rowRoles['a-lead'] = null
+ await host.tick()
+ release()
+ await f.pass(host, 1_000)
+ expect(f.sent).toEqual([])
+ expect(readFileSync(f.files.lead!, 'utf8') === before).toBe(!installed)
+ // The role back as it was: installed and told after all.
+ custom(f, 'Plan the work.\n')
+ await f.pass(host, 1_000)
+ expect(readFileSync(f.files.lead!, 'utf8')).toMatch(/\nPlan the work\.\n$/)
+ expect(f.sent).toHaveLength(1)
+ })
+ // Round 2 of that review: the roster that drops the role arrives while that poll's own delivery read stalls; the
+ // older refresh must already see it, not wait for the poll to finish.
+ it('drops a refresh whose role is gone in a roster whose poll is still reading deliveries', async () => {
+ const f = syncFixture(false, 'default')
+ custom(f, 'Plan the work.\n')
+ const before = readFileSync(f.files.lead!, 'utf8')
+ const fetch = f.holdNext(path => path.includes('/roles/'))
+ const host = f.t.open()
+ await host.tick()
+ await vi.waitFor(() => expect(vi.mocked(f.t.core.account.backend).mock.calls.some(([, path]) => path.includes('/roles/'))).toBe(true))
+ f.rowRoles['a-lead'] = null
+ const deliveries = f.holdNext(path => path.endsWith('/agents/a-lead/deliveries'))
+ const poll = host.tick()
+ await vi.waitFor(() => expect(vi.mocked(f.t.core.account.backend).mock.calls.filter(([, path]) => path.endsWith('/agents/a-lead/deliveries'))).toHaveLength(2))
+ fetch()
+ for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve))
+ expect(f.sent).toEqual([])
+ expect(readFileSync(f.files.lead!, 'utf8')).toBe(before)
+ deliveries()
+ await poll
+ await f.pass(host, 1_000)
+ expect(f.sent).toEqual([])
+ })
+ it('leaves an agent whose role is gone on its file, fetching and telling nothing: the backend tells it', async () => {
+ const f = syncFixture(false, 'default')
+ f.rowRoles['a-builder'] = null
+ const before = readFileSync(f.files.builder!, 'utf8')
+ await f.pass()
+ expect(readFileSync(f.files.builder!, 'utf8')).toBe(before)
+ expect(f.fetched).toEqual([])
+ expect(f.sent).toEqual([])
+ })
+ })
+
it('rewrites each running Lead, Builder and Reviewer skill once and tells each agent once, never a personal session', async () => {
const f = syncFixture()
const host = await f.pass()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 6a8e69323..3a74cfae9 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -83,7 +83,7 @@ interface Entry {
}
interface Journal { version: 1; machineId: string; entries: Record<string, Entry> }
/** `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; lead?: unknown }
+interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string; releaseId?: string }; skillMode?: unknown; lead?: unknown; role?: unknown }
export interface SuperTabHostOptions {
now?: () => number
write?: (file: string, journal: Journal) => void
@@ -106,6 +106,22 @@ export const hostJournalFile = (dataDir: string, machineId: string) => join(data
const JOIN_RETRY_MS = 60_000
/** How long a skill re-read notice that could not be sent (no open group yet, or the backend failed) waits to retry. */
const SKILL_RETRY_MS = 60_000
+/** Which skill each kind of Custom role is installed as. */
+const KIND_SKILLS: Record<string, string> = { lead: 'lead', builder: 'dev', reviewer: 'review' }
+interface CustomRole { id: string; name: string; kind: string; version: string; projectId: string }
+/** The roster's Custom role for this agent, or null: a built-in set, a role that is gone, or one not fit to use. */
+function customRole(target: HostAgent): CustomRole | null {
+ const role = object(target.role)
+ return identifier(role.id) && identifier(role.projectId) && typeof role.name === 'string' && role.name
+ && typeof role.version === 'string' && role.version && typeof role.kind === 'string' ? role as unknown as CustomRole : null
+}
+/** What a session's skill comes from: a built-in mode, or a Custom role's version and name (a rename rewrites the front
+ * matter without a fetch), or nothing (a role gone or unusable). */
+function skillSetOf(target: HostAgent): string {
+ if (!('role' in target)) return target.skillMode === 'default' ? 'default' : 'orchestration'
+ const role = customRole(target)
+ return role ? JSON.stringify([role.projectId, role.id, role.version, role.name]) : 'none'
+}
const JOIN_RETRY_MAX_MS = 30 * 60_000
/** Refusals no retry can change while this host runs: the Swarm has all its machines, or this account does not own it. */
const JOIN_FINAL = new Set(['MACHINES_FULL', 'OWNER_REQUIRED'])
@@ -190,8 +206,14 @@ 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>()
+ /** The set each session's skill was last compared with (a mode, or a Custom role's version): a change makes it due again
+ * at once. */
+ private readonly skillModes = new Map<string, string>()
+ /** Per running session, the skill set the latest roster names: a refresh started from an older roster installs and
+ * tells nothing once this has moved on (the review of #1660). */
+ private readonly rosterSkills = new Map<string, string>()
+ /** Per session, the Custom role text last fetched and the roster version it is: fetched again only when that changes. */
+ private readonly roleTexts = new Map<string, { version: string; text: string }>()
private skillsRunning: Promise<void> | null = null
private missing = new Map<string, number>()
/** Per Lead harness here: a reopen in progress, its failures, when the next may run, and the reason last logged. */
@@ -505,6 +527,15 @@ export class SuperTabHost {
this.nextConfigurationsAt = this.now() + 5_000
})
}
+ // Set as the roster arrives, before any delivery read can stall this poll: a refresh started from an older roster must
+ // see this one at once (round 2 of the review of #1660).
+ this.rosterSkills.clear()
+ for (const item of data) {
+ const row = object(item), agent = object(row.agent)
+ if (identifier(agent.harnessId) && agent.machineId === this.machineId && row.closeSession !== true && row.stopRequested !== true) {
+ this.rosterSkills.set(agent.harnessId, skillSetOf(row as unknown as HostAgent))
+ }
+ }
const stopKeys = new Set(data.filter(item => object(item).stopRequested === true).map(item => { const row = object(item); return `${row.tabId}:${object(row.agent).id}` }))
for (const key of this.releaseAttempts.keys()) if (!stopKeys.has(key)) this.releaseAttempts.delete(key)
const seen = new Set<string>()
@@ -647,31 +678,54 @@ export class SuperTabHost {
const session = this.core.agents.byAgent(target.agent.harnessId)
const skill = session?.swarmSkill
const mode: SwarmSkillMode = target.skillMode === 'default' ? 'default' : 'orchestration'
+ // Custom roles and skills per project (spec 2026-10-23): on Custom the roster names the agent's role and its text's
+ // version. A role that is gone (null) keeps its file; the backend tells the agent to finish its current work.
+ const custom = customRole(target)
+ if ('role' in target && (!custom || KIND_SKILLS[custom.kind] !== skill?.role)) return
+ const set = skillSetOf(target)
+ const current = () => this.rosterSkills.get(target.agent.harnessId) === set
// 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)
+ if (this.skillModes.get(target.agent.harnessId) !== set) {
+ this.skillModes.set(target.agent.harnessId, set)
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, mode)
+ let text: { name: string; text: string } | undefined
+ if (custom) {
+ let held = this.roleTexts.get(target.agent.harnessId)
+ if (held?.version !== custom.version) {
+ const answer = object(await backend(this.core, 'GET', `/api/super-tabs/${target.tabId}/projects/${custom.projectId}/roles/${custom.id}`))
+ if (answer.version !== custom.version || typeof answer.text !== 'string') {
+ throw new Error(`The ${custom.name} role's text is not the version this machine was told to install. Trying again later.`)
+ }
+ held = { version: custom.version, text: answer.text }
+ this.roleTexts.set(target.agent.harnessId, held)
+ }
+ text = { name: custom.name, text: held.text }
+ }
+ // Dropped, but due again: the roster may come back to this very role before anything was installed.
+ if (!current()) { this.skillChecks.delete(target.agent.harnessId); return }
+ const refresh = refreshSwarmSkill(session.cwd, skill, mode, text)
if (!refresh?.owed) return
- if (await this.tellSkill(target, refresh)) recordSwarmSkillNotice(session.cwd, skill, refresh)
+ if (await this.tellSkill(target, refresh, current)) recordSwarmSkillNotice(session.cwd, skill, refresh)
+ else if (!current()) this.skillChecks.delete(target.agent.harnessId)
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, refresh: SkillRefresh): Promise<boolean> {
+ /** False when nothing was sent: no open group, or the roster has moved on (`current`) and the next refresh decides. */
+ private async tellSkill(target: HostAgent, refresh: SkillRefresh, current: () => boolean): 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)
.filter(group => group.archived !== true && identifier(group.id) && Array.isArray(group.agentIds) && group.agentIds.includes(id))
const group = groups.find(g => g.leadId === id) ?? groups.find(g => object(g.assignment).agentId === id) ?? groups[0]
- if (!group) return false
+ if (!group || !current()) return false
try {
await backend(this.core, 'POST', `/api/super-tabs/${target.tabId}/commands`, {
// A switch back to an earlier mode's text is a new rewrite, so its count keeps it from reusing that text's id.
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 4cdd34d00..1b3fc5ba2 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -183,9 +183,9 @@ it('documents how a lead shares its project repository for other machines', asyn
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',
+ expect(answer.help.commands).toContainEqual({ type: 'project.skills', projectId: 'PROJECT', mode: 'default|orchestration|custom',
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.')
+ expect(answer.help.command).toContain('project.skills switches a project between the Default, Harness orchestration and Custom skills (Custom once its owner has made the project\'s roles): 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()
@@ -193,6 +193,13 @@ it('tells the Lead that start works only on a machine in the Swarm\'s Machines l
expect(answer.help.start).toContain('create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first.')
expect(answer.help.start).toContain('Repeat exactly after an interruption')
})
+// Custom roles and skills per project (spec 2026-10-23): a Lead starts and assigns by role, from the roles status shows.
+it('explains a project\'s Custom roles: where status shows them, and starting or assigning with one', async () => {
+ const answer = await setup().ask({ action: 'help' }, owner) as { help: { status: string; start: string; command: string } }
+ expect(answer.help.status).toContain('A project on Custom skills lists its roles (id, name, kind) in status.')
+ expect(answer.help.start).toContain('On Custom skills, add "roleId" to the start request to start the agent in that role of its kind')
+ expect(answer.help.command).toContain('work.assign takes "roleId" too')
+})
it('explains to a Lead other projects\' work and the Leads conversation', async () => {
const answer = await setup().ask({ action: 'help' }, owner) as { help: { status: string; leads: string } }
expect(answer.help.status).toContain('A Lead\'s status also lists otherProjectsWork: the active work of the Swarm\'s other projects')
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 756b32756..245b626fc 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -12,12 +12,12 @@ import { messageIdOf } from './attach.js'
import { cardId, SwarmCards } from './cards.js'
const HELP = {
- status: 'Read the shared tab roster and work. Its rules are the project owners\' routing rules, each in the owner\'s own words; each binds only the agents of its projectId. A Lead\'s status also lists otherProjectsWork: the active work of the Swarm\'s other projects (group, project, title, owned code, status, Engineer, PR), read only.',
+ status: 'Read the shared tab roster and work. Its rules are the project owners\' routing rules, each in the owner\'s own words; each binds only the agents of its projectId. A Lead\'s status also lists otherProjectsWork: the active work of the Swarm\'s other projects (group, project, title, owned code, status, Engineer, PR), read only. A project on Custom skills lists its roles (id, name, kind) in status.',
leads: 'The Leads conversation (leadsConversationId in a Lead\'s status) is one conversation for the whole Swarm, outside every project. Only Leads and people post there, and only Leads among agents receive it. Before assigning, look at otherProjectsWork; if your task touches the same code, say so there and agree an order first, then tell your own project. The Swarm posts there by itself when two projects\' active tasks own the same code.',
messages: 'messages GROUP: read recent messages in a conversation.',
message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]...: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.',
- start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on. Set role "reviewer" to start a Reviewer; leave role out for a Builder. The role is kept for the session. A Reviewer runs on claude or codex and is assigned only review groups (conversation.create with reviewOf naming the group it reviews); a review group is assigned only to a Reviewer. Add the Reviewer to the reviewed group with conversation.agent so it is told when that work is ready for review and can pass its independent check. Start one with a routeDecisionId like any agent.',
+ start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine in this Swarm\'s Machines list; to use another machine, a person adds it to the Swarm first. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work. With worktree true, the agent starts from the repository\'s default branch, fetched first, unless you set branchRef (refs/heads/BRANCH, or refs/remotes/origin/BRANCH to fetch it first) to start from another branch, such as the one this work builds on. Set role "reviewer" to start a Reviewer; leave role out for a Builder. The role is kept for the session. On Custom skills, add "roleId" to the start request to start the agent in that role of its kind (a builder or reviewer role from status); without it the agent takes the first role of its kind. A Reviewer runs on claude or codex and is assigned only review groups (conversation.create with reviewOf naming the group it reviews); a review group is assigned only to a Reviewer. Add the Reviewer to the reviewed group with conversation.agent so it is told when that work is ready for review and can pass its independent check. Start one with a routeDecisionId like any agent.',
release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
route: 'route GROUP JSON: before you start an agent or assign work to another agent, choose who does it. Work you do yourself is not routed. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","why":"one sentence","kind":"optional word such as ui or docs","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. size is how long the work runs: small about 20 minutes, medium about an hour, large about three hours. Candidates that break the owner\'s hard rules are left out; soft rules (a preferred engine for the kind, idle agents first) rank the rest. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason. An agent\'s start or work.assign without a routeDecisionId is refused, so route first; a person can still start and assign by hand.',
@@ -26,11 +26,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. 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.',
+ command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request. On Custom skills, work.assign takes "roleId" too, a role of the agent\'s kind. 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, Harness orchestration and Custom skills (Custom once its owner has made the project\'s roles): 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: 'project.skills', projectId: 'PROJECT', mode: 'default|orchestration|custom', 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 }] },