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.

34.7 KB
Raw Blame
import { describe, expect, it } from 'vitest'
import { storeOldLeads } from './leads.test-support.js'
import type { Prisma } from '@prisma/client'
import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
import { ANSWERED_NOTICE, askDecisions, checkAsker, decisionsWaiting, listDecisions, overdueNotice, delegatedNotice, answerDecision, waitingInProject, withdrawIn, workEnded, workOver, type DecisionTarget } from './decisions.js'
import { buddyChatId } from './buddies.js'
import { giveOwnBuddy } from './ownBuddy.test-support.js'

const HOLD = { kind: 'person', personId: 'owner', defaultAt: '2026-11-06T02:00:00.000Z' } as const

const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
const asAgent = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
const question = (text: string, recommended = 0) => ({ question: text, options: ['Behind a flag', 'To everyone'], recommended, unblocks: 'The release' })

/** A Swarm with the peer in it, a Lead, and a worker assigned to one group. */
function swarm() {
  let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
  let sequence = 0
  const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
    const effects = applyCommand(state, actor, command, { now: 1000, operationId: `op-${++sequence}`, ...context })
    state = effects.state
    return effects
  }
  const invited = run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
  run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
  const add = (harnessId: string, group: string, lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
    name: harnessId, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
  const lead = add('lead', 'lead', true)
  const group = run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits while offline.',
    checks: [{ description: 'Reconnect preserves the edits.', independent: true }] }).result.conversationId as string
  const worker = add('worker', group)
  const assignmentId = run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
  return { run, lead, group, worker, assignmentId, get state() { return state } }
}

describe('asking a person for decisions', () => {
  it('lets the Lead ask one person several questions at once, each with options, a recommendation and what it unblocks', () => {
    const s = swarm()
    const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Ship how?'), question('Which name?', 1)] }, asAgent(s.lead))
    expect(asked.decisions).toHaveLength(2)
    expect(asked.decisions![0]).toMatchObject({ conversationId: s.group, projectId: 'lead', personId: 'peer', askerAgentId: s.lead, assignmentId: null,
      question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'The release' })
    expect(asked.decisions![1]).toMatchObject({ question: 'Which name?', recommended: 1 })
    // One batch for the person: one id ties the questions together, and nobody is pinged in the transcript.
    expect(new Set(asked.decisions!.map(d => d.batchId)).size).toBe(1)
    expect(new Set(asked.decisions!.map(d => d.id)).size).toBe(2)
    expect(asked.messages).toEqual([])
    expect(asked.result.decisionIds).toEqual(asked.decisions!.map(d => d.id))
  })

  it('refuses a question from a person, to someone outside the Swarm, or with a recommendation that is not an option', () => {
    const s = swarm()
    const ask = (actor: Actor, personId = 'peer', recommended = 0) =>
      () => s.run({ type: 'decision.ask', conversationId: s.group, personId, questions: [question('Ship how?', recommended)] }, actor)
    expect(ask(owner)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
    expect(ask(asAgent(s.lead), 'stranger')).toThrow('person in this Swarm')
    expect(ask(asAgent(s.lead), 'peer', 2)).toThrow('recommend one of its options')
    // Someone who cannot read the conversation is named by username, never email (task #2954).
    const group = s.state.conversations.find(c => c.id === s.group)!
    const narrowed = { ...group, audience: { people: [{ id: 'owner', generation: s.state.people[0]!.generation }] } }
    expect(() => askDecisions(s.state, narrowed, 'peer', [question('Ship how?')], { now: 1000, operationId: 'op', askerAgentId: s.lead, assignmentId: null }))
      .toThrow(/^peer cannot read this conversation\.$/)
    expect(commandSchema.safeParse({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
      questions: [{ ...question('One option only'), options: ['Yes'] }] }).success).toBe(false)
    expect(commandSchema.safeParse({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
      questions: Array.from({ length: 11 }, (_, i) => question(`Question ${i}`)) }).success).toBe(false)
  })

  // People talk only to the PM (anh Dee, 11-05; crewNeeds.ts, task #3404): a worker's question is the PM's crew need, and
  // opens no decision for the person it names.
  it('tells the Lead a worker needs a person on its own task, for the Lead to ask them', () => {
    const s = swarm()
    const needs = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD, result: 'Ship to everyone, or behind a flag?',
      ask: { personId: 'peer', options: ['Behind a flag', 'To everyone'], recommended: 0, unblocks: 'Turning the feature on' } }, asAgent(s.worker))
    expect(needs.decisions ?? []).toEqual([])
    expect(needs.messages[0]).toMatchObject({ text: 'Needs a human\n\nShip to everyone, or behind a flag?\n\nFor the PM to ask peer.', recipients: [s.lead] })
    // Without a person and options it reaches the Lead as before, who asks.
    const plain = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD, result: 'Which database?' }, asAgent(s.worker))
    expect(plain.decisions ?? []).toEqual([])
    expect(() => s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'blocked', hold: HOLD, result: 'Stuck',
      ask: { personId: 'peer', options: ['A', 'B'], recommended: 0, unblocks: 'X' } }, asAgent(s.worker))).toThrow('needs a human')
  })

  // Who asks a person is workflow (project instructions, phase 4): any agent of the project, in its own project only, and
  // another agent than the PM asks through the PM (crewNeeds.ts, task #3404).
  it('lets any agent of the project ask, a worker through the PM', () => {
    const s = swarm()
    const task = s.state.conversations.find(c => c.id === s.group)!
    expect(checkAsker(s.state, asAgent(s.worker), task)).toBe(s.worker)
    const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Ship how?')] }, asAgent(s.worker))
    expect(asked.decisions ?? []).toEqual([])
    expect(asked.messages.map(m => [m.source?.kind, m.recipients])).toEqual([['crew-need', [s.lead]]])
    const other = s.run({ type: 'project.create', name: 'Other', visibility: 'public', brief: '' }).result as { projectId: string }
    const elsewhere = s.run({ type: 'conversation.create', projectId: other.projectId, title: 'Elsewhere', brief: '', checks: [] }).result.conversationId as string
    const state = structuredClone(s.state), leadsId = storeOldLeads(state), leads = state.conversations.find(c => c.id === leadsId)!
    for (const group of [leads, s.state.conversations.find(c => c.id === elsewhere)!]) {
      expect(() => checkAsker(s.state, asAgent(s.worker), group)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
    }
    expect(() => checkAsker(s.state, owner, task)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
  })
})

