The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Stuck work is flagged at once to the PM and the people on the task (#3915) (#3431)
harness-for-autonomous[bot]1622ac6359b7
diff --git a/backend/integration/superTabTimeChecks.test.ts b/backend/integration/superTabTimeChecks.test.tsindex 5e423786c..7cac9b2d7 100644--- a/backend/integration/superTabTimeChecks.test.ts+++ b/backend/integration/superTabTimeChecks.test.ts@@ -12,6 +12,7 @@ import type { Command } from '../src/superTabs/commands.js'import type { MachineObservation } from '../src/superTabs/machines.js'import { QUIET_CHECK_MS, runTimeCheckPass, timeCheckSwarms } from '../src/superTabs/timeChecks.js'import { poolRows, rosterRows } from './hostRows.test-support.js'+import { plan, profiled, reads } from './plans.test-support.js'// Task #3385 (anh Dee's Swarm redesign, 11-05): the stall, idle and lost-task follow-ups run in the backend worker, so they// keep running while the PM is down. Before, only the PM's own poll ran them: with the PM hung, five people's asks waited 3 to@@ -129,6 +130,37 @@ describe('the time checks with the PM down', () => {expect((await f.rows('work-lost')).map(r => r.text)).toContainEqual(expect.stringContaining('Worker lost its task "Ship the parser"'))})+ // Task #3915: a task whose agent went down and nobody took tells its PM and its people within the checks' 5 minutes, once,+ // in a line that tags them (their Needs you), and the tag resolves when someone takes it.+ it('flag a task nobody took 10 minutes after its agent went down, once, tagging its requester, and clear it when taken', async () => {+ const f = await swarm()+ await f.workerBeat()+ f.clock.now += 2 * MINUTE + 5_000+ await f.timed.runTimeChecks(f.tab)+ const stuck = async () => (await db.superTabMessage.findMany({ where: { tabId: f.tab, conversationId: f.group }, orderBy: { sequence: 'asc' } }))+ .filter(m => /stuck/i.test(m.text))+ expect(await stuck()).toEqual([])+ f.clock.now += 10 * MINUTE+ await f.timed.runTimeChecks(f.tab)+ f.clock.now += 5 * MINUTE+ await f.timed.runTimeChecks(f.tab)+ const told = await stuck()+ expect(told).toEqual([expect.objectContaining({ recipientIds: [f.lead], text: expect.stringContaining('Worker went down') })])+ const tag = () => db.superTabMention.findMany({ where: { tabId: f.tab, messageId: told[0]!.id } })+ expect(await tag()).toEqual([expect.objectContaining({ personId: owner.sub, conversationId: f.group, resolvedAt: null })])+ const taker = String((await f.execute({ type: 'agent.add', conversationId: f.group, machineId: 'lead-host', harnessId: randomUUID(), name: 'Taker',+ configuration: config, lead: false })).result.agentId)+ await f.execute({ type: 'work.assign', conversationId: f.group, agentId: taker })+ f.clock.now += MINUTE+ // Its tag resolves on the `[tabId, conversationId, personId]` index, examining only that person's tags there (backend AGENTS.md 3).+ const entries = await profiled(db, () => f.timed.runTimeChecks(f.tab))+ expect((await stuck()).map(m => m.text)).toEqual([told[0]!.text, 'No longer stuck: this task has an agent again.'])+ expect(await tag()).toEqual([expect.objectContaining({ resolvedBy: 'fixed' })])+ const resolve = reads(entries, 'SuperTabMention', ['messageId', 'personId'])+ expect(resolve).toHaveLength(1)+ expect(plan(resolve)).toEqual([expect.objectContaining({ plan: expect.stringMatching(/IXSCAN.*conversationId/), docsExamined: 1 })])+ })+it('are no longer run by the PM\'s poll', async () => {const f = await swarm()await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Started' }, host, f.worker)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 3014eddce..d930ed20e 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -25,6 +25,7 @@ import {import { jobKindOf } from './evidence/jobKind.js'import { endSteps, stepEndedRows, isStep, stepName, stepsOf, taskOwner } from './steps.js'import { closeMerged } from './mergedTasks.js'+import { noteWriter } from './stuck.js'import { reviewPlan, stepBrief, stepCheck, refreshStepBrief, type PlannedStep, type StepKind } from './reviewTable.js'import { builtBy, reviewerCandidates, STRENGTH_RULE } from './reviewerPick.js'import { recordCheckVerdict } from './checkVerdicts.js'@@ -4201,6 +4202,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,message(group.id, text, recipients, command.replyTo, command.agentOnly ? { ...AGENT_ONLY, ...command.notice ? { notice: command.notice } : {} } : undefined, attachments, tagged,tagged.length ? command.mentionsIfNoWorker : undefined)if (!command.agentOnly) effects.messages.at(-1)!.post = true+ // Whom a stuck line in a task tags, with its requester (stuck.ts, task #3915).+ if (actor.kind === 'person' && !command.agentOnly && !group.kind && !group.audience && !isProjectChat(state, group)) noteWriter(group, actor.userId)// After the post is marked: the crew need is the server's row for the PM, never a post of its own.if (pmInstead && routedTags.length) {crewNeed(group, pmInstead, { personIds: routedTags, messageId: operationId, conversationId: group.id }, text)diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex 48c1f1317..4df04a523 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -190,6 +190,18 @@ async function bringBackUnfollowed(tx: Tx, tabId: string, messages: MessageDraftif (answer.writeErrors?.length) throw new Error('The database refused some thread follows')}+/** A stuck line fixed, or its task ended (stuck.ts, task #3915): its tags still waiting resolve as `fixed`. One update per person+ * on the `[tabId, conversationId, personId]` index, at most MAX_MENTIONS a line. */+export async function resolveTags(tx: Tx, tabId: string, lines: ReadonlyArray<{ conversationId: string; messageId: string; personIds: readonly string[] }>,+ now: number): Promise<void> {+ for (const line of lines) {+ for (const personId of line.personIds) {+ await tx.superTabMention.updateMany({ where: { tabId, conversationId: line.conversationId, personId, messageId: line.messageId, ...waiting },+ data: { resolvedAt: new Date(now), resolvedBy: 'fixed' } })+ }+ }+}+/** Any post by the tagged person in that conversation answers every earlier tag there, in a thread or not. */export async function resolveByReply(tx: Tx, tabId: string, conversationId: string, personId: string, now: number): Promise<void> {await tx.superTabMention.updateMany({ where: { tabId, conversationId, personId, createdAt: { lte: new Date(now) }, ...waiting },diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex be13834c7..08b59d450 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -449,6 +449,11 @@ export interface Conversation {/** Each linked pull request's check state as the PR watch last read it, `green`, `red` or `running` (pullRequestEvents.ts* checksStateOf, task #3827): what the board's Done cards say. Written only when it changes; absent until the watch reads one. */pullRequestChecks?: Record<string, import('./pullRequestEvents.js').ChecksState>+ /** The people who posted here, newest last, at most four (stuck.ts noteWriter, task #3915): whom a stuck line tags. */+ writers?: string[]+ /** The stuck line this task's people were told, until it is fixed (stuck.ts, task #3915): its reason's key, the line, whom it+ * tagged and what its fix says. */+ stuck?: { key: string; messageId: string; tagged: string[]; fixed: string }/** Its steps and reviews (groups whose reviewOf is this one), newest last, at most 200 (production's most was 14): what a new* pull request head re-derives the checks of, dormant ones included (#3394). Empty from a task's start; absent on a task* from before, whose PR watch looks them up once (pullRequestEvents.ts listedSteps). */diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 6ad1086ca..4e2fb3670 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -88,11 +88,13 @@ const conversation: Required<Conversation> = {step: 'Review',stepIds: [],stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },+ stuck: { key: 'k', messageId: 'm', tagged: [], fixed: 'f' },talkedAt: { w: { person: 1, answer: 2 } },task: { goal: '', changes: '', constraints: '', owns: [] },teamWritten: true,teamWrittenBy: { kind: 'assigned' },title: 't',+ writers: [],}describe('the light conversation projection (parts/light.ts)', () => {diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex 517568dda..089348079 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -110,9 +110,11 @@ export const GROUP_FIELDS = {'step','stepIds','stepUp',+ 'stuck','talkedAt','teamWritten','teamWrittenBy',+ 'writers',],} as constconst LIGHT_GROUP = {diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 0057a5ca5..a1b84a33e 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -126,7 +126,8 @@ import { costRows, failedStarts, summarizeCosts } from './costs/read.js'import { MAX_PROPOSALS, proposalQuestion, proposalTitle, REASK_DAYS, reflectionMessageId, routingReflection, type ReflectionInput } from './costs/reflection.js'import { readEvidence, recordEvidence } from './evidence/store.js'import { closeAssignment, closeUnassignedStart, LIST_SIZE, newestConversations, newestDecisions, readDecision, recentDecisions, recordAttempts, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'-import { answeredAgents, dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByAnswer, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'+import { answeredAgents, dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByAnswer, resolveByReply, resolveTags, resolveWhenWorked, writeMentions } from './mentions.js'+import { stuckAlerts } from './stuck.js'import { OVERDUE_PER_PASS, overdueDecisions, dueDefaultDecisions } from './overdueDecisions.js'import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingConversations, waitingFor, waitingInProject, withdrawIn, workEnded, workOver, writeDecisions } from './decisions.js'import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'@@ -5558,6 +5559,9 @@ export class SuperTabStore {select: { agentId: true }, distinct: ['agentId'] })).map(d => d.agentId))for (const project of projects) written.push(...idleNotices(state, project.id, now, busy))}+ // Stuck work, told once to its PM and its people in a line that tags them, and cleared when fixed (stuck.ts, task #3915).+ const stuck = stuckAlerts(state, now)+ written.push(...stuck.rows)// What each PM owes people, for its host's watchdog: written only when it changes, so a steady Swarm writes nothing. A// project that lost its PM owes nothing until it has one again (review of #3213, Minor 4).for (const project of projectsOf(state)) {@@ -5575,6 +5579,10 @@ export class SuperTabStore {// A loss or a start's failure was judged from a machine's report: a newer report makes this write retry.await this.save(tx, loaded, state, clock.next(), judgedMachines(loaded.state, state, written))await this.writeMessages(tx, tabId, state, written, sequences, true)+ // Its tags put the line in their Needs you and on their phones; a fixed line's tags resolve.+ const tags = await writeMentions(tx, tabId, state, stuck.rows, now)+ await resolveTags(tx, tabId, stuck.resolved, now)+ this.tellPhones(tx, tabId, state, { replies: [], tags }, stuck.rows)return written.length})}diff --git a/backend/src/superTabs/stuck.test.ts b/backend/src/superTabs/stuck.test.tsnew file mode 100644index 000000000..4bbfdb202--- /dev/null+++ b/backend/src/superTabs/stuck.test.ts@@ -0,0 +1,190 @@+/**+ * Stuck work is flagged at once to the PM and the people on the task (task #3915, Tony 11-06: #3821 sat with red checks and a+ * lost Test step, and nobody told him).+ */+import { describe, expect, it } from 'vitest'+import { applyCommand, type Command, type CommandContext } from './commands.js'+import { createSuperTab, type Actor, type SuperTabState } from './model.js'+import { stuckAlerts, STUCK_DOWN_MS } from './stuck.js'++const PR = 'https://github.com/acme/app/pull/7'+const HEAD = 'abc1234def5678abc1234def5678abc1234def56'+const NOW = 10_000_000+const person = (userId: string): Actor => ({ kind: 'person', userId, email: `${userId}@example.com` })++const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }++/** A public project App with its PM and a worker, and people p (its owner), c and d (as boardRights.test.ts). */+function swarm() {+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: '[email protected]' }, 'test')+ state.people.push({ id: 'p', email: '[email protected]', role: 'collaborator', generation: 'p1' },+ { id: 'c', email: '[email protected]', role: 'collaborator', generation: 'c1' },+ { id: 'd', email: '[email protected]', role: 'collaborator', generation: 'd1' })+ let next = 0+ const run = (command: Command, actor: Actor = person('p'), context: Partial<CommandContext> = {}) => {+ const effect = applyCommand(state, actor, command, { operationId: `op${next++}`, now: NOW,+ contribution: { machineOwnerId: 'p', contributorId: actor.kind === 'person' ? actor.userId : 'p' }, ...context })+ state = effect.state+ return effect.result as Record<string, unknown>+ }+ const app = run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' } as Command) as { projectId: string; conversationId: string }+ const add = (harnessId: string, lead: boolean) => run({ type: 'agent.add', conversationId: app.conversationId, harnessId, machineId: 'machine',+ name: harnessId, lead, configuration } as Command).agentId as string+ const pm = add('pm', true), worker = add('worker', false)+ const asAgent = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'p' })+ return { run, app, pm, worker, add, asAgent, get state(): SuperTabState { return state } }+}++/** A task in App that d asked for, built by the worker. */+function fixture() {+ const f = swarm()+ const task = f.run({ type: 'conversation.create', projectId: f.app.projectId, title: 'Fix the host', brief: 'The host restarts.',+ checks: [{ description: 'Restarts', independent: true }], priority: 'P2', requesterId: 'd' } as Command, f.asAgent(f.pm)).conversationId as string+ f.run({ type: 'work.assign', conversationId: task, agentId: f.worker } as Command, f.asAgent(f.pm))+ const group = (id = task) => f.state.conversations.find(c => c.id === id)!+ const post = (actor: Actor, text: string, id = task) => f.run({ type: 'message.send', conversationId: id, text, replyTo: null, recipientIds: [] } as Command, actor)+ return { run: f.run, app: f.app, pm: f.pm, worker: f.worker, add: f.add, asAgent: f.asAgent, task, group, post, get state() { return f.state } }+}++describe('who wrote in a task', () => {+ it('records the people who post there, newest last, at most four, and no agent', () => {+ const f = fixture()+ f.state.people.push({ id: 'e', email: '[email protected]', role: 'collaborator', generation: 'e1' })+ f.post(person('c'), 'Any news?')+ f.post(person('d'), 'It still fails for me.')+ f.post(person('owner'), 'Looking.')+ f.post(person('e'), 'Same here.')+ f.post(person('c'), 'Still?')+ f.post(person('p'), 'On it.')+ f.post(f.asAgent(f.worker), 'Pushed a fix.')+ expect(f.group().writers).toEqual(['owner', 'e', 'c', 'p'])+ })+})++describe('a stuck task', () => {+ const lines = (rows: ReturnType<typeof stuckAlerts>['rows'], conversationId: string) => rows.filter(r => r.conversationId === conversationId)++ it('with red checks at its head while its Engineer says review, tells the PM and its people once, and clears when green', () => {+ const f = fixture()+ f.post(person('c'), 'Is this ready?')+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group().assignment!.id, status: 'review', result: `Ready: ${PR}` } as Command, f.asAgent(f.worker))+ const g = f.group()+ // As the PR watch sees it: the task links its pull request, read at its head with a check failed.+ g.pullRequestUrls = [PR]+ g.codePullRequestUrls = [PR]+ g.pullRequestHeads = { [PR]: { head: HEAD, patch: null, at: NOW } }+ g.pullRequestChecks = { [PR]: 'red' }+ const first = stuckAlerts(f.state, NOW)+ const told = lines(first.rows, f.task)+ expect(told).toHaveLength(1)+ expect(told[0]!.recipients).toEqual([f.pm])+ expect(told[0]!.author.id).toBe(f.pm)+ expect([...told[0]!.mentions!].sort()).toEqual(['c', 'd'])+ expect(told[0]!.text).toContain('checks are red on PR #7 at abc1234')+ // Every later pass says nothing while it stays red.+ expect(stuckAlerts(f.state, NOW + 60_000).rows).toEqual([])+ f.group().pullRequestChecks = { [PR]: 'green' }+ const fixed = stuckAlerts(f.state, NOW + 120_000)+ expect(lines(fixed.rows, f.task)).toEqual([expect.objectContaining({ text: expect.stringContaining('No longer stuck'), recipients: [f.pm] })])+ expect(lines(fixed.rows, f.task)[0]!.mentions ?? []).toEqual([])+ expect(fixed.resolved).toEqual([{ conversationId: f.task, messageId: told[0]!.id, personIds: told[0]!.mentions }])+ expect(f.group().stuck).toBeUndefined()+ expect(stuckAlerts(f.state, NOW + 180_000).rows).toEqual([])+ })++ // Review of #3431: a task links other tasks' pull requests too (its brief, a result); only its own code's checks count.+ it('reads only its own code pull request, never another task\'s it links', () => {+ const f = fixture()+ const OTHER = 'https://github.com/acme/app/pull/9'+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group().assignment!.id, status: 'review', result: `Ready: ${PR}` } as Command, f.asAgent(f.worker))+ const g = f.group()+ g.pullRequestUrls = [PR, OTHER]+ g.codePullRequestUrls = [PR]+ g.pullRequestChecks = { [PR]: 'green', [OTHER]: 'red' }+ expect(stuckAlerts(f.state, NOW).rows).toEqual([])+ f.group().pullRequestChecks = { [PR]: 'red', [OTHER]: 'green' }+ expect(stuckAlerts(f.state, NOW + 60_000).rows).toEqual([expect.objectContaining({ text: expect.stringContaining('checks are red on PR #7') })])+ })++ // Security review 1 of #3431: a reason that clears and comes back with the same key (CI red, green on a re-run, red again at the+ // same head) is a new line with new tags; reusing the first line's id made its tags' ids collide and stopped the time checks.+ it('told again when the same reason comes back after its fix, in a new line with its own id', () => {+ const f = fixture()+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group().assignment!.id, status: 'review', result: `Ready: ${PR}` } as Command, f.asAgent(f.worker))+ const g = f.group()+ g.pullRequestUrls = [PR]+ g.codePullRequestUrls = [PR]+ g.pullRequestHeads = { [PR]: { head: HEAD, patch: null, at: NOW } }+ const checks = (state: 'red' | 'green') => { f.group().pullRequestChecks = { [PR]: state } }+ checks('red')+ const first = lines(stuckAlerts(f.state, NOW).rows, f.task)+ checks('green')+ const fixed = lines(stuckAlerts(f.state, NOW + 60_000).rows, f.task)+ checks('red')+ const again = lines(stuckAlerts(f.state, NOW + 120_000).rows, f.task)+ expect(again).toHaveLength(1)+ expect(again[0]!.mentions).toEqual(['d'])+ expect(again[0]!.id).not.toBe(first[0]!.id)+ checks('green')+ const fixedAgain = lines(stuckAlerts(f.state, NOW + 180_000).rows, f.task)+ expect(fixedAgain).toHaveLength(1)+ expect(fixedAgain[0]!.id).not.toBe(fixed[0]!.id)+ })++ it('with red checks while its Engineer is still working, says nothing', () => {+ const f = fixture()+ f.group().pullRequestUrls = [PR]+ f.group().codePullRequestUrls = [PR]+ f.group().pullRequestChecks = { [PR]: 'red' }+ expect(stuckAlerts(f.state, NOW).rows).toEqual([])+ })++ it('whose step lost its Tester, says so once, and clears when someone takes the step', () => {+ const f = fixture()+ const tester = f.add('tst', false), other = f.add('tst2', false)+ const step = f.run({ type: 'conversation.create', title: 'Test', brief: 'Test it.', reviewOf: f.task, step: 'Test',+ checks: [{ description: 'Runs.', independent: true }] } as Command, f.asAgent(f.pm)).conversationId as string+ f.run({ type: 'work.assign', conversationId: step, agentId: tester } as Command, f.asAgent(f.pm))+ const held = f.group(step).assignment!+ held.status = 'lost'+ held.lost = { reason: 'its machine went offline', at: NOW }+ const told = lines(stuckAlerts(f.state, NOW).rows, f.task)+ expect(told).toHaveLength(1)+ expect(told[0]!.text).toContain('the Test step lost its agent')+ expect(told[0]!.mentions).toEqual(['d'])+ expect(stuckAlerts(f.state, NOW + 60_000).rows).toEqual([])+ f.run({ type: 'work.assign', conversationId: step, agentId: other } as Command, f.asAgent(f.pm))+ const fixed = stuckAlerts(f.state, NOW + 120_000)+ expect(lines(fixed.rows, f.task)).toEqual([expect.objectContaining({ text: expect.stringContaining('No longer stuck') })])+ expect(fixed.resolved).toHaveLength(1)+ })++ it('whose agent went down, says so only once nobody has taken it for 10 minutes, and clears when someone does', () => {+ const f = fixture()+ const held = f.group().assignment!+ held.status = 'lost'+ held.lost = { reason: 'its machine went offline', at: NOW }+ expect(stuckAlerts(f.state, NOW + STUCK_DOWN_MS - 60_000).rows).toEqual([])+ const told = lines(stuckAlerts(f.state, NOW + STUCK_DOWN_MS).rows, f.task)+ expect(told).toHaveLength(1)+ expect(told[0]!.text).toContain('worker went down 10 minutes ago and nobody has taken this task')+ expect(told[0]!.recipients).toEqual([f.pm])+ expect(told[0]!.mentions).toEqual(['d'])+ expect(stuckAlerts(f.state, NOW + STUCK_DOWN_MS + 60_000).rows).toEqual([])+ f.run({ type: 'work.assign', conversationId: f.task, agentId: f.worker } as Command, f.asAgent(f.pm))+ const fixed = stuckAlerts(f.state, NOW + STUCK_DOWN_MS + 120_000)+ expect(lines(fixed.rows, f.task)).toEqual([expect.objectContaining({ text: expect.stringContaining('No longer stuck') })])+ })++ it('that is cancelled while flagged, has its tags resolved and no line', () => {+ const f = fixture()+ const held = f.group().assignment!+ held.status = 'lost'+ held.lost = { reason: 'its machine went offline', at: NOW }+ const told = lines(stuckAlerts(f.state, NOW + STUCK_DOWN_MS).rows, f.task)+ f.group().assignment!.status = 'cancelled'+ const ended = stuckAlerts(f.state, NOW + STUCK_DOWN_MS + 60_000)+ expect(ended.rows).toEqual([])+ expect(ended.resolved).toEqual([{ conversationId: f.task, messageId: told[0]!.id, personIds: ['d'] }])+ })+})diff --git a/backend/src/superTabs/stuck.ts b/backend/src/superTabs/stuck.tsnew file mode 100644index 000000000..63dee2b92--- /dev/null+++ b/backend/src/superTabs/stuck.ts@@ -0,0 +1,123 @@+/**+ * Stuck work is flagged at once to the PM and the people on the task (task #3915, Tony 11-06: #3821 sat with red checks and a+ * lost Test step, and nobody told him; the same day Mac 3's terminal stopped and Engineers and Testers were down for an hour+ * with only scattered "could not start" notices). A task is stuck when its agent went down and nobody took it for+ * STUCK_DOWN_MS, when one of its steps lost its agent or its agent could not start, or when its pull request's checks are red+ * at its head while its Engineer says review or done. The time checks (store.ts runTimeChecks, every Swarm at least every 5+ * minutes) tell each change once, in one line in the task, written as its PM to its PM and tagging its people, so it is in+ * their Needs you; when it is fixed one line says so and the tags resolve. The record on the task is the deduplication.+ */+import { agentDisplayName } from './agentNames.js'+import { isBuddyChat } from './buddies.js'+import { MAX_MENTIONS } from './mentions.js'+import { codePullRequests, isLeads, stableId, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { canReadGroup, projectsOf } from './projects.js'+import { stepName, stepsOf } from './steps.js'++/** How long a task whose agent went down waits for a taker before its people hear it. */+export const STUCK_DOWN_MS = 10 * 60_000+/** The people a task keeps as its writers (Conversation.writers): with its requester, at most MAX_MENTIONS. */+const WRITERS_KEPT = MAX_MENTIONS - 1++/** [personId] posted in [group]: its writers, newest last, at most WRITERS_KEPT. */+export function noteWriter(group: Conversation, personId: string): void {+ const writers = group.writers ?? []+ if (writers.at(-1) === personId) return+ group.writers = [...writers.filter(id => id !== personId), personId].slice(-WRITERS_KEPT)+}++/** Why a task is stuck now: the key that names this reason (a new key is a new line), what its line says and what its fix says. */+interface Stuck { key: string; text: string; fixed: string }++const short = (sha: string) => sha.slice(0, 7)+const minutes = (ms: number) => { const n = Math.max(0, Math.floor(ms / 60_000)); return `${n} minute${n === 1 ? '' : 's'}` }+const prName = (url: string) => { const n = url.match(/\/pull\/(\d+)/)?.[1]; return n ? `PR #${n}` : url }++/** The first reason [task] is stuck at [now], or null: its own agent down, then a step, then red checks. */+export function stuckOf(state: SuperTabState, task: Conversation, now: number): Stuck | null {+ const assignment = task.assignment+ if (!assignment) return null+ if (assignment.status === 'lost') {+ const since = assignment.lost?.at ?? now+ if (now - since < STUCK_DOWN_MS) return null+ const who = agentDisplayName(state.agents, assignment.agentId) ?? 'Its agent'+ return { key: `down:${assignment.id}`, text: `Stuck: ${who} went down ${minutes(now - since)} ago and nobody has taken this task.`,+ fixed: 'this task has an agent again' }+ }+ for (const step of stepsOf(state, task.id)) {+ if (step.archived || !step.assignment) continue+ const name = stepName(step)+ if (step.assignment.status === 'lost') {+ return { key: `step:${step.assignment.id}`, text: `Stuck: the ${name} step lost its agent and nobody has taken it.`, fixed: `the ${name} step has an agent again` }+ }+ if (step.liveness?.why === 'start-failed') {+ return { key: `start:${step.id}:${step.assignment.id}`, text: `Stuck: the ${name} step's agent could not start again.`, fixed: `the ${name} step has an agent again` }+ }+ }+ // Red at its head while its Engineer says it is ready: in review or done, or reopened by that red and not picked up yet. Only its+ // own code's newest pull request: a task also links others' that its brief or a result names (review of #3431).+ const url = codePullRequests(task).at(-1)+ const ready = assignment.status === 'review' || assignment.status === 'done' || !!assignment.reopened+ if (url && ready && task.pullRequestChecks?.[url] === 'red') {+ const head = task.pullRequestHeads?.[url]?.head+ const says = assignment.status === 'done' ? 'done' : 'ready for review'+ return { key: `ci:${url}:${head ?? ''}`, text: `Stuck: checks are red on ${prName(url)}${head ? ` at ${short(head)}` : ''} while its Engineer says it is ${says}. ${url}`,+ fixed: `checks on ${prName(url)} are no longer red` }+ }+ return null+}++/** A task the checks read: a task of a project with work, never a step, a chat, a private chat or one archived. */+const flaggable = (state: SuperTabState, chats: ReadonlySet<string>, group: Conversation) =>+ !group.archived && !group.reviewOf && !group.kind && !group.audience && !isLeads(group) && !isBuddyChat(group) && !chats.has(group.id)+ && projectsOf(state).some(p => p.id === (group.projectId ?? 'lead'))++/** Tags a stuck line resolves once its task is fixed or ends: in [conversationId], [messageId]'s tags of [personIds]. */+export interface ResolvedTags { conversationId: string; messageId: string; personIds: string[] }++/**+ * Each task's change since its record: a new reason posts its line, as the project's PM to the PM, tagging its requester and+ * writers who can read it, at most MAX_MENTIONS; a reason gone posts "No longer stuck" to the PM, tagging nobody, and hands back+ * the old line's tags to resolve. A task that ended while stuck says nothing, and its tags resolve. A project with no PM is left+ * until it has one. Records the change on the task in the caller's write.+ */+export function stuckAlerts(state: SuperTabState, now: number): { rows: MessageDraft[]; resolved: ResolvedTags[] } {+ const rows: MessageDraft[] = [], resolved: ResolvedTags[] = []+ const projects = projectsOf(state)+ const chats = new Set(projects.map(p => p.leadConversationId))+ for (const task of state.conversations) {+ if (!task.stuck && !task.assignment) continue+ // Ended: archived, cancelled, stopped or merged. Its tags resolve and nothing is said.+ const status = task.assignment?.status+ const live = flaggable(state, chats, task) && status !== 'cancelled' && status !== 'stopped' && !(status === 'done' && task.ledger?.mergedAt != null)+ const chat = live ? state.conversations.find(c => c.id === projects.find(p => p.id === (task.projectId ?? 'lead'))!.leadConversationId) : undefined+ const pm = chat?.leadId ? state.agents.find(a => a.id === chat.leadId) : undefined+ const was = task.stuck+ const reason = live ? stuckOf(state, task, now) : null+ if (reason?.key === was?.key || (live && !pm)) continue+ if (was) {+ resolved.push({ conversationId: task.id, messageId: was.messageId, personIds: was.tagged })+ delete task.stuck+ }+ if (!pm) continue+ const author = { kind: 'agent' as const, id: pm.id, name: pm.name, displayName: agentDisplayName(state.agents, pm.id), membershipGeneration: pm.membershipGeneration }+ const recipients = task.agentIds.includes(pm.id) ? [pm.id] : []+ if (reason) {+ const tagged = [...new Set([task.requesterId, ...task.writers ?? []])].filter((id): id is string => !!id).filter(id => {+ const person = state.people.find(p => p.id === id)+ return !!person && canReadGroup(state, { kind: 'person', userId: person.id, email: person.email }, task)+ }).slice(0, MAX_MENTIONS)+ // One id an episode: the same reason coming back after its fix is a new line, and its tags new rows (security review 1 of+ // #3431: a repeated id made writeMentions refuse the tags and stopped the Swarm's time checks). The record is in this same+ // write, so a pass racing it on another server conflicts and retries instead of writing it twice.+ const id = stableId('stuck', task.id, reason.key, String(now))+ rows.push({ id, conversationId: task.id, author, text: reason.text, replyTo: null, recipients, ...tagged.length ? { mentions: tagged } : {},+ source: { kind: 'system' } })+ task.stuck = { key: reason.key, messageId: id, tagged, fixed: reason.fixed }+ } else if (was) {+ rows.push({ id: stableId('stuck-fixed', was.messageId), conversationId: task.id, author, text: `No longer stuck: ${was.fixed}.`, replyTo: null,+ recipients, source: { kind: 'system' } })+ }+ }+ return { rows, resolved }+}diff --git a/docs/plans/2026-11-06-stuck-alerts-plan.md b/docs/plans/2026-11-06-stuck-alerts-plan.mdnew file mode 100644index 000000000..618645463--- /dev/null+++ b/docs/plans/2026-11-06-stuck-alerts-plan.md@@ -0,0 +1,84 @@+# Stuck work is flagged at once to the PM and the people on the task: implementation plan++> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,+> the failing test committed before its code. No Execution Handoff.++**Goal:** Within 5 minutes of a task getting stuck, its PM and its people (its requester, and the people who wrote in it)+hear it in one line in the task, which tags them, so it is in their Needs you. The cases: (a) its pull request's checks are+red at its head while its Engineer says review or done; (b) one of its steps lost its agent, or its agent could not start;+(c) its own agent went down and nobody has taken it after 10 minutes. One line per change; when it is fixed, the tags+resolve and one line says so; nothing repeats (task #3915, Tony 11-06: #3821 sat with red mobile-checks and a lost Test+step, and nobody told him).++**Architecture:**++- `stuck.ts` (new): `stuckOf(state, task, now)` is the task's one stuck reason now, or null, with its key and line; the+ first of: down (c), a step (b), red checks (a). `stuckAlerts(state, now)` compares each task's reason with the one recorded+ on it (`Conversation.stuck`: key, message id, people tagged) and writes the change: a new reason posts one line as the+ PM, to the PM, tagging the task's people; a reason gone posts one "No longer stuck" line and hands back the tags to+ resolve. The time checks run it (store.ts `runTimeChecks`, every Swarm at least every 5 minutes, timeChecks.ts+ QUIET_CHECK_MS), and now write the tags of the rows they write (`writeMentions`, as a command's rows do) and tell phones.+- (a) reads `Conversation.pullRequestChecks` (task #3827, written by the PR watch every minute, done tasks included) for+ the task's newest pull request: `red` with the assignment in review or done, or reopened to its Engineer by that red and not+ picked up yet.+- (b) a step whose assignment is lost, or whose liveness says its start failed.+- (c) the task's assignment lost for 10 minutes or more.+- The people: the requester and `Conversation.writers` (new): the people who posted in the task, newest last, at most 4,+ kept by message.send. Only people who can read the task are tagged (`canReadGroup`), at most MAX_MENTIONS, so members see+ only their own tasks' alerts.+- Cleared tags resolve by `resolveTags` (mentions.ts, new): `resolvedBy: 'fixed'`, on the `[tabId, conversationId, personId]`+ index, one update per person (at most 5).++**Tech Stack:** TypeScript backend (vitest).++**Spec:** task #3915 brief.++## Global Constraints++- No new chat lines but one per state change, in the task's own conversation; nothing in the project chat.+- Steps, chats and finished, cancelled or archived tasks are never flagged; a task that ends while flagged has its tags+ resolved and no line.+- Owns backend/src/superTabs/.++## Design++- growth: `stuck` is one small record per stuck task, removed when it is fixed; `writers` at most 4 ids per task. Both go+ with the task. One tag row per tagged person per change, under the mentions' 30-day expiry.+- concurrency: inside the time check's own Swarm write, as its other notices.+- read cost: loaded state only; the tag resolve is one indexed update per person when a reason clears.+- scale: one pass over the loaded tasks per time check, which already walks them; lines only on change.+- compatibility: new optional group fields, a new `resolvedBy` value `fixed` (clients read a resolved tag as resolved).+- migration and rollback: none; revert. Old groups have neither field.+- audience: tags only to people who can read the task, by the server.+- identity: N/A because nothing runs as anyone.+- failure: this is the failure being made seen.+- platforms: backend only.++## Review Focus++- One line per change and none repeated across passes or servers (the record is in the same write as the line).+- A member is tagged only in tasks they can read.++## Task 1: who wrote in a task++**Files:** model.ts, commands.ts (message.send), stuck.test.ts (new).++- [ ] Test: a person's post in a task records them in `writers`, newest last, at most 4; an agent's post does not.+- [ ] Watch it fail; code; watch it pass; commit.++## Task 2: the stuck reason and its line++**Files:** stuck.ts (new), stuck.test.ts.++- [ ] Tests, for each case (red checks with status review, a lost step, a down agent with no taker after 10 minutes): the+ PM and the requester are told once in one line, a second pass says nothing, and when it is fixed one line clears it+ and hands back the tags; red checks while working, or a down agent for 9 minutes, say nothing.+- [ ] Watch them fail; code; watch them pass; commit.++## Task 3: the time checks write it, and fixed tags resolve++**Files:** store.ts (runTimeChecks), mentions.ts (resolveTags), mentions.test.ts or stuck.test.ts.++- [ ] Test: `resolveTags` resolves only the given message's waiting tags for those people.+- [ ] Watch it fail; code (runTimeChecks writes the rows' tags, tells phones and resolves the cleared ones); watch it pass;+ commit.