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.

53.9 KB
Raw Blame
import { recordPulse } from './pulse.js'
import { linesOf } from './statusCard.js'
import { CREW_REOPEN_GRACE_MS, isCrew } from './crew.js'
import { activeWork, forRecipients, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,
  type SuperTabState, type TaskLiveness } from './model.js'
import { failedSessionStart } from './buddySessions.js'
import { noteStartFailed } from './engineHealth.js'
import { machineOffline, sessionStopped } from './lostReason.js'
import { agentDisplayName } from './agentNames.js'
import { askedModel, coordinatorCopy, failureNotice, failureRecipients, leadPickupSuffix, REFUSED_INFIX, STILL_PREPARING_SUFFIX, STOPPED_REPORTING_SUFFIX, TIMED_OUT_SUFFIX } from './startFailure.js'
import { leadOf, toLead } from './terminal.js'
import { dropIdleBuddyMachines, MACHINE_FRESH_MS } from './machines.js'
import { leadStartFailed } from './leadStart.js'
import { staleModelRequests, staleSwitches } from './tidy.js'
import { ledProject, projectsOf } from './projects.js'
import { coordinatorNameOf } from './instructions.js'
import { waitedOn } from './leaderboard/record.js'
import { isStep } from './steps.js'
import { endedReply } from './taskLine.js'
import { crewClock, DISPATCH_RULES, laneOf, nudgeLine, returnReason, type DispatchLookup } from './dispatch.js'
import { handed, pickUp, unclaimedAt, unclaimedReason } from './handed.js'
import { isBuddy } from './buddies.js'
import { closeMergedLost } from './mergedTasks.js'
import { stepCandidates } from './reviewerPick.js'
import { noTesterFree, stepOs } from './reviewTable.js'

// Work never sits with a dead owner (design: "A Swarm that never stops", 2026-10-26). A worker's active assignment is held
// by a lease that its progress renews. A dead, stalled or limited worker loses it within minutes: the assignment becomes
// lost, its agent is fenced off, and the Lead is woken to hand it on. Leads are not covered here.
//
// The agent's own status, checks and posts renew the lease stored on the assignment. Its machine's reports renew it too,
// but are read from the report its machine part keeps (written on every report anyway), never written into the group: a
// group written once a minute per task would wake every reader of the Swarm.

/** How long an assignment stays its agent's without progress. */
export const LEASE_MS = 5 * 60_000
/** A session its machine still lists as running may go this long without a screen or transcript change before its task is
 *  lost: a long command that prints nothing (a test suite) is still work (Product Manager, 2026-10-26). Hard failures —
 *  offline, stopped, a usage limit — stay immediate. */
export const QUIET_RUNNING_MS = 30 * 60_000
/** A report renews the lease while the session's last progress is this recent, so its lease ends QUIET_RUNNING_MS after it. */
const PROGRESS_FRESH_MS = QUIET_RUNNING_MS - LEASE_MS
/** A machine silent this long has lost its work. */
const OFFLINE_LOST_MS = 2 * 60_000
/** A dispatched start not running this long after has failed. */
const START_RUN_MS = 3 * 60_000
/** A start its machine keeps reporting as preparing may take this long: the worktree checkout's own limit (10 minutes,
 *  cli lib/gitProject.ts WORKTREE_ADD_TIMEOUT) and the fetch before it. 3 minutes failed starts on a busy Mac that was
 *  still fetching and checking out a 470 MB project (2026-10-27). */
const START_PREPARE_MS = 15 * 60_000
/** Any machine's report runs the time checks for its Swarm at most this often. */
export const SWEEP_EVERY_MS = 30_000

const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
const machineName = (state: SuperTabState, machineId: string) => state.machines?.find(m => m.machineId === machineId)?.name ?? 'its machine'
/** What [group]'s project calls its coordinator; never a lookup that throws, since these checks run inside machine reports. */
const coordinatorOfGroup = (state: SuperTabState, group: Conversation) =>
  coordinatorNameOf(projectsOf(state).find(p => p.id === (group.projectId ?? 'lead')) ?? {})
/** [group]'s project chat when it is loaded; never a lookup that throws. */
const projectChatOf = (state: SuperTabState, group: Conversation) =>
  state.conversations.find(c => c.id === projectsOf(state).find(p => p.id === (group.projectId ?? 'lead'))?.leadConversationId)
/** A sweep runs inside a machine's report and the Lead's poll, so it never fails on an agent whose membership changed:
 *  it writes as that agent without checking it, and a delivery to an agent no longer shared is not created. */
const writtenBy = (state: SuperTabState, writer: Agent): Author => ({ kind: 'agent', id: writer.id, name: writer.name,
  displayName: agentDisplayName(state.agents, writer.id), membershipGeneration: writer.membershipGeneration })
const reachable = (state: SuperTabState, row: MessageDraft): MessageDraft => ({ ...row, recipients: row.recipients.filter(id => {
  const target = state.agents.find(a => a.id === id)
  return !!target && state.people.find(p => p.id === target.contributorId)?.generation === target.membershipGeneration
}) })

/** A notice for the Lead (terminal.ts toLead): when the Lead hears it in its own chat, the copy left in the task's chat for
 *  no one is that same notice, read by no one either. With no Lead to hear it, people read it (review of #2177). */
export function leadNoticeRows(rows: MessageDraft[]): MessageDraft[] {
  return rows.some(row => row.recipients.length) ? rows.map(row => row.recipients.length ? row : { ...row, source: forRecipients(row.source ?? {}) }) : rows
}

/** The agent's own progress (an assignment, a status, a check, a post) renews the lease stored on its assignment. */
export function renewLease(assignment: Assignment, now: number): void {
  assignment.leaseUntil = now + LEASE_MS
  assignment.progressAt = now
}

/** A hand-off as the older built-in skills write it: a result that says it is ready for review and names a revision (a commit
 *  hash). Right after '@', 'at ' or 'head ', the forms hand-offs use, any 7-40 hex digits count, since a short hash can be all
 *  digits or all letters; anywhere else it needs a digit and a letter, so dates and other numbers do not count (review of
 *  #2176). Desktop reads hand-offs with a copy of these two (desktop/lib/super_tabs/agent_mark.dart): change both together. */
const READY_FOR_REVIEW = /\bready for review\b/i
const REVISION = /(?:@|\b(?:at|head)\s+)[0-9a-f]{7,40}\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/i