describe('explicit decision deadlines', () => {
  const defaultAt = '2026-11-06T04:00:00.000Z'
  it('carries a decision deadline beside its recommended option', () => {
    const s = swarm()
    const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
      questions: [{ ...question('Ship when?'), defaultAt }] } as Command, asAgent(s.lead))
    expect(asked.decisions?.[0]).toMatchObject({ defaultAt, recommended: 0 })
  })

  it('carries a needs-human deadline when there is no PM to route through', () => {
    const s = swarm()
    s.state.conversations.find(c => c.id === 'lead')!.leadId = null
    const asked = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD,
      result: 'Ship when?', ask: { personId: 'peer', options: ['Today', 'Tomorrow'], recommended: 1, unblocks: 'Release', defaultAt } } as Command, asAgent(s.worker))
    expect(asked.decisions?.[0]).toMatchObject({ defaultAt, recommended: 1 })
  })

  it('keeps the deadline when a worker question becomes the PM’s crew need', () => {
    const s = swarm()
    const asked = s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
      questions: [{ ...question('Ship when?'), defaultAt }] } as Command, asAgent(s.worker))
    expect(asked.decisions ?? []).toEqual([])
    expect(asked.messages[0]?.source?.crewNeed).toMatchObject({ defaultAt, recommended: 0 })
    const needs = s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD,
      result: 'Ship when?', ask: { personId: 'peer', options: ['Today', 'Tomorrow'], recommended: 1, unblocks: 'Release', defaultAt } } as Command, asAgent(s.worker))
    expect(needs.messages.find(m => m.source?.crewNeed)?.source?.crewNeed).toMatchObject({ defaultAt, recommended: 1 })
  })

  it('requires 15 minutes for a person to see the ask, including needs-human and PM-routed asks', () => {
    const at = (ms: number) => new Date(ms).toISOString()
    for (const delta of [-1, 0, 15 * 60_000 - 1]) {
      const s = swarm()
      expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [{ ...question('Ship when?'), defaultAt: at(1000 + delta) }] }, asAgent(s.lead)))
        .toThrow(expect.objectContaining({ code: 'INVALID_DECISION' }))
      expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [{ ...question('Ship when?'), defaultAt: at(1000 + delta) }] }, asAgent(s.worker)))
        .toThrow(expect.objectContaining({ code: 'INVALID_DECISION' }))
      expect(() => s.run({ type: 'work.status', conversationId: s.group, assignmentId: s.assignmentId, status: 'needs_human', hold: HOLD, result: 'Ship when?',
        ask: { personId: 'peer', options: ['Today', 'Tomorrow'], recommended: 0, unblocks: 'Release', defaultAt: at(1000 + delta) } }, asAgent(s.worker)))
        .toThrow(expect.objectContaining({ code: 'INVALID_DECISION' }))
    }
    const s = swarm()
    expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [{ ...question('Ship when?'), defaultAt: at(1000 + 15 * 60_000) }] }, asAgent(s.lead))).not.toThrow()
  })

  it('refuses an invalid deadline and keeps deadline-free legacy callers valid', () => {
    const s = swarm()
    const send = (at?: string) => ({ type: 'decision.ask', conversationId: s.group, personId: 'peer',
      questions: [{ ...question('Ship when?'), ...at ? { defaultAt: at } : {} }] })
    expect(commandSchema.safeParse(send('tomorrow')).success).toBe(false)
    expect(commandSchema.safeParse(send()).success).toBe(true)
  })
})

