The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Require five-part tasks for Swarm delegation (#1517)
0xken155f4280016dad
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex af28a6e9d..92d7fa945 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -70,6 +70,27 @@ afterAll(async () => {await replica?.stop()})+describe('five-part task persistence', () => {+ it('stores structured tasks through the API and delivers all parts to the worker', async () => {+ const { tab, lead } = await fixture()+ const task = { goal: 'Keep drafts', changes: 'Persist pending edits', constraints: 'No dependencies', owns: ['backend/src/superTabs'] }+ const checks = [{ description: 'Draft survives reconnect', independent: false }]+ const created = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`,+ headers: { authorization: `Bearer ${host.sub}` }, payload: { operationId: randomUUID(), asAgentId: lead,+ command: { type: 'conversation.create', title: 'Drafts', task, checks } } })+ expect(created.statusCode, created.body).toBe(200)+ const group = created.json().data.result.conversationId as string+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(), name: 'Worker', configuration: config, lead: false })).result.agentId as string+ const row = (await store.read(owner, tab)).state.conversations.find(c => c.id === group)!+ expect(row.task).toEqual(task)+ expect(row.brief).toContain('Goal:\nKeep drafts')+ await run(tab, { type: 'work.assign', conversationId: group, agentId: worker }, host, lead)+ const messages = (await store.messages(owner, tab, group, {})).messages+ const delivered = messages.at(-1)!.text+ for (const part of ['Goal:', 'Changes:', 'Constraints:', 'Owns:', 'Acceptance checks:', ...Object.values(task).flat(), checks[0]!.description]) expect(delivered).toContain(part)+ })+})+describe('agent member identities', () => {it('keeps a name through replay and removal, including the stored message author', async () => {const tab = (await store.create(owner, randomUUID(), 'People and agents')).iddiff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 6ee587a0a..5696eece9 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -29,6 +29,54 @@ function fixture() {return { run, invite, add, group, get state() { return state } }}+describe('five-part tasks', () => {+ const task = { goal: 'Save edits', changes: 'Persist the draft', constraints: 'No dependencies', owns: ['backend/src/superTabs'] }+ const brief = 'Goal:\nSave edits\n\nChanges:\nPersist the draft\n\nConstraints:\nNo dependencies\n\nOwns:\n- backend/src/superTabs'+ const checks = [{ description: 'Reconnect preserves edits', independent: false }]++ it('creates and defines a structured task with a trimmed compatibility brief', () => {+ const f = fixture()+ const create = commandSchema.parse({ type: 'conversation.create', title: 'Drafts', task: { ...task, goal: ' Save edits ', owns: [' backend/src/superTabs '] }, checks })+ const group = f.run(create).result.conversationId as string+ expect(f.state.conversations[1]).toMatchObject({ task, brief })+ const define = commandSchema.parse({ type: 'work.define', conversationId: group, brief: 'ignored', task, checks })+ expect(f.run(define).messages[0]!.text).toBe(brief)+ expect(f.state.conversations[1]).toMatchObject({ task, brief })+ })++ it('delivers all five parts from the stored rendered brief', () => {+ const f = fixture(), group = f.group(), worker = f.add('worker', 'owner', group)+ f.run(commandSchema.parse({ type: 'work.define', conversationId: group, task, checks }))+ const delivery = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).messages[0]!+ expect(delivery.text).toBe(`${brief}\n\nAcceptance checks:\n- Reconnect preserves edits`)+ expect(delivery.recipients).toEqual([worker])+ })++ it('keeps legacy briefs working and clears a previous structured task', () => {+ const f = fixture(), group = f.group()+ f.run(commandSchema.parse({ type: 'work.define', conversationId: group, task, checks }))+ f.run({ type: 'work.define', conversationId: group, brief: 'Legacy update', checks })+ expect(f.state.conversations[1]).not.toHaveProperty('task')+ expect(f.state.conversations[1]!.brief).toBe('Legacy update')+ expect(commandSchema.safeParse({ type: 'work.define', conversationId: group, checks }).success).toBe(false)+ expect(commandSchema.safeParse({ type: 'conversation.create', title: 'Drafts', checks }).success).toBe(false)+ })++ it('bounds task strings and requires every part', () => {+ for (const type of ['conversation.create', 'work.define']) {+ const base = type === 'conversation.create' ? { type, title: 'Drafts' } : { type, conversationId: 'group' }+ for (const invalid of [null, {}, { ...task, goal: ' ' }, { ...task, changes: '' }, { ...task, constraints: '' },+ { ...task, goal: 'x'.repeat(8001) }, { ...task, changes: 'x'.repeat(8001) }, { ...task, constraints: 'x'.repeat(8001) },+ { ...task, owns: [] }, { ...task, owns: [' '] }, { ...task, owns: Array(41).fill('path') }, { ...task, owns: ['x'.repeat(4097)] },+ { ...task, extra: 'unexpected' }]) {+ expect(commandSchema.safeParse({ ...base, brief: 'legacy', task: invalid, checks }).success).toBe(false)+ }+ expect(commandSchema.safeParse({ ...base, task: { ...task, owns: Array(40).fill('path') }, checks }).success).toBe(true)+ expect(commandSchema.safeParse({ ...base, task: { ...task, owns: Array(40).fill('x'.repeat(4096)) }, checks }).success).toBe(false)+ }+ })+})+describe('Super Tab collaboration policy', () => {it('records host-observed runtime changes without rewriting an assignment\'s starting configuration', () => {const f = fixture(), group = f.group(), worker = f.add('worker', 'owner', group)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 8f1a9f8af..89cdc6090 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -2,7 +2,7 @@ import { admitMachineStart, machineContribution } from './machines.js'import { assignAgentDisplayNames } from './agentNames.js'import { z } from 'zod'import {- activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations, nextConversationNumber,+ activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations, nextConversationNumber, renderWorkTask,type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,} from './model.js'import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'@@ -41,6 +41,10 @@ export const startRequestSchema = z.object({devices: z.array(path).max(20), quotaRequired: z.boolean() }).strict(),}).strict()const check = z.object({ description: z.string().trim().min(1).max(1000), independent: z.boolean() }).strict()+const task = z.object({+ goal: z.string().trim().min(1).max(8000), changes: z.string().trim().min(1).max(8000),+ constraints: z.string().trim().min(1).max(8000), owns: z.array(z.string().trim().min(1).max(4096)).min(1).max(40),+}).strict()export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, scope: z.literal('swarm').optional(), engines: z.array(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)).min(1).max(32), maxAgents: z.number().int().min(1).max(16) }).strict(),@@ -56,7 +60,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('project.cadence'), projectId: id, minutes: z.union([z.literal(1), z.literal(5), z.literal(15), z.literal(30)]) }).strict(),z.object({ type: z.literal('project.report'), projectId: id, throughRevision: z.number().int().nonnegative().safe(), text: text.nullable() }).strict(),z.object({ type: z.literal('project.repository'), projectId: id, repositoryUrl }).strict(),- z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000), checks: z.array(check).max(40) }).strict(),+ z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), checks: z.array(check).max(40) }).strict()+ .refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')+ .refine(c => !c.task || renderWorkTask(c.task).length <= 8000, 'Keep the rendered task within 8,000 characters.'),z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), initialMessage: text.optional() }).strict(),@@ -76,7 +82,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(), recipientIds: z.array(id).max(16),attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional() }).strict(),z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),- z.object({ type: z.literal('work.define'), conversationId: id, brief: text, checks: z.array(check).min(1).max(40) }).strict(),+ z.object({ type: z.literal('work.define'), conversationId: id, brief: text.optional(), task: task.optional(), checks: z.array(check).min(1).max(40) }).strict()+ .refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')+ .refine(c => !c.task || renderWorkTask(c.task).length <= 32_000, 'Keep the rendered task within 32,000 characters.'),z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),z.object({ type: z.literal('work.status'), conversationId: id, assignmentId: id,status: z.enum(['working', 'needs_human', 'blocked', 'review', 'done', 'stopped']), result: text.nullable() }).strict(),@@ -328,23 +336,24 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaelse delete state.routingPolicybreakcase 'conversation.create': {+ const brief = command.task ? renderWorkTask(command.task) : command.brief ?? ''const project = readProject(state, actor, command.projectId ??(actor.kind === 'agent' ? agentProjectId(state, agent(state, actor.agentId)) : 'lead'))controls(state, actor, project.leadConversationId)if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')- if (actor.kind === 'agent' && (!command.brief || !command.checks.length)) {+ if (actor.kind === 'agent' && (!brief || !command.checks.length)) {fail('BRIEF_REQUIRED', 'Delegated work needs a brief and acceptance checks.', 400)}const leadId = conversation(state, project.leadConversationId).leadIdconst number = nextConversationNumber(state)state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),number, title: command.title, leadId, agentIds: leadId ? [leadId] : [],- archived: false, brief: command.brief, assignment: null, lastMessageSequence: 0,+ archived: false, brief, ...(command.task ? { task: command.task } : {}), assignment: null, lastMessageSequence: 0,checks: command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null })),})result.conversationId = operationIdresult.number = number- if (command.brief) message(operationId, command.brief)+ if (brief) message(operationId, brief)break}case 'conversation.rename':@@ -649,9 +658,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (activeWork(group)) fail('WORK_ACTIVE', 'Finish or stop the current assignment before changing its acceptance checks.')rememberAttempt(group)group.assignment = null- group.brief = command.brief+ group.brief = command.task ? renderWorkTask(command.task) : command.brief!+ if (command.task) group.task = command.task+ else delete group.taskgroup.checks = command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null }))- message(group.id, command.brief)+ message(group.id, group.brief)break}case 'work.assign': {diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 1a453a574..f121f6cff 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -78,6 +78,17 @@ export interface Assignment {execution: { machineId: string; harnessId: string; machineOwnerId: string }result: string | null}+export interface WorkTask {+ goal: string+ changes: string+ constraints: string+ owns: string[]+}++export function renderWorkTask(task: WorkTask): string {+ return `Goal:\n${task.goal}\n\nChanges:\n${task.changes}\n\nConstraints:\n${task.constraints}\n\nOwns:\n${task.owns.map(area => `- ${area}`).join('\n')}`+}+export interface Conversation {id: stringprojectId?: string@@ -88,6 +99,7 @@ export interface Conversation {agentIds: string[]archived: booleanbrief: string+ task?: WorkTaskchecks: Check[]assignment: Assignment | nulllastMessageSequence: numberdiff --git a/cli/e2e/superTabs.e2e.ts b/cli/e2e/superTabs.e2e.tsindex 5dbed7530..c855348b8 100644--- a/cli/e2e/superTabs.e2e.ts+++ b/cli/e2e/superTabs.e2e.ts@@ -38,6 +38,7 @@ it('starts either engine once, posts to its captured group and delivers shared iconst agents: Array<Record<string, any>> = []const starts = new Map<string, Record<string, any>>()const posts: Array<Record<string, any>> = []+ const tasks: Array<Record<string, any>> = []const pending = new Map<string, Record<string, any>>()const assignments: Array<Record<string, string>> = []const stopReceipts: Array<Record<string, any>> = []@@ -95,6 +96,9 @@ it('starts either engine once, posts to its captured group and delivers shared iconst id = idFor(String(command.harnessId))if (!agents.some(a => a.id === id)) agents.push({ id, harnessId: command.harnessId, machineId: ME.machineId, configuration: command.configuration })return { data: { result: { agentId: id } } }+ } else if (command.type === 'conversation.create') {+ tasks.push(body)+ if (command.task) return { status: 400, error: { code: 'VALIDATION_ERROR', message: 'command: Unrecognized key: "task"' } }} else if (command.type === 'message.send') posts.push(command)else if (command.type === 'agent.configuration') {const agent = agents.find(a => a.id === body.asAgentId)!@@ -140,6 +144,17 @@ it('starts either engine once, posts to its captured group and delivers shared iprint: text => { answer = JSON.parse(text) } })return { code, answer }}+ const task = { goal: 'Keep drafts', changes: 'Persist edits', constraints: 'No dependencies', owns: ['cli/src/superTabs'] }+ const taskCommand = { type: 'conversation.create', title: 'Drafts', task, checks: [{ description: 'Draft survives restart', independent: false }] }+ expect((await run(['command', 'missing-task', JSON.stringify({ ...taskCommand, task: undefined })])).answer).toMatchObject({ error: 'TASK_REQUIRED' })+ expect(tasks).toHaveLength(0)+ const defined = await run(['command', 'define-task', JSON.stringify(taskCommand)])+ expect(defined.code, JSON.stringify(defined.answer)).toBe(0)+ expect(tasks).toHaveLength(2)+ expect(tasks[0]).toMatchObject({ operationId: 'define-task', command: { task } })+ expect(tasks[1].operationId).toBe('define-task')+ expect(tasks[1].command).not.toHaveProperty('task')+ for (const part of ['Goal:', 'Changes:', 'Constraints:', 'Owns:', 'Keep drafts', 'cli/src/superTabs']) expect(tasks[1].command.brief).toContain(part)for (const engine of ['claude', 'codex']) {const request = { conversationId: 'feature', machineId: ME.machineId, engine, name: `Builder ${engine}`,cwd, worktree: false, permissionMode: 'auto', requirements: { memoryBytes: 0, diskBytes: 1,diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex ba3739a6f..5ad6d5dc5 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -48,6 +48,11 @@ function setup(messageFields: Record<string, unknown> = {}) {}describe('Super Tab native delivery handoff', () => {+ it('names all five task parts in the worker delivery header', async () => {+ const t = setup()+ await t.open().tick()+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('goal, changes, constraints, owned code and acceptance checks')+ })it('keeps roster members through host failure and restart, releasing only a confirmed removal', async () => {const t = setup(), first = t.open()await first.tick()diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 8c4eedf4b..ca935aadf 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -437,7 +437,7 @@ export class SuperTabHost {return `You are participating in a shared Super Tab conversation (${group}). Other humans and agents see messages posted there.\n`+ `Read its state: ${command} status\nRead this conversation: ${command} messages ${shellQuote(group)}\n`+ `Reply there: ${command} post ${shellQuote(group)} 'your message' UNIQUE_OPERATION_ID --reply-to ${shellQuote(String(message.id))}\n`- + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Use independently verifiable outcomes. Leads coordinate: multi-part work or work over about 15 minutes goes to Swarm agents in groups; a Lead does only small work itself and uses its own subagents only to read and look things up.\n`+ + `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Each task needs goal, changes, constraints, owned code and acceptance checks. Leads coordinate: multi-part work or work over about 15 minutes goes to Swarm agents in groups; a Lead does only small work itself and uses its own subagents only to read and look things up.\n`+ `Ask questions and post results in this conversation. ${SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`+ native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`+ (files ? `${message.text ? '\n\n' : ''}${files}` : '')diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 15e873350..393fe98fa 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -1,6 +1,7 @@import { createHash } from 'node:crypto'import { describe, expect, it, vi } from 'vitest'import { fakeCore } from '../testing/fakeCore.js'+import type { CoreApi } from '../core/api.js'import { superTabService } from './service.js'import type { SuperTabHost } from './host.js'import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'@@ -13,12 +14,102 @@ const owner = { local: true, owner: true }, visitor = { local: false, owner: falfunction setup(options: { jev?: () => JevDecide; prepareContribution?: typeof import('./contribution.js').prepareContribution } = {}) {const agentId = createHash('sha256').update(JSON.stringify(['machine-1', 'native'])).digest('hex').slice(0, 24)const agent = { id: agentId, machineId: 'machine-1', harnessId: 'native' }- const call = vi.fn(async () => ({ status: 200, body: { success: true, data: { state: { agents: [agent] } } } }))+ const call = vi.fn<CoreApi['account']['backend']>(async () => ({ status: 200, body: { success: true, data: { state: { agents: [agent] } } } }))const core = fakeCore({ account: { backend: call }, agents: { byAgent: vi.fn(() => ({ agentId: 'native' }) as never) } })const start = vi.fn(), stop = vi.fn()const service = superTabService(core, { host: () => ({ machineId: 'machine-1', start, stop }) as unknown as SuperTabHost, ...options })return { ...service, call, core, agent, agentId, start, stop, ask: service.requests.super_tabs }}+describe('five-part task commands', () => {+ const task = { goal: 'Save edits', changes: 'Persist drafts', constraints: 'No dependencies', owns: ['cli/src/superTabs'] }+ const brief = 'Goal:\nSave edits\n\nChanges:\nPersist drafts\n\nConstraints:\nNo dependencies\n\nOwns:\n- cli/src/superTabs'+ const checks = [{ description: 'Draft survives reconnect', independent: false }]+ const send = (t: ReturnType<typeof setup>, command: Record<string, unknown>) => t.ask({ action: 'command', tabId: 'tab', agentId: t.agentId, operationId: 'task-op', command }, owner)++ for (const type of ['conversation.create', 'work.define']) {+ const base = { type, ...(type === 'conversation.create' ? { title: 'Drafts' } : { conversationId: 'group' }) }+ it(`${type} requires each task part and a nonempty acceptance check`, async () => {+ for (const [field, invalid] of [+ ['goal', { task: { ...task, goal: ' ' } }], ['changes', { task: { ...task, changes: '' } }],+ ['constraints', { task: { ...task, constraints: null } }], ['owns', { task: { ...task, owns: [] } }],+ ['owns', { task: { ...task, owns: [' '] } }], ['goal', { task: undefined }],+ ['acceptance checks', { checks: [] }], ['acceptance checks', { checks: [{ description: ' ' }] }],+ ] as const) {+ const t = setup()+ expect(await send(t, Object.assign({ ...base, task, checks }, invalid))).toMatchObject({ error: 'TASK_REQUIRED', detail: expect.stringContaining(field) })+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(0)+ }+ })+ it(`${type} sends the complete template and renders its compatibility brief`, async () => {+ const t = setup()+ expect(await send(t, { ...base, brief: 'ignored', task: { ...task, goal: ' Save edits ', owns: [' cli/src/superTabs '] }, checks })).toMatchObject({ ok: true })+ expect(t.call).toHaveBeenLastCalledWith('POST', '/api/super-tabs/tab/commands', { operationId: 'task-op', asAgentId: t.agentId, command: { ...base, task, brief, checks } })+ })+ it(`${type} retries an old backend's task refusal once using the same operation`, async () => {+ const t = setup(), original = t.call.getMockImplementation()!+ t.call.mockImplementation(async (...args) => args[0] === 'POST' && (args[2] as { command: { task?: unknown } }).command.task+ ? { status: 400, body: { success: false, error: { code: 'VALIDATION_ERROR', message: 'command: Unrecognized key: "task"' } } } as never+ : original(...args))+ expect(await send(t, { ...base, task, checks })).toMatchObject({ ok: true })+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(2)+ expect(t.call).toHaveBeenLastCalledWith('POST', '/api/super-tabs/tab/commands', { operationId: 'task-op', asAgentId: t.agentId, command: { ...base, brief, checks } })+ })+ }+ it('preserves other errors and never repeats a failed compatibility retry', async () => {+ for (const [status, code, message, count] of [+ [403, 'FORBIDDEN', 'Unrecognized key: "task"', 1], [400, 'VALIDATION_ERROR', 'Invalid title', 1],+ [503, 'BACKEND_UNAVAILABLE', 'Offline', 1], [400, 'VALIDATION_ERROR', 'Unrecognized key: "task"', 2],+ ] as const) {+ const t = setup(), original = t.call.getMockImplementation()!+ t.call.mockImplementation(async (...args) => args[0] === 'POST'+ ? { status, body: { success: false, error: { code, message } } } as never : original(...args))+ expect(await send(t, { type: 'work.define', conversationId: 'group', task, checks })).toMatchObject({ error: code, detail: message })+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(count)+ }+ })+ it('recovers a committed legacy receipt after a lost reply and backend upgrade', async () => {+ const t = setup(), original = t.call.getMockImplementation()!+ let upgraded = false, recorded: string | null = null+ t.call.mockImplementation(async (...args) => {+ if (args[0] !== 'POST') return original(...args)+ const body = args[2] as { command: Record<string, unknown> }+ if (!upgraded && body.command.task) return { status: 400, body: { success: false, error: { code: 'VALIDATION_ERROR', message: 'command: Unrecognized key: "task"' } } }+ if (!recorded) { recorded = JSON.stringify(body); upgraded = true; throw new Error('Reply lost after commit') }+ return JSON.stringify(body) === recorded+ ? { status: 200, body: { success: true, data: { result: { conversationId: 'only-group' } } } }+ : { status: 409, body: { success: false, error: { code: 'OPERATION_REUSED', message: 'Choose a new operation ID for different content.' } } }+ })+ const command = { type: 'conversation.create', title: 'Drafts', task, checks }+ expect(await send(t, command)).toMatchObject({ error: 'SUPER_TAB_UNAVAILABLE' })+ expect(await send(t, command)).toMatchObject({ ok: true, value: { result: { conversationId: 'only-group' } } })+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(4)+ // A real content change must still fail even when its receipt is checked in legacy form.+ expect(await send(t, { ...command, title: 'Different work' })).toMatchObject({ error: 'OPERATION_REUSED' })+ })+ it('does not strip task fields from unrelated commands', async () => {+ const t = setup(), original = t.call.getMockImplementation()!+ t.call.mockImplementation(async (...args) => args[0] === 'POST'+ ? { status: 400, body: { success: false, error: { code: 'VALIDATION_ERROR', message: 'command: Unrecognized key: "task"' } } }+ : original(...args))+ expect(await send(t, { type: 'message.send', task })).toMatchObject({ error: 'VALIDATION_ERROR' })+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(1)+ })+ it('documents all five parts in both command examples', async () => {+ const t = setup(), answer = await t.ask({ action: 'help' }, owner) as { help: { commands: Array<Record<string, unknown>> } }+ for (const type of ['conversation.create', 'work.define']) {+ expect(answer.help.commands.find(c => c.type === type)).toMatchObject({ task: { goal: expect.any(String), changes: expect.any(String), constraints: expect.any(String), owns: expect.any(Array) }, checks: [expect.objectContaining({ description: expect.any(String) })] })+ }+ })+ it('rejects oversized task sections, ownership and compatibility briefs before sending', async () => {+ for (const invalid of [{ ...task, goal: 'x'.repeat(8001) }, { ...task, owns: Array(41).fill('path') },+ { ...task, owns: ['x'.repeat(4097)] }, { ...task, owns: Array(40).fill('x'.repeat(200)) }]) {+ const t = setup()+ expect(await send(t, { type: 'conversation.create', title: 'Drafts', task: invalid, checks })).toMatchObject({ error: 'INVALID_TASK' })+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(0)+ }+ })+})+it('keeps a shared machine controller out of the host account while accepting its own paired apps', async () => {const t = setup()for (const accountOwner of [undefined, false]) {diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 601276fe8..53d6559f2 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -27,9 +27,9 @@ const HELP = {{ 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: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },- { type: 'conversation.create', title: 'Outcome', brief: 'An independently assignable result', checks: [{ description: 'Observable acceptance evidence', independent: false }] },+ { 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.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: false },- { type: 'work.define', conversationId: 'GROUP', brief: 'What to deliver', checks: [{ description: 'Observable acceptance evidence', independent: false }] },+ { type: 'work.define', conversationId: 'GROUP', task: { goal: 'What to deliver', changes: 'What changes', constraints: 'What must stay true', owns: ['Paths or code areas'] }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },{ type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT', routeDecisionId: 'DECISION' },{ type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },// Both reach the Lead and alert the Harness Pro on the machine running the agent until the status moves on.@@ -42,6 +42,26 @@ const HELP = {const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []+function taskCommand(command: Record<string, unknown>): Record<string, unknown> {+ if (command.type !== 'conversation.create' && command.type !== 'work.define') return command+ const task = object(command.task), missing: string[] = []+ for (const part of ['goal', 'changes', 'constraints']) {+ if (typeof task[part] !== 'string' || !task[part].trim()) missing.push(part)+ }+ if (!Array.isArray(task.owns) || !task.owns.length || task.owns.some(area => typeof area !== 'string' || !area.trim())) missing.push('owns')+ if (!Array.isArray(command.checks) || !command.checks.length || command.checks.some(check => typeof object(check).description !== 'string' || !String(object(check).description).trim())) missing.push('acceptance checks')+ if (missing.length) throw new SuperTabHostError('TASK_REQUIRED', `Complete the task: ${missing.join(', ')}.`, 400)+ const trimmed = { ...task, goal: (task.goal as string).trim(), changes: (task.changes as string).trim(),+ constraints: (task.constraints as string).trim(), owns: (task.owns as string[]).map(area => area.trim()) }+ if ([trimmed.goal, trimmed.changes, trimmed.constraints].some(part => part.length > 8000) || trimmed.owns.length > 40 || trimmed.owns.some(area => area.length > 4096)) {+ throw new SuperTabHostError('INVALID_TASK', 'Task sections may have up to 8,000 characters; owns needs 1–40 paths or areas of up to 4,096 characters each.', 400)+ }+ const brief = `Goal:\n${trimmed.goal}\n\nChanges:\n${trimmed.changes}\n\nConstraints:\n${trimmed.constraints}\n\nOwns:\n${trimmed.owns.map(area => `- ${area}`).join('\n')}`+ const limit = command.type === 'conversation.create' ? 8000 : 32_000+ if (brief.length > limit) throw new SuperTabHostError('INVALID_TASK', `Keep the rendered task within ${limit.toLocaleString('en-US')} characters.`, 400)+ return { ...command, task: trimmed, brief }+}+/** Tell the agent which messages sent to it it has already answered, so it posts once (a Lead answered one question twice on* 2026-10-20). A message is answered when a later message of the agent's own replies to it. */function markAnswered(page: unknown, later: unknown[], agentId: string): unknown {@@ -215,8 +235,22 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =} catch { return { ok: true, value: page } }}if (payload.action === 'command' && identifier(payload.operationId) && payload.command && typeof payload.command === 'object' && !Array.isArray(payload.command)) {- return { ok: true, operationId: payload.operationId, value: await backend(core, 'POST', `${path}/commands`,- { operationId: payload.operationId, command: payload.command, asAgentId: agentId }) }+ const command = taskCommand(object(payload.command))+ const send = (command: Record<string, unknown>) => backend(core, 'POST', `${path}/commands`,+ { operationId: payload.operationId, command, asAgentId: agentId })+ let value: unknown+ try { value = await send(command) } catch (error) {+ if (!['conversation.create', 'work.define'].includes(String(command.type)) || !command.task || !(error instanceof SuperTabHostError)) throw error+ const oldSchema = error.status === 400 && error.code === 'VALIDATION_ERROR'+ && /^(?:command: )?Unrecognized (?:key: "task"|key\(s\) in object: 'task')$/.test(error.message)+ // A legacy write may commit before its reply is lost and the backend upgrades. Its receipt checks the exact+ // legacy content before returning success, so checking that form cannot create a second operation.+ const legacyReceipt = error.status === 409 && error.code === 'OPERATION_REUSED'+ if (!oldSchema && !legacyReceipt) throw error+ const { task: _task, ...legacy } = command+ value = await send(legacy)+ }+ return { ok: true, operationId: payload.operationId, value }}// `post --attach` asks first whether this post already went out with its files.if (payload.action === 'attachment' && identifier(payload.conversationId) && payload.step === 'sent' && identifier(payload.operationId)) {diff --git a/desktop/lib/super_tabs/launch_prompt.dart b/desktop/lib/super_tabs/launch_prompt.dartindex 67d1c78f4..8adfbd466 100644--- a/desktop/lib/super_tabs/launch_prompt.dart+++ b/desktop/lib/super_tabs/launch_prompt.dart@@ -16,6 +16,6 @@ String superTabLaunchPrompt({'Terminal output is not shared chat. If sandbox restrictions block this command, request permission. Use `help` for syntax. ''${lead ? 'Before starting or assigning work, use `route GROUP JSON` with difficulty, risk and size (small, medium or large); use its routeDecisionId or an explicit overrideReason. Explain NO_CANDIDATE reasons in chat. ' : ''}''${lead ? 'Coordinate: put multi-part or 15+ minute work in groups for Swarm agents. Do only answers, lookups and small fixes yourself; your subagents only read and look up. ' : ''}'- 'Reuse agents and groups. Each group needs an assignable outcome and acceptance checks. '+ 'Reuse agents and groups. Each task needs goal, changes, constraints, owned paths, checks. ''Write like a helpful colleague: answer first, in their language, under about 150 words unless asked. Hide commands, internal IDs and field names. Give results with revision/links. ''${lead ? 'Keep the Lead chat informed: plan, progress, blockers, next steps. Consolidate workgroup reports at the project cadence. Answer questions, serious blockers and completion immediately. On scheduled requests read new reports; use project.report for one update or text:null if nothing new. No per-turn summarizer. Keep workgroups and sessions scoped to this project.' : ''}';diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex d1204c868..f5652aa3d 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -47,6 +47,17 @@ class SuperTabAgent {String get engine => configuration['engine'] as String? ?? '';}+class SuperTabTask {+ SuperTabTask.fromJson(Map<String, dynamic> row)+ : goal = _text(row, 'goal'),+ changes = _text(row, 'changes'),+ constraints = _text(row, 'constraints'),+ owns = List.unmodifiable((row['owns'] as List).cast<String>());++ final String goal, changes, constraints;+ final List<String> owns;+}+class SuperTabConversation {SuperTabConversation.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),@@ -61,11 +72,15 @@ class SuperTabConversation {(check) => Map<String, dynamic>.unmodifiable(check),),brief = _text(row, 'brief'),+ task = row['task'] is Map+ ? SuperTabTask.fromJson(superTabMap(row['task']))+ : null,lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,assignment = row['assignment'] == null? null: Map.unmodifiable(superTabMap(row['assignment']));final String id, projectId, title, brief;+ final SuperTabTask? task;final int? number;String get label => number == null ? title : '#$number $title';final String? leadId;diff --git a/desktop/lib/super_tabs/work_details.dart b/desktop/lib/super_tabs/work_details.dartindex 4e03f009c..127d9726a 100644--- a/desktop/lib/super_tabs/work_details.dart+++ b/desktop/lib/super_tabs/work_details.dart@@ -27,7 +27,22 @@ Future<void> showSuperTabWork(child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [- if (group?.brief.isNotEmpty == true)+ if (group?.task case final task?) ...[+ for (final section in [+ ('Goal', task.goal),+ ('Changes', task.changes),+ ('Constraints', task.constraints),+ ('Owns', task.owns.map((area) => '- $area').join('\n')),+ ]) ...[+ Text(+ section.$1,+ style: DesktopChrome.control(medium: true),+ ),+ const SizedBox(height: 4),+ SuperTabMessageText(section.$2),+ const SizedBox(height: 16),+ ],+ ] else if (group?.brief.isNotEmpty == true)SuperTabMessageText(group!.brief)elseconst Text(@@ -39,6 +54,13 @@ Future<void> showSuperTabWork('${c.snapshot?.agentName(assignment['agentId'] as String, fallback: 'Agent unavailable') ?? 'Agent unavailable'} · ${superTabWorkStatusLabel(assignment['status'] as String)}',),],+ if (group?.checks.isNotEmpty == true) ...[+ const SizedBox(height: 16),+ Text(+ 'Acceptance checks',+ style: DesktopChrome.control(medium: true),+ ),+ ],for (final checkin group?.checks ?? <Map<String, dynamic>>[]) ...[const SizedBox(height: 16),diff --git a/desktop/test/super_tab_work_details_test.dart b/desktop/test/super_tab_work_details_test.dartnew file mode 100644index 000000000..b67445d36--- /dev/null+++ b/desktop/test/super_tab_work_details_test.dart@@ -0,0 +1,117 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/launch_prompt.dart';+import 'package:harness/super_tabs/message_text.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/work_details.dart';++import 'support/super_tab_fixture.dart';++const task = {+ 'goal': 'Keep drafts',+ 'changes': 'Store pending edits',+ 'constraints': 'No dependencies',+ 'owns': ['cli/src/superTabs', 'desktop/lib/super_tabs'],+};++void main() {+ test(+ 'conversation parses an optional immutable task and accepts old rows',+ () {+ final row = conversationFixture('group', 'Drafts');+ expect(SuperTabConversation.fromJson(row).task, isNull);+ row['task'] = task;+ final parsed = SuperTabConversation.fromJson(row).task!;+ expect(parsed.goal, 'Keep drafts');+ expect(parsed.changes, 'Store pending edits');+ expect(parsed.constraints, 'No dependencies');+ expect(parsed.owns, task['owns']);+ expect(() => parsed.owns.add('other'), throwsUnsupportedError);+ },+ );++ test(+ 'launch prompt names the five task parts and stays within the limit',+ () {+ for (final lead in [true, false]) {+ final prompt = superTabLaunchPrompt(+ tabId: 't' * 160,+ conversationId: 'c' * 160,+ lead: lead,+ );+ expect(+ prompt,+ contains(+ 'goal, changes, constraints, owned paths, checks',+ ),+ );+ expect(prompt.length, lessThanOrEqualTo(2000));+ }+ },+ );++ for (final structured in [true, false]) {+ testWidgets(+ 'work details show ${structured ? 'five labelled parts' : 'the legacy brief'}',+ (tester) async {+ final server = ConversationServer();+ final row =+ (server.state['conversations'] as List)[1] as Map<String, dynamic>;+ row['brief'] = 'Legacy instructions';+ if (structured) row['task'] = task;+ row['checks'] = [+ {+ 'id': 'check',+ 'description': 'Draft survives reconnect',+ 'independent': false,+ 'passedBy': null,+ },+ ];+ final controller = server.controller();+ addTearDown(controller.dispose);+ await controller.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => Scaffold(+ body: TextButton(+ onPressed: () =>+ showSuperTabWork(context, controller, 'offline'),+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ expect(find.text('Acceptance checks'), findsOneWidget);+ expect(find.text('Draft survives reconnect'), findsOneWidget);+ if (structured) {+ for (final heading in ['Goal', 'Changes', 'Constraints', 'Owns']) {+ expect(find.text(heading), findsOneWidget);+ }+ final texts = tester+ .widgetList<SuperTabMessageText>(find.byType(SuperTabMessageText))+ .map((widget) => widget.text)+ .join('\n');+ expect(texts, contains('Keep drafts'));+ expect(texts, contains('Store pending edits'));+ expect(texts, contains('No dependencies'));+ expect(texts, contains('cli/src/superTabs'));+ expect(texts, contains('desktop/lib/super_tabs'));+ expect(texts, isNot(contains('Legacy instructions')));+ } else {+ expect(find.byType(SuperTabMessageText), findsOneWidget);+ expect(+ tester+ .widget<SuperTabMessageText>(find.byType(SuperTabMessageText))+ .text,+ 'Legacy instructions',+ );+ }+ expect(tester.takeException(), isNull);+ },+ );+ }+}diff --git a/docs/plans/2026-10-22-five-part-tasks.md b/docs/plans/2026-10-22-five-part-tasks.mdnew file mode 100644index 000000000..538d511b7--- /dev/null+++ b/docs/plans/2026-10-22-five-part-tasks.md@@ -0,0 +1,69 @@+# Five-part Swarm tasks implementation plan++> **For agentic workers:** Use superpowers:executing-plans to implement this plan task by task. Track the steps below.++**Goal:** Every delegated task states its goal, changes, constraints, owned code and observable acceptance checks.++**Architecture:** Add an optional structured task to conversations and keep the existing brief as a rendered compatibility view. Validate complete tasks in the agent CLI command path, retry an explicit old-backend schema refusal once with the rendered brief, and display the structured fields in assignment deliveries and Desktop work details.++**Tech stack:** TypeScript, Zod, Vitest, Dart/Flutter. No new dependencies.++**Spec:** Workgroup assignment in the shared Swarm, Five-part task template (on Ken's machine), 2026-10-22. Its requirements are captured below.++## Global constraints++- Keep old CLI requests with a brief accepted by the backend. Desktop group creation continues using a free-text brief.+- New CLI requests require all four task fields and at least one nonempty acceptance check. New CLI against an older backend retries once only after an invalid-command refusal.+- Task goal, changes and constraints are trimmed nonempty strings, each limited to 8,000 characters. Owns has 1–40 trimmed nonempty paths/areas of at most 4,096 characters each. Rendered tasks also fit the existing brief limits: 8,000 characters for conversation.create, 32,000 for work.define. This keeps old-backend fallback valid without truncation.+- Only touch task-related cases/schema in backend commands, the conversation models, CLI task command validation/help and assignment text, Desktop details and the template sentence in the launch prompt. Coordinate shared files with the other workgroup.+- Tests use isolated data and never the live daemon, port 18473, real tmux, ~/.harness, ~/.claude or ~/.codex. CLI runs on Node 24.+- Start from current origin/main, rebase before delivery, push the branch and open a draft PR. Do not mark ready, merge or release.++## Review focus++- A legacy work.define replacing a structured task must clear the prior task, so details do not show stale instructions.+- A structured task takes precedence over a supplied brief on write; worker delivery reuses the stored rendered brief.+- Compatibility retry must preserve the operation ID and all non-task fields. Permission, transport and unrelated validation failures never retry; an operation conflict may check its exact legacy receipt once after an upgrade.+- Whitespace-only fields and empty check descriptions must be rejected with useful errors.+- Long real group/tab IDs must keep the launch prompt below 2,000 UTF-16 units.++## Phase 1: Backend contract and delivery++Files: `backend/src/superTabs/model.ts`, `commands.ts`, `commands.test.ts`.++Interface: `Conversation.task?: { goal: string; changes: string; constraints: string; owns: string[] }`. The conversation.create and work.define schemas accept task and optional brief; applying a task renders `Goal`, `Changes`, `Constraints`, `Owns`. Assignment messages add the existing acceptance checks as the fifth section.++- [x] Add failing tests for task-only create/define, trimmed storage and rendered brief, validation bounds, legacy requests, stale-task removal and structured worker delivery.+- [x] Run the affected tests and observe the missing behavior.+- [x] Implement schema, storage and rendering; reuse the rendered brief for assignment text while preserving legacy delivery.+- [x] Run backend unit tests and typecheck.++## Phase 2: CLI task enforcement and compatibility++Files: `cli/src/superTabs/service.ts`, `service.spec.ts`, `host.ts`, `host.spec.ts`; a focused task helper and its tests if needed.++Interface: the agent command path requires complete task fields and nonempty checks on conversation.create/work.define. It always sends a rendered brief with the task. On explicit invalid-command/schema rejection from an older backend, retry exactly once without task, with the same operation ID and rendered brief. If a later backend upgrade returns an operation conflict after a lost legacy acknowledgement, check the exact legacy-form receipt once; genuine content changes remain conflicts. Other commands retain their behavior. HELP demonstrates the whole template; the delivery header names its five parts.++- [x] Add failing service tests covering both commands, each missing field/check, rendered briefs, successful new backend, old backend rejection, a failed retry and unrelated errors.+- [x] Run the affected tests and observe failures.+- [x] Implement validation, rendering, bounded retry and HELP/header copy.+- [x] Run affected CLI tests, the 100% super-tabs coverage gate and typecheck on Node 24.++## Phase 3: Desktop structured work details++Files: `desktop/lib/super_tabs/model.dart`, `work_details.dart`, `launch_prompt.dart`, affected `desktop/test/super_tab_*_test.dart`.++Interface: parse optional task into a typed immutable object. Show Goal, Changes, Constraints and Owns sections when task exists, otherwise show the existing brief; label acceptance checks as the fifth section. The launch template sentence lists all five parts.++- [x] Add failing model/widget tests for structured details, legacy fallback and bounded launch copy.+- [x] Run the affected tests and observe failures.+- [x] Implement parsing and sections using existing typography and message rendering.+- [x] Run Flutter analyze and affected widget/unit tests.++## Phase 4: Validation and draft delivery++- [x] Run backend `npx tsc --noEmit`, `npx vitest run src/superTabs`, `npm run test:super-tabs`.+- [x] Run CLI `npm run typecheck`, affected unit tests and `npm run test:super-tabs` (100% gate). Assess the isolated end-to-end workflow coverage and full component checks required by the validation guide.+- [x] Run Desktop `flutter analyze` and affected tests; assess full component tests for the shared protocol change.+- [ ] Review the final diff independently, resolve material findings, fetch/rebase current main, and reuse only checks whose inputs remain unchanged.+- [ ] Commit and push the isolated branch, open a draft PR with exact check results and limitations, and report its revision/link to the workgroup. Record implementation, validation and waiting separately; merging/publication are outside scope.