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.

Fix the remaining v3 flow audit findings (#4252) (#3478)

0xken159ab16b002d71
diff --git a/backend/src/superTabs/agentNew.test.ts b/backend/src/superTabs/agentNew.test.ts
index 128ef33e4..99b0a4b5c 100644
--- a/backend/src/superTabs/agentNew.test.ts
+++ b/backend/src/superTabs/agentNew.test.ts
@@ -124,6 +124,12 @@ describe('a Regular agent\'s chat', () => {
f.run(say(f.chat, 'Hello'), { kind: 'agent', agentId: f.agentId, machineOwnerId: 'mate' })
})
+ // Task #4252 (audit 29): it is a talk with its person, as a Buddy's is, where a short reply is the answer.
+ it('takes the agent\'s short reply to its person, which a task would refuse as only an acknowledgement', () => {
+ const f = running()
+ expect(code(() => f.run(say(f.chat, 'Thanks!'), { kind: 'agent', agentId: f.agentId, machineOwnerId: 'mate' }))).toBeNull()
+ })
+
it('is read and written by nobody else: not the Swarm\'s owner, nor another agent', () => {
const f = running()
expect(code(() => f.run(say(f.chat, 'Peeking'), owner))).toBe('NOT_FOUND')
@@ -152,6 +158,48 @@ describe('joining by bringing your own agent', () => {
})
})
+// Task #4252 (audit 12): join, Bring agent, then + New agent before the Buddy settles. Desktop lists the computer first.
+describe('listing your computer while your Buddy is starting there', () => {
+ const contribute = (machineId: string) => ({ type: 'machine.contribute', machineId, name: machineId, cwd: '/home/mate/swarm', scope: 'swarm',
+ engines: ['claude', 'codex'], maxAgents: 2 }) as Command
+ const configuration = { engine: 'codex' as const, model: 'gpt-6.1-sol', effort: 'high', contextWindow: null, engineVersion: null }
+
+ it('lists it, and the Buddy still starts there', () => {
+ const f = swarm()
+ const made = f.run({ type: 'buddy.create', machineId: 'mate-laptop', engine: 'codex',
+ setup: { name: 'Mate laptop', cwd: '/home/mate/swarm', engines: ['codex'] } } as Command, mate, own('mate'))
+ const startId = made.result.startId as string
+ f.run(contribute('mate-laptop'), mate, own('mate'))
+ const listed = f.state.machines!.find(m => m.machineId === 'mate-laptop')!
+ expect(listed.buddyOnly).toBeUndefined()
+ expect(f.state.starts!.find(s => s.id === startId)!.poolGeneration).toBe(listed.generation)
+ listed.observation = reading // its host's next report
+ f.run({ type: 'agent.startDispatch', startId }, mate, own('mate'))
+ expect(f.run({ type: 'agent.started', startId, harnessId: 'h-buddy', configuration }, mate, own('mate')).result.agentId).toBeTruthy()
+ })
+
+ it('is still refused while any other start is pending there', () => {
+ const f = swarm()
+ f.add({ kind: 'regular', name: 'Ada' })
+ expect(code(() => f.run(contribute('mate-mac'), mate, own('mate')))).toBe('STARTS_PENDING')
+ })
+})
+
+// Task #4252 (audit 15): leave with the host online, get invited again, then Bring agent before the host reports its cleanup.
+describe('bringing an agent after leaving and rejoining', () => {
+ it('says the computer is finishing its cleanup, not that its contribution was withdrawn', () => {
+ const f = swarm()
+ f.run({ type: 'member.remove', userId: 'mate' }, mate)
+ const invited = f.run({ type: 'invite.create', email: mate.email, role: 'collaborator', conversationId: 'lead' }, owner)
+ f.run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, mate)
+ let refusal: unknown
+ try {
+ f.run({ type: 'buddy.create', machineId: 'mate-mac', engine: 'codex', setup: { name: 'mate-mac', cwd: '/swarm', engines: ['codex'] } } as Command, mate, own('mate'))
+ } catch (error) { refusal = error }
+ expect(refusal).toMatchObject({ code: 'MACHINE_CLEANING', message: expect.stringContaining('cleaning up') })
+ })
+})
+
// A host from before Regular agents would launch one as a project's agent, in a project folder it does not have: the start is
// listed apart, and a computer whose host cannot run one is told to update instead.
describe('a Regular agent\'s start on its computer', () => {
@@ -173,6 +221,18 @@ describe('a Regular agent\'s start on its computer', () => {
expect(code(() => f.add({ kind: 'regular', name: 'Ada' }))).toBe('HOST_OUTDATED')
expect(f.state.starts ?? []).toEqual([])
})
+
+ // Task #4252 (audit 11): Desktop lists a computer and creates its first agent at once, before the host has reported.
+ it('on a computer just listed, with no reading yet, says it is connecting rather than to update it', () => {
+ const f = swarm()
+ delete f.state.machines!.find(m => m.machineId === 'mate-mac')!.observation
+ for (const kind of [{ kind: 'regular', name: 'Ada' }, { kind: 'pm', projectName: 'Docs site' }]) {
+ let refusal: unknown
+ try { f.add(kind) } catch (error) { refusal = error }
+ expect(refusal).toMatchObject({ code: 'HOST_CONNECTING', message: expect.stringContaining('connecting') })
+ }
+ expect(f.state.starts ?? []).toEqual([])
+ })
})
// Task #4196 (anh Dee 11-07): + New agent opens Cmd-N, which starts the agent on the person's own computer at once. A Member's
diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.ts
index dde11628d..40350a62b 100644
--- a/backend/src/superTabs/buddies.test.ts
+++ b/backend/src/superTabs/buddies.test.ts
@@ -872,7 +872,7 @@ describe('a Buddy\'s proposal to the PM', () => {
})
// River, 11-04 (task #2926): proposals answered before threads, or opened as tasks without the link, still read as open.
- it('is closed with a reason by its project\'s PM or a person in the project, posting nothing, and by nobody else', () => {
+ it('is closed with a reason by its project\'s PM or a person in the project, posting only its person\'s notice, and by nobody else', () => {
const { f, propose } = asked()
const root = propose().messages[0]!
const context = { proposal: { id: root.id, conversationId: f.app.conversationId, author: root.author, source: root.source as Record<string, unknown> } }
@@ -880,7 +880,9 @@ describe('a Buddy\'s proposal to the PM', () => {
f.run({ type: 'proposal.close', projectId: f.app.projectId, messageId, reason: ' Built in #2901 ' }, actor, loaded)
const closed = close(agentActor(f.pm))
expect(closed.closedProposal).toEqual({ messageId: root.id, conversationId: f.app.conversationId, reason: 'Built in #2901' })
- expect(closed.messages).toEqual([])
+ // Nothing in the project's chat: only the notice to its person (task #4252).
+ expect(closed.messages.map(m => m.source?.kind)).toEqual(['proposal-notice'])
+ expect(closed.messages.some(m => m.conversationId === f.app.conversationId)).toBe(false)
expect(close(peer).closedProposal).toMatchObject({ messageId: root.id })
const webPm = group(f, f.web.conversationId).leadId!
for (const actor of [agentActor('buddy'), agentActor(webPm)]) expect(() => close(actor)).toThrow()
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 88fa7b110..3bf50a7c4 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,6 +1,6 @@
import { authorizeTaskApproval, pendingTaskApproval, personalApprovalCommand, rejectTaskApproval, reopenTaskApproval, REQUESTER_LEFT, requireTaskApproval, stageTaskApproval, undecidedProposal } from './taskApproval.js'
import type { PullRequestFilesRead } from './pullRequestFiles.js'
-import { legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'
+import { legacyProposalId, migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalNotices, proposalRoot, type ProposalRecord } from './proposalCards.js'
import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'
import { linesOf } from './statusCard.js'
import { applyPushOrigin, barredFromTeamWritten, failPushUnknown, failTeamWritten, mainAccountMembers, markTeamWritten, mayName, ownersOwnAgent, ownersOwnMachine, requireTeamWrittenAccount, requireTeamWrittenMachine, stepMark, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
@@ -1905,11 +1905,13 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
/** Every check work.assign makes before [worker] takes [group]'s work, throwing its refusal; nothing changes here, so a
- * caller trying candidates in turn (openReviewSteps) catches the refusal and tries the next. */
+ * caller trying candidates in turn (openReviewSteps) catches the refusal and tries the next. A [suggestion] (task.suggest,
+ * task.approve) checks only that it may ever take it: whether it is free now (launching, moving, busy) is the assignment's to
+ * check, so a person's consent is not refused for it (task #4252). */
const assignRefusal = (group: Conversation, worker: Agent, suggestion = false) => {
if (!suggestion) requireTaskApproval(group, worker.id)
if (!suggestion && undecidedProposal(group)) fail('PROPOSAL_UNDECIDED', 'The PM must accept or reshape this proposal before assigning work.', 409)
- if (state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === worker.machineId && s.harnessId === worker.harnessId)) {
+ if (!suggestion && state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === worker.machineId && s.harnessId === worker.harnessId)) {
fail('START_PENDING', 'Wait for the host to finish this agent’s launch and model selection.')
}
if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
@@ -1919,7 +1921,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// task is handed on (closedAgents.ts removeClosedAgents). Without a task it leaves on its machine's next report.
// A crew member on its way to another machine takes work once there; an asleep one wakes for it, in place (crewKeep.ts),
// so its session is not closed (assignTo wakes it).
- if (worker.movedTo) fail('CREW_MOVING', `${worker.displayName ?? worker.name} is moving to another machine. Assign it once it has moved.`)
+ if (!suggestion && worker.movedTo) fail('CREW_MOVING', `${worker.displayName ?? worker.name} is moving to another machine. Assign it once it has moved.`)
// The project's machine rules (machineRules.ts), for an assignment and for the review steps a Ready hands out alike.
refuseByMachineRules(context, { machineId: worker.machineId, engine: worker.configuration.engine, review: isReview(group) })
if (!worker.asleep && sessionClosed(state, worker, context.now)) {
@@ -1945,7 +1947,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A Team account's agent keeps what it holds and takes nothing new (task #4120); it is stopped after the release.
if (onTeamAccount(state, worker)) failTeamWork(TEAM_ACCOUNTS_GONE)
// A handed task does not occupy its Engineer (#3399 handed.ts): it may take this.
- if (state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
+ if (!suggestion && state.conversations.some(c => occupiesAgent(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
}
/** [worker] takes [group]'s work as assignment [assignmentId], after assignRefusal let it: what work.assign writes, and its
* brief to the worker. */
@@ -2603,7 +2605,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
effects.messages.push({ id: stableId(operationId, leadChat), conversationId: leadChat, author: sender, replyTo: null, recipients: [], source: SYSTEM_ROW,
text: `${[...names].join(', ')} never started and will not start now.` })
}
- if (state.starts?.some(s => s.request.machineId === command.machineId && (!s.harnessId || (s.poolGeneration && !s.poolSettled)) && !s.error)) fail('STARTS_PENDING', 'Reconcile pending starts before changing this contribution.')
+ const pendingHere = state.starts?.filter(s => s.request.machineId === command.machineId && (!s.harnessId || (s.poolGeneration && !s.poolSettled)) && !s.error) ?? []
+ // Its person's own Buddy starting on its Buddy-only record moves with it to the listed one (task #4252): same computer,
+ // person and account, so + New agent right after Bring agent is not refused until that Buddy settles.
+ const buddyOnlyHere = state.machines.some(m => m.machineId === command.machineId && m.buddyOnly && m.contributorId === actor.userId)
+ const carried = buddyOnlyHere ? pendingHere.filter(s => s.request.buddyOf?.personId === actor.userId && s.contributorId === actor.userId) : []
+ if (pendingHere.length > carried.length) fail('STARTS_PENDING', 'Reconcile pending starts before changing this contribution.')
// Saving settings sends the whole contribution again; only machine.pause changes its pause (review of #2084).
const paused = mac?.paused ?? state.machines.find(m => m.machineId === command.machineId)?.paused ?? false
// Added as its person joined (Desktop's join): teammates' work only through its Harness Team account, for as long as
@@ -2642,6 +2649,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...(previous?.machineSuspension ? { machineSuspension: previous.machineSuspension } : {}),
...(previous?.engineSuspensions ? { engineSuspensions: previous.engineSuspensions } : {}),
...(previous?.observation ? { observation: previous.observation } : {}) })
+ for (const start of carried) if (start.poolGeneration) start.poolGeneration = operationId
// A Mac given other slots or a new name gives its team account the same, and its pause; its own folder, engines and grant stay.
const added = state.machines.at(-1)!
for (const team of teamPoolsOf(state, added)) if (!team.removal) {
@@ -3551,6 +3559,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (mirror?.proposal && !mirror.proposal.mergedInto) {
mirror.archived = true
mirror.proposal.decision = { kind: 'no', reason: command.reason, at: context.now, by: sender.id }
+ // Its person hears it through their Buddy, as a board decision tells them (proposalCards.ts), unless they closed it.
+ const card = mirror as Conversation & { proposal: ProposalRecord }
+ effects.messages.push(...proposalNotices(state, card, 'decided', `${mirror.title}: no. ${command.reason}`, sender, operationId,
+ card.proposal.senders.filter(s => actor.kind !== 'person' || s.personId !== actor.userId)))
}
effects.closedProposal = { messageId, conversationId: project.leadConversationId, reason: command.reason }
result.proposalId = messageId
@@ -3755,6 +3767,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// A Buddy-only record is not the computer in the Swarm: its person adds it first (Desktop does, with no screen).
const pool = state.machines?.find(m => m.machineId === command.machineId && m.contributorId === me.id && !m.buddyOnly && !m.removal)
?? fail('MACHINE_NOT_LISTED', 'Add this computer to the Swarm first.', 403)
+ // Just listed, it has not reported yet: neither outdated nor offline (task #4252).
+ if (!pool.observation) fail('HOST_CONNECTING', `${pool.name ?? 'Your computer'} is still connecting to the Swarm. Try again in a moment.`, 409)
if (command.kind === 'pm') {
const projectName = command.projectName ?? fail('PROJECT_NAME_REQUIRED', 'Name the project its PM starts.', 400)
const project = createProject(me.id, projectName, 'public', '', 'full')
@@ -4404,8 +4418,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const attachments = ids.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))
if (!command.text && !attachments.length) fail('TEXT_REQUIRED', 'Write a message or attach a file.', 400)
// An agent's post that says nothing beyond an acknowledgement is refused: a reaction acknowledges (task #3391). Never a
- // person's, a note to itself, a post with a file or a tag, or a Buddy's talk with its person.
- if (actor.kind === 'agent' && !command.agentOnly && !attachments.length && !command.mentions?.length && !isBuddyChat(group) && isAcknowledgement(command.text)) {
+ // person's, a note to itself, a post with a file or a tag, or a Buddy's or a Regular agent's talk with its person.
+ if (actor.kind === 'agent' && !command.agentOnly && !attachments.length && !command.mentions?.length && !isBuddyChat(group)
+ && group.kind !== 'agent-chat' && isAcknowledgement(command.text)) {
fail('ACK_ONLY', ACK_ONLY_HINT, 400)
}
// A voice message is its clip alone, and its words are its text: what agents, search and older apps read (voiceMessages.ts).
@@ -4756,8 +4771,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
// This decision releases the gate; the ordinary work.assign path alone launches work, with all of the
// store's global session, repository, machine and account checks. Never introduce a second assignment path here.
- if (command.type === 'task.approve' && approval.suggestedAgentId)
+ if (command.type === 'task.approve' && approval.suggestedAgentId) {
+ if (!state.agents.some(a => a.id === approval.suggestedAgentId)) {
+ fail('SUGGESTED_AGENT_GONE', 'The agent suggested for this task is gone. Ask the PM to suggest another.', 409)
+ }
assignRefusal(group, readAgent(state, actor, approval.suggestedAgentId), true)
+ }
message(group.id, command.type === 'task.approve' ? 'Approved. Prepare and route this task using its chosen agent, if any.' : `Rejected: ${command.reason}`,
group.leadId ? [group.leadId] : [], null, { kind: 'task-approval', state: approval.state })
}
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 62e787e47..409f12a32 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -631,6 +631,10 @@ export function machineContribution(state: SuperTabState, machineId: string) {
const pool = state.machines?.find(m => m.machineId === machineId)
if (!pool) return null
const contributor = person(state, pool.contributorId)
+ // Its person left and came back while their host still removes what the Swarm had there (task #4252): that ends by itself.
+ if (contributor.role !== 'viewer' && contributor.generation !== pool.membershipGeneration && pool.removal) {
+ fail('MACHINE_CLEANING', `${pool.name ?? 'This machine'} is still cleaning up after its person left the Swarm. Try again once that finishes, in a minute or two.`)
+ }
if (contributor.role === 'viewer' || contributor.generation !== pool.membershipGeneration) {
fail('CONTRIBUTION_REVOKED', 'This machine contribution was withdrawn.', 403)
}
diff --git a/backend/src/superTabs/read/personalTasks.test.ts b/backend/src/superTabs/read/personalTasks.test.ts
index 0ee145229..f39bddb3b 100644
--- a/backend/src/superTabs/read/personalTasks.test.ts
+++ b/backend/src/superTabs/read/personalTasks.test.ts
@@ -129,6 +129,16 @@ describe('personal Tasks summaries', () => {
delete row.data!.pullRequestUrls
expect(personalTasksFor([row], s.view(), peer)!.upserts[0]).not.toHaveProperty('pullRequestUrl')
})
+ it('keeps a proposal the PM declined, as rejected with its reason; a merged one still leaves (task #4252, audit 3 and 18)', () => {
+ const s = scene(), row = s.stored.groups.find(g => g.key === s.f.web)!
+ const generation = s.f.state.people.find(p => p.id === peer.userId)!.generation
+ const proposal = { version: 1, text: 'Keep drafts', goal: 'Drafts', why: 'Loss', doneWhen: 'Returns', evidence: ['Repro'], priority: 'P2',
+ createdAt: NOW, questions: [], senders: [{ personId: peer.userId, generation }], decision: { kind: 'no', reason: 'Out of scope', at: NOW, by: 'pm' } }
+ const declined = { ...row, data: { ...row.data!, assignment: null, taskApproval: undefined, archived: true, proposal } } as typeof row
+ expect(personalTasksFor([declined], s.view(), peer)!.upserts).toEqual([expect.objectContaining({ id: row.key, status: 'rejected', reason: 'Out of scope' })])
+ const merged = { ...declined, data: { ...declined.data!, proposal: { ...proposal, mergedInto: 'other' } } } as typeof row
+ expect(personalTasksFor([merged], s.view(), peer)).toMatchObject({ upserts: [], removed: [row.key] })
+ })
it('never leaks a hidden project, private chat, hidden agent or stale membership proposal', () => {
const s = scene(), row = s.stored.groups.find(g => g.key === s.f.secretGroup)!
const hidden = s.f.state.agents.find(a => a.projectId === s.f.secret)
diff --git a/backend/src/superTabs/read/personalTasks.ts b/backend/src/superTabs/read/personalTasks.ts
index 149b96b49..9594cfdd7 100644
--- a/backend/src/superTabs/read/personalTasks.ts
+++ b/backend/src/superTabs/read/personalTasks.ts
@@ -81,14 +81,16 @@ function summary(part: Part, reader: Reader): PersonalTask | 'gone' | null {
const agent = view.parts.agents.find(a => a.key === worker)?.data
const asker = group.requesterId ? view.state.people.find(p => p.id === group.requesterId) : undefined
const askerName = asker && (asker.name ?? asker.username)
- const status = approval?.state === 'proposal' || approval?.state === 'rejected' ? approval.state
+ // A proposal the PM declined shows as rejected, with its reason (task #4252).
+ const declined = group.proposal?.decision?.kind === 'no'
+ const status = declined ? 'rejected' : approval?.state === 'proposal' || approval?.state === 'rejected' ? approval.state
: group.assignment?.status ?? (group.proposal && !['accept', 'reshape'].includes(group.proposal.decision?.kind ?? '') ? 'proposal' : 'planned')
const pullRequestUrl = group.pullRequestUrls?.at(-1)
return { id: group.id, version: part.version, at: activityAt(part as Part<GroupData>), projectId: project.id, projectName: project.name,
title: group.title, status, suggested: !group.assignment && !!approval?.suggestedAgentId, canApprove: approval?.state === 'proposal' && asked && !undecidedProposal(group),
agent: agent ? { id: agent.id, name: agent.displayName ?? agent.name, ...agent.avatar ? { avatar: agent.avatar } : {} } : null,
requester: asker ? { id: asker.id, ...askerName ? { name: askerName } : {}, ...asker.avatar ? { avatar: asker.avatar } : {} } : null,
- ...pullRequestUrl ? { pullRequestUrl } : {}, ...approval?.reason ? { reason: approval.reason } : {} }
+ ...pullRequestUrl ? { pullRequestUrl } : {}, ...declined ? { reason: group.proposal!.decision!.reason } : approval?.reason ? { reason: approval.reason } : {} }
}
const newestFirst = (a: PersonalTask, b: PersonalTask) => b.at - a.at || a.id.localeCompare(b.id)
diff --git a/backend/src/superTabs/taskApproval.test.ts b/backend/src/superTabs/taskApproval.test.ts
index cbcfef2e4..c7e8f5003 100644
--- a/backend/src/superTabs/taskApproval.test.ts
+++ b/backend/src/superTabs/taskApproval.test.ts
@@ -195,12 +195,30 @@ describe('personal approval enforced before work', () => {
})
it('refuses invalid suggestions and rechecks a changed agent atomically on approval', () => {
const f = fixture(); f.mode('review'); const id = f.create()
- for (const agentId of [f.buddy, f.worker, 'missing']) expect(() => f.runCommand({ type: 'task.suggest', conversationId: id, agentId })).toThrow()
+ for (const agentId of [f.buddy, 'missing']) expect(() => f.runCommand({ type: 'task.suggest', conversationId: id, agentId })).toThrow()
+ // A busy agent may be suggested: the task waits for it, and its assignment checks it is free (task #4252).
+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.worker })
f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate })
f.state.agents.find(a => a.id === f.candidate)!.workDecision = 'stop'
expect(() => f.runCommand({ type: 'task.approve', conversationId: id })).toThrow()
expect(f.card(id)).toMatchObject({ assignment: null, taskApproval: { state: 'proposal' } })
})
+ // Task #4252 (audit 20): Approve is the person's consent to the agent shown; whether it is free is the assignment's to check.
+ it('records approval of a busy suggested agent, and the assignment still waits for it to be free', () => {
+ const f = fixture(); f.mode('review'); const id = f.create()
+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate })
+ f.edit(s => { s.conversations.find(c => c.id === f.web)!.assignment!.agentId = f.candidate })
+ f.runCommand({ type: 'task.approve', conversationId: id })
+ expect(f.card(id).taskApproval?.state).toBe('approved')
+ expect(() => f.runCommand({ type: 'work.assign', conversationId: id, agentId: f.candidate }, f.pm)).toThrow(expect.objectContaining({ code: 'AGENT_BUSY' }))
+ })
+ it('says the suggested agent is gone when it was removed before the approval', () => {
+ const f = fixture(); f.mode('review'); const id = f.create()
+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate })
+ f.edit(s => { s.agents = s.agents.filter(a => a.id !== f.candidate) })
+ expect(() => f.runCommand({ type: 'task.approve', conversationId: id })).toThrow(expect.objectContaining({ code: 'SUGGESTED_AGENT_GONE' }))
+ expect(f.card(id).taskApproval?.state).toBe('proposal')
+ })
it('keeps a legacy proposal’s decision when the PM converts it to a task and refuses a second conversion', () => {
const f = fixture(false); f.mode('review'); const sent = f.propose()
const row = sent.messages.find(m => m.source?.kind === 'buddy-proposal')!
@@ -295,6 +313,17 @@ describe('personal approval enforced before work', () => {
{ proposal: { id: row.id, conversationId: row.conversationId, author: row.author, source: row.source ?? null } })
expect(f.state.conversations.find(c => c.proposal?.legacyMessageId === row.id)?.archived).toBe(true)
})
+ it('tells the person, through their Buddy, that the PM closed their proposal and why (task #4252, audit 18)', () => {
+ const f = fixture(false); const sent = f.propose()
+ const row = sent.messages.find(m => m.source?.kind === 'buddy-proposal')!
+ const closed = f.runCommand({ type: 'proposal.close', projectId: 'lead', messageId: row.id, reason: 'Out of scope' }, f.pm,
+ { proposal: { id: row.id, conversationId: row.conversationId, author: row.author, source: row.source ?? null } })
+ const notice = closed.messages.find(m => m.source?.kind === 'proposal-notice')
+ const mirror = f.state.conversations.find(c => c.proposal?.legacyMessageId === row.id)!
+ // Routed as a board decision's notice is (buddies.ts buddyFor).
+ expect(notice).toMatchObject({ source: { moment: 'decided', cardId: mirror.id } })
+ expect(notice!.text).toContain('Out of scope')
+ })
it('redacts a pasted credential from a rejection before its reason reaches stored parts or messages', () => {
const token = ['sk', 'AbCdEf0123456789'.repeat(3)].join('-') // Synthetic fixture, never a provider credential.
const removed: Parameters<typeof withoutCredentials>[1] = []
diff --git a/cli/hook/statusline.mjs b/cli/hook/statusline.mjs
index 9f0d4292e..8a440c542 100644
--- a/cli/hook/statusline.mjs
+++ b/cli/hook/statusline.mjs
@@ -11,7 +11,7 @@
*
* Claude Code hands its status line command a JSON status on stdin, with the plan's rate limits in it
* (`rate_limits.five_hour` / `seven_day`: `used_percentage` 0-100, `resets_at` in epoch seconds; null for an API key).
- * Those numbers, and nothing else of the status, go to `<data>/quota/claude-<sha256(CLAUDE_CONFIG_DIR)[0..16]>.json`,
+ * Those numbers, and nothing else of the status, go to `<data>/quota/claude-<sha256(reportKey(CLAUDE_CONFIG_DIR))[0..16]>.json`,
* which the daemon reads for the router's quota (lib/quotaReports.ts). Then the person's own command runs with the
* same input and its output is the status line, exactly as without Harness. Nothing in the recording may stop that:
* every error there is swallowed.
@@ -19,8 +19,9 @@
import { spawn } from 'node:child_process'
import { createHash, randomBytes } from 'node:crypto'
-import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
-import { delimiter, dirname, join } from 'node:path'
+import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { delimiter, dirname, join, resolve } from 'node:path'
// Claude Code closes stdin once it has written the status. Should it not, the person's line still shows, a little late.
const INPUT_WAIT_MS = 2000
@@ -65,8 +66,26 @@ function resetSeconds(value) {
function windowOf(value) {
if (!value || typeof value !== 'object') return null
const used = value.used_percentage ?? value.utilization
- if (typeof used !== 'number' || !Number.isFinite(used) || used < 0 || used > 100) return null
- return { used_percentage: used, resets_at: resetSeconds(value.resets_at) }
+ if (typeof used !== 'number' || !Number.isFinite(used) || used < 0) return null
+ // A window Claude Code ran past reads above 100: used up, not unmeasured (#4252).
+ return { used_percentage: Math.min(used, 100), resets_at: resetSeconds(value.resets_at) }
+}
+
+/** The real path, in the case the file system keeps; the path itself while there is none. */
+function realPath(path) {
+ try { return realpathSync.native(path) } catch { return path }
+}
+
+/**
+ * What names the report of a Claude config folder: '' for the default one (unset, or `~/.claude` however written), else
+ * its absolute real path. lib/quotaReports.ts claudeReportKey is the same rule: the daemon reads the folder from its
+ * own launch environment, which may spell it otherwise than this session's shell.
+ */
+function reportKey(configDir) {
+ const dir = configDir?.trim()
+ if (!dir) return ''
+ const key = realPath(resolve(dir))
+ return key === realPath(join(homedir(), '.claude')) ? '' : key
}
function record(input, data) {
@@ -80,7 +99,7 @@ function record(input, data) {
}
if (!Object.keys(windows).length) return
const folder = join(data, 'quota')
- const key = createHash('sha256').update(process.env.CLAUDE_CONFIG_DIR || '').digest('hex').slice(0, 16)
+ const key = createHash('sha256').update(reportKey(process.env.CLAUDE_CONFIG_DIR)).digest('hex').slice(0, 16)
const file = join(folder, `claude-${key}.json`)
try {
const { at, five_hour, seven_day } = JSON.parse(readFileSync(file, 'utf8'))
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 0a4e5086b..04a2d38bb 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1328,7 +1328,7 @@ describe('BackendSocket outbound queue', () => {
{ provider: 'codex', account: null, outcome: 'answered', httpStatus: 200, source: 'cli',
body: { rate_limit: { primary_window: { used_percent: 42, limit_window_seconds: 18_000, reset_at: null } } } },
]
- serveOn(socket, (host) => host.start('usage', (core, ports) => { ports.usage = { read: async () => ({}), stop: () => {} }; return startUsage(core, { codex: async () => codex, now: Date.now, env: {} }) }, fakeCore(), USAGE_FALLBACKS, USAGE_REQUESTS))
+ serveOn(socket, (host) => host.start('usage', (core, ports) => { ports.usage = { read: async () => ({}), stop: () => {} }; return startUsage(core, { codex: async () => codex, now: Date.now, env: async () => ({}) }) }, fakeCore(), USAGE_FALLBACKS, USAGE_REQUESTS))
socket.connect()
const ws = wsMock.instances[0]
ws.open()
@@ -3856,7 +3856,7 @@ describe('the connect burst with no network', () => {
bindAgentList(socket)
// A grid name that never comes, as a grid read that never lands; and a Codex that never answers, asked
// of the usage service beside models.
- serveModels(socket, { account: { privateGridName: () => new Promise<null>(() => {}) } }).start('usage', (core, ports) => { ports.usage = { read: async () => ({}), stop: () => {} }; return startUsage(core, { codex: () => new Promise(() => {}), now: Date.now, env: {} }) }, fakeCore(), USAGE_FALLBACKS, USAGE_REQUESTS)
+ serveModels(socket, { account: { privateGridName: () => new Promise<null>(() => {}) } }).start('usage', (core, ports) => { ports.usage = { read: async () => ({}), stop: () => {} }; return startUsage(core, { codex: () => new Promise(() => {}), now: Date.now, env: async () => ({}) }) }, fakeCore(), USAGE_FALLBACKS, USAGE_REQUESTS)
const frames: Array<Record<string, unknown>> = []
socket.registerLocalClient('local:burst', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })
diff --git a/cli/src/engines/claude/statusLine.spec.ts b/cli/src/engines/claude/statusLine.spec.ts
index 3f48404ba..adbe51338 100644
--- a/cli/src/engines/claude/statusLine.spec.ts
+++ b/cli/src/engines/claude/statusLine.spec.ts
@@ -8,7 +8,7 @@ import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { join, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { env } from '../../config/env.js'
@@ -89,11 +89,36 @@ describe('hook/statusline.mjs', () => {
expect(existsSync(reportPath(data, ''))).toBe(true)
})
+ // One key rule on both sides (lib/quotaReports.ts claudeReportKey, #4252): the daemon reads the folder its launch
+ // environment names, which may spell it otherwise than the shell the session ran in.
+ it('names the default folder after the empty string however it is written', () => {
+ const home = join(root, 'home')
+ for (const dir of [join(home, '.claude'), join(home, '.claude') + sep]) {
+ rmSync(data, { recursive: true, force: true })
+ run(['--data', data], STATUS, { HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: dir })
+ expect(existsSync(reportPath(data, '')), dir).toBe(true)
+ }
+ })
+
+ it('names a moved folder by its real path, so the daemon finds it however either side spells it', () => {
+ mkdirSync(configDir)
+ run(['--data', data], STATUS, { CLAUDE_CONFIG_DIR: configDir + sep })
+ expect(readClaudeReport(data, configDir)?.five_hour).toEqual(STATUS.rate_limits.five_hour)
+ expect(readClaudeReport(data, configDir + sep)?.five_hour).toEqual(STATUS.rate_limits.five_hour)
+ })
+
it('leaves out a window Claude Code did not report, and one whose percentage is not one', () => {
- run(['--data', data], { rate_limits: { five_hour: { used_percentage: 12, resets_at: null }, seven_day: { used_percentage: 140, resets_at: 1 } } })
+ run(['--data', data], { rate_limits: { five_hour: { used_percentage: 12, resets_at: null }, seven_day: { used_percentage: -3, resets_at: 1 } } })
expect(JSON.parse(readFileSync(reportPath(data, configDir), 'utf8'))).toEqual({ v: 1, at: expect.any(Number), five_hour: { used_percentage: 12, resets_at: null } })
})
+ // A window Claude Code ran past reads above 100 (finding 10, #4252): it is used up, and recorded so.
+ it('records a percentage above 100 as 100', () => {
+ run(['--data', data], { rate_limits: { five_hour: { used_percentage: 103, resets_at: 1 }, seven_day: { utilization: 140, resets_at: null } } })
+ expect(JSON.parse(readFileSync(reportPath(data, configDir), 'utf8'))).toEqual({ v: 1, at: expect.any(Number),
+ five_hour: { used_percentage: 100, resets_at: 1 }, seven_day: { used_percentage: 100, resets_at: null } })
+ })
+
// Claude Code 2.1.316's own schema for these windows names them `utilization` with an ISO `resets_at`, where its status
// line docs say `used_percentage` and epoch seconds: either is read, and kept as the report's one shape.
it('reads a window spelled as utilization with an ISO reset time', () => {
diff --git a/cli/src/lib/quotaReports.spec.ts b/cli/src/lib/quotaReports.spec.ts
index 3a30ee701..2a71c4f68 100644
--- a/cli/src/lib/quotaReports.spec.ts
+++ b/cli/src/lib/quotaReports.spec.ts
@@ -1,14 +1,16 @@
import { createHash } from 'node:crypto'
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { homedir, tmpdir } from 'node:os'
+import { join, resolve, sep } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import { accountKey, claudeReportPath, readClaudeReport } from './quotaReports.js'
+import { accountKey, claudeReportKey, claudeReportPath, readClaudeReport } from './quotaReports.js'
let dataDir: string
beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'quota-reports-')) })
afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+const hash = (text: string) => createHash('sha256').update(text).digest('hex').slice(0, 16)
+
const write = (report: unknown, configDir?: string) => {
mkdirSync(join(dataDir, 'quota'), { recursive: true })
writeFileSync(claudeReportPath(dataDir, configDir), typeof report === 'string' ? report : JSON.stringify(report))
@@ -27,13 +29,39 @@ describe('accountKey', () => {
})
})
+// The status line (hook/statusline.mjs) keys the file it writes by the same rule, from the CLAUDE_CONFIG_DIR of the
+// person's own shell; the daemon reads it with whatever spelling its launch environment holds (#4252).
+describe('claudeReportKey', () => {
+ it('is the empty string for the default folder however it is written', () => {
+ const home = join(dataDir, 'home')
+ mkdirSync(join(home, '.claude'), { recursive: true })
+ for (const dir of [undefined, '', ' ', join(home, '.claude'), join(home, '.claude') + sep, `${home}${sep}.${sep}.claude`]) {
+ expect(claudeReportKey(dir, home), String(dir)).toBe('')
+ }
+ expect(claudeReportKey(join(home, '.claude-work'), home)).not.toBe('')
+ })
+
+ it('is the real absolute path of a moved folder, whatever its spelling', () => {
+ const moved = join(dataDir, 'work')
+ mkdirSync(moved)
+ const real = realpathSync.native(moved)
+ for (const dir of [moved, moved + sep, `${moved}${sep}..${sep}work`, ` ${moved} `]) expect(claudeReportKey(dir), dir).toBe(real)
+ if (process.platform !== 'win32') {
+ symlinkSync(moved, join(dataDir, 'link'))
+ expect(claudeReportKey(join(dataDir, 'link'))).toBe(real)
+ }
+ // One not made yet is its absolute path.
+ expect(claudeReportKey(join(dataDir, 'later') + sep)).toBe(join(dataDir, 'later'))
+ })
+})
+
describe('claudeReportPath', () => {
- it('names one file per Claude config folder, by the first 16 hex of its sha256', () => {
- const hash = (text: string) => createHash('sha256').update(text).digest('hex').slice(0, 16)
- expect(claudeReportPath('/data', '/Users/me/.claude-work')).toBe(join('/data', 'quota', `claude-${hash('/Users/me/.claude-work')}.json`))
- // Unset and empty are both the default folder.
+ it('names one file per Claude config folder, by the first 16 hex of the sha256 of its key', () => {
+ expect(claudeReportPath('/data', '/Users/me/.claude-work')).toBe(join('/data', 'quota', `claude-${hash(resolve('/Users/me/.claude-work'))}.json`))
+ // Unset, empty and the default folder however written are one report.
expect(claudeReportPath('/data')).toBe(join('/data', 'quota', `claude-${hash('')}.json`))
- expect(claudeReportPath('/data', '')).toBe(claudeReportPath('/data'))
+ for (const dir of ['', join(homedir(), '.claude'), join(homedir(), '.claude') + sep]) expect(claudeReportPath('/data', dir), dir).toBe(claudeReportPath('/data'))
+ expect(claudeReportPath('/data', '/Users/me/.claude-work/')).toBe(claudeReportPath('/data', '/Users/me/.claude-work'))
})
})
@@ -48,6 +76,16 @@ describe('readClaudeReport', () => {
expect(readClaudeReport(dataDir, '/fixture/work')?.five_hour).toEqual({ used_percentage: 90, resets_at: 1 })
})
+ it('reads a report an older status line wrote under the raw folder name, until one is written under its key', () => {
+ const moved = join(dataDir, 'work')
+ mkdirSync(moved)
+ mkdirSync(join(dataDir, 'quota'), { recursive: true })
+ writeFileSync(join(dataDir, 'quota', `claude-${hash(moved + sep)}.json`), JSON.stringify(report))
+ expect(readClaudeReport(dataDir, moved + sep)?.five_hour).toEqual(report.five_hour)
+ write({ ...report, five_hour: { used_percentage: 50, resets_at: null } }, moved)
+ expect(readClaudeReport(dataDir, moved + sep)?.five_hour).toEqual({ used_percentage: 50, resets_at: null })
+ })
+
it('is null with no report yet', () => {
expect(readClaudeReport(dataDir)).toBeNull()
expect(readClaudeReport(dataDir, '/fixture/never')).toBeNull()
@@ -58,8 +96,14 @@ describe('readClaudeReport', () => {
expect(readClaudeReport(dataDir)).toEqual({ at: 5, seven_day: { used_percentage: 0, resets_at: 9 } })
})
+ // Claude Code reports a window it ran past as more than 100 (finding 10, #4252): that is a used-up window, not a bad one.
+ it('reads a percentage above 100 as 100', () => {
+ write({ ...report, five_hour: { used_percentage: 103, resets_at: 1 } })
+ expect(readClaudeReport(dataDir)?.five_hour).toEqual({ used_percentage: 100, resets_at: 1 })
+ })
+
it('drops a window that is not a measured percentage, and the report when no window is left', () => {
- write({ ...report, five_hour: { used_percentage: 101, resets_at: 1 } })
+ write({ ...report, five_hour: { used_percentage: -1, resets_at: 1 } })
expect(readClaudeReport(dataDir)).toEqual({ at: report.at, seven_day: report.seven_day })
for (const window of [{ used_percentage: -1, resets_at: 1 }, { used_percentage: Number.NaN }, { used_percentage: '5', resets_at: 1 },
{ used_percentage: 5, resets_at: 'soon' }, null, 'full']) {
diff --git a/cli/src/lib/quotaReports.ts b/cli/src/lib/quotaReports.ts
index 92cdd66c8..59616f7ea 100644
--- a/cli/src/lib/quotaReports.ts
+++ b/cli/src/lib/quotaReports.ts
@@ -7,8 +7,9 @@
* read sees a whole file. It holds only percentages, reset times (unix seconds, as Claude Code gives them) and when.
*/
import { createHash } from 'node:crypto'
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
+import { readFileSync, realpathSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join, resolve } from 'node:path'
export type UsageProviderId = 'claude' | 'codex'
@@ -29,15 +30,31 @@ export function accountKey(provider: UsageProviderId, accountId: string): string
export interface ClaudeReportWindow { used_percentage: number; resets_at: number | null }
export interface ClaudeReport { at: number; five_hour?: ClaudeReportWindow; seven_day?: ClaudeReportWindow }
-/** The report for the Claude config folder [configDir] (CLAUDE_CONFIG_DIR); unset and empty are both the default one. */
+/**
+ * What names the report of the Claude config folder [configDir] (CLAUDE_CONFIG_DIR): '' for the default folder, unset
+ * or however it is written, else its absolute real path. The status line (hook/statusline.mjs) carries the same rule:
+ * it reads the folder from the session's shell and the daemon from its launch environment, which may spell one
+ * folder two ways (#4252).
+ */
+export function claudeReportKey(configDir?: string, home = homedir()): string {
+ const dir = configDir?.trim()
+ if (!dir) return ''
+ const key = realPath(resolve(dir))
+ return key === realPath(join(home, '.claude')) ? '' : key
+}
+
+/** The report for the Claude config folder [configDir] (CLAUDE_CONFIG_DIR), by its key (`claudeReportKey`). */
export function claudeReportPath(dataDir: string, configDir?: string): string {
- return join(dataDir, 'quota', `claude-${createHash('sha256').update(configDir ?? '').digest('hex').slice(0, 16)}.json`)
+ return reportFile(dataDir, claudeReportKey(configDir))
}
/** The last report for [configDir], or null when there is none or it is not a version-1 report with a window in it. */
export function readClaudeReport(dataDir: string, configDir?: string): ClaudeReport | null {
let raw: unknown
- try { raw = JSON.parse(readFileSync(claudeReportPath(dataDir, configDir), 'utf8')) } catch { return null }
+ try { raw = JSON.parse(readFileSync(claudeReportPath(dataDir, configDir), 'utf8')) } catch {
+ // A status line from before the key rule named the file after the raw variable. Until 2026-12-07 (30 days).
+ try { raw = JSON.parse(readFileSync(reportFile(dataDir, configDir ?? ''), 'utf8')) } catch { return null }
+ }
const file = record(raw)
if (!file || file.v !== 1 || !finite(file.at)) return null
const five_hour = windowOf(file.five_hour), seven_day = windowOf(file.seven_day)
@@ -47,10 +64,14 @@ export function readClaudeReport(dataDir: string, configDir?: string): ClaudeRep
function windowOf(raw: unknown): ClaudeReportWindow | null {
const w = record(raw)
- if (!w || !finite(w.used_percentage) || w.used_percentage < 0 || w.used_percentage > 100) return null
+ if (!w || !finite(w.used_percentage) || w.used_percentage < 0) return null
if (w.resets_at !== null && w.resets_at !== undefined && !finite(w.resets_at)) return null
- return { used_percentage: w.used_percentage, resets_at: finite(w.resets_at) ? w.resets_at : null }
+ // Above 100 is a window run past, so used up; a status line from before the clamp wrote it as is (#4252).
+ return { used_percentage: Math.min(w.used_percentage, 100), resets_at: finite(w.resets_at) ? w.resets_at : null }
}
+const reportFile = (dataDir: string, key: string) => join(dataDir, 'quota', `claude-${createHash('sha256').update(key).digest('hex').slice(0, 16)}.json`)
+// The native call gives the case the file system keeps (macOS, Windows), so one folder typed two ways is one key.
+const realPath = (path: string) => { try { return realpathSync.native(path) } catch { return path } }
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
const record = (v: unknown): Record<string, unknown> | null => v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null
diff --git a/cli/src/services/handoffProcess.spec.ts b/cli/src/services/handoffProcess.spec.ts
index 90bdafcea..e60d45b1b 100644
--- a/cli/src/services/handoffProcess.spec.ts
+++ b/cli/src/services/handoffProcess.spec.ts
@@ -180,7 +180,9 @@ describe('the handoff in the edge host', () => {
expect(publicationErrors).toEqual([])
expect(readFileSync(join(ws, handed2.file!), 'utf8')).toContain('add a search box')
} finally { rmSync(ws, { recursive: true, force: true }) }
- })
+ // A real git repository and SQLite store: 1.6 s alone, 5.5 s in a full test:core run on a busy Mac (2026-11-07, #4252),
+ // past vitest's 5 s default.
+ }, 20_000)
})
it('refuses malformed read/publication replies and never sends a revoked publication', async () => {
diff --git a/cli/src/services/usage.spec.ts b/cli/src/services/usage.spec.ts
index 6258afd97..155c4cd75 100644
--- a/cli/src/services/usage.spec.ts
+++ b/cli/src/services/usage.spec.ts
@@ -11,6 +11,15 @@ import { usageTarget } from '../lib/agentUsageWire.js'
import { accountKey, claudeReportPath } from '../lib/quotaReports.js'
import type { CodexRateLimits } from '../lib/codexRateLimits.js'
import { quotaOf, quotaUnknownReason } from '../superTabs/capacity.js'
+import { env } from '../config/env.js'
+
+// The person's login shell, as the daemon reads it (lib/loginShellEnv.ts): never a real shell here.
+const shell = vi.hoisted(() => ({ env: {} as NodeJS.ProcessEnv }))
+vi.mock('../lib/loginShellEnv.js', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../lib/loginShellEnv.js')>(),
+ loginShellEnvironment: () => shell.env,
+ warmLoginShellEnvironment: async () => shell.env,
+}))
const ASKER = { local: false, owner: true }
const NOW = Date.parse('2026-11-07T01:00:00Z')
@@ -25,8 +34,8 @@ const STALE_REPORT = 'Claude Code last reported its allowance on this machine mo
const RESET_SINCE = 'Claude Code\'s allowance reset after its last report on this machine: it reports again after its next reply in a session Harness started.'
let dataDir: string
-beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'usage-service-')) })
-afterEach(() => rmSync(dataDir, { recursive: true, force: true }))
+beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'usage-service-')); shell.env = {} })
+afterEach(() => { rmSync(dataDir, { recursive: true, force: true }); vi.unstubAllEnvs() })
/** What the status line (hook/statusline.mjs) writes for [configDir]. */
function report(windows: Record<string, unknown>, configDir?: string, at = NOW - 60_000) {
@@ -35,7 +44,7 @@ function report(windows: Record<string, unknown>, configDir?: string, at = NOW -
}
function usage(over: Partial<UsageDeps> = {}) {
- const deps: UsageDeps = { codex: vi.fn(async () => CODEX), now: () => NOW, env: {}, ...over }
+ const deps: UsageDeps = { codex: vi.fn(async () => CODEX), now: () => NOW, env: async () => ({}), ...over }
return { deps, requests: startUsage(fakeCore({ dataDir }), deps) }
}
@@ -64,8 +73,8 @@ describe('the usage service', () => {
secondary_window: { used_percent: 7, limit_window_seconds: 604_800, reset_at: s('2026-11-12T00:00:00Z') },
} } },
] })
- // The default accounts: the owner's own CODEX_HOME, nothing injected.
- expect(deps.codex).toHaveBeenCalledWith({ codexHome: undefined })
+ // The default accounts: the CODEX_HOME a session launches with, none moved.
+ expect(deps.codex).toHaveBeenCalledWith({ codexHome: env.CODEX_HOME })
// The router reads both, by the windows' own lengths.
expect(quotaOf(reply, 'claude', false)).toMatchObject({ known: true, windows: [
{ name: '5-hour', usedPercent: 23.5, resetsAt: '2026-11-07T04:00:00.000Z' }, { name: 'weekly', usedPercent: 41, resetsAt: null }] })
@@ -73,15 +82,31 @@ describe('the usage service', () => {
{ name: '5-hour', usedPercent: 42 }, { name: 'weekly', usedPercent: 7 }] })
})
- it('usage_read: the default Claude account is the daemon\'s own CLAUDE_CONFIG_DIR, and a window Codex leaves out is left out', async () => {
+ it('usage_read: the default accounts are the folders a session launches with, and a window Codex leaves out is left out', async () => {
report({ seven_day: { used_percentage: 12, resets_at: null } }, '/fixture/claude-own')
- const { requests } = usage({ env: { CLAUDE_CONFIG_DIR: '/fixture/claude-own' },
- codex: async () => ({ ok: true, accountId: null, primary: null, secondary: { usedPercent: 3, windowDurationMins: null, resetsAt: null } }) })
+ const codex = vi.fn(async () => ({ ok: true as const, accountId: null, primary: null, secondary: { usedPercent: 3, windowDurationMins: null, resetsAt: null } }))
+ const { requests } = usage({ env: async () => ({ CLAUDE_CONFIG_DIR: '/fixture/claude-own/', CODEX_HOME: '/fixture/codex-own' }), codex })
expect(await requests.usage_read!({}, ASKER)).toEqual({ providers: [
expect.objectContaining({ provider: 'claude', body: { seven_day: { utilization: 12, resets_at: null } } }),
expect.objectContaining({ provider: 'codex', account: null,
body: { rate_limit: { secondary_window: { used_percent: 3, limit_window_seconds: null, reset_at: null } } } }),
] })
+ expect(codex.mock.calls).toEqual([[{ codexHome: '/fixture/codex-own' }]])
+ })
+
+ // People move CLAUDE_CONFIG_DIR in their shell profile; the daemon, started by the app or launchd, never read it, and
+ // the report the status line wrote under that folder read as "not reported yet" for good (#4252).
+ it('usage_read: the Claude folder the login shell sets outranks the daemon\'s own', async () => {
+ vi.stubEnv('CLAUDE_CONFIG_DIR', '/fixture/claude-daemon')
+ // The default deps read the real clock, so the reports are written now: older than an hour reads as stale (#4217).
+ report({ five_hour: { used_percentage: 1, resets_at: null } }, '/fixture/claude-daemon', Date.now())
+ report({ five_hour: { used_percentage: 77, resets_at: null } }, '/fixture/claude-shell', Date.now())
+ shell.env = { CLAUDE_CONFIG_DIR: '/fixture/claude-shell' }
+ // The default deps, with Codex left out by asking for the default Claude account alone.
+ const requests = startUsage(fakeCore({ dataDir }))
+ expect(await requests.usage_read!({ profile: { engine: 'claude', id: 'default' } }, ASKER)).toEqual({ providers: [
+ expect.objectContaining({ provider: 'claude', outcome: 'answered', body: { five_hour: { utilization: 77, resets_at: null } } }),
+ ] })
})
it('usage_read: a window whose reset has passed is unknown, never unused; one with none left is unknown, with why (task #4217)', async () => {
@@ -157,14 +182,14 @@ describe('the usage service', () => {
it('usage_read for a default profile reads that provider only, by either of its ids', async () => {
const core = fakeCore({ dataDir })
const codex = vi.fn(async () => CODEX)
- const requests = startUsage(core, { codex, now: () => NOW, env: {} })
+ const requests = startUsage(core, { codex, now: () => NOW, env: async () => ({}) })
const providers = async (engine: 'claude' | 'codex', id: string) =>
((await requests.usage_read!({ profile: { engine, id } }, ASKER)) as { providers: Array<{ provider: string }> }).providers.map(p => p.provider)
expect(await providers('claude', 'default')).toEqual(['claude'])
expect(await providers('codex', 'default')).toEqual(['codex'])
expect(await providers('claude', profileId(core.daemon.machineId(), 'claude', 'default'))).toEqual(['claude'])
expect(await providers('codex', profileId(core.daemon.machineId(), 'codex', 'default'))).toEqual(['codex'])
- expect(codex.mock.calls).toEqual([[{ codexHome: undefined }]])
+ expect(codex.mock.calls).toEqual([[{ codexHome: env.CODEX_HOME }]])
})
it('usage_read finds a Claude and a Codex profile by id, and reads each under its own folder', async () => {
diff --git a/cli/src/services/usage.ts b/cli/src/services/usage.ts
index 8accca594..dbc743160 100644
--- a/cli/src/services/usage.ts
+++ b/cli/src/services/usage.ts
@@ -15,6 +15,8 @@ import type { CoreApi, ServiceRequests } from '../core/api.js'
import { readCodexRateLimits, type CodexRateLimits, type CodexWindow } from '../lib/codexRateLimits.js'
import { accountKey, readClaudeReport, type ClaudeReport, type UsageProviderId } from '../lib/quotaReports.js'
import { profileHome } from '../lib/claudeProfiles.js'
+import { launchCodexHome } from '../lib/engineHomes.js'
+import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'
import { internalOnThrow } from './requestErrors.js'
/** The request usage answers for the apps, declared in core/api.ts for the core to route. */
@@ -35,14 +37,16 @@ export interface UsageReading {
}
export interface UsageDeps {
- /** Codex's own read for a CODEX_HOME, or the daemon's own. Injected so a spec starts no real codex. */
+ /** Codex's own read for a CODEX_HOME. Injected so a spec starts no real codex. */
codex: (options: { codexHome?: string }) => Promise<CodexRateLimits>
now: () => number
- /** The daemon's environment: its CLAUDE_CONFIG_DIR is the default Claude account's folder. */
- env: NodeJS.ProcessEnv
+ /** The environment a session launches with: its CLAUDE_CONFIG_DIR and CODEX_HOME are the default accounts' folders. */
+ env: () => Promise<NodeJS.ProcessEnv>
}
-const DEPS: UsageDeps = { codex: readCodexRateLimits, now: Date.now, env: process.env }
+// The login shell's variables over the daemon's, as every pane launches (lib/engineHomes.ts launchEnvironment). Read
+// here and not taken from that cache: this service may run in harnessd's edge process, where nothing else warms it.
+const DEPS: UsageDeps = { codex: readCodexRateLimits, now: Date.now, env: async () => ({ ...process.env, ...await warmLoginShellEnvironment() }) }
/** How long one Codex read stands for its home: the router asks every 3 minutes, Desktop on connect. */
const CODEX_FRESH_MS = 3 * 60_000
const NO_CLAUDE_REPORT = 'Claude Code has not reported its allowance on this machine yet: it does after its first reply in a session Harness started.'
@@ -69,11 +73,11 @@ function readerOf(core: CoreApi, engine: unknown, id: unknown): Wanted | null {
export function startUsage(core: CoreApi, deps: UsageDeps = DEPS): ServiceRequests {
const codexReads = new Map<string, { value: Promise<CodexRateLimits>; at: number }>()
- const codex = (home?: string): Promise<CodexRateLimits> => {
- const key = home ?? '', kept = codexReads.get(key), now = deps.now()
+ const codex = (home: string): Promise<CodexRateLimits> => {
+ const kept = codexReads.get(home), now = deps.now()
if (kept && now - kept.at < CODEX_FRESH_MS) return kept.value
const value = deps.codex({ codexHome: home })
- codexReads.set(key, { value, at: now })
+ codexReads.set(home, { value, at: now })
return value
}
return {
@@ -91,10 +95,10 @@ export function startUsage(core: CoreApi, deps: UsageDeps = DEPS): ServiceReques
only = found
}
const home = (engine: UsageProviderId) => only.engine === engine ? only.home : undefined
- return Promise.all([
- ...(only.engine !== 'codex' ? [claudeReading(readClaudeReport(core.dataDir, home('claude') ?? deps.env.CLAUDE_CONFIG_DIR), deps.now())] : []),
- ...(only.engine !== 'claude' ? [codex(home('codex')).then(codexReading)] : []),
- ]).then(
+ return deps.env().then((launch) => Promise.all([
+ ...(only.engine !== 'codex' ? [claudeReading(readClaudeReport(core.dataDir, home('claude') ?? launch.CLAUDE_CONFIG_DIR), deps.now())] : []),
+ ...(only.engine !== 'claude' ? [codex(launchCodexHome(home('codex'), launch)).then(codexReading)] : []),
+ ])).then(
(providers) => ({ providers }),
() => ({ error: 'USAGE_READ_FAILED' }),
)
diff --git a/docs/plans/2026-11-07-v3-flow-audit-fixes-plan.md b/docs/plans/2026-11-07-v3-flow-audit-fixes-plan.md
new file mode 100644
index 000000000..69fb65319
--- /dev/null
+++ b/docs/plans/2026-11-07-v3-flow-audit-fixes-plan.md
@@ -0,0 +1,140 @@
+# v3 flow audit fixes Implementation Plan
+
+> This plan is carried out by its Engineer task by task, test first (the project's Engineer rules): each task's failing
+> test is committed and seen failing before the code that passes it. Steps use checkbox (`- [ ]`) syntax.
+
+**Goal:** Fix the bugs from the v3 flow audit (#4212) that no other task covers, each verified in code first, with a test
+that fails without the fix (task #4252).
+
+**Architecture:** Each fix is the smallest change at the layer where the behavior lives: the backend's command rules
+(`commands.ts`, `machines.ts`), its reads (`read/personalTasks.ts`, `leaderboard/stats.ts`), and the CLI's quota report
+(`hook/statusline.mjs`, `lib/quotaReports.ts`, `services/usage.ts`). No new data, no new command, no Desktop change.
+
+**Tech Stack:** TypeScript backend and CLI, vitest.
+
+**Spec:** the #4212 audit posts (findings 2, 3/18, 9, 10, 11, 12, 15, 20, 29); docs/specs/2026-11-07-swarm-v3.md.
+
+## Triage of the 35 findings
+
+| Finding | Became |
+|---|---|
+| 1, 7, 8 | #4248 (Flowp0) |
+| 6 | #4194, merged |
+| 16 | #4249 |
+| 17, and the idea "dispatch skips idle Regular agents" | #4218 (its tasks 6 and 3) |
+| 5, 19, 28 | #4220 |
+| 35 (stale reports) | #4217 |
+| 2, 3/18, 9, 10, 11 (server half), 12, 15, 20, 29 | this plan, tasks 1-9 |
+| 13, 14, 21, 27, 11 (Desktop half), Regular name field, Bring agent seen early | Desktop only, outside this task's files: proposed to the PM as one Desktop task |
+| 34 | not a bug: a contributed computer takes the Swarm's work by its person's choice, which is what contributing is |
+| 4, 22, 23, 24, 25, 26, 30, 31, 32, 33, 35 (profile), batch 3 backend polish | polish, after these bugs |
+
+## Global Constraints
+
+- Owns backend/src/superTabs/ and cli/src/ (and cli/hook/statusline.mjs, which cli/src writes out at launch).
+- Never read or print a secret or login. The quota report keeps only percentages and reset times.
+- No new collection, field or command; older clients keep working (published contracts only extended).
+- The person's own status line still prints unchanged; nothing in the recording may stop it.
+
+## Design
+
+- growth: none new. A declined proposal is already kept (archived); it now stays in its person's Tasks until it goes dormant.
+- concurrency: the Swarm's single write per command, unchanged.
+- read cost: Tasks reads only changed parts, as today; the Leaderboard reads the state it already holds.
+- scale: unchanged.
+- compatibility: backend first; CLI 0.5.63 hosts keep working. A report written by an older status line under the old key is
+ read until the new one replaces it (task 3).
+- migration and rollback: none; rolled back, the bugs return and no data needs undoing.
+- audience: the server enforces it, unchanged. The Leaderboard's agent count is a number, not the agents.
+- identity: unchanged; no start under another person's login.
+- failure: each refusal names its cause (connecting, cleaning up) instead of a wrong one.
+- platforms: backend (Linux in CI); CLI on macOS, Linux and Windows (path resolution in task 3).
+
+## Review Focus
+
+- A person who sets CLAUDE_CONFIG_DIR to `~/.claude` (the default) explicitly, or with a trailing slash: one report key.
+- A report written before this change: still read (no "not reported yet" after updating).
+- A declined proposal merged into another card: still leaves Tasks (it was merged, not declined).
+- Approve when the suggested agent was removed: refused with a reason that says so, not a crash.
+- Listing a computer while another person's start is pending there: still refused.
+
+---
+
+### Task 1: a declined proposal stays in Tasks with its reason (findings 3, 18)
+
+**Files:** backend/src/superTabs/read/personalTasks.ts, backend/src/superTabs/commands.ts (`proposal.close`),
+backend/src/superTabs/read/personalTasks.test.ts, backend/src/superTabs/taskApproval.test.ts
+
+- [ ] Test (personalTasks.test.ts): an archived proposal card with `proposal.decision.kind === 'no'` is an upsert with
+ `status: 'rejected'` and `reason` = the decision's reason; a merged one (`mergedInto`) is still removed. Watch it fail.
+- [ ] Test (taskApproval.test.ts): `proposal.close` on an older-path proposal sends its sender the 'decided' notice, as
+ `proposal.decide no` does. Watch it fail.
+- [ ] personalTasksFor keeps a declined card; `proposal.close` pushes `proposalNotices(state, mirror, 'decided', …)`. Pass.
+
+### Task 2: "agents brought" is one count for every reader (finding 2)
+
+**Files:** backend/src/superTabs/leaderboard/stats.ts, backend/src/superTabs/read/service.ts,
+backend/src/superTabs/leaderboard/weekly.test.ts
+
+- [ ] Test: the weekly org board counts a member's idle Regular agent the same whether or not `visibleAgents` holds it.
+ Watch it fail.
+- [ ] Count from `state.agents` with the same filters; drop the `visibleAgents` input and its computation in service.ts. Pass.
+
+### Task 3: the quota report has one key per Claude folder (finding 9)
+
+**Files:** cli/hook/statusline.mjs, cli/src/lib/quotaReports.ts, cli/src/services/usage.ts, their specs
+
+**Interfaces:** `claudeReportKey(configDir?: string, home = homedir()): string` in quotaReports.ts: '' for unset, empty,
+or the default folder (`~/.claude`) however written; else the absolute path, resolved, real path where it exists, with no
+trailing separator. statusline.mjs carries the same rule (it imports nothing of the CLI).
+
+- [ ] Test: `~/.claude`, `~/.claude/` and unset give one report path; a moved folder with a trailing slash matches the one
+ without. Watch it fail.
+- [ ] Test: usage_read finds the report of the folder the login shell sets (launch environment), not the daemon's. Watch fail.
+- [ ] Both sides use the rule; usage.ts reads `launchClaudeConfigDir()`'s variable through engineHomes' launch environment,
+ and Codex's read the launch CODEX_HOME. A report under the old raw key is read when none is under the new. Pass.
+
+### Task 4: a 5-hour usage above 100% reads as 100 (finding 10)
+
+**Files:** cli/hook/statusline.mjs, cli/src/lib/quotaReports.ts, their specs
+
+- [ ] Test: a status with `used_percentage: 103` records 100; a report file holding 103 reads as 100. Watch it fail.
+- [ ] Clamp to 100 in both `windowOf`s; a negative or non-number stays refused. Pass.
+
+### Task 5: + New agent on a computer with no reading yet says it is connecting (finding 11, server half)
+
+**Files:** backend/src/superTabs/commands.ts (`agent.new`), backend/src/superTabs/agentNew.test.ts
+
+- [ ] Test: a listed computer with no `observation` refuses a Regular agent with `HOST_CONNECTING` and a "still connecting"
+ text, not `HOST_OUTDATED`. Watch it fail. Pass with the one branch.
+
+### Task 6: your own Buddy starting doesn't block listing your computer (finding 12)
+
+**Files:** backend/src/superTabs/commands.ts (`machine.contribute`), backend/src/superTabs/agentNew.test.ts
+
+- [ ] Test: the person's Buddy start pending on their Buddy-only record; `machine.contribute` of that computer succeeds and
+ the start carries over (`poolGeneration` = the new generation), so it still settles. Another start pending still
+ refuses. Watch it fail.
+- [ ] Only the actor's own Buddy starts on a Buddy-only record of theirs are carried over. Pass.
+
+### Task 7: rejoining while the old contribution cleans up says so (finding 15)
+
+**Files:** backend/src/superTabs/machines.ts (`machineContribution`), backend/src/superTabs/leadStart.test.ts
+
+- [ ] Test: a rejoined person's computer whose old record is still being removed refuses Bring agent with
+ `MACHINE_CLEANING` ("finishing its cleanup"), not "withdrawn". Watch it fail. Pass.
+
+### Task 8: Approve records consent; availability is the assignment's (finding 20)
+
+**Files:** backend/src/superTabs/commands.ts (`task.approve`), backend/src/superTabs/taskApproval.test.ts
+
+- [ ] Test: approving while the suggested agent is busy records `approved`; the PM's later work.assign still checks it.
+ A removed suggested agent refuses with `SUGGESTED_AGENT_GONE`. Watch it fail.
+- [ ] Approve checks the agent exists and is readable, not its availability. Pass.
+
+### Task 9: a Regular agent may say "Thanks!" in its own chat (finding 29)
+
+**Files:** backend/src/superTabs/commands.ts (`message.send`), backend/src/superTabs/agentNew.test.ts
+
+- [ ] Test: a Regular agent's "Thanks!" in its agent chat is posted; in a task it is still ACK_ONLY. Watch it fail.
+- [ ] The agent chat is exempt as a Buddy chat is. Pass.