describe('answering a decision', () => {
  const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',
    conversationId: s.group, projectId: 'lead', askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 0,
    answeredAt: null, createdAt: 0, assignmentId: null, ...overrides })

  it('records the asked person\'s choice and tells the asking agent and the Lead with a notice only they read, carrying none of it', () => {
    const s = swarm()
    const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 1, note: 'We are confident.' }, peer, { decision: open(s) })
    expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 1, note: 'We are confident.' })
    expect(answered.messages).toEqual([expect.objectContaining({ conversationId: s.group, recipients: [s.worker, s.lead],
      source: { kind: 'agent-only', decisionId: 'decision-1' } })])
    for (const text of ['Ship how?', 'To everyone', 'We are confident.']) expect(answered.messages[0]!.text).not.toContain(text)
  })

  it('takes an answer only from the person asked, once, and only for one of its options', () => {
    const s = swarm()
    const answer = (actor: Actor, decision: DecisionTarget | undefined, choice = 0) =>
      () => s.run({ type: 'decision.answer', decisionId: 'decision-1', choice }, actor, decision ? { decision } : {})
    expect(answer(owner, open(s))).toThrow('unavailable')
    expect(answer(peer, undefined)).toThrow('unavailable')
    expect(answer(peer, open(s, { answeredAt: 5 }))).toThrow('already answered')
    expect(answer(peer, open(s), 2)).toThrow('Choose one of its options')
    // A person who can no longer read its conversation cannot answer it, though they stay in the Swarm.
    const hidden = 'owner-buddy'
    s.state.conversations.push({ id: hidden, kind: 'buddy', projectId: 'lead', title: 'Owner\'s Buddy', leadId: null, agentIds: [], archived: false,
      brief: '', checks: [], assignment: null, lastMessageSequence: 0, audience: { people: [{ id: 'owner', generation: s.state.people[0]!.generation }] } })
    expect(answer(peer, open(s, { conversationId: hidden }))).toThrow('unavailable')
    expect(answer(peer, open(s, { conversationId: 'gone' }))).toThrow('unavailable')
  })

  it('takes a typed answer as its note with no option, and tells the asker as it does for an option', () => {
    const s = swarm()
    expect(commandSchema.safeParse({ type: 'decision.answer', decisionId: 'decision-1', note: 'Use the Mac Studio' }).success).toBe(true)
    const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', note: 'Use the Mac Studio' }, peer, { decision: open(s) })
    expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: null, note: 'Use the Mac Studio' })
    expect(answered.messages).toEqual([expect.objectContaining({ conversationId: s.group, recipients: [s.worker, s.lead], text: ANSWERED_NOTICE,
      source: { kind: 'agent-only', decisionId: 'decision-1' } })])
    expect(answered.messages[0]!.text).not.toContain('Mac Studio')
  })

  it('still records the answer when the asker has left the conversation, telling whoever of them is left', () => {
    const s = swarm()
    const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0 }, peer, { decision: open(s, { askerAgentId: 'gone' }) })
    expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 0, note: null })
    expect(answered.messages[0]!.recipients).toEqual([s.lead])
  })
})