/** Work that waits for others, whose quiet time therefore does not count (2026-10-29: five Engineers who had handed over lost
 *  their tasks waiting for a Reviewer): the review status its agent set, or, while agents on the older built-in skills exist
 *  (this release), a working task whose result is their hand-off, until someone else's verdict finds problems in it
 *  (commands.ts work.check sets reviewFoundAt). Those skills had Done refused until a review passed. */
export function waitingForReview(assignment: Assignment): boolean {
  if (assignment.status === 'review') return true
  return assignment.status === 'working' && assignment.reviewFoundAt === undefined && !!assignment.result
    && READY_FOR_REVIEW.test(assignment.result) && REVISION.test(assignment.result)
}

/** A task's Engineer waits on one of its own steps while that step's agent is at work on it (Diego, 2026-11-03, #2323: the
 *  instructions never ask the Engineer to set review while its Review and Test run, so it lost its task 35 minutes in). A
 *  step in Ready has handed its verdict over, and one whose verdict asked for changes waits for the Engineer's new revision
 *  (review of #2744): then it is the Engineer's turn, else the two would wait on each other. */
export function waitingOnSteps(state: SuperTabState, group: Conversation, steps: StepIndex = stepIndex(state)): boolean {
  return !isStep(group) && (steps.get(group.id) ?? []).some(step => !step.archived && activeWork(step) && step.assignment!.status !== 'review'
    && !(reviews(step, group) && waitsOnRevisionOf(step, group)))
}

/** The loaded steps of each task, by task id, read once per pass: liveness runs inside every machine report and command
 *  write, so a scan of every conversation per task would grow with tasks times conversations (review of #2744). */
type StepIndex = ReadonlyMap<string, Conversation[]>
function stepIndex(state: SuperTabState): StepIndex {
  const steps = new Map<string, Conversation[]>()
  for (const c of state.conversations) {
    if (!c.reviewOf) continue
    const of = steps.get(c.reviewOf)
    if (of) of.push(c)
    else steps.set(c.reviewOf, [c])
  }
  return steps
}

/** [task]'s Engineer waited on its steps, as its record says, and none is at work now: its quiet time runs from now, as
 *  revisionReady's does, so it has 30 minutes to act on what they found and a hung Engineer is still found. The record it
 *  writes ends that wait, so this runs once per wait. */
function stepsEnded(state: SuperTabState, task: Conversation, now: number, steps?: StepIndex): void {
  if (!activeWork(task) || task.assignment!.status !== 'working' || task.liveness?.state !== 'waiting' || task.liveness.why !== 'review') return
  if (waitingOnSteps(state, task, steps)) return
  restartQuietTime(task.assignment!, now)
  recordTaskState(state, task, now)
}

/** Work that stopped waiting for its review counts its quiet time from now: its agent keeps it QUIET_RUNNING_MS without
 *  progress, as after its last screen change, though its screen stayed still while it waited. */
export function restartQuietTime(assignment: Assignment, now: number): void {
  assignment.progressAt = now
  assignment.leaseUntil = Math.max(assignment.leaseUntil ?? 0, now + QUIET_RUNNING_MS)
}

/** The build a linked task (reviewOf) reviews, while that build is active work of the same project and not archived. Only
 *  a loaded build counts: an active one is always loaded, by a machine's report (parts/load.ts loadObserved reads running
 *  groups) as by the Lead's poll. A cancelled, finished, lost, archived or asleep build reviews nothing. */
function reviewedBuild(state: SuperTabState, group: Conversation): Conversation | undefined {
  if (!group.reviewOf) return undefined
  const build = state.conversations.find(c => c.id === group.reviewOf)
  return build && reviews(group, build) ? build : undefined
}

/** Whether [build] is one [step] reviews now: active work of the same project, not archived (reviewedBuild). */
const reviews = (step: Conversation, build: Conversation): boolean =>
  !build.archived && activeWork(build) && (build.projectId ?? 'lead') === (step.projectId ?? 'lead')

/** The active linked tasks (reviewOf [build]) its own [agentId] holds: the Reviewer's or Tester's task for that build. */
function ownLinkedTasks(state: SuperTabState, build: Conversation, agentId: string): Conversation[] {
  return state.conversations.filter(c => c.reviewOf === build.id && activeWork(c) && c.assignment!.agentId === agentId
    && reviewedBuild(state, c) === build)
}

/** A linked task waits for the new revision from its own Reviewer's verdict asking for changes until the build's next Ready,
 *  while that build is still active, so its quiet time does not count then (Diego, 2026-11-01: a Reviewer waiting on a normal
 *  fix round of ~31 minutes lost its task, its Lead was woken and its verdict refused). It follows the Reviewer, never the
 *  Engineer: an Engineer's own posts or "working" heartbeats keep no idle Reviewer (review of #2487). A verdict is usually a
 *  post to the Engineer, which holds only while the Engineer isn't itself waiting on a review, so a "starting now" followed by
 *  silence still moves (#2241: 35 attempts lost in a day). */
export function waitingForRevision(state: SuperTabState, group: Conversation): boolean {
  const build = reviewedBuild(state, group)
  return !!build && waitsOnRevisionOf(group, build)
}

/** waitingForRevision of [step] for the [build] it reviews, already found (reviewedBuild). */
function waitsOnRevisionOf(step: Conversation, build: Conversation): boolean {
  const assignment = step.assignment
  return assignment?.changesRequestedAt !== undefined || (assignment?.toldEngineerAt !== undefined && !waitingForReview(build.assignment!))
}

/** [agentId] wrote to its Engineer, in its own linked task's chat or in the build's, while the Engineer was waiting on this
 *  review: it may now wait for the new revision (waitingForRevision). A note to a working Engineer keeps no Reviewer that then
 *  hangs. What the post says is not read (Dee, #3394): a verdict asking for changes is a failed check, recorded at the head it
 *  read (changesRequested). Written in that post's own write. */
export function toldEngineer(state: SuperTabState, group: Conversation, agentId: string, recipients: string[], now: number): void {
  const own = activeWork(group) && group.assignment!.agentId === agentId && reviewedBuild(state, group) ? [group] : ownLinkedTasks(state, group, agentId)
  for (const step of own) {
    const engineer = reviewedBuild(state, step)!.assignment!
    if (!recipients.includes(engineer.agentId) || !waitingForReview(engineer)) continue
    step.assignment!.toldEngineerAt = now
    recordTaskState(state, step, now)
  }
}

/** The Engineer [agentId] wrote to a step's agent waiting for its revision, in the step's chat or the build's: a "fixed at abc,
 *  please re-check" is a Ready by post, so that wait ends and its 30 minutes run from now (review of #2659), whether a post or
 *  a failed check began it, as revisionReady ends both (#2301: a failed check's wait held a hung Reviewer for hours). A step
 *  not waiting gets no time from it: an Engineer's posts keep no idle Reviewer (review of #2487). */
