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: one request is one task with steps, and agents know their work (#2511)

0xken151ec0ca9ea950
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 7a703758f..4de6416ec 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1953,7 +1953,8 @@ describe('role kinds decide nothing', () => {
const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: builder }).result.assignmentId as string
const status = (actor: Actor, status: 'review' | 'working') =>
f.run({ type: 'work.status', conversationId: group, assignmentId, status, result: status === 'review' ? 'Head abc123' : null }, actor).messages[0]!.recipients
- expect(status(as(builder), 'review')).toEqual([lead])
+ // Its own Ready wakes nobody, the coordinator included (Ken, 2026-11-02): it names whom it hands to.
+ expect(status(as(builder), 'review')).toEqual([])
status(as(builder), 'working')
// The coordinator's change reaches the task's agent alone, never the Reviewer.
expect(status(coordinator, 'review')).toEqual([builder])
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index ae231b797..4f1cee8a0 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -9,6 +9,7 @@ import {
type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type BuddySessionEntry, type WorkTask, type Agent, type Author, type Check, type CommandEffects, type Conversation, type SuperTabState,
} from './model.js'
import { jobKindOf } from './evidence/jobKind.js'
+import { endSteps, holdsStepOf, isStep, taskOwner } from './steps.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSaveSchema } from './routingPolicy.js'
import { askedInSchema, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema } from './rules.js'
@@ -169,7 +170,10 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('project.role.remove'), projectId: id, roleId }).strict(),
z.object({ type: z.literal('project.roles.reset'), projectId: id, roles: roleSet }).strict(),
// `audience`: a private conversation that only these people and the project's Lead read (projects.ts canReadGroup).
- z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(), checks: z.array(check).max(40),
+ z.object({ type: z.literal('conversation.create'), projectId: id.optional(), title, brief: z.string().trim().max(8000).optional(), task: task.optional(), reviewOf: id.optional(),
+ // A step of the task `reviewOf` names (task steps design): its name as the instructions give it, free text in any language.
+ // No line break or control character: the name is printed in agents' terminals (final review, minor 10).
+ step: z.string().trim().min(1).max(40).regex(/^[^\u0000-\u001f\u007f]+$/, 'A step name is one line of text.').optional(), checks: z.array(check).max(40),
audience: z.object({ personIds: z.array(id).max(200) }).strict().optional(), requesterId: id.optional(),
// The Buddy's proposal message in the project chat the group comes from (Lead, 2026-10-29): the Buddy earns when it ships.
proposalMessageId: id.optional() }).strict()
@@ -825,6 +829,22 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
/** Any other row the system writes in the actor's name. Without a source, a notice written as the owner read as the owner
* asking, and a Lead could quote it to change rules (review of #1594). Only `message.send` and an initial message stay plain. */
const SYSTEM_ROW = { kind: 'system' }
+ /** [agentId] as a member of [group] who may be told there: joined when it is not one yet and may join; else null. */
+ const reachable = (group: Conversation, agentId: string | null): string | null => {
+ if (!agentId || group.agentIds.includes(agentId)) return agentId
+ if (!joinsProject(state, group, agentId)) return null
+ group.agentIds.push(agentId)
+ return agentId
+ }
+ /** A task ended: its open steps are cancelled and their agents told why, in each step (task steps design); with
+ * [archive], its finished steps archive with it. */
+ const endStepsOf = (task: Conversation, reason: string, archive: boolean) => {
+ // A row of its own in each step, as the command's own row may be in the task: one id per row.
+ for (const step of endSteps(state, task, reason, archive)) {
+ effects.messages.push({ id: stableId(operationId, 'step-ended', step.id), conversationId: step.id, author: sender, text: reason,
+ replyTo: null, recipients: [step.assignment!.agentId], source: SYSTEM_ROW })
+ }
+ }
/** Agent bookkeeping, a routing line or an agent joined or ready: no one's in the project chat, which carries only what
* people read or decide on (the Lead's ruling, 2026-10-29); a task's chat keeps it as its record. */
const bookkeeping = (conversationId: string, source: Record<string, unknown>) =>
@@ -1690,6 +1710,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
requirable(command.task)
if (command.audience) pmChatClosed()
const leadId = conversation(state, project.leadConversationId).leadId
+ if (command.step && !command.reviewOf) fail('INVALID_REQUEST', 'A step belongs to a task: name the task with reviewOf.', 400)
if (command.reviewOf) {
// A task links to another task of its own project, a linked one included, and to nothing else: the project chat, a
// Buddy chat, a private chat, the Leads conversation and other projects' tasks read as missing, archived or not, so the
@@ -1698,6 +1719,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (!reviewed || isLeads(reviewed) || reviewed.kind || reviewed.audience || reviewed.id === project.leadConversationId
|| groupProject(state, reviewed).id !== project.id) fail('NOT_FOUND', 'This conversation is unavailable.', 404)
open(state, reviewed.id)
+ // One level: a step's own work is a task's step, never a task with steps of its own (task steps design).
+ if (command.step && reviewed.step) fail('STEP_OF_STEP', 'A step belongs to a task, not to another step.', 400)
}
// Who asked: the person named, else the one a Buddy's proposal was sent for, else a person opening it themselves.
const proposal = command.proposalMessageId ? proposalOf(state, project, context.proposal) : undefined
@@ -1708,9 +1731,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// The agent that opens a task is in it, so an Engineer that opens its own review can post there and pass its checks.
const creator = actor.kind === 'agent' && actor.agentId !== leadId ? [actor.agentId] : []
for (const id of creator) teamJoin(project, id)
+ // A step's opener is in its task too: the task's chat is where the step's work is talked over (task steps design).
+ if (command.step && command.reviewOf) {
+ const owning = conversation(state, command.reviewOf)
+ for (const id of creator) if (!owning.agentIds.includes(id)) owning.agentIds.push(id)
+ }
state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),
number, title: command.title, leadId, agentIds: [...leadId ? [leadId] : [], ...creator],
archived: false, brief, ...(command.task ? { task: command.task } : {}), ...(command.reviewOf ? { reviewOf: command.reviewOf } : {}),
+ ...(command.step ? { step: command.step } : {}),
assignment: null, lastMessageSequence: 0,
checks: storedChecks(command.checks, operationId),
})
@@ -1796,6 +1825,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (group.id === groupProject(state, group).leadConversationId) fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')
if (command.archived && activeWork(group)) fail('WORK_ACTIVE', 'Resolve the active assignment before archiving this conversation.')
group.archived = command.archived
+ if (command.archived) endStepsOf(group, `${group.title} was archived.`, true)
// Archived by hand, it leaves the active set until it is reopened (spec, Archive), once its reports are acknowledged:
// until then the sweep leaves it in the active set, where the report check sees it (design section 3.6).
if (command.archived && !dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true
@@ -2491,7 +2521,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const leadToWorker = actor.kind === 'agent' && actor.agentId === group.leadId && assigned && assigned !== group.leadId
&& group.agentIds.includes(assigned) && (!context.reply || replyAgent === assigned)
&& !leadWorkerBounced(context.recent, group.leadId, assigned) ? assigned : null
+ // A step's agent tells its task's owner, as its status does (task steps design); with no owner, the coordinator.
+ const stepOwner = actor.kind === 'agent' && isStep(group) ? taskOwner(state, group) : null
const workerToLead = actor.kind === 'agent' && activeWork(group) && group.assignment?.agentId === actor.agentId
+ && stepOwner && stepOwner !== actor.agentId ? stepOwner
+ : actor.kind === 'agent' && activeWork(group) && group.assignment?.agentId === actor.agentId
&& group.leadId && group.leadId !== actor.agentId && group.agentIds.includes(group.leadId) ? group.leadId : null
const agentRecipient = leadToWorker ?? workerToLead
// Any other agent's unnamed post in the group reaches its Lead: an agent whose task here was lost, moved or cancelled has
@@ -2501,7 +2535,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// A post that names its agents reaches only them: copying every one to the Lead filled its terminal (Ken, 10-30: 198 of
// the 486 messages it got in a day were such copies). The assigned worker keeps its own rule above; a note to itself
// stays its own.
- const memberToLead = actor.kind === 'agent' && !command.agentOnly && !addressed.length && assigned !== actor.agentId && group.leadId
+ // In a task, an agent holding one of its open steps reaches the task's owner instead (task steps design).
+ const ownerHere = actor.kind === 'agent' && assigned && assigned !== actor.agentId && holdsStepOf(state, group.id, actor.agentId) ? assigned : null
+ const memberToLead = actor.kind === 'agent' && !command.agentOnly && !addressed.length && assigned !== actor.agentId && ownerHere ? [ownerHere]
+ : actor.kind === 'agent' && !command.agentOnly && !addressed.length && assigned !== actor.agentId && group.leadId
&& group.leadId !== actor.agentId && group.agentIds.includes(group.leadId) ? [group.leadId] : []
// Buddy thread sessions (buddySessions.ts): a session thread's replies reach its session alone and stay in its thread; the
// main Buddy hears the rest. Decided here from the thread, so every client, an old one or the phone, is routed alike.
@@ -2703,6 +2740,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// Any assignment, an agent's or a person's, takes a worker that lost its task back into routing (model.ts lostTask).
delete worker.lostTask
if (!group.agentIds.includes(worker.id)) group.agentIds.push(worker.id)
+ // A step's agent works in its task's chat, where its owner and the other steps' agents are (task steps design).
+ const owning = group.step && group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : undefined
+ if (owning && !owning.agentIds.includes(worker.id) && joinsProject(state, owning, worker.id)) owning.agentIds.push(worker.id)
rememberAttempt(group)
group.assignment = { id: operationId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }
@@ -2770,14 +2810,27 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
// Finished work shows the worker recovered from a task it lost before.
if (command.status === 'done') delete state.agents.find(a => a.id === assignment.agentId)?.lostTask
if (changed) {
- const label = STATUS_LABELS[command.status]
+ // A step's Ready is its own hand-over, whatever its instructions call it (task steps design): not "for review".
+ const label = isStep(group) && command.status === 'review' ? 'Ready' : STATUS_LABELS[command.status]
const lead = group.leadId
const own = actor.kind === 'agent' && actor.agentId === assignment.agentId
+ // A step's progress is its task owner's to act on (Ken, 2026-11-02: the PM's terminal got a message every few
+ // seconds from builders and reviewers). Ready and Done go to the owner, else the coordinator; what needs a person or
+ // is stuck goes to both.
+ // The owner is told in the step, so it is one of the step's members: a delivery reaches members only (store.ts
+ // deliveryAllowed; final review, finding 1: a step the PM opened had no owner in it). One that may not join is
+ // not the owner here, and the coordinator hears instead.
+ const owner = isStep(group) ? reachable(group, taskOwner(state, group)) : null
+ const stepTold = !isStep(group) || !own ? null
+ : ['review', 'done'].includes(command.status) ? [owner ?? lead]
+ : ['needs_human', 'blocked'].includes(command.status) ? [lead, owner] : []
// Its own agent's change reaches the coordinator when the work waits on someone or is done: stuck is the coordinator's
// to hear as a human decision is. Anyone else's changes that agent's work, so it reaches the agent (unless its host
// confirmed it stopped) and the coordinator (final review). Nobody else is woken by role: the agent whose work is
// ready names who reviews it (project instructions, phase 4).
- const told = own ? (lead && ['needs_human', 'blocked', 'review', 'done'].includes(command.status) ? [lead] : [])
+ const told = stepTold ? stepTold.filter((id): id is string => !!id)
+ // Its own Ready wakes nobody (Ken, 2026-11-02: every hand-over reached the PM): it names whom it hands to.
+ : own ? (lead && ['needs_human', 'blocked', 'done'].includes(command.status) ? [lead] : [])
: [...command.status === 'stopped' ? [] : [assignment.agentId], ...lead ? [lead] : []]
const recipients = [...new Set(told)].filter(id => actor.kind !== 'agent' || id !== actor.agentId)
const asked = !command.ask ? '' : effects.result.notAsked ? `\n\n${effects.result.notAsked}` : `\n\nAsked ${person(state, command.ask.personId).email}.`
@@ -2826,6 +2879,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
message(group.id, `${who} cancelled this task: ${command.reason.replace(/[.\s]+$/, '')}.`, [], null, SYSTEM_ROW)
// Its line is a report the coordinator acknowledges first, so the sweep puts it to sleep later (sweeps.ts), as for any archive.
group.archived = true
+ endStepsOf(group, `${group.title} was archived.`, true)
break
}
if (!assignment || assignment.id !== command.assignmentId) fail('STALE_ASSIGNMENT', 'This is no longer the active assignment.')
@@ -2840,6 +2894,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
assignment.status = 'cancelled'
assignment.result = command.reason
if (!lost) finishWorker(state, assignment.agentId)
+ // Its steps' work ends with it; finished ones stay until it archives (task steps design; final review, finding 2).
+ endStepsOf(group, `${group.title} was cancelled.`, false)
message(group.id, `${who} cancelled this task: ${command.reason.replace(/[.\s]+$/, '')}.${gone ? '' : ' Stop working on it.'}`,
// Telling its agent to stop is the agent's alone; people read the cancel and its reason on the task itself.
gone ? [] : [assignment.agentId], null, gone ? SYSTEM_ROW : forRecipients(SYSTEM_ROW))
diff --git a/backend/src/superTabs/evidence/contribution.ts b/backend/src/superTabs/evidence/contribution.ts
index 7c72634da..2bcbf525d 100644
--- a/backend/src/superTabs/evidence/contribution.ts
+++ b/backend/src/superTabs/evidence/contribution.ts
@@ -48,7 +48,7 @@ const zero = (): Counts => Object.fromEntries(COUNTS.map(k => [k, 0])) as unknow
* rework rounds come from its ledger entry, and its ship from the group's ledger; when that entry rolled off or the group is
* gone, what was counted before stays, as those no longer change.
*/
-export function contributionOf(decision: EvidenceDecision, group: Pick<Conversation, 'reviewOf' | 'task' | 'ledger'> | undefined,
+export function contributionOf(decision: EvidenceDecision, group: Pick<Conversation, 'reviewOf' | 'step' | 'task' | 'ledger'> | undefined,
previous: Contribution | null, groupProjectId: string | undefined): Contribution | null {
const run = decision.run
const projectId = groupProjectId ?? previous?.projectId
diff --git a/backend/src/superTabs/evidence/jobKind.test.ts b/backend/src/superTabs/evidence/jobKind.test.ts
index c35d989d0..01e2b59f2 100644
--- a/backend/src/superTabs/evidence/jobKind.test.ts
+++ b/backend/src/superTabs/evidence/jobKind.test.ts
@@ -39,4 +39,11 @@ describe('job kind', () => {
expect(jobKindOf(group(['./cli/src']))).toBe('cli')
expect(jobKindOf(group(['Desktop Models section']))).toBe('desktop')
})
+ // Task steps design: a step is named by its project's instructions, so it is ranked as the work its route says, never as
+ // a review because it is linked (a marketing team's Design step is not a review).
+ it('ranks a step by its route word, else general; an old linked group stays a review', () => {
+ expect(jobKindOf({ ...group([], 'task'), step: 'Design' }, 'docs')).toBe('docs')
+ expect(jobKindOf({ ...group([], 'task'), step: 'Design' })).toBe('general')
+ expect(jobKindOf(group([], 'task'), 'docs')).toBe('review')
+ })
})
diff --git a/backend/src/superTabs/evidence/jobKind.ts b/backend/src/superTabs/evidence/jobKind.ts
index 5d2f602b8..2cd2d4d59 100644
--- a/backend/src/superTabs/evidence/jobKind.ts
+++ b/backend/src/superTabs/evidence/jobKind.ts
@@ -28,8 +28,10 @@ function entryKind(entry: string): JobKind | 'tests' | null {
* tests counting as the code and only tests as `tests`; entries naming several components, or none, leave it to the route
* word when that is a kind, else `general`.
*/
-export function jobKindOf(group: Pick<Conversation, 'reviewOf'> & { task?: { owns: string[] } }, routeWord?: string): JobKind {
- if (group.reviewOf) return 'review'
+export function jobKindOf(group: Pick<Conversation, 'reviewOf'> & { step?: string; task?: { owns: string[] } }, routeWord?: string): JobKind {
+ // A step is named by its project's instructions (task steps design): ranked as its route says, as any task is, never as a
+ // review because it is linked. A linked group from before steps is a review.
+ if (group.reviewOf && !group.step) return 'review'
if (routeWord === 'security') return 'security'
const kinds = new Set((group.task?.owns ?? []).map(entryKind).filter(k => k !== null))
const components = [...kinds].filter(k => k !== 'tests')
diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.ts
index 338b8603a..b46e3030d 100644
--- a/backend/src/superTabs/instructions.test.ts
+++ b/backend/src/superTabs/instructions.test.ts
@@ -3,7 +3,9 @@ import { applyCommand, type Command, type CommandContext } from './commands.js'
import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
import { appendRouting, instructionsHash, legacyRoleName, MAX_INSTRUCTIONS_BYTES, roleNameOf, routingSummary, summarySchema } from './instructions.js'
import type { SwarmProject } from './projects.js'
-import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
+import { INSTRUCTIONS_TEMPLATE, TEMPLATE_WORKFLOW } from './instructionsTemplate.js'
+import { hostTab } from './read/hostRows.js'
+import { FIRST_INSTRUCTIONS } from './instructions.js'
const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
@@ -30,6 +32,22 @@ function fixture() {
}
describe('the built-in template', () => {
+ // Ken, 2026-11-02: one pull request showed as three tasks (#1835, its review #1918, its test #1919), and the PM opened
+ // groups to hold, batch and triage work. Agents forgot which task they were on (agent context design, section 3).
+ it('the template workflow has one task per request, steps, and the context tools', () => {
+ expect(TEMPLATE_WORKFLOW).toContain('1. One request is one task.')
+ // Ken, 2026-11-02: the PM sets the task's team once, then stays out of it until the Engineer reports.
+ expect(TEMPLATE_WORKFLOW).toContain('names its Reviewer, and its Tester when the change needs one')
+ expect(TEMPLATE_WORKFLOW).toContain('assigns them to the Reviewer and the Tester the task names')
+ expect(TEMPLATE_WORKFLOW).toContain('The PM opens no task to hold, batch, triage or list work')
+ expect(TEMPLATE_WORKFLOW).toContain('adds a review step to its task')
+ expect(TEMPLATE_WORKFLOW).toContain('it adds no new step for a second round')
+ expect(TEMPLATE_WORKFLOW).toContain('run `mine`')
+ expect(TEMPLATE_WORKFLOW).toContain('read `task GROUP`')
+ expect(TEMPLATE_WORKFLOW).toContain('read the thread before acting on it')
+ expect(TEMPLATE_WORKFLOW).toContain('The PM reads `mine` for progress, not `status`.')
+ expect(TEMPLATE_WORKFLOW.split('\n').filter(l => /^\d+\. /.test(l))).toHaveLength(11)
+ })
it('describes the spec\'s roles, workflow and routing in one short document', () => {
for (const heading of ['## Roles', '## Workflow', '## Routing', '### PM', '### Engineer', '### Reviewer', '### Tester']) {
expect(INSTRUCTIONS_TEMPLATE).toContain(heading)
@@ -272,3 +290,19 @@ describe('role names and the coordinator\'s name', () => {
expect(() => f.run(rename('x'.repeat(41)))).toThrow()
})
})
+
+// 2026-11-02, the rollout of #2495: running agents kept the template they first read, because a project with no saved
+// document stays at revision 0 and the host's hash was null, so nothing told the daemon the template had moved.
+describe('a project on the template', () => {
+ it('names the template\'s hash to its host', async () => {
+ const f = fixture()
+ const agentId = f.add('worker-1')
+ // A project from before project instructions: nothing saved, so it reads the template.
+ for (const project of f.state.projects ?? []) { delete project.instructionsRevision; delete project.instructionsHash }
+ const lookups = { people: [], confidential: new Set<string>(), agentGrant: async () => {}, teams: [], githubApp: false }
+ const user = { sub: 'host-owner', email: '[email protected]', role: 'user', autonomousEnv: 'test' } as never
+ const rows = await hostTab('tab', f.state, 'host', user, null, lookups as never)
+ const row = rows.roster.find(r => (r as { agent?: { id: string } }).agent?.id === agentId) as { instructions?: { revision: number; hash: string | null } }
+ expect(row.instructions).toMatchObject({ revision: 0, hash: FIRST_INSTRUCTIONS.instructionsHash })
+ })
+})
diff --git a/backend/src/superTabs/instructionsTemplate.ts b/backend/src/superTabs/instructionsTemplate.ts
index a09acc621..504f37718 100644
--- a/backend/src/superTabs/instructionsTemplate.ts
+++ b/backend/src/superTabs/instructionsTemplate.ts
@@ -43,17 +43,25 @@ export const TEMPLATE_ROLES = `## Roles
export const TEMPLATE_WORKFLOW = `## Workflow
-1. The PM opens a task with its goal and "Done when", and assigns an Engineer. When no Engineer is free, it starts one.
-2. When the pull request is ready, the Engineer opens its review. When the change is something a user sees or uses
- (screens, CLI commands, install and release, sign-in, connections between machines, devices), it also opens its test.
- It messages the Reviewer and the Tester directly. Review and test run in parallel. Refactors, docs and test-only
- changes get a review only.
-3. Findings go straight to the Engineer. The Engineer fixes them and asks again. The Reviewer re-reads what changed; the
- Tester tests again when the fix changes behavior.
+1. One request is one task. The PM opens it with its goal and "Done when" and assigns an Engineer. It also
+ names its Reviewer, and its Tester when the change needs one; when no agent is free for a role, it starts one.
+ That is the PM's part until the Engineer reports. The PM opens no task to hold, batch, triage or list work: that
+ goes in its notes or the project chat.
+2. When the pull request is ready, the Engineer adds a review step to its task, and a test step when the change is
+ something a user sees or uses (screens, CLI commands, install and release, sign-in, connections between machines,
+ devices). It assigns them to the Reviewer and the Tester the task names, and messages them directly.
+ Review and test run in parallel. Refactors, docs and test-only changes get a review only. A task whose review plan
+ asks for two reviews gets two review steps.
+3. Findings go straight to the Engineer. The Engineer fixes them and asks the same Reviewer or Tester again in the same
+ step; it adds no new step for a second round.
4. When the review passes, and the test passes where there is one, the Engineer tells the PM once.
5. The PM checks CI on the pull requests that passed, merges them, and tells the people who asked.
6. A task that needs a person, or a machine that is down, goes to the PM at once, by name.
-7. Idle Engineers are stopped. Reviewers and Testers are kept while the work they checked is open.`
+7. Idle Engineers are stopped. Reviewers and Testers are kept while the work they checked is open.
+8. Before acting after a pause, or when unsure what you are working on, run \`mine\`.
+9. Before saying your work is done, read \`task GROUP\` and check that every check has passed.
+10. In a thread others have written in, read the thread before acting on it, unless the delivery already says enough.
+11. The PM reads \`mine\` for progress, not \`status\`.`
export const TEMPLATE_ROUTING = `## Routing
diff --git a/backend/src/superTabs/leaderboard/read.test.ts b/backend/src/superTabs/leaderboard/read.test.ts
index 41ec926ca..1d210fa48 100644
--- a/backend/src/superTabs/leaderboard/read.test.ts
+++ b/backend/src/superTabs/leaderboard/read.test.ts
@@ -21,7 +21,7 @@ describe('the dormant groups the leaderboard sums', () => {
const [{ pipeline }] = asked as [{ pipeline: Array<Record<string, Record<string, unknown>>> }]
expect(pipeline[0]!.$match).toEqual({ tabId: 'tab', deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(since).toISOString() } }, projectId: { $in: ['web'] } })
expect(Object.keys(pipeline[1]!.$project!).sort()).toEqual(['_id', ...['archived', 'assignment.id', 'assignment.status', 'audience', 'id', 'kind', 'leadId', 'ledger',
- 'projectId', 'pullRequestUrls', 'requesterId', 'reviewOf', 'title'].map(field => `data.${field}`)].sort())
+ 'projectId', 'pullRequestUrls', 'requesterId', 'reviewOf', 'step', 'title'].map(field => `data.${field}`)].sort())
})
it('reads the default project\'s groups stored with no project too', async () => {
diff --git a/backend/src/superTabs/leaderboard/read.ts b/backend/src/superTabs/leaderboard/read.ts
index 5504b5dcf..59c53a0ce 100644
--- a/backend/src/superTabs/leaderboard/read.ts
+++ b/backend/src/superTabs/leaderboard/read.ts
@@ -17,7 +17,7 @@ export function readableWeek(week: number | undefined, now: number): number {
/** What the board reads of a group (stats.ts, record.ts waitsNow) and its read check (projects.ts canReadGroup); the title
* names it in a person's details. */
-const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'leadId', 'audience', 'requesterId', 'reviewOf', 'archived', 'pullRequestUrls', 'ledger',
+const BOARD_FIELDS = ['id', 'kind', 'projectId', 'title', 'leadId', 'audience', 'requesterId', 'reviewOf', 'step', 'archived', 'pullRequestUrls', 'ledger',
'assignment.id', 'assignment.status'] as const
/** Dormant groups of one project active since [since]: a request shipped in a week the board sums wrote its Done row then.
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 55a0bd545..2af83a20b 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -292,6 +292,9 @@ export interface Conversation {
task?: WorkTask
/** A review group names the group whose work it reviews; only a Reviewer is assigned it, and a Reviewer nothing else. */
reviewOf?: string
+ /** A step of the task `reviewOf` names (task steps design, 2026-11-02): its name as the instructions give it, in any
+ * language. Readers show it inside its task, never as a task of its own. Absent on a linked group opened before steps. */
+ step?: string
/** An automatic review's hand-over of a two-review task (#2382); never written since project instructions, phase 4. */
reviewStamp?: ReviewStamp
checks: Check[]
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 2bd0d6f82..ba0c52eb2 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -13,7 +13,7 @@ const assignment: Required<Assignment> = {
}
const conversation: Required<Conversation> = {
id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',
- task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},
+ task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', step: 'Review', reviewStamp: { assignmentId: 'w', handoff: 1 }, checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},
messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], buddyDownTold: true, liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },
stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index 5e162266b..64139de28 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
'assignment.lost'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'reviewOf', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp',
+ unread: ['number', 'brief', 'reviewOf', 'step', 'reviewStamp', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'buddyDownTold', 'liveness', 'leadAction', 'stepUp',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt', 'assignment.changesRequestedAt',
'assignment.handoffs', 'assignment.verdicts'],
} as const
diff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.ts
index 9498d8405..eeb32b0c2 100644
--- a/backend/src/superTabs/parts/write.ts
+++ b/backend/src/superTabs/parts/write.ts
@@ -69,7 +69,8 @@ export function extracted(kind: PartKind, data: unknown, stamp: number): Record<
messageSeq: group.messageSeq ?? 0, reportSeq: group.reportSeq ?? 0,
lastActivityAt: group.lastActivityAt ? new Date(group.lastActivityAt) : new Date(stamp), hostDigest: hostDigest(group),
// A review with no active Reviewer is read by the archive pass too: it closes once its pull requests are (tidy.ts reviewClosable).
- workFinished: ['done', 'cancelled'].includes(group.assignment?.status ?? '') || (!!group.reviewOf && !activeWork(group)) }
+ // A step is never: it archives with its task (task steps design; steps.ts closeSteps), not on its own clock.
+ workFinished: !(group.step && group.reviewOf) && (['done', 'cancelled'].includes(group.assignment?.status ?? '') || (!!group.reviewOf && !activeWork(group))) }
}
case 'agent': {
const agent = data as Agent
diff --git a/backend/src/superTabs/projectUpdates.ts b/backend/src/superTabs/projectUpdates.ts
index f824c6869..61b97703d 100644
--- a/backend/src/superTabs/projectUpdates.ts
+++ b/backend/src/superTabs/projectUpdates.ts
@@ -58,6 +58,14 @@ const throughOf = (groups: Conversation[]) => Object.fromEntries(groups.map(g =>
* could not go quiet for two days (prod, 2026-10-28). One not yet received (its host offline) holds them as before. */
export const UNANSWERED_REQUEST_MS = 2 * 60 * 60_000
+/** How a report names [group]: its number (its title when it has none); a step also names its task (task steps design), and
+ * keeps its own number, which is the conversation whose messages the report asks the coordinator to read. */
+export function reportedAs(state: SuperTabState, group: Conversation): string {
+ const name = (g: Conversation) => g.number !== undefined ? `#${g.number}` : JSON.stringify(g.title)
+ const task = group.step && group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : undefined
+ return task ? `${name(group)} (step ${group.step} of ${name(task)})` : name(group)
+}
+
export function projectUpdateRequest(state: SuperTabState, target: Agent, now: number): MessageDraft | null {
// An older Swarm without stored projects is one synthesized project. It keeps no report progress (noteWorkChanges),
// so its Lead is woken only for lost work (liveness.ts), which replaced the wake-up for workers down two hours.
@@ -73,7 +81,7 @@ export function projectUpdateRequest(state: SuperTabState, target: Agent, now: n
if (!reports) return null
const through = throughOf(dirty)
const id = stableId('project-update', state.id, project.id, JSON.stringify(through))
- const after = (g: Conversation) => `${g.number !== undefined ? `#${g.number}` : JSON.stringify(g.title)} after ${progress!.summarized[g.id] ?? progress!.summarizedFloor}`
+ const after = (g: Conversation) => `${reportedAs(state, g)} after ${progress!.summarized[g.id] ?? progress!.summarizedFloor}`
const text = `Work changed in project ${JSON.stringify(project.name)}. ` +
`Read the new messages of these workgroups: ${dirty.map(after).join(', ')}; inspect their current work. ` +
'Then keep the project\'s status card current: one short line per active task saying where it is, what changed, and what it waits on; ' +
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 838c08828..ff57c2f35 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -128,6 +128,8 @@ interface ReadMeta {
export interface FirstLoad extends ReadMeta {
tabId: string
githubApp?: true
+ /** This backend opens a task's steps (`conversation.create` with `step`, task steps design); absent on an older one. */
+ steps?: true
head: LivePart<HeadView>
members: LivePart<MemberView>[]
agents: LivePart<AgentView>[]
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index 690081d54..628e0c012 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -10,7 +10,7 @@ import { hostLocalGrid, machineContribution, type MachineCleanup } from '../mach
import { agentProjectId, agentSetRole, canWatchAgent, isConfidential, groupProject, ledProject, projectsOf, skillModeOf, startProject, skillSetOf, watchClosed } from '../projects.js'
import type { HostAgentRow, HostPool, HostRosterRow, HostTabRows } from './contract.js'
import { hostEtag } from './hostEtag.js'
-import { coordinatorNameOf, roleNameOf } from '../instructions.js'
+import { coordinatorNameOf, FIRST_INSTRUCTIONS, roleNameOf } from '../instructions.js'
export interface HostLookups {
/** The Swarm's people with their account emails (observers). */
@@ -82,7 +82,10 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
skillMode: home ? skillModeOf(home) : 'orchestration',
// What the host installs as the agent's instructions, read again when the revision moves (project instructions, phase 3).
roleName: roleNameOf(state, target),
- instructions: home ? { projectId: home.id, revision: home.instructionsRevision ?? 0, hash: home.instructionsHash ?? null,
+ // At revision 0 (nothing saved) the hash is the template's, so a backend release that changes the template moves it and
+ // running daemons read the text again (2026-11-02: agents kept the old routing after #2495, as revision 0 never moves).
+ instructions: home ? { projectId: home.id, revision: home.instructionsRevision ?? 0,
+ hash: home.instructionsHash ?? (home.instructionsRevision ? null : FIRST_INSTRUCTIONS.instructionsHash),
coordinatorName: coordinatorNameOf(home) } : null,
...(custom ? { role: chosen && { ...chosen, projectId: custom.id } } : {}),
lead: !!ledProject(state, target.id),
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index ba4d297bc..2b7a79e6d 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -98,7 +98,8 @@ export class SwarmReads {
const read = await this.load(tx, cached, user, tabId, asAgentId, t0, { includeRecentStarts: true })
const { parts: loaded, view, lastChangedAt } = read
return { format: READ_FORMAT, tabId, cursor: cursorFor(t0, loaded.visibilityEpoch), serverTime: t0, lastChangedAt, epoch: loaded.visibilityEpoch,
- ...(this.options.githubApp ? { githubApp: true as const } : {}), ...view.parts,
+ // This backend opens steps (task steps design): a newer CLI sends `step` only to a backend that says so.
+ ...(this.options.githubApp ? { githubApp: true as const } : {}), steps: true as const, ...view.parts,
derived: { ...await this.withAvatars(view, t0), ...readableMarks(read, await this.marksOf(tx, tabId, read.actor),
await this.threadMarksOf(tx, tabId, read.actor), await this.settingsOf(tx, tabId, read.actor)) } }
})
diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.ts
new file mode 100644
index 000000000..42933438d
--- /dev/null
+++ b/backend/src/superTabs/steps.test.ts
@@ -0,0 +1,288 @@
+/**
+ * Steps inside a task (design docs/plans/2026-11-02-task-steps-design.md). Ken, 2026-11-02: one pull request showed as three
+ * tasks (#1835, its review #1918 and its test #1919). A step is a linked group (`reviewOf`) with a name the instructions give;
+ * readers show it inside its task. No step name means anything to the server.
+ */
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import { extracted } from './parts/write.js'
+import { stepSleeps } from './steps.js'
+import { reportedAs } from './projectUpdates.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+
+export function stepsFixture() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0, now = 1000
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const add = (harnessId: string, group = 'lead', lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
+ name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const lead = add('pm', 'lead', true)
+ const task = run({ type: 'conversation.create', title: 'Fix login', brief: 'Sign in works offline.',
+ checks: [{ description: 'Signs in offline', independent: true }] }, as(lead)).result.conversationId as string
+ const dev = add('dev', task)
+ run({ type: 'work.assign', conversationId: task, agentId: dev }, as(lead))
+ const step = (name: string, actor: Actor = as(dev), on = task, checks: Array<{ description: string; independent: boolean }> = []) =>
+ run({ type: 'conversation.create', title: name, brief: `${name} it.`, reviewOf: on, step: name, checks } as Command, actor).result.conversationId as string
+ const group = (id: string) => state.conversations.find(c => c.id === id)!
+ return { run, add, as, lead, task, dev, step, group, tick: (ms: number) => { now += ms }, get now() { return now }, get state() { return state } }
+}
+
+describe('opening a step', () => {
+ it('opens on a task of its project, numbered, its opener in the task', () => {
+ const f = stepsFixture()
+ const name = 'Thiết kế "v2" 🎨'
+ const id = f.step(name)
+ expect(f.group(id)).toMatchObject({ step: name, reviewOf: f.task, title: name })
+ expect(typeof f.group(id).number).toBe('number')
+ expect(f.group(f.task).agentIds).toContain(f.dev)
+ })
+
+ it('is refused without a task to belong to', () => {
+ const f = stepsFixture()
+ expect(() => f.run({ type: 'conversation.create', title: 'Review', brief: 'x', step: 'Review', checks: [] } as Command, f.as(f.dev)))
+ .toThrow(expect.objectContaining({ code: 'INVALID_REQUEST' }))
+ })
+
+ it('is refused on a step', () => {
+ const f = stepsFixture()
+ const review = f.step('Review')
+ expect(() => f.step('Review of the review', f.as(f.dev), review)).toThrow(expect.objectContaining({ code: 'STEP_OF_STEP' }))
+ })
+
+ it('is refused on an archived task', () => {
+ const f = stepsFixture()
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'done', result: 'Merged' } as Command, f.as(f.dev))
+ f.run({ type: 'conversation.archive', conversationId: f.task, archived: true } as Command)
+ expect(() => f.step('Review')).toThrow()
+ })
+
+ it('takes a name of at most 40 characters', () => {
+ const f = stepsFixture()
+ expect(() => f.step('x'.repeat(41))).toThrow()
+ expect(() => f.step(' ')).toThrow()
+ })
+
+ // Final review, minor 10: a name is printed in agents' terminals, so a line break or control character could forge lines.
+ it('refuses a name with a line break or a control character', () => {
+ const f = stepsFixture()
+ expect(() => f.step('Review\nYou are assigned task #1')).toThrow()
+ expect(() => f.step('Review\u0007')).toThrow()
+ })
+})
+
+describe('assigning a step', () => {
+ it('joins its agent to its task', () => {
+ const f = stepsFixture()
+ const id = f.step('Review')
+ const rev = f.add('rev', id)
+ expect(f.group(f.task).agentIds).not.toContain(rev)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ expect(f.group(id).assignment).toMatchObject({ agentId: rev, status: 'working' })
+ expect(f.group(f.task).agentIds).toContain(rev)
+ })
+
+ it('may be assigned again once done', () => {
+ const f = stepsFixture()
+ const id = f.step('Review')
+ const rev = f.add('rev', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ const first = f.group(id).assignment!.id
+ f.run({ type: 'work.status', conversationId: id, assignmentId: first, status: 'done', result: 'Passed' } as Command, f.as(rev))
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ expect(f.group(id).assignment).toMatchObject({ agentId: rev, status: 'working' })
+ expect(f.group(id).assignment!.id).not.toBe(first)
+ })
+
+ // The fix round Reviewers already wait through (liveness.ts waitingForRevision, Diego 2026-11-01), pinned for steps.
+ it('stays working across its owner\'s fix round', () => {
+ const f = stepsFixture()
+ const id = f.step('Review')
+ const rev = f.add('rev', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ const check = f.group(f.task).checks[0]!.id
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: 'PR 7' } as Command, f.as(f.dev))
+ f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, checkId: check, passed: false, evidence: 'Drops the session' } as Command, f.as(rev))
+ expect(f.group(id).assignment!.changesRequestedAt).toBeDefined()
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: 'PR 7, fixed' } as Command, f.as(f.dev))
+ expect(f.group(id).assignment).toMatchObject({ status: 'working' })
+ expect(f.group(id).assignment!.changesRequestedAt).toBeUndefined()
+ })
+})
+
+describe('a step closes with its task', () => {
+ const finishStep = (f: ReturnType<typeof stepsFixture>, id: string, agent: string) =>
+ f.run({ type: 'work.status', conversationId: id, assignmentId: f.group(id).assignment!.id, status: 'done', result: 'Passed' } as Command, f.as(agent))
+
+ it('is not marked finished work while open or done, so the archive pass never takes it on its own clock', () => {
+ const f = stepsFixture()
+ const id = f.step('Review')
+ const rev = f.add('rev', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ finishStep(f, id, rev)
+ expect(extracted('group', f.group(id), 1).workFinished).toBe(false)
+ })
+
+ it('keeps an old linked group\'s mark: it archives on its own clock as today', () => {
+ const f = stepsFixture()
+ const old = f.run({ type: 'conversation.create', title: 'Review', brief: 'x', reviewOf: f.task, checks: [] }, f.as(f.dev)).result.conversationId as string
+ expect(extracted('group', f.group(old), 1).workFinished).toBe(true)
+ })
+
+ it('archiving a task by hand cancels its working step', () => {
+ const f = stepsFixture()
+ const working = f.step('Review'), done = f.step('Test')
+ const rev = f.add('rev', working), tester = f.add('tester', done)
+ f.run({ type: 'work.assign', conversationId: working, agentId: rev }, f.as(f.dev))
+ f.run({ type: 'work.assign', conversationId: done, agentId: tester }, f.as(f.dev))
+ finishStep(f, done, tester)
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'done', result: 'Merged' } as Command, f.as(f.dev))
+ const effects = f.run({ type: 'conversation.archive', conversationId: f.task, archived: true } as Command)
+ // Final review, finding 2: an archived conversation takes no delivery, so a cancelled step stays open until it sleeps
+ // with its task, and its agent is told there.
+ expect(f.group(working)).toMatchObject({ archived: false, assignment: { status: 'cancelled', result: 'Fix login was archived.' } })
+ expect(f.group(done)).toMatchObject({ archived: true, assignment: { status: 'done' } })
+ expect(effects.messages.filter(m => m.conversationId === working).map(m => [m.text, m.recipients])).toEqual([['Fix login was archived.', [rev]]])
+ })
+
+ it('cancelling an unassigned task closes its steps', () => {
+ const f = stepsFixture()
+ const other = f.run({ type: 'conversation.create', title: 'Docs', brief: 'Write docs.', checks: [] }, f.as(f.lead)).result.conversationId as string
+ const id = f.step('Review', f.as(f.lead), other)
+ f.run({ type: 'work.cancel', conversationId: other, assignmentId: 'current', reason: 'Not needed' } as Command, f.as(f.lead))
+ expect(f.group(other).archived).toBe(true)
+ expect(f.group(id).archived).toBe(true)
+ })
+
+ // Final review, minor 5: a step that slept with a done but unarchived task was not loaded when that task was archived
+ // later, so it stayed open inside an archived task. It sleeps once its task is archived, when it was closed with it.
+ it('sleeps only once its task is archived', () => {
+ expect(stepSleeps(null)).toBe(true)
+ expect(stepSleeps({ archived: false, dormant: false })).toBe(false)
+ expect(stepSleeps({ archived: true, dormant: false })).toBe(true)
+ expect(stepSleeps({ archived: false, dormant: true })).toBe(false)
+ })
+})
+
+// Ken, 2026-11-02: the PM's terminal got a message every few seconds, a builder's or a reviewer's. A step's progress is its
+// task owner's to act on; the PM hears what needs a person, what is stuck, and what the owner tells it.
+describe('who hears a step', () => {
+ function reviewing(f = stepsFixture()) {
+ const id = f.step('Review')
+ const rev = f.add('rev', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ const status = (status: string, result: string | null = 'note', on = id, by = rev) =>
+ f.run({ type: 'work.status', conversationId: on, assignmentId: f.group(on).assignment!.id, status, result } as Command, f.as(by)).messages
+ const post = (on: string, by = rev) =>
+ f.run({ type: 'message.send', conversationId: on, text: 'Two findings.', replyTo: null, recipientIds: [] } as Command, f.as(by)).messages
+ return { f, id, rev, status, post }
+ }
+ const to = (messages: Array<{ conversationId: string; recipients: string[]; text: string }>, id: string) =>
+ messages.filter(m => m.conversationId === id).map(m => m.recipients)
+
+ it('a step\'s review and done reach the task\'s owner, not the coordinator', () => {
+ const { f, id, status } = reviewing()
+ expect(to(status('review', 'Findings posted'), id)).toEqual([[f.dev]])
+ expect(to(status('done', 'Passed'), id)).toEqual([[f.dev]])
+ })
+
+ it('with no owner, a step\'s done reaches the coordinator', () => {
+ const { f, id, status } = reviewing()
+ // The task's own work is over: nobody owns it now.
+ status('done', 'Merged', f.task, f.dev)
+ expect(to(status('done', 'Passed'), id)).toEqual([[f.lead]])
+ })
+
+ it('a step\'s blocked reaches the coordinator and the owner', () => {
+ const { f, id, status } = reviewing()
+ expect(to(status('blocked', 'No Mac'), id).map(r => [...r].sort())).toEqual([[f.lead, f.dev].sort()])
+ })
+
+ it('a step\'s review row reads Ready', () => {
+ const { id, status } = reviewing()
+ expect(status('review', 'Findings posted').filter(m => m.conversationId === id).map(m => m.text)).toEqual(['Ready\n\nFindings posted'])
+ })
+
+ it('a step agent\'s unnamed post reaches the owner, in its step or in its task', () => {
+ const { f, id, post } = reviewing()
+ expect(to(post(id), id)).toEqual([[f.dev]])
+ expect(to(post(f.task), f.task)).toEqual([[f.dev]])
+ })
+
+ it('an agent with no open step in the task still reaches the coordinator', () => {
+ const { f, post } = reviewing()
+ const other = f.add('other', f.task)
+ expect(to(post(f.task, other), f.task)).toEqual([[f.lead]])
+ })
+
+ it('an old linked group keeps today\'s notices', () => {
+ const f = stepsFixture()
+ const old = f.run({ type: 'conversation.create', title: 'Review', brief: 'x', reviewOf: f.task, checks: [] }, f.as(f.dev)).result.conversationId as string
+ const rev = f.add('rev', old)
+ f.run({ type: 'work.assign', conversationId: old, agentId: rev }, f.as(f.dev))
+ const messages = f.run({ type: 'work.status', conversationId: old, assignmentId: f.group(old).assignment!.id, status: 'done', result: 'Passed' } as Command, f.as(rev)).messages
+ expect(to(messages, old)).toEqual([[f.lead]])
+ expect(messages.find(m => m.conversationId === old)!.text).toBe('Done\n\nPassed')
+ })
+})
+
+describe('the PM\'s reports', () => {
+ it('name a step by its own number and its task', () => {
+ const f = stepsFixture()
+ const id = f.step('Review')
+ expect(reportedAs(f.state, f.group(id))).toBe(`#${f.group(id).number} (step Review of #${f.group(f.task).number})`)
+ expect(reportedAs(f.state, f.group(f.task))).toBe(`#${f.group(f.task).number}`)
+ })
+})
+
+// Ken, 2026-11-02 (a Reviewer's and a builder's every hand-over reached the PM): an agent's Ready on its own task wakes
+// nobody by itself. It names whom it hands to; the PM hears Done, Stuck and Needs a human.
+describe('an agent\'s own Ready', () => {
+ it('reaches nobody by itself', () => {
+ const f = stepsFixture()
+ const messages = f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: 'PR 7' } as Command, f.as(f.dev)).messages
+ expect(messages.filter(m => m.conversationId === f.task).map(m => m.recipients)).toEqual([[]])
+ })
+ it('Done still reaches the coordinator', () => {
+ const f = stepsFixture()
+ const messages = f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'done', result: 'Merged' } as Command, f.as(f.dev)).messages
+ expect(messages.filter(m => m.conversationId === f.task && m.text.startsWith('Done')).map(m => m.recipients)).toEqual([[f.lead]])
+ })
+})
+
+// Final review, finding 1: a step the PM opened has no owner in it, so a Ready or Done told to the owner was never
+// delivered (store.ts deliveryAllowed reads membership). The owner joins the step when it is told.
+describe('a step the PM opened', () => {
+ it('its Done reaches the owner, who joins the step', () => {
+ const f = stepsFixture()
+ const id = f.step('Review', f.as(f.lead))
+ const rev = f.add('rev', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.lead))
+ expect(f.group(id).agentIds).not.toContain(f.dev)
+ const messages = f.run({ type: 'work.status', conversationId: id, assignmentId: f.group(id).assignment!.id, status: 'done', result: 'Passed' } as Command, f.as(rev)).messages
+ expect(messages.filter(m => m.conversationId === id).map(m => m.recipients)).toEqual([[f.dev]])
+ expect(f.group(id).agentIds).toContain(f.dev)
+ })
+})
+
+describe('cancelling an assigned task', () => {
+ it('cancels its open steps and tells their agents, leaving finished ones', () => {
+ const f = stepsFixture()
+ const working = f.step('Review'), done = f.step('Test')
+ const rev = f.add('rev', working), tester = f.add('tester', done)
+ f.run({ type: 'work.assign', conversationId: working, agentId: rev }, f.as(f.dev))
+ f.run({ type: 'work.assign', conversationId: done, agentId: tester }, f.as(f.dev))
+ f.run({ type: 'work.status', conversationId: done, assignmentId: f.group(done).assignment!.id, status: 'done', result: 'Passed' } as Command, f.as(tester))
+ const effects = f.run({ type: 'work.cancel', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, reason: 'Not needed' } as Command, f.as(f.lead))
+ expect(f.group(working).assignment).toMatchObject({ status: 'cancelled', result: 'Fix login was cancelled.' })
+ expect(f.group(done).assignment).toMatchObject({ status: 'done' })
+ expect(effects.messages.filter(m => m.conversationId === working).map(m => [m.text, m.recipients])).toEqual([['Fix login was cancelled.', [rev]]])
+ })
+})
diff --git a/backend/src/superTabs/steps.ts b/backend/src/superTabs/steps.ts
new file mode 100644
index 000000000..ea834af94
--- /dev/null
+++ b/backend/src/superTabs/steps.ts
@@ -0,0 +1,46 @@
+/**
+ * Steps inside a task (design docs/plans/2026-11-02-task-steps-design.md). A step is a linked group (`reviewOf` names its
+ * task) with a name the project's instructions give: it keeps its own assignment, lease, attempts and costs, and readers
+ * show it inside its task. Nothing here reads a step's name: which steps a task has is the instructions' to say.
+ */
+import { activeWork, finishWorker, type Conversation, type SuperTabState } from './model.js'
+
+/** Whether [group] is a step of a task (an older linked group, with no name, is not). */
+export const isStep = (group: Pick<Conversation, 'step' | 'reviewOf'>): boolean => !!group.step && !!group.reviewOf
+
+/** The steps of task [taskId], in creation order. */
+export const stepsOf = (state: SuperTabState, taskId: string): Conversation[] =>
+ state.conversations.filter(c => c.reviewOf === taskId && !!c.step)
+
+/** Ends [task]'s steps with it, in the same write. An open one is cancelled with [reason] as its result and its agent
+ * freed; it stays unarchived, as an archived conversation takes no delivery (store.ts deliveryAllowed) and its agent is
+ * told there, and it sleeps with its task. With [archive], a finished one is archived with its task: without that, a
+ * `done` step with no pull request of its own was archived within one archive pass (`settled([])`), and a second round on
+ * it failed ARCHIVED. Returns the cancelled ones, whose agents the caller tells. */
+export function endSteps(state: SuperTabState, task: Conversation, reason: string, archive: boolean): Conversation[] {
+ const cancelled: Conversation[] = []
+ for (const step of stepsOf(state, task.id)) {
+ if (step.archived) continue
+ if (activeWork(step)) {
+ Object.assign(step.assignment!, { status: 'cancelled', result: reason })
+ finishWorker(state, step.assignment!.agentId)
+ cancelled.push(step)
+ } else if (archive) step.archived = true
+ }
+ return cancelled
+}
+
+/** Whether a step may sleep, given its task's row as the sweep read it (null: gone). A step sleeps once its task is
+ * archived, never on its own clock nor with a task that is only dormant: a dormant step drops out of the Swarm read with
+ * its verdict, and one asleep under a done task was not loaded when that task was archived later, so it stayed open in an
+ * archived task (final review, minor 5). */
+export const stepSleeps = (task: { archived: boolean; dormant: boolean } | null): boolean => !task || task.archived
+/** The task's owner for [step]: the agent assigned its task while that work is open, else null (the coordinator's then). */
+export function taskOwner(state: SuperTabState, step: Conversation): string | null {
+ const task = isStep(step) ? state.conversations.find(c => c.id === step.reviewOf) : undefined
+ return task && activeWork(task) ? task.assignment!.agentId : null
+}
+
+/** Whether [agentId] holds an open step of task [taskId]. */
+export const holdsStepOf = (state: SuperTabState, taskId: string, agentId: string): boolean =>
+ stepsOf(state, taskId).some(s => activeWork(s) && s.assignment!.agentId === agentId)
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index caf7165e5..5caeb3d95 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -47,6 +47,7 @@ import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './part
import { memberSwarms } from './swarmRows.js'
import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'
import { loadDeliveryParts, ms } from './parts/light.js'
+import { endSteps } from './steps.js'
import { guardedWrite, partId } from './parts/write.js'
import { retryable } from './retry.js'
import { touchesFor } from './parts/touches.js'
@@ -1497,8 +1498,12 @@ export class SuperTabStore {
// A task cancelled with no assignment archives (commands.ts work.cancel).
|| command.type === 'work.cancel' && !original.conversations.find(c => c.id === command.conversationId)?.archived
&& !!effects.state.conversations.find(c => c.id === command.conversationId)?.archived
- if (unreadable) {
- await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: command.conversationId, status: { in: ['queued', 'claimed', 'uncertain'] },
+ // A task's finished steps archive with it (steps.ts endSteps): their deliveries end too (final review, finding 2).
+ const archivedSteps = unreadable && command.type !== 'conversation.agent' ? effects.state.conversations.filter(c => c.reviewOf === command.conversationId
+ && c.step && c.archived && !original.conversations.find(o => o.id === c.id)?.archived).map(c => c.id) : []
+ // One plain match per conversation: an `in` on this hot collection is sent as $expr, which no index bounds (hotFilters).
+ for (const conversationId of unreadable ? [command.conversationId, ...archivedSteps] : []) {
+ await tx.superTabDelivery.updateMany({ where: { tabId, conversationId, status: { in: ['queued', 'claimed', 'uncertain'] },
...(command.type === 'conversation.agent' ? { agentId: command.agentId } : {}) },
data: { status: 'cancelled', holdReason: null, holdSince: null } })
}
@@ -2069,7 +2074,7 @@ export class SuperTabStore {
if (revision && stored?.revision !== revision) fail('INSTRUCTIONS_UNAVAILABLE', 'This project\'s instructions cannot be read now. Try again in a moment.', 503)
const notes = buddy ? undefined : liveNotes(await readNotes(tx, tabId, projectId), this.now())
.map(n => ({ id: n.id, text: n.text, askedBy: n.askedBy, at: new Date(n.at), expiresAt: n.expiresAt === null ? null : new Date(n.expiresAt) }))
- return { projectId, revision, hash: stored?.hash ?? null, text: stored?.text ?? INSTRUCTIONS_TEMPLATE, template: !stored,
+ return { projectId, revision, hash: stored ? stored.hash : FIRST_INSTRUCTIONS.instructionsHash, text: stored?.text ?? INSTRUCTIONS_TEMPLATE, template: !stored,
coordinatorName: coordinatorNameOf(project), notesRevision: project.notesRevision ?? 0, ...(notes ? { notes } : {}) }
})
}
@@ -3404,6 +3409,9 @@ export class SuperTabStore {
// Its work is over: a decision still waiting there waits no more (Dee, 10-31), as when the work ended by a command.
await withdrawIn(tx, tabId, [groupId], now)
group.archived = true
+ // Its steps archive with it (task steps design): its work is done or cancelled and its pull requests settled, so a
+ // step still open there has nothing left to check.
+ endSteps(state, group, `${group.title} was archived.`, true)
const line = finished ? archiveLine(state, group, now) : reviewCloseLine(state, group, checked, now), rows = line ? [line] : []
const sequences = numberMessages(state, rows, now)
if (!dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true
diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.ts
index 071454d62..19d94c840 100644
--- a/backend/src/superTabs/sweeps.ts
+++ b/backend/src/superTabs/sweeps.ts
@@ -1,5 +1,6 @@
import type { Prisma, PrismaClient } from '@prisma/client'
import type { AgentStart, Conversation } from './model.js'
+import { stepSleeps } from './steps.js'
import { clock, guardedWrite, PartConflict, type HeadData, type ProgressData } from './parts/index.js'
import { DORMANT_AFTER_MS, RETENTION_MS } from './parts/types.js'
import { deletedSwarms } from './deletion.js'
@@ -86,6 +87,12 @@ async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number>
if (!progress.has(id)) progress.set(id, ((await db.swarmProgress.findUnique({ where: { id } }))?.data as unknown as ProgressData | undefined) ?? null)
return progress.get(id)!
}
+ const tasks = new Map<string, { archived: boolean; dormant: boolean } | null>()
+ const taskOf = async (tabId: string, key: string) => {
+ const id = `${tabId}:${key}`
+ if (!tasks.has(id)) tasks.set(id, await db.swarmGroup.findUnique({ where: { tabId_key: { tabId, key } }, select: { archived: true, dormant: true } }))
+ return tasks.get(id)!
+ }
// A deleted Swarm's groups stay as they are for its restore (deletion.ts).
const isDeleted = deletedSwarms(db)
let slept = 0, after: { at: Date; id: string } | null = null
@@ -98,6 +105,8 @@ async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number>
const quiet = row.lastActivityAt.getTime() < now - DORMANT_AFTER_MS && ['done', 'cancelled'].includes(group.assignment?.status ?? '')
if (!group.archived && !quiet) continue
if ((await leadsOf(row.tabId)).has(group.id)) continue
+ // A step sleeps with its task (task steps design): read once per task in this pass.
+ if (group.step && group.reviewOf && !stepSleeps(await taskOf(row.tabId, group.reviewOf))) continue
const reports = group.audience ? null : await progressOf(row.tabId, group.projectId ?? 'lead')
if (reports && (group.reportSeq ?? 0) > (reports.summarized[group.id] ?? reports.summarizedFloor)) continue
if (await guarded(db, { tabId: row.tabId, op: 'update', kind: 'group', key: row.key, seen: row.version, data: { ...group, dormant: true } })) slept++
diff --git a/cli/src/lib/swarmTools.spec.ts b/cli/src/lib/swarmTools.spec.ts
index 231c28e5a..4638c2853 100644
--- a/cli/src/lib/swarmTools.spec.ts
+++ b/cli/src/lib/swarmTools.spec.ts
@@ -40,4 +40,25 @@ describe('SWARM_TOOLS_SKILL', () => {
expect(lineOf('"type":"note.add"')).toMatch(/only the project's coordinator/i)
expect(lineOf('"type":"note.remove"')).toMatch(/coordinator/)
})
+ // Agent context design, section 1: the skill says what each tool returns; when to use it is the instructions'.
+ it('lists mine, task and reading one thread', () => {
+ expect(SWARM_TOOLS_SKILL).toContain('- \`mine\`:')
+ expect(SWARM_TOOLS_SKILL).toContain('- \`task GROUP\`:')
+ expect(SWARM_TOOLS_SKILL).toContain('messages GROUP --thread ROOT')
+ })
+ // Task steps design: a step's name is the instructions', so the skill shows how to add one and lists no kinds of step.
+ it('says how to add a step, naming no kinds of step', () => {
+ expect(SWARM_TOOLS_SKILL).toContain('Add a step to a task:')
+ expect(SWARM_TOOLS_SKILL).not.toMatch(/Review, Test|review and test steps/i)
+ })
+ // Ken, 2026-11-02: an agent's own Ready no longer reaches the coordinator (backend commands.ts work.status).
+ it('says a review status wakes nobody by itself', () => {
+ expect(SWARM_TOOLS_SKILL).toContain('A \`review\` status wakes nobody by itself')
+ expect(SWARM_TOOLS_SKILL).not.toContain('tells only the reviewed group\'s coordinator')
+ })
+ // Final review, minor 9: the step bullet ran into the next one.
+ it('keeps the step bullet on a line of its own', () => {
+ const line = SWARM_TOOLS_SKILL.split('\n').find(l => l.startsWith('- Add a step to a task:'))!
+ expect(line).not.toContain('A review group')
+ })
})
diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.ts
index ddb9638aa..35e3abea2 100644
--- a/cli/src/lib/swarmTools.ts
+++ b/cli/src/lib/swarmTools.ts
@@ -15,7 +15,9 @@ Every command starts \`harness super-tab --tab TAB\` (your tab id is in your lau
## Read
- \`status [--archived [PAGE]]\`: the shared roster and work: people, projects, agents (id, name, machine, state), conversations, tasks. Agent ids for \`--to\` come from here.
-- \`messages GROUP [--before SEQUENCE MESSAGE_ID]\`: recent messages of a conversation, thread replies included; each names the thread (the root message) it answers in. \`--before\` pages back from the cursor the last page named.
+- \`mine\`: what you work on, one line per task: its number, title, conversation id, status, when it last changed, its last result and pull requests, and the open tasks linked to it. A project's coordinator gets every open task of its project instead.
+- \`task GROUP\`: one task: its project, status, assignee, pull requests, brief, checks (passed, by whom, or failed with the evidence's first line), attempts newest first, and linked tasks. It reads a finished task too.
+- \`messages GROUP [--before SEQUENCE MESSAGE_ID]\`: recent messages of a conversation, thread replies included; each names the thread (the root message) it answers in. \`--before\` pages back from the cursor the last page named. \`messages GROUP --thread ROOT\` reads one thread whole: its root and every reply.
- \`message GROUP MESSAGE_ID\`: one exact message, such as an earlier question or result a reply refers to.
- \`instructions [PROJECT]\`: your project's instructions and the coordinator's notes, printed whole. Read them when you start and when told they changed. Without PROJECT, the project you work in. INSTRUCTIONS_UNAVAILABLE saying the Swarm has no project instructions yet is an older Swarm: work by the swarm skill Harness gave you at start (your role file) then. The same code saying to try again is a passing failure: run \`instructions\` again in a moment.
- \`decisions [--answered]\`: decisions asked of people, still open, or with \`--answered\` those answered, each with its choice and note.
@@ -96,7 +98,8 @@ Swarm and machine settings (each refused unless you may change that setting; a p
- Start only on the Swarm's listed machines; to use another, a person adds it first. \`resume START_ID\` finishes a pending start without creating another agent; repeat \`start\` with the same id after an interruption. Two failed starts in a row suspend the engine on that machine; the route says so.
- A start that fails is reported (\`START_FAILED\`, with why) and moved nowhere: you decide what next, and the project's coordinator is told too.
- Starts can be refused when too many starts are pending.
-- A review group is a group created with \`reviewOf\` naming the group it reviews. A \`review\` status tells only the reviewed group's coordinator: when the work is ready for review, name the reviewing agent with \`--to\` in your post.
+- Add a step to a task: create a conversation with \`reviewOf\` set to the task and \`step\` set to the step's name from your project's instructions, then assign it. A step's status reaches the task's assignee.
+- A review group is a group created with \`reviewOf\` naming the group it reviews. A \`review\` status wakes nobody by itself: when the work is ready for review, name the reviewing agent with \`--to\` in your post.
## Requests, tasks and cards
- A group opened for a person's request, asked in the chat or proposed by their Buddy, names them as requester (\`requesterId\`, or \`conversation.requester\` later). It records only that they asked, never what they wrote.
diff --git a/cli/src/superTabs/agentContext.spec.ts b/cli/src/superTabs/agentContext.spec.ts
new file mode 100644
index 000000000..d1c430056
--- /dev/null
+++ b/cli/src/superTabs/agentContext.spec.ts
@@ -0,0 +1,189 @@
+import { describe, expect, it } from 'vitest'
+import { isCoordinator, mineText, openWorkOf, taskText } from './agentContext.js'
+
+const NOW = Date.parse('2026-11-02T10:00:00.000Z')
+const MIN = 60_000
+
+type Group = Record<string, unknown>
+function swarm(groups: Group[], extra: Record<string, unknown> = {}) {
+ return {
+ projects: [{ id: 'app', name: 'App', leadConversationId: 'lead-app' }, { id: 'web', name: 'Web', leadConversationId: 'lead-web' }],
+ people: [{ id: 'ken', email: '[email protected]' }],
+ agents: [{ id: 'pm', name: 'PM' }, { id: 'dev1', name: 'Dev1' }, { id: 'rev1', name: 'Rev1' }, { id: 'pm-web', name: 'Web PM' }],
+ conversations: [
+ { id: 'lead-app', projectId: 'app', title: 'App', leadId: 'pm', agentIds: ['pm'], archived: false, checks: [], assignment: null },
+ { id: 'lead-web', projectId: 'web', title: 'Web', leadId: 'pm-web', agentIds: ['pm-web'], archived: false, checks: [], assignment: null },
+ ...groups,
+ ],
+ ...extra,
+ }
+}
+const task = (id: string, number: number, title: string, agentId: string | null, status: string | null, more: Group = {}): Group => ({
+ id, projectId: 'app', number, title, leadId: 'pm', agentIds: ['pm'], archived: false, checks: [],
+ assignment: agentId ? { id: `as-${id}`, agentId, status, result: null } : null, ...more,
+})
+const changed = (entries: Record<string, number>) => new Map(Object.entries(entries))
+
+describe('mine', () => {
+ it('lists an agent\'s open task with status, update time, result and PR', () => {
+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working', {
+ assignment: { id: 'a', agentId: 'dev1', status: 'working', result: 'Tests pass on main\nmore detail' },
+ pullRequestUrls: ['https://github.com/o/r/pull/7'] })])
+ expect(mineText(state, changed({ g12: NOW - 5 * MIN }), 'dev1', NOW)).toBe(
+ '#12 Fix login (conversation g12) — working, updated 5 min ago; last result: Tests pass on main; PR https://github.com/o/r/pull/7')
+ })
+
+ it('leaves out a reused agent\'s finished task', () => {
+ const state = swarm([task('g11', 11, 'Old work', 'dev1', 'done'), task('g12', 12, 'Fix login', 'dev1', 'working')])
+ expect(openWorkOf(state, 'dev1').map(t => t.number)).toEqual([12])
+ expect(mineText(state, changed({}), 'dev1', NOW)).not.toContain('#11')
+ })
+
+ it('leaves out archived tasks', () => {
+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working', { archived: true })])
+ expect(mineText(state, changed({}), 'dev1', NOW)).toBe('No task is assigned to you.')
+ })
+
+ it('lists linked tasks of its work with their assignee', () => {
+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working'),
+ task('g13', 13, 'Review: Fix login', 'rev1', 'working', { reviewOf: 'g12' })])
+ expect(mineText(state, changed({}), 'dev1', NOW)).toContain('\n linked: #13 Review: Fix login (conversation g13) — Rev1, working')
+ // The Reviewer sees the task its work is linked to, either way.
+ expect(mineText(state, changed({}), 'rev1', NOW)).toContain('\n linked: #12 Fix login (conversation g12) — Dev1, working')
+ })
+
+ it('the coordinator\'s mine lists its project\'s open tasks and counts them', () => {
+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working'), task('g14', 14, 'Docs', null, null),
+ task('g15', 15, 'Shipped', 'dev1', 'done'), task('g16', 16, 'Review', 'rev1', 'review', { reviewOf: 'g12' }),
+ { ...task('g20', 20, 'Web work', 'pm-web', 'working'), projectId: 'web' }])
+ expect(isCoordinator(state, 'pm')).toBe(true)
+ const text = mineText(state, changed({}), 'pm', NOW)
+ expect(text).toContain('#12 Fix login (conversation g12) — Dev1, working')
+ expect(text).toContain('#14 Docs (conversation g14) — unassigned')
+ expect(text).not.toContain('#15')
+ expect(text).not.toContain('Web work')
+ expect(text.endsWith('3 open tasks.')).toBe(true)
+ })
+
+ it('with nothing says so', () => {
+ expect(mineText(swarm([]), changed({}), 'dev1', NOW)).toBe('No task is assigned to you.')
+ })
+
+ it('cuts a result to its first line and 160 characters', () => {
+ const long = 'x'.repeat(200)
+ const state = swarm([task('g12', 12, 'Fix login', 'dev1', 'working', { assignment: { id: 'a', agentId: 'dev1', status: 'working', result: long } })])
+ expect(mineText(state, changed({}), 'dev1', NOW)).toContain(`last result: ${'x'.repeat(160)}…`)
+ })
+})
+
+describe('task', () => {
+ const group = task('g12', 12, 'Fix login', 'dev1', 'working', {
+ brief: 'Goal:\nSign in works offline.', pullRequestUrls: ['https://github.com/o/r/pull/7'],
+ assignment: { id: 'a3', agentId: 'dev1', status: 'working', result: 'Fixed the token refresh' },
+ checks: [
+ { id: 'c1', description: 'Signs in offline', independent: true, evidence: 'Ran the app offline', passedBy: 'agent:rev1' },
+ { id: 'c2', description: 'Refresh keeps the session', independent: true, evidence: 'Session dropped after refresh\nlog…', passedBy: null },
+ { id: 'c3', description: 'Docs updated', independent: false, evidence: null, passedBy: null },
+ ],
+ })
+ const attempts = [
+ { id: 'a2', agentId: 'gone', status: 'lost', result: 'Stalled', createdAt: '2026-11-01T09:00:00.000Z' },
+ { id: 'a1', agentId: 'dev1', status: 'stopped', result: null, createdAt: '2026-10-31T09:00:00.000Z' },
+ ]
+
+ it('shows goal, checks, attempts and linked tasks', () => {
+ const state = swarm([group, task('g13', 13, 'Review: Fix login', 'rev1', 'working', { reviewOf: 'g12' })])
+ const text = taskText(group, state, attempts, changed({ g12: NOW - 2 * MIN }), NOW)
+ expect(text.split('\n')[0]).toBe('#12 Fix login (conversation g12)')
+ expect(text).toContain('Project: App · Status: working · Assignee: Dev1 · Updated 2 min ago')
+ expect(text).toContain('PR: https://github.com/o/r/pull/7')
+ expect(text).toContain('Goal:\nSign in works offline.')
+ expect(text).toContain('✓ Signs in offline — by Rev1')
+ expect(text).toContain('✗ Refresh keeps the session — Session dropped after refresh')
+ expect(text).toContain('· Docs updated')
+ const lines = text.split('\n')
+ const at = lines.indexOf('Attempts (newest first):')
+ expect(lines.slice(at + 1, at + 4)).toEqual([
+ '- Dev1, working (current): Fixed the token refresh',
+ '- gone, lost, 2026-11-01 09:00 UTC: Stalled',
+ '- Dev1, stopped, 2026-10-31 09:00 UTC',
+ ])
+ expect(text).toContain('- #13 Review: Fix login (conversation g13) — Rev1, working')
+ expect(text).toContain('messages g12')
+ expect(text).toContain('messages g12 --thread ROOT')
+ })
+
+ it('shows at most 10 attempts', () => {
+ const many = Array.from({ length: 15 }, (_, i) => ({ id: `x${i}`, agentId: 'dev1', status: 'stopped', result: null, createdAt: '2026-10-31T09:00:00.000Z' }))
+ const text = taskText(group, swarm([group]), many, changed({}), NOW)
+ expect(text.split('\n').filter(l => l.startsWith('- Dev1, '))).toHaveLength(10)
+ })
+
+ it('cuts a long brief with a pointer', () => {
+ const long = { ...group, brief: 'b'.repeat(2000) }
+ const text = taskText(long, swarm([long]), [], changed({}), NOW)
+ expect(text).toContain(`${'b'.repeat(1500)}… (cut; the whole brief: status)`)
+ })
+
+ it('says when its attempts could not be read', () => {
+ expect(taskText(group, swarm([group]), null, changed({}), NOW)).toContain('Earlier attempts could not be read.')
+ })
+})
+
+// Task steps design: a step is shown inside its task, never as a task of its own.
+describe('steps', () => {
+ const withSteps = () => swarm([
+ task('g1835', 1835, 'Fix login', 'dev1', 'working'),
+ task('g1918', 1918, 'Review', 'rev1', 'working', { reviewOf: 'g1835', step: 'Review',
+ checks: [{ id: 'c', description: 'Verdict', independent: false, evidence: null, passedBy: 'agent:rev1' }] }),
+ task('g1919', 1919, 'Test', 'dev1', 'done', { reviewOf: 'g1835', step: 'Test', assignment: { id: 'a', agentId: 'dev1', status: 'done', result: 'Passed on a Mac' } }),
+ ], { agents: [{ id: 'pm', name: 'PM' }, { id: 'dev1', name: 'Dev1' }, { id: 'rev1', name: 'Rev1' }] })
+
+ it('mine shows a step\'s agent its step by its task', () => {
+ expect(mineText(withSteps(), changed({}), 'rev1', NOW)).toBe('#1835 Fix login · Review (conversation g1918) — working')
+ })
+
+ it('mine shows the owner its task\'s steps on one line', () => {
+ expect(mineText(withSteps(), changed({}), 'dev1', NOW)).toBe(
+ '#1835 Fix login (conversation g1835) — working\n steps: Review (Rev1): working · Test (Dev1): done')
+ })
+
+ it('the coordinator\'s open work counts tasks, not steps', () => {
+ const text = mineText(withSteps(), changed({}), 'pm', NOW)
+ expect(text).toContain('#1835 Fix login (conversation g1835) — Dev1, working\n steps: Review (Rev1): working · Test (Dev1): done')
+ expect(text).not.toContain('#1918')
+ expect(text.endsWith('1 open task.')).toBe(true)
+ })
+
+ it('task lists its steps', () => {
+ const state = withSteps()
+ const group = (state.conversations as Array<Record<string, unknown>>).find(c => c.id === 'g1835')!
+ const text = taskText(group, state, [], changed({}), NOW)
+ expect(text).toContain('Steps:\n- Review (Rev1): working, 1 of 1 checks passed (conversation g1918)\n- Test (Dev1): done: Passed on a Mac (conversation g1919)')
+ expect(text).not.toContain('Linked:')
+ })
+
+ it('task of a step shows its task with the step marked', () => {
+ const state = withSteps()
+ const step = (state.conversations as Array<Record<string, unknown>>).find(c => c.id === 'g1918')!
+ const text = taskText(step, state, [], changed({}), NOW)
+ expect(text.split('\n')[0]).toBe('#1835 Fix login (conversation g1835)')
+ expect(text).toContain('▶ Review (Rev1): working')
+ })
+})
+
+// E2E 2026-11-02: a new Swarm's default project is 'lead', whose Lead conversation has no projectId while its tasks say
+// 'lead' (backend groupProject reads a missing one as 'lead'): the PM's mine counted none of them.
+describe('the default project', () => {
+ it('the coordinator\'s mine counts the tasks of a Lead conversation with no projectId', () => {
+ const state = {
+ projects: [{ id: 'lead', name: 'Main', leadConversationId: 'lead' }],
+ agents: [{ id: 'pm', name: 'PM' }, { id: 'dev1', name: 'Dev1' }],
+ conversations: [
+ { id: 'lead', title: 'Main', leadId: 'pm', agentIds: ['pm'], archived: false, checks: [], assignment: null },
+ { ...task('g1', 1, 'Fix login', 'dev1', 'review'), projectId: 'lead' },
+ ],
+ }
+ expect(mineText(state, changed({}), 'pm', NOW)).toBe('#1 Fix login (conversation g1) — Dev1, review\n1 open task.')
+ })
+})
diff --git a/cli/src/superTabs/agentContext.ts b/cli/src/superTabs/agentContext.ts
new file mode 100644
index 000000000..b25e7d08c
--- /dev/null
+++ b/cli/src/superTabs/agentContext.ts
@@ -0,0 +1,217 @@
+/**
+ * What an agent works on, from the Swarm read it already makes (design docs/plans/2026-11-02-agent-context-design.md,
+ * section 1). Ken, 2026-11-02: agents forgot which task they were on and how far it got, and the PM read the whole Swarm
+ * (over a hundred groups) to learn its project's progress. `mine` is one short line per task; `task` is one task as its
+ * readers need it. Nothing here decides workflow: when to read them is the project's instructions'.
+ */
+
+type Json = Record<string, unknown>
+const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}
+const list = (value: unknown): Json[] => Array.isArray(value) ? value.map(object) : []
+const text = (value: unknown): string | null => typeof value === 'string' && value !== '' ? value : null
+
+/** Statuses of finished work, as the backend's FINISHED (parts/light.ts) and activeWork (model.ts) read them. */
+export const FINISHED_STATUSES: readonly string[] = ['done', 'stopped', 'cancelled', 'lost']
+const RESULT_MAX = 160
+const BRIEF_MAX = 1500
+const ATTEMPTS_MAX = 10
+
+export interface TaskLine {
+ id: string
+ number: number | null
+ title: string
+ status: string
+ agentName: string | null
+ updatedAt: number | null
+ result: string | null
+ pullRequestUrls: string[]
+ step: string | null
+ taskId: string | null
+ /** For a step: its task's number and title, by which it is shown (task steps design). */
+ taskNumber: number | null
+ taskTitle: string | null
+}
+
+const isOpen = (group: Json): boolean => {
+ const status = text(object(group.assignment).status)
+ return !!status && !FINISHED_STATUSES.includes(status)
+}
+const leadConversations = (state: Json): string[] =>
+ Array.isArray(state.projects) ? list(state.projects).map(p => String(p.leadConversationId)) : ['lead']
+/** A step of a task (task steps design): a linked group with a name; an older linked group has none. */
+export const isStep = (group: Json): boolean => typeof group.step === 'string' && group.step !== '' && typeof group.reviewOf === 'string'
+/** Work an agent may hold: a group of a project that is not its Lead conversation, a Buddy chat or any other kind. */
+const isWork = (state: Json, group: Json): boolean => !group.kind && !leadConversations(state).includes(String(group.id))
+/** A task: work that is not a step. */
+const isTask = (state: Json, group: Json): boolean => isWork(state, group) && !isStep(group)
+
+/** A project's Lead is its Lead conversation's, as the backend reads it; a Swarm from before projects has one, 'lead'. */
+export function isCoordinator(state: Json, agentId: string): boolean {
+ const leads = leadConversations(state)
+ return list(state.conversations).some(c => leads.includes(String(c.id)) && c.leadId === agentId)
+}
+
+const agentName = (state: Json, agentId: unknown): string | null =>
+ typeof agentId === 'string' ? text(list(state.agents).find(a => a.id === agentId)?.name) ?? agentId : null
+
+function lineOf(state: Json, group: Json): TaskLine {
+ const assignment = object(group.assignment)
+ const task = isStep(group) ? list(state.conversations).find(c => c.id === group.reviewOf) : undefined
+ return {
+ taskNumber: task && typeof task.number === 'number' ? task.number : null, taskTitle: task ? String(task.title ?? '') : null,
+ id: String(group.id), number: typeof group.number === 'number' ? group.number : null, title: String(group.title ?? ''),
+ status: text(assignment.status) ?? 'unassigned', agentName: agentName(state, assignment.agentId),
+ updatedAt: null, result: text(assignment.result),
+ pullRequestUrls: Array.isArray(group.pullRequestUrls) ? group.pullRequestUrls.filter((u): u is string => typeof u === 'string') : [],
+ step: text(group.step), taskId: text(group.reviewOf),
+ }
+}
+
+/** The tasks assigned to [agentId] that are open work and not archived. A reused agent keeps `assignment.agentId` on an
+ * old finished task until it goes dormant; listing it ("#11 (done)") is the confusion this exists to end. */
+export function openWorkOf(state: Json, agentId: string): TaskLine[] {
+ return list(state.conversations)
+ .filter(g => isWork(state, g) && g.archived !== true && isOpen(g) && object(g.assignment).agentId === agentId)
+ .map(g => lineOf(state, g))
+}
+
+/** The coordinator's project: every task of it that is not archived and not finished, assigned or not. */
+export function projectOpenWork(state: Json, agentId: string): TaskLine[] {
+ const leads = new Set(leadConversations(state))
+ const lead = list(state.conversations).find(c => leads.has(String(c.id)) && c.leadId === agentId)
+ if (!lead) return []
+ // A missing projectId is the default project, 'lead', as the backend reads it (groupProject): a new Swarm's Lead
+ // conversation has none while its tasks say 'lead' (E2E 2026-11-02: the PM's mine counted none of them).
+ const projectOf = (g: Json) => String(g.projectId ?? 'lead')
+ const home = String(list(state.projects).find(p => p.leadConversationId === lead.id)?.id ?? projectOf(lead))
+ return list(state.conversations)
+ .filter(g => isTask(state, g) && g.archived !== true && projectOf(g) === home
+ && (!g.assignment || isOpen(g)))
+ .map(g => lineOf(state, g))
+}
+
+const firstLine = (value: string, max: number): string => {
+ const line = value.split('\n', 1)[0]!.trim()
+ return line.length > max ? `${line.slice(0, max)}…` : line
+}
+/** How long ago, for a person or a model reading a terminal: minutes and hours, else the UTC time. */
+export function ago(at: number, now: number): string {
+ const ms = now - at
+ if (ms < 60_000) return 'just now'
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)} min ago`
+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)} h ago`
+ return utc(at)
+}
+const utc = (at: number): string => `${new Date(at).toISOString().slice(0, 16).replace('T', ' ')} UTC`
+
+const label = (line: TaskLine): string => line.step && line.taskTitle !== null
+ ? `${line.taskNumber !== null ? `#${line.taskNumber} ` : ''}${line.taskTitle} · ${line.step} (conversation ${line.id})`
+ : `${line.number !== null ? `#${line.number} ` : ''}${line.title} (conversation ${line.id})`
+
+function ownLine(line: TaskLine, changedAt: number | undefined, now: number): string {
+ return `${label(line)} — ${line.status}`
+ + (changedAt !== undefined ? `, updated ${ago(changedAt, now)}` : '')
+ + (line.result ? `; last result: ${firstLine(line.result, RESULT_MAX)}` : '')
+ + (line.pullRequestUrls.length ? `; PR ${line.pullRequestUrls.join(', ')}` : '')
+}
+const otherLine = (line: TaskLine): string =>
+ `${label(line)} — ${line.agentName ? `${line.agentName}, ${line.status}` : 'unassigned'}`
+
+/** Open tasks linked to [taskId] either way (`reviewOf`), not archived; steps are listed as steps instead. */
+function linkedTo(state: Json, group: Json): TaskLine[] {
+ return list(state.conversations)
+ .filter(g => g.id !== group.id && g.archived !== true && !isStep(g) && (g.reviewOf === group.id || g.id === group.reviewOf)
+ && (!g.assignment || isOpen(g)))
+ .map(g => lineOf(state, g))
+}
+
+/** The steps of task [taskId] that are not archived, finished ones included: their verdicts are what the owner acts on. */
+function stepsOf(state: Json, taskId: string): Json[] {
+ return list(state.conversations).filter(g => isStep(g) && g.reviewOf === taskId && g.archived !== true)
+}
+const stepState = (state: Json, step: Json): string => {
+ const line = lineOf(state, step)
+ return `${line.step}${line.agentName ? ` (${line.agentName})` : ''}: ${line.status}`
+}
+/** One line with every step of a task, for `mine`: " steps: Review (Rev1): working · Test (Dev1): done". */
+function stepsLine(state: Json, taskId: string): string[] {
+ const steps = stepsOf(state, taskId)
+ return steps.length ? [` steps: ${steps.map(s => stepState(state, s)).join(' · ')}`] : []
+}
+
+export function mineText(state: Json, groupChangedAt: ReadonlyMap<string, number>, agentId: string, now: number): string {
+ if (isCoordinator(state, agentId)) {
+ const open = projectOpenWork(state, agentId)
+ if (!open.length) return 'Your project has no open task.'
+ return [...open.flatMap(line => [otherLine(line), ...stepsLine(state, line.id)]), `${open.length} open task${open.length === 1 ? '' : 's'}.`].join('\n')
+ }
+ const own = openWorkOf(state, agentId)
+ if (!own.length) return 'No task is assigned to you.'
+ const groups = new Map(list(state.conversations).map(g => [String(g.id), g]))
+ return own.map(line => [ownLine(line, groupChangedAt.get(line.id), now),
+ ...line.step ? [] : [...stepsLine(state, line.id), ...linkedTo(state, groups.get(line.id)!).map(linked => ` linked: ${otherLine(linked)}`)]].join('\n')).join('\n')
+}
+
+function checkLine(state: Json, check: Json): string {
+ const description = String(check.description ?? '')
+ const by = text(check.passedBy)
+ if (by) {
+ const [kind, id] = by.split(':', 2)
+ const name = kind === 'agent' ? agentName(state, id) : text(list(state.people).find(p => p.id === id)?.email) ?? id
+ return `✓ ${description} — by ${name}`
+ }
+ const evidence = text(check.evidence)
+ return evidence ? `✗ ${description} — ${firstLine(evidence, RESULT_MAX)}` : `· ${description}`
+}
+
+function attemptLine(state: Json, attempt: Json, current: boolean): string {
+ const at = typeof attempt.createdAt === 'string' ? Date.parse(attempt.createdAt) : NaN
+ const result = text(attempt.result)
+ return `- ${agentName(state, attempt.agentId) ?? 'unknown'}, ${String(attempt.status)}`
+ + (current ? ' (current)' : Number.isFinite(at) ? `, ${utc(at)}` : '')
+ + (result ? `: ${firstLine(result, RESULT_MAX)}` : '')
+}
+
+/** One task: what it is, its checks, its attempts (the current one, then [attempts] as the backend's attempts read gives
+ * them, newest first; null when that read failed), its linked tasks and how to read its conversation. */
+export function taskText(asked: Json, state: Json, attempts: Json[] | null, groupChangedAt: ReadonlyMap<string, number>, now: number): string {
+ // A step is read as its task, with the step marked (task steps design); a step whose task is not in the read reads alone.
+ const owning = isStep(asked) ? list(state.conversations).find(c => c.id === asked.reviewOf) : undefined
+ const group = owning ?? asked
+ const marked = owning ? String(asked.id) : null
+ const line = lineOf(state, group)
+ const project = list(state.projects).find(p => p.id === group.projectId)
+ const changedAt = groupChangedAt.get(line.id)
+ const brief = text(group.brief) ?? ''
+ const assignment = group.assignment ? object(group.assignment) : null
+ const tried = [...assignment ? [attemptLine(state, assignment, true)] : [],
+ ...(attempts ?? []).map(a => attemptLine(state, a, false))].slice(0, ATTEMPTS_MAX)
+ const checks = list(group.checks)
+ const linked = linkedTo(state, group)
+ const steps = stepsOf(state, String(group.id)).map(step => {
+ const own = lineOf(state, step)
+ const checks = list(step.checks)
+ const passed = checks.filter(c => text(c.passedBy)).length
+ return `${step.id === marked ? '▶' : '-'} ${stepState(state, step)}${checks.length ? `, ${passed} of ${checks.length} checks passed` : ''}`
+ + `${own.result ? `: ${firstLine(own.result, RESULT_MAX)}` : ''} (conversation ${own.id})`
+ })
+ return [
+ label(line),
+ [project ? `Project: ${String(project.name)}` : null, `Status: ${line.status}`, line.agentName ? `Assignee: ${line.agentName}` : null,
+ changedAt !== undefined ? `Updated ${ago(changedAt, now)}` : null].filter(Boolean).join(' · '),
+ ...line.pullRequestUrls.length ? [`PR: ${line.pullRequestUrls.join(', ')}`] : [],
+ '',
+ brief.length > BRIEF_MAX ? `${brief.slice(0, BRIEF_MAX)}… (cut; the whole brief: status)` : brief || 'No brief.',
+ '',
+ 'Checks:',
+ ...checks.length ? checks.map(c => checkLine(state, c)) : ['none'],
+ '',
+ 'Attempts (newest first):',
+ ...tried.length ? tried : ['none'],
+ ...attempts === null ? ['Earlier attempts could not be read.'] : [],
+ ...steps.length ? ['', 'Steps:', ...steps] : [],
+ ...linked.length ? ['', 'Linked:', ...linked.map(l => `- ${otherLine(l)}`)] : [],
+ '',
+ `Read its conversation: messages ${line.id}; one thread: messages ${line.id} --thread ROOT`,
+ ].join('\n')
+}
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index 158aa7379..8312f2919 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -902,3 +902,17 @@ it('parses status --project NAME, alone or with --archived, and refuses it witho
expect(() => parseSuperTabArgs([...prefix, ...argv], where)).toThrow('harness super-tab')
}
})
+
+// Agent context design, section 1: an agent's own work, and one task.
+it('parses mine and task GROUP', () => {
+ expect(parseSuperTabArgs([...prefix, 'mine'], where).payload).toMatchObject({ action: 'mine' })
+ expect(parseSuperTabArgs([...prefix, 'task', 'g12'], where).payload).toMatchObject({ action: 'task', conversationId: 'g12' })
+ for (const argv of [[...prefix, 'task'], [...prefix, 'mine', 'extra'], [...prefix, 'task', 'g12', 'extra']]) expect(() => parseSuperTabArgs(argv, where)).toThrow('harness super-tab')
+})
+it('prints mine and task as text', async () => {
+ const request = vi.fn(async () => ({ ok: true, value: { text: '#12 Fix login (conversation g12) — working' } }))
+ const print = vi.fn()
+ const deps = { where: () => where, pane: undefined, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }), print }
+ expect(await superTabCommand([...prefix, 'mine'], deps as never)).toBe(0)
+ expect(print).toHaveBeenCalledWith('#12 Fix login (conversation g12) — working')
+})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index 274ee59ac..37a41b18e 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -28,7 +28,7 @@ function harnessIn(frames: PaneFrame[], pane: string, machineId: string): boolea
const ELSEWHERE = 'From a harness, Swarm commands go to this computer\'s own Harness only: leave out --machine and --port, or give this computer\'s own.'
-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--project NAME] [--archived [PAGE]] | messages GROUP [--thread ROOT] [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--to AGENT]... [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | instructions [PROJECT] | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--project NAME] [--archived [PAGE]] | messages GROUP [--thread ROOT] [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | mine | task GROUP | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--to AGENT]... [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | instructions [PROJECT] | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'
/** A Buddy's guard refuses a post or a proposal read from stdin (#2358): there its words would skip the secret check. A Buddy
* that followed the stdin form here was refused and tried again (#2360 took it out of a Buddy's help), so a Buddy's usage
* line and JSON hints never offer it. */
@@ -194,6 +194,8 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:
else if (action === 'status' && first === '--archived' && (positional.length === 2 || positional.length === 3 && /^[A-Za-z0-9_-]{1,512}$/.test(second ?? ''))) {
Object.assign(payload, { archived: true, ...(second ? { before: second } : {}) })
}
+ else if (action === 'mine' && positional.length === 1) { /* the agent's own work (agentContext.ts) */ }
+ else if (action === 'task' && identifier(first) && positional.length === 2) payload.conversationId = first
else if (action === 'decisions' && (positional.length === 1 || (positional.length === 2 && first === '--answered'))) payload.state = first ? 'answered' : 'open'
else if (action === 'instructions' && (positional.length === 1 || positional.length === 2 && identifier(first))) {
if (first) payload.projectId = first
@@ -388,6 +390,13 @@ export async function superTabCommand(argv: readonly string[], deps: {
if (request.payload.action === 'screen' && value.ok === true && typeof value.text === 'string') print(value.text)
else print(JSON.stringify(answer.error ? answer : value))
return value.ok === true ? 0 : 1
+ } else if (request.payload.action === 'mine' || request.payload.action === 'task') {
+ // Printed as text for the agent to read (agent context design); every failure, as JSON.
+ const answer = await scoped({ ...request.payload })
+ const value = object(answer.value)
+ if (answer.ok === true && typeof value.text === 'string') { print(value.text); return 0 }
+ print(JSON.stringify(answer))
+ return 1
} else if (request.payload.action === 'instructions') {
// Printed as text for the agent to work by; every failure, as JSON.
const answer = await scoped({ ...request.payload })
diff --git a/cli/src/superTabs/deliveryContext.spec.ts b/cli/src/superTabs/deliveryContext.spec.ts
new file mode 100644
index 000000000..a8c6de27a
--- /dev/null
+++ b/cli/src/superTabs/deliveryContext.spec.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest'
+import { placeLine, threadLine, workLine } from './deliveryContext.js'
+
+const state = {
+ projects: [{ id: 'app', name: 'App', leadConversationId: 'lead-app' }],
+ people: [{ id: 'ken', email: '[email protected]' }],
+ agents: [{ id: 'pm', name: 'PM' }, { id: 'dev1', name: 'Dev1' }, { id: 'buddy', name: 'Ken\'s Buddy', buddyOf: { personId: 'ken' } }],
+ conversations: [
+ { id: 'lead-app', projectId: 'app', title: 'App', leadId: 'pm', agentIds: ['pm'], archived: false, assignment: null },
+ { id: 'g12', projectId: 'app', number: 12, title: 'Fix login', leadId: 'pm', archived: false, assignment: { agentId: 'dev1', status: 'working' } },
+ { id: 'g13', projectId: 'app', number: 13, title: 'Review: Fix login', reviewOf: 'g12', leadId: 'pm', archived: false, assignment: null },
+ { id: 'g14', projectId: 'app', number: 14, title: 'Docs', leadId: 'pm', archived: false, assignment: { agentId: 'dev1', status: 'review' } },
+ { id: 'g15', projectId: 'app', number: 15, title: 'Old', leadId: 'pm', archived: false, assignment: { agentId: 'dev1', status: 'done' } },
+ { id: 'chat', kind: 'buddy', projectId: 'app', title: 'Buddy', leadId: null, agentIds: ['buddy'], archived: false, assignment: null },
+ ],
+}
+
+describe('placeLine', () => {
+ it('names a task by its number and title', () => {
+ expect(placeLine(state, 'g12')).toBe('In task #12 "Fix login" (conversation g12).')
+ })
+ it('names a linked task by its title', () => {
+ expect(placeLine(state, 'g13')).toBe('In "Review: Fix login" (conversation g13).')
+ })
+ it('names the project chat', () => {
+ expect(placeLine(state, 'lead-app')).toBe('In the project chat of App (conversation lead-app).')
+ })
+ it('names a Buddy chat by its person', () => {
+ expect(placeLine(state, 'chat')).toBe('In [email protected]\'s Buddy chat (conversation chat).')
+ })
+ it('gives the id alone when it does not know the conversation', () => {
+ expect(placeLine(state, 'gone')).toBe('In conversation gone.')
+ })
+})
+
+describe('workLine', () => {
+ it('names the agent\'s open tasks and leaves out finished ones', () => {
+ expect(workLine(state, 'dev1')).toBe('You are assigned task #12 "Fix login" (working) and task #14 "Docs" (review).')
+ })
+ it('names three, then how many more', () => {
+ const many = { ...state, conversations: [...state.conversations,
+ ...[20, 21, 22].map(n => ({ id: `g${n}`, projectId: 'app', number: n, title: `T${n}`, leadId: 'pm', archived: false, assignment: { agentId: 'dev1', status: 'working' } }))] }
+ expect(workLine(many, 'dev1')).toBe('You are assigned task #12 "Fix login" (working), task #14 "Docs" (review) and task #20 "T20" (working). And 2 more: mine.')
+ })
+ it('gives the coordinator its project\'s open tasks', () => {
+ expect(workLine(state, 'pm')).toBe('Open tasks in your project: 3; mine lists them.')
+ })
+ it('says nothing for an agent with none', () => {
+ expect(workLine(state, 'nobody')).toBeNull()
+ })
+})
+
+describe('threadLine', () => {
+ it('names the root, its replies and who wrote them, and how to read it', () => {
+ expect(threadLine({ author: 'Ken', createdAt: '2026-11-02T09:15:30.000Z', text: 'Should we ship today?\nDetails…' }, 4, ['Dev1', 'Rev1'],
+ 'harness super-tab --tab t messages g12 --thread m1')).toBe(
+ 'In a thread Ken started (2026-11-02 09:15 UTC): "Should we ship today?" — 4 replies so far, from Dev1, Rev1. '
+ + 'Read the whole thread before acting on it: harness super-tab --tab t messages g12 --thread m1')
+ })
+ it('keeps the root and the command without counts', () => {
+ expect(threadLine({ author: 'Ken', createdAt: '2026-11-02T09:15:30.000Z', text: 'Ship?' }, null, [], 'cmd')).toBe(
+ 'In a thread Ken started (2026-11-02 09:15 UTC): "Ship?". Read the whole thread before acting on it: cmd')
+ })
+ it('cuts a long root line at 200 characters', () => {
+ expect(threadLine({ author: 'Ken', createdAt: '2026-11-02T09:15:30.000Z', text: 'r'.repeat(250) }, 2, ['A'], 'cmd'))
+ .toContain(`"${'r'.repeat(200)}…"`)
+ })
+})
+
+describe('steps', () => {
+ const stepped = { ...state, conversations: [...state.conversations,
+ { id: 'g20', projectId: 'app', number: 20, title: 'Thiết kế "v2"', step: 'Thiết kế "v2"', reviewOf: 'g12', leadId: 'pm', archived: false, assignment: { agentId: 'rev', status: 'working' } }] }
+ it('a step\'s row says its task and step', () => {
+ expect(placeLine(stepped, 'g20')).toBe('In task #12 "Fix login", step "Thiết kế \\"v2\\"" (conversation g20).')
+ })
+ it('names a step the agent holds by its task', () => {
+ expect(workLine(stepped, 'rev')).toBe('You are assigned task #12 "Fix login", step "Thiết kế \\"v2\\"" (working).')
+ })
+})
diff --git a/cli/src/superTabs/deliveryContext.ts b/cli/src/superTabs/deliveryContext.ts
new file mode 100644
index 000000000..ac0a6e57a
--- /dev/null
+++ b/cli/src/superTabs/deliveryContext.ts
@@ -0,0 +1,63 @@
+/**
+ * The short lines a delivery carries before its message, so the agent knows where the message is and what it works on
+ * (design docs/plans/2026-11-02-agent-context-design.md, section 2). Ken, 2026-11-02: a delivery gave only a 24-hex
+ * conversation id, so agents and the PM lost track of which task a message was about and who else had answered in its
+ * thread. Each line is left out when it does not apply or cannot be read; the delivery always goes.
+ */
+import { isCoordinator, isStep, openWorkOf, projectOpenWork } from './agentContext.js'
+
+type Json = Record<string, unknown>
+const object = (value: unknown): Json => value && typeof value === 'object' && !Array.isArray(value) ? value as Json : {}
+const list = (value: unknown): Json[] => Array.isArray(value) ? value.map(object) : []
+const ROOT_MAX = 200
+const WORK_SHOWN = 3
+
+/** Which conversation [groupId] is, in words: a task by number and title, a linked task by title, a project chat, a
+ * Buddy chat by its person; the id alone when the read does not have it. */
+export function placeLine(state: Json, groupId: string): string {
+ const group = list(state.conversations).find(c => c.id === groupId)
+ const at = `(conversation ${groupId}).`
+ if (!group) return `In conversation ${groupId}.`
+ const project = list(state.projects).find(p => p.leadConversationId === groupId)
+ if (project) return `In the project chat of ${String(project.name)} ${at}`
+ if (group.kind === 'buddy' || group.kind === 'swarm-buddy') {
+ const buddy = list(state.agents).find(a => Array.isArray(group.agentIds) && group.agentIds.includes(a.id) && object(a.buddyOf).personId)
+ const person = buddy ? list(state.people).find(p => p.id === object(buddy.buddyOf).personId) : undefined
+ return person ? `In ${String(person.email)}'s Buddy chat ${at}` : `In a Buddy chat ${at}`
+ }
+ const title = JSON.stringify(String(group.title ?? ''))
+ // A step is said as its task and its name (task steps design).
+ const task = isStep(group) ? list(state.conversations).find(c => c.id === group.reviewOf) : undefined
+ if (task) return `In ${taskWords(task)}, step ${JSON.stringify(String(group.step))} ${at}`
+ if (group.reviewOf || typeof group.number !== 'number') return `In ${title} ${at}`
+ return `In ${taskWords(group)} ${at}`
+}
+const taskWords = (task: Json): string =>
+ `task ${typeof task.number === 'number' ? `#${task.number} ` : ''}${JSON.stringify(String(task.title ?? ''))}`
+
+const and = (items: string[]): string => items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`
+
+/** What the receiving agent itself works on: its open tasks, up to three; the coordinator's count of its project's. */
+export function workLine(state: Json, agentId: string): string | null {
+ if (isCoordinator(state, agentId)) {
+ const open = projectOpenWork(state, agentId).length
+ return `Open tasks in your project: ${open}; mine lists them.`
+ }
+ const own = openWorkOf(state, agentId)
+ if (!own.length) return null
+ const named = own.slice(0, WORK_SHOWN).map(t => t.step && t.taskTitle !== null
+ ? `task ${t.taskNumber !== null ? `#${t.taskNumber} ` : ''}${JSON.stringify(t.taskTitle)}, step ${JSON.stringify(t.step)} (${t.status})`
+ : `task ${t.number !== null ? `#${t.number} ` : ''}${JSON.stringify(t.title)} (${t.status})`)
+ return `You are assigned ${and(named)}.${own.length > WORK_SHOWN ? ` And ${own.length - WORK_SHOWN} more: mine.` : ''}`
+}
+
+/** The thread a message is in: who started it and when, its root's first line, how many replies it has so far and from
+ * whom ([replies] null when the read gave no counts), and the command that reads it whole. */
+export function threadLine(root: { author: string; createdAt: string; text: string }, replies: number | null, authors: string[],
+ readCommand: string): string {
+ const at = /^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(root.createdAt) ? ` (${root.createdAt.slice(0, 16).replace('T', ' ')} UTC)` : ''
+ const first = root.text.split('\n', 1)[0]!.trim()
+ const quoted = `"${first.length > ROOT_MAX ? `${first.slice(0, ROOT_MAX)}…` : first}"`
+ const counted = replies === null ? '.' : ` — ${replies} replies so far${authors.length ? `, from ${authors.slice(0, 3).join(', ')}` : ''}.`
+ return `In a thread ${root.author} started${at}: ${quoted}${counted} Read the whole thread before acting on it: ${readCommand}`
+}
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index c27cf6910..66db19a59 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -314,18 +314,19 @@ describe('Super Tab native delivery handoff', () => {
expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
})
// The design of #1726 (section 5.3): the roster names the Leads conversation, so no delivery costs a read of the Swarm.
- it('reads no Swarm to judge a delivery, for an agent that leads nothing or a Lead', async () => {
+ // Agent context design, section 2: a delivery reads the Swarm once, for the lines that say where it is (by what changed
+ // since the last read); judging the delivery itself still reads none, and a delivery tried again reads nothing more.
+ it('reads the Swarm once per delivery, for its context lines, and not again when it is tried again', async () => {
const t = setup(), host = t.open()
+ const swarmReads = () => vi.mocked(t.call).mock.calls.filter(([, path]) => path.includes('asAgentId=')).length
await host.tick()
expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ const first = swarmReads()
+ expect(first).toBe(1)
t.event('rejected', 'team_waiting_busy')
await host.tick()
- expect(vi.mocked(t.call).mock.calls.some(([, path]) => path.includes('asAgentId='))).toBe(false)
- const lead = setup()
- lead.row.lead = true
- await lead.open().tick()
- expect(lead.core.turns.deliver).toHaveBeenCalledTimes(1)
- expect(vi.mocked(lead.call).mock.calls.some(([, path]) => path.includes('asAgentId='))).toBe(false)
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(2)
+ expect(swarmReads()).toBe(first)
})
it('keeps roster members through host failure and restart, releasing only a confirmed removal', async () => {
const t = setup(), first = t.open()
@@ -748,6 +749,78 @@ describe('Super Tab native delivery handoff', () => {
await person.open().tick()
expect(vi.mocked(person.core.turns.deliver).mock.calls[0]![1] as string).not.toContain('--to')
})
+ // Agent context design, section 2 (Ken, 2026-11-02): a delivery named only a 24-hex conversation id, so agents lost which
+ // task a message was about and who else had answered in its thread.
+ describe('where a delivery is', () => {
+ const SWARM = { projects: [{ id: 'app', name: 'App', leadConversationId: 'lead' }], agents: [{ id: 'agent', name: 'Dev1' }],
+ conversations: [{ id: 'lead', projectId: 'app', leadId: 'pm', archived: false, assignment: null },
+ { id: 'g12', projectId: 'app', number: 12, title: 'Fix login', leadId: 'pm', archived: false, assignment: { agentId: 'agent', status: 'working' } }] }
+ const page = (rows: Array<Record<string, unknown>>, threads: Array<Record<string, unknown>> = []) => ({ messages: rows, next: null, threads })
+ const ROOT = { id: 'root', conversationId: 'g12', text: 'Should we ship today?\nDetails', author: { name: 'Ken' }, createdAt: '2026-11-02T09:15:00.000Z', thread: 'root' }
+ function wired(fields: Record<string, unknown>, pages: Record<string, unknown> = {}, swarm: () => unknown = () => SWARM) {
+ const t = setup({ conversationId: 'g12', ...fields })
+ const original = vi.mocked(t.call).getMockImplementation()!
+ const reads: string[] = []
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {
+ const one = /\/messages\?asAgentId=agent&messageId=([a-z0-9]+)$/.exec(path)
+ if (one) { reads.push(one[1]!); return { status: 200, body: { success: true, data: pages[one[1]!] ?? page([]) } } }
+ if (/\/api\/super-tabs\/tab\/(parts|changes)/.test(path)) return { status: 200, body: { success: true, data: swarmReply(path, swarm() as never) } }
+ return original(method, path, body)
+ })
+ return { t, reads }
+ }
+ const delivered = async (t: ReturnType<typeof setup>) => { await t.open().tick(); return vi.mocked(t.core.turns.deliver).mock.calls[0]![1] as string }
+ it('names its task and the agent\'s own work before the message', async () => {
+ const { t } = wired({})
+ const prompt = await delivered(t)
+ expect(prompt).toContain('In task #12 "Fix login" (conversation g12).\nYou are assigned task #12 "Fix login" (working).\n')
+ expect(prompt.indexOf('You are assigned')).toBeLessThan(prompt.indexOf('Message message from'))
+ })
+ it('a delivery whose read fails still goes, without its lines', async () => {
+ const { t } = wired({}, {}, () => { throw new Error('offline') })
+ const prompt = await delivered(t)
+ expect(prompt).toContain('Message message from Collaborator')
+ expect(prompt).not.toContain('You are assigned')
+ })
+ // Final review, finding 3: a delivery never waits on its context; a read that hangs leaves its lines out.
+ it('a delivery whose context read hangs still goes, without its lines', async () => {
+ const { t } = wired({ thread: 'root', replyTo: 'm2' })
+ const original = vi.mocked(t.call).getMockImplementation()!
+ const hangs = (path: string) => /messageId=root$/.test(path) || /\/api\/super-tabs\/tab\/(parts|changes)/.test(path)
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => hangs(path) ? new Promise(() => {}) as never : original(method, path, body))
+ await t.open({ contextWaitMs: 20 }).tick()
+ const prompt = vi.mocked(t.core.turns.deliver).mock.calls[0]![1] as string
+ expect(prompt).toContain('Message message from Collaborator')
+ expect(prompt).not.toContain('You are assigned')
+ expect(prompt).not.toContain('In a thread')
+ })
+ it('a reply to the root needs no extra read', async () => {
+ const { t, reads } = wired({ thread: 'root', replyTo: 'root' }, { root: page([ROOT], [{ id: 'root', replies: 3, authors: [{ name: 'Dev1' }, { name: 'Rev1' }] }]) })
+ const prompt = await delivered(t)
+ expect(prompt).toContain('In a thread Ken started (2026-11-02 09:15 UTC): "Should we ship today?" — 3 replies so far, from Dev1, Rev1. '
+ + 'Read the whole thread before acting on it: ')
+ expect(prompt).toContain("messages 'g12' --thread 'root'")
+ expect(reads).toEqual(['root'])
+ })
+ it('a reply to a later reply reads the root once', async () => {
+ const later = { id: 'm2', conversationId: 'g12', text: 'Not yet', author: { name: 'Dev1' }, createdAt: '2026-11-02T09:20:00.000Z', thread: 'root' }
+ const { t, reads } = wired({ thread: 'root', replyTo: 'm2' }, { m2: page([later]), root: page([ROOT], [{ id: 'root', replies: 2, authors: [{ name: 'Dev1' }] }]) })
+ const prompt = await delivered(t)
+ expect(prompt).toContain('In a thread Ken started')
+ expect(reads.filter(id => id === 'root')).toHaveLength(1)
+ })
+ it('a thread\'s only reply has no thread line', async () => {
+ const { t } = wired({ thread: 'root', replyTo: 'root' }, { root: page([ROOT], [{ id: 'root', replies: 1, authors: [{ name: 'Collaborator' }] }]) })
+ expect(await delivered(t)).not.toContain('In a thread')
+ })
+ it('a work.assign delivered right after it names the new task', async () => {
+ let swarm: Record<string, unknown> = { ...SWARM, conversations: [SWARM.conversations[0]] }
+ const { t } = wired({}, {}, () => swarm)
+ swarm = SWARM
+ expect(await delivered(t)).toContain('You are assigned task #12 "Fix login" (working).')
+ })
+ })
+
it('keeps workflow out of the delivered prompt (it lives in the project instructions)', async () => {
const t = setup({ author: { kind: 'person', id: 'p1', name: '[email protected]' }, text: 'Hi' })
await t.open().tick()
@@ -1649,12 +1722,14 @@ describe('what a Buddy\'s own person sends it in their Buddy chat', () => {
expect(delivered[0]!.text).not.toContain('Artifact links your owner sent')
})
- it('lists nothing for a session that is not a Buddy, and reads nothing for it', async () => {
+ it('lists nothing for a session that is not a Buddy, and reads only for its context lines', async () => {
const { t, host, delivered, reads } = buddyOn()
vi.mocked(t.core.agents.byAgent).mockReturnValue({ agentId: 'harness', swarmSkill: { role: 'dev', key } } as never)
await host.tick()
expect(delivered).toHaveLength(1)
- expect([listed(), reads]).toEqual([null, []])
+ // Its one read is the delivery's context lines (agent context design, section 2), not a Buddy's grant.
+ expect(listed()).toBeNull()
+ expect(reads).toHaveLength(1)
})
// Each message its person sends decides whether it reads beyond its folder (security reviews 1 and 2 of #2310): one read
@@ -3258,11 +3333,35 @@ describe('project instructions from the roster', () => {
return { t, sent, reads, pass, holdNext, file, roleFiles, launched, folder, agents,
save: (summary: string, text: string, at = LONG_AGO) => { const revision = saves.length + 1; saves.push({ revision, hash: `hash-${revision}`, summary, text, at }); return revision },
move: (revision: number) => { doc = { projectId: 'app', revision, hash: `hash-${revision}`, coordinatorName: 'Product Manager' } },
+ /** The project on the built-in template (nothing saved: revision 0) whose text is [text], as a backend build serves it. */
+ template: (hash: string, text: string) => { saves.length = 0; saves.push({ revision: 0, hash, summary: '', text, at: LONG_AGO })
+ doc = { projectId: 'app', revision: 0, hash, coordinatorName: 'Product Manager' } },
setDoc: (next: typeof doc) => { doc = next }, setLag: (revision: number | undefined) => { lag = revision }, setHistory: (served: boolean) => { history = served } }
}
const instructionsRead = (agentId: string) => `/api/super-tabs/tab/projects/app/instructions?asAgentId=${agentId}`
const historyRead = (agentId: string) => `/api/super-tabs/tab/projects/app/instructions/revisions?asAgentId=${agentId}`
+ // 2026-11-02, the rollout of #2495: a project with nothing saved stays at revision 0, so the text read once was kept until
+ // the daemon restarted. The template's hash moves with each backend build that changes it.
+ it('reads a changed template again at revision 0', async () => {
+ const f = docFixture()
+ f.template('template-1', 'Template one.\n')
+ const host = await f.pass()
+ expect(readFileSync(f.file('tester'), 'utf8')).toContain('Template one.')
+ f.template('template-2', 'Template two.\n')
+ await f.pass(host, 120_000)
+ expect(f.reads.filter(path => path === instructionsRead('a-tester'))).toHaveLength(2)
+ expect(readFileSync(f.file('tester'), 'utf8')).toContain('Template two.')
+ })
+
+ it('does not read the template again while its hash stays', async () => {
+ const f = docFixture()
+ f.template('template-1', 'Template one.\n')
+ const host = await f.pass()
+ for (let i = 1; i <= 3; i++) await f.pass(host, i * 120_000)
+ expect(f.reads.filter(path => path === instructionsRead('a-tester'))).toHaveLength(1)
+ })
+
it('installs a Tester\'s instructions from the roster and tells it nothing at first', async () => {
const f = docFixture()
const role = readFileSync(f.roleFiles.tester!, 'utf8')
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 070a97e6a..95dd20bde 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -25,6 +25,7 @@ import { TerminalHost } from './terminal.js'
import { LimitResume } from './limitResume.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
+import { placeLine, threadLine, workLine } from './deliveryContext.js'
import { UPDATE_REQUIRED } from './readContract.js'
import { projectsRoot } from '../lib/projectFolder.js'
import { worktreeFolderName } from '../lib/agentNames.js'
@@ -38,7 +39,7 @@ const readCommand = (entry: Entry, prefix: string, group: string, id: string, bu
`${agentCommandOf(entry, prefix, buddy)} message ${shellQuote(group)} ${shellQuote(id)}`
export { backend, identifier, object, SuperTabHostError } from './wire.js'
import { leadSwitchOf, SWITCH_ADOPT_MS, switchWithin, type LeadSwitch } from './leadSwitch.js'
-import { backend, ENDED_WORK, identifier, object, SuperTabHostError } from './wire.js'
+import { backend, ENDED_WORK, identifier, object, SuperTabHostError, within } from './wire.js'
import { parseSwarmSkill, recordSwarmSkillNotice, refreshSwarmSkill, wireRole, type CustomSwarmRole, type SkillRefresh, type SwarmSkill, type SwarmSkillGrant,
type SwarmSkillMode } from '../lib/swarmSkills.js'
import { recordProjectSkillsNotice, refreshProjectSkills } from '../lib/swarmInstructionsSkill.js'
@@ -144,6 +145,8 @@ export interface SuperTabHostOptions {
attachedFiles?: typeof attachedFiles
/** How long a pass waits on the downloads it starts (DOWNLOAD_WAIT_MS), for a spec. */
downloadWaitMs?: number
+ /** How long a delivery waits on each read for its context lines (CONTEXT_WAIT_MS), for a spec. */
+ contextWaitMs?: number
prepareContribution?: typeof prepareContribution
/** This Mac's Harness Team account preparing its workspace through the relay (contribution.ts), for a spec. */
prepareTeam?: (core: CoreApi, input: { tabId: string; machineId: string }) => Promise<Record<string, unknown>>
@@ -271,6 +274,8 @@ const DELIVERY_RETRY_MS = 1_000
* in the same pass; a larger one downloads on in the background while its delivery is withheld (FilesDownloading), and no
* later pass waits on it at all: once in, it starts a pass of its own. */
const DOWNLOAD_WAIT_MS = 2_000
+/** How long a delivery waits on each read for its context lines: they are pointers, never worth holding a message for. */
+const CONTEXT_WAIT_MS = 3_000
/** A delivery whose files are still downloading. Tried again like any withheld one (at most DELIVERY_RETRY_MAX_MS apart), and
* each try claims it again with the same claim id: that writes the delivery, so the backend never takes the claim for one
* nobody holds (backend deliverySettle.ts CLAIM_QUIET_MS, 10 minutes). Said once, not as a failure. */
@@ -401,11 +406,16 @@ export class SuperTabHost {
/** The files those downloads are fetching, so two deliveries of one file download it once at a time (attachments.ts). */
private readonly inFlight: FilesInFlight = new Map()
private readonly downloadWaitMs: number
+ private readonly contextWaitMs: number
/** This pass's one wait on the downloads it starts (DOWNLOAD_WAIT_MS), shared by all of them; null until one starts. */
private passWait: Promise<null> | null = null
/** Each delivery's quote of the message it replies to ('' when none is shown), read once like its files. A failed read is
* not kept, so the next try reads again. */
private readonly quotes = new Map<string, string>()
+ /** Each delivery's context lines (deliveryContext.ts), read once per delivery and kept while it is tried again. */
+ private readonly contexts = new Map<string, string>()
+ /** The one-message page `repliedTo()` read, for the thread line when the reply answers its thread's root. */
+ private readonly replyPages = new Map<string, Json>()
private readonly active = new Set<string>()
private readonly authorized = new Map<string, number>()
private readonly withheld = new WithheldDeliveries()
@@ -472,7 +482,7 @@ export class SuperTabHost {
/** Per tab and project (instructionsKey), the instructions text last read, its revision, and that revision's summary and
* save time once a history read answered (`failedSince`: when it first failed): read again only when the roster's
* revision moves, and dropped once no roster row names the project. */
- private readonly instructionTexts = new Map<string, { revision: number; text: string
+ private readonly instructionTexts = new Map<string, { revision: number; hash: string | null; text: string
history: { summary: string | null; savedAt: number | null } | null; failedSince?: number }>()
private skillsRunning: Promise<void> | null = null
private missing = new Map<string, number>()
@@ -499,6 +509,7 @@ export class SuperTabHost {
this.observers = options.observers ?? publishObservers
this.attachedFiles = options.attachedFiles ?? attachedFiles
this.downloadWaitMs = options.downloadWaitMs ?? DOWNLOAD_WAIT_MS
+ this.contextWaitMs = options.contextWaitMs ?? CONTEXT_WAIT_MS
this.prepareContribution = options.prepareContribution ?? prepareContribution
this.machineDeps = options.machines ?? {}
this.prepareTeam = options.prepareTeam ?? ((core, input) => prepareTeamContribution(core, input))
@@ -1094,6 +1105,8 @@ export class SuperTabHost {
for (const deliveryId of this.files.keys()) if (!this.journal.entries[deliveryId]) this.files.delete(deliveryId)
for (const deliveryId of [...this.downloads.keys()]) if (!this.journal.entries[deliveryId]) this.dropDownload(deliveryId)
for (const deliveryId of this.quotes.keys()) if (!this.journal.entries[deliveryId]) this.quotes.delete(deliveryId)
+ for (const deliveryId of this.contexts.keys()) if (!this.journal.entries[deliveryId]) this.contexts.delete(deliveryId)
+ for (const deliveryId of this.replyPages.keys()) if (!this.journal.entries[deliveryId]) this.replyPages.delete(deliveryId)
for (const entry of Object.values(this.journal.entries)) {
const id = typedId(entry)
if (!seen.has(entry.deliveryId)) {
@@ -1433,7 +1446,9 @@ export class SuperTabHost {
const key = instructionsKey(target.tabId, doc.projectId, buddy ? target.agent.id : undefined)
const path = `/api/super-tabs/${target.tabId}/projects/${doc.projectId}/instructions`, as = `asAgentId=${target.agent.id}`
let held = this.instructionTexts.get(key)
- if (held?.revision !== doc.revision) {
+ // The hash as well as the revision: a project with nothing saved stays at revision 0 while the template it reads changes
+ // with backend builds (2026-11-02: running agents kept the old routing after #2495 until their daemon restarted).
+ if (held?.revision !== doc.revision || held.hash !== doc.hash) {
const answer = object(await backend(this.core, 'GET', `${path}?${as}`))
// A newer roster's refresh reads its own revision: this one installs and says nothing.
if (!current()) { this.skillChecks.delete(harnessId); return }
@@ -1441,7 +1456,7 @@ export class SuperTabHost {
throw new Error(`The project's instructions read back are not revision ${doc.revision}, which this machine was told to install. Trying again later.`)
}
// A Buddy reads no history: it names who asked for what. Revision 0 is the built-in template: nothing was saved.
- held = { revision: doc.revision, text: answer.text, history: buddy || !doc.revision ? { summary: null, savedAt: null } : null }
+ held = { revision: doc.revision, hash: doc.hash, text: answer.text, history: buddy || !doc.revision ? { summary: null, savedAt: null } : null }
this.instructionTexts.set(key, held)
}
// Task 4's review: a failed history read kept for the revision's life left every notice without its summary and gave each
@@ -1733,6 +1748,11 @@ export class SuperTabHost {
quote = await this.repliedTo(entry, message, command)
if (quote !== undefined) this.quotes.set(deliveryId, quote)
}
+ let context = this.contexts.get(deliveryId)
+ if (context === undefined) {
+ context = await this.contextLines(entry, message, command)
+ this.contexts.set(deliveryId, context)
+ }
if (this.stopped || this.journal.entries[deliveryId] !== entry) return
this.authorized.set(id, this.now() + 2_500)
if (!(await this.leases()) || this.stopped) { this.authorized.delete(id); return }
@@ -1758,7 +1778,7 @@ export class SuperTabHost {
const attached = [files.text, sent?.links.length ? ARTIFACT_LINKS(sent.links) : '', elsewhere.length ? LINKS_ELSEWHERE(elsewhere) : '',
approving ? APPROVALS(approving.judged) : '']
.filter(Boolean).join('\n\n')
- this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, attached, command, quote ?? '', result.buddyNews === true), id)
+ this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, attached, command, quote ?? '', result.buddyNews === true, context), id)
}
/** Takes out of a person's one Buddy's folder each project worktree whose project its person no longer reads, as the Swarm
@@ -1882,6 +1902,7 @@ export class SuperTabHost {
this.log(`reply ${id} for delivery ${entry.deliveryId} unreadable: ${error instanceof Error ? error.message : String(error)}`)
return undefined
}
+ this.replyPages.set(entry.deliveryId, page)
const quoted = (Array.isArray(page.messages) ? page.messages : []).map(object).find(m => m.id === id && m.conversationId === group)
if (!quoted || typeof quoted.text !== 'string') return ''
if (object(quoted.source).kind === 'agent-only' && !(Array.isArray(quoted.recipientIds) && quoted.recipientIds.includes(entry.agentId))) return ''
@@ -1919,7 +1940,56 @@ export class SuperTabHost {
return this.core.agents.byAgent(entry.harnessId)?.swarmSkill?.role === 'buddy'
}
- private prompt(entry: Entry, message: Json, files: string, prefix: string, quote: string, buddyNews = false): string {
+ /** The lines that say where a delivery is (agent context design, section 2): the conversation, the agent's own work, and
+ * the thread it is in. Read fresh for each delivery, as the agent: a 60 s cache could build the delivery announcing a
+ * work.assign from a read taken before it. Anything that cannot be read leaves its line out; the delivery always goes. */
+ private async contextLines(entry: Entry, message: Json, prefix: string): Promise<string> {
+ // A Buddy reads its own person's chat and holds no task, and each read it makes is judged for its grants (security
+ // reviews of #2310): it gets no context lines, so a delivery costs it no read beyond those (design call).
+ if (object(message.source).kind === 'agent-only' || this.isBuddy(entry)) return ''
+ const group = String(message.conversationId)
+ const lines: string[] = []
+ const wait = this.contextWaitMs
+ try {
+ // Bounded: a delivery never waits on its context (final review, finding 3). A read that does not answer in time
+ // leaves its lines out, and the read goes on for the next delivery.
+ const read = await within(this.sources.reads.read(entry.tabId, entry.agentId), wait)
+ if (!read) throw new Error(`no answer in ${wait} ms`)
+ const { state } = read
+ lines.push(placeLine(state, group))
+ const work = workLine(state, entry.agentId)
+ if (work) lines.push(work)
+ } catch (error) {
+ this.log(`context for delivery ${entry.deliveryId} unreadable: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ const root = message.thread
+ if (identifier(root) && root !== message.id) {
+ const thread = await within(this.threadOf(entry, group, root), wait)
+ if (thread && (thread.replies === null || thread.replies > 1)) {
+ lines.push(threadLine(thread.root, thread.replies, thread.authors,
+ `${agentCommandOf(entry, prefix)} messages ${shellQuote(group)} --thread ${shellQuote(root)}`))
+ }
+ }
+ return lines.length ? `${lines.join('\n')}\n\n` : ''
+ }
+
+ /** A thread's root and its summary, from the page `repliedTo()` read when the reply answers the root (Desktop and the
+ * phone reply in a thread with replyTo set to the root), else from one read of the root. Null when the root is gone. */
+ private async threadOf(entry: Entry, group: string, root: string): Promise<{ root: { author: string; createdAt: string; text: string }
+ replies: number | null; authors: string[] } | null> {
+ let page = this.replyPages.get(entry.deliveryId)
+ const has = (p: Json | undefined) => (Array.isArray(p?.messages) ? p!.messages : []).map(object).some(m => m.id === root)
+ if (!has(page)) page = object(await backend(this.core, 'GET', `/api/super-tabs/${entry.tabId}/conversations/${group}/messages?asAgentId=${entry.agentId}&messageId=${root}`))
+ const row = (Array.isArray(page!.messages) ? page!.messages : []).map(object).find(m => m.id === root && m.conversationId === group)
+ if (!row || typeof row.text !== 'string') return null
+ // An older backend's one-message page has no thread summaries: the line keeps the root and the command.
+ const summary = Array.isArray(page!.threads) ? page!.threads.map(object).find(t => t.id === root) : undefined
+ const replies = Array.isArray(page!.threads) ? (summary && typeof summary.replies === 'number' ? summary.replies : 0) : null
+ return { root: { author: String(object(row.author).name ?? 'a collaborator'), createdAt: String(row.createdAt ?? ''), text: row.text },
+ replies, authors: (Array.isArray(summary?.authors) ? summary!.authors : []).map(a => String(object(a).name ?? '')).filter(Boolean) }
+ }
+
+ private prompt(entry: Entry, message: Json, files: string, prefix: string, quote: string, buddyNews = false, context = ''): string {
const buddy = this.isBuddy(entry)
const command = agentCommandOf(entry, prefix, buddy)
const group = message.conversationId as string
@@ -1946,7 +2016,7 @@ export class SuperTabHost {
+ `Reply there: ${command} post ${shellQuote(group)} 'your message' UNIQUE_OPERATION_ID --reply-to ${shellQuote(String(message.id))}${to}\n`
+ `Manage agreed work and delegation: ${command} help.\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 + said
+ + context + native + reply + said
}
/** Says why the core keeps holding this delivery: once in the log per change of reason, and once to the conversation after 30 s. */
diff --git a/cli/src/superTabs/partsStore.ts b/cli/src/superTabs/partsStore.ts
index 20e7e1964..46b25baba 100644
--- a/cli/src/superTabs/partsStore.ts
+++ b/cli/src/superTabs/partsStore.ts
@@ -12,6 +12,8 @@ export interface PartsStore {
epoch: number
lastChangedAt: number | null
githubApp: boolean
+ /** The backend opens a task's steps (task steps design): said by its first load, kept across changes. */
+ steps?: boolean
head: PartEnvelope | null
/** Live parts by kind, in the order the server listed them; new keys go last. */
parts: Map<ListedKind, Map<string, PartEnvelope>>
@@ -27,7 +29,7 @@ const LISTS: Array<[keyof PartsPayload, ListedKind]> = [
export function storeOf(first: FirstLoad): PartsStore {
const parts = new Map<ListedKind, Map<string, PartEnvelope>>(LISTS.map(([field, kind]) =>
[kind, new Map((first[field] as PartEnvelope[]).map(part => [part.key, part]))]))
- return { cursor: first.cursor, epoch: first.epoch, lastChangedAt: first.lastChangedAt, githubApp: first.githubApp === true,
+ return { cursor: first.cursor, epoch: first.epoch, lastChangedAt: first.lastChangedAt, githubApp: first.githubApp === true, steps: first.steps === true,
head: first.head, parts, dormant: new Map(), derived: first.derived }
}
@@ -48,6 +50,6 @@ export function mergeChanges(store: PartsStore, changes: ChangedParts): PartsSto
}
}
const head = changes.head && (!store.head || changes.head.version > store.head.version) ? changes.head : store.head
- return { cursor: changes.cursor, epoch: changes.epoch, lastChangedAt: changes.lastChangedAt, githubApp: store.githubApp,
+ return { cursor: changes.cursor, epoch: changes.epoch, lastChangedAt: changes.lastChangedAt, githubApp: store.githubApp, steps: store.steps,
head, parts, dormant, derived: changes.derived }
}
diff --git a/cli/src/superTabs/readContract.ts b/cli/src/superTabs/readContract.ts
index 413549cee..a9d610866 100644
--- a/cli/src/superTabs/readContract.ts
+++ b/cli/src/superTabs/readContract.ts
@@ -60,7 +60,7 @@ export interface PartsPayload extends ReadMeta {
derived: Derived
}
/** `GET /api/super-tabs/:tabId/parts` (design 4.3). */
-export interface FirstLoad extends PartsPayload { tabId: string; githubApp?: true }
+export interface FirstLoad extends PartsPayload { tabId: string; githubApp?: true; /** The backend opens steps (task steps design). */ steps?: true }
/** `GET /api/super-tabs/:tabId/changes?cursor=` (design 4.4); `{ reload: true }` asks for a first load instead. */
export type ChangedParts = PartsPayload & { reload: false }
export type Changes = ChangedParts | { reload: true }
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 9e0285b3a..edb57e05a 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1513,3 +1513,145 @@ describe('finishing your own work', () => {
expect(posts(t)).toEqual([{ ...status('done'), tokens: opus }, status('done')])
})
})
+
+// Agent context design, section 1 (Ken, 2026-11-02: agents forgot their task; the PM read the whole Swarm for progress).
+describe('mine and task', () => {
+ const ok = (data: unknown) => ({ status: 200, body: { success: true, data } })
+ const withState = (t: ReturnType<typeof setup>, conversations: Array<Record<string, unknown>>, groupRead?: (path: string) => unknown) => {
+ const state = { agents: [{ ...t.agent, name: 'Dev1' }], conversations }
+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => {
+ if (path.includes('/attempts')) return ok([]) as never
+ if (path.startsWith('/api/super-tabs/tab/groups/') && groupRead) return groupRead(path) as never
+ return ok(swarmData(t.agent, path, state)) as never
+ })
+ }
+ it('mine answers its text', async () => {
+ const t = setup()
+ withState(t, [{ id: 'g12', number: 12, title: 'Fix login', archived: false, checks: [], assignment: { agentId: t.agentId, status: 'working', result: null } }])
+ const answer = await t.ask({ action: 'mine', tabId: 'tab', harnessId: 'native' }, owner) as { value: { text: string } }
+ expect(answer.value.text).toMatch(/^#12 Fix login \(conversation g12\) — working/)
+ })
+ it('task reads a dormant group from the group read', async () => {
+ const t = setup()
+ const dormant = { id: 'g9', number: 9, title: 'Old fix', archived: true, dormant: true, checks: [], brief: 'Goal:\nOld.', assignment: { agentId: t.agentId, status: 'done', result: 'Merged' } }
+ withState(t, [], path => path.startsWith('/api/super-tabs/tab/groups/g9?') ? ok({ group: { key: 'g9', version: 1, changedAt: 1, data: dormant } }) : ok({}))
+ const answer = await t.ask({ action: 'task', tabId: 'tab', harnessId: 'native', conversationId: 'g9' }, owner) as { value: { text: string } }
+ expect(answer.value.text.split('\n')[0]).toBe('#9 Old fix (conversation g9)')
+ expect(answer.value.text).toContain('- Dev1, done (current): Merged')
+ })
+ it('task of a group it cannot read answers NOT_FOUND', async () => {
+ const t = setup()
+ withState(t, [], () => ({ status: 404, body: { success: false, error: { code: 'NOT_FOUND', message: 'This conversation is unavailable.' } } }))
+ expect(await t.ask({ action: 'task', tabId: 'tab', harnessId: 'native', conversationId: 'g404' }, owner)).toMatchObject({ error: 'NOT_FOUND' })
+ })
+ it('help names mine and task', async () => {
+ const t = setup()
+ const answer = await t.ask({ action: 'help', tabId: 'tab', harnessId: 'native' }, owner) as { help: Record<string, unknown> }
+ expect(answer.help.mine).toEqual(expect.stringContaining('mine'))
+ expect(answer.help.task).toEqual(expect.stringContaining('task GROUP'))
+ })
+})
+
+describe('status with steps', () => {
+ it('prints a task\'s steps under it, not as rows', async () => {
+ const t = setup()
+ const conversations = [{ id: 'g1835', number: 1835, title: 'Fix login', archived: false, checks: [] },
+ { id: 'g1918', number: 1918, title: 'Review', reviewOf: 'g1835', step: 'Review', archived: false, checks: [] },
+ { id: 'g9', number: 9, title: 'Old review', reviewOf: 'g1835', archived: false, checks: [] }]
+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true,
+ data: swarmData(t.agent, path, { agents: [t.agent], conversations }) } }) as never)
+ const answer = await t.ask({ action: 'status', tabId: 'tab', harnessId: 'native' }, owner) as { value: { state: { conversations: Array<Record<string, unknown>> } } }
+ const rows = answer.value.state.conversations
+ expect(rows.map(c => c.id)).toEqual(['g1835', 'g9'])
+ expect((rows[0]!.steps as Array<Record<string, unknown>>).map(s => s.id)).toEqual(['g1918'])
+ })
+})
+
+// Task steps design: a task's chat shows its steps' rows by time, and a step is opened only on a backend that has steps.
+describe('a task\'s steps in messages and commands', () => {
+ const ok = (data: unknown) => ({ status: 200, body: { success: true, data } })
+ const row = (id: string, conversationId: string, createdAt: string) => ({ id, conversationId, createdAt, text: id, author: { name: 'A' } })
+ const conversations = [{ id: 'g1835', number: 1835, title: 'Fix login', archived: false, checks: [] },
+ { id: 'g1918', number: 1918, title: 'Review', reviewOf: 'g1835', step: 'Thiết kế "v2"', archived: false, checks: [] },
+ { id: 'g1919', number: 1919, title: 'Test', reviewOf: 'g1835', step: 'Test', archived: false, checks: [] }]
+ function wired(t: ReturnType<typeof setup>, options: { steps?: boolean; failing?: string } = {}) {
+ const sent: Array<Record<string, unknown>> = []
+ vi.mocked(t.core.account.backend).mockImplementation(async (method, path, body) => {
+ const read = /\/conversations\/(g\d+)\/messages\?/.exec(path)
+ if (read) {
+ if (read[1] === options.failing) return { status: 403, body: { success: false, error: { code: 'FORBIDDEN', message: 'No' } } } as never
+ const rows = { g1835: [row('t1', 'g1835', '2026-11-02T09:00:00Z'), row('t2', 'g1835', '2026-11-02T09:10:00Z')],
+ g1918: [row('s1', 'g1918', '2026-11-02T09:05:00Z')], g1919: [row('u1', 'g1919', '2026-11-02T09:15:00Z')] }[read[1]!] ?? []
+ return ok({ messages: rows, next: null, threads: [] }) as never
+ }
+ if (method === 'POST' && path.endsWith('/commands')) { sent.push(object(body)); return ok({ revision: 1, result: {} }) as never }
+ const data = swarmData(t.agent, path, { agents: [t.agent], conversations })
+ return ok(options.steps && /\/parts/.test(path) ? { ...object(data), steps: true } : data) as never
+ })
+ return sent
+ }
+ it('messages of a task merges its steps\' rows by time and tags them', async () => {
+ const t = setup(); wired(t, { steps: true })
+ const answer = await t.ask({ action: 'messages', tabId: 'tab', harnessId: 'native', conversationId: 'g1835' }, owner) as { value: { messages: Array<Record<string, unknown>> } }
+ expect(answer.value.messages.map(m => [m.id, m.step ?? null])).toEqual([['t1', null], ['s1', 'Thiết kế "v2"'], ['t2', null], ['u1', 'Test']])
+ })
+ it('an unreadable step leaves the task\'s rows and says which step is missing', async () => {
+ const t = setup(); wired(t, { steps: true, failing: 'g1919' })
+ const answer = await t.ask({ action: 'messages', tabId: 'tab', harnessId: 'native', conversationId: 'g1835' }, owner) as { value: { messages: Array<Record<string, unknown>>; stepsMissing: string[] } }
+ expect(answer.value.messages.map(m => m.id)).toEqual(['t1', 's1', 't2'])
+ expect(answer.value.stepsMissing).toEqual(['Test'])
+ })
+ // Final review, minor 6: an archived task keeps its steps' rows, archived with it.
+ it('messages of an archived task still merges its archived steps', async () => {
+ const t = setup()
+ const archived = conversations.map(c => ({ ...c, archived: true }))
+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => {
+ const read = /\/conversations\/(g\d+)\/messages\?/.exec(path)
+ if (read) return ok({ messages: read[1] === 'g1918' ? [row('s1', 'g1918', '2026-11-02T09:05:00Z')] : [], next: null, threads: [] }) as never
+ return ok(swarmData(t.agent, path, { agents: [t.agent], conversations: archived })) as never
+ })
+ const answer = await t.ask({ action: 'messages', tabId: 'tab', harnessId: 'native', conversationId: 'g1835' }, owner) as { value: { messages: Array<Record<string, unknown>> } }
+ expect(answer.value.messages.map(m => m.id)).toEqual(['s1'])
+ })
+ it('messages of a step reads the step alone', async () => {
+ const t = setup(); wired(t, { steps: true })
+ const answer = await t.ask({ action: 'messages', tabId: 'tab', harnessId: 'native', conversationId: 'g1918' }, owner) as { value: { messages: Array<Record<string, unknown>> } }
+ expect(answer.value.messages.map(m => m.id)).toEqual(['s1'])
+ })
+ it('step is dropped for a backend without steps', async () => {
+ const t = setup(); const sent = wired(t, { steps: false })
+ await t.ask({ action: 'command', tabId: 'tab', harnessId: 'native', operationId: 'op-1',
+ command: { type: 'conversation.create', title: 'Review', reviewOf: 'g1835', step: 'Review', checks: [] } }, owner)
+ expect(object(sent[0]!.command)).toMatchObject({ type: 'conversation.create', reviewOf: 'g1835' })
+ expect(object(sent[0]!.command)).not.toHaveProperty('step')
+ })
+ // Final review, minor 7: the flag is read at the first load, so a backend rolled back since refuses `step`; the command is
+ // sent once more without it, and the step opens as a plain linked task.
+ it('sends it again without step when the backend refuses the field', async () => {
+ const t = setup(); const sent = wired(t, { steps: true })
+ const answer = vi.mocked(t.core.account.backend).getMockImplementation()!
+ vi.mocked(t.core.account.backend).mockImplementation(async (method, path, body) => method === 'POST' && path.endsWith('/commands')
+ && 'step' in object(object(body).command)
+ ? { status: 400, body: { success: false, error: { code: 'VALIDATION_ERROR', message: 'Unrecognized key: "step"' } } } as never
+ : answer(method, path, body))
+ const result = await t.ask({ action: 'command', tabId: 'tab', harnessId: 'native', operationId: 'op-1',
+ command: { type: 'conversation.create', title: 'Review', reviewOf: 'g1835', step: 'Review', checks: [] } }, owner)
+ expect(result).toMatchObject({ ok: true })
+ expect(sent).toHaveLength(1)
+ expect(object(sent[0]!.command)).not.toHaveProperty('step')
+ })
+ it('step is sent to a backend that has steps', async () => {
+ const t = setup(); const sent = wired(t, { steps: true })
+ await t.ask({ action: 'command', tabId: 'tab', harnessId: 'native', operationId: 'op-1',
+ command: { type: 'conversation.create', title: 'Review', reviewOf: 'g1835', step: 'Review', checks: [] } }, owner)
+ expect(object(sent[0]!.command)).toMatchObject({ step: 'Review' })
+ })
+})
+
+it('help shows a step\'s example with neutral words', async () => {
+ const t = setup()
+ const answer = await t.ask({ action: 'help', tabId: 'tab', harnessId: 'native' }, owner) as { help: { commands: Array<Record<string, unknown>> } }
+ const step = answer.help.commands.find(c => c.type === 'conversation.create' && 'step' in c)!
+ expect(step).toMatchObject({ reviewOf: 'GROUP', step: 'STEP_NAME' })
+ expect(JSON.stringify(answer.help.commands)).not.toContain('Review: Outcome')
+})
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index a3853a8e9..5b0316d92 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -10,6 +10,7 @@ import { backend, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHos
import { HostFeed } from './hostFeed.js'
import { SwarmReads, type SwarmRead } from './swarmReads.js'
import { within } from './wire.js'
+import { isCoordinator, isStep, mineText, taskText } from './agentContext.js'
import { machineChoices } from '../lib/newCommand.js'
import { wireRole } from '../lib/swarmSkills.js'
import { START_REQUIREMENTS } from './capacity.js'
@@ -67,6 +68,8 @@ async function finishingWith(core: CoreApi, command: Record<string, unknown>, ha
* is the project's instructions', never this help's. */
const HELP = {
status: 'Read the shared tab roster and work: people, projects, agents, conversations and their tasks. How the project routes work is in its instructions (instructions). The PM\'s status also lists otherProjectsWork: the active work of the Swarm\'s other projects (group, project, title, owned code, status, agent, PR), read only.',
+ mine: 'mine: what you work on, one line per task (number, title, conversation id, status, when it changed, last result, pull requests) with the open tasks linked to it. A project\'s coordinator gets every open task of its project instead.',
+ task: 'task GROUP: one task, active or finished: project, status, assignee, pull requests, brief, checks, attempts newest first, and linked tasks.',
messages: 'messages GROUP: read recent messages in a conversation, thread replies included: each names its thread, the root message it answers there. A post with --reply-to lands in that message\'s thread. messages GROUP --thread ROOT reads one thread, its root and replies; a Buddy\'s thread session also gets there, as context, the main-chat messages it started from.',
message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
instructions: 'instructions [PROJECT]: print your project\'s instructions (its roles, workflow and routing) and the coordinator\'s notes, each with its id. Work by them; ask the coordinator, or a person, to change them.',
@@ -101,7 +104,8 @@ const HELP = {
{ 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'],
review: { focus: 'Optional: what every review of it checks first, such as the most-likely-wrong list (up to 2,000 characters)', reviews: 2 } }, checks: [{ description: 'Observable acceptance evidence', independent: false }] },
- { type: 'conversation.create', title: 'Review: Outcome', reviewOf: 'GROUP', task: { goal: 'A verdict on the linked group\'s revision', changes: 'None: read only', constraints: 'The linked group\'s constraints', owns: ['The linked group\'s owned code, read only'] }, checks: [{ description: 'Verdict with the reviewed revision', independent: false }] },
+ // A step of a task (task steps design): its name is the one the project's instructions give.
+ { type: 'conversation.create', title: 'STEP_NAME', reviewOf: 'GROUP', step: 'STEP_NAME', task: { goal: 'What this step delivers for the task', changes: 'What it changes, or None', constraints: 'The task\'s constraints', owns: ['What it works on'] }, checks: [{ description: 'Its verdict, with evidence', independent: false }] },
{ type: 'conversation.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: 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.cancel', conversationId: 'GROUP', assignmentId: 'current', reason: 'Why the task is cancelled, in one short sentence' },
@@ -128,6 +132,26 @@ const HELP = {
}
const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
+/** [page] of a task with its [steps]' newest rows merged in by time, each tagged `step: <name>`; a step whose read fails is
+ * named in `stepsMissing`, and the task's rows still come back. */
+async function withSteps(page: unknown, steps: Array<Record<string, unknown>>, read: (step: Record<string, unknown>) => Promise<unknown>): Promise<Record<string, unknown>> {
+ const answers = await Promise.all(steps.map(step => read(step).then(answer => ({ step, rows: list(object(answer).messages) }), () => ({ step, rows: null }))))
+ const at = (row: Record<string, unknown>) => String(row.createdAt ?? '')
+ const rows: Array<Record<string, unknown>> = [...list(object(page).messages),
+ ...answers.flatMap(({ step, rows }) => (rows ?? []).map(row => ({ ...row, step: step.step } as Record<string, unknown>)))]
+ rows.sort((a, b) => at(a) === at(b) ? String(a.id).localeCompare(String(b.id)) : at(a) < at(b) ? -1 : 1)
+ const missing = answers.filter(a => !a.rows).map(a => String(a.step.step))
+ return { ...object(page), messages: rows, ...(missing.length ? { stepsMissing: missing } : {}) }
+}
+
+/** One group by id as [identity] reads it, active or dormant (design 4.5); null when it is not there or not this agent's
+ * to read (403 or 404), so the answer never tells which. */
+async function readGroupAsAgent(core: CoreApi, path: string, id: string, identity: string): Promise<Record<string, unknown> | null> {
+ const answer = await backend(core, 'GET', `${path}/groups/${encodeURIComponent(id)}?${identity}`)
+ .catch(error => { if (error instanceof SuperTabHostError && [403, 404].includes(error.status)) return null; throw error })
+ const group = object(object(answer).group).data
+ return group && typeof group === 'object' ? object(group) : null
+}
/** A Swarm read as `GET /api/super-tabs/:id` answered it, `lastChangedAt` in place of `revision` (design 2026-10-26 5.3). */
const answerOf = (read: SwarmRead) => ({ lastChangedAt: read.lastChangedAt, state: read.state, ...(read.githubApp ? { githubApp: true } : {}) })
const OFF_ROSTER = 'This agent is not on this machine\'s Swarm roster right now. That can mean this machine has no access to it, or its billing does not allow it. Check how this machine is shared.'
@@ -138,19 +162,21 @@ const OTHER_WORK_FIELDS = ['conversationId', 'projectName', 'title', 'owns', 'st
/** How old a host form a one-off question about this machine's Swarms may take: the host reads one every second. */
const POOLS_FRESH_MS = 5_000
-/** A project's Lead is its Lead conversation's, as the backend reads it; a Swarm from before projects has one, 'lead'. */
-function isLead(state: Record<string, unknown>, agentId: string): boolean {
- const leads = Array.isArray(state.projects) ? list(state.projects).map(p => p.leadConversationId) : ['lead']
- return list(state.conversations).some(c => leads.includes(c.id) && c.leadId === agentId)
-}
/** Leads see each other's work (spec 2026-10-23): a Lead reads other projects' active work in the backend's fields alone;
* any other agent reads none of it. Nobody reads the Leads conversation, removed on 10-31, even from an older server
* that still sends it. */
function statusView(answer: Record<string, unknown>, agentId: string): Record<string, unknown> {
const { otherProjectsWork, leadsConversationId, ...state } = object(answer.state)
- const conversations = list(state.conversations).filter(c => c.kind !== 'leads' && (leadsConversationId == null || c.id !== leadsConversationId))
- if (isLead(state, agentId)) {
+ const shown = list(state.conversations).filter(c => c.kind !== 'leads' && (leadsConversationId == null || c.id !== leadsConversationId))
+ // A task's steps are printed under it, not as rows of their own (task steps design); one whose task is not here stays a row.
+ const ids = new Set(shown.map(c => c.id))
+ const nested = (c: Record<string, unknown>) => isStep(c) && ids.has(c.reviewOf)
+ const conversations = shown.filter(c => !nested(c)).map(c => {
+ const steps = shown.filter(s => nested(s) && s.reviewOf === c.id)
+ return steps.length ? { ...c, steps } : c
+ })
+ if (isCoordinator(state, agentId)) {
return { ...answer, state: { ...state, conversations,
...(Array.isArray(otherProjectsWork) ? { otherProjectsWork: list(otherProjectsWork).map(work =>
Object.fromEntries(OTHER_WORK_FIELDS.filter(key => key in work).map(key => [key, work[key]]))) } : {}) } }
@@ -601,8 +627,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
if (payload.action === 'routeHistory') {
// The one group by id, active or dormant (design 4.5): a group that left the active set still has its history, and
// a group this agent cannot read answers 403 or 404, before any history is read (review round 1).
- const group = identifier(payload.conversationId) ? object(object(await backend(core, 'GET', `${path}/groups/${encodeURIComponent(String(payload.conversationId))}?${identity}`)
- .catch(error => { if (error instanceof SuperTabHostError && [403, 404].includes(error.status)) return null; throw error })).group).data : null
+ const group = identifier(payload.conversationId) ? await readGroupAsAgent(core, path, String(payload.conversationId), identity) : null
if (!group) return { error: 'NOT_FOUND', detail: 'No such group, or this agent cannot read it.', status: 404 }
const [logged, tried] = await Promise.all([
within(backend(core, 'GET', `${path}/route-decisions?${identity}`)),
@@ -623,6 +648,21 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
const attempts = Array.isArray(tried) ? tried.slice(0, 50).map(object).map(a => ({ id: a.id, agentId: a.agentId, status: a.status, result: typeof a.result === 'string' ? a.result.slice(0, 500) : null, createdAt: a.createdAt ?? null })) : null
return { ok: true, value: { ...(decisions ? { decisions } : { decisionsUnreadable: true }), ...(attempts ? { attempts } : { attemptsUnreadable: true }) } }
}
+ // What this agent works on, and one task (agent context design, section 1). Both read the Swarm read `status` makes;
+ // a task that left the active set (finished and quiet for a day, or archived) is read by id, as routeHistory reads it.
+ if (payload.action === 'mine') {
+ const read = await swarm()
+ return { ok: true, value: { text: mineText(read.state, read.groupChangedAt, agentId, Date.now()) } }
+ }
+ if (payload.action === 'task' && identifier(payload.conversationId)) {
+ const id = String(payload.conversationId)
+ const read = await swarm()
+ const active = list(read.state.conversations).find(c => c.id === id)
+ const group = active ?? await readGroupAsAgent(core, path, id, identity)
+ if (!group) return { error: 'NOT_FOUND', detail: 'No such task, or this agent cannot read it.', status: 404 }
+ const tried = await within(backend(core, 'GET', `${path}/conversations/${encodeURIComponent(id)}/attempts?${identity}`))
+ return { ok: true, value: { text: taskText(group, read.state, Array.isArray(tried) ? list(tried) : null, read.groupChangedAt, Date.now()) } }
+ }
// The jobs running and waiting on a project's GitHub Actions, counts only, for the route's machine-fit plug-in
// (machineFit.ts; backend github/ciLoad.ts). The server reads it through its GitHub App, never this machine's login.
if (payload.action === 'ciLoad' && identifier(payload.projectId)) {
@@ -670,6 +710,17 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
if (payload.thread !== undefined && !identifier(payload.thread)) return { error: 'INVALID_REQUEST' }
const thread = payload.thread !== undefined ? `&thread=${payload.thread}` : ''
const page = await backend(core, 'GET', `${path}/conversations/${encodeURIComponent(String(payload.conversationId))}/messages?${identity}${before}${thread}`)
+ // A task's newest page shows its steps' rows by time, each tagged with its step (task steps design): the step's own
+ // conversation keeps its brief and work rows, and the talk is in the task. Older pages and threads are the task's.
+ if (!paged && !thread) {
+ const read = await swarm().catch(() => null)
+ // An archived task keeps the steps archived with it, and their rows (final review, minor 6).
+ const task = read ? list(read.state.conversations).find(c => c.id === payload.conversationId) : undefined
+ const steps = read ? list(read.state.conversations).filter(c => isStep(c) && c.reviewOf === payload.conversationId
+ && (task?.archived === true || c.archived !== true)) : []
+ if (steps.length) return { ok: true, value: markAnswered(await withSteps(page, steps, step =>
+ backend(core, 'GET', `${path}/conversations/${encodeURIComponent(String(step.id))}/messages?${identity}`)), [], agentId) }
+ }
return { ok: true, value: markAnswered(page, [], agentId) }
}
if (payload.action === 'message' && identifier(payload.conversationId) && identifier(payload.messageId)) {
@@ -687,7 +738,10 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
if (payload.action === 'command' && identifier(payload.operationId) && payload.command && typeof payload.command === 'object' && !Array.isArray(payload.command)) {
const asked = object(payload.command)
// `current` (or no id) names the group's active assignment for the agent (superTabs/assignmentIds.ts).
- const filled = wantsCurrent(asked) ? withCurrentAssignment(asked, (await swarm()).state, agentId) : asked
+ const current = wantsCurrent(asked) ? withCurrentAssignment(asked, (await swarm()).state, agentId) : asked
+ // An older backend refuses an unknown field: there a step opens as a plain linked task (task steps design).
+ const filled = current.type === 'conversation.create' && 'step' in current && !(await swarm()).steps
+ ? Object.fromEntries(Object.entries(current).filter(([key]) => key !== 'step')) : current
const command = await finishingWith(core, await mentionCommand(taskCommand(filled), async () => (await swarm()).state), String(agent.harnessId))
const send = (command: Record<string, unknown>) => backend(core, 'POST', `${path}/commands`,
{ operationId: payload.operationId, command, asAgentId: agentId })
@@ -698,6 +752,13 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
const hint = await swarm().then(read => staleAssignmentHint(command, read.state, agentId), () => '')
throw new SuperTabHostError(error.code, `${error.message}${hint ? ` ${hint}` : ''}`, error.status)
}
+ // A backend rolled back since this machine's first load (which said `steps: true`) refuses the field: the step
+ // opens as a plain linked task (final review, minor 7). Only that refusal: a bad name is refused by name.
+ if ('step' in command && command.type === 'conversation.create' && error instanceof SuperTabHostError && error.status === 400
+ && error.code === 'VALIDATION_ERROR' && /Unrecognized key[^"]*"step"/.test(error.message)) {
+ const { step: _step, ...plain } = command
+ return { ok: true, operationId: payload.operationId, value: await send(plain) }
+ }
// A backend from before cost records refuses the totals; the status itself still goes.
if (command.tokens && error instanceof SuperTabHostError && error.status === 400 && error.code === 'VALIDATION_ERROR' && /"tokens"|'tokens'/.test(error.message)) {
const { tokens: _tokens, ...status } = command
diff --git a/cli/src/superTabs/serviceReads.spec.ts b/cli/src/superTabs/serviceReads.spec.ts
index 8a59abc00..f1ddf0e71 100644
--- a/cli/src/superTabs/serviceReads.spec.ts
+++ b/cli/src/superTabs/serviceReads.spec.ts
@@ -47,8 +47,13 @@ describe('status from parts', () => {
})
describe('what each action reads of the Swarm', () => {
+ // Task steps design: a task's newest page shows its steps' rows, so it reads the Swarm, by what changed, to find them.
+ it('reads the Swarm once for a conversation\'s newest messages, to find its steps', async () => {
+ const s = swarm()
+ expect(await s.ask({ action: 'messages', tabId: T, agentId: FIXTURE.builderId, conversationId: FIXTURE.workGroup }, owner)).not.toHaveProperty('error')
+ expect(s.reads()).toEqual([`/api/super-tabs/${T}/parts?asAgentId=${FIXTURE.builderId}`])
+ })
it.each([
- ['messages', { conversationId: FIXTURE.workGroup }],
['message', { conversationId: FIXTURE.workGroup, messageId: 'f00000000000000000000001' }],
['terminalResult', { terminalRequestId: 'r1' }],
['startStatus', { startId: FIXTURE.startId }],
diff --git a/cli/src/superTabs/swarmReads.spec.ts b/cli/src/superTabs/swarmReads.spec.ts
index 7a191344b..436c56264 100644
--- a/cli/src/superTabs/swarmReads.spec.ts
+++ b/cli/src/superTabs/swarmReads.spec.ts
@@ -27,7 +27,7 @@ describe('the daemon\'s Swarm reads', () => {
it('first loads a Swarm once as the agent, then reads only what changed', async () => {
const { call, reads } = backendOf({ [FIRST]: [ok(readFixture('parts-lead'))], [CHANGES()]: [ok(readFixture('changes-lead'))] })
const first = await reads.read(T, LEAD)
- expect(first).toEqual({ state: readFixture<{ state: Json }>('legacy-tab-lead').state, lastChangedAt: 1793010101002, githubApp: true, teamAccounts: true,
+ expect(first).toEqual({ state: readFixture<{ state: Json }>('legacy-tab-lead').state, lastChangedAt: 1793010101002, githubApp: true, steps: false, teamAccounts: true,
groupChangedAt: new Map([['c00000000000000000000001', 1793010000000], ['c00000000000000000000000', 1793009000000],
['c00000000000000000000002', 1793010101002], ['c00000000000000000000003', 1793009500000]]) })
const next = await reads.read(T, LEAD)
diff --git a/cli/src/superTabs/swarmReads.ts b/cli/src/superTabs/swarmReads.ts
index f46f186c7..c83f3b0d7 100644
--- a/cli/src/superTabs/swarmReads.ts
+++ b/cli/src/superTabs/swarmReads.ts
@@ -13,7 +13,7 @@ type Json = Record<string, unknown>
/** A Swarm as `GET /api/super-tabs/:id` gave it: its state in the old shape, `lastChangedAt` in place of `revision`. */
/** `teamAccounts`: whether Harness Team accounts are used in this Swarm; false only where its server says they are not tried
* yet, so an older server's Swarm reads true. */
-export interface SwarmRead { state: Json; lastChangedAt: number | null; githubApp: boolean; teamAccounts: boolean
+export interface SwarmRead { state: Json; lastChangedAt: number | null; githubApp: boolean; steps?: boolean; teamAccounts: boolean
/** When each active group last changed, from its part: what a Buddy's summary marks as new since its last read. */
groupChangedAt: ReadonlyMap<string, number> }
@@ -65,6 +65,6 @@ export class SwarmReads {
this.held.delete(oldest)
}
const groupChangedAt = new Map([...store.parts.get('group')?.values() ?? []].map(part => [part.key, part.changedAt]))
- return { state: reassemble(store), lastChangedAt: store.lastChangedAt, githubApp: store.githubApp, teamAccounts: store.derived.teamAccounts !== false, groupChangedAt }
+ return { state: reassemble(store), lastChangedAt: store.lastChangedAt, githubApp: store.githubApp, steps: store.steps === true, teamAccounts: store.derived.teamAccounts !== false, groupChangedAt }
}
}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index c04469af7..b0912c388 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -22,6 +22,7 @@ import 'parts.dart';
import 'read_marks.dart';
import 'reading.dart';
import 'linked_tasks.dart';
+import 'task_steps.dart';
/// A messages read started beside a state read, and what it asked for.
typedef _EarlyRead = ({String query, Future<Map<String, dynamic>> page});
@@ -1744,6 +1745,34 @@ class SuperTabController extends ChangeNotifier {
static bool _listed(SuperTabMessage m) =>
m.source['kind'] != 'update-request';
+ /// [id]'s messages with its steps' rows merged in by time (task steps
+ /// design): each step keeps its own conversation, shown inside its task.
+ List<SuperTabMessage> taskMessages(String id) {
+ final state = snapshot;
+ final task = state?.conversation(id);
+ final steps = state == null || task == null
+ ? const <SuperTabConversation>[]
+ : superTabStepsOf(state, task);
+ if (steps.isEmpty) return messages(id);
+ // Merged from the rows held, as they are held: an unchanged chat is the
+ // same list, not sorted again on each of a build's reads of it.
+ final merged = (_merges[id] ??= SuperTabStepsMerge()).of(
+ _messages[id] ?? const [],
+ {for (final step in steps) step.id: _messages[step.id] ?? const []},
+ );
+ return merged.every(_listed)
+ ? merged
+ : List.unmodifiable(merged.where(_listed));
+ }
+
+ final _merges = <String, SuperTabStepsMerge>{};
+
+ /// The name of the step [message] was written in; null for a task's own.
+ String? stepNameOf(SuperTabMessage message) {
+ final group = snapshot?.conversation(message.conversationId);
+ return group != null && superTabIsStep(group) ? group.step : null;
+ }
+
/// [group]'s linked tasks with their checks' results ([superTabLinkedLine]);
/// null without any.
String? linkedLine(SuperTabConversation? group) {
@@ -3623,13 +3652,34 @@ class SuperTabController extends ChangeNotifier {
bool older = false,
bool light = false,
_EarlyRead? early,
- }) => _reading[(id, older)] ??=
- _loadMessages(id, older: older, light: light, early: early).whenComplete(
- () {
+ }) {
+ final read = _reading[(id, older)] ??=
+ _loadMessages(
+ id,
+ older: older,
+ light: light,
+ early: early,
+ ).whenComplete(() {
// A block: whenComplete would wait on the removed future, itself.
_reading.remove((id, older));
- },
- );
+ });
+ // The open task's steps are read with it: its chat shows their rows.
+ if (!older && id == selectedId) _readSteps(id, light: light);
+ return read;
+ }
+
+ void _readSteps(String id, {required bool light}) {
+ final state = snapshot;
+ final task = state?.conversation(id);
+ if (state == null || task == null) return;
+ for (final step in superTabStepsOf(state, task)) {
+ // Read again only when the Swarm says the step moved past the rows held
+ // (final review, minor 8: every poll read every step).
+ final held = _messages[step.id]?.lastOrNull?.sequence;
+ if (held != null && step.lastMessageSequence <= held) continue;
+ unawaited(_readMessages(step.id, light: light));
+ }
+ }
Future<void> _loadMessages(
String id, {
diff --git a/desktop/lib/super_tabs/linked_tasks.dart b/desktop/lib/super_tabs/linked_tasks.dart
index f1164ceae..b8e8075fd 100644
--- a/desktop/lib/super_tabs/linked_tasks.dart
+++ b/desktop/lib/super_tabs/linked_tasks.dart
@@ -26,8 +26,35 @@ String? superTabLinkedLine(
final byNumber = order(a).compareTo(order(b));
return byNumber != 0 ? byNumber : a.id.compareTo(b.id);
});
- return [for (final task in linked) '${task.label}: ${_state(task)}']
- .join(' · ');
+ return [
+ for (final task in linked)
+ superTabIsStep(task)
+ ? '${_stepLabel(snapshot, task)}: ${_state(task)}'
+ : '${task.label}: ${_state(task)}',
+ ].join(' · ');
+}
+
+/// Whether [conversation] is a step of a task (task steps design): shown on
+/// its task's row and inside its task, never as a task of its own.
+bool superTabIsStep(SuperTabConversation conversation) =>
+ conversation.step != null && conversation.reviewOf != null;
+
+/// [groups] as the project's list shows them: without steps, which sit on
+/// their task's row (task steps design).
+List<SuperTabConversation> superTabListedWork(
+ Iterable<SuperTabConversation> groups,
+) => [
+ for (final g in groups)
+ if (!superTabIsStep(g)) g,
+];
+
+/// A step by its own name and its agent: "Copy (Atlas)".
+String _stepLabel(SuperTabSnapshot snapshot, SuperTabConversation step) {
+ final agentId = step.assignment?['agentId'];
+ final name = agentId is String && snapshot.agent(agentId) != null
+ ? snapshot.agentName(agentId)
+ : null;
+ return name == null ? step.step! : '${step.step} ($name)';
}
/// A linked task's state: its work's status while it has no checks; else a
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 75209a035..70897e33c 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -315,6 +315,7 @@ class SuperTabConversation {
),
cards = SuperTabCards.fromJson(row['cards']),
reviewOf = row['reviewOf'] as String?,
+ step = row['step'] as String?,
brief = _text(row, 'brief'),
task = row['task'] is Map
? SuperTabTask.fromJson(superTabMap(row['task']))
@@ -383,6 +384,11 @@ class SuperTabConversation {
/// A review group's reviewed group; null for any other conversation.
final String? reviewOf;
+
+ /// A step of the task [reviewOf] names, by the name its project's
+ /// instructions give it (task steps design); null for a task, and for a
+ /// linked task opened before steps.
+ final String? step;
final int lastMessageSequence;
/// Its newest message in the main stream: a reply only in its thread
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index 165e69a69..1bba09454 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -24,6 +24,7 @@ import 'leaderboard/reader.dart';
import 'local_models.dart';
import 'buddies.dart';
import 'machines.dart';
+import 'linked_tasks.dart';
import 'model.dart';
import 'buddy_rows.dart';
import 'section_heading.dart';
@@ -1254,15 +1255,18 @@ List<SuperTabConversation> superTabOpenWorkgroups(
SuperTabProject project, [
List<SuperTabConversation>? conversations,
]) {
- final groups = (conversations ?? controller.projectConversations(project.id))
- .where(
- (g) =>
- g.id != project.leadConversationId &&
- !g.isBuddyChat &&
- !controller.hiddenByBuddies(g) &&
- !g.closed,
- )
- .toList();
+ final groups =
+ superTabListedWork(
+ conversations ?? controller.projectConversations(project.id),
+ )
+ .where(
+ (g) =>
+ g.id != project.leadConversationId &&
+ !g.isBuddyChat &&
+ !controller.hiddenByBuddies(g) &&
+ !g.closed,
+ )
+ .toList();
// A stable sort keeps the backend's order among unnumbered ones.
mergeSort(
groups,
diff --git a/desktop/lib/super_tabs/task_steps.dart b/desktop/lib/super_tabs/task_steps.dart
new file mode 100644
index 000000000..23f60c552
--- /dev/null
+++ b/desktop/lib/super_tabs/task_steps.dart
@@ -0,0 +1,70 @@
+import 'linked_tasks.dart';
+import 'model.dart';
+
+// Kept byte-identical on Desktop (lib/super_tabs/task_steps.dart) and the
+// phone (lib/swarm/task_steps.dart): mobile/test/swarm/desktop_parity_test.dart.
+
+/// [task]'s steps, by number (task steps design): each keeps its own
+/// conversation, shown inside its task. An open task shows those not archived;
+/// an archived one keeps the steps archived with it, and their rows.
+List<SuperTabConversation> superTabStepsOf(
+ SuperTabSnapshot snapshot,
+ SuperTabConversation task,
+) {
+ final steps = [
+ for (final g in snapshot.conversations)
+ if (superTabIsStep(g) &&
+ g.reviewOf == task.id &&
+ g.projectId == task.projectId &&
+ (task.archived || !g.archived))
+ g,
+ ];
+ int order(SuperTabConversation g) => g.number ?? 1 << 30;
+ steps.sort((a, b) {
+ final byNumber = order(a).compareTo(order(b));
+ return byNumber != 0 ? byNumber : a.id.compareTo(b.id);
+ });
+ return steps;
+}
+
+/// [task]'s rows with its steps' rows ([steps], by step conversation id)
+/// merged in by when they were written, then by id. Each conversation numbers
+/// its own messages, so sequences do not compare across them.
+List<SuperTabMessage> superTabMergeSteps(
+ List<SuperTabMessage> task,
+ Map<String, List<SuperTabMessage>> steps,
+) {
+ final all = [...task, for (final rows in steps.values) ...rows];
+ if (steps.isEmpty) return all;
+ final zero = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
+ all.sort((a, b) {
+ final byTime = (a.createdAt ?? zero).compareTo(b.createdAt ?? zero);
+ return byTime != 0 ? byTime : a.id.compareTo(b.id);
+ });
+ return all;
+}
+
+/// The last merge of a task's chat, kept while its rows are the same lists:
+/// a chat drawn again with nothing new is not sorted again (final review,
+/// minor 8).
+class SuperTabStepsMerge {
+ List<SuperTabMessage>? _task;
+ Map<String, List<SuperTabMessage>> _steps = const {};
+ List<SuperTabMessage> _rows = const [];
+
+ List<SuperTabMessage> of(
+ List<SuperTabMessage> task,
+ Map<String, List<SuperTabMessage>> steps,
+ ) {
+ final same =
+ identical(task, _task) &&
+ steps.length == _steps.length &&
+ steps.entries.every((e) => identical(_steps[e.key], e.value));
+ if (!same) {
+ _task = task;
+ _steps = Map.of(steps);
+ _rows = List.unmodifiable(superTabMergeSteps(task, steps));
+ }
+ return _rows;
+ }
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index ba2226692..dff4a94eb 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -249,7 +249,11 @@ class _SuperTabViewState extends State<SuperTabView>
snapshot!.conversation(project!.leadConversationId)?.leadId ==
message.authorId
? '$name (${snapshot.roleOf(message.authorId)?.badge ?? 'PM'}) → you'
- : name;
+ : switch (c.stepNameOf(message)) {
+ // A step's row in its task's chat names its step (task steps design).
+ final String step => '$name · $step',
+ null => name,
+ };
}
@override
@@ -385,7 +389,7 @@ class _SuperTabViewState extends State<SuperTabView>
}
_selected = id;
setState(() {});
- final mark = c.readMark(id), shown = _shownMessages(id);
+ final mark = c.readMark(id), shown = _ownShown(id);
if (c.awaitsNewest(id)) {
// Held from an earlier visit: the line is placed, the end followed and
// anything marked read once the newest messages have landed.
@@ -1948,7 +1952,7 @@ class _SuperTabViewState extends State<SuperTabView>
/// The messages [id]'s list shows, in order.
/// A thread reply shows in its thread, and here only when also sent.
List<SuperTabMessage> _shownMessages(String id) {
- final messages = c.messages(id);
+ final messages = c.taskMessages(id);
final answered = answeredPromptAlerts(
messages,
(agentId) => c.snapshot?.agent(agentId),
@@ -1958,6 +1962,13 @@ class _SuperTabViewState extends State<SuperTabView>
.toList();
}
+ /// [id]'s own rows as its list shows them: without its steps' rows, which
+ /// are numbered in their own conversations (task steps design).
+ List<SuperTabMessage> _ownShown(String id) => [
+ for (final m in _shownMessages(id))
+ if (m.conversationId == id) m,
+ ];
+
/// A message waiting for an agent is never announced; notices older
/// backends stored stay hidden, in the list and as a reply's quote.
static bool _shown(SuperTabMessage m) => m.source['kind'] != 'delivery-hold';
@@ -1965,9 +1976,13 @@ class _SuperTabViewState extends State<SuperTabView>
/// The row of [id]'s list that shows [messageId]: its own, or the notice
/// that folds it in. Null while the message is not loaded.
String? _rowShowing(String id, String messageId) {
- final shown = _shownMessages(id);
- final message = shown.where((m) => m.id == messageId).firstOrNull;
+ final message = _shownMessages(id)
+ .where((m) => m.id == messageId)
+ .firstOrNull;
if (message == null) return null;
+ // A step's row is a row of its own: no notice of the task folds it in.
+ if (message.conversationId != id) return message.id;
+ final shown = _ownShown(id);
return superTabTranscriptEntries(shown)
.lastWhere(
(e) => superTabMessageOrder(e.message, message) <= 0,
@@ -2943,7 +2958,7 @@ class _SuperTabViewState extends State<SuperTabView>
void _moveSplitToView(String id, SuperTabChatScroll scroll) {
final split = _split[id];
if (split == null) return;
- final messages = _shownMessages(id);
+ final messages = _ownShown(id);
final at = messages.indexWhere((m) => superTabMessageOrder(m, split) >= 0);
final top = _rowAtTop();
if (at < 0 || messages.length - at <= _rowsBelowSplit || top == null) {
@@ -3127,6 +3142,14 @@ class _SuperTabViewState extends State<SuperTabView>
.toList();
final pendingById = {for (final sent in outgoing) sent.operationId: sent};
final messages = [...actualMessages, ...outgoing.map(_outgoingMessage)];
+ // The task's own rows, for what is placed by sequence (the split, its
+ // grouping, the count of new rows, the read mark): each conversation
+ // numbers its own messages, so its steps' rows have no place in it.
+ final ownMessages = [
+ for (final m in actualMessages)
+ if (m.conversationId == c.selectedId) m,
+ ];
+ final ownWithOutgoing = [...ownMessages, ...outgoing.map(_outgoingMessage)];
final entries = superTabTranscriptEntries(messages);
final byId = {for (final message in messages) message.id: message};
final rowIndex = {
@@ -3137,12 +3160,12 @@ class _SuperTabViewState extends State<SuperTabView>
int? rowOf(Key key) => key is ValueKey<String> ? rowIndex[key.value] : null;
final split = _splitAt(
c.selectedId,
- superTabTranscriptEntries(actualMessages),
+ superTabTranscriptEntries(ownMessages),
);
// Rows on their way group by the same rule, so a quick line keeps the
// shape it will have once confirmed; one Not sent keeps its name and
// actions.
- final grouped = _joined(messages, _split[c.selectedId])
+ final grouped = _joined(ownWithOutgoing, _split[c.selectedId])
..removeWhere(
(id) => switch (pendingById[id]?.state) {
SuperTabOutgoingState.refused ||
@@ -3230,7 +3253,9 @@ class _SuperTabViewState extends State<SuperTabView>
final newAfter = _newAfter[c.selectedId];
final newCount = newAfter == null
? 0
- : messages.where((message) => message.sequence > newAfter).length;
+ : ownWithOutgoing
+ .where((message) => message.sequence > newAfter)
+ .length;
// More came than were read: the count is a floor.
final moreNew = c.hasNewer(c.selectedId);
// Scrolled away from the newest message, or newer pages wait unread.
@@ -3373,7 +3398,7 @@ class _SuperTabViewState extends State<SuperTabView>
if (atEnd) {
// A row still sending has no place in the transcript.
final sequence =
- actualMessages.lastOrNull?.sequence ?? 0;
+ ownMessages.lastOrNull?.sequence ?? 0;
WidgetsBinding.instance.addPostFrameCallback((
_,
) {
diff --git a/desktop/test/super_tab_review_test.dart b/desktop/test/super_tab_review_test.dart
index a4d92cbbb..af32902d6 100644
--- a/desktop/test/super_tab_review_test.dart
+++ b/desktop/test/super_tab_review_test.dart
@@ -254,4 +254,206 @@ void main() {
await tester.pumpAndSettle();
expect(find.text('This task has no description yet.'), findsOneWidget);
});
+
+ // Task steps design (Ken, 2026-11-02: one pull request showed as three tasks). A step sits on its task's row, by its own
+ // name and agent; a linked task from before steps reads as before.
+ test("a task's steps line names each step and its agent", () {
+ final server = groupServer(
+ linked: [
+ {
+ ...conversationFixture('copy', 'Copy'),
+ 'number': 30,
+ 'reviewOf': 'offline',
+ 'step': 'Copy',
+ 'assignment': {'id': 'w1', 'agentId': 'builder', 'status': 'done'},
+ },
+ {
+ ...conversationFixture('design', 'Thiết kế "v2"'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Thiết kế "v2"',
+ 'assignment': {
+ 'id': 'w2',
+ 'agentId': 'reviewer',
+ 'status': 'working',
+ },
+ },
+ {
+ ...conversationFixture('old', 'Review PR 12'),
+ 'number': 20,
+ 'reviewOf': 'offline',
+ },
+ ],
+ );
+ final snapshot = SuperTabSnapshot.fromJson(server.state);
+ expect(snapshot.conversation('copy')!.step, 'Copy');
+ expect(superTabIsStep(snapshot.conversation('copy')!), isTrue);
+ expect(superTabIsStep(snapshot.conversation('old')!), isFalse);
+ expect(
+ superTabLinkedLine(snapshot, snapshot.conversation('offline')!),
+ '#20 Review PR 12: not started · Copy (Atlas): done · '
+ 'Thiết kế "v2" (Nova): working',
+ );
+ });
+
+ test('the sidebar lists no step as a task of its own', () {
+ final server = groupServer(
+ linked: [
+ {
+ ...conversationFixture('copy', 'Copy'),
+ 'number': 30,
+ 'reviewOf': 'offline',
+ 'step': 'Copy',
+ },
+ {
+ ...conversationFixture('old', 'Review PR 12'),
+ 'number': 20,
+ 'reviewOf': 'offline',
+ },
+ ],
+ );
+ final snapshot = SuperTabSnapshot.fromJson(server.state);
+ final listed = superTabListedWork(snapshot.conversations).map((g) => g.id);
+ expect(listed, contains('old'));
+ expect(listed, isNot(contains('copy')));
+ });
+
+ // Task steps design: a task's chat shows its steps' rows by time, each
+ // with its step's name beside the author.
+ testWidgets("a task's chat shows its steps' rows with the step's name", (
+ tester,
+ ) async {
+ final server = groupServer(
+ linked: [
+ {
+ ...conversationFixture('design', 'Design'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Design',
+ 'agentIds': ['reviewer'],
+ },
+ ],
+ messages: [('builder', 'Draft is up')],
+ );
+ server.append('Two findings on the draft', conversationId: 'design');
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'reviewer',
+ 'name': 'Nova',
+ };
+ await showView(tester, server);
+ expect(find.textContaining('Two findings on the draft'), findsOneWidget);
+ expect(find.textContaining('Nova · Design'), findsOneWidget);
+ });
+
+ // Final review, finding 4: each conversation numbers its own messages, so a
+ // step's row last in the task's chat must not move the task's read mark
+ // (markRead keeps it within the task's own loaded rows).
+ testWidgets("a step's row last in the chat leaves the task's read mark on "
+ "the task's own newest row", (tester) async {
+ final server = groupServer(
+ linked: [
+ {
+ ...conversationFixture('design', 'Design'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Design',
+ 'agentIds': ['reviewer'],
+ },
+ ],
+ messages: [for (var i = 0; i < 40; i++) ('builder', 'Line $i')],
+ );
+ final taskLast = server.messages.last['sequence'] as int;
+ server.append('Step row', conversationId: 'design');
+ server.messages.last
+ ..['sequence'] = taskLast + 5
+ ..['createdAt'] = '2026-10-18T00:05:00Z';
+ await showView(tester, server);
+ await tester.pumpAndSettle();
+ // Read back, then down to the end: reaching the end marks the chat read.
+ final list = find.byType(Scrollable).first;
+ await tester.drag(list, const Offset(0, 600));
+ await tester.pumpAndSettle();
+ await tester.drag(list, const Offset(0, -3000));
+ await tester.pumpAndSettle();
+ final marks = server.readMarkPosts.where(
+ (m) => m['conversationId'] == 'offline',
+ );
+ expect(marks, isNotEmpty);
+ expect(marks.last['sequence'], taskLast);
+ });
+
+ // Final review, minor 8: the open task's reads read each step again only
+ // when the Swarm says it moved past the rows held.
+ test("a task's reads skip a step that has nothing new", () async {
+ final server = groupServer(
+ linked: [
+ {
+ ...conversationFixture('design', 'Design'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Design',
+ },
+ ],
+ );
+ server.append('Step row', conversationId: 'design');
+ final paths = <String>[];
+ server.onRead = paths.add;
+ final controller = server.controller();
+ addTearDown(controller.dispose);
+ await controller.refresh();
+ controller.select('offline');
+ await controller.loadMessages('offline');
+ await Future<void>.delayed(Duration.zero);
+ int stepReads() =>
+ paths.where((p) => p.contains('/conversations/design/messages')).length;
+ final first = stepReads();
+ expect(first, 1);
+ await controller.loadMessages('offline');
+ await Future<void>.delayed(Duration.zero);
+ expect(stepReads(), first);
+ server.append('Another step row', conversationId: 'design');
+ await controller.refresh();
+ await controller.loadMessages('offline');
+ await Future<void>.delayed(Duration.zero);
+ expect(stepReads(), first + 1);
+ });
+
+ // Final review, finding 4: the New messages line is placed by the task's
+ // own sequences; a step's row, numbered in its own conversation, is not
+ // where it goes.
+ testWidgets("a task's New messages line ignores its steps' sequences", (
+ tester,
+ ) async {
+ final server = groupServer(
+ linked: [
+ {
+ ...conversationFixture('design', 'Design'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Design',
+ },
+ ],
+ messages: [for (var i = 1; i <= 6; i++) ('builder', 'Line $i')],
+ );
+ final read =
+ (server.messages.where((m) => m['text'] == 'Line 4').single['sequence']
+ as int);
+ server.markReadElsewhere('offline', read);
+ server.append('Early step row', conversationId: 'design');
+ server.messages.last
+ ..['sequence'] = 999
+ ..['createdAt'] = '2026-10-17T23:00:00Z';
+ await showView(tester, server);
+ const line = ValueKey('super-new-messages-line');
+ expect(find.byKey(line), findsOneWidget);
+ expect(
+ tester.getTopLeft(find.byKey(line)).dy,
+ greaterThan(tester.getTopLeft(find.textContaining('Line 4')).dy),
+ );
+ expect(
+ tester.getTopLeft(find.byKey(line)).dy,
+ lessThan(tester.getTopLeft(find.textContaining('Line 5')).dy),
+ );
+ });
}
diff --git a/desktop/test/super_tab_task_steps_test.dart b/desktop/test/super_tab_task_steps_test.dart
new file mode 100644
index 000000000..45276203c
--- /dev/null
+++ b/desktop/test/super_tab_task_steps_test.dart
@@ -0,0 +1,151 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/task_steps.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Task steps design: a task's chat shows its steps' rows by time.
+void main() {
+ SuperTabMessage row(
+ String id,
+ String conversationId,
+ String at,
+ int sequence,
+ ) => SuperTabMessage.fromJson({
+ 'id': id,
+ 'conversationId': conversationId,
+ 'sequence': sequence,
+ 'text': id,
+ 'createdAt': at,
+ 'author': {'kind': 'agent', 'id': 'a', 'name': 'A'},
+ });
+
+ test("steps' rows merge into the task's by time", () {
+ final merged = superTabMergeSteps(
+ [
+ row('t1', 'task', '2026-11-02T09:00:00Z', 1),
+ row('t2', 'task', '2026-11-02T09:10:00Z', 2),
+ ],
+ {
+ 'review': [row('s1', 'review', '2026-11-02T09:05:00Z', 1)],
+ 'test': [row('u1', 'test', '2026-11-02T09:15:00Z', 1)],
+ },
+ );
+ expect(merged.map((m) => m.id), ['t1', 's1', 't2', 'u1']);
+ });
+
+ test("a task without steps keeps its rows as they were", () {
+ final rows = [
+ row('t2', 'task', '2026-11-02T09:10:00Z', 2),
+ row('t1', 'task', '2026-11-02T09:00:00Z', 1),
+ ];
+ expect(superTabMergeSteps(rows, const {}).map((m) => m.id), ['t2', 't1']);
+ });
+
+ test("a task's steps, by number, without archived ones or other tasks'", () {
+ final server = ConversationServer();
+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ {
+ ...conversationFixture('s2', 'Test'),
+ 'number': 32,
+ 'reviewOf': 'offline',
+ 'step': 'Test',
+ },
+ {
+ ...conversationFixture('s1', 'Review'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Review',
+ },
+ {
+ ...conversationFixture('s3', 'Gone'),
+ 'number': 33,
+ 'reviewOf': 'offline',
+ 'step': 'Gone',
+ 'archived': true,
+ },
+ {
+ ...conversationFixture('old', 'Review PR'),
+ 'number': 20,
+ 'reviewOf': 'offline',
+ },
+ ]);
+ final snapshot = SuperTabSnapshot.fromJson(server.state);
+ expect(
+ superTabStepsOf(
+ snapshot,
+ snapshot.conversation('offline')!,
+ ).map((g) => g.id),
+ ['s1', 's2'],
+ );
+ });
+
+ // Final review, minor 6: an archived task's chat kept none of its finished
+ // steps' rows, as they archive with it.
+ test("an archived task keeps its archived steps", () {
+ final server = ConversationServer();
+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ {
+ ...conversationFixture('s1', 'Review'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Review',
+ 'archived': true,
+ },
+ ]);
+ (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'offline')['archived'] =
+ true;
+ final snapshot = SuperTabSnapshot.fromJson(server.state);
+ expect(
+ superTabStepsOf(
+ snapshot,
+ snapshot.conversation('offline')!,
+ ).map((g) => g.id),
+ ['s1'],
+ );
+ });
+
+ // Final review, minor 8: a chat built again with nothing new is not sorted
+ // again.
+ test('a merge of unchanged rows is the same list', () {
+ final task = [row('t1', 'task', '2026-11-02T09:00:00Z', 1)];
+ final step = [row('s1', 'review', '2026-11-02T09:05:00Z', 1)];
+ final merge = SuperTabStepsMerge();
+ final first = merge.of(task, {'review': step});
+ expect(identical(merge.of(task, {'review': step}), first), isTrue);
+ final more = [...step, row('s2', 'review', '2026-11-02T09:06:00Z', 2)];
+ expect(merge.of(task, {'review': more}).map((m) => m.id), [
+ 't1',
+ 's1',
+ 's2',
+ ]);
+ });
+
+ test(
+ "the controller's merged chat is the same list while nothing changed",
+ () async {
+ final server = ConversationServer();
+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[
+ {
+ ...conversationFixture('s1', 'Review'),
+ 'number': 31,
+ 'reviewOf': 'offline',
+ 'step': 'Review',
+ },
+ ]);
+ server.append('Task row', conversationId: 'offline');
+ server.append('Step row', conversationId: 's1');
+ final controller = server.controller();
+ addTearDown(controller.dispose);
+ await controller.refresh();
+ controller.select('offline');
+ await controller.loadMessages('offline');
+ await controller.loadMessages('s1');
+ final first = controller.taskMessages('offline');
+ expect(first.map((m) => m.text), ['Task row', 'Step row']);
+ expect(identical(controller.taskMessages('offline'), first), isTrue);
+ },
+ );
+}
diff --git a/docs/plans/2026-11-02-agent-context-and-task-steps-plan.md b/docs/plans/2026-11-02-agent-context-and-task-steps-plan.md
new file mode 100644
index 000000000..ef26f5a78
--- /dev/null
+++ b/docs/plans/2026-11-02-agent-context-and-task-steps-plan.md
@@ -0,0 +1,420 @@
+# Agent context and task steps Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Agents know their work and their conversations (`mine`, `task`, delivery lines), and one request is one task
+whose review, test or any other work runs as steps inside it.
+
+**Architecture:** Five phases, each shippable on its own: (A) the template and the revision-0 instructions refresh,
+(B) CLI tools and delivery lines, (C) backend steps (a `step` field on a linked group; archive, sleep, notices and job
+kind follow it), (D) CLI views of steps, (E) Desktop and phone. A step stays a linked conversation (`reviewOf`) with its
+own number and rows; readers show it inside its task and merge its rows into the task's chat.
+
+**Tech Stack:** backend TypeScript (Fastify, Prisma on MongoDB, zod, vitest); CLI daemon TypeScript (vitest); Flutter
+(Desktop `desktop/`, phone `mobile/`).
+
+**Spec:** `docs/plans/2026-11-02-agent-context-design.md` and `docs/plans/2026-11-02-task-steps-design.md`. Read both.
+
+## Global Constraints
+
+- No code, field, notice or copy names a pull request, review, test, Engineer or Reviewer as a kind of step; a step's
+ name is free text (1-40 characters, any language) the instructions give. Template text (phase A) is the exception.
+- The server decides no workflow: no fixed step names, no order, no automatic step.
+- Every read is as the agent (`asAgentId`); a delivery never waits on a read that fails: its line is left out.
+- "Open work" is `activeWork` (`backend/src/superTabs/model.ts`); finished is `done`, `stopped`, `cancelled`, `lost`.
+- Do not edit `cli/src/lib/e2ee/core.ts`. Do not bulk `dart format lib` or `test`; format only files you touched.
+- Backend tests: `cd backend && npx prisma generate` once, then
+ `NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= npx vitest run <files>`.
+- CLI tests: `cd cli && npx vitest run <files>`; `npm run typecheck` before each commit.
+- Comments say why, in plain sentences, naming the incident or spec (cli/AGENTS.md rule 7).
+- Docs and code comments in English.
+- Linked groups opened before steps (no `step` field) keep every behavior they have today.
+- Known red on main, not ours: `cli/src/superTabs/buddyHome.spec.ts` on macOS/Node 23.
+
+## Review Focus
+
+1. A step whose task is archived by hand while the step is `working`: the step must be cancelled with the task's
+ reason in the same write, never left active in an archived task (Task 8 test `archiving a task by hand cancels its working step`).
+2. A reused agent whose old finished task still names it: `mine` and the "your work" line must not list that task
+ (Task 3 test `mine leaves out a reused agent's finished task`).
+3. A step name with quotes, emoji or Vietnamese diacritics reaching deliveries and shell commands: lines must keep it
+ intact and shell-quote it (Task 12 test `a step name with quotes and diacritics is shown and quoted`).
+4. A task with a step whose message read fails (403, network): `messages TASK` still returns the task's rows and names
+ the missing step (Task 12 test `an unreadable step leaves the task's rows and says which step is missing`).
+5. An old daemon sending `conversation.create` with `step` to an old backend: the CLI drops `step` when the read has no
+ `steps: true`, so the command succeeds as a linked task (Task 12 test `step is dropped for a backend without steps`).
+
+---
+
+## Phase A. Template and the revision-0 refresh
+
+### Task 1: Template Workflow
+
+**Files:**
+- Modify: `backend/src/superTabs/instructionsTemplate.ts` (`TEMPLATE_WORKFLOW`, lines 44-56)
+- Test: `backend/src/superTabs/instructions.test.ts`
+
+**Interfaces:**
+- Produces: `TEMPLATE_WORKFLOW` with eleven numbered lines: the seven of the task-steps spec Part 1, then the four of
+ the agent-context spec section 3, as lines 8-11.
+
+- [ ] **Step 1: Write the failing test** `the template workflow has one task per request, steps, and the context tools`:
+
+```ts
+expect(TEMPLATE_WORKFLOW).toContain('1. One request is one task.')
+expect(TEMPLATE_WORKFLOW).toContain('The PM opens no task to hold, batch, triage or list work')
+expect(TEMPLATE_WORKFLOW).toContain('adds a review step to its task')
+expect(TEMPLATE_WORKFLOW).toContain('it adds no new step for a second round')
+expect(TEMPLATE_WORKFLOW).toContain('run `mine`')
+expect(TEMPLATE_WORKFLOW).toContain('read `task GROUP`')
+expect(TEMPLATE_WORKFLOW).toContain('read the thread before acting on it')
+expect(TEMPLATE_WORKFLOW).toContain('The PM reads `mine` for progress, not `status`.')
+expect(TEMPLATE_WORKFLOW.split('\n').filter(l => /^\d+\. /.test(l))).toHaveLength(11)
+```
+
+- [ ] **Step 2: Run it and see it fail.** `npx vitest run src/superTabs/instructions.test.ts` → FAIL.
+- [ ] **Step 3: Replace `TEMPLATE_WORKFLOW`** with the spec's seven lines verbatim (task-steps spec, Part 1 code
+ block), then lines 8-11, wrapped at 120 columns like the rest of the file:
+ `8. Before acting after a pause, or when unsure what you are working on, run \`mine\`.`
+ `9. Before saying your work is done, read \`task GROUP\` and check that every check has passed.`
+ `10. In a thread others have written in, read the thread before acting on it, unless the delivery already says enough.`
+ `11. The PM reads \`mine\` for progress, not \`status\`.`
+- [ ] **Step 4: Run the instructions, migration and catalog tests.**
+ `npx vitest run src/superTabs/instructions.test.ts src/superTabs/migration src/superTabs/routingPolicy.test.ts` → PASS.
+ Update any snapshot or exact-text expectation of the old workflow to the new text; no other change.
+- [ ] **Step 5: Commit** `Template: one request is one task, its review and test are steps; agents read mine and task`.
+
+### Task 2: Running daemons pick up a changed template
+
+**Files:**
+- Modify: `backend/src/superTabs/read/hostRows.ts:87`, `backend/src/superTabs/store.ts:2072`
+- Modify: `cli/src/superTabs/host.ts` (`instructionTexts` type at 475, `refreshInstructions` at ~1431)
+- Test: `backend/src/superTabs/read/views.test.ts` (or the host rows test beside it), `cli/src/superTabs/host.spec.ts`
+
+**Interfaces:**
+- Consumes: `FIRST_INSTRUCTIONS.instructionsHash` (`backend/src/superTabs/instructions.ts:28`), the hash of
+ `INSTRUCTIONS_TEMPLATE`.
+- Produces: host rows and `GET …/instructions` give `hash: FIRST_INSTRUCTIONS.instructionsHash` at revision 0 (never
+ null). The CLI's held text is `{ revision: number; hash: string | null; text: string; history: …; failedSince?: number }`.
+
+- [ ] **Step 1: Backend failing test** `a project with no saved instructions names the template's hash`: a host row for
+ an agent of a project with `instructionsRevision` absent has `instructions.revision === 0` and
+ `instructions.hash === FIRST_INSTRUCTIONS.instructionsHash`; the instructions read answers the same hash with
+ `template: true`.
+- [ ] **Step 2: Run it, see it fail; implement** `hash: home.instructionsHash ?? (revision 0 ? FIRST_INSTRUCTIONS.instructionsHash : null)`
+ in `hostRows.ts`, and `hash: stored?.hash ?? FIRST_INSTRUCTIONS.instructionsHash` in `store.ts:2072`. Run → PASS.
+- [ ] **Step 3: CLI failing tests** in `host.spec.ts`:
+ - `a template change at revision 0 is read again`: roster 1 gives `{revision: 0, hash: 'a'}`, roster 2 `{revision: 0, hash: 'b'}`;
+ the instructions GET is called twice and the installed text is the second answer's.
+ - `the same revision and hash is not read again`: two rosters with `{revision: 0, hash: 'a'}` → one GET.
+- [ ] **Step 4: Implement** in `refreshInstructions`: read again when `held?.revision !== doc.revision || held.hash !== doc.hash`;
+ store `hash: doc.hash` in `held`. Comment: the 2026-11-02 rollout of #2495, where running agents kept the old template
+ because revision 0 never moves. Run `npx vitest run src/superTabs/host.spec.ts` → PASS (or only the known reds).
+- [ ] **Step 5: Commit** `Instructions: a template change reaches running agents at revision 0`.
+
+## Phase B. CLI tools and delivery lines
+
+### Task 3: `mine` and `task` views (pure)
+
+**Files:**
+- Create: `cli/src/superTabs/agentContext.ts`
+- Test: `cli/src/superTabs/agentContext.spec.ts`
+
+**Interfaces:**
+- Consumes: a Swarm read `state` (`SwarmRead.state`, `cli/src/superTabs/swarmReads.ts`), `groupChangedAt: ReadonlyMap<string, number>`.
+- Produces:
+
+```ts
+export interface TaskLine { id: string; number: number | null; title: string; status: string; agentName: string | null
+ updatedAt: number | null; result: string | null; pullRequestUrls: string[]; step: string | null; taskId: string | null }
+export const FINISHED_STATUSES: readonly string[] // ['done', 'stopped', 'cancelled', 'lost'], as backend FINISHED
+export function openWorkOf(state: Record<string, unknown>, agentId: string): TaskLine[]
+export function projectOpenWork(state: Record<string, unknown>, agentId: string): TaskLine[] // the coordinator's project
+export function isCoordinator(state: Record<string, unknown>, agentId: string): boolean // service.ts isLead, moved here
+export function mineText(state: Record<string, unknown>, groupChangedAt: ReadonlyMap<string, number>, agentId: string, now: number): string
+export function taskText(group: Record<string, unknown>, state: Record<string, unknown>,
+ attempts: Array<Record<string, unknown>> | null, groupChangedAt: ReadonlyMap<string, number>, now: number): string
+```
+
+- [ ] **Step 1: Failing tests** (fixture builders in the spec file; times as `now - 5 * 60_000` print "5 min ago"):
+ - `mine lists an agent's open task with status, update time, result and PR`: line equals
+ `#12 Fix login — working, updated 5 min ago; last result: Tests pass on main; PR https://github.com/o/r/pull/7`.
+ - `mine leaves out a reused agent's finished task`: agent holds #11 `done` and #12 `working` → only #12.
+ - `mine leaves out archived tasks` (archived: true, status working).
+ - `mine lists linked tasks of its work with their assignee`: #13 `reviewOf` #12, assignee Rev1 working → a line
+ ` linked: #13 Review: Fix login — Rev1, working`.
+ - `the coordinator's mine lists its project's open tasks and counts them`: ends with `3 open tasks.`; other
+ projects' tasks are absent.
+ - `mine with nothing says so`: `No task is assigned to you.`
+ - `a result is cut to its first line and 160 characters`.
+ - `task shows goal, checks, attempts and linked tasks`: checks print `✓ <description> — by Rev1` /
+ `✗ <description> — <evidence first line>` / `· <description>`; attempts newest first, current first, at most 10; a
+ removed agent shows by id; a brief over 1,500 characters ends with `… (cut; the whole brief: status)`.
+- [ ] **Step 2: Run, see them fail.** `npx vitest run src/superTabs/agentContext.spec.ts`.
+- [ ] **Step 3: Implement** the functions. Move `isLead` from `service.ts:142` into `isCoordinator` and import it
+ back. Relative times: under 1 min "just now", minutes, hours, else the UTC date `YYYY-MM-DD HH:MM UTC`.
+- [ ] **Step 4: Run → PASS; `npm run typecheck`.**
+- [ ] **Step 5: Commit** `CLI: mine and task views of an agent's work`.
+
+### Task 4: Wire `mine` and `task`, help and the tools skill
+
+**Files:**
+- Modify: `cli/src/superTabs/command.ts` (`parseSuperTabArgs`, beside `decisions` at ~198)
+- Modify: `cli/src/superTabs/service.ts` (`HELP` at 68; action handlers beside `routeHistory` at 601)
+- Modify: `cli/src/lib/swarmTools.ts` (`SWARM_TOOLS_SKILL` Read list)
+- Test: `cli/src/superTabs/command.spec.ts`, `cli/src/superTabs/service.spec.ts`, the swarm tools spec
+
+**Interfaces:**
+- Consumes: Task 3 functions; the `routeHistory` group read (`GET ${path}/groups/:id?asAgentId`, 403/404 → not found)
+ and attempts read. Extract them from `routeHistory` into `readGroupAsAgent(core, path, id, identity)` and
+ `readAttempts(core, path, id, identity)` in `service.ts`, used by both.
+- Produces: actions `mine` (`{ action: 'mine' }`) and `task` (`{ action: 'task', conversationId }`), each answering
+ `{ ok: true, value: string }`.
+
+- [ ] **Step 1: Failing tests:** `parses mine` (`['mine']` → `{action:'mine'}`), `parses task GROUP`, `task without a
+ group is a usage error`; service: `mine answers the text`, `task reads a dormant group from the group read`,
+ `task of an unreadable group answers NOT_FOUND`; skill text contains `mine`, `task GROUP` and
+ `messages GROUP --thread ROOT`; `HELP.mine` and `HELP.task` exist.
+- [ ] **Step 2: Run, fail; implement.** `task` uses the active group from `reads.read` when present, else
+ `readGroupAsAgent`. The printer prints a string value as is (check `superTabCommand`'s print path handles a string;
+ if it JSON-encodes, print strings raw).
+- [ ] **Step 3: Run** `npx vitest run src/superTabs/command.spec.ts src/superTabs/service.spec.ts src/lib` → PASS.
+- [ ] **Step 4: Commit** `CLI: mine and task commands, in help and the tools skill`.
+
+### Task 5: Deliveries say where they are
+
+**Files:**
+- Modify: `cli/src/superTabs/host.ts` (`prompt()` at ~1922, the caller at ~1730, `repliedTo()` at 1875)
+- Create: `cli/src/superTabs/deliveryContext.ts`
+- Test: `cli/src/superTabs/deliveryContext.spec.ts`, `cli/src/superTabs/host.spec.ts`
+
+**Interfaces:**
+- Consumes: `SwarmReads.read(tabId, agentId)` (fresh per delivery, no time cache); Task 3 `openWorkOf`,
+ `projectOpenWork`, `isCoordinator`; the one-message read `repliedTo()` already makes (its `thread` summary).
+- Produces:
+
+```ts
+export function placeLine(state: Record<string, unknown>, groupId: string): string | null
+// `In task #12 "Fix login" (conversation <id>).` | `In "Review: Fix login" (conversation <id>).` |
+// `In the project chat of <project> (conversation <id>).` | `In <person>'s Buddy chat (conversation <id>).`
+export function workLine(state: Record<string, unknown>, agentId: string): string | null
+// `You are assigned task #12 "Fix login" (working).` up to three, then ` And N more: mine.`;
+// coordinator: `Open tasks in your project: N; mine lists them.`
+export function threadLine(root: { author: string; createdAt: string; text: string }, replies: number,
+ authors: string[], readCommand: string): string
+// `In a thread <author> started (<YYYY-MM-DD HH:MM> UTC): "<first line ≤200>" — <N> replies so far, from <≤3 authors>.
+// Read the whole thread before acting on it: <readCommand>`
+```
+
+- [ ] **Step 1: Failing tests** for each line form above; `workLine` for an agent with none → null; `threadLine`
+ without counts keeps the root's line and the command; a Buddy's thread session gets the place and reply lines only.
+ In `host.spec.ts`: `a delivery whose read fails still goes, without its lines`; `a reply to the root needs no extra
+ read`; `a reply to a later reply reads the root once`; `a work.assign delivered right after it names the new task`.
+- [ ] **Step 2: Run, fail; implement.** In the caller, read the Swarm once per delivery (catch → no lines, logged once
+ per delivery); put the lines before `Message <id> from <author>:`, then the existing quote.
+- [ ] **Step 3: Run** `npx vitest run src/superTabs/deliveryContext.spec.ts src/superTabs/host.spec.ts` → PASS.
+- [ ] **Step 4: Commit** `CLI: a delivery says its task, the agent's own work and its thread`.
+
+## Phase C. Backend steps
+
+### Task 6: The `step` field and opening a step
+
+**Files:**
+- Modify: `backend/src/superTabs/model.ts` (`Conversation`, beside `reviewOf` at 294)
+- Modify: `backend/src/superTabs/commands.ts` (schema at 172; `conversation.create` at 1685-1735)
+- Modify: `backend/src/superTabs/parts/light.ts` (add `step` wherever `reviewOf` is listed, line 30)
+- Modify: `backend/src/superTabs/read/service.ts:101` and the `/changes` answer: `steps: true` beside `githubApp`
+- Modify: `backend/src/superTabs/read/contract.ts` (`steps?: true`)
+- Test: `backend/src/superTabs/commands.test.ts`, `backend/src/superTabs/read/changes.test.ts`
+
+**Interfaces:**
+- Produces: `Conversation.step?: string`; `conversation.create` accepts `step: z.string().trim().min(1).max(40)`
+ (optional); reads carry `steps: true`. `isStep(group): boolean` = `!!group.step && !!group.reviewOf`, exported from
+ `model.ts`. `stepsOf(state, taskId): Conversation[]` = groups with `reviewOf === taskId && step`, exported from
+ `model.ts`.
+
+- [ ] **Step 1: Failing tests:** `a step opens on a task of its project, numbered, its opener in the task`
+ (`step: 'Thiết kế "v2" 🎨'` kept byte for byte; `number` set; opener in the task's `agentIds`); refused with
+ `INVALID_REQUEST` when `step` has no `reviewOf`; refused `NOT_FOUND` on another project's task; refused on a task
+ that is itself a step (`STEP_OF_STEP`, 400, "A step belongs to a task, not to another step."); refused on an archived
+ task (as `open()` refuses today); the read and `/changes` carry `steps: true`.
+- [ ] **Step 2: Run, fail; implement.** The opener joining the task: add it to the reviewed task's `agentIds` with
+ `teamJoin` when it is not the coordinator.
+- [ ] **Step 3: Run** `npx vitest run src/superTabs/commands.test.ts src/superTabs/read` → PASS.
+- [ ] **Step 4: Commit** `Swarm: a task's step is a linked group with a name`.
+
+### Task 7: Assigning a step joins its agent to the task
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts` (`work.assign`, membership at ~2705)
+- Test: `backend/src/superTabs/commands.test.ts`
+
+- [ ] **Step 1: Failing test** `a step's agent joins its task`: `work.assign` on a step → the agent is in the step's and
+ the task's `agentIds`. `a done step may be assigned again` → an attempt row, status `working`. `a step stays working
+ across its owner's fix round`: the step's agent fails a task check, its quiet time does not count
+ (`waitingForRevision`), the owner's next `review` clears it (`revisionReady`), and liveness does not mark it lost
+ (`liveness.test.ts`; these already key on `reviewOf`, so this pins them for steps).
+- [ ] **Step 2: Run, fail; implement** with `joinsProject` (`commands.ts:597`) on the task; run → PASS.
+- [ ] **Step 3: Commit** `Swarm: a step's agent joins its task's chat`.
+
+### Task 8: A step archives and sleeps only with its task
+
+**Files:**
+- Modify: `backend/src/superTabs/parts/write.ts:72` (`workFinished` false for a step)
+- Modify: `backend/src/superTabs/sweeps.ts` (`sleepQuietGroups`, line 73)
+- Create helper in `backend/src/superTabs/tidy.ts`: `closeSteps(state, task, reason: string, now: number): Conversation[]`
+- Modify callers that archive a task: `commands.ts:1798` (archive by hand), `commands.ts:2828` (`work.cancel`),
+ `store.ts:3406` (`archiveFinished`); `parts/touches.ts` gains the task's steps for those writes.
+- Test: `backend/src/superTabs/archive.test.ts`, `backend/src/superTabs/tidy.test.ts`, `backend/src/superTabs/commands.test.ts`,
+ the sweeps test beside `sweepsThreadMarks.test.ts`
+
+**Interfaces:**
+- Produces: `closeSteps` archives every step of `task`; an open one is cancelled first with
+ `` `${reason}` `` as its result and a system row `"<task title>" was closed: <reason>.` in the step.
+
+- [ ] **Step 1: Failing tests:**
+ - `a done step with no pull request is not archived while its task is active` (archive pass after 31 min).
+ - `a done step does not sleep while its task is active` (sweep after a day).
+ - `a step sleeps once its task is archived`.
+ - `archiving a task by hand cancels its working step` (same write: step `cancelled`, `archived: true`).
+ - `cancelling a task closes its steps`; `archiveFinished closes the task's steps`.
+ - `an old linked group (no step) archives on its own clock as today`.
+- [ ] **Step 2: Run, fail; implement.** In the sweep, a candidate step reads its task's row (`db.swarmGroup.findUnique`
+ by `tabId_key`, cached per pass) and sleeps only when the task is archived or dormant.
+- [ ] **Step 3: Run** `npx vitest run src/superTabs/archive.test.ts src/superTabs/tidy.test.ts src/superTabs/commands.test.ts src/superTabs/sweepsThreadMarks.test.ts` → PASS.
+- [ ] **Step 4: Commit** `Swarm: a step archives and sleeps with its task`.
+
+### Task 9: Who hears a step
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts` (`work.status` `told` at ~2777; `message.send` `workerToLead` and
+ `memberToLead` at ~2492-2504; the status label at ~2773)
+- Create in `model.ts`: `taskOwner(state, step): string | null` (the task's assignee while its work is open, else null)
+- Test: `backend/src/superTabs/commands.test.ts`
+
+- [ ] **Step 1: Failing tests:**
+ - `a step's review and done reach the task's owner, not the coordinator`.
+ - `with no owner, a step's done reaches the coordinator` (task unassigned; and task `done`).
+ - `a step's blocked reaches the coordinator and the owner`.
+ - `a step agent's unnamed post in its step reaches the owner`; `… in its task reaches the owner`.
+ - `an agent with no open step in the task still reaches the coordinator` (the 10-29 rule).
+ - `a step's review row reads Ready, not Ready for review`.
+ - `an old linked group keeps today's notices`.
+- [ ] **Step 2: Run, fail; implement.** For a step: `told` = `review`/`done` → `[owner ?? lead]`;
+ `needs_human`/`blocked` → `[lead, owner]`. Unnamed posts: `workerToLead` in a step → owner ?? lead; `memberToLead` in a
+ task when the poster holds an open step of it → owner ?? lead. Label: `isStep(group) && status === 'review' ? 'Ready' : STATUS_LABELS[status]`.
+ Comment the Ken 2026-11-02 overload ("the PM's terminal gets a message every few seconds").
+- [ ] **Step 3: Run → PASS. Commit** `Swarm: a step tells its task's owner, the PM only what needs it`.
+
+### Task 10: Job kind and reports name a step by its task
+
+**Files:**
+- Modify: `backend/src/superTabs/evidence/jobKind.ts:31-32`
+- Modify: `backend/src/superTabs/projectUpdates.ts:76-79` (the "#N after S" list)
+- Test: `backend/src/superTabs/evidence/*.test.ts` (jobKind's), `backend/src/superTabs/projectStatus.test.ts` or the
+ project updates test
+
+- [ ] **Step 1: Failing tests:** `a step's job kind is its route word's, else general` (`step: 'Design'`, route word
+ `docs` → `docs`; none → `general`); `an old linked group is review`; the PM's report names a step
+ `#1835 · Review after 12`.
+- [ ] **Step 2: Run, fail; implement** (`jobKindOf` takes `step` in its `Pick`; a step skips the `review` branch).
+- [ ] **Step 3: Run → PASS. Commit** `Swarm: a step is ranked as its own kind of work and named by its task`.
+
+## Phase D. CLI views of steps
+
+### Task 11: `status`, `mine`, `task` and the place line show steps
+
+**Files:**
+- Modify: `cli/src/superTabs/agentContext.ts`, `cli/src/superTabs/deliveryContext.ts`, `cli/src/superTabs/service.ts`
+ (`statusView` at 150)
+- Test: their specs
+
+- [ ] **Step 1: Failing tests:**
+ - `status prints a task's steps under it, not as rows` (each group in `conversations` with `step` moves under its task as `steps: [...]`).
+ - `mine shows a step's agent its step by its task`: `#1835 "Fix login" · Review — working (step <id>)`.
+ - `mine shows the owner its task's steps on one line`: ` steps: Review: Rev1, working · Test: Tester, done`.
+ - `the coordinator's open work counts tasks, not steps`.
+ - `task lists its steps` (name, agent, status, checks, result's first line, id); `task STEP shows its task with the step marked` (`▶ Review`).
+ - `a step's row says its task and step`: `In task #1835 "Fix login", step Review (conversation <step id>).`
+- [ ] **Step 2: Run, fail; implement. Run → PASS. Commit** `CLI: steps shown inside their task`.
+
+### Task 12: Merged `messages TASK`, adding a step, and old backends
+
+**Files:**
+- Modify: `cli/src/superTabs/service.ts` (`messages` handler at 665; the `command` handler at ~680; `HELP.commands`
+ example at 104)
+- Modify: `cli/src/lib/swarmTools.ts` (one line: how to add a step, one example)
+- Test: `cli/src/superTabs/service.spec.ts`, the swarm tools spec
+
+**Interfaces:**
+- Produces: `messages TASK` (no `--before`, no `--thread`) answers the task's page with each step's latest page merged
+ in by `createdAt`, each step row with `step: '<name>'`; `stepsMissing: ['<name>']` when a step's read failed.
+
+- [ ] **Step 1: Failing tests:**
+ - `messages of a task merges its steps' rows by time and tags them`.
+ - `an unreadable step leaves the task's rows and says which step is missing`.
+ - `messages of a step reads the step alone`.
+ - `step is dropped for a backend without steps` (read without `steps: true`; the sent command has `reviewOf`, no `step`).
+ - `a step name with quotes and diacritics is shown and quoted` (`Thiết kế "v2"` in a place line and in the
+ `--thread` / `messages` command it prints, through `shellQuote`).
+ - the tools skill's step line names no step kind list (`expect(SWARM_TOOLS_SKILL).not.toMatch(/Review, Test/)`).
+- [ ] **Step 2: Run, fail; implement.** HELP example: `{ type: 'conversation.create', title: 'Step name', reviewOf: 'GROUP', step: 'Step name', task: {...} }`
+ replacing the `Review: Outcome` example's wording with neutral words; the skill line: "Add a step to a task: create
+ a conversation with `reviewOf` set to the task and `step` set to the step's name from your instructions, then
+ assign it." Changing the skill moves its version (one update notice per agent); keep it to this one line.
+- [ ] **Step 3: Run** `npx vitest run src/superTabs src/lib` (known reds only) and `npm run typecheck` → PASS.
+- [ ] **Step 4: Commit** `CLI: a task's messages include its steps; adding a step`.
+
+## Phase E. Desktop and phone
+
+### Task 13: Steps in the task list
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/model.dart` (`reviewOf` at 317/385: add `step`), the phone's `mobile/lib/swarm/model.dart`
+- Modify: `desktop/lib/super_tabs/linked_tasks.dart` and `mobile/lib/swarm/linked_tasks.dart` (byte-identical)
+- Modify: `desktop/lib/super_tabs/project_sidebar.dart:1253` (`superTabOpenWorkgroups`), `mobile/lib/swarm/swarm_project_page.dart:68-72`
+- Test: `desktop/test/super_tabs/` (linked tasks and sidebar tests), `mobile/test/swarm/desktop_parity_test.dart`
+
+**Interfaces:**
+- Produces: `SuperTabConversation.step` (`String?`); `superTabLinkedLine` prints a step as `<step> (<agent>): <state>`
+ and a linked group without `step` as today (`#14 Review PR 12: passed`); `superTabIsStep(conversation)`.
+
+- [ ] **Step 1: Failing tests:** `the sidebar hides steps and keeps old linked groups`; `the steps line names each
+ step and its agent` (`Copy (Writer): passed · Design (Designer): working`); phone list the same; parity test passes
+ with both files identical.
+- [ ] **Step 2: Run** (`cd desktop && flutter test test/super_tabs/<files>`; `cd mobile && flutter test test/swarm/<files>`)
+ → FAIL; implement; run → PASS. `dart format` the touched files only.
+- [ ] **Step 3: Commit** `Desktop, phone: a task's steps sit on its row, not in the list`.
+
+### Task 14: Steps panel and the merged chat
+
+**Files:**
+- Modify: Desktop's task header and message loader (`desktop/lib/super_tabs/controller.dart` ~3518 and ~3698, the
+ selected group's view in `view.dart`); phone's `mobile/lib/swarm/swarm_chat_cache.dart` and the chat page
+- Create: `desktop/lib/super_tabs/task_steps.dart` and `mobile/lib/swarm/task_steps.dart` (byte-identical: the merge
+ and the panel rows' text), added to the parity test
+- Test: `desktop/test/super_tabs/task_steps_test.dart`, `mobile/test/swarm/task_steps_test.dart`
+
+**Interfaces:**
+- Produces: `List<SuperTabMessage> superTabMergeSteps(List<SuperTabMessage> task, Map<String, List<SuperTabMessage>> steps,
+ Map<String, String> stepNames)` (by `createdAt`, then id; each step row carries its step name for the row label);
+ `String superTabStepRow(SuperTabConversation step, SuperTabSnapshot snapshot)` (`Review · Rev1 · working · 2 of 3 checks passed`).
+
+- [ ] **Step 1: Failing tests:** `steps' rows merge into the task's by time with their step's name`; `a step whose
+ read fails leaves the task's rows`; `the panel row shows name, agent, status and checks`; tapping a row opens the
+ step agent's pane (widget test on Desktop).
+- [ ] **Step 2: Run, fail; implement.** Opening a task reads each step's latest page once, then follows each step's
+ changes as any group's; a step row shows its step's name beside the author.
+- [ ] **Step 3: Run → PASS; `dart format` touched files. Commit** `Desktop, phone: a task shows its steps and their messages`.
+
+## Shipping order
+
+1. Phase A (Tasks 1-2): backend then CLI, before `scripts/swarm-instructions/migrate.ts --apply` runs on prod.
+2. Phase B (Tasks 3-5): CLI.
+3. Phase C (Tasks 6-10): backend.
+4. Phase D (Tasks 11-12): CLI.
+5. Phase E (Tasks 13-14): Desktop and phone.
+
+Validation per phase: the touched tests above, then for backend phases the whole `src/superTabs` vitest run; for CLI
+phases `npx vitest run src/superTabs src/lib` plus `npm run typecheck`; for clients `flutter test` of `test/super_tabs`
+and `test/swarm`. Record what ran in the PR.
diff --git a/docs/plans/2026-11-02-agent-context-design.md b/docs/plans/2026-11-02-agent-context-design.md
new file mode 100644
index 000000000..ce5209210
--- /dev/null
+++ b/docs/plans/2026-11-02-agent-context-design.md
@@ -0,0 +1,198 @@
+# Agents know their work and their conversations
+
+Status: design, 2026-11-02. Requested by Ken. Replaces the draft `2026-11-02-delivery-context-design.md` (merged in).
+
+## Why
+
+Ken sees agents forget their task: which one they are on, and how far it got. The PM loses track when several people
+answer one thread, and agents answering each other, or the PM and an agent, lack the context between their messages.
+
+What an agent has today:
+
+- **Deliveries** (`cli/src/superTabs/host.ts` `prompt()`): the conversation's id (24 hex characters, never its name or
+ task number), the message's id, author and text, the one message a reply answers (quoted up to 600 characters,
+ `repliedTo()`), and the commands to read and answer. Nothing says which task the agent itself is assigned, how a
+ thread began, or that others replied in it.
+- **Tools** (`harness super-tab`, help in `cli/src/superTabs/service.ts` `HELP`): `status` returns everything the agent
+ may read: every person and agent, and every active conversation of its own project with its task (an agent reads only
+ its project's groups, `canReadProject`; over a hundred on the openharness project), with no "mine" view;
+ `messages GROUP [--thread ROOT]`, `message GROUP ID`, `instructions`, `decisions`, `costs`. No command shows one task
+ with its checks and earlier attempts, though the backend serves the attempts
+ (`GET /api/super-tabs/:tab/conversations/:id/attempts`).
+- Agents do not fetch what they are not told exists: the delivery once gave only a command to read the message a reply
+ answers, agents skipped it, and a Lead took Ken's "GO" as approving a different plan (why `repliedTo()` quotes it now).
+
+## What Ken decided
+
+- Harness gives tools and facts; how an agent works (when to look, what to read before acting) is the project's
+ instructions'. The same split as the rest of the Swarm: the server and the CLI decide no workflow.
+- Deliveries carry a few short pointers to their context, and the agent (an LLM) decides what more to read.
+- One design for both: the task an agent works on, and the conversation a message belongs to.
+
+## Goals
+
+- An agent can always learn, in one short command, what it is assigned and how far each task got.
+- A PM can see its project's open work in one short command, without reading the whole Swarm.
+- From a delivery alone, an agent knows which task or chat a message belongs to, which task it is itself on, whether the
+ message sits in a thread others have written in, and how to read more.
+- The instructions tell agents when to use these; a project can change that.
+
+## Non-goals
+
+- Pushing whole threads, conversations or task histories into a terminal.
+- Summarising with a model.
+- New server state or endpoints beyond small read fields; workflow rules in code.
+
+## Anti-goals
+
+- A delivery so long that the message is lost in it.
+- An agent seeing, through a tool or a delivery, anything it could not read itself (every read is `asAgentId`).
+- A delivery held back because its context could not be read.
+
+## Words used below
+
+- **Open work**: an assignment whose status is not finished (`activeWork` in `backend/src/superTabs/model.ts`; finished
+ is `done`, `stopped`, `cancelled`, `lost`, `FINISHED` in `parts/light.ts`). Design call: "your work" and `mine` list
+ open work only. A reused Engineer keeps `assignment.agentId` on its old finished task until that task goes dormant,
+ and listing it ("task #11 (done)") is the confusion this design is for.
+- **Coordinator**: the agent that leads the project (`isLead` in `service.ts`, the project's Lead conversation). Every
+ task group's `leadId` is that agent, so `swarmRoleFor` in `host.ts` agrees.
+- **Updated**: when the task's group last changed (`groupChangedAt` from `SwarmReads`; reads carry no
+ `lastActivityAt`, and an assignment has no update time).
+
+## 1. Tools (CLI, the same for every agent but a Buddy)
+
+### `harness super-tab mine`
+
+What this agent works on, compact (design call: a short table, not JSON, at most one line per task):
+
+- its open work, not archived: `#<number> <title> — <status>, updated <time>; last result: <first line, up to 160
+ characters>; PR <url>` (status and result from its `assignment`, PR from `pullRequestUrls`);
+- every review or test task linked to that work (`reviewOf` either way) that is open, with its assignee and status;
+- for the coordinator: every open task of its project instead (not archived), with its assignee;
+- an empty list says so ("No task is assigned to you."), and the coordinator's ends with how many tasks are open.
+
+Read from the Swarm read the CLI already makes for `status` (`reads.read(tabId, agentId)`), filtered and shaped on the
+daemon. No new endpoint. The read holds active groups only: a finished task quiet for a day, or one archived by hand,
+is dormant (`sweeps.ts` `sleepQuietGroups`, `commands.ts` ~1801) and is not listed, which suits a list of open work. An
+archived group still in the read (`archived: true`) is filtered out.
+
+### `harness super-tab task GROUP`
+
+One task, as its readers need it:
+
+The group comes from the Swarm read when it is active, else from `GET /api/super-tabs/:tab/groups/:id?asAgentId=…`,
+which serves active and dormant groups and answers 404 for one the agent may not read (as `routeHistory` in
+`cli/src/superTabs/service.ts` ~603 already does; reuse it). It shows:
+
+- number, title, project, status, assignee, PR links, updated;
+- the task: `goal`, `changes`, `constraints`, `owns`, `requires`, `review` (`WorkTask`), else the `brief`, cut to 1,500
+ characters with the command for the rest (`status` for an active one). There is no "Done when" field: a template's
+ "Done when" is words in the brief, and the acceptance criteria are the checks;
+- its checks: each `description`, passed (`passedBy` set: by whom, the actor's name from `state.agents` or the
+ person) or not, and the evidence's first line (a failed check keeps its evidence with `passedBy` null,
+ `commands.ts` ~2884; the read does not say who failed it);
+- its attempts, newest first, at most 10: the current one from `assignment`, then earlier ones from the backend's
+ `attempts` read (`store.ts` ~2540; a row is written when an assignment is replaced, at most 50, newest first, each
+ `{agentId, status, result ≤500, createdAt}`): assignee (by name, or the id when the agent is gone), status, the
+ result's first line, when;
+- its linked tasks (`reviewOf` either way) with assignee and status;
+- the commands to read its conversation (`messages GROUP`) and a thread (`--thread ROOT`).
+
+### Help and the Harness tools skill
+
+`HELP` gains `mine` and `task`; the fixed Harness tools skill (`SWARM_TOOLS_SKILL`, `cli/src/lib/swarmTools.ts`, every
+agent but a Buddy, the PM included, in every project) lists them, and `messages GROUP --thread ROOT` in its Read list.
+Changing that text moves its version, so each running agent gets one skill-update notice. The skill says what each tool
+returns, not when to use it; that is the instructions'.
+
+## 2. Deliveries say where they are (CLI)
+
+In `prompt()`, before the message (`Message <id> from <author>:`), at most four short lines, each only when it applies:
+
+1. **Where:** `In <place> (conversation <id>).` The place is the task's number and title (`task #12 "Fix login"`), a
+ review's title (`"Review: Fix login"`), the project chat (`the project chat of <project>`), a Buddy chat (`<person>'s
+ Buddy chat`) or the Leads conversation; the id alone when the name is not known.
+2. **Your work:** `You are assigned task #<n> "<title>" (<status>).` for each task assigned to the receiving agent (at
+ most three, then "and N more: mine"), or nothing when it has none. The coordinator gets `Open tasks in your project:
+ <count>; mine lists them.` instead.
+3. **Thread:** whenever the message is in a thread (its `thread` is set and is not its own id) that has replies besides
+ it. Desktop and the phone answer in a thread with `replyTo` set to the root (`desktop/lib/super_tabs/controller.dart`
+ ~1538, `mobile/lib/swarm/swarm_thread.dart` ~523), so this is the common case:
+ `In a thread <root author> started (<time UTC>): "<the root's first line, up to 200 characters>" — <N> replies so
+ far, from <up to three authors>. Read the whole thread before acting on it: <command> messages <group> --thread
+ <root>`. N counts every reply when read, the delivered one and any that came after included ("so far"). Without
+ counts, the line keeps the root's line and the command.
+4. **Reply:** today's quote of the message it answers (`repliedTo()`), unchanged.
+
+A Buddy's thread session gets lines 1 and 4 only (design call: its whole chat is one thread, and it holds no tasks).
+
+**What is read.**
+
+- Lines 1 and 2 come from the Swarm read (`cli/src/superTabs/swarmReads.ts`; the host's rows carry only `tabName` and
+ the agent, `backend/src/superTabs/read/hostRows.ts`). Design call: read it fresh for each delivery, no time cache.
+ `SwarmReads` already keeps each (tab, agent) store and fetches only `/changes` since its cursor, so a read is one
+ small call plus `reassemble()`; a 60 s cache could build the delivery announcing a `work.assign` from a read taken
+ before it, without the new task.
+- Line 3 needs no backend change: a one-message read (`messages?asAgentId=…&messageId=…`, the one `repliedTo()` makes)
+ returns that message's thread summary (`backend/src/superTabs/store.ts` ~2456 from each row's `thread`; a top-level
+ message's `thread` is its own id, ~2293; `threads.ts` `threadSummaries`). The reply to the root needs no new read; a
+ reply to a later reply, or a thread message with no `replyTo`, needs one read of the root.
+- A root or a task this agent may not read comes back empty, and its line is left out; the delivery always goes.
+
+## 3. Instructions: when to use them (the template)
+
+The template's Workflow (`backend/src/superTabs/instructionsTemplate.ts`) gains, as plain workflow a project may change:
+
+- "Before acting after a pause, or when unsure what you are working on, run `mine`."
+- "Before saying your work is done, read `task GROUP` and check that every check has passed."
+- "In a thread others have written in, read the thread before acting on it, unless the delivery already says enough."
+- "The PM reads `mine` for progress, not `status`."
+
+**Reaching projects.** On prod (v1.3.78_backend, 2026-11-02) no project has saved instructions
+(`SuperTabInstructions` is empty) and every one reads the template, revision 0. Two things decide whether the new lines
+reach agents:
+
+- The migration (`scripts/swarm-instructions/migrate.ts --apply`, not yet run) gives every older project its own
+ document, copied from the template current at that time, and new projects and Swarms already save one at creation
+ (`commands.ts` ~1334, `store.ts` ~939). Design call: these lines land before the migration runs, so the copies
+ carry them; after that, a template change reaches only new projects.
+- The daemon reads the text once per (project, revision) (`instructionTexts`, `host.ts` ~1435). At revision 0 the
+ revision never moves and the host row's hash is null (`hostRows.ts` 87), so a running daemon keeps the template it
+ first read until it restarts. Part of this design: at revision 0 the host row carries the template's hash, and the
+ daemon reads again when the hash moves. The same gap held back #2495's routing lines from running agents.
+
+## Design
+
+- **Growth**: N/A because nothing is stored; the daemon keeps the Swarm stores `SwarmReads` already keeps.
+- **Concurrency**: N/A because nothing is written.
+- **Read cost**: `mine` and lines 1-2 reuse the Swarm read (one `/changes` call per delivery, only what changed);
+ `task` is one Swarm read (or one group read for a dormant task) and one `attempts` read when asked; line 3 at most
+ one one-message read per threaded delivery; the template hash is a constant per backend build.
+- **Scale**: the Swarm read grows with the Swarm; the warning metric is the daemon's delivery latency and the
+ `/changes` read time.
+- **Compatibility**: an older backend without thread summaries on a one-message page gives line 3 without counts; an
+ older daemon writes today's delivery and lacks the new commands; agents with an older skill learn the commands at
+ the skill update.
+- **Migration and rollback**: none for data. Order: the template lines ship before the instructions migration is
+ applied. Rollback is the previous CLI and backend; an older daemon ignores the hash and behaves as today.
+- **Audience**: every read is as the receiving agent; an agent-only notice never quotes or points (as today).
+- **Identity**: the agent's own.
+- **Failure**: an unreadable name, task or root leaves its line out, logged once per delivery; `mine` and `task` say
+ what they could not read.
+- **Platforms**: daemon-side; the same everywhere.
+
+## Tests
+
+- `mine`: an Engineer with two tasks, one done; a Reviewer with a linked review; the coordinator's open project work;
+ an agent with none; archived tasks left out; lines within their caps.
+- `task GROUP`: checks passed, failed with evidence, and untouched; the current attempt and earlier ones (newest first,
+ at most 10, a removed agent by id); linked tasks; a long brief cut with its pointer.
+- `prompt()`: place line for each kind of conversation; "your work" lines for an Engineer, the coordinator and an agent
+ with none; thread line for a reply to the root (no extra read), a reply to a later reply (one read), a thread's only
+ reply (none) and a Buddy's thread session (none); an unreadable root still delivers; a `work.assign` delivered right after it names the new task.
+- `swarmTools.ts` lists `mine`, `task` and `--thread`; the template's Workflow has the four lines.
+- Instructions: a host row at revision 0 carries the template's hash; a daemon holding revision 0 reads the text again
+ when the hash moves, and not when it stays.
+- `mine` lists no finished task (a reused Engineer's old `done` task), and `task` serves a dormant task from the group
+ read and refuses a group the agent may not read.
diff --git a/docs/plans/2026-11-02-task-steps-design.md b/docs/plans/2026-11-02-task-steps-design.md
new file mode 100644
index 000000000..d9fa20be6
--- /dev/null
+++ b/docs/plans/2026-11-02-task-steps-design.md
@@ -0,0 +1,259 @@
+# One request, one task: steps inside a task
+
+Status: design, 2026-11-02. Requested by Ken. Builds on `2026-11-02-agent-context-design.md` (`mine`, `task GROUP`,
+delivery lines), which shows steps once this lands.
+
+## Why
+
+Ken opened the openharness project's task list and saw one pull request as several tasks: #1835 (the build), #1918
+"Review: PR #2494" and #1919 "Test: PR #2494". On prod (2026-11-02) the project's numbers reach #1919, but only 100
+groups are not archived, and 88 of those have no assignment. Many are bookkeeping the PM opened: "Holder" (security
+review), "Security review 2", "Merge batch", "Combined merge", one "PR triage" per outside pull request, "To do", and a
+review and a test group per pull request. Only 21 have `reviewOf`; nothing else links a group to the request it serves.
+
+Two causes:
+
+- **The model.** A conversation holds exactly one `assignment` (one agent, one status, one result, one lease, one cost
+ line). A Reviewer and a Tester therefore each need their own conversation, linked by `reviewOf`, with its own number,
+ its own chat and its own row in every list.
+- **The instructions.** Nothing tells the PM not to open groups for bookkeeping, or an Engineer to ask the same Reviewer
+ again instead of opening "Review 2".
+
+The PM also hears every step: a linked task's own agent setting `review` or `done` notifies the coordinator
+(`commands.ts` `work.status`, `told`), though the Engineer is the one who acts on a verdict.
+
+## What Ken decided
+
+- One request is one task. Review, test and the like are **steps** of that task, each with its own agent and verdict
+ (Ken chose "cách 2" over showing linked groups nested in the UI alone).
+- The instructions change too, in the same design: the bookkeeping groups stop.
+- As everywhere in the Swarm, the server names no step and checks no order. Which steps a task has, who works them and
+ when, is the project's instructions'. The PM role always exists.
+- Steps are not a software idea. The same model has to serve a marketing team's instructions as well as openharness's:
+ no code, field or notice may name a pull request, a review, a test, an Engineer or a Reviewer (Ken, 2026-11-02).
+- A task has an **owner** when it has an assignee, and the owner hears its steps. A task with no assignee is the
+ coordinator's: its steps report to the PM (design call, proposed on Ken's "đề xuất đi"). Someone has to collect the
+ verdicts and tell the PM once; with nobody, every step would reach the PM, which is the overload this design removes.
+
+What it looks like for two teams, written only in their instructions:
+
+- openharness: "The Engineer owns the task. When its pull request is ready it adds a Review step, and a Test step when a
+ user sees the change." The list shows `#1835 Fix login — Review: passed · Test: 1 check failed`.
+- A marketing team: "Each campaign is a task the Campaign Lead owns. The Lead adds Copy (a Copywriter) and Design (a
+ Designer) in parallel, then Brand check (a Brand reviewer), then Schedule." The list shows `#42 Black Friday — Copy:
+ passed · Design: working · Brand check: not started`.
+
+## Goals
+
+- The project's task list shows one row per request, with its steps' agents and verdicts on it.
+- A step keeps what a task gives its agent today: liveness and lease (a dead Reviewer is found), its attempts, its
+ cost and model, its checks, its place in `mine`.
+- A step's messages are in the task's one chat, so its owner, every step's agent and the PM read one conversation.
+- A step's progress goes to the task's owner, not the PM. The PM hears when a step needs a person or is stuck, when the
+ owner tells it the task is ready, and every step of a task with no owner.
+- The PM opens no group for bookkeeping.
+
+## Non-goals
+
+- Workflow in code: no fixed step names, no required order, no automatic review.
+- Rewriting liveness, costs, evidence or the leaderboard around a new structure.
+- Moving existing linked groups' messages into their tasks.
+
+## Anti-goals
+
+- A step that dies silently because nothing watches its agent (what "Reviewer joins the Engineer's group" would cost).
+- An older Desktop, phone or daemon that breaks or loses messages while steps roll out.
+- A PM that learns less than today: it still hears every `needs_human` and `blocked`.
+
+## Part 1. The instructions (template only; ships first)
+
+The template (`backend/src/superTabs/instructionsTemplate.ts`) changes as plain words a project may change. Until part 2
+ships, a "step" is a linked task as today (`conversation.create` with `reviewOf`); the words stay true after it.
+
+TEMPLATE_WORKFLOW becomes:
+
+```
+1. One request is one task. The PM opens it with its goal and "Done when" and assigns an Engineer; when no Engineer is
+ free, it starts one. The PM opens no task to hold, batch, triage or list work: that goes in its notes or the project
+ chat.
+2. When the pull request is ready, the Engineer adds a review step to its task, and a test step when the change is
+ something a user sees or uses (screens, CLI commands, install and release, sign-in, connections between machines,
+ devices). It messages the Reviewer and the Tester directly. Review and test run in parallel. Refactors, docs and
+ test-only changes get a review only. A task whose review plan asks for two reviews gets two review steps.
+3. Findings go straight to the Engineer. The Engineer fixes them and asks the same Reviewer or Tester again in the same
+ step; it adds no new step for a second round.
+4. When the review passes, and the test passes where there is one, the Engineer tells the PM once.
+5. The PM checks CI on the pull requests that passed, merges them, and tells the people who asked.
+6. A task that needs a person, or a machine that is down, goes to the PM at once, by name.
+7. Idle Engineers are stopped. Reviewers and Testers are kept while the work they checked is open.
+```
+
+The four agent-context lines (`2026-11-02-agent-context-design.md` section 3) join it in the same edit. Both specs
+change one template; the plan writes it once.
+
+**Reaching projects.** As the agent-context spec says: these words land before the instructions migration
+(`scripts/swarm-instructions/migrate.ts --apply`) runs, so each project's copy carries them; and the revision-0 hash
+fix there makes running daemons read them.
+
+## Part 2. Steps (backend, CLI, Desktop, phone)
+
+The model, in words any team's instructions can use:
+
+- A **task** has a goal, checks, one chat and, when it is assigned, an **owner** (its assignee).
+- A task has any number of **steps**. Each has a name the instructions give, an agent, its own status and result, and
+ its own checks as its verdict.
+- Anyone in the project who may open a linked task today may add a step to an open task, at any time: when the task is
+ opened, or later. Steps run in parallel or one after another as the instructions say; the server orders nothing.
+- A step's progress reaches the task's owner, or the coordinator when the task has none.
+
+### Storage: a step is a linked group, shown inside its task
+
+Design call. A step stays a conversation row with `reviewOf` naming its task, with its own number and its own rows, so
+everything that works on linked tasks today keeps working unchanged: its `assignment`, lease and liveness
+(`liveness.ts`), attempts (`store.ts` attempts read), costs (`costs/read.ts`), checks, decisions, catch-up
+(`catchUp.ts`), the PM's reports (`projectUpdates.ts`), the leaderboard (`stats.ts` counts only groups without
+`reviewOf` as requests), and every writer of rows (liveness notices, tidy and cancel lines, terminal turns,
+`native.ts`). What is new is one field, and how readers show it:
+
+```ts
+// Conversation
+/** A step of the task `reviewOf` names (task steps design): its name as the instructions give it, in any language.
+ * Readers show it inside its task, never as a task of its own. Absent on a linked group opened before steps. */
+step?: string
+```
+
+Why not one chat in storage (the first draft wrote a step's rows into its task): every writer of rows would have to
+follow the redirect (status and lost notices, decisions, cancel and archive lines, terminal turns), and the task's
+catch-up, reports and delivery `assignmentId` would read a step's rows as the task's own. Agents already talk in the
+task's group: a Reviewer or Tester checks and posts there (`renewOwnTask`, `liveness.ts` ~148). What stays in the step's
+own conversation is its brief and the system rows of its work; readers merge them into the task's view.
+
+- **Opening one:** `conversation.create` gains `step` (1-40 characters, free text), allowed only with `reviewOf`, on a
+ task of the same project (as `reviewOf` already requires) that is not itself a step (one level). It takes a number as
+ every group does (`numberConversations`, `commands.ts` 674), so commands may name it, and so a rollback leaves nothing
+ to renumber. Readers show it as `#<task number> · <step>`. The opener joins the task (`agentIds`), as it joins its
+ own review today.
+- **Assigning one:** `work.assign` on a step as on any task; its agent joins the task, so it reads and posts there.
+- **A second round** keeps the step open: its agent stays `working` while the owner fixes, as Reviewers do today
+ (`changesRequestedAt`, `waitingForRevision`, `revisionReady`, `liveness.ts` 109-138, which already key on `reviewOf`).
+ A `done` step may still be assigned again (`commands.ts` ~2686, an attempt row), which the instructions may ask for.
+- **Verdicts:** as today. A step's agent passes or fails the task's checks (`work.check` in the task, which already
+ marks its own step waiting, `commands.ts` ~2901), and the step's own checks when it was opened with some; its status
+ and result say how it ended.
+- **Archive and sleep:** a step archives and sleeps with its task, never on its own clock. The archive pass
+ (`archive.ts` ~100) and the sleep sweep (`sweeps.ts` 74, 98) skip a step while its task is active and not archived;
+ when its task archives, its steps archive in the same write, open ones cancelled with the task's reason. Otherwise a
+ `done` step with no pull request of its own archives within one pass (`settled([])`), a second round then fails
+ `ARCHIVED`, and a dormant step drops out of the read with its verdict.
+
+### Who hears a step
+
+The task's **owner** is its assignee's agent while the task's assignment is open work, else nobody.
+
+- **Status** (`work.status`, `told`), when a step's own agent sets it: `review` and `done` go to the owner, not the
+ coordinator; with no owner, to the coordinator. `needs_human` and `blocked` go to the coordinator as today, and to the
+ owner. Someone else changing a step's work: unchanged.
+- **Unnamed posts** (`message.send`): a step's agent posting with no recipient, in its step (`workerToLead`) or in its
+ task (`memberToLead`), reaches the owner; with no owner, the coordinator. An agent that holds no open step there keeps
+ today's rule (`memberToLead`, the 10-29 prod-watch fix: a moved agent's posts still reach the PM).
+- **Reports** (`projectUpdates.ts`): a step stays in the PM's scheduled reports as today, named `#<task> · <step>`, so
+ the PM learns no less; it is no longer woken by each step's progress.
+- Linked groups opened before steps (no `step`) keep today's rules.
+
+This is the notice Ken was offered on 2026-11-02 ("remove the automatic review notices to the PM"), scoped to steps.
+
+### Nothing in code names a kind of work
+
+- `jobKindOf` (`evidence/jobKind.ts`) reads every linked group as `review`, so a Design step would be compared with
+ reviews when models are ranked. A step takes its job kind as any task does (its route word, else `general`); a linked
+ group opened before steps stays `review`. The job kinds list itself (components of this repository) is outside this
+ design.
+- Copy shown to people names the step by its own name ("Copy: passed"), never "review" or "test". The status label
+ `Ready for review` (`STATUS_LABELS.review`) is shown on a step as `Ready` (design call: the status's meaning is the
+ instructions'; for the task itself the label stays).
+- The Harness tools skill says "add a step to a task" and shows one example step, never a list of step names.
+
+### Reads
+
+- **Swarm read and `status`:** steps are groups and stay in the read, so nothing new is fetched. `status` prints a
+ task's steps under it instead of as rows of their own.
+- **`mine`** (agent-context spec): a step's agent sees `#1835 "Fix login" · Review — working` with the step's id; the
+ owner sees its task with its steps' agents and statuses on one line; the coordinator's open work counts tasks,
+ not steps.
+- **`task GROUP`:** a task lists its steps (name, agent, status, checks' verdicts, the latest result's first line, the
+ step id). Given a step's id, it shows its task with that step marked.
+- **Deliveries:** a row of a step's own says `In task #1835 "Fix login", step Review (conversation <step id>).`; a row
+ in the task says the task. Reply commands stay with the row's own conversation, as today.
+- **`messages TASK`:** the task's rows with its steps' rows merged in by time, each step row tagged with its step's
+ name (a read of each step, as the agent; a task has a few). `messages STEP` reads the step alone.
+
+### Clients
+
+Desktop and the phone (`linked_tasks.dart` is kept byte-identical on both):
+
+- The task list hides steps as rows. The task's row shows its steps line (`superTabLinkedLine` already builds "Review:
+ passed · Test: 1 check failed") with each step's agent.
+- Opening a task shows its steps above the chat: name, agent, status, checks; tapping one opens that agent's pane.
+- The task's chat merges its steps' rows by time, each with its step's name beside the author (one message read per
+ step when the task opens, then the steps' changes as any group's).
+- Linked groups opened before steps show as today.
+
+## Design
+
+- **Growth**: steps are groups and go as groups go, but only with their task: archived with it, then dormant, then
+ deleted with the Swarm. Fewer groups than today: one step replaces each review, test and re-review group, and the
+ bookkeeping groups stop.
+- **Concurrency**: as today, guarded writes per part (`parts/commit.ts` 224-283). Archiving a task writes its steps'
+ parts in the same write (`parts/touches.ts` gains a task's steps for archive and cancel); nothing else touches more
+ than today.
+- **Read cost**: no new backend reads. Steps are in the Swarm read already; a task's merged chat reads each step's
+ messages once when opened (a task has a few steps), then only what changed.
+- **Scale**: a task with 10 steps is 10 groups, as 10 linked tasks are today, and opening it reads 10 small pages. The
+ metric that warns first: groups per project in the Swarm read (`/changes` size), which falls with this design.
+- **Compatibility**:
+ - Old daemons and agents: a step is a linked task, as today; every command they send works.
+ - An older Desktop or phone: shows a step as a numbered linked task, its own chat as today.
+ - An older backend never receives `step`: the CLI sends it only when the Swarm read says the backend has steps (a
+ capability flag on the read).
+- **Migration and rollback**: no data migration; existing linked groups stay as they are. Rollback of the backend:
+ `step` is an unknown field the old backend keeps; steps read as linked tasks, numbered as they already are, and may
+ archive on their own clock again.
+- **Audience**: every read is as the reader. A step is readable exactly when its task is. A private chat cannot hold
+ steps: `conversation.create` already refuses `reviewOf` on a group with an audience (`commands.ts` 1698).
+- **Identity**: actors as today; a step's agent acts as itself.
+- **Failure**: opening a step on a task that is missing, archived, another project's, or itself a step is refused with
+ the reason. A step whose read fails leaves the merged chat with the task's rows and says which step is missing.
+- **Platforms**: backend and daemon on every platform; Desktop (macOS, Windows, Linux, web) and the phone share
+ `linked_tasks.dart`.
+
+## Order
+
+1. Part 1 (template) with the agent-context template lines and the revision-0 hash fix; before the migration runs.
+2. Backend: `step`, archive and sleep with the task, its notices and unnamed posts, `jobKindOf`, the capability flag.
+3. CLI: `mine`, `task`, deliveries, `status` and merged `messages` with steps; the Harness tools skill says how to add
+ a step (one skill-update notice).
+4. Desktop and the phone.
+
+Each ships on its own: before 2 the words mean linked tasks; before 3 and 4 a step shows as a linked task.
+
+## Tests
+
+- Backend: opening a step (numbered, joins the task), with a name in any language; refused with no `reviewOf`, on a
+ step, on another project's task, on an archived task; a `done` step is neither archived nor put to sleep while its
+ task is active, and archives with its task, open ones cancelled; `review` and `done` from a step's agent reach the
+ owner and not the coordinator, and the coordinator when the task has no owner or its work is finished; `blocked`
+ reaches both; a step agent's unnamed post in its step or its task reaches the owner, and a moved agent's still the
+ coordinator; a step's job kind is its route word's, an old linked group's `review`; an old linked group keeps
+ today's rules; a second round keeps the step `working` across the owner's fix; liveness marks a step's dead agent
+ lost; reports name a step as `#<task> · <step>`.
+- CLI: `status`, `mine`, `task` and the "where" line with steps; `messages TASK` merges steps' rows by time and tags
+ them; `step` is sent only to a backend that has it.
+- Clients: the list hides steps and shows the steps line; the task's steps panel; the merged chat with step names;
+ an old linked group shows as today; parity test for `linked_tasks.dart`.
+- Template: Workflow has the seven lines above.
+
+## Left to the builder
+
+- The capability flag's name and where in the read it sits.
+- The steps panel's layout on Desktop and the phone, within the existing task header.
+- Whether `status` prints steps nested or as one line per task.
diff --git a/docs/swarms.md b/docs/swarms.md
index 09c05b047..d51be9a85 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -918,9 +918,12 @@ are delivered at once, with no delay.
every one is close to running out). The review-capacity note is the
coordinator's alone; a project chat with no coordinator in it has its people
read it, tagging who can fix it.
-- **Status changes**: the task's own agent's Ready for review, Needs a human,
- Stuck and Done reach the coordinator. A status anyone else sets reaches the
- task's agent and the coordinator.
+- **Status changes**: the task's own agent's Needs a human, Stuck and Done reach
+ the coordinator; its Ready wakes nobody by itself, as it names whom it hands to
+ (Ken, 2026-11-02). A step's own agent's Ready and Done reach its task's owner
+ (the task's assignee while that work is open), else the coordinator; its Needs
+ a human and Stuck reach both. A status anyone else sets reaches the task's
+ agent and the coordinator.
- **Stalled tasks**: a task whose agent reported nothing for 30 minutes, and a
task in review for 30 minutes with no linked task open (since its last
progress or since its last linked task ended), are told to the coordinator
@@ -1046,13 +1049,16 @@ and on which model is the document's to say, and the agents follow it.
nobody's skill. Where a note and the document disagree, the coordinator follows
the newer one.
- **The template** has the work go from "ready" to "passed" with no coordinator
- action in between. The agent whose work is ready opens its own review, linked
- to its task, and messages the Reviewer, and the Tester when users see the
- change. Review and test run in parallel. A reviewer, not the agent that did the
- work, passes the verdict. Findings go straight to the agent, which fixes them
- and asks again. The coordinator hears once, merges and tells the people who
- asked. Idle Engineers are stopped; Reviewers and Testers are kept while the
- work they checked is open.
+ action in between. One request is one task; the PM opens no task to hold,
+ batch, triage or list work (its notes or the project chat hold that). The
+ agent whose work is ready adds a review step to its task, and a test step when
+ users see the change, and messages the Reviewer and the Tester. Review and test
+ run in parallel. A reviewer, not the agent that did the work, passes the
+ verdict. Findings go straight to the agent, which fixes them and asks the same
+ Reviewer again in the same step. The coordinator hears once, merges and tells
+ the people who asked. Idle Engineers are stopped; Reviewers and Testers are
+ kept while the work they checked is open. Agents read `mine` when unsure what
+ they work on and `task GROUP` before saying they are done.
- **Buddies** read the document as their member's helper, never the history or
the notes, and change it only by asking the coordinator.
- **Older projects** start on the built-in template (revision 0) until their
@@ -1108,6 +1114,32 @@ Design (docs/feature-design-rules.md):
- Platforms: the backend is the same everywhere; Desktop and the web app (which
runs Desktop's screens) edit, the phone reads.
+## Steps inside a task
+
+Design: [docs/plans/2026-11-02-task-steps-design.md](plans/2026-11-02-task-steps-design.md).
+A step is a linked conversation (`reviewOf` names its task) with a name the
+project's instructions give (`step`, free text in any language): review, test, a
+marketing team's design or brand check. It keeps its own number, assignment,
+lease, attempts, costs and checks; readers show it inside its task.
+
+- **Opening one**: `conversation.create` with `reviewOf` and `step`, on an open
+ task of the same project that is not itself a step. Its opener joins the task;
+ so does each agent assigned to it, so the task's chat is where its work is
+ talked over.
+- **Who hears it**: its agent's Ready and Done go to the task's owner, not the
+ coordinator; an unnamed post from its agent, in the step or in the task, does
+ too. With no owner, the coordinator hears them.
+- **Closing**: a step archives and sleeps with its task, never on its own clock;
+ archiving a task cancels its open steps and tells their agents.
+- **Reading**: `status` prints steps under their task; `mine` and `task GROUP`
+ show them; a delivery names the task and step. Desktop and the phone hide steps
+ from the task list, put them on the task's row ("Review (Nova): working") and
+ merge their messages into the task's chat with the step's name beside the
+ author. The CLI sends `step` only to a backend whose first load says
+ `steps: true`; elsewhere a step opens as a plain linked task.
+- **Older linked tasks** (no `step`) keep their own number, row, chat and
+ notices.
+
## A message that is not getting in
A message waits as a delivery until its recipient's computer takes it. Your newest message shows a line under it only
diff --git a/mobile/lib/swarm/linked_tasks.dart b/mobile/lib/swarm/linked_tasks.dart
index f1164ceae..b8e8075fd 100644
--- a/mobile/lib/swarm/linked_tasks.dart
+++ b/mobile/lib/swarm/linked_tasks.dart
@@ -26,8 +26,35 @@ String? superTabLinkedLine(
final byNumber = order(a).compareTo(order(b));
return byNumber != 0 ? byNumber : a.id.compareTo(b.id);
});
- return [for (final task in linked) '${task.label}: ${_state(task)}']
- .join(' · ');
+ return [
+ for (final task in linked)
+ superTabIsStep(task)
+ ? '${_stepLabel(snapshot, task)}: ${_state(task)}'
+ : '${task.label}: ${_state(task)}',
+ ].join(' · ');
+}
+
+/// Whether [conversation] is a step of a task (task steps design): shown on
+/// its task's row and inside its task, never as a task of its own.
+bool superTabIsStep(SuperTabConversation conversation) =>
+ conversation.step != null && conversation.reviewOf != null;
+
+/// [groups] as the project's list shows them: without steps, which sit on
+/// their task's row (task steps design).
+List<SuperTabConversation> superTabListedWork(
+ Iterable<SuperTabConversation> groups,
+) => [
+ for (final g in groups)
+ if (!superTabIsStep(g)) g,
+];
+
+/// A step by its own name and its agent: "Copy (Atlas)".
+String _stepLabel(SuperTabSnapshot snapshot, SuperTabConversation step) {
+ final agentId = step.assignment?['agentId'];
+ final name = agentId is String && snapshot.agent(agentId) != null
+ ? snapshot.agentName(agentId)
+ : null;
+ return name == null ? step.step! : '${step.step} ($name)';
}
/// A linked task's state: its work's status while it has no checks; else a
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index a1348c7f1..c804ec018 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -300,6 +300,7 @@ class SuperTabConversation {
),
cards = SuperTabCards.fromJson(row['cards']),
reviewOf = row['reviewOf'] as String?,
+ step = row['step'] as String?,
brief = _text(row, 'brief'),
task = row['task'] is Map
? SuperTabTask.fromJson(superTabMap(row['task']))
@@ -367,6 +368,11 @@ class SuperTabConversation {
/// A review group's reviewed group; null for any other conversation.
final String? reviewOf;
+
+ /// A step of the task [reviewOf] names, by the name its project's
+ /// instructions give it (task steps design); null for a task, and for a
+ /// linked task opened before steps.
+ final String? step;
final int lastMessageSequence;
/// Its newest message in the main stream: a reply only in its thread
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index b9bca943b..63cd7964a 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -29,6 +29,8 @@ import 'swarm_chat_menu.dart';
import 'swarm_file_links.dart';
import 'swarm_choices.dart';
import 'swarm_conversation.dart';
+import 'linked_tasks.dart' show superTabIsStep;
+import 'task_steps.dart';
import 'swarm_face.dart';
import 'swarm_file_picker.dart';
import 'swarm_outgoing_files.dart';
@@ -607,6 +609,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
void _see() {
final session = _session, c = _conversation;
if (session == null || c == null) return;
+ _syncSteps(c);
if (_ownerUnknown && c.reader.snapshot != null) {
_ownerUnknown = false;
_unreadLine = swarmIsOwnBuddyChat(c.reader, widget.conversationId);
@@ -648,6 +651,12 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
c.reader.removeListener(_guardVoice);
c.dispose();
}
+ for (final step in _steps.values) {
+ step
+ ..removeListener(_stepsMoved)
+ ..dispose();
+ }
+ _steps.clear();
if (_buddy != widget.buddy) _buddy?.dispose();
_buddy = null;
_rows.clear();
@@ -1401,8 +1410,47 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
person.chosenUsername ?? person.email.split('@').first: person.email,
};
+ /// The open task's steps, each read on its own, merged into its chat (task
+ /// steps design): a step keeps its own conversation.
+ final _steps = <String, SwarmConversation>{};
+
+ /// The merged chat, the same list while no row changed, so the timeline is
+ /// not made again on every build (final review, minor 8).
+ final _merge = SuperTabStepsMerge();
+
+ void _stepsMoved() {
+ if (mounted) setState(() {});
+ }
+
+ /// Opens a reader for each step the task has now, and closes those it no
+ /// longer has.
+ void _syncSteps(SwarmConversation c) {
+ final snapshot = c.reader.snapshot;
+ final task = snapshot?.conversation(c.id);
+ final wanted = snapshot == null || task == null
+ ? const <String>{}
+ : {for (final step in superTabStepsOf(snapshot, task)) step.id};
+ for (final id in [..._steps.keys]) {
+ if (wanted.contains(id)) continue;
+ _steps.remove(id)!
+ ..removeListener(_stepsMoved)
+ ..dispose();
+ }
+ for (final id in wanted) {
+ if (_steps.containsKey(id)) continue;
+ final step = _steps[id] = SwarmConversation(c.reader, id, shown: false)
+ ..addListener(_stepsMoved);
+ unawaited(step.load());
+ }
+ }
+
String _nameOf(SwarmConversation c, SuperTabMessage m) {
- final name = c.reader.snapshot?.authorName(m) ?? m.authorName;
+ final named = c.reader.snapshot?.authorName(m) ?? m.authorName;
+ // A step's row in its task's chat names its step (task steps design).
+ final group = c.reader.snapshot?.conversation(m.conversationId);
+ final name = group != null && superTabIsStep(group)
+ ? '$named · ${group.step}'
+ : named;
if (!swarmIsPmLine(c.reader, m)) return name;
// The coordinator's own badge, whatever its role is called.
final badge = c.reader.snapshot?.roleOf(m.authorId)?.badge ?? 'PM';
@@ -1508,8 +1556,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
}
}
final snapshot = c.reader.snapshot;
- // A reply only in its thread shows there alone.
- final stream = c.stream;
+ // A reply only in its thread shows there alone. A task's steps' rows are
+ // merged in by time (task steps design).
+ final stream = _steps.isEmpty
+ ? c.stream
+ : _merge.of(c.stream, {
+ for (final MapEntry(:key, :value) in _steps.entries)
+ key: value.stream,
+ });
final answered = answeredPromptAlerts(
stream,
(agentId) => snapshot?.agent(agentId),
diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dart
index cd7ed666b..7c0f7cdff 100644
--- a/mobile/lib/swarm/swarm_project_page.dart
+++ b/mobile/lib/swarm/swarm_project_page.dart
@@ -13,6 +13,7 @@ import 'package:harness_mobile/shared/widgets/skeleton.dart';
import 'package:harness_mobile/shared/widgets/touch_target.dart';
import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+import 'linked_tasks.dart';
import 'model.dart';
import 'swarm_buddy.dart';
import 'swarm_buddy_chat.dart';
@@ -50,7 +51,7 @@ swarmProjectWork(
SwarmBuddies buddies = SwarmBuddies.none,
}) {
final work =
- snapshot.conversations
+ superTabListedWork(snapshot.conversations)
.where(
(g) =>
g.projectId == project.id &&
diff --git a/mobile/lib/swarm/task_steps.dart b/mobile/lib/swarm/task_steps.dart
new file mode 100644
index 000000000..23f60c552
--- /dev/null
+++ b/mobile/lib/swarm/task_steps.dart
@@ -0,0 +1,70 @@
+import 'linked_tasks.dart';
+import 'model.dart';
+
+// Kept byte-identical on Desktop (lib/super_tabs/task_steps.dart) and the
+// phone (lib/swarm/task_steps.dart): mobile/test/swarm/desktop_parity_test.dart.
+
+/// [task]'s steps, by number (task steps design): each keeps its own
+/// conversation, shown inside its task. An open task shows those not archived;
+/// an archived one keeps the steps archived with it, and their rows.
+List<SuperTabConversation> superTabStepsOf(
+ SuperTabSnapshot snapshot,
+ SuperTabConversation task,
+) {
+ final steps = [
+ for (final g in snapshot.conversations)
+ if (superTabIsStep(g) &&
+ g.reviewOf == task.id &&
+ g.projectId == task.projectId &&
+ (task.archived || !g.archived))
+ g,
+ ];
+ int order(SuperTabConversation g) => g.number ?? 1 << 30;
+ steps.sort((a, b) {
+ final byNumber = order(a).compareTo(order(b));
+ return byNumber != 0 ? byNumber : a.id.compareTo(b.id);
+ });
+ return steps;
+}
+
+/// [task]'s rows with its steps' rows ([steps], by step conversation id)
+/// merged in by when they were written, then by id. Each conversation numbers
+/// its own messages, so sequences do not compare across them.
+List<SuperTabMessage> superTabMergeSteps(
+ List<SuperTabMessage> task,
+ Map<String, List<SuperTabMessage>> steps,
+) {
+ final all = [...task, for (final rows in steps.values) ...rows];
+ if (steps.isEmpty) return all;
+ final zero = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
+ all.sort((a, b) {
+ final byTime = (a.createdAt ?? zero).compareTo(b.createdAt ?? zero);
+ return byTime != 0 ? byTime : a.id.compareTo(b.id);
+ });
+ return all;
+}
+
+/// The last merge of a task's chat, kept while its rows are the same lists:
+/// a chat drawn again with nothing new is not sorted again (final review,
+/// minor 8).
+class SuperTabStepsMerge {
+ List<SuperTabMessage>? _task;
+ Map<String, List<SuperTabMessage>> _steps = const {};
+ List<SuperTabMessage> _rows = const [];
+
+ List<SuperTabMessage> of(
+ List<SuperTabMessage> task,
+ Map<String, List<SuperTabMessage>> steps,
+ ) {
+ final same =
+ identical(task, _task) &&
+ steps.length == _steps.length &&
+ steps.entries.every((e) => identical(_steps[e.key], e.value));
+ if (!same) {
+ _task = task;
+ _steps = Map.of(steps);
+ _rows = List.unmodifiable(superTabMergeSteps(task, steps));
+ }
+ return _rows;
+ }
+}
diff --git a/mobile/test/swarm/desktop_parity_test.dart b/mobile/test/swarm/desktop_parity_test.dart
index b01e834ba..dacd4fa89 100644
--- a/mobile/test/swarm/desktop_parity_test.dart
+++ b/mobile/test/swarm/desktop_parity_test.dart
@@ -20,6 +20,8 @@ const _copies = {
// reader has no copy here.
'lib/swarm/live_card_model.dart': 'lib/super_tabs/live_card_model.dart',
'lib/swarm/linked_tasks.dart': 'lib/super_tabs/linked_tasks.dart',
+ // Task steps design: a task's steps and its merged chat.
+ 'lib/swarm/task_steps.dart': 'lib/super_tabs/task_steps.dart',
'lib/swarm/instructions_model.dart': 'lib/super_tabs/instructions_model.dart',
};
diff --git a/mobile/test/swarm/swarm_task_steps_chat_test.dart b/mobile/test/swarm/swarm_task_steps_chat_test.dart
new file mode 100644
index 000000000..2a7ecc537
--- /dev/null
+++ b/mobile/test/swarm/swarm_task_steps_chat_test.dart
@@ -0,0 +1,117 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Task steps design: a task's chat on the phone shows its steps' rows by
+/// time, each with its step's name beside the author, as on Desktop.
+void main() {
+ Map<String, dynamic> said(
+ String id,
+ String conversation,
+ int minute,
+ String author,
+ ) => {
+ 'id': id,
+ 'conversationId': conversation,
+ 'text': 'Row $id.',
+ 'sequence': minute,
+ 'author': {'kind': 'agent', 'id': author, 'name': author},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 11, 2, 9, minute).toIso8601String(),
+ };
+
+ testWidgets("a task's chat shows its steps' rows with the step's name", (
+ tester,
+ ) async {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData(
+ 'task',
+ title: 'Fix login',
+ number: 12,
+ lastMessageSequence: 2,
+ status: 'working',
+ workerId: 'agent-dev',
+ ),
+ {
+ ...groupData(
+ 'review',
+ title: 'Review',
+ number: 13,
+ lastMessageSequence: 1,
+ status: 'working',
+ workerId: 'agent-rev',
+ ),
+ 'reviewOf': 'task',
+ 'step': 'Review',
+ },
+ ],
+ agents: [
+ agent('agent-dev', displayName: 'Dev'),
+ agent('agent-rev', displayName: 'Nova'),
+ ],
+ ),
+ 'members': [part(me, 1, person(me))],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/task/messages'] = (_) => {
+ 'messages': [
+ said('t2', 'task', 10, 'agent-dev'),
+ said('t1', 'task', 1, 'agent-dev'),
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/review/messages'] = (_) => {
+ 'messages': [said('s1', 'review', 5, 'agent-rev')],
+ 'next': null,
+ };
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ upload: refuseSwarmUpload,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'task'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Row s1.'), findsOneWidget);
+ expect(find.textContaining('Nova · Review'), findsOneWidget);
+ double y(String text) => tester.getTopLeft(find.textContaining(text)).dy;
+ expect(y('Row t1.') < y('Row s1.') && y('Row s1.') < y('Row t2.'), isTrue);
+ });
+}
diff --git a/mobile/test/swarm/swarm_task_steps_test.dart b/mobile/test/swarm/swarm_task_steps_test.dart
new file mode 100644
index 000000000..067a467e1
--- /dev/null
+++ b/mobile/test/swarm/swarm_task_steps_test.dart
@@ -0,0 +1,60 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/linked_tasks.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/parts.dart';
+import 'package:harness_mobile/swarm/swarm_project_page.dart';
+
+import 'swarm_fixture.dart';
+
+/// Task steps design (Ken, 2026-11-02: one pull request showed as three
+/// tasks): a step sits on its task's row, not in the project's list; a linked
+/// task from before steps is listed as before.
+void main() {
+ SuperTabSnapshot swarm(List<Map<String, dynamic>> groups) =>
+ SuperTabSnapshot.fromJson(
+ SuperTabParts.firstLoad(
+ firstLoad(
+ agents: [agent('a-dev', displayName: 'Dev')],
+ groups: groups,
+ ),
+ ).state,
+ );
+
+ test('the project list hides steps and keeps old linked tasks', () {
+ final snapshot = swarm([
+ groupData(
+ 'task',
+ title: 'Fix login',
+ number: 12,
+ status: 'working',
+ workerId: 'a-dev',
+ ),
+ {
+ ...groupData(
+ 'step',
+ title: 'Review',
+ number: 13,
+ status: 'working',
+ workerId: 'a-dev',
+ ),
+ 'reviewOf': 'task',
+ 'step': 'Review',
+ },
+ {
+ ...groupData('old', title: 'Review PR 9', number: 9),
+ 'reviewOf': 'task',
+ },
+ ]);
+ final work = swarmProjectWork(snapshot, snapshot.projects.single);
+ expect(work.active.map((g) => g.id), containsAll(['task', 'old']));
+ expect(
+ [...work.active, ...work.older].map((g) => g.id),
+ isNot(contains('step')),
+ );
+ expect(superTabIsStep(snapshot.conversation('step')!), isTrue);
+ expect(
+ superTabLinkedLine(snapshot, snapshot.conversation('task')!),
+ '#9 Review PR 9: not started · Review (Dev): working',
+ );
+ });
+}