describe('leaving a decision to the PM', () => {
  const open = (s: ReturnType<typeof swarm>, overrides: Partial<DecisionTarget> = {}): DecisionTarget => ({ id: 'decision-1', personId: 'peer',
    conversationId: s.group, projectId: 'lead', askerAgentId: s.worker, question: 'Ship how?', options: ['Behind a flag', 'To everyone'], recommended: 1,
    answeredAt: null, createdAt: 0, assignmentId: null, ...overrides })
  /** The peer's own Buddy chat in the project, as adding a Buddy opens it (buddies.ts). */
  const buddyChat = (s: ReturnType<typeof swarm>) => {
    const generation = s.state.people.find(p => p.id === 'peer')!.generation
    const id = buddyChatId('lead', { id: 'peer', generation })
    s.state.conversations.push({ id, kind: 'buddy', projectId: 'lead', title: 'peer\'s Buddy', leadId: null, agentIds: [], archived: false,
      brief: '', checks: [], assignment: null, lastMessageSequence: 0, audience: { people: [{ id: 'peer', generation }] } })
    return id
  }
  /** The peer's own Buddy, who writes the line: only they and it post in their private chat (task #4558). */
  const withBuddy = (s: ReturnType<typeof swarm>) => giveOwnBuddy(s.state, 'peer')
  const delegate = (s: ReturnType<typeof swarm>, actor: Actor, decision: DecisionTarget | undefined) =>
    s.run({ type: 'decision.answer', decisionId: 'decision-1', delegate: true }, actor, decision ? { decision } : {})

  it('answers with the recommended option for the person asked, recorded as delegated, and their own Buddy says what the PM chose', () => {
    const s = swarm()
    withBuddy(s)
    const chat = buddyChat(s)
    const answered = delegate(s, peer, open(s))
    expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 1, note: null, delegated: true })
    const [notice, swarmLine, line] = answered.messages
    // The asker and the Lead are told the PM decided, with none of the answer, as for any answer.
    expect(notice).toMatchObject({ conversationId: s.group, recipients: [s.worker, s.lead], source: { kind: 'agent-only', decisionId: 'decision-1' } })
    expect(notice!.text).toContain('left to the Product Manager')
    for (const text of ['Ship how?', 'To everyone']) expect(notice!.text).not.toContain(text)
    // One line from their own Buddy in their one Buddy chat, marked with its project, and the same in their older chat there for
    // older apps (Dee, 10-31): only they read either, and it goes to nobody. Never the PM's: only they and their agent post there.
    const swarmChat = s.state.conversations.find(c => c.kind === 'swarm-buddy')!
    expect(swarmLine).toMatchObject({ conversationId: swarmChat.id, recipients: [], text: 'PM decided: To everyone — Ship how?',
      author: { kind: 'agent', id: 'peer-buddy' }, source: { kind: 'decision-delegated', decisionId: 'decision-1', projectId: 'lead' } })
    expect(line).toMatchObject({ conversationId: chat, recipients: [], text: 'PM decided: To everyone — Ship how?',
      author: { kind: 'agent', id: 'peer-buddy' }, source: { kind: 'decision-delegated', decisionId: 'decision-1' } })
    expect(new Set([notice!.id, swarmLine!.id, line!.id]).size).toBe(3)
    expect(answered.messages).toHaveLength(3)
  })

  it('writes no line without a Buddy, else opens the person\'s older chat for it when they have none, and an archived one again', () => {
    const s = swarm()
    expect(delegate(s, peer, open(s)).messages.map(m => m.conversationId)).toEqual([s.group])
    withBuddy(s)
    const answered = delegate(s, peer, open(s))
    expect(answered.decisionAnswer).toMatchObject({ choice: 1, delegated: true })
    const chat = s.state.conversations.find(c => c.kind === 'buddy')!, swarmChat = s.state.conversations.find(c => c.kind === 'swarm-buddy')!
    expect(chat).toMatchObject({ projectId: 'lead', agentIds: [], audience: { people: [{ id: 'peer' }] } })
    expect(swarmChat).toMatchObject({ agentIds: ['peer-buddy'], audience: { people: [{ id: 'peer' }] } })
    expect(swarmChat.projectId).toBeUndefined()
    expect(answered.messages.map(m => m.conversationId)).toEqual([s.group, swarmChat.id, chat.id])
    chat.archived = true
    swarmChat.archived = true
    expect(delegate(s, peer, open(s)).messages.map(m => m.conversationId)).toEqual([s.group, swarmChat.id, chat.id])
    expect(s.state.conversations.find(c => c.id === chat.id)!.archived).toBe(false)
    expect(s.state.conversations.find(c => c.id === swarmChat.id)!.archived).toBe(false)
  })

  it('lets only the person asked delegate, once, and only a decision with a recommended option', () => {
    const s = swarm()
    expect(() => delegate(s, owner, open(s))).toThrow('unavailable')
    expect(() => delegate(s, peer, undefined)).toThrow('unavailable')
    expect(() => delegate(s, peer, open(s, { answeredAt: 5 }))).toThrow('already answered')
    expect(() => delegate(s, peer, open(s, { recommended: 2 }))).toThrow('no recommended option')
  })

  it('takes a choice, a typed answer or a delegation, not a choice and a delegation or none of them', () => {
    const s = swarm()
    expect(() => s.run({ type: 'decision.answer', decisionId: 'decision-1', choice: 0, delegate: true }, peer, { decision: open(s) })).toThrow('or leave it to the PM')
    expect(() => s.run({ type: 'decision.answer', decisionId: 'decision-1' }, peer, { decision: open(s) }))
      .toThrow('Choose one of its options, type an answer, or leave it to the PM.')
    expect(commandSchema.safeParse({ type: 'decision.answer', decisionId: 'decision-1', delegate: false }).success).toBe(false)
  })

  it('an overdue answer takes the recommended option and says it waited 24 hours', () => {
    const s = swarm()
    const answered = s.run({ type: 'decision.answer', decisionId: 'decision-1', delegate: true }, peer, { decision: open(s), overdue: true })
    expect(answered.decisionAnswer).toEqual({ id: 'decision-1', choice: 1, note: null, delegated: true, overdue: true })
    expect(answered.messages[0]!.text).toBe(overdueNotice('Product Manager'))
  })

  it('takes a timed default only at its trusted deadline, and never accepts the marker from a client', () => {
    const s = swarm()
    withBuddy(s)
    const decision = open(s, { defaultAt: 1000 })
    const command = { type: 'decision.answer', decisionId: 'decision-1', delegate: true } as const
    expect(() => s.run(command, peer, { decision, defaulted: true, now: 999 } as Partial<CommandContext>)).toThrow(/default.*time|deadline/i)
    expect(() => s.run(command, peer, { decision: open(s), defaulted: true, now: 1000 } as Partial<CommandContext>)).toThrow(/default.*time|deadline/i)
    expect(() => s.run(command, peer, { decision: open(s, { defaultAt: 1000, kind: 'routing-reflection' }), defaulted: true, now: 1000 } as Partial<CommandContext>)).toThrow(/default|reflection/i)
    expect(commandSchema.safeParse({ ...command, defaulted: true }).success).toBe(false)
    const taken = s.run(command, peer, { decision, defaulted: true, now: 1000 } as Partial<CommandContext>)
    expect(taken.decisionAnswer).toMatchObject({ delegated: true, defaulted: true, choice: 1 })
    expect(taken.messages[0]!.text).toMatch(/default.*time|deadline/i)
    expect(taken.messages[1]!.text).toBe('Default applied: To everyone — Ship how?')
  })

  it('overdue without delegate is refused', () => {
    const s = swarm()
    expect(() => answerDecision(s.state, peer, open(s), { choice: 0, note: null, delegate: false, overdue: true }))
      .toThrow(expect.objectContaining({ code: 'INVALID_DECISION', status: 400 }))
  })

  it('a person\'s delegate is not overdue', () => {
    const s = swarm()
    const answered = delegate(s, peer, open(s))
    expect(answered.decisionAnswer).not.toHaveProperty('overdue')
    expect(answered.messages[0]!.text).toBe(delegatedNotice('Product Manager'))
  })
})

