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.

Trust fixes: shipped news after release, assigned news once, prompt waits kept, approval names its agent, Leaderboard counts merges, stale quota unknown (#4217) (#3468)

0xken15cd431c9cd40d
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index a927d4431..be69481d4 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -858,7 +858,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',
configuration: config, lead: false })).result.agentId)
await f.execute({ type: 'work.assign', conversationId: group, agentId: builder })
const notice = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, conversationId: group, recipientIds: { has: agentId } } })
- expect(notice).toMatchObject({ source: { kind: 'agent-only' }, text: expect.stringMatching(/^News for your owner: #\d+ "Offline sync", which they requested, is assigned and working\.$/) })
+ expect(notice).toMatchObject({ source: { kind: 'agent-only' }, text: expect.stringMatching(/^News for your owner: #\d+ "Offline sync", recorded as their request, is assigned and working\.$/) })
const got = await heard()
expect(got).toEqual([answer, followUp, tag, notice.id])
expect(got).not.toContain(unrelated)
@@ -924,7 +924,7 @@ describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)',
configuration: config, lead: false })).result.agentId)
await f.execute({ type: 'work.assign', conversationId: group, agentId: builder })
const notice = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, conversationId: group, recipientIds: { has: agentId } } })
- expect(notice.text).toMatch(/^News for your owner: #\d+ "Offline sync", which they requested, is assigned and working\.$/)
+ expect(notice.text).toMatch(/^News for your owner: #\d+ "Offline sync", recorded as their request, is assigned and working\.$/)
expect(await heard()).toEqual([notice.id])
})
diff --git a/backend/integration/superTabLeaderboard.test.ts b/backend/integration/superTabLeaderboard.test.ts
index 4449968b6..00f56d945 100644
--- a/backend/integration/superTabLeaderboard.test.ts
+++ b/backend/integration/superTabLeaderboard.test.ts
@@ -72,7 +72,7 @@ async function scene(before?: (state: SuperTabState) => void) {
const done = { id: 'done', agentId: worker, status: 'done' as const, result: PR, configuration: state.agents[0]!.configuration,
execution: { machineId: 'host', harnessId: 'h', machineOwnerId: owner.sub } }
const ship = (id: string, shippedAt: number) => Object.assign(state.conversations.find(c => c.id === id)!,
- { requesterId: peer.sub, assignment: done, pullRequestUrls: [PR], ledger: { askedAt: shippedAt - 2 * HOUR, shippedAt } })
+ { requesterId: peer.sub, assignment: done, pullRequestUrls: [PR], ledger: { askedAt: shippedAt - 2 * HOUR, shippedAt, mergedAt: shippedAt } })
ship(fresh, NOW - HOUR)
ship(old, WEEK - 2 * 86_400_000)
ship(chat, NOW - HOUR)
diff --git a/backend/integration/superTabRequestReads.test.ts b/backend/integration/superTabRequestReads.test.ts
index d8203b468..6d70b0777 100644
--- a/backend/integration/superTabRequestReads.test.ts
+++ b/backend/integration/superTabRequestReads.test.ts
@@ -62,7 +62,7 @@ async function scene() {
const done = { id: 'done', agentId: worker, status: 'done' as const, result: PR, configuration: state.agents[0]!.configuration,
execution: { machineId: 'host', harnessId: 'h', machineOwnerId: owner.sub } }
const ship = (id: string, shippedAt: number) => Object.assign(state.conversations.find(c => c.id === id)!,
- { requesterId: peer.sub, assignment: done, pullRequestUrls: [PR], ledger: { askedAt: shippedAt - 2 * HOUR, shippedAt } })
+ { requesterId: peer.sub, assignment: done, pullRequestUrls: [PR], ledger: { askedAt: shippedAt - 2 * HOUR, shippedAt, mergedAt: shippedAt } })
ship(fresh, NOW - HOUR)
ship(old, WEEK - WEEK_MS - DAY)
ship(lastWeek, WEEK - 2 * DAY)
diff --git a/backend/src/superTabs/buddyNews.test.ts b/backend/src/superTabs/buddyNews.test.ts
index dad1a0fcd..196cc071b 100644
--- a/backend/src/superTabs/buddyNews.test.ts
+++ b/backend/src/superTabs/buddyNews.test.ts
@@ -4,6 +4,7 @@ import { createSuperTab, forRecipients, type Actor, type Conversation, type Mess
import { buddyChatId } from './buddies.js'
import { assignedNotice, buddiesTold } from './buddyNews.js'
import { SHIP_KIND } from './ship.js'
+import { pendingKey, settleReleases } from './releases.js'
import { TASK_LINE_KIND } from './taskLine.js'
import { leaderboard } from './leaderboard/stats.js'
import { weekStart } from './leaderboard/week.js'
@@ -137,7 +138,17 @@ describe('the assignment notice a Buddy gets for work its person requested', ()
it('is one line inside the task, for the Buddy alone: its number, title and status, nothing more', () => {
const { group, assign, number } = requested()
expect(notices(assign())).toEqual([expect.objectContaining({ conversationId: group, recipients: ['buddy'], source: { kind: 'agent-only' },
- text: `News for your owner: #${number} "Offline edits", which they requested, is assigned and working.` })])
+ text: `News for your owner: #${number} "Offline edits", recorded as their request, is assigned and working.` })])
+ })
+
+ it('is sent once per task: a replacement agent taking the work over is no new news (task #4217)', () => {
+ const { f, group, assign } = requested()
+ expect(notices(assign())).toHaveLength(1)
+ const first = f.state.conversations.find(c => c.id === group)!.assignment!
+ f.run({ type: 'agent.alert', agentId: first.agentId, alert: 'model', active: true }, { kind: 'agent', agentId: first.agentId, machineOwnerId: 'host' })
+ expect(f.state.conversations.find(c => c.id === group)!.assignment!.status).toBe('lost')
+ const replacement = f.add(group, 'replacement')
+ expect(notices(f.run({ type: 'work.assign', conversationId: group, agentId: replacement }).messages)).toEqual([])
})
it('is not sent for a private task in a public project, though its person requested it (security review 2 of #2178)', () => {
@@ -200,14 +211,36 @@ describe('work the PM opens from a Buddy\'s proposal without naming anyone (grou
expect(done.messages.filter(m => m.recipients.includes('buddy'))).toEqual([])
const merged = f.run({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/o/r/pull/7' }, agentActor(worker))
expect(merged.messages).toEqual(expect.arrayContaining([expect.objectContaining({ thread: find().cards!.line!.messageId, text: 'Merged: PR #7. Ships in the next release.' })]))
- expect(merged.messages.filter(m => m.recipients.includes('buddy'))).toEqual([expect.objectContaining({ conversationId: group,
- source: { kind: 'agent-only' }, text: expect.stringContaining('which they requested, shipped') })])
+ // A merge is not shipped: the news waits for the release that holds it (task #4217).
+ expect(merged.messages.filter(m => m.recipients.includes('buddy'))).toEqual([])
expect(f.run({ type: 'conversation.merged', conversationId: group, pullRequestUrl: 'https://github.com/o/r/pull/7' }, agentActor(worker))
.messages.filter(m => m.recipients.includes('buddy'))).toEqual([])
const board = leaderboard({ state: f.state, groups: f.state.conversations, machines: [], projectId: f.app.projectId, week: weekStart(1000), now: 1000 })
expect(board.people.find(p => p.personId === 'peer')).toMatchObject({ points: 3, shipped: { count: 1 } })
})
+ it('tells the Buddy its work shipped only when a verified release holds it, once (task #4217)', () => {
+ const { f, group, find } = opened()
+ const worker = f.add(group, 'worker')
+ f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ const url = 'https://github.com/o/r/pull/7'
+ expect(f.run({ type: 'conversation.merged', conversationId: group, pullRequestUrl: url }, agentActor(worker))
+ .messages.filter(m => m.recipients.includes('buddy'))).toEqual([])
+ const key = pendingKey({ groupId: group, url })
+ const settle = (tag: string, carries: string[], at: number) => {
+ const state = structuredClone(f.state)
+ const out = settleReleases(state, f.app.projectId, { resolved: [{ groupId: group, url, components: ['backend'], sha: 'merge' }],
+ releases: { backend: { tag, sha: tag, at, carries, compared: [key] } } }, at)
+ Object.assign(f.state, state)
+ return out.messages.filter(m => m.recipients.includes('buddy'))
+ }
+ // A release that does not hold the merge says nothing; the one that does tells the Buddy, inside the task, once.
+ expect(settle('v1.0.1_backend', [], 5000)).toEqual([])
+ expect(settle('v1.0.2_backend', [key], 6000)).toEqual([expect.objectContaining({ conversationId: group, recipients: ['buddy'],
+ source: { kind: 'agent-only' }, text: `News for your owner: #${find().number} "Offline edits", recorded as their request, shipped.` })])
+ expect(settle('v1.0.3_backend', [key], 7000)).toEqual([])
+ })
+
it('keeps the requester the PM names, even someone else', () => {
const { find } = opened({ requesterId: 'owner' })
expect(find().requesterId).toBe('owner')
diff --git a/backend/src/superTabs/buddyNews.ts b/backend/src/superTabs/buddyNews.ts
index 55d53c6c3..3456fba48 100644
--- a/backend/src/superTabs/buddyNews.ts
+++ b/backend/src/superTabs/buddyNews.ts
@@ -58,24 +58,25 @@ export function tellBuddies(state: SuperTabState, message: MessageDraft, threadS
if (buddies.length) message.buddyRecipients = buddies
}
-/** Work [group]'s requester asked for was just assigned: one line for their Buddy alone, inside the task, saying only what
- * its person reads there (its number, title and status, Lead's ruling 10-29). None when the Buddy cannot read the task. */
+/** Work recorded as [group]'s requester's was just assigned: one line for their Buddy alone, inside the task, saying only what
+ * its person reads there (its number, title and status, Lead's ruling 10-29). None when the Buddy cannot read the task.
+ * An agent may name a task's requester, so the line says only what the server knows: the record (task #4217). */
export function assignedNotice(state: SuperTabState, group: Conversation, author: Author, operationId: string): MessageDraft | null {
if (groupProject(state, group).boardMode) return null
const buddy = group.requesterId ? listeningBuddy(state, group.requesterId, group) : undefined
if (!buddy || !group.assignment) return null
return { id: stableId(operationId, 'buddy-news'), conversationId: group.id, author, replyTo: null, recipients: [buddy.id], source: AGENT_ONLY,
- text: `News for your owner: #${group.number} "${group.title}", which they requested, is assigned and ${group.assignment.status}.` }
+ text: `News for your owner: #${group.number} "${group.title}", recorded as their request, is assigned and ${group.assignment.status}.` }
}
-/** Work [group]'s requester asked for just shipped: the news the Shipped line brought their Buddy, now that the task's line
- * says it (taskLine.ts), as one line for their Buddy alone inside the task, like the assignment's. */
+/** Work [group]'s requester asked for just shipped: a verified release holds it (releases.ts settleReleases), as one line for
+ * their Buddy alone inside the task, like the assignment's. */
export function shippedNotice(state: SuperTabState, group: Conversation, author: Author, operationId: string): MessageDraft | null {
if (group.proposal) return null
const buddy = group.requesterId ? listeningBuddy(state, group.requesterId, group) : undefined
if (!buddy) return null
return { id: stableId(operationId, 'buddy-news', 'shipped'), conversationId: group.id, author, replyTo: null, recipients: [buddy.id], source: AGENT_ONLY,
- text: `News for your owner: #${group.number} "${group.title}", which they requested, shipped.` }
+ text: `News for your owner: #${group.number} "${group.title}", recorded as their request, shipped.` }
}
/** Every Buddy hearing input, in its own chat too: the agent guard meets a concurrent sleep (#3824), and the person's
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index d0700059d..5cd3a71d3 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -437,7 +437,9 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('member.status'), status: statusSchema.nullable() }).strict(),
z.object({ type: z.literal('member.approvalMode'), mode: z.enum(['autoApprove', 'review']) }).strict(),
z.object({ type: z.literal('task.suggest'), conversationId: id, agentId: id }).strict(),
- z.object({ type: z.literal('task.approve'), conversationId: id }).strict(),
+ // The suggested agent the person was shown, null for none (task #4217): compared, never read. Optional only for Desktops
+ // from before it, until 2026-12-07.
+ z.object({ type: z.literal('task.approve'), conversationId: id, suggestedAgentId: id.nullable().optional() }).strict(),
z.object({ type: z.literal('task.reject'), conversationId: id, reason: z.string().trim().min(1).max(2000) }).strict(),
z.object({ type: z.literal('member.timeZone'), timeZone: z.string().min(1).max(64).nullable() }).strict(),
z.object({ type: z.literal('member.avatar'), avatar: avatarChoice }).strict(),
@@ -1955,6 +1957,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId, contributorId: worker.contributorId }, result: null }
renewLease(group.assignment, context.now)
leadActed(group.id, 'assign')
+ // Its requester's Buddy hears of the task's first assignment only: a replacement agent is no news (task #4217).
+ const firstAssignment = group.ledger?.firstAssignedAt == null && !group.ledger?.runs?.length
recordRun(state, group, group.assignment, worker, context.now)
const others = othersWorkNotice(state, group, worker, context.now, ENGINE_NAMES[worker.configuration.engine] ?? worker.configuration.engine)
if (others) effects.messages.push({ id: stableId(assignmentId, 'others-work-notice'), conversationId: others.conversationId, author: sender,
@@ -1967,7 +1971,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...recovery ? [recovery] : [],
...group.checks.length ? [`Acceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`] : [],
...requestedBy ? [requestedBy] : []].join('\n\n'), [worker.id], null, SYSTEM_ROW, undefined, undefined, undefined, assignmentId)
- const news = assignedNotice(state, group, sender, assignmentId)
+ const news = firstAssignment && assignedNotice(state, group, sender, assignmentId)
if (news) effects.messages.push(news)
}
/** The kind of a step already open on a task, by its name, so a step its Engineer opened is reused, not doubled. */
@@ -4616,6 +4620,10 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
} else {
if (command.type === 'task.approve' && undecidedProposal(group))
fail('PROPOSAL_UNDECIDED', 'Approve the task once the PM has accepted or reshaped this proposal.', 409)
+ // A suggestion that moved between the person's look and their tap is not what they approved.
+ if (command.type === 'task.approve' && command.suggestedAgentId !== undefined && command.suggestedAgentId !== (approval.suggestedAgentId ?? null)) {
+ fail('TASK_SUGGESTION_CHANGED', 'The suggested agent changed since you looked. Read the task again and approve the agent it names now.', 409)
+ }
approval.state = command.type === 'task.approve' ? 'approved' : 'rejected'
approval.decidedAt = context.now
if (command.type === 'task.reject') approval.reason = command.reason
diff --git a/backend/src/superTabs/leaderboard/brought.test.ts b/backend/src/superTabs/leaderboard/brought.test.ts
index 4338d6f48..d1551be1a 100644
--- a/backend/src/superTabs/leaderboard/brought.test.ts
+++ b/backend/src/superTabs/leaderboard/brought.test.ts
@@ -29,7 +29,7 @@ function group(ledger: GroupLedger, extra: Partial<Conversation> = {}): Conversa
}
/** A request someone asked for that shipped at [at] on an attempt that ran on [machineId]. */
const shippedOn = (machineId: string | undefined, at: number, ledger: GroupLedger = {}, extra: Partial<Conversation> = {}) =>
- group({ askedAt: at - HOUR, shippedAt: at, runs: [run(machineId, at - HOUR)], ...ledger }, extra)
+ group({ askedAt: at - HOUR, shippedAt: at, mergedAt: at, runs: [run(machineId, at - HOUR)], ...ledger }, extra)
const board = (state: SuperTabState, groups: Conversation[], machines = state.machines ?? []) =>
leaderboard({ state, groups, machines, projectId: 'lead', week: WEEK, now: NOW })
const brought = (view: ReturnType<typeof board>, id: string) => view.people.find(p => p.personId === id)!.details.brought
@@ -54,7 +54,7 @@ describe('Brought: the machines a person brought, what shipped on each, and thei
it('credits the attempt the request shipped on, not a later or earlier one', () => {
const state = swarm()
state.machines = [machine('studio', 'ken'), machine('box', 'diego')]
- const g = group({ askedAt: WEEK, shippedAt: WEEK + 2 * HOUR, runs: [run('box', WEEK), run('studio', WEEK + HOUR), run('box', WEEK + 3 * HOUR)],
+ const g = group({ askedAt: WEEK, shippedAt: WEEK + 2 * HOUR, mergedAt: WEEK + 2 * HOUR, runs: [run('box', WEEK), run('studio', WEEK + HOUR), run('box', WEEK + 3 * HOUR)],
shippedBy: { assignmentId: 'x', engine: 'claude', model: 'opus', at: WEEK + HOUR, machineId: 'studio' } })
const view = board(state, [g])
expect(brought(view, 'ken')[0]!.shipped).toBe(1)
diff --git a/backend/src/superTabs/leaderboard/brought.ts b/backend/src/superTabs/leaderboard/brought.ts
index 7b0c8343e..0a03c85f6 100644
--- a/backend/src/superTabs/leaderboard/brought.ts
+++ b/backend/src/superTabs/leaderboard/brought.ts
@@ -24,9 +24,13 @@ export function shippedOnMachine(state: SuperTabState, group: Conversation): str
return shipping.machineId ?? runMachine(state, ledger.runs?.find(r => r.assignmentId === shipping.assignmentId) ?? {})
}
-/** Verified, as far as the server knows (the PM's north star): shipped with a pull request, and no fix merged after it. */
-export const verified = (group: Conversation): boolean =>
- group.ledger?.shippedAt != null && (group.pullRequestUrls?.length ?? 0) > 0 && group.ledger.fixedAfterMergeAt == null
+/** Shipped: its pull request's merge recorded (leaderboard/record.ts recordMerged, which ships it then), not Done alone, which
+ * a task with a PR nobody merged reaches too (task #4217). */
+export const shippedByMerge = (group: Conversation): boolean =>
+ group.ledger?.mergedAt != null && group.ledger.shippedAt != null && (group.pullRequestUrls?.length ?? 0) > 0
+
+/** Verified, as far as the server knows (the PM's north star): shipped by its merge, and no fix merged after it. */
+export const verified = (group: Conversation): boolean => shippedByMerge(group) && group.ledger!.fixedAfterMergeAt == null
/** The machine a pool stands for among [machines]: a Harness Team account's Mac when the reader sees it, else itself. */
export function homeOf(machines: readonly ContributedMachine[], machineId: string): ContributedMachine | undefined {
diff --git a/backend/src/superTabs/leaderboard/rolling.test.ts b/backend/src/superTabs/leaderboard/rolling.test.ts
index 35856677f..9ccc303f3 100644
--- a/backend/src/superTabs/leaderboard/rolling.test.ts
+++ b/backend/src/superTabs/leaderboard/rolling.test.ts
@@ -20,7 +20,7 @@ function swarm(): SuperTabState {
let n = 0
const group = (extra: Partial<Conversation> & { ledger?: GroupLedger } = {}): Conversation => ({ id: `r${++n}`, projectId: 'lead', title: `Group ${n}`, leadId: null,
agentIds: [], archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0, ...extra })
-const shipped = (at: number, extra: Partial<Conversation> = {}) => group({ requesterId: 'dee', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt: at - HOUR, shippedAt: at }, ...extra })
+const shipped = (at: number, extra: Partial<Conversation> = {}) => group({ requesterId: 'dee', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt: at - HOUR, shippedAt: at, mergedAt: at }, ...extra })
const machine = (extra: Partial<ContributedMachine>): ContributedMachine => ({ machineId: 'mac', name: 'Studio', contributorId: 'dee', membershipGeneration: 'g', generation: 'g1',
cwd: '/repo', engines: ['claude'], maxAgents: 2, paused: false, ...extra })
const read = (period: PeriodName, groups: Conversation[], machines: ContributedMachine[] = [], now = NOW) =>
@@ -50,7 +50,7 @@ describe('the rolling periods', () => {
it('scores points, details, agents and models over the same period', () => {
const answers = group({ ledger: { unblocks: [{ personId: 'dee', at: NOW - HOUR, waitedMs: 0, kind: 'decision' }, { personId: 'dee', at: NOW - 3 * DAY, waitedMs: 0, kind: 'decision' }] } })
- const ran = shipped(NOW - HOUR, { ledger: { askedAt: NOW - 2 * HOUR, shippedAt: NOW - HOUR, runs: [{ assignmentId: 'a', at: NOW - 2 * HOUR, ...opus }] } })
+ const ran = shipped(NOW - HOUR, { ledger: { askedAt: NOW - 2 * HOUR, shippedAt: NOW - HOUR, mergedAt: NOW - HOUR, runs: [{ assignmentId: 'a', at: NOW - 2 * HOUR, ...opus }] } })
const view = read('24h', [answers, ran, shipped(NOW - 3 * DAY)])
expect(dee(view)).toMatchObject({ points: 4, prevWeekPoints: 0, shipped: { count: 1 }, unblocked: { count: 1 } })
expect(dee(view).details.shipped).toHaveLength(1)
@@ -59,7 +59,7 @@ describe('the rolling periods', () => {
})
it('never counts a private conversation or a machine it was not handed', () => {
- const hidden = shipped(NOW - HOUR, { audience: { people: [{ id: 'dee', generation: 'g' }] }, ledger: { askedAt: 0, shippedAt: NOW - HOUR,
+ const hidden = shipped(NOW - HOUR, { audience: { people: [{ id: 'dee', generation: 'g' }] }, ledger: { askedAt: 0, shippedAt: NOW - HOUR, mergedAt: NOW - HOUR,
reviewHours: [{ hour: TODAY, ...opus, count: 9 }] } })
const view = read('7d', [hidden])
expect(dee(view).shipped.count).toBe(0)
diff --git a/backend/src/superTabs/leaderboard/stats.test.ts b/backend/src/superTabs/leaderboard/stats.test.ts
index f3c6c33fc..f3ba7a992 100644
--- a/backend/src/superTabs/leaderboard/stats.test.ts
+++ b/backend/src/superTabs/leaderboard/stats.test.ts
@@ -25,9 +25,9 @@ function group(extra: Partial<Conversation> & { ledger?: GroupLedger; status?: W
return { id, projectId: 'lead', title: `Group ${id}`, leadId: null, agentIds: [], archived: false, brief: 'Do it', checks: [], assignment,
lastMessageSequence: 0, ...rest }
}
-/** A request by [requesterId] asked at [askedAt] and shipped at [shippedAt] with a linked PR. */
+/** A request by [requesterId] asked at [askedAt] and shipped at [shippedAt]: its linked PR merged then. */
const shipped = (requesterId: string, askedAt: number, shippedAt: number, extra: Partial<Conversation> = {}) =>
- group({ requesterId, status: 'done', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt, shippedAt }, ...extra })
+ group({ requesterId, status: 'done', pullRequestUrls: ['https://github.com/o/r/pull/1'], ledger: { askedAt, shippedAt, mergedAt: shippedAt }, ...extra })
const answered = (...unblocks: Array<[personId: string, at: number, waitedMs: number]>) =>
group({ status: 'working', ledger: { unblocks: unblocks.map(([personId, at, waitedMs]) => ({ personId, at, waitedMs })) } })
function machine(contributorId: string, lent: Array<[week: number, busyMs: number]>, machineId = `mac-${contributorId}`): ContributedMachine {
@@ -50,6 +50,11 @@ describe('Shipped: requests a person asked for, done with a linked PR, 3 points
expect(person(view, 'dee').shipped.count).toBe(0)
})
+ it('needs the PR merged: work Done with a linked PR nobody merged has not shipped (task #4217)', () => {
+ const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR, { ledger: { askedAt: WEEK, shippedAt: WEEK + HOUR } })])
+ expect(person(view, 'dee')).toMatchObject({ points: 0, shipped: { count: 0 } })
+ })
+
it('counts a request, not its review group, and never a group nobody asked for', () => {
const view = board(swarm(), [shipped('dee', WEEK, WEEK + HOUR, { reviewOf: 'g0' }), shipped('', WEEK, WEEK + HOUR, { requesterId: undefined })])
expect(view.people.map(p => [p.personId, p.shipped.count])).toEqual([['dee', 0], ['ken', 0], ['scholes', 0], ['tony', 0]])
@@ -284,7 +289,7 @@ describe('Models: temporary workers by engine, model and effort, never by agent
({ assignmentId, engine: model.startsWith('gpt') ? 'codex' : 'claude', model, ...effort ? { effort } : {}, at, ...extra })
/** A request shipped at [shippedAt] after [runs]. */
const landed = (shippedAt: number, runs: Run[], extra: Partial<GroupLedger> = {}) =>
- shipped('dee', runs[0]?.at ?? shippedAt, shippedAt, { ledger: { askedAt: runs[0]?.at ?? shippedAt, shippedAt, runs, ...extra } })
+ shipped('dee', runs[0]?.at ?? shippedAt, shippedAt, { ledger: { askedAt: runs[0]?.at ?? shippedAt, shippedAt, mergedAt: shippedAt, runs, ...extra } })
const model = (view: ReturnType<typeof board>, name: string, effort: string | null = 'high') =>
view.byModel.find(m => m.model === name && m.effort === effort)!
@@ -406,7 +411,7 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like people
it('credits a group opened from a proposal with no person named as its requester (review of #2097)', () => {
const run = { assignmentId: 'a1', engine: 'claude', model: 'opus', effort: 'high', at: WEEK }
const fromProposal = group({ leadId: 'river', status: 'done', pullRequestUrls: ['https://github.com/o/r/pull/1'],
- ledger: { askedAt: WEEK, shippedAt: WEEK + HOUR, runs: [run], proposal: { buddyId: 'sparky', messageId: 'm1' } } })
+ ledger: { askedAt: WEEK, shippedAt: WEEK + HOUR, mergedAt: WEEK + HOUR, runs: [run], proposal: { buddyId: 'sparky', messageId: 'm1' } } })
const view = board(agents(swarm()), [fromProposal])
expect(of(view, 'sparky')).toMatchObject({ points: 3, shipped: 1 })
expect(of(view, 'river')).toMatchObject({ points: 3, shipped: 1 })
@@ -416,7 +421,7 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like people
})
it('credits the PM who led the group when it shipped, not whoever leads it now (review of #2097)', () => {
- const ledger = (shippedLeadId: string | null) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, shippedLeadId })
+ const ledger = (shippedLeadId: string | null) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, mergedAt: WEEK + HOUR, shippedLeadId })
const view = board(agents(swarm()), [
shipped('dee', WEEK, WEEK + HOUR, { leadId: 'someone-else', ledger: ledger('river') }),
shipped('dee', WEEK, WEEK + HOUR, { leadId: null, ledger: ledger('river') }),
@@ -430,7 +435,7 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like people
const state = agents(swarm())
state.agents = state.agents.filter(a => a.id !== 'sparky')
state.agents.push({ ...state.agents.find(a => a.id === 'river')!, id: 'old-pm', displayName: 'Atlas' })
- const ledger = (extra: object) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, ...extra })
+ const ledger = (extra: object) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, mergedAt: WEEK + HOUR, ...extra })
const view = board(state, [
shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: 'old-pm' }) }),
shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: 'gone-pm' }) }),
@@ -448,7 +453,7 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like people
const river = state.agents.find(a => a.id === 'river')!
state.agents.push({ ...river, id: 'old-pm', projectId: 'secret', displayName: 'Hidden', machineId: 'mac-secret' },
{ ...river, id: 'old-buddy', projectId: 'secret', displayName: 'Whisper', machineId: 'mac-secret', buddyOf: { personId: 'tony', generation: 'g' } })
- const ledger = (extra: object) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, ...extra })
+ const ledger = (extra: object) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, mergedAt: WEEK + HOUR, ...extra })
const view = board(state, [
shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: 'old-pm' }) }),
shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: null, proposal: { buddyId: 'old-buddy', messageId: 'm1' } }) }),
@@ -460,7 +465,7 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like people
})
it('gives a Buddy 3 points per group opened from its proposal that shipped this week', () => {
- const fromProposal = { askedAt: WEEK, shippedAt: WEEK + HOUR, proposal: { buddyId: 'sparky', messageId: 'm1' } }
+ const fromProposal = { askedAt: WEEK, shippedAt: WEEK + HOUR, mergedAt: WEEK + HOUR, proposal: { buddyId: 'sparky', messageId: 'm1' } }
const view = board(agents(swarm()), [shipped('dee', WEEK, WEEK + HOUR, { ledger: fromProposal }), shipped('dee', WEEK, WEEK + HOUR)])
expect(of(view, 'sparky')).toMatchObject({ points: 3, shipped: 1 })
expect(of(view, 'river')).toMatchObject({ points: 0, shipped: 0, rank: 2 })
@@ -479,7 +484,7 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like people
buddySession: { thread: 't', from: 1, projectId: 'lead' }, machineId: 'mac-dee' })
return state
}
- const ledger = (buddyId: string) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, proposal: { buddyId, messageId: 'm1' } })
+ const ledger = (buddyId: string) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, mergedAt: WEEK + HOUR, proposal: { buddyId, messageId: 'm1' } })
const buddies = (view: ReturnType<typeof board>) => view.agents.filter(a => a.kind === 'buddy')
it('lists it in every project its person reads, with its name and person, and never its sessions', () => {
diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.ts
index 5ac236882..07b53bd50 100644
--- a/backend/src/superTabs/leaderboard/stats.ts
+++ b/backend/src/superTabs/leaderboard/stats.ts
@@ -10,7 +10,7 @@ import { isBuddy, isSwarmBuddy } from '../buddies.js'
import { agentProjectId, canReadProject, NO_PROJECT, projectOf } from '../projects.js'
import { firstAssignedAt, waitedOn, waitsNow, type RanOn, type Unblock } from './record.js'
import { lentIn, periodSpans, reviewsIn, weekSpan, within, type PeriodName, type Span } from './rolling.js'
-import { broughtMachines, contributorsIn } from './brought.js'
+import { broughtMachines, contributorsIn, shippedByMerge } from './brought.js'
import { DAY_MS, WEEK_MS } from './week.js'
import type { AgentScore, Leaderboard, Medal, ModelScore, ModelShare, PersonDetails, PersonScore, RecentModel, WeekGoal } from './contract.js'
@@ -58,9 +58,9 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI
const leadConversations = new Set([...projectIds].map(id => projectOf(state, id).leadConversationId))
const shared = visible.filter(g => !leadConversations.has(g.id))
const requests = shared.filter(g => !g.reviewOf)
- // Shipped with a PR: what agents and models are credited for. A person's points also need them to have asked (review
- // of #2097: a group opened from a Buddy's proposal may name no requester).
- const shippedRequests = requests.filter(g => g.ledger?.shippedAt != null && (g.pullRequestUrls?.length ?? 0) > 0)
+ // Shipped by a recorded merge: what agents and models are credited for (Done with a PR nobody merged is not, task #4217). A
+ // person's points also need them to have asked (review of #2097: a group opened from a Buddy's proposal may name no requester).
+ const shippedRequests = requests.filter(shippedByMerge)
const landed = shippedRequests.filter(g => g.requesterId)
const players = allProjects ? state.people : state.people.filter(p => canReadProject(state, { kind: 'person', userId: p.id, email: p.email }, project))
const { current, previous } = period ? periodSpans(period, now) : { current: weekSpan(week), previous: weekSpan(week - WEEK_MS) }
diff --git a/backend/src/superTabs/leaderboard/weekly.test.ts b/backend/src/superTabs/leaderboard/weekly.test.ts
index 2eabaad92..6f00987f4 100644
--- a/backend/src/superTabs/leaderboard/weekly.test.ts
+++ b/backend/src/superTabs/leaderboard/weekly.test.ts
@@ -11,7 +11,7 @@ function fixture() {
const request = (id: string, person = 'owner', projectId = 'lead', extra: Partial<Conversation> = {}): Conversation => ({
id, projectId, title: id, leadId: null, agentIds: [], archived: false, brief: '', checks: [], assignment: null,
lastMessageSequence: 0, requesterId: person, pullRequestUrls: ['https://github.com/o/r/pull/1'],
- ledger: { firstAssignedAt: WEEK + 1, shippedAt: WEEK + 2 }, ...extra,
+ ledger: { firstAssignedAt: WEEK + 1, shippedAt: WEEK + 2, mergedAt: WEEK + 2 }, ...extra,
})
const agent = (id: string, extra: Partial<Agent> = {}): Agent => ({
id, projectId: 'lead', name: id, machineId: 'mac', harnessId: id, machineOwnerId: 'owner', contributorId: 'owner',
diff --git a/backend/src/superTabs/liveness.test.ts b/backend/src/superTabs/liveness.test.ts
index e738b5855..6cf02f95b 100644
--- a/backend/src/superTabs/liveness.test.ts
+++ b/backend/src/superTabs/liveness.test.ts
@@ -95,6 +95,18 @@ describe('a task waiting on a person (task #2969)', () => {
expect(status(working(asked + QUIET_RUNNING_MS + 1), asked + QUIET_RUNNING_MS + 1).status).toBe('lost')
})
+ it('stays its agent\'s while its terminal waits at a prompt for a person, though its status says working (task #4217)', () => {
+ const prompted = (alerting: Array<'prompt'>) => {
+ const state = swarm(assignment({ leaseUntil: asked + LEASE_MS, progressAt: asked }), { receivedAt: asked + 2 * HOUR, harnessProgress: { h: asked } })
+ state.agents[0]!.alerting = alerting
+ return state
+ }
+ expect(status(prompted(['prompt']), asked + 2 * HOUR).status).toBe('working')
+ expect(nextLossAt(prompted(['prompt']), 'm')).toBeUndefined()
+ // The prompt answered, its quiet time counts again.
+ expect(status(prompted([]), asked + 2 * HOUR).status).toBe('lost')
+ })
+
it('has no loss time while it waits for the person, so a machine\'s report is not scheduled for it', () => {
expect(nextLossAt(waiting(), 'm')).toBeUndefined()
})
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index 0f75637a4..33c63d4bd 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -261,13 +261,15 @@ function answeredAt(group: Conversation, assignment: Assignment): number | undef
return assignment.status === 'needs_human' && waiting?.assignmentId === assignment.id ? waiting.answeredAt ?? undefined : undefined
}
-/** A task waits on a person (needs_human, or blocked: its agent cannot go on) and its agent is alive: its machine's last report
- * lists the session running. Its terminal prints nothing while it waits, so quiet time does not count (Ken, 2026-11-04, #2969:
- * a task waiting on Huy was lost after 30 quiet minutes, twice). Not once the person answered (the agent then has 30 minutes
- * from the answer, leaseEnd), and not for an agent no report shows running: that one is gone and loses it as before. */
+/** A task waits on a person (needs_human, or blocked: its agent cannot go on; or its terminal at a prompt its host alerted,
+ * terminal.ts, whatever its status says, task #4217) and its agent is alive: its machine's last report lists the session
+ * running. Its terminal prints nothing while it waits, so quiet time does not count (Ken, 2026-11-04, #2969: a task waiting on
+ * Huy was lost after 30 quiet minutes, twice). Not once the person answered (the agent then has 30 minutes from the answer,
+ * leaseEnd), and not for an agent no report shows running: that one is gone and loses it as before. */
function waitingOnPerson(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment): boolean {
- return (assignment.status === 'needs_human' || assignment.status === 'blocked') && answeredAt(group, assignment) === undefined
- && !!state.machines?.find(m => m.machineId === worker.machineId)?.observation?.runningHarnessIds.includes(worker.harnessId)
+ const asked = ((assignment.status === 'needs_human' || assignment.status === 'blocked') && answeredAt(group, assignment) === undefined)
+ || !!worker.alerting?.includes('prompt')
+ return asked && !!state.machines?.find(m => m.machineId === worker.machineId)?.observation?.runningHarnessIds.includes(worker.harnessId)
}
/** When a worker's lease ends: from its own last status, check or post (for an assignment from before leases, its group's
diff --git a/backend/src/superTabs/releases.ts b/backend/src/superTabs/releases.ts
index b839690ab..935d8788e 100644
--- a/backend/src/superTabs/releases.ts
+++ b/backend/src/superTabs/releases.ts
@@ -1,4 +1,5 @@
import { proposalNotices } from './proposalCards.js'
+import { shippedNotice } from './buddyNews.js'
/**
* Releases scheduled by the Swarm (task #3405, anh Dee's Swarm redesign, 2026-11-05: the server does the routine). A merge
* recorded on a task puts it on its project's release list; the worker (releaseWatch.ts) reads GitHub for each component's
@@ -278,12 +279,20 @@ export function settleReleases(state: SuperTabState, projectId: string, facts: R
}
+ // Shipped once a verified release holds all of it (task #4217: a merge alone is not shipped): a proposal's card says so, and a
+ // task's requester's Buddy hears it, by an id the release fixes, so a settle retried tells nobody twice.
if (lead) for (const id of new Set(outcome.shipped)) {
const group = state.conversations.find(c => c.id === id)
- if (!group?.proposal || group.releasing) continue
+ if (!group || group.releasing) continue
const sender = { kind: 'agent' as const, id: lead.id, name: lead.name, membershipGeneration: lead.membershipGeneration }
- outcome.messages.push(...proposalNotices(state, group as Conversation & { proposal: NonNullable<Conversation['proposal']> },
- 'shipped', `${group.title} shipped.`, sender, stableId(group.id, 'shipped', String(group.released!.at))))
+ const once = stableId(group.id, 'shipped', String(group.released!.at))
+ if (group.proposal) {
+ outcome.messages.push(...proposalNotices(state, group as Conversation & { proposal: NonNullable<Conversation['proposal']> },
+ 'shipped', `${group.title} shipped.`, sender, once))
+ } else {
+ const news = shippedNotice(state, group, sender, once)
+ if (news) outcome.messages.push(news)
+ }
}
for (const component of RELEASE_COMPONENTS) {
diff --git a/backend/src/superTabs/taskApproval.test.ts b/backend/src/superTabs/taskApproval.test.ts
index a6f2ad7d9..e6a1899a7 100644
--- a/backend/src/superTabs/taskApproval.test.ts
+++ b/backend/src/superTabs/taskApproval.test.ts
@@ -80,6 +80,24 @@ describe('personal approval enforced before work', () => {
expect(approved.messages.some(m => m.recipients.includes(f.other))).toBe(false)
expect(approved.messages.some(m => m.recipients.includes(f.candidate))).toBe(false)
})
+ it('approves only the agent the person was shown: a suggestion changed since is refused and approves nothing (task #4217)', () => {
+ const f = fixture(); f.mode('review'); const id = f.create()
+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.candidate }, f.pm)
+ // The person saw the candidate; the PM suggests another before their tap lands.
+ f.runCommand({ type: 'task.suggest', conversationId: id, agentId: f.other }, f.pm)
+ for (const agentId of [f.candidate, null]) {
+ expect(() => f.runCommand({ type: 'task.approve', conversationId: id, suggestedAgentId: agentId })).toThrow(expect.objectContaining({ code: 'TASK_SUGGESTION_CHANGED' }))
+ expect(f.card(id).taskApproval).toMatchObject({ state: 'proposal', suggestedAgentId: f.other })
+ }
+ f.runCommand({ type: 'task.approve', conversationId: id, suggestedAgentId: f.other })
+ expect(f.card(id).taskApproval).toMatchObject({ state: 'approved', suggestedAgentId: f.other })
+ // With no agent suggested, the approval names none.
+ const plain = f.create()
+ expect(() => f.runCommand({ type: 'task.approve', conversationId: plain, suggestedAgentId: f.other })).toThrow(expect.objectContaining({ code: 'TASK_SUGGESTION_CHANGED' }))
+ f.runCommand({ type: 'task.approve', conversationId: plain, suggestedAgentId: null })
+ expect(f.card(plain).taskApproval?.state).toBe('approved')
+ })
+
it('refuses another person, PM or Buddy approval and old membership authority before receipt replay', () => {
const f = fixture(); f.mode('review'); const id = f.create()
for (const actor of [owner, outsider, f.pm, f.buddyActor]) for (const type of ['task.approve', 'task.reject'])
diff --git a/backend/src/superTabs/taskLine.ts b/backend/src/superTabs/taskLine.ts
index a8fedeb99..453b58e25 100644
--- a/backend/src/superTabs/taskLine.ts
+++ b/backend/src/superTabs/taskLine.ts
@@ -1,7 +1,6 @@
import { projectPm } from './crewNeeds.js'
import { agentDisplayName } from './agentNames.js'
import { isBuddyChat } from './buddies.js'
-import { shippedNotice } from './buddyNews.js'
import { activeWork, isLeads, stableId, type Assignment, type Author, type CommandEffects, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
import { groupProject, projectsOf } from './projects.js'
import type { Reaction } from './reactions.js'
@@ -138,11 +137,6 @@ export function syncTaskLines(before: SuperTabState, effects: CommandEffects, se
function moved(state: SuperTabState, effects: CommandEffects, group: Conversation, previous: Conversation | undefined, sender: Author | undefined,
operationId: string): void {
if (group.cards?.line || group.ledger?.proposal) inThread(state, effects, group, previous, sender, operationId)
- // Only its first recorded merge is news to the Buddy, as the Shipped line was: a merge recorded again tells nobody again.
- if (group.ledger?.mergedAt != null && previous?.ledger?.mergedAt == null) {
- const news = sender && shippedNotice(state, group, sender, operationId)
- if (news) effects.messages.push(news)
- }
}
/** [group]'s replies in the thread of the message that asked for it: its name when it opens there (several tasks may share one
diff --git a/cli/src/services/usage.spec.ts b/cli/src/services/usage.spec.ts
index faedd2713..6258afd97 100644
--- a/cli/src/services/usage.spec.ts
+++ b/cli/src/services/usage.spec.ts
@@ -21,6 +21,8 @@ const CODEX: CodexRateLimits = {
secondary: { usedPercent: 7, windowDurationMins: 10_080, resetsAt: s('2026-11-12T00:00:00Z') },
}
const NO_REPORT = 'Claude Code has not reported its allowance on this machine yet: it does after its first reply in a session Harness started.'
+const STALE_REPORT = 'Claude Code last reported its allowance on this machine more than an hour ago: it reports again after its next reply in a session Harness started.'
+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-')) })
@@ -82,12 +84,26 @@ describe('the usage service', () => {
] })
})
- it('usage_read: an old report still answers, and a window whose reset has passed reads as unused', async () => {
- report({ five_hour: { used_percentage: 98, resets_at: s('2026-11-06T20:00:00Z') }, seven_day: { used_percentage: 60, resets_at: s('2026-11-10T00:00:00Z') } },
- undefined, NOW - 9 * 3_600_000)
+ it('usage_read: a window whose reset has passed is unknown, never unused; one with none left is unknown, with why (task #4217)', async () => {
+ report({ five_hour: { used_percentage: 98, resets_at: s('2026-11-07T00:30:00Z') }, seven_day: { used_percentage: 60, resets_at: s('2026-11-10T00:00:00Z') } })
const reply = await usage().requests.usage_read!({}, ASKER) as { providers: Array<Record<string, unknown>> }
- expect(reply.providers[0]).toMatchObject({ outcome: 'answered',
- body: { five_hour: { utilization: 0, resets_at: null }, seven_day: { utilization: 60, resets_at: '2026-11-10T00:00:00.000Z' } } })
+ expect(reply.providers[0]).toMatchObject({ outcome: 'answered', body: { seven_day: { utilization: 60, resets_at: '2026-11-10T00:00:00.000Z' } } })
+ expect(reply.providers[0]!.body).not.toHaveProperty('five_hour')
+ expect(quotaOf(reply, 'claude', false).windows).toEqual([{ name: 'weekly', usedPercent: 60, resetsAt: '2026-11-10T00:00:00.000Z' }])
+ report({ five_hour: { used_percentage: 98, resets_at: s('2026-11-07T00:30:00Z') } })
+ const passed = await usage().requests.usage_read!({}, ASKER) as Record<string, unknown>
+ expect((passed.providers as unknown[])[0]).toEqual({ provider: 'claude', account: null, outcome: 'unreachable', source: 'cli', message: RESET_SINCE })
+ expect(quotaOf(passed, 'claude', false).known).toBe(false)
+ })
+
+ it('usage_read: a report more than an hour old is unknown, with why, however its windows read (task #4217)', async () => {
+ const windows = { five_hour: { used_percentage: 20, resets_at: s('2026-11-07T03:00:00Z') }, seven_day: { used_percentage: 60, resets_at: s('2026-11-10T00:00:00Z') } }
+ report(windows, undefined, NOW - 3_600_000)
+ expect(((await usage().requests.usage_read!({}, ASKER)) as { providers: Array<Record<string, unknown>> }).providers[0]).toMatchObject({ outcome: 'answered' })
+ report(windows, undefined, NOW - 3_600_001)
+ const stale = await usage().requests.usage_read!({}, ASKER) as Record<string, unknown>
+ expect((stale.providers as unknown[])[0]).toEqual({ provider: 'claude', account: null, outcome: 'unreachable', source: 'cli', message: STALE_REPORT })
+ expect(quotaUnknownReason(stale, 'claude')).toBe(STALE_REPORT)
})
it('usage_read: no report yet is unreachable, with the reason the route shows', async () => {
diff --git a/cli/src/services/usage.ts b/cli/src/services/usage.ts
index 0c7bb6fa1..8accca594 100644
--- a/cli/src/services/usage.ts
+++ b/cli/src/services/usage.ts
@@ -13,7 +13,7 @@ import type { CorePorts } from '../core/api.js'
*/
import type { CoreApi, ServiceRequests } from '../core/api.js'
import { readCodexRateLimits, type CodexRateLimits, type CodexWindow } from '../lib/codexRateLimits.js'
-import { accountKey, readClaudeReport, type ClaudeReport, type ClaudeReportWindow, type UsageProviderId } from '../lib/quotaReports.js'
+import { accountKey, readClaudeReport, type ClaudeReport, type UsageProviderId } from '../lib/quotaReports.js'
import { profileHome } from '../lib/claudeProfiles.js'
import { internalOnThrow } from './requestErrors.js'
@@ -46,6 +46,11 @@ const DEPS: UsageDeps = { codex: readCodexRateLimits, now: Date.now, env: proces
/** 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.'
+/** How long a Claude report stands: Claude Code writes one after each reply, and the account's own use elsewhere moves it
+ * unseen, so an older one is a guess, not a reading (task #4217). */
+const CLAUDE_REPORT_FRESH_MS = 60 * 60_000
+const STALE_CLAUDE_REPORT = 'Claude Code last reported its allowance on this machine more than an hour ago: it reports again after its next reply in a session Harness started.'
+const RESET_SINCE_REPORT = 'Claude Code\'s allowance reset after its last report on this machine: it reports again after its next reply in a session Harness started.'
const CODEX_UNREACHABLE = {
missing: 'Codex is not installed where this machine\'s daemon can start it.',
failed: 'Codex did not answer when asked for its allowance on this machine.',
@@ -97,24 +102,25 @@ export function startUsage(core: CoreApi, deps: UsageDeps = DEPS): ServiceReques
}
}
-/** Claude's report as Anthropic's usage answer was shaped (`utilization`, ISO `resets_at`). A report is kept however old:
- * each window says when it resets, and one whose reset has passed is unused until Claude Code reports again. */
+/** Claude's report as Anthropic's usage answer was shaped (`utilization`, ISO `resets_at`). Only what it still knows: a report
+ * over [CLAUDE_REPORT_FRESH_MS] old is unknown, and so is a window whose reset has passed since, which says nothing of its use
+ * after the reset; never read as unused (task #4217). */
function claudeReading(report: ClaudeReport | null, now: number): UsageReading {
- if (!report) return { provider: 'claude', account: null, outcome: 'unreachable', source: 'cli', message: NO_CLAUDE_REPORT }
+ const unknown = (message: string): UsageReading => ({ provider: 'claude', account: null, outcome: 'unreachable', source: 'cli', message })
+ if (!report) return unknown(NO_CLAUDE_REPORT)
+ if (now - report.at > CLAUDE_REPORT_FRESH_MS) return unknown(STALE_CLAUDE_REPORT)
const body: Record<string, unknown> = {}
for (const name of ['five_hour', 'seven_day'] as const) {
const window = report[name]
- if (window) body[name] = claudeWindow(window, now)
+ const resetsAt = window?.resets_at == null ? null : window.resets_at * 1000
+ if (window && (resetsAt === null || resetsAt > now)) {
+ body[name] = { utilization: window.used_percentage, resets_at: resetsAt === null ? null : new Date(resetsAt).toISOString() }
+ }
}
+ if (!Object.keys(body).length) return unknown(RESET_SINCE_REPORT)
return { provider: 'claude', account: null, outcome: 'answered', httpStatus: 200, source: 'cli', body }
}
-function claudeWindow(window: ClaudeReportWindow, now: number) {
- const resetsAt = window.resets_at === null ? null : window.resets_at * 1000
- if (resetsAt !== null && resetsAt <= now) return { utilization: 0, resets_at: null }
- return { utilization: window.used_percentage, resets_at: resetsAt === null ? null : new Date(resetsAt).toISOString() }
-}
-
/** Codex's read as its usage answer was shaped (`rate_limit.primary_window`, seconds-long windows, unix `reset_at`). */
function codexReading(read: CodexRateLimits): UsageReading {
if (!read.ok) {
diff --git a/desktop/lib/super_tabs/tasks/personal_tasks_pane.dart b/desktop/lib/super_tabs/tasks/personal_tasks_pane.dart
index 2b83530bf..bfcd1d504 100644
--- a/desktop/lib/super_tabs/tasks/personal_tasks_pane.dart
+++ b/desktop/lib/super_tabs/tasks/personal_tasks_pane.dart
@@ -457,6 +457,10 @@ class _TasksPaneState extends State<SuperTabPersonalTasksPane> {
'type': 'task.approve',
'conversationId':
task.id,
+ // The agent shown, null for none: a suggestion changed
+ // since is refused (task #4217).
+ 'suggestedAgentId':
+ task.agentId,
})
: null,
child: const Text('Approve'),
diff --git a/desktop/test/super_tab_personal_tasks_pane_test.dart b/desktop/test/super_tab_personal_tasks_pane_test.dart
index 4100b496b..479feef50 100644
--- a/desktop/test/super_tab_personal_tasks_pane_test.dart
+++ b/desktop/test/super_tab_personal_tasks_pane_test.dart
@@ -203,6 +203,7 @@ void main() {
expect(f.commands.single, {
'type': 'task.approve',
'conversationId': 'new',
+ 'suggestedAgentId': '0540',
});
});
}
@@ -221,9 +222,28 @@ void main() {
expect(f.commands.single, {
'type': 'task.approve',
'conversationId': 'new',
+ 'suggestedAgentId': '0540',
});
expect(find.text('Task new'), findsOneWidget);
});
+ testWidgets('approve with no agent shown says none was shown', (t) async {
+ await mount(t);
+ f.rows.last
+ ..['agent'] = null
+ ..['suggested'] = false
+ ..['version'] = 2;
+ await f.controller.refresh();
+ await t.pump();
+ await t.tap(find.text('Task new'));
+ await t.pump();
+ await t.tap(find.text('Approve'));
+ await t.pumpAndSettle();
+ expect(f.commands.single, {
+ 'type': 'task.approve',
+ 'conversationId': 'new',
+ 'suggestedAgentId': null,
+ });
+ });
testWidgets('rejection needs a reason and remains in the list', (t) async {
await mount(t);
await t.tap(find.text('Task new'));
diff --git a/docs/plans/2026-11-07-trust-fixes-plan.md b/docs/plans/2026-11-07-trust-fixes-plan.md
new file mode 100644
index 000000000..2c2416aed
--- /dev/null
+++ b/docs/plans/2026-11-07-trust-fixes-plan.md
@@ -0,0 +1,90 @@
+# Trust fixes (task #4217) Implementation Plan
+
+> Written by the Engineer by the project's way of working: superpowers writing-plans, then each task test first
+> (test-driven-development), one pull request.
+
+**Goal:** Six things the Swarm says or counts that it cannot back: fix each, with a test that fails without the fix.
+
+**Architecture:** Each fix stays in the module that owns the behavior: Buddy news (`buddyNews.ts`, `taskLine.ts`,
+`releases.ts`), assignment (`commands.ts`), liveness (`liveness.ts`), task approval (`commands.ts`), the Leaderboard
+(`leaderboard/stats.ts`, `leaderboard/brought.ts`), and the CLI's Claude allowance reading (`cli/src/services/usage.ts`).
+
+**Tech Stack:** TypeScript, vitest (backend), the CLI's spec runner, Flutter for the one Desktop line.
+
+**Spec:** Task #4217's brief, from anh Dee's Buddy's review of main 0413586e.
+
+## Verification (before any code)
+
+| Finding | Verdict | Evidence |
+|---|---|---|
+| `conversation.merged` sends "shipped" with no release check (taskLine.ts:143) | Real | `moved()` sends `shippedNotice` when `ledger.mergedAt` is first set; `settleReleases` marks `released` later and tells only proposals. |
+| Assigned news repeats for every replacement agent (commands.ts:1946) | Real | `assignTo` calls `assignedNotice` on every assignment; a lost task re-assigned tells the Buddy again. |
+| "Which they requested" trusts an unproven field (buddyNews.ts:65) | Partly real | `requesterId` is checked only to be a person who reads the project; an agent may name anyone, and it wins over the request message's author. The Buddy states it as the person's own request. |
+| Waiting at a person's prompt is lost as no progress (liveness.ts:268) | Real | `waitingOnPerson` reads only `needs_human`/`blocked`; a terminal at a permission prompt (`alerting: 'prompt'`, `agent.alert`) prints nothing, so its lease runs out. |
+| `task.approve` names no agent (commands.ts:446) | Real | The command carries only the conversation; a `task.suggest` between the person's look and the tap approves an agent they never saw. |
+| Leaderboard counts any done task as Shipped (leaderboard/record.ts:111) | Real | `recordStatus` sets `shippedAt` at Done; the board counts `shippedAt` plus any linked PR, merged or not. |
+| Claude reports never expire; unknown counts as available (usage.ts, route.ts:495) | Real | `claudeReading` keeps a report however old, and a window whose reset passed reads as 0% used, so the route says it fits with all its allowance. |
+
+## Global Constraints
+
+- Never read or print a secret or a login. Clients from the last 30 days keep working.
+- No new stored field; no new query.
+
+## Review Focus
+
+- The release path tells the Buddy once per release, by a stable id.
+- The approval refusal cannot block a client that sends no agent (compatibility until 2026-12-07).
+
+## Task 1: Shipped news only when a release holds the work
+
+**Files:** `backend/src/superTabs/taskLine.ts`, `releases.ts`, `buddyNews.ts`, `releases.test.ts`
+**Interfaces:** `settleReleases` adds `shippedNotice` drafts to `outcome.messages`.
+
+- [x] Test: a merge sends the Buddy no shipped news; the settle that marks it released does, once.
+- [x] Run it: fails (news at merge, none at release).
+- [x] Move the notice from `taskLine.ts moved()` to `settleReleases`, authored by the project's lead.
+- [x] Run it: passes.
+
+## Task 2: Assigned news once per task
+
+**Files:** `backend/src/superTabs/commands.ts`, `buddyNews.test.ts`
+
+- [x] Test: a task lost and assigned to a replacement tells the Buddy once.
+- [x] Run it: fails. Send the notice only on the task's first assignment (`ledger.firstAssignedAt` unset before it). Passes.
+
+## Task 3: The Buddy says only what the server knows
+
+**Files:** `backend/src/superTabs/buddyNews.ts`, `buddyNews.test.ts`
+
+- [x] Test: the news says the task is in the person's name, not that they requested it.
+- [x] Run it: fails. Change both notices' words. Passes.
+
+## Task 4: A task at a person's prompt is not lost
+
+**Files:** `backend/src/superTabs/liveness.ts`, `liveness.test.ts`
+
+- [x] Test: a working task whose agent's terminal waits at a prompt, quiet past its lease, is not lost; once the prompt
+ closes it is lost as before.
+- [x] Run it: fails. `waitingOnPerson` also reads the agent's open `prompt` alert. Passes.
+
+## Task 5: Approval names the agent shown
+
+**Files:** `backend/src/superTabs/commands.ts`, `taskApproval.test.ts`, `desktop/lib/super_tabs/tasks/personal_tasks_pane.dart`, its test
+
+- [x] Test: `task.approve` naming an agent other than the current suggestion is refused and approves nothing.
+- [x] Run it: fails (schema refuses the field). Add `suggestedAgentId` (nullable, optional until 2026-12-07; compared, never read as an agent) and refuse a mismatch.
+- [x] Desktop sends the agent it shows.
+
+## Task 6: Leaderboard counts merges
+
+**Files:** `backend/src/superTabs/leaderboard/stats.ts`, `leaderboard/brought.ts`, a stats test
+
+- [x] Test: a done task with a linked, unmerged PR is not Shipped on the board.
+- [x] Run it: fails. Count `ledger.mergedAt`. Passes.
+
+## Task 7: Claude reports expire; unknown is unknown
+
+**Files:** `cli/src/services/usage.ts`, `usage.spec.ts`
+
+- [x] Test: a report older than an hour, and a window whose reset passed, read as unknown with a reason.
+- [x] Run it: fails. Expire reports after an hour; leave a passed window out. Passes.