export function engineerAnswered(state: SuperTabState, group: Conversation, agentId: string, recipients: string[], now: number): void {
  const steps = group.reviewOf ? [group] : state.conversations.filter(c => c.reviewOf === group.id)
  for (const step of steps) {
    if (!activeWork(step) || !recipients.includes(step.assignment!.agentId)) continue
    if (step.assignment!.toldEngineerAt === undefined && step.assignment!.changesRequestedAt === undefined) continue
    if (reviewedBuild(state, step)?.assignment!.agentId !== agentId) continue
    delete step.assignment!.changesRequestedAt
    delete step.assignment!.toldEngineerAt
    restartQuietTime(step.assignment!, now)
    recordTaskState(state, step, now)
  }
}

/** [agentId]'s verdict in [build] asked for changes (a failed check by someone other than its assignee): its own linked task
 *  waits for the new revision (waitingForRevision). Written in that command's own write, with the linked task's group. */
export function changesRequested(state: SuperTabState, build: Conversation, agentId: string, now: number): void {
  for (const linked of ownLinkedTasks(state, build, agentId)) {
    linked.assignment!.changesRequestedAt = now
    recordTaskState(state, linked, now)
  }
}

/** [build] is ready for review again: each linked task that waited for this revision counts its quiet time from now, so the end
 *  of the wait does not lose it, as an Engineer whose review found problems does (restartQuietTime). */
export function revisionReady(state: SuperTabState, build: Conversation, now: number): void {
  for (const linked of state.conversations.filter(c => c.reviewOf === build.id && activeWork(c) && (c.assignment!.changesRequestedAt !== undefined || c.assignment!.toldEngineerAt !== undefined))) {
    delete linked.assignment!.changesRequestedAt
    delete linked.assignment!.toldEngineerAt
    restartQuietTime(linked.assignment!, now)
    recordTaskState(state, linked, now)
  }
}

/** The active assignments held by workers, not by a Lead, and not already being reconciled after their agent left. */
function workerTasks(state: SuperTabState): Array<{ group: Conversation; assignment: Assignment; worker: Agent }> {
  return state.conversations.filter(activeWork).flatMap(group => {
    const assignment = group.assignment!
    const worker = state.agents.find(a => a.id === assignment.agentId)
    if (!worker || assignment.status === 'reconciling' || state.conversations.some(c => c.leadId === worker.id)) return []
    return [{ group, assignment, worker }]
  })
}

/** The worker's own status, check or message in its task's group renews its lease. A Reviewer or Tester checks and posts in
 *  the build's group, so there it renews its own linked task (reviewOf), never another agent's. */
export function renewOwnTask(state: SuperTabState, group: Conversation, agentId: string, now: number): void {
  if (activeWork(group) && group.assignment!.agentId === agentId) {
    renewLease(group.assignment!, now)
    // A task that came back to it (handed.ts, #3399) is picked up by its own progress there.
    pickUp(group.assignment!)
  }
  for (const linked of ownLinkedTasks(state, group, agentId)) renewLease(linked.assignment!, now)
}

/** The last time its machine's reports renewed a worker's lease: a report listing it running with recent progress renews at
 *  that report, so a lease from the last report with progress P runs from P + PROGRESS_FRESH_MS at the latest.
 *  A host that sends no progress at all (before harnessProgress) renews by running alone; one that stopped listing the
 *  session renewed last when it went down. Undefined when no report ever showed it. */
function reportRenewedAt(state: SuperTabState, worker: Agent): number | undefined {
  const report = state.machines?.find(m => m.machineId === worker.machineId)?.observation
  if (!report) return undefined
  if (!report.runningHarnessIds.includes(worker.harnessId)) return worker.downSince ? Date.parse(worker.downSince) : undefined
  if (!report.harnessProgress) return report.receivedAt
  const progress = report.harnessProgress[worker.harnessId]
  return progress === undefined ? undefined : Math.min(report.receivedAt, progress + PROGRESS_FRESH_MS)
}

/** When the person its agent asked answered, while the assignment still says needs_human (the agent has not set working yet). */
function answeredAt(group: Conversation, assignment: Assignment): number | undefined {
  const waiting = group.ledger?.waiting
  return assignment.status === 'needs_human' && waiting?.assignmentId === assignment.id ? waiting.answeredAt ?? undefined : undefined
}

/** A task waits on a person (needs_human, or blocked: its agent cannot go on; or its terminal at a prompt its host alerted,
 *  terminal.ts, whatever its status says, task #4217) and its agent is alive: its machine's last report lists the session
 *  running. Its terminal prints nothing while it waits, so quiet time does not count (Ken, 2026-11-04, #2969: a task waiting on
 *  Huy was lost after 30 quiet minutes, twice). Not once the person answered (the agent then has 30 minutes from the answer,
 *  leaseEnd), and not for an agent no report shows running: that one is gone and loses it as before. */
function waitingOnPerson(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment): boolean {
  const asked = ((assignment.status === 'needs_human' || assignment.status === 'blocked') && answeredAt(group, assignment) === undefined)
    || !!worker.alerting?.includes('prompt')
  return asked && !!state.machines?.find(m => m.machineId === worker.machineId)?.observation?.runningHarnessIds.includes(worker.harnessId)
}

/** When a worker's lease ends: from its own last status, check or post (for an assignment from before leases, its group's
 *  last message), or from its machine's reports, whichever is later; a person's answer to its question starts its quiet
 *  time too. Undefined when nothing ever renewed it. */
function leaseEnd(group: Conversation, assignment: Assignment, renewed: number | undefined): number | undefined {
  const answered = answeredAt(group, assignment)
  const lease = assignment.leaseUntil ?? (group.lastActivityAt ? Date.parse(group.lastActivityAt) + LEASE_MS : undefined)
  const own = answered === undefined ? lease : Math.max(lease ?? 0, answered + QUIET_RUNNING_MS)
  const reported = renewed === undefined ? undefined : renewed + LEASE_MS
  return own === undefined ? reported : reported === undefined ? own : Math.max(own, reported)
}

/** The worker's last progress any renewal saw: its own report, or a screen change its machine reported. */
function lastProgress(state: SuperTabState, worker: Agent, assignment: Assignment): number | undefined {
  const report = state.machines?.find(m => m.machineId === worker.machineId)?.observation
  const reported = report?.harnessProgress?.[worker.harnessId]
  const seen = [assignment.progressAt, reported === undefined ? undefined : Math.min(reported, report!.receivedAt)].filter((t): t is number => t !== undefined)
  return seen.length ? Math.max(...seen) : undefined
}