describe('listing a person\'s decisions', () => {
  /** A transaction whose open decisions are [count] rows asked of the peer in the group, newest first. */
  const reading = (s: ReturnType<typeof swarm>, count: number) => {
    const asked: Array<{ take?: number }> = []
    const rows = Array.from({ length: count }, (_, i) => ({ id: `decision-${i}`, batchId: `batch-${i}`, projectId: 'lead', conversationId: s.group,
      assignmentId: null, personId: 'peer', askerAgentId: s.lead, question: `Question ${i}`, options: ['Behind a flag', 'To everyone'], recommended: 0,
      unblocks: 'The release', createdAt: new Date(1000 - i), answeredAt: null, choice: null, note: null, delegated: null }))
    const tx = { superTabDecision: { findMany: async (args: { take?: number }) => { asked.push(args); return rows.slice(0, args.take) } } }
    return { tx: tx as unknown as Prisma.TransactionClient, asked }
  }

  it('says when the newest page leaves open decisions out, so a client never takes it for all of them', async () => {
    const s = swarm()
    const full = reading(s, 201)
    const page = await listDecisions(full.tx, 'tab', s.state, peer, 'open')
    expect(page.decisions).toHaveLength(200)
    expect(page.more).toBe(true)
    const all = await listDecisions(reading(s, 3).tx, 'tab', s.state, peer, 'open')
    expect(all.decisions.map(d => d.id)).toEqual(['decision-0', 'decision-1', 'decision-2'])
    expect(all.more).toBe(false)
  })
})

