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.

27.0 KB
Raw Blame
import { describe, expect, it } from 'vitest'
import { agentOnly, type Agent, type Assignment, type Conversation, type SuperTabState } from './model.js'
import { ARCHIVE_QUIET_MS, archivable, archiveWaitsFor, IDLE_NOTICE_MS, idleNotices, linkPending, staleSwitches, SWITCH_UNCLAIMED_MS, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'

const MINUTE = 60_000
const START = Date.parse('2026-10-27T08:00:00.000Z')
const iso = (at: number) => new Date(at).toISOString()
const config = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
const done = (patch: Partial<Assignment> = {}): Assignment => ({ id: 'a1', agentId: 'w', status: 'done', result: 'Merged', configuration: config,
  execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'o' }, progressAt: START, ...patch })
const worker = (patch: Partial<Agent> = {}): Agent => ({ id: 'w', machineId: 'm', harnessId: 'h', machineOwnerId: 'o', contributorId: 'p',
  membershipGeneration: 'g', name: 'Builder', displayName: 'Rowan', configuration: config,
  startedSession: { creationId: 'c1', sessionId: 's1', createdAt: iso(START - 60 * MINUTE) }, ...patch })
const group = (patch: Partial<Conversation> = {}): Conversation => ({ id: 'g1', title: 'Task', leadId: 'L', agentIds: ['L', 'w'], archived: false,
  brief: 'Do it', checks: [], assignment: done(), lastMessageSequence: 3, lastActivityAt: iso(START), ...patch })

/** A Swarm whose coordinator `L` runs on machine `m` with agent `w` (session `h`). */
function swarm(opts: { agents?: Agent[]; groups?: Conversation[] } = {}) {
  return {
    id: 't', ownerId: 'p', paused: false,
    agents: [worker({ id: 'L', harnessId: 'hl', name: 'Lead', displayName: 'River' }), ...opts.agents ?? [worker()]],
    people: [{ id: 'p', email: '[email protected]', role: 'owner', generation: 'g' }],
    machines: [{ machineId: 'm', name: 'Studio' }],
    conversations: [{ id: 'lead', title: 'Lead', leadId: 'L', agentIds: ['L'], archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0 },
      ...opts.groups ?? [group()]],
  } as unknown as SuperTabState
}
const at = START + IDLE_NOTICE_MS
const target = (state: SuperTabState, id = 'w') => state.agents.find(a => a.id === id)!

