The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Swarm: never archive unfinished work silently; PR links only from real results (#1903)
0xken15990ef37ee283
diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.tsindex 2ddf6aceb..9e0310eb0 100644--- a/backend/integration/superTabTidy.test.ts+++ b/backend/integration/superTabTidy.test.ts@@ -9,6 +9,8 @@ import { PrismaClient } from '@prisma/client'import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'import type { Command } from '../src/superTabs/commands.js'+import type { Conversation } from '../src/superTabs/model.js'+import type { HeadData } from '../src/superTabs/parts/index.js'import type { MachineObservation } from '../src/superTabs/machines.js'import { poolRows, rosterRows } from './hostRows.test-support.js'import { archiveFinishedGroups, markFinishedGroups, type PullRequestState } from '../src/superTabs/archive.js'@@ -224,7 +226,7 @@ describe('a finished group', () => {expect(prs.read).toContain(PR)expect(prs.closed).toBe(true)expect(await archiveLines(f)).toEqual([expect.objectContaining({ recipientIds: [],- text: 'Archived: the work is cancelled and its pull requests are merged or closed.' })])+ text: 'Archived: the work is cancelled (Done elsewhere) and its pull requests are merged or closed.' })])// It never archives twice.f.clock.now += 40 * MINUTEawait archiveFinishedGroups(db, f.timed, prs, f.clock.now)@@ -253,6 +255,64 @@ describe('a finished group', () => {expect(await db.superTabDecision.findUnique({ where: { id } })).toMatchObject({ withdrawn: true, choice: null, answeredAt: new Date(f.clock.now) })})+ it('waits for a pull request its cancel names only as "PR #N", read in the project\'s repository, until it is merged or closed', async () => {+ const f = await swarm()+ // As a Lead started in its repository records it (tab.project).+ const head = await db.swarmHead.findUniqueOrThrow({ where: { id: `${f.tab}:head` } }), data = head.data as unknown as HeadData+ const repository = { machineId: 'lead-host', cwd: '/repo', repositoryUrl: 'https://github.com/acme/app' }+ await db.swarmHead.update({ where: { id: head.id }, data: { data: (data.projects+ ? { ...data, projects: data.projects.map(p => p.id === 'lead' ? { ...p, repository } : p) } : { ...data, project: repository }) as object } })+ const handed = String((await f.execute({ type: 'conversation.create', title: 'Phone leaderboard', brief: 'Ship it', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ const worker = await f.add(handed, 'test-host', randomUUID(), 'Phone')+ const work = String((await f.execute({ type: 'work.assign', conversationId: handed, agentId: worker })).result.assignmentId)+ await f.execute({ type: 'work.cancel', conversationId: handed, assignmentId: work, reason: 'Handed off as PR #1875' })+ const open = async () => !(await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: handed } })).archived+ f.clock.now += 40 * MINUTE+ const prs = github({ 'https://github.com/acme/app/pull/1875': 'open' })+ await archiveFinishedGroups(db, f.timed, prs, f.clock.now)+ expect(prs.read).toContain('https://github.com/acme/app/pull/1875')+ expect(await open()).toBe(true)+ await archiveFinishedGroups(db, f.timed, github({ 'https://github.com/acme/app/pull/1875': 'merged' }), f.clock.now)+ expect(await open()).toBe(false)+ })++ it('stays open when its work names "PR #N" and the project has no repository to read it in', async () => {+ const f = await swarm()+ const handed = String((await f.execute({ type: 'conversation.create', title: 'Sidebar', brief: 'Ship it', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ const worker = await f.add(handed, 'test-host', randomUUID(), 'Sidebar')+ const work = String((await f.execute({ type: 'work.assign', conversationId: handed, agentId: worker })).result.assignmentId)+ await f.execute({ type: 'work.cancel', conversationId: handed, assignmentId: work, reason: 'PR #1868 is in the merge queue' })+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({}), f.clock.now)+ expect((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: handed } })).archived).toBe(false)+ expect(await archived(f)).toBe(true)+ })++ it('stays open while its task is lost, even marked finished, so unfinished work never closes silently', async () => {+ const f = await swarm()+ const lost = String((await f.execute({ type: 'conversation.create', title: 'Round tabs', brief: 'Drop closed tabs', checks: [{ description: 'Verified', independent: false }] })).result.conversationId)+ const worker = await f.add(lost, 'test-host', randomUUID(), 'Dial')+ await f.execute({ type: 'work.assign', conversationId: lost, agentId: worker })+ const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: lost } })+ const data = part.data as unknown as Conversation+ await db.swarmGroup.update({ where: { id: part.id }, data: { workFinished: true,+ data: { ...data, assignment: { ...data.assignment!, status: 'lost', lost: { reason: 'its model keeps failing', at: f.clock.now } } } as object } })+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({}), f.clock.now)+ expect((await db.swarmGroup.findUniqueOrThrow({ where: { id: part.id } })).archived).toBe(false)+ expect(await archived(f)).toBe(true)+ })++ it('tags the person who asked for a cancelled task, with the reason, when it archives', async () => {+ const f = await swarm()+ f.clock.now += 40 * MINUTE+ await archiveFinishedGroups(db, f.timed, github({}), f.clock.now)+ const [line] = await archiveLines(f)+ expect(line).toMatchObject({ text: 'Archived: the work is cancelled (Done elsewhere).', mentions: [owner.sub] })+ expect(await db.superTabMention.findMany({ where: { tabId: f.tab, conversationId: f.group } }))+ .toEqual([expect.objectContaining({ personId: owner.sub, messageId: line!.id, resolvedAt: null })])+ })+it('stays open once the owner turned tidying off, and never archives the Lead conversation', async () => {const f = await swarm()await f.execute({ type: 'tab.tidy', enabled: false })diff --git a/backend/src/superTabs/archive.ts b/backend/src/superTabs/archive.tsindex 2e2a2f97d..d9313d9ac 100644--- a/backend/src/superTabs/archive.ts+++ b/backend/src/superTabs/archive.ts@@ -1,10 +1,11 @@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 { activeWork, type Conversation } from './model.js'+import { activeWork, type Conversation, type SuperTabState } from './model.js'import type { HeadData } from './parts/index.js'import type { SuperTabStore } from './store.js'-import { ARCHIVE_QUIET_MS } from './tidy.js'+import { projectsOf } from './projects.js'+import { ARCHIVE_QUIET_MS, archiveWaitsFor } from './tidy.js'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@@ -89,14 +90,16 @@ export async function markFinishedGroups(db: PrismaClient): Promise<number> {* tidying on, is archived once GitHub says each of its pull requests is merged or closed. Read oldest first by a cursor,* so groups that stay open never hold later ones back. */export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperTabStore, 'archiveFinished'>, prs: PullRequests, now: number): Promise<number> {- const tidy = new Map<string, boolean>()+ // One head read per Swarm a pass: whether it keeps tidying on, and its projects' repositories (tidy.ts archiveWaitsFor).+ const heads = new Map<string, Promise<HeadData | undefined>>()+ const headOf = (tabId: string) => {+ if (!heads.has(tabId)) heads.set(tabId, db.swarmHead.findUnique({ where: { id: `${tabId}:head` } }).then(row => row?.data as unknown as HeadData | undefined))+ return heads.get(tabId)!+ }+ // A deleted Swarm (deletion.ts) is left alone: none of its pull requests is read.const tidyOn = async (tabId: string) => {- // A deleted Swarm (deletion.ts) is left alone: none of its pull requests is read.- if (!tidy.has(tabId)) {- const head = (await db.swarmHead.findUnique({ where: { id: `${tabId}:head` } }))?.data as unknown as HeadData | undefined- tidy.set(tabId, head?.tidy !== false && !head?.deletion)- }- return tidy.get(tabId)!+ const head = await headOf(tabId)+ return head?.tidy !== false && !head?.deletion}// One read per pull request a pass, however many groups link it.const states = new Map<string, Promise<PullRequestState>>()@@ -131,7 +134,11 @@ export async function archiveFinishedGroups(db: PrismaClient, store: Pick<SuperT}return true}- const own = group.pullRequestUrls ?? []+ // Its links, and a "PR #N" its result or check evidence names; none to read it in keeps it open.+ const head = await headOf(row.tabId)+ const project = head && projectsOf(head as unknown as SuperTabState).find(p => p.id === (group.projectId ?? 'lead'))+ const own = archiveWaitsFor(group, project?.repository?.repositoryUrl)+ if (!own) continueif (!step) {if (await settled(own) && await archive(row, checked)) archived++continuediff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 3e78e0a1d..b41244c30 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -2216,8 +2216,9 @@ describe('cancelling work', () => {expect(() => f.run(cancel, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))})it('refuses work that already finished', () => {- const { f, group, leadActor, assignmentId, cancel } = active()- f.run({ type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: null }, owner, { confirmedStopped: true })+ const { f, group, leadActor, cancel } = active()+ // A stopped task did not finish, so it still cancels ('archiving unfinished work'); a done one has ended.+ f.state.conversations.find(c => c.id === group)!.assignment!.status = 'done'expect(() => f.run(cancel, leadActor)).toThrow('already ended')})@@ -4193,6 +4194,48 @@ describe('agent.stopRefused', () => {})})+describe('archiving unfinished work', () => {+ /** A task Peer asked for, its worker's attempt left at [status]. */+ function task(status: 'lost' | 'stopped' | 'cancelled' | 'done') {+ const f = fixture()+ f.invite()+ const group = f.run({ type: 'conversation.create', title: 'Round tabs', brief: 'Drop closed tabs.', requesterId: 'peer',+ checks: [{ description: 'Closed tabs leave the dial.', independent: false }] }).result.conversationId as string+ const worker = f.add('worker', 'owner', group)+ const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string+ if (status === 'cancelled') f.run({ type: 'work.cancel', conversationId: group, assignmentId, reason: 'Superseded by the dial rewrite.' })+ else f.state.conversations.find(c => c.id === group)!.assignment!.status = status+ return { f, group, assignmentId }+ }+ const archive = (t: ReturnType<typeof task>) => t.f.run({ type: 'conversation.archive', conversationId: t.group, archived: true })++ it.each(['lost', 'stopped'] as const)('refuses to archive a %s task by hand, so nothing unfinished closes silently', status => {+ const t = task(status)+ expect(() => archive(t)).toThrow('cancel it with a reason')+ expect(t.f.state.conversations.find(c => c.id === t.group)!.archived).toBe(false)+ })++ it('cancels a stopped task, which then archives', () => {+ const t = task('stopped')+ t.f.run({ type: 'work.cancel', conversationId: t.group, assignmentId: t.assignmentId, reason: 'Nobody can finish it here.' })+ expect(t.f.state.conversations.find(c => c.id === t.group)!.assignment!.status).toBe('cancelled')+ archive(t)+ expect(t.f.state.conversations.find(c => c.id === t.group)!.archived).toBe(true)+ })++ it('tags the requester with the reason when a cancelled task is archived', () => {+ const t = task('cancelled')+ expect(archive(t).messages).toEqual([expect.objectContaining({ conversationId: t.group, mentions: ['peer'],+ text: 'Archived without shipping: the task was cancelled (Superseded by the dial rewrite).' })])+ })++ it('archives a done task without tagging anyone', () => {+ const t = task('done')+ expect(archive(t).messages).toEqual([])+ expect(t.f.state.conversations.find(c => c.id === t.group)!.archived).toBe(true)+ })+})+// Ken, 2026-10-29: simple work runs on a grid model first, and a failed first review or a grid host that never starts the// agent steps it up a tier (Sonnet, then Opus), at most twice per group.// Ken and Dee, 2026-10-30: Builders run on Opus high or Astra xhigh. Review of #2314: an existing Sonnet agent still got builds,diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex dd74f6f6b..92a38239c 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -39,7 +39,7 @@ import { syncTaskLines } from './taskLine.js'import { assignedNotice, tellBuddies } from './buddyNews.js'import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged } from './cards.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'-import { switchExpired } from './tidy.js'+import { cancelledTags, cancelReason, switchExpired, unfinishedWork } from './tidy.js'import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, canReadProject, deleteProject, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'import { recordClosing } from './closedAgents.js'import { declinedWith, declinedWithout } from './sharing.js'@@ -1978,6 +1978,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,const group = conversation(state, command.conversationId)if (group.id === groupProject(state, group).leadConversationId) fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')if (command.archived && activeWork(group)) fail('WORK_ACTIVE', 'Resolve the active assignment before archiving this conversation.')+ if (command.archived && unfinishedWork(group)) fail('WORK_UNFINISHED', 'This task did not finish. Hand it on, or cancel it with a reason, before archiving.')+ const tags = command.archived && !group.archived ? cancelledTags(state, group, actor) : []+ if (tags.length) message(group.id, `Archived without shipping: the task was cancelled${cancelReason(group) ? ` (${cancelReason(group)})` : ''}.`, [], null, SYSTEM_ROW, undefined, tags)group.archived = command.archivedif (command.archived) endStepsOf(group, `${group.title} was archived.`, true)// Archived by hand, it leaves the active set until it is reopened (spec, Archive), once its reports are acknowledged:@@ -3174,14 +3177,15 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,if (!allowed) fail('FORBIDDEN', 'Only an agent of this project 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'- if (!activeWork(group) && !lost) fail('ATTEMPT_CLOSED', 'This attempt has already ended.')+ // A stopped task is unfinished too, and only a cancel closes it (tidy.ts unfinishedWork): its worker is finished already.+ const lost = assignment.status === 'lost', stopped = assignment.status === 'stopped'+ if (!activeWork(group) && !lost && !stopped) fail('ATTEMPT_CLOSED', 'This attempt has already ended.')// A removed worker (reconciling) can never confirm a stop, so this is the only way to close its task; nobody is left to tell.// A lost task's agent was told already that its task moved, and does not wait for a decision.- const gone = assignment.status === 'reconciling' || lost+ const gone = assignment.status === 'reconciling' || lost || stoppedassignment.status = 'cancelled'assignment.result = command.reason- if (!lost) finishWorker(state, assignment.agentId)+ if (!lost && !stopped) finishWorker(state, assignment.agentId)// Its steps' work ends with it; finished ones stay until it archives (task steps design; final review, finding 2).endStepsOf(group, `${group.title} was cancelled.`, false)message(group.id, `${who} cancelled this task: ${command.reason.replace(/[.\s]+$/, '')}.${gone ? '' : ' Stop working on it.'}`,diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex fe8da1c60..c1e02625b 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -48,7 +48,7 @@ import { moveChatMark } from './read/threadMarkSeeds.js'import { closedAgents, nextRemovalAt, removeClosedAgents, reopened, restoreRefusal, restoreSessions } from './closedAgents.js'import { sessionRows } from './memberRows.js'import { judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'-import { archivable, archiveLine, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'+import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'@@ -3901,7 +3901,12 @@ export class SuperTabStore {const group = state.conversations.find(c => c.id === groupId)const now = this.now()if (!group) return false- const read = (urls: readonly string[]) => urls.every(url => checked[url] === 'merged' || checked[url] === 'closed')+ // Its links, and a "PR #N" its result or check evidence names, read in its project's repository; with none to read+ // it in it stays open (tidy.ts archiveWaitsFor). Read only once it may close, so its project is a real one.+ const read = (urls: readonly string[]) => {+ const waits = archiveWaitsFor(group, groupProject(state, group).repository?.repositoryUrl)+ return !!waits && [...urls, ...waits].every(url => checked[url] === 'merged' || checked[url] === 'closed')+ }// A step's task's pull requests count too: it may yet be handed back while one is open, and need its step again.const finished = archivable(state, group, now) && read(reviewPullRequests(state, group))// Only the group it reviews as the pass read it: one this write did not load would hide its open pull requests.@@ -3937,6 +3942,7 @@ export class SuperTabStore {// A finished step's too: its task handed on again since the load must not lose the step it will need.await this.save(tx, loaded, state, clock.next(), group.reviewOf ? [{ kind: 'group', key: group.reviewOf }] : [])await this.writeMessages(tx, tabId, state, rows, sequences)+ await writeMentions(tx, tabId, state, rows, now)return true})}diff --git a/backend/src/superTabs/tidy.ts b/backend/src/superTabs/tidy.tsindex 4fcbbf0af..2250e34f8 100644--- a/backend/src/superTabs/tidy.ts+++ b/backend/src/superTabs/tidy.ts@@ -1,8 +1,9 @@import { checksOpenWork, isStep, taskEnded } from './steps.js'import { isBuddy } from './buddies.js'import { agentDisplayName } from './agentNames.js'-import { activeWork, stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'-import { agentProjectId, groupProject, ledProject, projectsOf } from './projects.js'+import { githubRepository } from '../github/repository.js'+import { activeWork, appendPullRequestUrls, stableId, type Actor, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { agentProjectId, canReadGroup, groupProject, ledProject, projectsOf } from './projects.js'import { toLead } from './terminal.js'// Nobody has to tidy a Swarm by hand (roadmap, December). The server stops no agent (project instructions, phase 4): an agent@@ -121,10 +122,45 @@ export function archivable(state: SuperTabState, group: Conversation, now: numbereturn last !== undefined && now - last >= ARCHIVE_QUIET_MS}-/** The one quiet line an archived group gets, to nobody, written as its project's Lead; none when the project has no Lead. */+/** Work that ended without finishing: only a cancel with a reason closes it, never an archive alone (#558). */+export const unfinishedWork = (group: Conversation): boolean => ['lost', 'stopped'].includes(group.assignment?.status ?? '')++/** Who hears that a group archives without shipping: the person who asked for its cancelled task, unless they archive it+ * themselves or can no longer read it (#558). */+export function cancelledTags(state: SuperTabState, group: Conversation, actor?: Actor): string[] {+ if (group.assignment?.status !== 'cancelled' || !group.requesterId) return []+ if (actor?.kind === 'person' && actor.userId === group.requesterId) return []+ const requester = state.people.find(p => p.id === group.requesterId)+ return requester && canReadGroup(state, { kind: 'person', userId: requester.id, email: requester.email }, group) ? [requester.id] : []+}++/** Why a cancelled task ended, as its cancel recorded it, without the final full stop. */+export const cancelReason = (group: Conversation): string => (group.assignment?.result ?? '').replace(/[.\s]+$/, '')++/** "PR #1875", as a Lead's cancel or a builder's result names a pull request without its link. */+const PR_NUMBER = /\bPR #([1-9][0-9]{0,8})\b/gi++/** The pull requests a group's archive waits on: those it links, and those its result and check evidence name, a "PR #N"+ * read in its project's repository. A cancel saying "Handed off as PR #1875" linked nothing, so the group archived while+ * that PR was open (#558). Null when it names a number with no GitHub repository to read it in: it stays open. */+export function archiveWaitsFor(group: Conversation, repositoryUrl: string | null | undefined): string[] | null {+ const texts = [group.assignment?.result, ...group.checks.map(check => check.evidence)]+ const named = { pullRequestUrls: [...group.pullRequestUrls ?? []] } as Conversation+ appendPullRequestUrls(named, texts)+ const numbers = texts.flatMap(text => [...(text ?? '').matchAll(PR_NUMBER)].map(match => match[1]!))+ if (!numbers.length) return named.pullRequestUrls!+ const repository = githubRepository(repositoryUrl)+ if (!repository) return null+ return [...new Set([...named.pullRequestUrls!, ...numbers.map(n => `https://github.com/${repository.fullName}/pull/${n}`)])]+}++/** The one quiet line an archived group gets, to nobody, written as its project's Lead; none when the project has no Lead.+ * A cancelled task's requester is tagged in it (cancelledTags). */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}.`)+ const mentions = cancelledTags(state, group), reason = mentions.length && cancelReason(group) ? ` (${cancelReason(group)})` : ''+ const line = leadLine(state, group, now, `Archived: the work is ${group.assignment!.status}${reason}${prs}.`)+ return line && mentions.length ? { ...line, mentions } : line}function leadLine(state: SuperTabState, group: Conversation, now: number, text: string): MessageDraft | null {