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(swarm): a review nobody reviews closes once its PRs are merged or closed; a Lead can cancel an unassigned task (#2322)

0xken15b3ec5e332b78
diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.ts
index b7f00021e..e605133c6 100644
--- a/backend/integration/superTabTidy.test.ts
+++ b/backend/integration/superTabTidy.test.ts
@@ -381,6 +381,133 @@ describe('a finished group', () => {
})
})
+// Ken, 2026-10-30: 28 of 31 open review groups waited for a Reviewer on pull requests already merged or closed.
+describe('a review nobody reviews', () => {
+ const PR = 'https://github.com/example/parser/pull/9'
+ const github = (states: Record<string, PullRequestState>) => ({ async state(url: string) { return states[url] ?? null }, async done() {} })
+ /** A Swarm whose Builder marked "Parser v2" ready with PR, and whose review opened with no Reviewer free (or [reviewer]). */
+ async function waiting(withReviewer = false) {
+ const f = await swarm()
+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } })
+ const data = head.data as { projects: Array<Record<string, unknown>> }
+ data.projects[0]!.repository = { machineId: 'lead-host', cwd: '/repo', repositoryUrl: 'https://github.com/example/parser' }
+ await db.swarmHead.update({ where: { id: head.id }, data: { data: data as object } })
+ const reviewed = String((await f.execute({ type: 'conversation.create', title: 'Parser v2', brief: 'More parsing',
+ checks: [{ description: 'Verified', independent: true }] })).result.conversationId)
+ const builder = await f.add(reviewed, 'test-host', randomUUID(), 'Builder')
+ const work = String((await f.execute({ type: 'work.assign', conversationId: reviewed, agentId: builder })).result.assignmentId)
+ if (withReviewer) {
+ const session = randomUUID()
+ const reviewer = await f.add('lead', 'test-host', session, 'Reviewer')
+ // A strong model on the engine its machine offers, which reports it running: a Reviewer below quality 2, whose machine
+ // is silent, or whose engine cannot start there, is never picked (rules.ts reviewRefusal, autoReview.ts unable).
+ await f.started(reviewer, { role: 'reviewer', configuration: { ...config, model: 'gpt-6.1-sol' } })
+ await f.observe('test-host', [f.harness.worker, session])
+ }
+ const ready = (text: string) => f.execute({ type: 'work.status', conversationId: reviewed, assignmentId: work, status: 'review', result: text }, host, builder)
+ await ready(`Ready: yes, revision abc..def. ${PR}`)
+ const reviews = async () => (await db.swarmGroup.findMany({ where: { tabId: f.tab, deleted: false } }))
+ .filter(row => (row.data as { reviewOf?: string }).reviewOf === reviewed)
+ const review = (await reviews())[0]!
+ const closeLines = async () => (await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: review.key } }))
+ .filter(m => (m.source as { kind?: string } | null)?.kind === 'auto-archive')
+ const isArchived = async () => (await db.swarmGroup.findUniqueOrThrow({ where: { id: review.id } })).archived
+ return { ...f, reviewed, builder, work, ready, reviews, review, closeLines, isArchived }
+ }
+
+ it('closes 30 minutes after its last message once every pull request of the work it reviews is merged, with one line saying why', async () => {
+ const f = await waiting()
+ expect((f.review.data as { assignment: unknown }).assignment).toBeNull()
+ expect(f.review.workFinished).toBe(true)
+ f.clock.now += 29 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ f.clock.now += MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(true)
+ expect(await f.closeLines()).toEqual([expect.objectContaining({ recipientIds: [], author: expect.objectContaining({ id: f.lead }),
+ text: 'Closed: #9 merged; no Swarm review is needed now.' })])
+ // The work it reviews is untouched: its Builder still waits, for the Lead to settle.
+ expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.reviewed } })).archived).toBe(false)
+ })
+
+ it('stays open while a pull request of the work it reviews is open, reopened, or unknown to GitHub', async () => {
+ const SECOND = 'https://github.com/example/parser/pull/10'
+ for (const states of [{ [PR]: 'open' }, { [PR]: null }, { [PR]: 'merged', [SECOND]: 'open' }] as Array<Record<string, PullRequestState>>) {
+ const f = await waiting()
+ // A second pull request linked to the work it reviews only, after the review opened.
+ await f.execute({ type: 'message.send', conversationId: f.reviewed, text: `Follow-up: ${SECOND}`, replyTo: null, recipientIds: [] })
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github(states), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ expect(await f.closeLines()).toEqual([])
+ }
+ })
+
+ it('never closes while a Reviewer works on it', async () => {
+ const f = await waiting(true)
+ expect((f.review.data as { assignment: { status: string } }).assignment.status).toBe('working')
+ expect(f.review.workFinished).toBe(false)
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ })
+
+ it('is found once the worker marks it at startup when it was written before reviews took the mark', async () => {
+ const f = await waiting()
+ await db.swarmGroup.update({ where: { id: f.review.id }, data: { workFinished: false } })
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(false)
+ expect(await markFinishedGroups(db)).toBeGreaterThanOrEqual(1)
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(true)
+ })
+
+ // Review of #2322: a Ready committed inside the close's write saw the review still open and opened none; the close then
+ // archived it, and the work was left with no review, silently (the 10-28 failure).
+ it('stays open when a Ready for review with a new pull request commits during its close, so the work keeps a review', async () => {
+ const f = await waiting()
+ let during: (() => Promise<unknown>) | null = () => f.ready('Ready: yes, revision fff. https://github.com/example/parser/pull/11')
+ const hooked = db.$extends({ query: { superTabDecision: { async findFirst({ args, query }) {
+ if (during && (args.where as { conversationId?: string } | undefined)?.conversationId === f.review.key) { const run = during; during = null; await run() }
+ return query(args)
+ } } } })
+ const closing = new SuperTabStore(hooked as unknown as PrismaClient, () => f.clock.now)
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, closing, github({ [PR]: 'merged' }), f.clock.now)
+ expect(during).toBeNull()
+ expect(await f.isArchived()).toBe(false)
+ expect(await f.closeLines()).toEqual([])
+ expect((await f.reviews()).filter(row => !row.archived)).toHaveLength(1)
+ })
+
+ it('is cancelled by its Lead with "current": it archives with the reason, and what waited there for the Lead ends', async () => {
+ const f = await waiting()
+ const waitingFor = await db.superTabDelivery.findMany({ where: { tabId: f.tab, conversationId: f.review.key, status: 'queued' } })
+ expect(waitingFor.map(d => d.agentId)).toEqual([f.lead])
+ await f.execute({ type: 'work.cancel', conversationId: f.review.key, assignmentId: 'current', reason: 'Reviewed outside the Swarm' }, host, f.lead)
+ expect(await f.isArchived()).toBe(true)
+ expect((await db.superTabDelivery.findMany({ where: { id: { in: waitingFor.map(d => d.id) } } })).map(d => d.status)).toEqual(['cancelled'])
+ const line = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, conversationId: f.review.key, text: { startsWith: 'The Lead cancelled' } } })
+ expect(line).toMatchObject({ text: 'The Lead cancelled this task: Reviewed outside the Swarm.', recipientIds: [] })
+ })
+
+ it('opens a new review when the work comes back ready with an open pull request after the close, and tells the Lead', async () => {
+ const f = await waiting()
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [PR]: 'merged' }), f.clock.now)
+ expect(await f.isArchived()).toBe(true)
+ await f.execute({ type: 'work.status', conversationId: f.reviewed, assignmentId: f.work, status: 'working', result: null }, host, f.builder)
+ await f.ready('Ready: yes, revision fff. https://github.com/example/parser/pull/11')
+ const open = (await f.reviews()).filter(row => !row.archived)
+ expect(open).toHaveLength(1)
+ expect(open[0]!.key).not.toBe(f.review.key)
+ const told = await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: open[0]!.key, recipientIds: { has: f.lead } } })
+ expect(told.map(m => m.text)).toEqual([expect.stringContaining('Review opened by itself for #')])
+ })
+})
+
describe('the archive pass', () => {
it('reads each pull request once however many groups link it', async () => {
const PR = 'https://github.com/acme/app/pull/9'
@@ -397,6 +524,25 @@ describe('the archive pass', () => {
expect(read.filter(url => url === PR)).toEqual([PR])
})
+ // Review of #2322: a busy group whose write kept conflicting ended the pass for every group after it.
+ it('skips a group whose write fails, with a warning, and goes on to the rest', async () => {
+ const f = await swarm()
+ const second = String((await f.execute({ type: 'conversation.create', title: 'Docs', brief: 'Docs too', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
+ const writer = await f.add(second, 'test-host', randomUUID(), 'Writer')
+ const work = String((await f.execute({ type: 'work.assign', conversationId: second, agentId: writer })).result.assignmentId)
+ await f.execute({ type: 'work.cancel', conversationId: second, assignmentId: work, reason: 'Done elsewhere' })
+ // f.group went quiet first, so the pass reaches it first.
+ const failing: Pick<SuperTabStore, 'archiveFinished'> = { archiveFinished: async (tabId, groupId, checked, reviewOf) => {
+ if (groupId === f.group) throw new Error('write conflict')
+ return f.timed.archiveFinished(tabId, groupId, checked, reviewOf)
+ } }
+ f.clock.now += 40 * MINUTE
+ await expect(archiveFinishedGroups(db, failing, { state: async () => null, done: async () => {} }, f.clock.now)).resolves.toBeGreaterThanOrEqual(1)
+ const archivedOf = async (key: string) => (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key } })).archived
+ expect(await archivedOf(f.group)).toBe(false)
+ expect(await archivedOf(second)).toBe(true)
+ })
+
it('finds a finished group written before the finished mark once the worker marks it at startup', async () => {
const f = await swarm()
const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.group } })
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 2e565fbcc..e936f742c 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -4352,7 +4352,7 @@ describe('a migrated Swarm\'s kept old state (Stability 2.1)', () => {
await db.superTab.update({ where: { id: own }, data: { legacyState: OLD_STATE } })
expect((await measured('list', () => store.list(solo))).tabs).toEqual([expect.objectContaining({ id: own, name: 'Solo', ownerId: solo.sub })])
expect(await measured('host grids', () => store.hostGrids(solo))).toEqual([expect.objectContaining({ tabId: own, enabled: true })])
- expect(await measured('archive', () => store.archiveFinished(tab, group, []))).toBe(false)
+ expect(await measured('archive', () => store.archiveFinished(tab, group, {}))).toBe(false)
const requestId = (await run(tab, { type: 'agent.screen', agentId: worker, scrollback: 20 }, host, lead)).result.requestId as string
expect((await measured('terminal pickup', () => store.hostTerminal(host, 'test-host'))).filter(row => row.tabId === tab).map(row => row.request.id))
.toEqual([requestId])
diff --git a/backend/src/superTabs/archive.ts b/backend/src/superTabs/archive.ts
index fcc823a8b..53d239d30 100644
--- a/backend/src/superTabs/archive.ts
+++ b/backend/src/superTabs/archive.ts
@@ -1,7 +1,7 @@
import type { Prisma, PrismaClient } from '@prisma/client'
import { PULL_READ_PERMISSIONS, type GitHubApp } from '../github/app.js'
import { githubRepository, type GitHubRepository } from '../github/repository.js'
-import type { Conversation } from './model.js'
+import { activeWork, type Conversation } from './model.js'
import type { HeadData } from './parts/index.js'
import type { SuperTabStore } from './store.js'
import { ARCHIVE_QUIET_MS } from './tidy.js'
@@ -10,7 +10,8 @@ import { logger } from '../utils/logger.js'
// A finished group archives by itself (roadmap, December: nobody tidies a Swarm by hand): its task done or cancelled, quiet
// for 30 minutes, no person's decision waiting there, and every pull request it links merged or closed. Only GitHub says
// that, over the network, so this runs in the singleton worker and never inside a Swarm's write; the write itself checks
-// everything the Swarm knows again (store.ts archiveFinished).
+// everything the Swarm knows again (store.ts archiveFinished). A review nobody is reviewing closes the same way once every
+// pull request of the work it reviews is merged or closed (tidy.ts reviewClosable).
export type PullRequestState = 'open' | 'merged' | 'closed' | null
/** What a sweep asks GitHub: a pull request's state (null: it cannot say), and `done` once the sweep is over. */
@@ -51,11 +52,18 @@ export function appPullRequests(app: GitHubApp): PullRequests {
const BATCH = 500
-/** Marks every part written before the finished mark whose task is done or cancelled, so the pass finds it: run once by the
- * worker at startup, as its other index work is. Every later write of a part sets the mark itself (parts/write.ts). */
+/** Marks every part written before the finished mark whose task is done or cancelled, and every open review written before
+ * reviews took the mark while nobody reviews them, so the pass finds it: run once by the worker at startup, as its other
+ * index work is. Every later write of a part sets the mark itself (parts/write.ts). */
export async function markFinishedGroups(db: PrismaClient): Promise<number> {
- const answer = await db.$runCommandRaw({ update: 'SwarmGroup', updates: [{ q: { workFinished: { $exists: false }, deleted: false,
- 'data.assignment.status': { $in: ['done', 'cancelled'] } }, u: { $set: { workFinished: true } }, multi: true }] })
+ const answer = await db.$runCommandRaw({ update: 'SwarmGroup', updates: [
+ { q: { workFinished: { $exists: false }, deleted: false, 'data.assignment.status': { $in: ['done', 'cancelled'] } }, u: { $set: { workFinished: true } }, multi: true },
+ // Open groups only (the mark's index leads with it and archived): the reviews waiting for a Reviewer on 2026-10-30.
+ // Measured on prod that day: about 290 index keys and documents examined, 1 ms; it marked 35. Remove it in the
+ // release after #2322's, once every part has been written or marked by it.
+ { q: { workFinished: { $in: [false, null] }, archived: false, deleted: false, 'data.reviewOf': { $type: 'string' },
+ $or: [{ 'data.assignment': null }, { 'data.assignment.status': { $in: ['done', 'stopped', 'cancelled', 'lost'] } }] }, u: { $set: { workFinished: true } }, multi: true },
+ ] })
return Number((answer as { nModified?: number }).nModified ?? 0)
}
@@ -71,6 +79,16 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperT
// One read per pull request a pass, however many groups link it.
const states = new Map<string, Promise<PullRequestState>>()
const stateOf = (url: string) => { if (!states.has(url)) states.set(url, prs.state(url)); return states.get(url)! }
+ // One group's failed write (a busy group's conflicts outlasting its retries, a GitHub error) skips that group for this
+ // pass, with a warning, instead of ending the pass for every group after it (review of #2322).
+ const archive = async (row: { tabId: string; key: string }, checked: Record<string, 'merged' | 'closed'>, reviewOf?: string) => {
+ try {
+ return await store.archiveFinished(row.tabId, row.key, checked, reviewOf)
+ } catch (error) {
+ logger.warn('[swarm-archive] group skipped', { tabId: row.tabId, group: row.key, error: error instanceof Error ? error.message : String(error) })
+ return false
+ }
+ }
let archived = 0, after: { at: Date; id: string } | null = null
try {
for (;;) {
@@ -79,11 +97,24 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperT
orderBy: [{ lastActivityAt: 'asc' }, { id: 'asc' }], take: BATCH, select: { id: true, tabId: true, key: true, lastActivityAt: true, data: true } })
for (const row of rows) {
const group = row.data as unknown as Conversation
- if (group.audience || !['done', 'cancelled'].includes(group.assignment?.status ?? '') || !await tidyOn(row.tabId)) continue
- const urls = group.pullRequestUrls ?? []
- let settled = true
- for (const url of urls) if (!['merged', 'closed'].includes(await stateOf(url) ?? '')) { settled = false; break }
- if (settled && await store.archiveFinished(row.tabId, row.key, urls)) archived++
+ const finished = ['done', 'cancelled'].includes(group.assignment?.status ?? ''), review = !!group.reviewOf && !activeWork(group)
+ if (group.audience || !(finished || review) || !await tidyOn(row.tabId)) continue
+ const checked: Record<string, 'merged' | 'closed'> = {}
+ // Stops at the first pull request still open, or that GitHub cannot read.
+ const settled = async (urls: string[]) => {
+ for (const url of urls) {
+ const state = await stateOf(url)
+ if (state !== 'merged' && state !== 'closed') return false
+ checked[url] = state
+ }
+ return true
+ }
+ const own = group.pullRequestUrls ?? []
+ if (finished && await settled(own) && await archive(row, checked)) { archived++; continue }
+ if (!review) continue
+ const reviewed = (await db.swarmGroup.findUnique({ where: { tabId_key: { tabId: row.tabId, key: group.reviewOf! } }, select: { data: true } }))?.data as unknown as Conversation | undefined
+ const urls = [...new Set([...own, ...reviewed?.pullRequestUrls ?? []])]
+ if (urls.length && await settled(urls) && await archive(row, checked, group.reviewOf)) archived++
}
if (rows.length < BATCH) return archived
after = { at: rows.at(-1)!.lastActivityAt, id: rows.at(-1)!.id }
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 8934c2b58..98ecda907 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -1336,6 +1336,57 @@ describe('cancelling work', () => {
f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })
expect(() => f.run(cancel, leadActor)).toThrow('already ended')
})
+
+ // Ken, 2026-10-30: a review no Reviewer was free for had no assignment to name, so a Lead could not cancel it.
+ describe('a task nobody was assigned', () => {
+ function unassigned() {
+ const f = fixture(); f.invite()
+ const lead = f.add('lead', 'owner', 'lead', true), group = f.group(), worker = f.add('worker', 'owner', group)
+ const leadActor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }
+ const workerActor: Actor = { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }
+ const cancel = { type: 'work.cancel', conversationId: group, assignmentId: 'current', reason: 'Merged outside the Swarm.' } as Command
+ const at = () => f.state.conversations.find(c => c.id === group)!
+ return { f, group, lead, leadActor, workerActor, cancel, at }
+ }
+
+ it('is cancelled by its Lead with "current": it archives, with the reason in one line to nobody', () => {
+ const { f, leadActor, cancel, at } = unassigned()
+ expect(at().assignment).toBeNull()
+ const effects = f.run(cancel, leadActor)
+ expect(at()).toMatchObject({ archived: true, assignment: null })
+ expect(effects.messages).toMatchObject([{ conversationId: at().id, recipients: [], text: 'The Lead cancelled this task: Merged outside the Swarm.' }])
+ // A retry finds it archived and changes nothing.
+ expect(() => f.run(cancel, leadActor)).toThrow('Reopen this conversation')
+ })
+
+ it('is cancelled by the tab owner the same way', () => {
+ const { f, cancel, at } = unassigned()
+ expect(f.run(cancel).messages.map(m => m.text)).toEqual(['The tab owner cancelled this task: Merged outside the Swarm.'])
+ expect(at().archived).toBe(true)
+ })
+
+ it('still answers a named assignment id that is not current as stale', () => {
+ const { f, leadActor, cancel, at } = unassigned()
+ expect(() => f.run({ ...cancel, assignmentId: '58c2d5f2bdc100771bc57de7' } as Command, leadActor)).toThrow('no longer the active assignment')
+ expect(at().archived).toBe(false)
+ })
+
+ it('refuses the worker, a collaborator and another project\'s Lead, and leaves it open', () => {
+ const { f, workerActor, cancel, at } = unassigned()
+ const project = f.run({ type: 'project.create', name: 'Other', visibility: 'public', brief: '' }).result
+ const otherLead = f.add('other-lead', 'owner', project.conversationId as string, true)
+ expect(() => f.run(cancel, workerActor)).toThrow('no longer the active assignment')
+ expect(() => f.run(cancel, peer)).toThrow('no longer the active assignment')
+ expect(() => f.run(cancel, { kind: 'agent', agentId: otherLead, machineOwnerId: 'host-owner' })).toThrow()
+ expect(at().archived).toBe(false)
+ })
+
+ it('never archives the Lead conversation through it', () => {
+ const { f, leadActor, cancel } = unassigned()
+ expect(() => f.run({ ...cancel, conversationId: 'lead' } as Command, leadActor)).toThrow('no longer the active assignment')
+ expect(f.state.conversations.find(c => c.id === 'lead')!.archived).toBe(false)
+ })
+ })
})
it('allows routing directly to the awaiting worker without first keeping it', () => {
@@ -1803,6 +1854,48 @@ describe('Reviewer role', () => {
.toEqual([['Review opened by itself for #1, but no Reviewer is free. Route it and start one.', true]])
})
+ // Ken, 2026-10-30: a review no Reviewer was free for could not be cancelled, and on 10-28 archiving an open review made
+ // the work's next Ready for review open nothing, silently.
+ it('lets the Lead cancel a review no Reviewer was free for, and the next Ready for review opens a new one and tells the Lead', () => {
+ const { f, lead, leadActor, reviewer, fresh, markReady, reviews } = ready()
+ for (const id of [reviewer, fresh]) f.run({ type: 'agent.release', agentId: id, decision: 'stop' }, leadActor)
+ markReady(`Ready. ${pr}`)
+ const first = reviews()[0]!
+ expect(first.assignment).toBeNull()
+ f.run({ type: 'work.cancel', conversationId: first.id, assignmentId: 'current', reason: 'Reviewed outside the Swarm' }, leadActor)
+ expect(reviews()[0]!.archived).toBe(true)
+ const again = markReady(`Ready, head 2. ${pr.replace('/42', '/43')}`)
+ expect(reviews()).toHaveLength(2)
+ const second = reviews().find(c => c.id !== first.id)!
+ expect(second.archived).toBe(false)
+ expect(again.messages.filter(m => m.conversationId === second.id && m.recipients.includes(lead)).map(m => m.text))
+ .toEqual([`Review opened by itself for #1, but no Reviewer is free. Route it and start one.`])
+ })
+
+ // Review of #2322: a review whose Reviewer stopped had an ended attempt, which the CLI names for "current", so it answered
+ // "already ended" and stayed open while its pull request was.
+ it('lets the Lead cancel a review whose Reviewer stopped, by "current" or by the ended attempt\'s id', () => {
+ for (const named of ['current', 'ended']) {
+ const { f, leadActor, markReady, reviews } = ready()
+ markReady(`Ready. ${pr}`)
+ const review = reviews()[0]!, attempt = review.assignment!.id
+ f.run({ type: 'work.status', conversationId: review.id, assignmentId: attempt, status: 'stopped', result: null }, owner, { confirmedStopped: true })
+ const effects = f.run({ type: 'work.cancel', conversationId: review.id, assignmentId: named === 'current' ? 'current' : attempt, reason: 'Merged' }, leadActor)
+ expect(reviews()[0]).toMatchObject({ archived: true, assignment: { status: 'stopped' } })
+ expect(effects.messages.map(m => [m.text, m.recipients])).toEqual([['The Lead cancelled this task: Merged.', []]])
+ }
+ })
+
+ it('opens a new review on the next Ready for review once the archive pass closed the open one (tidy.ts)', () => {
+ const { f, leadActor, reviewer, fresh, markReady, reviews } = ready()
+ for (const id of [reviewer, fresh]) f.run({ type: 'agent.release', agentId: id, decision: 'stop' }, leadActor)
+ markReady(`Ready. ${pr}`)
+ // As store.ts archiveFinished leaves it.
+ reviews()[0]!.archived = true
+ markReady(`Ready, head 2. ${pr}`)
+ expect(reviews().filter(c => !c.archived)).toHaveLength(1)
+ })
+
it('gives a delta review to the Reviewer of the earlier head while it is still free', () => {
const { f, group, builderActor, built, reviewer, fresh, markReady, reviews } = ready()
markReady(`Ready. ${pr}`)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index b908d87cf..76a23be18 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -2309,12 +2309,24 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'work.cancel': {
const group = open(state, command.conversationId)
const assignment = group.assignment
- if (!assignment || assignment.id !== command.assignmentId) fail('STALE_ASSIGNMENT', 'This is no longer the active assignment.')
const project = groupProject(state, group)
const isLead = actor.kind === 'agent' && conversation(state, project.leadConversationId).leadId === actor.agentId
- if (!isLead && !(actor.kind === 'person' && actor.userId === state.ownerId)) {
- fail('FORBIDDEN', 'Only this project’s Lead or the tab owner can cancel work.', 403)
+ const allowed = isLead || (actor.kind === 'person' && actor.userId === state.ownerId)
+ // A task nobody was ever assigned, such as a review no Reviewer was free for, has no assignment to name: its Lead or
+ // the tab owner cancels it by "current", and it archives with the reason (Ken, 2026-10-30: 28 reviews waited for a
+ // Reviewer with no way out). So does a review whose Reviewer stopped or finished, by "current" or that ended attempt's
+ // id (the CLI fills "current" with it). A named id, a chat, or anyone else is refused as before.
+ const unassigned = !assignment && command.assignmentId === 'current'
+ const reviewEnded = !!group.reviewOf && !!assignment && ['stopped', 'done'].includes(assignment.status)
+ && (command.assignmentId === 'current' || command.assignmentId === assignment.id)
+ if ((unassigned || reviewEnded) && allowed && group.id !== project.leadConversationId && !group.kind && !group.audience) {
+ message(group.id, `${isLead ? 'The Lead' : 'The tab owner'} cancelled this task: ${command.reason.replace(/[.\s]+$/, '')}.`, [], null, SYSTEM_ROW)
+ // Its line is a report the Lead acknowledges first, so the sweep puts it to sleep later (sweeps.ts), as for any archive.
+ group.archived = true
+ break
}
+ if (!assignment || assignment.id !== command.assignmentId) fail('STALE_ASSIGNMENT', 'This is no longer the active assignment.')
+ if (!allowed) fail('FORBIDDEN', 'Only this project’s Lead or the tab owner can cancel work.', 403)
// A retry after the cancel keeps the first reason and tells the worker once.
if (assignment.status === 'cancelled') break
const lost = assignment.status === 'lost'
diff --git a/backend/src/superTabs/parts/write.test.ts b/backend/src/superTabs/parts/write.test.ts
index b4ddab1fa..18a1e77ab 100644
--- a/backend/src/superTabs/parts/write.test.ts
+++ b/backend/src/superTabs/parts/write.test.ts
@@ -38,4 +38,10 @@ describe('the finished-work mark a conversation write stores', () => {
expect(extracted('group', group('cancelled'), 1).workFinished).toBe(true)
for (const status of ['working', 'review', 'lost', 'stopped', null]) expect(extracted('group', group(status), 1).workFinished).toBe(false)
})
+
+ it('is set on a review while no Reviewer works on it, so the pass can close it once its pull requests are (tidy.ts)', () => {
+ const review = (status: string | null) => ({ ...group(status), reviewOf: 'built' })
+ for (const status of [null, 'lost', 'stopped', 'done', 'cancelled']) expect(extracted('group', review(status), 1).workFinished).toBe(true)
+ for (const status of ['working', 'review', 'needs_human', 'blocked']) expect(extracted('group', review(status), 1).workFinished).toBe(false)
+ })
})
diff --git a/backend/src/superTabs/parts/write.ts b/backend/src/superTabs/parts/write.ts
index ba2488268..9498d8405 100644
--- a/backend/src/superTabs/parts/write.ts
+++ b/backend/src/superTabs/parts/write.ts
@@ -68,7 +68,8 @@ export function extracted(kind: PartKind, data: unknown, stamp: number): Record<
agentIds: group.agentIds, executionMachineId: activeWork(group) ? group.assignment!.execution.machineId : null,
messageSeq: group.messageSeq ?? 0, reportSeq: group.reportSeq ?? 0,
lastActivityAt: group.lastActivityAt ? new Date(group.lastActivityAt) : new Date(stamp), hostDigest: hostDigest(group),
- workFinished: ['done', 'cancelled'].includes(group.assignment?.status ?? '') }
+ // A review with no active Reviewer is read by the archive pass too: it closes once its pull requests are (tidy.ts reviewClosable).
+ workFinished: ['done', 'cancelled'].includes(group.assignment?.status ?? '') || (!!group.reviewOf && !activeWork(group)) }
}
case 'agent': {
const agent = data as Agent
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 332c1cf30..c2efbfcf7 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -31,7 +31,7 @@ import { confidentialSessions, otherRegistrations, recordConfidential } from './
import { answersRequest, dirtyGroups, noteProjectReports, projectUpdateRequest, UNANSWERED_REQUEST_MS } from './projectUpdates.js'
import { digestDue, digestMessageId, digestRequest, digestSince } from './digest.js'
import { judgedMachines, loseTasks, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'
-import { archivable, archiveLine, ASLEEP_FIELDS, asleepMatch, stopIdleWorkers, stoppedMachines, type GroupActivity } from './tidy.js'
+import { archivable, archiveLine, ASLEEP_FIELDS, asleepMatch, reviewClosable, reviewCloseLine, reviewPullRequests, stopIdleWorkers, stoppedMachines, type GroupActivity } from './tidy.js'
import { clock, insertParts, loadActive, loadLightGroups, loadObserved, reassemble, split, type GroupData, type HeadData, type Part, type SwarmParts } from './parts/index.js'
import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'
import { memberSwarms } from './swarmRows.js'
@@ -1330,6 +1330,9 @@ export class SuperTabStore {
// so a claim of one conflicts with it. An archived conversation, or one its receiver left, ends them: kept for a
// reopening, 6 of the 9 deliveries prod watch found stuck for days on 2026-10-28 waited in archived groups, unread.
const unreadable = command.type === 'conversation.archive' && command.archived || command.type === 'conversation.agent' && !command.present
+ // A task cancelled with no assignment archives (commands.ts work.cancel).
+ || command.type === 'work.cancel' && !original.conversations.find(c => c.id === command.conversationId)?.archived
+ && !!effects.state.conversations.find(c => c.id === command.conversationId)?.archived
if (unreadable) {
await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: command.conversationId, status: { in: ['queued', 'claimed', 'uncertain'] },
...(command.type === 'conversation.agent' ? { agentId: command.agentId } : {}) },
@@ -2835,24 +2838,34 @@ export class SuperTabStore {
/** Archives a finished group whose pull requests `checked` were all read merged or closed (archive.ts), only if it still
* qualifies inside this write: no message since, no decision waiting and no pull request linked since the read. Its
- * waiting deliveries end, as a person's archive ends them. True when it archived. */
- async archiveFinished(tabId: string, groupId: string, checked: readonly string[]): Promise<boolean> {
+ * waiting deliveries end, as a person's archive ends them. With `reviewOf`, the group the pass read as the one it
+ * reviews, a review nobody is reviewing closes the same way once those of the work it reviews are too (tidy.ts
+ * reviewClosable). True when it archived. */
+ async archiveFinished(tabId: string, groupId: string, checked: Readonly<Record<string, 'merged' | 'closed'>>, reviewOf?: string): Promise<boolean> {
return transaction(this.db, async tx => {
const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
if (!row) return false
- const loaded = await loadRow(tx, requireParts(row), { groupIds: [groupId] }), state = structuredClone(loaded.state)
+ const loaded = await loadRow(tx, requireParts(row), { groupIds: reviewOf ? [groupId, reviewOf] : [groupId] }), state = structuredClone(loaded.state)
const group = state.conversations.find(c => c.id === groupId)
const now = this.now()
- if (!group || !archivable(state, group, now) || (group.pullRequestUrls ?? []).some(url => !checked.includes(url))) return false
+ if (!group) return false
+ const read = (urls: readonly string[]) => urls.every(url => checked[url] === 'merged' || checked[url] === 'closed')
+ const finished = archivable(state, group, now) && read(group.pullRequestUrls ?? [])
+ // Only the group it reviews as the pass read it: one this write did not load would hide its open pull requests.
+ const review = !finished && !!reviewOf && group.reviewOf === reviewOf && reviewClosable(state, group, now) && read(reviewPullRequests(state, group))
+ if (!finished && !review) return false
if (await waitingIn(tx, tabId, groupId)) return false
group.archived = true
- const line = archiveLine(state, group, now), rows = line ? [line] : []
+ const line = finished ? archiveLine(state, group, now) : reviewCloseLine(state, group, checked, now), rows = line ? [line] : []
const sequences = numberMessages(state, rows, now)
if (!dirtyGroups(state, groupProject(state, group)).includes(group)) group.dormant = true
// As a person's archive does (execute): a claim of a delivery here conflicts with this write.
await tx.superTabDelivery.updateMany({ where: { tabId, conversationId: groupId, status: { in: [...OPEN_DELIVERY] } },
data: { status: 'cancelled', holdReason: null, holdSince: null } })
- await this.save(tx, loaded, state, clock.next())
+ // A review's close also writes the work it reviews (review of #2322): a Ready for review committed since the load linked
+ // a new pull request and saw this review still open, so it opened none. The touch makes one of the two writes retry,
+ // and the retry sees the other: this one declines (a pull request not read), or that one opens a new review.
+ await this.save(tx, loaded, state, clock.next(), review ? [{ kind: 'group', key: group.reviewOf! }] : [])
await this.writeMessages(tx, tabId, state, rows, sequences)
return true
})
diff --git a/backend/src/superTabs/tidy.test.ts b/backend/src/superTabs/tidy.test.ts
index 254359118..548a1f02d 100644
--- a/backend/src/superTabs/tidy.test.ts
+++ b/backend/src/superTabs/tidy.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { agentOnly, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'
-import { ARCHIVE_QUIET_MS, archivable, IDLE_STOP_MS, stopIdleWorkers } from './tidy.js'
+import { ARCHIVE_QUIET_MS, archivable, IDLE_STOP_MS, reviewClosable, reviewCloseLine, reviewPullRequests, stopIdleWorkers } from './tidy.js'
const MINUTE = 60_000
const START = Date.parse('2026-10-27T08:00:00.000Z')
@@ -199,3 +199,55 @@ describe('which finished groups archive', () => {
expect(archivable(off, off.conversations[1]!, quiet)).toBe(false)
})
})
+
+// Ken, 2026-10-30: 28 of 31 open review groups waited for a Reviewer on pull requests already merged or closed.
+describe('which reviews nobody reviews may close', () => {
+ const quiet = START + ARCHIVE_QUIET_MS
+ const PR = 'https://github.com/acme/app/pull/2288', SECOND = 'https://github.com/acme/app/pull/2290'
+ /** Work still waiting for its review, linking [built], and its review with no Reviewer, linking [own]. */
+ const reviewState = (patch: Partial<Conversation> = {}, built: string[] = [PR], own: string[] = []) => swarm({ groups: [
+ group({ assignment: done({ status: 'review' }), pullRequestUrls: built }),
+ group({ id: 'r1', title: 'Review: Task', reviewOf: 'g1', assignment: null, pullRequestUrls: own, ...patch })] })
+ const review = (state: SuperTabState) => state.conversations[2]!
+
+ it('is a review with no Reviewer, or one whose Reviewer\'s task ended, quiet for 30 minutes, whose work links a pull request', () => {
+ for (const assignment of [null, done({ status: 'lost' }), done({ status: 'stopped' })]) {
+ const state = reviewState({ assignment })
+ expect(reviewClosable(state, review(state), quiet)).toBe(true)
+ expect(reviewClosable(state, review(state), quiet - 1)).toBe(false)
+ }
+ })
+
+ it('is never one a Reviewer works on', () => {
+ for (const status of ['working', 'review', 'needs_human', 'blocked'] as const) {
+ const state = reviewState({ assignment: done({ status }) })
+ expect(reviewClosable(state, review(state), quiet)).toBe(false)
+ }
+ })
+
+ it('is never one with no pull request anywhere: nothing can say the work needs no review', () => {
+ const state = reviewState({}, [])
+ expect(reviewClosable(state, review(state), quiet)).toBe(false)
+ })
+
+ it('is never an archived one, a chat, a group that reviews nothing, or any once tidying is off', () => {
+ for (const patch of [{ archived: true }, { audience: { people: [] } as never }, { kind: 'buddy' as const }, { reviewOf: undefined }]) {
+ const state = reviewState(patch)
+ expect(reviewClosable(state, review(state), quiet)).toBe(false)
+ }
+ const off = reviewState()
+ off.tidy = false
+ expect(reviewClosable(off, review(off), quiet)).toBe(false)
+ })
+
+ it('reads the pull requests of the review and of the work it reviews, each once', () => {
+ const state = reviewState({}, [PR, SECOND], [PR])
+ expect(reviewPullRequests(state, review(state))).toEqual([PR, SECOND])
+ })
+
+ it('says, as the Lead and to nobody, how each pull request ended', () => {
+ const state = reviewState({}, [PR, SECOND])
+ expect(reviewCloseLine(state, review(state), { [PR]: 'merged', [SECOND]: 'closed' }, quiet)).toMatchObject({ conversationId: 'r1', recipients: [],
+ author: { kind: 'agent', id: 'L' }, source: { kind: 'auto-archive' }, text: 'Closed: #2288 merged, #2290 closed; no Swarm review is needed now.' })
+ })
+})
diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.ts
index 4a990d8f2..3696575e6 100644
--- a/backend/src/superTabs/tidy.ts
+++ b/backend/src/superTabs/tidy.ts
@@ -149,11 +149,48 @@ export function archivable(state: SuperTabState, group: Conversation, now: numbe
/** The one quiet line an archived group gets, to nobody, written as its project's Lead; none when the project has no Lead. */
export function archiveLine(state: SuperTabState, group: Conversation, now: number): MessageDraft | null {
+ const prs = group.pullRequestUrls?.length ? ' and its pull requests are merged or closed' : ''
+ return leadLine(state, group, now, `Archived: the work is ${group.assignment!.status}${prs}.`)
+}
+
+function leadLine(state: SuperTabState, group: Conversation, now: number, text: string): MessageDraft | null {
const leadId = state.conversations.find(c => c.id === groupProject(state, group).leadConversationId)?.leadId
const lead = leadId ? state.agents.find(a => a.id === leadId) : undefined
if (!lead) return null
- const prs = group.pullRequestUrls?.length ? ' and its pull requests are merged or closed' : ''
return { id: stableId('auto-archive', group.id, String(now)), conversationId: group.id, replyTo: null, recipients: [],
author: { kind: 'agent', id: lead.id, name: lead.name, displayName: agentDisplayName(state.agents, lead.id), membershipGeneration: lead.membershipGeneration },
- text: `Archived: the work is ${group.assignment!.status}${prs}.`, source: { kind: 'auto-archive' } }
+ text, source: { kind: 'auto-archive' } }
+}
+
+// A review nobody is reviewing closes once the work it reviews needs no Swarm review (Ken, 2026-10-30): 28 of 31 open
+// review groups waited for a Reviewer on pull requests already merged, reviewed outside the Swarm or folded into a batch PR.
+// A review with no Reviewer has no task to finish or cancel, so `archivable` never matched it.
+
+/** A review group with no active Reviewer: none was ever free, or its Reviewer's task ended. The archive pass reads these
+ * as it reads finished work (parts/write.ts workFinished). */
+export const unattendedReview = (group: Conversation): boolean => !!group.reviewOf && !activeWork(group)
+
+/** The pull requests that decide whether an unattended review still matters: those it links and those of the work it reviews. */
+export function reviewPullRequests(state: SuperTabState, review: Conversation): string[] {
+ const reviewed = state.conversations.find(c => c.id === review.reviewOf)
+ return [...new Set([...review.pullRequestUrls ?? [], ...reviewed?.pullRequestUrls ?? []])]
+}
+
+/** Whether an unattended review may close by itself, as far as the Swarm alone can tell: it links, or the work it reviews
+ * links, a pull request, and it has been quiet for ARCHIVE_QUIET_MS. That each of those pull requests is merged or
+ * closed, and that no decision waits there, the caller checks (archive.ts, store.ts archiveFinished). */
+export function reviewClosable(state: SuperTabState, review: Conversation, now: number): boolean {
+ if (state.tidy === false || review.archived || review.kind || review.audience || !unattendedReview(review)) return false
+ if (projectsOf(state).some(p => p.leadConversationId === review.id)) return false
+ if (!reviewPullRequests(state, review).length) return false
+ const last = time(review.lastActivityAt)
+ return last !== undefined && now - last >= ARCHIVE_QUIET_MS
+}
+
+const pullNumber = (url: string) => `#${url.slice(url.lastIndexOf('/') + 1)}`
+
+/** The one quiet line a closed review gets, naming each pull request and how it ended. */
+export function reviewCloseLine(state: SuperTabState, review: Conversation, settled: Readonly<Record<string, 'merged' | 'closed'>>, now: number): MessageDraft | null {
+ const prs = reviewPullRequests(state, review).map(url => `${pullNumber(url)} ${settled[url]}`).join(', ')
+ return leadLine(state, review, now, `Closed: ${prs}; no Swarm review is needed now.`)
}