// Dee, 2026-11-06: the server decides routine idle handling; the PM's notice is informational.
describe('idle agents', () => {
  it('tells the coordinator once about an agent with no open task for 15 minutes', () => {
    const state = swarm({ agents: [worker({ startedSession: { creationId: 'c', sessionId: 's', createdAt: iso(START - MINUTE) } })], groups: [] })
    const rows = idleNotices(state, 'lead', at, new Set())
    expect(rows).toEqual([expect.objectContaining({ conversationId: 'lead', recipients: ['L'], replyTo: null,
      author: expect.objectContaining({ kind: 'agent', id: 'L' }), text: 'Rowan has had no open task for 15 minutes.', source: { kind: 'idle', agentId: 'w' } })])
    // The coordinator's alone: people do not read it (model.ts agentOnly).
    expect(rows.map(row => agentOnly(row.source, row.recipients))).toEqual([true])
    // Its host confirms the stop and may refuse it if the worktree became dirty.
    expect(target(state).workDecision).toBe('stop')
    expect(target(state).releaseId).toEqual(expect.any(String))
    expect(target(state).idleStop).toEqual({ previous: null })
    expect(target(state).idleNoticedAt).toBe(START - MINUTE)
    // Once per idle spell: the next polls say nothing.
    expect(idleNotices(state, 'lead', at + MINUTE, new Set())).toEqual([])
    expect(idleNotices(state, 'lead', at + 60 * MINUTE, new Set())).toEqual([])
    // New work and a new idle spell after it: one more.
    target(state).workDecision = 'awaiting'
    delete target(state).idleStop
    delete target(state).releaseId
    state.conversations.push(group({ assignment: done({ progressAt: at + 2 * MINUTE }), lastActivityAt: iso(at + 2 * MINUTE) }))
    expect(idleNotices(state, 'lead', at + 10 * MINUTE, new Set())).toEqual([])
    const again = idleNotices(state, 'lead', at + 17 * MINUTE, new Set())
    expect(again).toEqual([expect.objectContaining({ text: 'Rowan has had no open task for 15 minutes.' })])
    expect(new Set([...rows, ...again].map(row => row.id)).size).toBe(2)
    expect(target(state).idleNoticedAt).toBe(at + 2 * MINUTE)
  })

  // Task #3397: a crew member stands by between tasks; the coordinator is not told to stop it.
  it('never tells of a crew member, and tells of the same agent off the crew', () => {
    const crew = swarm({ agents: [worker({ crew: { role: 'Engineer', at: START, by: 'p' } })], groups: [] })
    expect(idleNotices(crew, 'lead', at, new Set())).toEqual([])
    delete target(crew).crew
    expect(idleNotices(crew, 'lead', at, new Set())).toEqual([expect.objectContaining({ text: 'Rowan has had no open task for 15 minutes.' })])
  })

  it('never tells of a Buddy, the coordinator, an agent with a delivery waiting or one in a task with active work', () => {
    const buddy = swarm({ agents: [worker({ buddyOf: { personId: 'p', generation: 'g' } })], groups: [] })
    expect(idleNotices(buddy, 'lead', at, new Set())).toEqual([])
    const alone = swarm({ agents: [], groups: [] })
    expect(idleNotices(alone, 'lead', at, new Set())).toEqual([])
    expect(idleNotices(swarm({ groups: [] }), 'lead', at, new Set(['w']))).toEqual([])
    // Its own work, or a member of a task whose work is going (a Reviewer or a Tester linked to it).
    expect(idleNotices(swarm({ groups: [group({ assignment: done({ status: 'working' }) })] }), 'lead', at, new Set())).toEqual([])
    const linked = group({ agentIds: ['L', 'other', 'w'], assignment: done({ agentId: 'other', status: 'review' }), lastActivityAt: iso(START - 60 * MINUTE) })
    expect(idleNotices(swarm({ groups: [linked] }), 'lead', at, new Set())).toEqual([])
  })

  it('keeps an Engineer whose own task is handed over, while review or CI can return work to it', () => {
    const handed = group({ assignment: done({ status: 'review', result: 'Ready for review: PR #7 at abc1234' }) })
    const state = swarm({ groups: [handed] })
    expect(idleNotices(state, 'lead', at, new Set())).toEqual([])
    expect(target(state).workDecision).not.toBe('stop')
    // A step's own Ready is its verdict, no hand-over: its Reviewer is still at work on it.
    const step = group({ reviewOf: 'g0', assignment: done({ status: 'review' }) })
    expect(idleNotices(swarm({ groups: [step] }), 'lead', at, new Set())).toEqual([])
  })

  it('waits until a full 15 minutes have passed since the group of its own task last spoke', () => {
    const state = swarm({ groups: [group({ lastActivityAt: iso(START + 5 * MINUTE) })] })
    expect(idleNotices(state, 'lead', at, new Set())).toEqual([])
    expect(idleNotices(state, 'lead', at + 5 * MINUTE, new Set())).toHaveLength(1)
  })

  it('counts its start and its last progress as activity', () => {
    const fresh = swarm({ agents: [worker({ startedSession: { creationId: 'c', sessionId: 's', createdAt: iso(START + MINUTE) } })], groups: [] })
    expect(idleNotices(fresh, 'lead', at, new Set())).toEqual([])
    const progressed = swarm({ groups: [group({ assignment: done({ progressAt: START + MINUTE }) })] })
    expect(idleNotices(progressed, 'lead', at, new Set())).toEqual([])
  })

  // A keep is the coordinator's answer to the notice: it is not asked again every 15 minutes while the agent waits, only once
  // the agent has had and finished another task (final review of the branch).
  it('says nothing more of a kept agent until it has had and finished another task', () => {
    const kept = swarm({ agents: [worker({ workDecision: 'keep', keptAt: START + MINUTE })] })
    expect(idleNotices(kept, 'lead', at + MINUTE, new Set())).toEqual([])
    expect(idleNotices(kept, 'lead', at + 24 * 60 * MINUTE, new Set())).toEqual([])
    // Assigned again, its keep is cleared (commands.ts work.assign); finished, it is marked awaiting (model.ts finishWorker).
    const later = at + 30 * MINUTE
    target(kept).workDecision = 'awaiting'
    kept.conversations.push(group({ id: 'g2', assignment: done({ id: 'a2', progressAt: later }), lastActivityAt: iso(later) }))
    expect(idleNotices(kept, 'lead', later + IDLE_NOTICE_MS - 1, new Set())).toEqual([])
    expect(idleNotices(kept, 'lead', later + IDLE_NOTICE_MS, new Set())).toHaveLength(1)
  })

  // Swarm autonomous-harness, 2026-10-29: an agent started by hand in a busy chat never got a task, and every message there
  // kept it idle. Messages in a group without active work are about others' work: it is idle from its start.
  // Task #3816 (hieule, 11-06): two agents he was chatting with in his panel dropped to "Kept (closed)" every 5 to 10
  // minutes. An agent the Swarm started that never had a task was idle from its start alone: a person talking with it never
  // renewed it.
  it('never keeps or stops an agent a person talked with in the last 15 minutes, and still does one nobody talked to', () => {
    const started = { creationId: 'c', sessionId: 's', createdAt: iso(START - MINUTE) }
    const talked = worker({ startedSession: started })
    const quiet = worker({ id: 'q', harnessId: 'hq', displayName: 'Quinn', startedSession: started })
    const reviewer = worker({ id: 'r', harnessId: 'hr', displayName: 'Ash', roleName: 'Reviewer', startedSession: started })
    const chat = group({ id: 'g2', agentIds: ['w', 'q', 'r'], assignment: null, talkedAt: { w: { person: at - 6 * MINUTE, answer: at - 5 * MINUTE }, r: { person: at - 5 * MINUTE } } })
    const state = swarm({ agents: [talked, quiet, reviewer], groups: [chat] })
    const agentOf = (id: string) => state.agents.find(a => a.id === id)!
    const rows = idleNotices(state, 'lead', at, new Set())
    expect(rows.map(row => (row.source as { agentId: string }).agentId)).toEqual(['q'])
    expect(agentOf('q').workDecision).toBe('stop')
    expect(agentOf('w').workDecision).toBeUndefined()
    expect(agentOf('r').workDecision).toBeUndefined()
    // Fifteen minutes after the person's last word, it is idle like any other.
    idleNotices(state, 'lead', at + 10 * MINUTE, new Set())
    expect(agentOf('w').workDecision).toBe('stop')
    expect(agentOf('r').workDecision).toBe('keep')
  })

  it('tells of an agent that never had a task 15 minutes after its start, however busy a finished group it sits in is', () => {
    const chatty = group({ assignment: done({ agentId: 'other' }), agentIds: ['L', 'other', 'w'], lastActivityAt: iso(at - MINUTE) })
    expect(idleNotices(swarm({ groups: [chatty] }), 'lead', at, new Set())).toEqual([expect.objectContaining({ source: { kind: 'idle', agentId: 'w' } })])
    // One that had a task of its own and finished it: its group's last message still counts.
    const finished = swarm({ groups: [group({ lastActivityAt: iso(at - MINUTE) })] })
    expect(idleNotices(finished, 'lead', at, new Set())).toEqual([])
  })

  it('tells of an agent a person added by hand, from its groups\' last activity, and of no agent it cannot time', () => {
    const added = worker({ startedSession: undefined })
    expect(idleNotices(swarm({ agents: [added], groups: [group({ assignment: null, lastActivityAt: iso(START) })] }), 'lead', at, new Set())).toHaveLength(1)
    expect(idleNotices(swarm({ agents: [added], groups: [group({ assignment: null, lastActivityAt: iso(START + MINUTE) })] }), 'lead', at, new Set())).toEqual([])
    expect(idleNotices(swarm({ agents: [added], groups: [] }), 'lead', at, new Set())).toEqual([])
  })

  it('leaves stopping agents and agents waiting out a usage limit alone, past its reset time too, until their task is handed on', () => {
    expect(idleNotices(swarm({ agents: [worker({ workDecision: 'stop', releaseId: 'r1' })] }), 'lead', at, new Set())).toEqual([])
    const lostTask = { conversationId: 'g1', assignmentId: 'a1', reason: 'limit', at: START, resumeAt: iso(START + MINUTE) }
    const lost = () => group({ assignment: done({ status: 'lost', lost: { reason: 'limit', at: START, resumeAt: iso(START + MINUTE) } }) })
    expect(idleNotices(swarm({ agents: [worker({ lostTask })], groups: [lost()] }), 'lead', at + 10 * MINUTE, new Set())).toEqual([])
    const handed = swarm({ agents: [worker({ lostTask })], groups: [group({ assignment: done({ id: 'a2', agentId: 'other', status: 'done' }) })] })
    expect(idleNotices(handed, 'lead', at, new Set())).toHaveLength(1)
  })

  it('tells whether or not the owner turned tidying off, and never of another project\'s agents', () => {
    const off = swarm({ groups: [] })
    off.tidy = false
    expect(idleNotices(off, 'lead', at, new Set())).toHaveLength(1)
    expect(idleNotices(swarm({ agents: [worker({ projectId: 'other' })] }), 'lead', at, new Set())).toEqual([])
  })

  it.each(['Reviewer', 'Tester'])('keeps an idle %s without asking the PM', roleName => {
    const state = swarm({ agents: [worker({ roleName })], groups: [] })
    expect(idleNotices(state, 'lead', at, new Set())).toEqual([])
    expect(target(state).workDecision).toBe('keep')
    expect(target(state).releaseId).toBeUndefined()
    expect(idleNotices(state, 'lead', at + MINUTE, new Set())).toEqual([])
  })

  // The job is a Review step; legacy agents need not have a configured Reviewer role.
  it('reports a step-only Reviewer idle once its done task sleeps', () => {
    const review = group({ id: 'r1', reviewOf: 'g1', step: 'Review' })
    const state = swarm({ groups: [review] })
    state.tidy = false
    const rows = idleNotices(state, 'lead', START + 25 * 60 * MINUTE, new Set())
    expect(rows).toEqual([expect.objectContaining({ source: { kind: 'idle', agentId: 'w' } })])
    expect(target(state).workDecision).toBe('stop')
    expect(idleNotices(state, 'lead', START + 26 * 60 * MINUTE, new Set())).toEqual([])
  })

  it.each(['done', 'cancelled'] as const)('reports the same step-only agent idle with its %s task still loaded', status => {
    const parent = group({ agentIds: ['L', 'other'], assignment: done({ agentId: 'other', status }) })
    const state = swarm({ groups: [parent, group({ id: 'r1', reviewOf: 'g1', step: 'Review' })] })
    expect(idleNotices(state, 'lead', START + 25 * 60 * MINUTE, new Set()))
      .toEqual([expect.objectContaining({ source: { kind: 'idle', agentId: 'w' } })])
  })

  it.each(['Reviewer', 'Tester'])('keeps a configured %s once its finished step has an unloaded parent', roleName => {
    const state = swarm({ agents: [worker({ roleName })], groups: [group({ id: 'r1', reviewOf: 'g1', step: 'Review' })] })
    expect(idleNotices(state, 'lead', START + 25 * 60 * MINUTE, new Set())).toEqual([])
    expect(target(state).workDecision).toBe('keep')
    expect(target(state).releaseId).toBeUndefined()
  })

  it('keeps a step-only agent while any loaded parent is open', () => {
    const state = swarm({ groups: [
      group({ agentIds: ['L', 'other'], assignment: done({ agentId: 'other', status: 'review' }) }),
      group({ id: 'r1', reviewOf: 'g1', step: 'Review' }),
      group({ id: 'r2', reviewOf: 'sleeping', step: 'Test' }),
    ] })
    expect(idleNotices(state, 'lead', START + 25 * 60 * MINUTE, new Set())).toEqual([])
    expect(target(state).workDecision).toBeUndefined()
  })

  it('keeps an Engineer with its own open task and a finished step whose parent is unloaded', () => {
    const state = swarm({ groups: [group({ assignment: done({ status: 'review' }) }),
      group({ id: 'r1', reviewOf: 'sleeping', step: 'Review' })] })
    expect(idleNotices(state, 'lead', START + 25 * 60 * MINUTE, new Set())).toEqual([])
    expect(target(state).workDecision).toBeUndefined()
  })

  it('does not stop anyone while paused, and does not close a manually shared session', () => {
    const paused = swarm({ groups: [] })
    paused.paused = true
    expect(idleNotices(paused, 'lead', at, new Set())).toEqual([])
    expect(target(paused).workDecision).toBeUndefined()
    const shared = swarm({ agents: [worker({ startedSession: undefined })] })
    idleNotices(shared, 'lead', at, new Set())
    expect(target(shared).workDecision).not.toBe('stop')
  })

  it('retains the prior decision for a dirty-folder refusal and never replaces a pending stop', () => {
    const state = swarm({ agents: [worker({ workDecision: 'awaiting' })] })
    idleNotices(state, 'lead', at, new Set())
    expect(target(state).idleStop).toEqual({ previous: 'awaiting' })
    const release = target(state).releaseId
    idleNotices(state, 'lead', at + MINUTE, new Set())
    expect(target(state).releaseId).toBe(release)
  })
})