function limitReason(worker: Agent, now: number): string | null {
  return worker.alerting?.includes('limit') && worker.limitedUntil && Date.parse(worker.limitedUntil) > now
    ? `it hit a usage limit until ${worker.limitedUntil.slice(11, 16)} UTC` : null
}

/** The earliest time a task held by a worker on [machineId] may be lost to its lease running out, as lostReason reads it now,
 *  or undefined when none can. Reports that keep its session running with progress no older can only move it later. */
export function nextLossAt(state: SuperTabState, machineId: string): number | undefined {
  const steps = stepIndex(state)
  const mine = workerTasks(state).filter(({ worker }) => worker.machineId === machineId)
  const ends = [...mine
    .filter(({ group, worker, assignment }) => !waitingForReview(assignment) && !waitingForRevision(state, group)
      && !waitingOnSteps(state, group, steps) && !waitingOnPerson(state, group, worker, assignment))
    .map(({ group, assignment, worker }) => leaseEnd(group, assignment, reportRenewedAt(state, worker))),
  // A task back with its Engineer and not picked up leaves it then, whatever it waits on (handed.ts).
  ...mine.map(({ assignment }) => unclaimedAt(assignment))]
    .filter((end): end is number => end !== undefined)
  return ends.length ? Math.min(...ends) : undefined
}

/** A crew member whose session went down less than CREW_REOPEN_GRACE_MS ago, which its host is reopening: never one asleep
 *  (closed on purpose) or moved to another machine (task #3398 adds both marks), which its host leaves closed. */
const reopening = (worker: Agent, now: number): boolean => {
  const away = worker as Agent & { asleep?: unknown; movedTo?: unknown }
  return isCrew(worker) && !away.asleep && !away.movedTo && !!worker.downSince && now - Date.parse(worker.downSince) < CREW_REOPEN_GRACE_MS
}

/** Why [worker] cannot work now: its session stopped (unless [closedOnPurpose]: asleep, task #3398; or, for a task it
 *  [holds], a crew member its host is reopening, crew.ts), its machine offline, a usage limit, or its model failing. A task
 *  its agent holds is lost for it (lostReason); the crew dispatch hands such a member nothing new (dispatch.ts freeCrew).
 *  Only a machine that has reported can be offline. */
export function unavailableReason(state: SuperTabState, worker: Agent, now: number, closedOnPurpose = false, holds = false): string | null {
  const pool = state.machines?.find(m => m.machineId === worker.machineId)
  if (!closedOnPurpose && pool?.observation?.stoppedHarnessIds.includes(worker.harnessId) && !(holds && reopening(worker, now))) return sessionStopped(pool.name)
  if (pool?.observation && now - pool.observation.receivedAt > OFFLINE_LOST_MS) return machineOffline(pool.name)
  const limited = limitReason(worker, now)
  if (limited) return limited
  // Its host alerts only after ten minutes of retries without an answer (cli superTabs/terminal.ts MODEL_WAIT_MS), so a
  // short burst of failures that recovers never gets here.
  if (worker.alerting?.includes('model')) return 'its model keeps failing'
  return null
}