describe('reading a typed answer', () => {
  it('shows the asker the note as the answer, with no option', async () => {
    const s = swarm()
    const row = { id: 'decision-1', batchId: 'batch-1', projectId: 'lead', conversationId: s.group, assignmentId: null, personId: 'peer',
      askerAgentId: s.worker, question: 'Which machine runs the phone tests?', options: ['Tony\'s Mac', 'Mac Studio'], recommended: 0,
      unblocks: 'The phone tests', createdAt: new Date(1000), answeredAt: new Date(2000), choice: null, note: 'Use the Mac Studio', delegated: null,
      overdue: null, kind: null, withdrawn: null }
    const tx = { superTabDecision: { findMany: async () => [row] } } as unknown as Prisma.TransactionClient
    const read = await listDecisions(tx, 'tab', s.state, asAgent(s.worker), 'answered')
    expect(read.decisions).toEqual([expect.objectContaining({ id: 'decision-1', choice: null, note: 'Use the Mac Studio', answer: 'Use the Mac Studio' })])
  })
})

// groupBy on SuperTabDecision once panicked the Prisma engine on Mongo: the digest counts the open decisions it reads instead.
describe('the decisions waiting in a project', () => {
  it('counts each conversation and person\'s open decisions without groupBy, reading only who and where', async () => {
    const asked: unknown[] = []
    const rows = [{ conversationId: 'c1', personId: 'owner' }, { conversationId: 'c2', personId: 'peer' }, { conversationId: 'c1', personId: 'owner' },
      { conversationId: 'c1', personId: 'peer' }, { conversationId: 'c1', personId: 'owner' }]
    const tx = { superTabDecision: {
      groupBy: async () => { throw new Error('groupBy on SuperTabDecision') },
      findMany: async (args: unknown) => { asked.push(args); return rows },
    } } as unknown as Prisma.TransactionClient
    expect(await waitingInProject(tx, 'tab', 'web')).toEqual([{ conversationId: 'c1', personId: 'owner', count: 3 },
      { conversationId: 'c2', personId: 'peer', count: 1 }, { conversationId: 'c1', personId: 'peer', count: 1 }])
    expect(asked).toEqual([{ where: { tabId: 'tab', projectId: 'web', OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] },
      select: { conversationId: true, personId: true } }])
  })
})