describe('which finished groups archive', () => {
  const quiet = START + ARCHIVE_QUIET_MS

  it('never archives a finished step whose parent is open or absent from loaded state', () => {
    const review = group({ id: 'r1', reviewOf: 'g1', step: 'Review' })
    const state = swarm({ groups: [review] })
    expect(archivable(state, review, START + 25 * 60 * MINUTE)).toBe(false)
    const parent = group({ assignment: done({ agentId: 'other', status: 'working' }) })
    state.conversations.push(parent)
    expect(archivable(state, review, START + 25 * 60 * MINUTE)).toBe(false)
    parent.assignment!.status = 'done'
    expect(archivable(state, review, START + 25 * 60 * MINUTE)).toBe(true)
  })
  it('is a group whose task is done or cancelled and that has been quiet for 30 minutes', () => {
    const state = swarm()
    expect(archivable(state, state.conversations[1]!, quiet)).toBe(true)
    expect(archivable(state, state.conversations[1]!, quiet - 1)).toBe(false)
    const cancelled = swarm({ groups: [group({ assignment: done({ status: 'cancelled' }) })] })
    expect(archivable(cancelled, cancelled.conversations[1]!, quiet)).toBe(true)
  })

  it('is never a group with work still going, lost or stopped, or no task at all', () => {
    for (const assignment of [done({ status: 'working' }), done({ status: 'review' }), done({ status: 'lost' }), done({ status: 'stopped' }), null]) {
      const state = swarm({ groups: [group({ assignment })] })
      expect(archivable(state, state.conversations[1]!, quiet)).toBe(false)
    }
  })

  // By hand any agent or person archives a linked task (project instructions, phase 4); the Swarm alone still waits for it.
  it('is never a linked task with no verdict while the work it links to is going, unless it was cancelled', () => {
    const verdict = { id: 'v', description: 'Verdict with the reviewed revision', independent: false }
    const review = (patch: Partial<Conversation>) => group({ id: 'r1', reviewOf: 'g1', ...patch })
    // Stored as done with no verdict, as no command allows: the rule still holds.
    const state = swarm({ groups: [group({ assignment: done({ status: 'review' }) }),
      review({ checks: [{ ...verdict, evidence: null, passedBy: null }] }),
      review({ id: 'r2', checks: [{ ...verdict, evidence: 'Ready: yes — revision abc', passedBy: 'agent:w' }] }),
      review({ id: 'r3', checks: [{ ...verdict, evidence: null, passedBy: null }], assignment: done({ status: 'cancelled' }) })] })
    // A step, with its task open: none, whatever its own verdict says (task steps design).
    expect(state.conversations.slice(2).map(g => archivable(state, g, quiet))).toEqual([false, false, false])
    expect(state.conversations.slice(2).map(g => linkPending(state, g))).toEqual([true, false, false])
    // Once the reviewed work is done, its review is moot.
    state.conversations[1]!.assignment = done()
    expect(archivable(state, state.conversations[2]!, quiet)).toBe(true)
    expect(linkPending(state, state.conversations[2]!)).toBe(false)
  })

  it('is never a Lead conversation, a private chat, the Leads conversation, an archived group, or any once tidying is off', () => {
    const state = swarm({ groups: [group({ audience: { people: [] } as never }), group({ id: 'leads', kind: 'leads' }), group({ id: 'old', archived: true })] })
    for (const g of state.conversations) expect(archivable(state, g, quiet)).toBe(false)
    const off = swarm()
    off.tidy = false
    expect(archivable(off, off.conversations[1]!, quiet)).toBe(false)
  })
})