/** Why a worker has lost its task now, or null while it still holds it. */
function lostReason(state: SuperTabState, group: Conversation, worker: Agent, assignment: Assignment, now: number, steps: StepIndex, rulesFor: DispatchLookup): string | null {
  // A handed task waits on its Reviewers and CI, not on its Engineer, which may be down or at work elsewhere (task #3399).
  if (handed(group)) return null
  // A crew member its host is reopening keeps its task for the reopen's grace (crew.ts).
  const gone = unavailableReason(state, worker, now, false, true)
  if (gone) return gone
  // Back with its Engineer and not picked up in time: anyone free in the lane takes it (handed.ts, #3399).
  const unclaimed = unclaimedReason(assignment, now)
  if (unclaimed) return unclaimed
  if (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return null
  // A crew member 3 hours without progress of its own puts its task back in its lane (task #3400), however busy its screen.
  const rules = rulesFor(group.projectId ?? 'lead')
  if (!rules) return null
  if (crewClock(group, worker, assignment, now, rules) === 'return') return returnReason(laneOf(group, rules.lanes), rules)
  const end = leaseEnd(group, assignment, reportRenewedAt(state, worker))
  if (end !== undefined && now > end) {
    const progress = lastProgress(state, worker, assignment)
    return progress === undefined ? 'no progress seen' : `no progress for ${plural(Math.floor((now - progress) / 60_000), 'minute')}`
  }
  return null
}

/** Marks a worker's task lost and fences its agent. The Lead hears who, why, how long since progress and the last result;
 *  the old agent hears that its task moved. Rows are written as the Lead, or as the worker when the project has none. */
function loseTask(state: SuperTabState, group: Conversation, worker: Agent, reason: string, now: number, resumeAt?: string): MessageDraft[] {
  const assignment = group.assignment!
  const resume = resumeAt ? { resumeAt } : {}
  assignment.status = 'lost'
  assignment.lost = { reason, at: now, ...resume }
  group.lostAttempt = { id: assignment.id, agentId: worker.id, machineId: assignment.execution.machineId, engine: assignment.configuration.engine }
  worker.lostTask = { conversationId: group.id, assignmentId: assignment.id, reason, at: now, ...resume }
  const sender = writtenBy(state, leadOf(state, worker) ?? worker)
  const progress = lastProgress(state, worker, assignment)
  const since = progress === undefined ? 'unknown' : `${plural(Math.max(0, Math.floor((now - progress) / 60_000)), 'minute')} ago`
  const result = assignment.result?.replace(/[.\s]+$/, '')
  const pr = group.pullRequestUrls?.at(-1)
  const source = { kind: 'work-lost', agentId: worker.id, assignmentId: assignment.id, reason }
  // A step named for an OS that no free agent of that OS can take waits for one, and says so (task #3926): the dispatch never
  // hands it to another OS, so without these words it would only sit there.
  const os = stepOs(group)
  const waits = os && !stepCandidates(state, group, now).length ? noTesterFree(os) : null
  // What happened, never the next step (project instructions, phase 4): the instructions say what the coordinator does.
  const wake = `${worker.displayName ?? worker.name} lost its task "${group.title}": ${reason}. Last progress ${since}. `
    + `Last result: ${result || 'none'}.${pr && !result?.includes(pr) ? ` Pull request: ${pr}.` : ''}`
    + (resumeAt ? ` It resumes by itself when its limit resets at ${resumeAt.slice(11, 16)} UTC.` : '')
    + (waits ? ` ${waits}: the step waits for one.` : '')
  // Named by the loss, not the task: a task resumed after a usage limit keeps its id and can be lost again (2026-10-28).
  const loss = String(now)
  return [...leadNoticeRows(toLead(state, worker, { id: stableId('work-lost', assignment.id, loss), conversationId: group.id, author: sender, replyTo: null,
    recipients: [], text: wake, source }).map(row => reachable(state, row))),
  reachable(state, { id: stableId('work-lost', assignment.id, loss, 'agent'), conversationId: group.id, author: sender, replyTo: null, recipients: [worker.id], source,
    text: `Your task "${group.title}" moved: ${reason}. Stop working on it; your status and results for it are no longer accepted.` }),
  ...(waits ? [{ id: stableId('work-lost', assignment.id, loss, 'waits'), conversationId: group.id, author: sender, replyTo: null, recipients: [],
    text: `${waits}: this step waits until one is.`, source: { kind: 'system' } }] : []),
  // And its project chat's thread says Stuck, as no command saw the loss (task #2693).
  ...endedReply(state, group, stableId('task-line-lost', assignment.id, loss), sender)]
}

/** Every worker 2 hours without progress hears it once in its task, without waiting for the PM (dispatch.ts crewClock). */
function crewNudges(state: SuperTabState, now: number, rulesFor: DispatchLookup): MessageDraft[] {
  const workers = new Map(state.agents.filter(a => !isBuddy(a)).map(a => [a.id, a]))
  let leaders: Set<string> | undefined, steps: StepIndex | undefined
  return state.conversations.flatMap(group => {
    const assignment = group.assignment, worker = assignment && workers.get(assignment.agentId)
    if (!worker || !activeWork(group)) return []
    const rules = rulesFor(group.projectId ?? 'lead')
    if (!rules) return []
    if (crewClock(group, worker, assignment, now, rules) !== 'nudge') return []
    leaders ??= new Set(state.conversations.flatMap(c => c.leadId ? [c.leadId] : []))
    if (leaders.has(worker.id)) return []
    steps ??= stepIndex(state)
    // Waiting on others is no lack of progress: the waits that stop a loss stop the line too (lostReason).
    if (waitingForReview(assignment) || waitingForRevision(state, group) || waitingOnSteps(state, group, steps) || waitingOnPerson(state, group, worker, assignment)) return []
    assignment.nudgedAt = now
    return [reachable(state, { id: stableId('crew-nudge', assignment.id, String(now)), conversationId: group.id, author: writtenBy(state, leadOf(state, worker) ?? worker),
      replyTo: null, recipients: [worker.id], text: nudgeLine(laneOf(group, rules.lanes), rules), source: { kind: 'crew-nudge', assignmentId: assignment.id } })]
  })
}

/** Loses at once the tasks of the workers `which` picks that have a reason now: an agent that just reported a usage limit,
 *  the agents of a machine that just reported. A task lost to that limit resumes at `resumeAt` when its screen said when the
 *  limit resets (the host types into the same session then, cli superTabs/limitResume.ts). */
export function loseTasks(state: SuperTabState, now: number, which: (worker: Agent) => boolean = () => true, resumeAt?: string, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
  const steps = stepIndex(state)
  return workerTasks(state).filter(t => which(t.worker)).flatMap(({ group, assignment, worker }) => {
    // A step that ended with no write to its task, or was lost earlier in this same pass, ends its Engineer's wait first.
    stepsEnded(state, group, now, steps)
    const reason = lostReason(state, group, worker, assignment, now, steps, rulesFor)
    return reason ? loseTask(state, group, worker, reason, now, resumeAt && reason === limitReason(worker, now) ? resumeAt : undefined) : []
  })
}

/** The machine parts a loss was judged from (offline, stopped, its reports' renewals), and those a start failed since
 *  `before` was judged from (its own machine's preparing report). The write touches them, so a fresh report committed since
 *  the read makes it retry on current data instead of fencing a live worker or failing a start still being prepared. */
export function judgedMachines(before: SuperTabState, state: SuperTabState, rows: MessageDraft[]): Array<{ kind: 'machine'; key: string }> {
  const lost = new Set(rows.flatMap(r => r.source?.kind === 'work-lost' ? [r.source.agentId as string] : []))
  const failed = (state.starts ?? []).filter(s => s.error && !before.starts?.find(b => b.id === s.id)?.error).map(s => s.request.machineId)
  const machines = new Set([...state.agents.filter(a => lost.has(a.id)).map(a => a.machineId), ...failed])
  return [...machines].filter(id => state.machines?.some(m => m.machineId === id)).map(key => ({ kind: 'machine' as const, key }))
}

/** A Buddy chat has no Lead: its owner reads why their Buddy did not start, written as theirs and sent to no one. */
function buddyNotice(state: SuperTabState, start: AgentStart): MessageDraft[] {
  const owner = state.people.find(p => p.id === start.request.buddyOf!.personId && p.generation === start.request.buddyOf!.generation)
  if (!owner || !state.conversations.some(c => c.id === start.request.conversationId)) return []
  return [{ id: stableId('start-timeout', start.id), conversationId: start.request.conversationId, replyTo: null, recipients: [],
    author: { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation },
    // Their own Buddy on a machine of the Swarm: the reason names only that machine, so its owner reads it whole.
    text: `Could not start ${start.request.name}: ${start.error!}`, source: { kind: 'start-timeout', startId: start.id } }]
}

/** A Product Manager's start that stopped trying ([text], leadStart.ts), said once as a system row of its project's
 *  conversation, written under the person who asked for it. Nothing while
 *  it still waits for a machine. */
function leadNotice(state: SuperTabState, start: AgentStart, text: string | null): MessageDraft[] {
  const asker = start.request.leadFor!
  const person = state.people.find(p => p.id === asker.personId && p.generation === asker.generation)
  if (!text || !person || !state.conversations.some(c => c.id === start.request.conversationId)) return []
  return [{ id: stableId('start-timeout', start.id), conversationId: start.request.conversationId, replyTo: null, recipients: [],
    author: { kind: 'person', id: person.id, name: person.email, membershipGeneration: person.generation },
    text, source: { kind: 'system' } }]
}

/** The time checks, run on the Lead's poll and on any machine's report: every worker task with a reason is lost, and
 *  every start dispatched over 3 minutes ago that is not running fails, unless its machine is still preparing it. */
export function sweepLiveness(state: SuperTabState, now: number, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
  const drafts = [...loseTasks(state, now, undefined, undefined, rulesFor), ...crewNudges(state, now, rulesFor), ...failStalledStarts(state, now), ...unpurged(state, now), ...staleSwitches(state, now), ...staleModelRequests(state, now),
    // A lost task whose own merge is recorded is done, never handed out again (mergedTasks.ts, task #4032); written as its PM.
    ...closeMergedLost(state, now, task => {
      const pm = projectChatOf(state, task)?.leadId, writer = state.agents.find(a => a.id === pm)
      return writer ? writtenBy(state, writer) : null
    })]
  // A Buddy start that timed out may have been the last on its Buddy-only machine (security review 1 of #2234).
  dropIdleBuddyMachines(state, now)
  return drafts
}

/** How long a removed confidential session's data may take to be deleted in its Team account before the Swarm says so. */
export const PURGE_NOTICE_MS = 15 * 60_000

/** What its project's conversation hears of a removed confidential session [unpurged] still holds on [machine]. */
export const unpurgedNotice = (machine: string) =>
  `The saved session of a removed agent that held people's private chats, on ${machine}, is not deleted yet, so its Harness Team account takes no other project's work until it is.`

/** A removed confidential session whose host has not confirmed its data deleted (commands.ts removeAgent `heldFor`): its
 *  Team account keeps serving only its project, and its project's conversation hears once, or the Swarm's first one when
 *  its project went with it. Its host keeps trying (cli superTabs/host.ts endSession). */
function unpurged(state: SuperTabState, now: number): MessageDraft[] {
  const owner = state.people.find(p => p.id === state.ownerId)
  return (state.closingSessions ?? []).flatMap(closing => {
    if (!closing.heldFor || closing.noticed || closing.since === undefined || now - closing.since <= PURGE_NOTICE_MS || !owner) return []
    closing.noticed = true
    const project = projectsOf(state).find(p => p.id === closing.heldFor) ?? projectsOf(state)[0]
    if (!project || !state.conversations.some(c => c.id === project.leadConversationId)) return []
    // Its source names the machine, so a Buddy reading this conversation reads it without (store.ts withoutMachineNames).
    const machine = state.machines?.find(m => m.machineId === closing.machineId)?.name
    return [{ id: stableId('unpurged', closing.agentId, closing.harnessId), conversationId: project.leadConversationId, replyTo: null, recipients: [],
      author: { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation },
      text: unpurgedNotice(machine ?? machineName(state, closing.machineId)), source: machine ? { kind: 'system', machine } : { kind: 'system' } }]
  })
}

/** The Lead's own time checks: those above, then each task's state, waking the Lead for those that just stalled. Only the
 *  Lead's poll runs them, where the whole active Swarm is loaded and the one they wake is listening: a machine's reading
 *  loads only running work and must write no group (read/host.ts). */
export function sweepForLead(state: SuperTabState, now: number, rulesFor: DispatchLookup = () => DISPATCH_RULES): MessageDraft[] {
  // Each task's status line before the sweep moves any (statusCard.ts): only the lines it moves are written.
  const before = linesOf(state, now)
  const drafts = [...sweepLiveness(state, now, rulesFor), ...recordTaskStates(state, now)]
  // Where the whole active Swarm is loaded, as for a command: a task lost here may leave Working at 0 (pulse.ts).
  recordPulse(state, now, undefined, before)
  return drafts
}

/** A task whose agent has reported nothing itself (a status, check or post) this long is quiet, and its Lead is woken to act
 *  (Ken, 2026-10-29). Its screen may still be changing: a session whose screen stays still this long loses its task. */
export const TASK_QUIET_MS = 30 * 60_000
/** A start for a task still not launched this long after it was asked for, and after the Lead last acted on the task, leaves
 *  the task orphaned: its Lead's machine never found room for it. */
export const START_PICKUP_MS = 10 * 60_000

const FINISHED_WORK = ['done', 'cancelled', 'stopped']

/** A task in review waits while one of its linked tasks (reviewOf it) is open. With none open, nothing opens a review by itself
 *  (project instructions, phase 4), so after TASK_QUIET_MS from its last progress, or from when its last linked task ended, it
 *  is quiet and its coordinator hears once (final review of the branch). Only loaded linked tasks count: an archived one ended. */
function reviewWait(group: Conversation, progress: number, now: number, steps: StepIndex): TaskLiveness {
  const linked = steps.get(group.id) ?? []
  const ended = (c: Conversation) => c.archived || (!!c.assignment && FINISHED_WORK.includes(c.assignment.status))
  if (linked.some(c => !ended(c))) return { state: 'waiting', why: 'review', since: progress }
  const since = Math.max(progress, ...linked.map(c => (c.lastActivityAt && Date.parse(c.lastActivityAt)) || 0))
  return { state: now - since >= TASK_QUIET_MS ? 'quiet' : 'waiting', why: 'review', since }
}

/** The state of a project task now, from what is loaded (never a further read), or null while it is working (its agent
 *  reported in the last 30 minutes) and for anything that is not a task: a Lead or Leads conversation, a private chat (it
 *  never holds work), an archived group, finished work, or none yet. */
export function taskLiveness(state: SuperTabState, group: Conversation, now: number, steps: StepIndex = stepIndex(state)): TaskLiveness | null {
  if (group.kind || group.audience || group.archived || projectsOf(state).some(p => p.leadConversationId === group.id)) return null
  if (!projectsOf(state).some(p => p.id === (group.projectId ?? 'lead'))) return null
  const assignment = group.assignment
  if (assignment && activeWork(group)) {
    const worker = state.agents.find(a => a.id === assignment.agentId)
    if (worker && ledProject(state, worker.id)) return null
    if (!worker || assignment.status === 'reconciling') return { state: 'orphaned', why: 'removed', since: now }
    const progress = assignment.progressAt ?? (group.lastActivityAt ? Date.parse(group.lastActivityAt) : now)
    if (assignment.status === 'needs_human') {
      // The person its agent asked, else whom the work waits on by default (its requester, else the project's owner).
      const asked = assignment.askedOf && state.people.some(p => p.id === assignment.askedOf) ? assignment.askedOf : undefined
      return { state: 'waiting', why: 'person', personId: asked ?? waitedOn(state, group), since: group.ledger?.waiting?.since ?? progress }
    }
    // A step in Ready is the review itself: it waits on its task's owner to act on its verdict, never on a review of its own.
    if (assignment.status === 'review' && isStep(group)) return { state: 'waiting', why: 'review', since: progress }
    if (assignment.status === 'review') return reviewWait(group, progress, now, steps)
    if (assignment.status === 'blocked') return { state: 'waiting', why: 'blocked', since: progress }
    // A review whose verdict asked for changes waits for the new revision; once it is ready, its quiet time runs from then
    // (revisionReady restarts its progress).
    if (waitingForRevision(state, group)) return { state: 'waiting', why: 'revision', since: progress }
    if (waitingOnSteps(state, group, steps)) return { state: 'waiting', why: 'review', since: progress }
    return now - progress >= TASK_QUIET_MS ? { state: 'quiet', why: 'silent', since: progress } : null
  }
  // Only unfinished starts are loaded, with those that ended in this same write.
  const start = state.starts?.findLast(s => s.request.conversationId === group.id && !s.request.buddyOf)
  if (start && !start.harnessId && !start.error) {
    if (start.dispatched) return { state: 'waiting', why: 'starting', since: start.dispatchedAt ?? now }
    // A start from before requestedAt runs from when it was first recorded queued.
    const recorded = group.liveness?.why === 'queued' || group.liveness?.why === 'unstarted' ? group.liveness.since : now
    const asked = start.requestedAt ?? recorded
    const stale = now - Math.max(asked, group.leadAction?.at ?? 0) >= START_PICKUP_MS
    return { state: stale ? 'orphaned' : 'waiting', why: stale ? 'unstarted' : 'queued', since: asked }
  }
  if (assignment && FINISHED_WORK.includes(assignment.status)) return null
  if (start?.error && !start.harnessId) return { state: 'orphaned', why: 'start-failed', since: now }
  if (assignment?.status === 'lost') return { state: 'orphaned', why: 'lost', since: assignment.lost?.at ?? now }
  return null
}

const FINISHED_OR_ARCHIVED = (group: Conversation) => group.archived || (!!group.assignment && FINISHED_WORK.includes(group.assignment.status))

/** What a task's record becomes: its state now. A task whose start failed stays orphaned until it has work again, since
 *  that start is no longer loaded once it ended; nothing else outlives what made it. */
const nextState = (state: SuperTabState, group: Conversation, now: number, steps?: StepIndex) => taskLiveness(state, group, now, steps)
  ?? (group.liveness?.why === 'start-failed' && !activeWork(group) && !FINISHED_OR_ARCHIVED(group) ? group.liveness : undefined)

/** Records the state of the task a command changed, in that command's own write, so the time checks find nothing to rewrite
 *  (a machine's reading must write no group, read/host.ts). A stall is left to the time checks, which wake the Lead for it;
 *  a failed start is not, since its own notice told the Lead and the next sweep no longer loads it. */
export function recordTaskState(state: SuperTabState, group: Conversation, now: number): void {
  // A step's change is its task's too: the Engineer waits on it from its start and gets its time back when it ends.
  const task = isStep(group) ? state.conversations.find(c => c.id === group.reviewOf) : undefined
  if (task) {
    stepsEnded(state, task, now)
    recordTaskState(state, task, now)
  }
  const next = nextState(state, group, now)
  if (sameState(group.liveness, next) || (next && next.state !== 'waiting' && next.why !== 'start-failed')) return
  if (next) group.liveness = next
  else delete group.liveness
}

/** A new question, review or blocker moves a wait's start; any other `since` is kept as first recorded, so a sweep never
 *  rewrites a group just because its clock moved. */
const sameState = (a: TaskLiveness | undefined, b: TaskLiveness | undefined) => a?.state === b?.state && a?.why === b?.why
  && a?.personId === b?.personId && (a?.state !== 'waiting' || a.why === 'queued' || a.why === 'starting' || a.since === b?.since)

function stalledLine(state: SuperTabState, group: Conversation, liveness: TaskLiveness, now: number): string {
  const task = `${group.number ? `#${group.number} ` : ''}"${group.title}"`
  const worker = state.agents.find(a => a.id === group.assignment?.agentId)
  const minutes = plural(Math.max(0, Math.floor((now - liveness.since) / 60_000)), 'minute')
  const why = liveness.why === 'silent' ? `quiet, ${worker?.displayName ?? worker?.name ?? 'its agent'} has reported nothing for ${minutes}`
    : liveness.why === 'review' ? `waited for review for ${minutes}; no review task is open`
    : liveness.why === 'removed' ? 'orphaned, its agent was removed from the Swarm' : `orphaned, its agent has not started for ${minutes}`
  return `- ${task}: ${why}.`
}

/** Records each task's state where it changed, so readers see it, and wakes each project's Lead once, in its chat, for the
 *  tasks that just turned quiet or orphaned. A task lost or whose start failed has had its own notice already. The record
 *  is the deduplication: a sweep on another server writes the same group, so one of the two retries and finds it recorded.
 *  A stall is recorded only with a wake that reaches its Lead: a project with none yet is told once it has one. A working
 *  task has no record, so a steady Swarm's sweeps write nothing. */
function recordTaskStates(state: SuperTabState, now: number): MessageDraft[] {
  const stalled = new Map<string, Array<{ group: Conversation; next: TaskLiveness }>>()
  const steps = stepIndex(state)
  for (const group of state.conversations) {
    // A step lost earlier in this pass, after loseTasks passed its task, ends its Engineer's wait before the task is judged,
    // as a command's write does (recordTaskState): else the Engineer reads as stalled and loses its task the next sweep.
    stepsEnded(state, group, now, steps)
    const before = group.liveness
    const next = nextState(state, group, now, steps)
    if (sameState(before, next)) continue
    if (next && (next.state === 'quiet' || next.state === 'orphaned') && before?.state !== next.state && next.why !== 'lost' && next.why !== 'start-failed') {
      const projectId = group.projectId ?? 'lead'
      stalled.set(projectId, [...stalled.get(projectId) ?? [], { group, next }])
      continue
    }
    if (next) group.liveness = next
    else delete group.liveness
  }
  return [...stalled].flatMap(([projectId, tasks]) => {
    const chat = state.conversations.find(c => c.id === projectsOf(state).find(p => p.id === projectId)!.leadConversationId)
    const lead = chat?.leadId ? state.agents.find(a => a.id === chat.leadId) : undefined
    if (!chat || !lead) return []
    const one = tasks.length === 1
    const text = `${one ? 'A task is' : `${tasks.length} tasks are`} stalled:\n${tasks.map(t => stalledLine(state, t.group, t.next, now)).join('\n')}`
    const row = reachable(state, { id: stableId('work-stalled', state.id, projectId, String(now)), conversationId: chat.id, author: writtenBy(state, lead), replyTo: null,
      recipients: chat.agentIds.includes(lead.id) ? [lead.id] : [], text,
      source: { kind: 'work-stalled', tasks: tasks.map(t => ({ conversationId: t.group.id, state: t.next.state, why: t.next.why })) } })
    if (!row.recipients.length) return []
    for (const t of tasks) t.group.liveness = t.next
    return [row]
  })
}

/** A Buddy's start its machine has not taken this long after it was asked for, while that machine reports, has failed: a
 *  host from before Buddies never sees one (read/hostRows.ts). */
export const BUDDY_PICKUP_MS = 5 * 60_000

function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {
  return (state.starts ?? []).flatMap(start => {
    if ((start.request.buddyOf || start.request.leadFor) && !start.dispatched && !start.harnessId && !start.error && start.requestedAt !== undefined
      && now - start.requestedAt > BUDDY_PICKUP_MS) {
      const report = state.machines?.find(m => m.machineId === start.request.machineId)?.observation
      if (!report || now - report.receivedAt > MACHINE_FRESH_MS) return []
      if (start.request.leadFor) {
        start.error = `${machineName(state, start.request.machineId)}${leadPickupSuffix(start.request.name)}`
        return leadNotice(state, start, leadStartFailed(state, start, start.error))
      }
      start.error = start.request.buddySession ? `${machineName(state, start.request.machineId)} did not start this session.`
        : `${machineName(state, start.request.machineId)} did not start this Buddy. Update Harness on it, then add the Buddy again.`
      // A thread session's start ends through its own path: its thread says why, never the main chat (buddySessions.ts).
      return start.request.buddySession ? failedSessionStart(state, start) : buddyNotice(state, start)
    }
    if (!start.dispatched || start.harnessId || start.error || start.dispatchedAt === undefined || now - start.dispatchedAt <= START_RUN_MS) return []
    // Only its own machine's report can say it is preparing; one before preparingStartIds never does, so its starts get 3 minutes.
    const report = state.machines?.find(m => m.machineId === start.request.machineId)?.observation
    const named = !!report?.preparingStartIds?.includes(start.id)
    const silent = !!report && now - report.receivedAt > MACHINE_FRESH_MS
    if (named && !silent && now - start.dispatchedAt <= START_PREPARE_MS) return []
    const machine = machineName(state, start.request.machineId)
    start.error = `${machine}${!named ? TIMED_OUT_SUFFIX : silent ? STOPPED_REPORTING_SUFFIX : STILL_PREPARING_SUFFIX}`
    // Counted as a host's failure is (commands.ts agent.startFailed); a pickup timeout suspends the machine, not its engine.
    return failedStartNotices(state, start, now, noteStartFailed(state, start, now))
  })
}

/**
 * Fails at once each start that machine [machineId]'s reading names refused: the server refused that machine's own report for
 * it, so it would otherwise wait out the 3 minutes with the reason in that machine's log alone (task #2441). Only a reading
 * the store took from that machine's own pool names one, and only one of its starts that neither runs nor failed
 * (machines.ts refusableStart). A refusal is no failure of its engine, so it suspends nothing.
 */
export function failRefusedStarts(state: SuperTabState, machineId: string, now: number): MessageDraft[] {
  const refused = state.machines?.find(m => m.machineId === machineId)?.observation?.refusedStarts ?? []
  return refused.flatMap(({ startId, reason }) => {
    const start = state.starts?.find(s => s.id === startId)
    if (!start || start.request.machineId !== machineId || start.harnessId || start.error) return []
    start.error = `${machineName(state, machineId)}${REFUSED_INFIX}${reason}`
    return failedStartNotices(state, start, now, null)
  })
}

/** Who hears that [start] failed, and what they read: its Lead, its Buddy's person, or its task's coordinator and the agent
 *  that made it. [suspended]: the line saying its engine is now suspended there, if this failure suspended it. */
function failedStartNotices(state: SuperTabState, start: AgentStart, now: number, suspended: string | null): MessageDraft[] {
  if (start.request.leadFor) return leadNotice(state, start, leadStartFailed(state, start, start.error!))
  // Never a lookup that throws: these checks run inside every machine's report.
  if (start.request.buddyOf) return start.request.buddySession ? failedSessionStart(state, start) : buddyNotice(state, start)
  const group = state.conversations.find(c => c.id === start.request.conversationId)
  // Recorded in this write: once the start has ended, no later poll loads it.
  if (group) recordTaskState(state, group, now)
  if (!group) return []
  // Told to the coordinator and the agent that made it, with the model it asked for; nothing is started elsewhere (project
  // instructions, phase 4, decision 18).
  const text = `${failureNotice(start.request.name, start.error!, askedModel(start), coordinatorOfGroup(state, group))}${suspended ? `\n\n${suspended}` : ''}`
  const source = { kind: 'start-timeout', startId: start.id }
  const author = failureAuthor(state, start, group)
  if (!author) return []
  const recipients = failureRecipients(start, group)
  const row = reachable(state, { id: stableId('start-timeout', start.id), conversationId: group.id, replyTo: null, recipients,
    author, text, ...(suspended && start.machineOwnerId ? { mentions: [start.machineOwnerId] } : {}), source })
  // A task with no lead, or one its lead left: its coordinator hears it in its own chat.
  const copy = coordinatorCopy(state, group, recipients)
  return copy ? [row, reachable(state, { id: stableId('start-timeout', start.id, 'coordinator'), conversationId: copy.conversationId, replyTo: null,
    recipients: [copy.coordinator], author, text, source: forRecipients(source) })] : [row]
}

/** Who a failed start's notice is written as: its task's lead, else the agent that made the start, else its project's
 *  coordinator, else the Swarm's owner, so it is never left unsaid (final review). Undefined only with none of them. */
function failureAuthor(state: SuperTabState, start: AgentStart, group: Conversation): Author | undefined {
  const maker = start.actorKey?.startsWith('agent:') ? start.actorKey.slice('agent:'.length) : undefined
  const chat = projectChatOf(state, group)
  const writer = [group.leadId, maker, chat?.leadId].map(id => id && state.agents.find(a => a.id === id)).find(a => !!a)
  if (writer) return writtenBy(state, writer)
  const owner = state.people.find(p => p.id === state.ownerId)
  return owner && { kind: 'person', id: owner.id, name: owner.email, membershipGeneration: owner.generation }
}