// Dee, 10-31: "4 decisions wait for you", two of them asked in tasks already done and merged.
describe('a decision whose work is over', () => {
  const at = (s: ReturnType<typeof swarm>, id: string) => s.state.conversations.find(c => c.id === id)!
  const ended = (s: ReturnType<typeof swarm>, change: (state: ReturnType<typeof swarm>['state']) => void) => {
    const before = structuredClone(s.state), after = structuredClone(s.state)
    change(after)
    return workEnded(before, after)
  }

  it('is over once its work group\'s task is done or cancelled, or the group archived; not while its task is open or reopened', () => {
    const s = swarm()
    const group = at(s, s.group)
    expect(workOver(s.state, group)).toBe(false)
    for (const status of ['done', 'cancelled'] as const) expect(workOver(s.state, { ...group, assignment: { ...group.assignment!, status } })).toBe(true)
    for (const status of ['working', 'needs_human', 'blocked', 'review', 'stopped', 'lost'] as const) {
      expect(workOver(s.state, { ...group, assignment: { ...group.assignment!, status } })).toBe(false)
    }
    expect(workOver(s.state, { ...group, archived: true })).toBe(true)
    expect(workOver(s.state, { ...group, assignment: null })).toBe(false)
  })

  it('is never over in a project chat, a Buddy chat or a closed Chat with PM, whatever they hold', () => {
    const s = swarm()
    const finished = { archived: true, assignment: { ...at(s, s.group).assignment!, status: 'cancelled' as const } }
    expect(workOver(s.state, { ...at(s, 'lead'), ...finished })).toBe(false)
    expect(workOver(s.state, { ...at(s, s.group), ...finished, kind: 'buddy' })).toBe(false)
    expect(workOver(s.state, { ...at(s, s.group), ...finished, audience: { people: [] } })).toBe(false)
  })

  it('names the conversations a write ended, once: not those already over, nor one reopened', () => {
    const s = swarm()
    expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.assignment!.status = 'done' })).toEqual([s.group])
    expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.archived = true })).toEqual([s.group])
    expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.assignment!.status = 'review' })).toEqual([])
    s.run({ type: 'work.cancel', conversationId: s.group, assignmentId: s.assignmentId, reason: 'Not needed' })
    expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.archived = true })).toEqual([])
    expect(ended(s, state => { state.conversations.find(c => c.id === s.group)!.assignment = null })).toEqual([])
  })

  it('closes those still waiting there as withdrawn, never a routing reflection\'s, and only in the conversations named', async () => {
    const calls: unknown[] = []
    const tx = { superTabDecision: { updateMany: async (args: unknown) => { calls.push(args); return { count: 2 } } } } as unknown as Prisma.TransactionClient
    expect(await withdrawIn(tx, 'tab', [], 5)).toBe(0)
    expect(calls).toEqual([])
    expect(await withdrawIn(tx, 'tab', ['g1', 'g1'], 5)).toBe(2)
    expect(calls).toEqual([{ where: { tabId: 'tab', conversationId: 'g1', AND: [
      { OR: [{ answeredAt: null }, { answeredAt: { isSet: false } }] },
      { OR: [{ kind: { isSet: false } }, { kind: null }, { kind: { not: 'routing-reflection' } }] }] },
    data: { answeredAt: new Date(5), withdrawn: true } }])
  })

  it('leaves the open list and the count, closed or not yet, while one in an open task stays', async () => {
    const s = swarm()
    const other = s.run({ type: 'conversation.create', title: 'Search', brief: 'Find things.', checks: [] }).result.conversationId as string
    at(s, other).assignment = { ...at(s, s.group).assignment!, id: 'old', status: 'done' }
    const row = (id: string, conversationId: string) => ({ id, batchId: id, projectId: 'lead', conversationId, assignmentId: null, personId: 'peer',
      askerAgentId: s.lead, question: id, options: ['A', 'B'], recommended: 0, unblocks: 'X', createdAt: new Date(1), answeredAt: null, choice: null,
      note: null, delegated: null })
    const rows = [row('open-task', s.group), row('done-task', other), row('project-chat', 'lead')]
    const tx = { superTabDecision: { findMany: async () => rows } } as unknown as Prisma.TransactionClient
    expect((await listDecisions(tx, 'tab', s.state, peer, 'open')).decisions.map(d => d.id)).toEqual(['open-task', 'project-chat'])
    expect((await decisionsWaiting(tx, 'tab', s.state, peer)).count).toBe(2)
    // Its answered history stays: a decision answered before the work ended is still listed as answered.
    const answered = rows.map(r => ({ ...r, answeredAt: new Date(2), choice: 0 }))
    const read = { superTabDecision: { findMany: async () => answered } } as unknown as Prisma.TransactionClient
    expect((await listDecisions(read, 'tab', s.state, peer, 'settled')).decisions.map(d => d.id)).toEqual(['open-task', 'done-task', 'project-chat'])
  })

  it('says which decisions the 24-hour sweep takes over: not a reflection, not a recommended option that does not exist', async () => {
    const s = swarm()
    const row = (id: string, extra: Record<string, unknown>) => ({ id, batchId: id, projectId: 'lead', conversationId: 'lead', assignmentId: null, personId: 'peer',
      askerAgentId: s.lead, question: id, options: ['A', 'B'], recommended: 0, unblocks: 'X', createdAt: new Date(1), answeredAt: null, choice: null,
      note: null, delegated: null, ...extra })
    const rows = [row('plain', {}), row('reflection', { kind: 'routing-reflection' }), row('out-of-range', { recommended: 9 }), row('negative', { recommended: -1 })]
    const tx = { superTabDecision: { findMany: async () => rows } } as unknown as Prisma.TransactionClient
    const listed = (await listDecisions(tx, 'tab', s.state, peer, 'open')).decisions
    expect(Object.fromEntries(listed.map(d => [d.id, d.pmTakesOver]))).toEqual({ plain: true, reflection: false, 'out-of-range': false, negative: false })
  })

  it('takes no new question in finished work, where it would wait for nobody', () => {
    const s = swarm()
    const ask = () => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Reopen it?')] }, asAgent(s.lead))
    expect(ask().decisions).toHaveLength(1)
    s.run({ type: 'work.cancel', conversationId: s.group, assignmentId: s.assignmentId, reason: 'Not needed' })
    expect(ask).toThrow(expect.objectContaining({ code: 'WORK_FINISHED' }))
    // Anyone who may not ask there is refused as before, never told the work is finished.
    expect(() => s.run({ type: 'decision.ask', conversationId: s.group, personId: 'peer', questions: [question('Reopen it?')] }, owner))
      .toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
    // The project chat always takes one.
    expect(s.run({ type: 'decision.ask', conversationId: 'lead', personId: 'peer', questions: [question('Reopen it?')] }, asAgent(s.lead)).decisions).toHaveLength(1)
  })

  it('takes no answer, closed or not yet, with the code an answered one gets', () => {
    const s = swarm()
    const decision: DecisionTarget = { id: 'decision-1', personId: 'peer', conversationId: s.group, projectId: 'lead', askerAgentId: s.worker,
      question: 'Ship how?', options: ['A', 'B'], recommended: 0, answeredAt: null, createdAt: 0, assignmentId: null }
    const answer = (d: DecisionTarget) => () => s.run({ type: 'decision.answer', decisionId: d.id, choice: 0 }, peer, { decision: d })
    expect(answer({ ...decision, answeredAt: 5, withdrawn: true })).toThrow(expect.objectContaining({ code: 'DECISION_ANSWERED', message: expect.stringContaining('no longer waits') }))
    s.run({ type: 'work.cancel', conversationId: s.group, assignmentId: s.assignmentId, reason: 'Not needed' })
    expect(answer(decision)).toThrow(expect.objectContaining({ code: 'DECISION_ANSWERED', message: expect.stringContaining('no longer waits') }))
    // Anyone but the person asked is told it does not exist, as before: never that its work is finished.
    expect(() => s.run({ type: 'decision.answer', decisionId: decision.id, choice: 0 }, owner, { decision }))
      .toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
  })
})