// Diego, 11-04: "Ported from autonomous-harness PR #2716" read as this project's pull/2716 kept the task open forever (#2602).
describe('what a finished group\'s archive waits on', () => {
  const repo = 'https://github.com/acme/openharness', pull = (n: number) => `${repo}/pull/${n}`
  const named = (result: string) => group({ assignment: done({ result }) })
  it('waits on a "PR #N" of its project\'s repository, never on one another repository\'s name sits next to', () => {
    expect(archiveWaitsFor(named('Merged PR #40. Ported from autonomous-harness PR #2716.'), repo)).toEqual([pull(40)])
    for (const result of ['Ported (from autonomous-harness PR #12)', 'From other/tool PR #12', 'from foo.js/bar_baz PR #12',
      'acme/tool PR #12', 'PR #12 in acme/tool', 'PR #12 of ACME/tool']) {
      expect(archiveWaitsFor(named(result), repo)).toEqual([])
    }
  })

  // Review of #2895: dropping one of its own numbers archives it while that PR is open (#558); reading another's as its own
  // waits at most until that number of its own closes, or is not found. So a name counts only where it plainly says so.
  it('still reads a number its own repository names, or an ordinary word sits next to, as its project\'s', () => {
    for (const result of ['acme/openharness PR #12', 'ACME/OpenHarness PR #12', 'openharness PR #12', 'Follow-up PR #12', 'Re-opened PR #12',
      'Merged. PR #12', 'Merged PR #12', 'PR #12 in review', 'PR #12 of the batch', 'from openharness PR #12', 'from acme/openharness PR #12',
      'Desktop/CLI PR #12 is open', 'test-only PR #12', 'docs-only PR #12', 'backend-only PR #12', 'CLI-side PR #12', 'v0.5.33 PR #12',
      'fix/2598-relay-offline-hold PR #12', 'PR #12 in docs/plans', 'PR #12 in desktop/src', 'PR #12 of 2026-11-04', 'PR #12 of autonomous-harness']) {
      expect(archiveWaitsFor(named(result), repo)).toEqual([pull(12)])
    }
  })

  it('stays open for a bare number with no repository to read it in, but not for another repository\'s', () => {
    expect(archiveWaitsFor(named('PR #12'), null)).toBeNull()
    expect(archiveWaitsFor(named('Ported from autonomous-harness PR #2716.'), null)).toEqual([])
  })
})

// 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 ended, linking [built], and its review with no Reviewer, linking [own]. */
  const reviewState = (patch: Partial<Conversation> = {}, built: string[] = [PR], own: string[] = [], work: 'done' | 'cancelled' | 'review' | 'working' | 'stopped' | 'lost' = 'done') => swarm({ groups: [
    group({ assignment: done({ status: work }), 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 whose task is open or was lost: it stays with its task, and is not archived while the task may need it', () => {
    for (const work of ['review', 'working', 'stopped', 'lost'] as const) {
      const state = reviewState({}, [PR], [], work)
      expect(reviewClosable(state, review(state), quiet)).toBe(false)
    }
    for (const work of ['done', 'cancelled'] as const) {
      const state = reviewState({}, [PR], [], work)
      expect(reviewClosable(state, review(state), quiet)).toBe(true)
    }
  })

  it('is never one whose task this write did not load', () => {
    const state = reviewState()
    state.conversations.splice(1, 1)
    expect(reviewClosable(state, state.conversations[1]!, quiet)).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.' })
  })

  it('says a pull request GitHub does not know was not found', () => {
    const state = reviewState({}, [PR])
    expect(reviewCloseLine(state, review(state), { [PR]: 'missing' }, quiet)?.text).toBe('Closed: #2288 not found; no Swarm review is needed now.')
  })
})

describe('staleSwitches', () => {
  const request = (patch = {}) => ({ id: 'op1', engine: 'codex', profileId: 'p', requestedBy: 'p', at: iso(START), ...patch })
  const asked = (switchRequest?: Agent['switchRequest']) => { const state = swarm(); target(state, 'L').switchRequest = switchRequest; return state }
  const line = { conversationId: 'lead', recipients: [], text: "Couldn't switch the PM: its machine did not answer." }

  it('drops a request nobody claimed in 2 minutes, with one line in the project chat', () => {
    const state = asked(request())
    expect(staleSwitches(state, START + SWITCH_UNCLAIMED_MS - 1)).toEqual([])
    expect(target(state, 'L').switchRequest).toBeDefined()
    expect(staleSwitches(state, START + SWITCH_UNCLAIMED_MS)).toMatchObject([line])
    expect(target(state, 'L').switchRequest).toBeUndefined()
    expect(staleSwitches(state, START + 3 * SWITCH_UNCLAIMED_MS)).toEqual([])
  })

  it('keeps a claimed request while its lease lasts and drops it once it lapsed', () => {
    const state = asked(request({ claimedUntil: iso(START + 15 * MINUTE) }))
    expect(staleSwitches(state, START + 10 * MINUTE)).toEqual([])
    expect(target(state, 'L').switchRequest).toBeDefined()
    expect(staleSwitches(state, START + 15 * MINUTE)).toMatchObject([line])
    expect(target(state, 'L').switchRequest).toBeUndefined()
  })
})