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.

Merge batch 11-06 j1040: #3220 #3213 (#3271)

0xken1565df43e84da4
diff --git a/backend/integration/superTabHotReads.test.ts b/backend/integration/superTabHotReads.test.ts
index 540aabb37..4381f4e29 100644
--- a/backend/integration/superTabHotReads.test.ts
+++ b/backend/integration/superTabHotReads.test.ts
@@ -259,6 +259,8 @@ describe('hot reads read only what they return (roadmap 2.7)', () => {
clock = Date.now()
await hosts.changes(owner, s.machineId, { cursor: first.cursor })
await store.deliveries(owner, s.tabId, s.lead)
+ // The worker's time checks (timeChecks.ts), which read the Swarm's open deliveries for its idle agents.
+ await store.runTimeChecks(s.tabId)
// Last: ending the running work releases its run record and open deliveries.
const work = ((await db.swarmGroup.findFirst({ where: { tabId: s.tabId, key: s.web } }))!.data as { assignment: { id: string } }).assignment.id
await store.execute(owner, s.tabId, { operationId: randomUUID(),
@@ -284,7 +286,7 @@ describe('hot reads read only what they return (roadmap 2.7)', () => {
expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(rows[0]!.nreturned!)
})
- it('the Lead\'s poll reads only the Swarm\'s open deliveries, not each agent\'s closed ones', () => {
+ it('the time checks read only the Swarm\'s open deliveries, not each agent\'s closed ones', () => {
// Prisma sends the open statuses as an $or; the claimed-only read ending deliveries makes is the next test's.
const rows = reads(entries, 'SuperTabDelivery', ['tabId', 'status', 'or'], ['agentId', 'messageId', 'assignmentId', 'conversationId'])
expect(rows).toHaveLength(1)
diff --git a/backend/integration/superTabInstructions.test.ts b/backend/integration/superTabInstructions.test.ts
index 146c0a697..6572ea7ba 100644
--- a/backend/integration/superTabInstructions.test.ts
+++ b/backend/integration/superTabInstructions.test.ts
@@ -517,3 +517,32 @@ describe('the migration job', () => {
expect((await db.superTabInstructions.findFirstOrThrow({ where: { tabId: tab, projectId: 'lead' } })).text).toBe('Our own words.')
})
})
+
+// Task #3392 (anh Dee, 11-05, decision 5): a person's rule may move into a code task, its line staying until that task merges.
+// A merged task goes quiet after a day, out of the Swarm a command loads: the save names it, and the store loads it.
+describe('a rule moved into a code task that went quiet', () => {
+ it('counts once the save names the merged task, and not before', async () => {
+ const { tab, lead } = await withLead()
+ const quiet = 'No releases between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).'
+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')
+ await run(tab, save(1, doc(quiet, 'Tests run first.')))
+ const task = (await run(tab, { type: 'conversation.create', title: 'Release guard', brief: `Goal:\nBlock night releases.\n\nChanges:\n- ${quiet}`,
+ checks: [] })).result.conversationId as string
+ const drop = (tasks?: string[]) => run(tab, { type: 'instructions.save', projectId: 'lead', baseRevision: 2, text: doc('Tests run first.'),
+ summary: 'Moved the release rule to its task', askedBy: owner.sub, ...tasks ? { tasks } : {} }, host, lead)
+ // Open: the line stays until the task merges.
+ await expect(drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })
+ // Its own merge record is no merge (River, review of #3220): only what the Swarm read on GitHub is.
+ const part = await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: task } })
+ const data = part.data as { ledger?: object }
+ await db.swarmGroup.update({ where: { id: part.id }, data: { version: { increment: 1 },
+ data: { ...data, ledger: { ...data.ledger, mergedAt: now, shippedAt: now } } } })
+ await expect(drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'waiting' }] } })
+ // Seen merged on GitHub (store.ts archiveFinished), then quiet: out of the command's load unless the save names it.
+ const seen = await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: task } })
+ await db.swarmGroup.update({ where: { id: seen.id }, data: { dormant: true, version: { increment: 1 },
+ data: { ...seen.data as object, dormant: true, mergeSeen: { 'https://github.com/acme/app/pull/7': now } } } })
+ await expect(drop()).rejects.toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ why: 'removed' }] } })
+ expect((await drop([task])).result).toMatchObject({ revision: 3 })
+ })
+})
diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.ts
index 8732c54c2..832aeacb3 100644
--- a/backend/integration/superTabLiveness.test.ts
+++ b/backend/integration/superTabLiveness.test.ts
@@ -85,6 +85,8 @@ async function swarm({ legacy = false, client = db, hooks, independent = false,
/** What the Lead's host receives now (this poll is also the Lead's wake-up path), with each row's text, and what it hears in a
* digest (noticeDigest.ts): gathered for one, or named by one. Those of no digest of its own come first, in the order written. */
const leadInbox = async () => {
+ // The worker's time checks run every 30 s (timeChecks.ts): one runs before each poll here.
+ await timed.runTimeChecks(tab)
const rows = await timed.deliveries(host, tab, lead)
const digest = await db.superTabDelivery.findMany({ where: { tabId: tab, agentId: lead, status: { in: ['gathered', 'digested'] } }, orderBy: { createdAt: 'asc' } })
const ids = [...rows, ...digest].map(r => r.messageId)
@@ -160,7 +162,7 @@ describe('work that loses its owner', () => {
raced = true
await f.observe('test-host', [f.harness.worker], { harnessProgress: { [f.harness.worker]: f.clock.now } })
}), () => f.clock.now)
- await racing.deliveries(host, f.tab, f.lead)
+ await racing.runTimeChecks(f.tab)
expect(raced).toBe(true)
expect((await f.assignment()).status).toBe('working')
expect(await f.lostRows()).toEqual([])
@@ -182,7 +184,7 @@ describe('work that loses its owner', () => {
raced = true
await f.execute({ type: 'agent.alert', agentId: other, alert: 'model', active: false }, host, other)
}), () => f.clock.now)
- await racing.deliveries(host, f.tab, f.lead)
+ await racing.runTimeChecks(f.tab)
expect(raced).toBe(true)
expect((await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === group)!.assignment!.status).toBe('working')
})
@@ -1052,7 +1054,7 @@ describe('an agent whose task was lost', () => {
if (next) return
next = String((await f.execute({ type: 'work.assign', conversationId: f.group, agentId: f.worker })).result.assignmentId)
}), () => f.clock.now)
- await racing.deliveries(host, f.tab, f.lead)
+ await racing.runTimeChecks(f.tab)
expect(next).not.toBe('')
expect(await runOf(f.worker)).toMatchObject({ tabId: f.tab, assignmentId: next })
expect(await f.assignment()).toMatchObject({ id: next, status: 'working' })
@@ -1185,9 +1187,9 @@ describe('a start that never runs', () => {
}
})
- // The time checks run on the Lead's poll and on any other machine's report (store.ts).
+ // The time checks run in the worker (timeChecks.ts) and on any other machine's report (store.ts).
it.each([
- ['the Lead\'s poll', (racing: SuperTabStore, f: Awaited<ReturnType<typeof swarm>>) => racing.deliveries(host, f.tab, f.lead)],
+ ['the worker\'s time checks', (racing: SuperTabStore, f: Awaited<ReturnType<typeof swarm>>) => racing.runTimeChecks(f.tab)],
['another machine\'s report', (racing: SuperTabStore, f: Awaited<ReturnType<typeof swarm>>) => f.observe('lead-host', [f.harness.lead], {}, racing)],
])('is not failed by %s that read its machine silent while that machine reported it preparing', async (_, sweep) => {
const f = await swarm()
@@ -1708,7 +1710,8 @@ describe('the delivery poll of an agent with a held delivery', () => {
}
f.clock.now += 6 * MINUTE
const expectedIds = assignments.map(assignment => stableId(stableId('work-lost', assignment, String(f.clock.now)), 'lead'))
- await f.timed.deliveries(host, f.tab, f.lead)
+ // The worker's time checks lose the tasks.
+ await f.timed.runTimeChecks(f.tab)
// Gathered for a digest; each goes on its own after the settle pass's 30 minutes, the ones these cases are about.
await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: f.lead, status: 'gathered' }, data: { status: 'queued' } })
const first = (await f.timed.deliveries(host, f.tab, f.lead)).filter(row => expectedIds.includes(row.messageId))
@@ -1787,8 +1790,8 @@ describe('the push for a new delivery', () => {
f.clock.now += 6 * MINUTE
// Each loss notice is named by its task and the time of the loss (this poll).
const expectedIds = assignments.map(assignment => stableId(stableId('work-lost', assignment, String(f.clock.now)), 'lead'))
- // One poll expires all three assignments and inserts their messages/deliveries together.
- await f.timed.deliveries(host, f.tab, f.lead)
+ // One run of the worker's time checks expires all three assignments and inserts their messages/deliveries together.
+ await f.timed.runTimeChecks(f.tab)
// Gathered for a digest; each goes on its own after the settle pass's 30 minutes, the ones these cases are about.
await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: f.lead, status: 'gathered' }, data: { status: 'queued' } })
const first = (await f.timed.deliveries(host, f.tab, f.lead)).filter(row => expectedIds.includes(row.messageId))
diff --git a/backend/integration/superTabNoticeDigest.test.ts b/backend/integration/superTabNoticeDigest.test.ts
index ca280ac58..54c969e2a 100644
--- a/backend/integration/superTabNoticeDigest.test.ts
+++ b/backend/integration/superTabNoticeDigest.test.ts
@@ -196,7 +196,7 @@ describe('which messages to the coordinator are gathered', () => {
const id = await f.write({ kind: 'idle' }, f.worker)
await db.superTabDelivery.update({ where: { id: stableId(id, f.worker) }, data: { status: 'gathered' } })
f.clock.now += 16 * MINUTE
- await f.poll()
+ await f.timed.runTimeChecks(f.tab)
const told = (await db.superTabMessage.findMany({ where: { tabId: f.tab } })).filter(m => kindOf(m) === 'idle' && m.text.includes('no open task'))
expect(told).toHaveLength(1)
})
diff --git a/backend/integration/superTabPmSchedule.test.ts b/backend/integration/superTabPmSchedule.test.ts
index b516b7b45..36a841548 100644
--- a/backend/integration/superTabPmSchedule.test.ts
+++ b/backend/integration/superTabPmSchedule.test.ts
@@ -86,6 +86,8 @@ async function swarm({ fresh = false, told }: { fresh?: boolean; told?: string[]
// Its worker keeps saying where it is, as a live one does; a finished task refuses the line and nothing changes.
await execute({ type: 'work.status', conversationId: group, assignmentId, status: 'working', result: randomUUID() }, host, worker).catch(() => {})
await report()
+ // The worker's time checks run every 30 s (timeChecks.ts): one runs before each poll here.
+ await timed.runTimeChecks(tab)
return timed.deliveries(host, tab, lead)
}
const status = (s: 'done' | 'blocked' | 'needs_human' | 'working', result = 'A result') =>
diff --git a/backend/integration/superTabTidy.test.ts b/backend/integration/superTabTidy.test.ts
index ebb922e3a..c9ab72344 100644
--- a/backend/integration/superTabTidy.test.ts
+++ b/backend/integration/superTabTidy.test.ts
@@ -20,7 +20,7 @@ import { logger } from '../src/utils/logger.js'
import { fakeApp, fakeGitHub, throwawayKey } from '../src/github/fakeGitHub.js'
import { appPullRequests } from '../src/superTabs/archive.js'
-// Nobody tidies a Swarm by hand: an agent idle for 15 minutes is told to its coordinator on its poll, and finished groups
+// Nobody tidies a Swarm by hand: an agent idle for 15 minutes is told to its coordinator by the worker's time checks, and finished groups
// archive. A fresh loopback replica set, created here.
let replica: MongoMemoryReplSet
let db: PrismaClient
@@ -98,13 +98,13 @@ async function swarm() {
// Project instructions, phase 4 (decision 7): the server stops no idle agent. Its coordinator is told once per idle spell,
// whether tidying is on or off, and the instructions say whether it stops or keeps the agent.
describe('an agent left idle', () => {
- it('is told to its coordinator on its poll 15 minutes after its last activity, once, and nothing stops it', async () => {
+ it('is told to its coordinator by the time checks 15 minutes after its last activity, once, and nothing stops it', async () => {
const f = await swarm()
f.clock.now += 14 * MINUTE
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await f.lines()).toEqual([])
f.clock.now += MINUTE + 1_000
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
const lines = await f.lines()
expect(lines).toEqual([expect.objectContaining({ conversationId: 'lead', recipientIds: [f.lead], text: 'Worker has had no open task for 15 minutes.',
source: { kind: 'idle', agentId: f.worker } })])
@@ -116,14 +116,14 @@ describe('an agent left idle', () => {
expect((await rosterRows(f.timed, host, 'test-host')).find(r => r.agent.id === f.worker)!.agent.releaseId ?? null).toBeNull()
// The same idle spell is told once, however many polls follow.
f.clock.now += 30 * MINUTE
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await f.lines()).toHaveLength(1)
})
it('is told to the coordinator alone: no person or other agent reads it', async () => {
const f = await swarm()
f.clock.now += 15 * MINUTE + 1_000
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
const [line] = await f.lines()
const page = async (user: AuthUser, conversationId: string, query: { messageId?: string } = {}, asAgentId?: string) =>
(await f.timed.messages(user, f.tab, conversationId, query, asAgentId)).messages.map(m => m.id)
@@ -142,10 +142,10 @@ describe('an agent left idle', () => {
// Written straight into the queue, as a delivery from a moment ago that its host has not picked up yet.
const waiting = await db.superTabDelivery.create({ data: { id: randomUUID(), tabId: f.tab, conversationId: f.group, messageId: randomUUID(), agentId: f.worker,
machineId: 'test-host', machineOwnerId: host.sub, assignmentId: null, membershipGeneration: 'g', authorKind: 'person', authorId: owner.sub, authorGeneration: 'g' } })
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await f.lines()).toEqual([])
await db.superTabDelivery.update({ where: { id: waiting.id }, data: { status: 'delivered' } })
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await f.lines()).toHaveLength(1)
})
@@ -163,12 +163,12 @@ describe('an agent left idle', () => {
f.clock.now += 20 * MINUTE
// The Builder's session is at work: its machine's report keeps its task's lease (liveness.ts).
await f.observe('test-host', [f.harness.worker, builderHarness], { harnessProgress: { [builderHarness]: f.clock.now } })
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await told()).toEqual([])
await f.execute({ type: 'work.cancel', conversationId: reviewed, assignmentId: work, reason: 'Dropped' })
await f.delivered()
f.clock.now += 15 * MINUTE + 1_000
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await told()).toHaveLength(1)
})
@@ -188,7 +188,7 @@ describe('an agent left idle', () => {
const recent = new Date(f.clock.now - 10 * MINUTE)
await db.swarmGroup.update({ where: { id: part.id }, data: { dormant: true, lastActivityAt: recent,
data: { ...part.data as object, dormant: true, lastActivityAt: recent.toISOString() } } })
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
const named = (await f.timed.read(owner, f.tab)).state.agents.find(a => a.id === reviewer)!
expect((await f.lines()).filter(m => (m.source as { agentId?: string }).agentId === reviewer))
.toEqual([expect.objectContaining({ conversationId: 'lead', text: `${named.displayName ?? named.name} has had no open task for 15 minutes.` })])
@@ -199,7 +199,7 @@ describe('an agent left idle', () => {
const f = await swarm()
await f.execute({ type: 'tab.tidy', enabled: false })
f.clock.now += 20 * MINUTE
- await f.timed.deliveries(host, f.tab, f.lead)
+ await f.timed.runTimeChecks(f.tab)
expect(await f.lines()).toHaveLength(1)
expect((await f.member()).workDecision).toBe('awaiting')
})
@@ -292,6 +292,20 @@ describe('a finished group', () => {
}
const isArchived = async (f: Awaited<ReturnType<typeof swarm>>, key: string) => (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key } })).archived
+ // Task #3392 (River, review of #3220): a person's rule moved into a code task may leave the instructions once that task
+ // merged, and only the Swarm's own read of GitHub says so: what the archive read merged in the project's repository.
+ it('records which of its pull requests GitHub says merged in its project\'s repository, and no other', async () => {
+ const f = await swarm()
+ const task = await cancelledIn(f, 'Shipped in the batch')
+ const ours = 'https://github.com/acme/app/pull/41', closed = 'https://github.com/acme/app/pull/42', theirs = 'https://github.com/other/app/pull/43'
+ await f.execute({ type: 'message.send', conversationId: task, text: `Pull requests: ${ours} ${closed} ${theirs}`, replyTo: null, recipientIds: [] })
+ f.clock.now += 40 * MINUTE
+ await archiveFinishedGroups(db, f.timed, github({ [ours]: 'merged', [closed]: 'closed', [theirs]: 'merged' }), f.clock.now)
+ const data = (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: task } })).data as { archived: boolean; mergeSeen?: Record<string, number> }
+ expect(data.archived).toBe(true)
+ expect(data.mergeSeen).toEqual({ [ours]: f.clock.now })
+ })
+
// Diego, 11-04 (#2602): another repository's number, read in this one, kept the task open forever.
it('waits on no "PR #N" another repository\'s name sits next to', async () => {
const f = await swarm()
diff --git a/backend/integration/superTabTimeChecks.test.ts b/backend/integration/superTabTimeChecks.test.ts
new file mode 100644
index 000000000..c648c2f1d
--- /dev/null
+++ b/backend/integration/superTabTimeChecks.test.ts
@@ -0,0 +1,231 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import type { Command } from '../src/superTabs/commands.js'
+import type { 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'
+
+// 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
+// 10 hours and the board showed nothing working. Nothing here polls as the PM. A fresh loopback replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '200000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const host: AuthUser = { sub: '200000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const MINUTE = 60_000
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_time_checks_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })
+ for (const machineId of ['lead-host', 'test-host']) {
+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })
+ }
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm whose PM runs on one of host's machines and whose worker, on another, is assigned "Ship the parser". */
+async function swarm() {
+ let now = Date.parse('2026-11-05T08:00:00.000Z')
+ const timed = new SuperTabStore(db, () => now)
+ const tab = (await timed.create(owner, randomUUID(), 'Time checks', 'public')).id
+ const execute = (command: Command, user = owner, asAgentId?: string) => timed.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)
+ const invitation = await execute({ type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })
+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)
+ for (const [machineId, name] of [['lead-host', 'Lead Mac'], ['test-host', 'Worker Mac']]) {
+ await execute({ type: 'machine.contribute', machineId: machineId!, name: name!, cwd: '/repo', engines: ['codex'], maxAgents: 4 }, host)
+ }
+ const generations = new Map<string, string>()
+ for (const machineId of ['lead-host', 'test-host']) generations.set(machineId, (await poolRows(timed, host, machineId)).find(p => p.tabId === tab)!.machine.generation)
+ const harness = { lead: randomUUID(), worker: randomUUID() }
+ const add = async (conversationId: string, machineId: string, harnessId: string, name: string, lead = false) => String((await execute({ type: 'agent.add',
+ conversationId, machineId, harnessId, name, configuration: config, lead })).result.agentId)
+ const lead = await add('lead', 'lead-host', harness.lead, 'Lead', true)
+ const group = String((await execute({ type: 'conversation.create', title: 'Ship the parser', brief: 'Implement it',
+ checks: [{ description: 'Verified', independent: false }] })).result.conversationId)
+ const worker = await add(group, 'test-host', harness.worker, 'Worker')
+ const assignmentId = String((await execute({ type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId)
+ const observe = (machineId: string, running: string[], extra: Partial<MachineObservation> = {}) => timed.observeMachine(host, tab, machineId, {
+ generation: generations.get(machineId)!, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9,
+ diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },
+ quotas: [], tools: {}, runningHarnessIds: running, stoppedHarnessIds: [], ...extra })
+ /** Only the worker's machine reports, its screen changing: the PM's host is down and never polls. */
+ const workerBeat = () => observe('test-host', [harness.worker], { harnessProgress: { [harness.worker]: now } })
+ const rows = async (kind: string) => (await db.superTabMessage.findMany({ where: { tabId: tab }, orderBy: { sequence: 'asc' } }))
+ .filter(m => (m.source as { kind?: string } | null)?.kind === kind)
+ return { timed, tab, execute, lead, group, worker, assignmentId, harness, observe, workerBeat, rows,
+ clock: { get now() { return now }, set now(value: number) { now = value } } }
+}
+
+describe('the time checks with the PM down', () => {
+ it('tell the PM of a task that went quiet, once, with no PM poll', async () => {
+ const f = await swarm()
+ const posted = f.clock.now
+ await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Started' }, host, f.worker)
+ for (const minutes of [10, 20, 29]) {
+ f.clock.now = posted + minutes * MINUTE
+ await f.workerBeat()
+ await f.timed.runTimeChecks(f.tab)
+ }
+ expect(await f.rows('work-stalled')).toEqual([])
+ f.clock.now = posted + 30 * MINUTE
+ await f.workerBeat()
+ expect(await f.timed.runTimeChecks(f.tab)).toBeGreaterThan(0)
+ const stalled = await f.rows('work-stalled')
+ expect(stalled).toEqual([expect.objectContaining({ conversationId: 'lead', recipientIds: [f.lead] })])
+ expect(stalled[0]!.text).toContain('"Ship the parser": quiet, ')
+ for (const minutes of [31, 45]) {
+ f.clock.now = posted + minutes * MINUTE
+ await f.workerBeat()
+ await f.timed.runTimeChecks(f.tab)
+ }
+ expect(await f.rows('work-stalled')).toHaveLength(1)
+ })
+
+ it('tell the PM of an agent left idle for 15 minutes, once, with no PM poll', async () => {
+ const f = await swarm()
+ await f.execute({ type: 'work.cancel', conversationId: f.group, assignmentId: f.assignmentId, reason: 'Done elsewhere' })
+ // Its host took the cancel notice, as a running host does.
+ await db.superTabDelivery.updateMany({ where: { tabId: f.tab, agentId: f.worker, status: 'queued' }, data: { status: 'delivered' } })
+ f.clock.now += 14 * MINUTE
+ await f.workerBeat()
+ await f.timed.runTimeChecks(f.tab)
+ expect(await f.rows('idle')).toEqual([])
+ f.clock.now += MINUTE + 1_000
+ await f.workerBeat()
+ await f.timed.runTimeChecks(f.tab)
+ expect(await f.rows('idle')).toEqual([expect.objectContaining({ conversationId: 'lead', recipientIds: [f.lead], text: 'Worker has had no open task for 15 minutes.' })])
+ f.clock.now += 10 * MINUTE
+ await f.workerBeat()
+ await f.timed.runTimeChecks(f.tab)
+ expect(await f.rows('idle')).toHaveLength(1)
+ })
+
+ it('lose the task of a worker whose machine went silent, and tell the PM, with no report and no PM poll', async () => {
+ const f = await swarm()
+ await f.workerBeat()
+ f.clock.now += 2 * MINUTE + 5_000
+ // No machine reports from here on: the worker's machine died, and the PM's host is down too.
+ await f.timed.runTimeChecks(f.tab)
+ expect((await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!.assignment!.status).toBe('lost')
+ expect((await f.rows('work-lost')).map(r => r.text)).toContainEqual(expect.stringContaining('Worker lost its task "Ship the parser"'))
+ })
+
+ 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)
+ f.clock.now += 31 * MINUTE
+ await f.workerBeat()
+ await f.timed.deliveries(host, f.tab, f.lead)
+ expect(await f.rows('work-stalled')).toEqual([])
+ expect((await f.timed.read(owner, f.tab)).state.conversations.find(c => c.id === f.group)!.liveness).toBeUndefined()
+ })
+})
+
+describe('the worker\'s pass', () => {
+ it('runs the checks of each Swarm active in the last week, and leaves a deleted one alone', async () => {
+ const f = await swarm(), quiet = await swarm()
+ await f.execute({ type: 'work.status', conversationId: f.group, assignmentId: f.assignmentId, status: 'working', result: 'Started' }, host, f.worker)
+ f.clock.now += 31 * MINUTE
+ await f.workerBeat()
+ expect(await timeCheckSwarms(db, f.clock.now)).toEqual(expect.arrayContaining([f.tab, quiet.tab]))
+ await db.superTab.update({ where: { id: quiet.tab }, data: { deletedAt: new Date(f.clock.now) } })
+ const pass = await runTimeCheckPass(db, f.timed, f.clock.now)
+ expect(pass.failed).toBe(0)
+ expect(await f.rows('work-stalled')).toHaveLength(1)
+ expect(await quiet.rows('work-stalled')).toEqual([])
+ // A week later nothing there is read again.
+ expect(await timeCheckSwarms(db, f.clock.now + 8 * 24 * 60 * MINUTE)).not.toContain(f.tab)
+ })
+})
+
+describe('what the PM owes', () => {
+ const owedOf = async (f: Awaited<ReturnType<typeof swarm>>) => {
+ const head = await db.swarmHead.findFirstOrThrow({ where: { tabId: f.tab } })
+ return ((head.data as { projects?: Array<{ owed?: unknown }> }).projects ?? [])[0]?.owed
+ }
+ const pmRow = async (f: Awaited<ReturnType<typeof swarm>>, agentId = f.lead) =>
+ (await rosterRows(f.timed, host, agentId === f.lead ? 'lead-host' : 'test-host')).find(r => r.tabId === f.tab && 'agent' in r && r.agent.id === agentId) as Record<string, unknown>
+
+ it('is the oldest message a person sent it that it has not answered, until it answers, and only its own host row carries it', async () => {
+ const f = await swarm()
+ // An agent's message to the PM is never an ask it owes a person.
+ await f.execute({ type: 'message.send', conversationId: f.group, text: 'Halfway there.', replyTo: null, recipientIds: [f.lead] } as Command, host, f.worker)
+ await f.timed.runTimeChecks(f.tab)
+ expect(await owedOf(f)).toBeUndefined()
+ const sent = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Where is my parser?', replyTo: null, recipientIds: [] } as Command)
+ f.clock.now += MINUTE
+ const next = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'And the docs?', replyTo: null, recipientIds: [] } as Command)
+ f.clock.now += MINUTE
+ await f.timed.runTimeChecks(f.tab)
+ const messageId = String(sent.result.messageId)
+ // When its delivery to the PM was written, as the server's clock read then.
+ const sentAt = async (id: unknown) => (await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, messageId: String(id), agentId: f.lead } })).createdAt.getTime()
+ const asked = await sentAt(messageId)
+ expect(await owedOf(f)).toEqual({ messageId, since: asked })
+ expect((await pmRow(f)).owed).toEqual({ messageId, since: asked, restartAfterMs: 20 * MINUTE })
+ expect((await pmRow(f, f.worker)).owed).toBeNull()
+ // Readers never see it: it may name a message in a person's private chat with the PM.
+ expect((await f.timed.read(owner, f.tab)).state.projects![0]).not.toHaveProperty('owed')
+ await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Parser ships today.', replyTo: null, recipientIds: [], answers: messageId } as Command, host, f.lead)
+ await f.timed.runTimeChecks(f.tab)
+ expect(await owedOf(f)).toEqual({ messageId: String(next.result.messageId), since: await sentAt(next.result.messageId) })
+ })
+})
+
+// Reviews of #3213 (Wren, Important 1; SecAlder, Minor 3): the instructions tell the PM to react instead of acknowledging, so
+// a message it reacted to was owed for a day and every long PM turn read as hung.
+describe('what the PM owes, once it reacted', () => {
+ it('is not a message the PM reacted to', async () => {
+ const f = await swarm()
+ const sent = await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Thanks for the fix!', replyTo: null, recipientIds: [] } as Command)
+ const messageId = String(sent.result.messageId)
+ await f.timed.runTimeChecks(f.tab)
+ const head = async () => ((await db.swarmHead.findFirstOrThrow({ where: { tabId: f.tab } })).data as { projects?: Array<{ owed?: { messageId: string } }> }).projects![0]!.owed
+ expect((await head())?.messageId).toBe(messageId)
+ await f.execute({ type: 'message.react', conversationId: 'lead', messageId, emoji: 'check', on: true } as Command, host, f.lead)
+ expect((await db.superTabDelivery.findFirstOrThrow({ where: { tabId: f.tab, messageId, agentId: f.lead } })).status).toBe('answered')
+ await f.timed.runTimeChecks(f.tab)
+ expect(await head()).toBeUndefined()
+ })
+})
+
+// Review of #3213 (Wren, Important 2; ENGINEERING.md 4: a timer that wakes while nothing changed is a defect): a Swarm whose
+// groups show no new activity is checked every few minutes, not every 30 s.
+describe('the worker\'s pass on a quiet Swarm', () => {
+ it('checks a Swarm again at once when its activity moved, and otherwise only every QUIET_CHECK_MS', async () => {
+ const f = await swarm()
+ const calls: string[] = []
+ const counting = { runTimeChecks: async (tabId: string) => { if (tabId === f.tab) calls.push(tabId); return 0 } }
+ const seen = new Map()
+ await runTimeCheckPass(db, counting, f.clock.now, undefined, seen)
+ await runTimeCheckPass(db, counting, f.clock.now + 30_000, undefined, seen)
+ expect(calls).toHaveLength(1)
+ f.clock.now += 60_000
+ await f.execute({ type: 'message.send', conversationId: 'lead', text: 'Any news?', replyTo: null, recipientIds: [] } as Command)
+ await runTimeCheckPass(db, counting, f.clock.now, undefined, seen)
+ expect(calls).toHaveLength(2)
+ await runTimeCheckPass(db, counting, f.clock.now + QUIET_CHECK_MS - 1, undefined, seen)
+ expect(calls).toHaveLength(2)
+ await runTimeCheckPass(db, counting, f.clock.now + QUIET_CHECK_MS, undefined, seen)
+ expect(calls).toHaveLength(3)
+ })
+})
diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.ts
index bea644a40..15e633393 100644
--- a/backend/integration/workerIndexPlans.test.ts
+++ b/backend/integration/workerIndexPlans.test.ts
@@ -366,3 +366,51 @@ describe('the delivery re-push pass (superTabs/deliveryRepush.ts, task #2800)',
expect(read[0]!.docsExamined).toBe(3)
})
})
+
+describe('the time checks\' pass', () => {
+ // Task #3385: every 30 s the worker picks the Swarms to check by their groups awake and active this week, on the
+ // [dormant, lastActivityAt] index: never every group of every Swarm.
+ it('reads only the groups awake and active in the last week, by the activity index', async () => {
+ const { timeCheckSwarms, TIME_CHECK_QUIET_MS } = await import('../src/superTabs/timeChecks.js')
+ const group = (tabId: string, at: number, dormant: boolean) => ({ id: randomUUID(), tabId, key: randomUUID(), version: 1, changedAt: new Date(at),
+ ordinal: 1, data: {}, agentIds: [], dormant, lastActivityAt: new Date(at) })
+ await db.swarmGroup.createMany({ data: [
+ ...Array.from({ length: 20 }, (_, i) => group(`asleep-${i}`, NOW - DAY, true)),
+ ...Array.from({ length: 20 }, (_, i) => group(`old-${i}`, NOW - TIME_CHECK_QUIET_MS - DAY, false)),
+ group('busy', NOW - 60_000, false), group('busy', NOW - 120_000, false), group('quiet', NOW - 3 * DAY, false),
+ ] })
+ let tabs: string[] = []
+ const entries = await profiled(db, async () => { tabs = await timeCheckSwarms(db, NOW) })
+ // Newest first; other tests' groups may be there too.
+ expect(tabs.filter(t => t === 'busy' || t === 'quiet' || t.startsWith('asleep-') || t.startsWith('old-'))).toEqual(['busy', 'quiet'])
+ const awake = await db.swarmGroup.count({ where: { dormant: false, lastActivityAt: { gte: new Date(NOW - TIME_CHECK_QUIET_MS) } } })
+ const rows = reads(entries, 'SwarmGroup', ['dormant', 'lastActivityAt'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ dormant: 1, lastActivityAt: 1/)
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(awake)
+ })
+})
+
+describe('what a PM owes', () => {
+ // Task #3385: each pass reads, per PM, its oldest unanswered message from a person, on [tabId, agentId, status, createdAt].
+ it('reads the PM\'s unanswered deliveries of the last day alone, by the delivery index', async () => {
+ const { owedAsk, OWED_REACH_MS } = await import('../src/superTabs/timeChecks.js')
+ const delivery = (agentId: string, status: string, at: number, authorKind = 'person') => ({ id: randomUUID(), tabId: 'owed-tab', conversationId: 'lead',
+ messageId: randomUUID(), agentId, machineId: 'm', membershipGeneration: 'g', authorKind, authorId: 'a', authorGeneration: 'g', status, createdAt: new Date(at) })
+ const asked = delivery('pm', 'delivered', NOW - 3_600_000)
+ await db.superTabDelivery.createMany({ data: [
+ ...Array.from({ length: 20 }, () => delivery('pm', 'answered', NOW - 60_000)),
+ ...Array.from({ length: 20 }, () => delivery('pm', 'delivered', NOW - OWED_REACH_MS - 60_000)),
+ ...Array.from({ length: 20 }, () => delivery('other', 'queued', NOW - 60_000)),
+ asked, delivery('pm', 'queued', NOW - 60_000),
+ ] })
+ let owed: Awaited<ReturnType<typeof owedAsk>> = null
+ const entries = await profiled(db, async () => { owed = await owedAsk(db, 'owed-tab', 'pm', NOW) })
+ expect(owed).toEqual({ messageId: asked.messageId, since: NOW - 3_600_000 })
+ const rows = reads(entries, 'SuperTabDelivery', ['tabId', 'agentId', 'status', 'createdAt'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, agentId: 1, status: 1, createdAt: 1/)
+ // The two unanswered rows of the last day, at most one key past each status's range.
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(2)
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 1df7ed85e..b282da0a9 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -70,7 +70,7 @@ import { BUDDY_OWN_MACHINE_REFUSAL } from './buddyContract.js'
import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'
import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadEffort, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'
import { ACK_ONLY_HINT, isAcknowledgement } from './acknowledgements.js'
-import { allowedDrops, approvedDropNotice, droppedLines, MAX_APPROVALS, MAX_DROPPED_LINES, refuseRepeats, type ApprovalRow, type DroppedLine } from './ruleGuard.js'
+import { allowedDrops, approvedDropNotice, droppedLines, MAX_APPROVALS, MAX_DROPPED_LINES, refuseOverBudget, refuseRepeats, type ApprovalRow, type DroppedLine } from './ruleGuard.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
import { BUILT_IN_HEADING, tidySaved } from './pmSchedule.js'
@@ -238,6 +238,8 @@ export const commandSchema = z.discriminatedUnion('type', [
summary: summarySchema, askedBy: id.optional(),
// A person's own messages approving the drop of their rules (ruleGuard.ts), when the save drops any.
approvals: z.array(id).max(MAX_APPROVALS).optional(),
+ // Code tasks the save's rules moved into (ruleGuard.ts rulePlaces), loaded even when quiet (store.ts namedFor; #3392).
+ tasks: z.array(id).max(MAX_APPROVALS).optional(),
// How the writer sorted the lines it dropped, for the History (ruleGuard.ts droppedLines; the daily tidy).
dropped: z.array(z.object({ text: z.string().trim().min(1).max(2000), kind: z.enum(['merged', 'expired', 'rule']) }).strict())
.max(MAX_DROPPED_LINES).optional(),
@@ -2033,6 +2035,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
: fail('INSTRUCTIONS_UNAVAILABLE', 'This project\'s instructions cannot be read now. Try again in a moment.', 503)
// A line the save adds that the document already has is refused with the existing line quoted (#3283).
refuseRepeats(before, command.text)
+ // No part grows past its size budget: core, each role section, people notes, the whole (#3392).
+ refuseOverBudget(before, command.text)
// A person's rule, or who gave it, is dropped only by that person or with their own message approving it (#3151).
const { told, rules } = allowedDrops(state, project, before, command.text, sender, command.approvals ?? [], context.approvals ?? [],
context.instructions?.at ?? 0)
diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.ts
index 3d0bed1a5..0ec260023 100644
--- a/backend/src/superTabs/instructions.test.ts
+++ b/backend/src/superTabs/instructions.test.ts
@@ -4,6 +4,7 @@ import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
import { appendRouting, instructionsHash, legacyRoleName, MAX_INSTRUCTIONS_BYTES, roleNameOf, routingSummary, summarySchema } from './instructions.js'
import type { SwarmProject } from './projects.js'
import { INSTRUCTIONS_TEMPLATE, TEMPLATE_WORKFLOW } from './instructionsTemplate.js'
+import { budgetParts, INSTRUCTIONS_BUDGET } from './instructionsDiff.js'
import { hostTab } from './read/hostRows.js'
import { FIRST_INSTRUCTIONS } from './instructions.js'
@@ -32,33 +33,48 @@ function fixture() {
}
describe('the built-in template', () => {
+ // Task #3392 (River, 11-05): a new project's PM must be able to add its routing lines, and a member a line to the PM's
+ // section, so the template keeps room in its core and 200 B in its PM section, every role within its budget. The core's
+ // room went from 800 B to 300 B when #3227's rule that the server opens review steps came in word for word (River, 11-06):
+ // rules leaving for code free room again.
+ it('keeps to the size budget, with room in its core and its PM section', () => {
+ const parts = budgetParts(INSTRUCTIONS_TEMPLATE)
+ expect(parts.find(p => p.part === 'core')!.bytes).toBeLessThanOrEqual(INSTRUCTIONS_BUDGET.core - 300)
+ expect(parts.find(p => p.part === 'role PM')!.bytes).toBeLessThanOrEqual(INSTRUCTIONS_BUDGET.role - 200)
+ for (const role of parts.filter(p => p.part.startsWith('role '))) expect(role.bytes, role.part).toBeLessThanOrEqual(INSTRUCTIONS_BUDGET.role)
+ expect(parts.filter(p => p.part.startsWith('role ')).map(p => p.part)).toEqual(['role PM', 'role Engineer', 'role Reviewer', 'role Tester'])
+ })
// Ken, 2026-11-02: one pull request showed as three tasks (#1835, its review #1918, its test #1919), and the PM opened
// groups to hold, batch and triage work. Agents forgot which task they were on (agent context design, section 3).
it('the template workflow has one task per request, steps, and the context tools', () => {
+ // Its wording is checked as text, wrapping aside (the template was rewrapped to its size budget, #3392).
+ const workflow = TEMPLATE_WORKFLOW.replace(/\s+/g, ' ')
expect(TEMPLATE_WORKFLOW).toContain('1. One request is one task.')
// Ken, 2026-11-02: the PM says what the task needs once, then stays out of it until the Engineer reports.
- expect(TEMPLATE_WORKFLOW).toContain('It says which\n reviews and tests the task needs')
- expect(TEMPLATE_WORKFLOW).toContain("That is the PM's part until the Engineer reports.")
- expect(TEMPLATE_WORKFLOW).toContain('The PM opens no task to hold, batch, triage or list work')
- expect(TEMPLATE_WORKFLOW).toContain('adds a review step to its task')
+ expect(workflow).toContain('says which reviews and tests the task needs')
+ expect(workflow).toContain("That is the PM's part until the Engineer reports.")
+ expect(workflow).toContain('The PM opens no task to hold, batch, triage or list work')
+ expect(workflow).toContain('adds a review step to its task')
// Task #3401: the server opens a ready pull request's steps from the files it changes; the Engineer opens them only
// where it opened none.
- expect(TEMPLATE_WORKFLOW).toContain('2. When the pull request is ready, the server opens its review steps from the files it changes')
- expect(TEMPLATE_WORKFLOW).toContain('Where it opened none, the Engineer adds a review step to its task')
- expect(TEMPLATE_WORKFLOW).toContain('it adds no new step for a second round')
+ expect(workflow).toContain('2. When the pull request is ready, the server opens its review steps from the files it changes')
+ expect(workflow).toContain('Where it opened none, the Engineer adds a review step to its task')
+ expect(workflow).toContain('it adds no new step for a second round')
expect(TEMPLATE_WORKFLOW).toContain('run `mine`')
expect(TEMPLATE_WORKFLOW).toContain('read `task GROUP`')
- expect(TEMPLATE_WORKFLOW).toContain('read the thread before acting on it')
+ expect(workflow).toContain('In a thread others wrote in, read it before acting')
// Task #2963: an unnamed post no longer reaches the PM, so the workflow says where verdicts and results go.
- expect(TEMPLATE_WORKFLOW).toContain('A verdict goes to the Engineer by name\n (--to, or a reply to its request); a result reaches the PM through status, never by a post to the PM.')
+ expect(workflow).toContain('3. Findings and verdicts go straight to the Engineer by name (--to, or a reply), never through the PM.')
+ expect(workflow).toContain('the Engineer sets its task done with the pull request and the evidence: that status is how the PM hears, once.')
+ expect(workflow).toContain('No agent sends the PM any other message besides a task that needs a person')
// Ken, 2026-11-02 (from openharness): a two-review task gets two review steps; the Engineer picks its Reviewers
// itself instead of asking the PM (since 2026-11-03, when the pull request is ready).
- expect(TEMPLATE_WORKFLOW).toContain('A task that needs two\n reviews gets two review steps.')
- expect(TEMPLATE_WORKFLOW).toContain('never one that\n worked on this task itself')
+ expect(workflow).toContain('A task that needs two reviews gets two review steps.')
+ expect(workflow).toContain('never one that worked on this task,')
// Ken, 2026-11-02: an Engineer posted "review and test pass" and then set Done, two messages for one event.
- expect(TEMPLATE_WORKFLOW).toContain('that status is how the PM hears, once')
- expect(TEMPLATE_WORKFLOW).toContain('The PM reads `mine` for progress, not `status`.')
- expect(TEMPLATE_WORKFLOW.split('\n').filter(l => /^\d+\. /.test(l))).toHaveLength(11)
+ expect(workflow).toContain('that status is how the PM hears, once')
+ expect(workflow).toContain('run `mine`; the PM reads it for progress, not `status`.')
+ expect(TEMPLATE_WORKFLOW.split('\n').filter(l => /^\d+\. /.test(l))).toHaveLength(10)
})
// Ken, 2026-11-03: in two days agents sent openharness's PM 850 direct messages, 73% of them answers to the PM's own
// 1,437 (review asks, status asks, thanks), and Reviewers sent their verdicts to the PM instead of the Engineer.
@@ -69,7 +85,8 @@ describe('the built-in template', () => {
const flat = (text: string) => text.replace(/\s+/g, ' ')
const reviewer = flat(INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('### Reviewer'), INSTRUCTIONS_TEMPLATE.indexOf('### Tester')))
expect(reviewer).toContain('It gives its verdict once it has read the code and never waits for CI to finish: the PM checks CI before it merges (Workflow 5).')
- expect(flat(TEMPLATE_WORKFLOW)).toContain('A verdict asking for changes, a Tester\'s too, is a message to the Engineer with the line "Ready to merge: No" or "Ready to merge: With fixes"')
+ expect(flat(TEMPLATE_WORKFLOW)).toContain('Findings and verdicts go straight to the Engineer by name')
+ expect(flat(TEMPLATE_WORKFLOW)).toContain('A verdict asking for changes, a Tester\'s too, carries the line "Ready to merge: No" or "Ready to merge: With fixes"')
})
it('keeps messages to and from the PM to work, answers and people, with verdicts on the step', () => {
const flat = (text: string) => text.replace(/\s+/g, ' ')
@@ -79,10 +96,10 @@ describe('the built-in template', () => {
expect(role('Reviewer', 'Tester')).toContain('Gives its verdict to the Engineer and records it as its step\'s result')
expect(flat(INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('### Tester')))).toContain('Gives its verdict to the Engineer and records it as its step\'s result')
const workflow = flat(TEMPLATE_WORKFLOW)
- expect(workflow).toContain('The PM neither adds these steps nor asks anyone to review or test a task\'s pull request')
- expect(workflow).toContain('3. Findings go straight to the Engineer, never through the PM.')
+ expect(workflow).toContain('The PM neither adds these steps nor asks anyone to review or test')
+ expect(workflow).toContain('3. Findings and verdicts go straight to the Engineer by name')
expect(workflow).toContain('No agent sends the PM any other message besides a task that needs a person (Workflow 6) or the answer to a question the PM asked')
- expect(workflow).toContain('no acknowledgement such as "understood", "on it" or "stopped"')
+ expect(workflow).toContain('no progress notes and no acknowledgements')
})
// Audit M3 (task #2021): the host marks a message an agent of another account wrote; the Engineer and the Reviewer are told
// what that means, in the words the CLI's built-in texts use (cli/src/lib/swarmTools.ts).
@@ -97,9 +114,9 @@ describe('the built-in template', () => {
// about quota now; an account any project's PM runs on keeps 20% of its weekly quota for that PM, and every other is used.
it('keeps 20% of the week on an account any project\'s PM runs on, uses every other account, and asks no one', () => {
const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\s+/g, ' ')
- expect(routing).toContain('2. An account any project\'s PM runs on (this project\'s or another\'s; the route notes it) keeps 20% of its weekly quota for that PM: below 20% left it takes no new work and idle agents there are not reused. Above that it is used like any other account.')
+ expect(routing).toContain('2. An account any project\'s PM runs on keeps 20% of its weekly quota for that PM: below that it takes no new work and its idle agents are not reused; above it, like any other account.')
expect(routing).toContain('- Nobody is asked about quota or whose account to use. When no account fits, the work waits for the soonest reset, and the task says so.')
- expect(routing).toContain('or whose account is a PM\'s and falls below 20%, hands its pushed branch')
+ expect(routing).toContain('or is a PM\'s and falls below 20%, hands its pushed branch')
for (const gone of ['share of its week left', 'owner asks for', 'takes work as any other account does']) expect(routing).not.toContain(gone)
})
@@ -110,7 +127,7 @@ describe('the built-in template', () => {
expect(INSTRUCTIONS_TEMPLATE).toContain('Review and test run in parallel')
expect(INSTRUCTIONS_TEMPLATE).toContain('Does not read the code')
// Ken, 2026-11-02: small work on Sonnet or Sol, big work on Opus or Astra, nothing below high effort.
- expect(INSTRUCTIONS_TEMPLATE).toContain('Claude Sonnet at high effort or Codex GPT-6.1 Sol at high effort')
+ expect(INSTRUCTIONS_TEMPLATE.replace(/\s+/g, ' ')).toContain('Claude Sonnet or Codex GPT-6.1 Sol, both at high effort; big, hard or risky work on Claude Opus at high effort or Codex GPT-6 Astra at xhigh')
expect(INSTRUCTIONS_TEMPLATE).toContain('No agent runs below high effort, and none on Claude Haiku.')
expect(INSTRUCTIONS_TEMPLATE).not.toContain('No Engineer runs on Claude Sonnet')
expect(INSTRUCTIONS_TEMPLATE).toMatch(/Low-risk docs, tests and fixtures go to a model on the Swarm's grid first/)
@@ -119,8 +136,8 @@ describe('the built-in template', () => {
const pm = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('### PM'), INSTRUCTIONS_TEMPLATE.indexOf('### Engineer'))
expect(pm).toContain('nightly routing proposal')
// Ken, 2026-11-02: a PM copied old workflow lines into a brief; the workflow lives in the instructions only.
- expect(pm).toContain('It copies no workflow into a brief')
- expect(pm).toContain('- When the project owner answers Yes to a nightly routing proposal, writes its line into Routing, naming the owner as who asked.')
+ expect(INSTRUCTIONS_TEMPLATE.replace(/\s+/g, ' ')).toContain('The PM opens it with a brief: goal, "Done when", changes, constraints, checks, never workflow (these instructions win).')
+ expect(pm.replace(/\s+/g, ' ')).toContain('- When the project owner answers Yes to a nightly routing proposal, writes its line into Routing, naming the owner as who asked.')
expect(Buffer.byteLength(INSTRUCTIONS_TEMPLATE)).toBeLessThan(16_384)
})
// Ken, 11-05: openharness's and lamp's PMs own their projects; what made them owners is every new project's PM's now.
@@ -128,7 +145,7 @@ describe('the built-in template', () => {
const pm = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('### PM'), INSTRUCTIONS_TEMPLATE.indexOf('### Engineer')).replace(/\s+/g, ' ')
for (const line of [
'Owns the project: its roadmap, deadlines, progress and quality, and every task and pull request.',
- 'Decides, doesn\'t ask: it decides and reports the result.',
+ 'Decides, doesn\'t ask: it decides and reports the result, asking a person only where a rule names them or for a step only they can do',
'It never asks "OK to build?", "should I" or "do you want", and never offers a choice it can make itself: it picks, says why in one line, and goes.',
'Says no by default to new features and growing scope: it answers each request Accept, Reshape, Later (and when) or No, naming why.',
'Thinks fast and slow:',
@@ -136,16 +153,33 @@ describe('the built-in template', () => {
'Sets deadlines for today, in hours.',
'Each hour it finds where work waits and fixes the slowest step itself, without waiting to be told.',
'A status gives the goal, what must exist today, and what is stuck (owner and time); never what is already done.',
- 'Before answering a message in a task, reads that task\'s state and its latest messages.',
- 'Links every issue and pull request number it names.',
]) expect(pm).toContain(line)
+ // Its mechanics live in the Workflow, where they leave the PM's section room (River, review of #3220).
+ const workflow = TEMPLATE_WORKFLOW.replace(/\s+/g, ' ')
+ expect(workflow).toContain('Before answering a message in a task, the PM reads that task\'s state and its latest messages.')
+ expect(workflow).toContain('It tags a person only to answer them or when they must act (an agent\'s owner, to have it act), and links every issue and pull request number it names.')
// Shared lines name no person (instructions attribution).
expect(pm).not.toMatch(/\((Ken|Dee|Leo)[,)]/)
})
+ // Review of #3220 (#3392): trimming the template to its budget cut wording, never a rule's meaning.
+ it('keeps every rule\'s meaning through the trim to its size budget', () => {
+ const flat = INSTRUCTIONS_TEMPLATE.replace(/\s+/g, ' ')
+ const pm = flat.slice(flat.indexOf('### PM'), flat.indexOf('### Engineer'))
+ for (const line of [
+ 'works without pause toward the goal with every machine and agent the Swarm has',
+ 'it decides and reports the result',
+ 'A fix to what ships, a security fix, or crew speed or reliability is a yes at once.',
+ 'what is cheap to undo it decides in the same turn; what is hard to undo (a feature, deleting data, production writes, spending money) after reading the evidence',
+ ]) expect(pm).toContain(line)
+ expect(flat).toContain('a mid-strength model is enough for most testing.')
+ expect(flat).toContain('Any member may change it, directly or through the PM, who says what it changed.')
+ expect(flat).toContain('go straight to the Engineer by name (--to, or a reply), never through the PM.')
+ })
it('keeps a Reviewer or Tester working on its step while the Engineer fixes findings: blocked is for a person', () => {
// Ken, 2026-11-02: 47 of a day's "Stuck" statuses reached the PM from Reviewers waiting on the Engineer's fixes.
const workflow = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Workflow'), INSTRUCTIONS_TEMPLATE.indexOf('## Routing'))
+ .replace(/\s+/g, ' ')
expect(workflow).toContain('While the Engineer fixes them, the Reviewer or Tester stays Working on its step')
expect(workflow).toContain('blocked and needs_human are only for something a person must do.')
})
@@ -169,25 +203,20 @@ describe('the built-in template', () => {
expect(routing).toContain('keeps 20% of its weekly quota for that PM')
expect(routing).toContain('Every other account is used while it has weekly quota left: the one resetting soonest first')
expect(routing).toContain('An idle agent is reused only between candidates equal so far')
- expect(routing).toContain('"Idle" or "first in the list" is not a reason.')
+ expect(routing).toContain('never "idle" or "first in the list".')
expect(routing).toContain('hands its pushed branch to an agent on another account.')
expect(routing).toContain('Urgent work (production down, security) ignores quota.')
for (const gone of ['share per day', '5-hour', 'Engineers move to the next model', 'Max 20x']) expect(routing).not.toContain(gone)
})
- it('says the route lists every engine on every machine with its weekly quota, which the PM orders by itself', () => {
- // Ken, 2026-11-03: the route's rows now carry each account's quota, and no account is cut from them.
- const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\n +/g, ' ')
- expect(routing).toContain('- The route lists the best new agent and the best idle agent of every engine on every machine, each with its quota: '
- + 'fits or short, weekly quota left and reset time.')
- expect(routing).not.toContain('The route\'s lines show')
- })
- it('says the route ranks nothing and picks nothing, and every start from it gives the rule that chose it', () => {
+ it('says the PM applies the order itself, from a route that ranks nothing, and every start gives the rule that chose it', () => {
// Task #2901 (Ken, 2026-11-04): PMs took the route's first line, nearly always Opus or Astra, against this order and quota.
- // The route now lists by machine name and names no pick; the reason goes with the start or assignment.
- const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\n +/g, ' ')
- expect(routing).toContain('It lists them by machine name, with no ranking and no pick: the PM applies this order itself.')
- expect(routing).toContain('Every start or assignment from a route gives as its reason the rule above that chose it: urgency, context or a '
- + 'machine the work needs where it departs from the order. "Idle" or "first in the list" is not a reason.')
+ // The route lists by machine name with each account's quota (Ken, 2026-11-03) and names no pick; the reason goes with the
+ // start or assignment. What the route's rows show is the route's own to say: the template keeps the rule (#3392).
+ const routing = INSTRUCTIONS_TEMPLATE.slice(INSTRUCTIONS_TEMPLATE.indexOf('## Routing')).replace(/\s+/g, ' ')
+ // Any start or assignment, the Engineer's of its Reviewer and Tester too (review of #3220).
+ expect(routing).toContain('- The PM applies this order itself (the route ranks nothing). Each start or assignment gives as its reason the rule '
+ + 'that chose it, or the urgency, context or machine need that departs from it; never "idle" or "first in the list".')
+ expect(routing).not.toContain('The route\'s lines show')
for (const gone of ['Its order does not rank by quota', 'Picking against it needs a reason in the route\'s override']) expect(routing).not.toContain(gone)
})
})
@@ -337,9 +366,11 @@ describe('instructions.save', () => {
it('keeps a document within 64 KB and a summary on one line, and saves nothing new for the same text', () => {
const f = fixture()
expect(() => f.run(save(1, 'x'.repeat(65_537)))).toThrow()
- expect(f.run(save(1, 'é'.repeat(32_768))).result.revision).toBe(2)
+ // Within 64 KB, a document is still held to its size budget (#3392): 'é' is two bytes, so 3,072 of them are 6 KB of core.
+ expect(() => f.run(save(1, 'é'.repeat(32_768)))).toThrow(expect.objectContaining({ code: 'INSTRUCTIONS_OVER_BUDGET' }))
+ expect(f.run(save(1, 'é'.repeat(3_072))).result.revision).toBe(2)
expect(() => f.run(save(2, 'Other.', { summary: 'two\nlines' }))).toThrow()
- const same = f.run(save(2, 'é'.repeat(32_768)))
+ const same = f.run(save(2, 'é'.repeat(3_072)))
expect(same.result).toMatchObject({ revision: 2, unchanged: true })
expect(same.instructions).toBeUndefined()
expect(same.messages).toEqual([])
@@ -679,3 +710,132 @@ describe('a project on the template', () => {
expect(row.instructions).toMatchObject({ revision: 0, hash: FIRST_INSTRUCTIONS.instructionsHash })
})
})
+
+// Task #3392 (anh Dee, 11-05, decision 5): the instructions have a size budget by section: core 6 KB, each role section 2 KB,
+// people notes 3 KB, 20 KB in all. A save that makes a part bigger than its budget is refused with the sizes.
+describe('an instructions save keeps to the size budget', () => {
+ const save = (baseRevision: number, text: string): Command =>
+ ({ type: 'instructions.save', projectId: 'lead', baseRevision, text, summary: 'Changed the instructions' })
+ const stored = (text: string, revision = 1) => ({ instructions: { revision, text, at: 500 } })
+ /** [n] distinct lines of about 100 bytes, each too short to read as a repeat of another. */
+ const lines = (n: number, tag: string) => Array.from({ length: n }, (_, i) => `- ${tag}${i} ${'x'.repeat(90)}`)
+ const doc = ({ core = 10, pm = 5, notes = 0 }: { core?: number; pm?: number; notes?: number }) => [
+ '# Project instructions', '', '## Roles', '', '### PM', '', ...lines(pm, 'pm'), '', '## Workflow', '', ...lines(core, 'core'),
+ ...notes ? ['', '## People notes', '', ...lines(notes, 'note')] : []].join('\n')
+ const refusal = (run: () => unknown) => {
+ try { run() } catch (error) { return error as { code: string; status: number; message: string; details: { parts: unknown[] } } }
+ throw new Error('the save went through')
+ }
+
+ it('refuses a save whose core grows past 6 KB, naming its size and budget', () => {
+ const f = fixture()
+ const refused = refusal(() => f.run(save(1, doc({ core: 70 })), owner, stored(doc({}))))
+ expect(refused).toMatchObject({ code: 'INSTRUCTIONS_OVER_BUDGET', status: 409, details: { parts: [{ part: 'core', budget: 6144 }] } })
+ expect(refused.message).toMatch(/Core: 6\.\d KB of 6 KB/)
+ expect(f.state.projects![0]).toMatchObject({ instructionsRevision: 1 })
+ })
+
+ it('refuses a role section past 2 KB, people notes past 3 KB, and a document past 20 KB', () => {
+ const f = fixture()
+ expect(refusal(() => f.run(save(1, doc({ pm: 25 })), owner, stored(doc({}))))).toMatchObject({ details: { parts: [{ part: 'role PM', budget: 2048 }] } })
+ expect(refusal(() => f.run(save(1, doc({ notes: 35 })), owner, stored(doc({}))))).toMatchObject({ details: { parts: [{ part: 'people notes', budget: 3072 }] } })
+ // Every part within its own budget, the whole past 20 KB: twelve roles of 1.8 KB each.
+ const roles = Array.from({ length: 12 }, (_, r) => ['', `### Role${r}`, '', ...lines(18, `r${r}-`)]).flat()
+ const wide = ['# Project instructions', '', '## Roles', ...roles].join('\n')
+ const message = refusal(() => f.run(save(1, wide), owner, stored(doc({})))).message
+ expect(message).toMatch(/Whole document: 2\d\.\d KB of 20 KB/)
+ expect(message).not.toContain('Role0')
+ })
+
+ it('lets a part already over budget be saved when it does not grow, and saves within budget', () => {
+ const f = fixture()
+ // Today's documents are over budget: shrinking a part, or leaving it as it was, is the way down.
+ expect(f.run(save(1, doc({ core: 75 })), owner, stored(doc({ core: 80 }))).result.revision).toBe(2)
+ expect(f.run(save(2, doc({ core: 75, pm: 6 })), owner, stored(doc({ core: 75 }), 2)).result.revision).toBe(3)
+ expect(refusal(() => f.run(save(3, doc({ core: 76, pm: 6 })), owner, stored(doc({ core: 75, pm: 6 }), 3))))
+ .toMatchObject({ code: 'INSTRUCTIONS_OVER_BUDGET', message: expect.stringMatching(/was 7\.\d KB/) })
+ expect(f.run(save(3, doc({ core: 20, pm: 6, notes: 10 })), owner, stored(doc({ core: 75, pm: 6 }), 3)).result.revision).toBe(4)
+ })
+})
+
+// Task #3392 (anh Dee, 11-05, decision 5): one restructure save may move every person's rule, word for word with who gave
+// it, into people notes or a role section, the project's rules record, or a code task (its line stays until that merges).
+describe('an instructions save may move a person\'s rule', () => {
+ const save = (baseRevision: number, text: string, extra: Partial<Extract<Command, { type: 'instructions.save' }>> = {}): Command =>
+ ({ type: 'instructions.save', projectId: 'lead', baseRevision, text, summary: 'Restructured', askedBy: 'owner', ...extra })
+ const leo = 'A bug that reaches stable: the previous build is promoted back within the hour and the fix ships the same day (peer, 2026-11-04).'
+ const quiet = 'No releases between 18:00 and 09:00 Vietnam time (owner, 2026-11-02).'
+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')
+ const stored = (text = doc(leo, quiet)) => ({ instructions: { revision: 1, text, at: 500 } })
+ const refusal = (run: () => unknown) => {
+ try { run() } catch (error) { return error as { code: string; message: string; details: { dropped: unknown[] } } }
+ throw new Error('the save went through')
+ }
+ function pm() {
+ const f = fixture()
+ f.invite()
+ const lead = f.add('lead', 'lead', true)
+ return { f, lead }
+ }
+ const PR = 'https://github.com/acme/app/pull/7'
+ /** A code task of the project whose brief carries [line]; [merged]: GitHub, read by the Swarm itself, saw its pull request
+ * merge (store.ts archiveFinished), as no command can say. */
+ function codeTask(f: ReturnType<typeof fixture>, line: string, merged: boolean) {
+ const id = f.run({ type: 'conversation.create', title: 'Release guard', brief: `Goal:\nBlock releases at night.\n\nChanges:\n- ${line}`, checks: [] })
+ .result.conversationId as string
+ const group = f.state.conversations.find(c => c.id === id)!
+ if (merged) group.mergeSeen = { [PR]: 900 }
+ return group
+ }
+
+ it('lets a rule move word for word into people notes', () => {
+ const { f, lead } = pm()
+ const moved = [doc(leo), '', '## People notes', '', `- ${quiet}`].join('\n')
+ expect(f.run(save(1, moved), as(lead), stored()).result.revision).toBe(2)
+ })
+
+ it('lets a rule move into the project\'s rules record, asked for by its person', () => {
+ const { f, lead } = pm()
+ f.state.rules = [{ id: 'r1', projectId: 'lead', rule: { kind: 'preferIdle' }, text: 'No releases between 18:00 and 09:00 Vietnam time.',
+ askedBy: 'owner', askedIn: null, addedBy: 'owner', createdAt: '2026-11-05T00:00:00.000Z' }]
+ expect(f.run(save(1, doc(leo)), as(lead), stored()).result.revision).toBe(2)
+ })
+
+ it('lets a rule move into a code task once it merged, and keeps the line while the task is open, naming it', () => {
+ const { f, lead } = pm()
+ const open = codeTask(f, quiet, false)
+ const refused = refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))
+ expect(refused).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ rule: quiet, people: ['owner'], why: 'waiting',
+ movedTo: `task #${open.number}` }] } })
+ expect(refused.message).toContain(`task #${open.number}`)
+ expect(refused.message).toContain('until it merges')
+ open.mergeSeen = { [PR]: 900 }
+ expect(f.run(save(1, doc(leo)), as(lead), stored()).result.revision).toBe(2)
+ })
+
+ // River, 11-05 (review of #3220): a task's own merge record is any agent's word, with any pull request link. Only the
+ // Swarm's own read of GitHub makes a moved rule's task merged.
+ it('takes no task\'s merge record for a merge: a forged one keeps the line', () => {
+ const { f, lead } = pm()
+ const task = codeTask(f, quiet, false)
+ f.run({ type: 'conversation.merged', conversationId: task.id, pullRequestUrl: PR }, as(lead))
+ expect(f.state.conversations.find(c => c.id === task.id)!.ledger?.mergedAt).toBeDefined()
+ expect(refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))).toMatchObject({ details: { dropped: [{ rule: quiet, why: 'waiting' }] } })
+ // Nor can any command write what the Swarm saw.
+ expect(() => f.run({ type: 'conversation.create', title: 'Forged', brief: `Changes:\n- ${quiet}`, checks: [], mergeSeen: { [PR]: 1 } } as never, as(lead))).toThrow()
+ })
+
+ it('still refuses a real drop, a move without who gave it, and a move into a cancelled task, saying how a rule may move', () => {
+ const { f, lead } = pm()
+ const refused = refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))
+ expect(refused).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED', details: { dropped: [{ rule: quiet, why: 'removed' }] } })
+ expect(refused.message).toContain('people notes')
+ expect(refused.message).toContain('rules record')
+ expect(refused.message).toContain('code task')
+ codeTask(f, 'No releases between 18:00 and 09:00 Vietnam time.', true)
+ expect(refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))).toMatchObject({ code: 'INSTRUCTIONS_RULES_DROPPED' })
+ const cancelled = codeTask(f, quiet, false)
+ cancelled.assignment = { status: 'cancelled' } as never
+ expect(refusal(() => f.run(save(1, doc(leo)), as(lead), stored()))).toMatchObject({ details: { dropped: [{ why: 'removed' }] } })
+ })
+})
diff --git a/backend/src/superTabs/instructionsDiff.test.ts b/backend/src/superTabs/instructionsDiff.test.ts
index 1692ec705..9fbb4b6e0 100644
--- a/backend/src/superTabs/instructionsDiff.test.ts
+++ b/backend/src/superTabs/instructionsDiff.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { attributedRules, droppedRules, personKey, repeatedRules } from './instructionsDiff.js'
+import { attributedRules, budgetParts, droppedRules, INSTRUCTIONS_BUDGET, personKey, repeatedRules } from './instructionsDiff.js'
// Task #3151 (Ken, 11-05, from lamp): a PM's tidy from revision 70 to 71 dropped Leo's rule and the "(0xken15, 4 Nov)" of a
// rule it kept, and nothing checked the save.
@@ -160,3 +160,81 @@ describe('repeatedRules', () => {
expect(repeatedRules(base, `${base}\n## Reviewer\n\n${added}\n`)).toEqual([{ added: added.slice(2), existing: 'Decides, never asks the owner to choose (Ken, 2026-11-04).' }])
})
})
+
+// Task #3392 (anh Dee, 11-05, decision 5): the instructions have a size budget by section, so they stay small.
+describe('budgetParts', () => {
+ const size = (text: string) => Buffer.byteLength(text)
+ const parts = (text: string) => Object.fromEntries(budgetParts(text).map(p => [p.part, p.bytes]))
+
+ it('splits core, each role section under Roles, and people notes, counting UTF-8 bytes', () => {
+ const intro = '# Project instructions\n\nHow this project works.\n\n## Roles\n\nEvery agent reads its role.\n\n'
+ const pm = '### PM\n\n- Opens one task per request.\n\n'
+ const engineer = '### Engineer\n\n- Builds it test first, chị Hà\u2019s way.\n\n'
+ const workflow = '## Workflow\n\n1. One request is one task.\n\n'
+ const notes = '## People notes\n\n- Ken likes short replies (Ken, 11-05).\n'
+ const doc = intro + pm + engineer + workflow + notes
+ expect(parts(doc)).toEqual({ core: size(intro + workflow), 'role PM': size(pm), 'role Engineer': size(engineer), 'people notes': size(notes), total: size(doc) })
+ expect(budgetParts(doc).find(p => p.part === 'role PM')!.budget).toBe(INSTRUCTIONS_BUDGET.role)
+ expect(INSTRUCTIONS_BUDGET).toEqual({ core: 6 * 1024, role: 2 * 1024, people: 3 * 1024, total: 20 * 1024 })
+ })
+
+ it('reads a heading inside a fenced block as text, and a ### outside Roles as core', () => {
+ const doc = '# P\n\n## Roles\n\n### PM\n\n```\n## Workflow\n```\n\n## Routing\n\n### Models\n\n- Opus builds.\n'
+ const pm = '### PM\n\n```\n## Workflow\n```\n\n'
+ expect(parts(doc)).toEqual({ core: size(doc) - size(pm), 'role PM': size(pm), total: size(doc) })
+ })
+})
+
+// Task #3392 (anh Dee, 11-05, decision 5): a person's rule may move instead of being kept in place, word for word with who
+// gave it: into people notes or a role section, into the project's rules record, or into a code task once it merges.
+describe('droppedRules with moved rules', () => {
+ const leo = 'A bug that reaches stable: the previous build is promoted back within the hour and the fix ships the same day (Leo, 2026-11-04).'
+ const quiet = 'No releases between 18:00 and 09:00 Vietnam time (Ken, 2026-11-02).'
+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')
+ const brief = (line: string) => `Goal:\nShip the release guard.\n\nChanges:\n- ${line}\n\nConstraints:\nNone.\n\nOwns:\n- backend/`
+ const task = (line: string, open = false) => ({ text: brief(line), people: [], where: 'task #12', open })
+
+ it('keeps a rule moved word for word into people notes or a role section', () => {
+ const moved = ['# Project instructions', '', '## Roles', '', '### PM', '', `- ${quiet}`, '', '## People notes', '', `- ${leo}`].join('\n')
+ expect(droppedRules(doc(leo, quiet), moved)).toEqual([])
+ })
+
+ it('keeps a rule moved into the rules record, by who asked for it or by its attribution', () => {
+ const record = (text: string, people: string[]) => ({ text, people, where: 'the rules record', open: false })
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [record('No releases between 18:00 and 09:00 Vietnam time.', ['ken'])])).toEqual([])
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [record(quiet, [])])).toEqual([])
+ // Asked for by someone else, its person is lost: still dropped.
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [record('No releases between 18:00 and 09:00 Vietnam time.', ['dee'])]))
+ .toEqual([expect.objectContaining({ people: ['Ken'], why: 'removed' })])
+ })
+
+ it('keeps a rule moved into a code task once that task merged; an open one keeps the line, naming the task', () => {
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [task(quiet)])).toEqual([])
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [task(quiet, true)]))
+ .toEqual([{ text: quiet, people: ['Ken'], why: 'waiting', movedTo: 'task #12' }])
+ })
+
+ it('still drops a rule that moved without who gave it, or changed on the way', () => {
+ const unattributed = 'No releases between 18:00 and 09:00 Vietnam time.'
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [task(unattributed)])).toEqual([expect.objectContaining({ why: 'removed' })])
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [task(quiet.replace('18:00', '20:00'))])).toEqual([expect.objectContaining({ why: 'removed' })])
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [task(quiet.replace('time', 'time, unless the PM judges it urgent'))]))
+ .toEqual([expect.objectContaining({ why: 'removed' })])
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [task(quiet.replace('No releases', 'Releases'))])).toEqual([expect.objectContaining({ why: 'removed' })])
+ // A real drop, with nowhere it moved to.
+ expect(droppedRules(doc(leo, quiet), doc(leo), personKey, [])).toEqual([expect.objectContaining({ people: ['Ken'], why: 'removed' })])
+ })
+})
+
+describe('droppedRules with a rule in several places', () => {
+ const quiet = 'No releases between 18:00 and 09:00 Vietnam time (Ken, 2026-11-02).'
+ const doc = (...rules: string[]) => ['# Project instructions', '', '## Rules', '', ...rules.map(r => `- ${r}`)].join('\n')
+ // Review of #3220: an open task listed first hid the rules record that keeps the same rule.
+ it('counts a rule kept when any place keeps it, an open task listed first or not', () => {
+ const open = { text: `Changes:\n- ${quiet}`, people: [], where: 'task #12', open: true }
+ const record = { text: quiet, people: [], where: 'the rules record', open: false }
+ expect(droppedRules(doc(quiet), doc(), personKey, [open, record])).toEqual([])
+ expect(droppedRules(doc(quiet), doc(), personKey, [open, { ...open, where: 'task #13' }]))
+ .toEqual([expect.objectContaining({ why: 'waiting', movedTo: 'task #12' })])
+ })
+})
diff --git a/backend/src/superTabs/instructionsDiff.ts b/backend/src/superTabs/instructionsDiff.ts
index 7325c4f55..fe34e8f9e 100644
--- a/backend/src/superTabs/instructionsDiff.ts
+++ b/backend/src/superTabs/instructionsDiff.ts
@@ -76,8 +76,15 @@ export interface AttributedRule {
people: string[]
}
/** How a save lost a rule: gone, kept without who gave it, or changed so its meaning may differ (a negation, a number, a
- * condition, more than a rewording). The last is "can't tell", refused like the others. */
-export interface DroppedRule extends AttributedRule { why: 'removed' | 'unattributed' | 'changed' }
+ * condition, more than a rewording). The last is "can't tell", refused like the others. `waiting`: moved into a code task
+ * that has not merged, named by `movedTo` (#3392): its line stays until that task merges. */
+export interface DroppedRule extends AttributedRule { why: 'removed' | 'unattributed' | 'changed' | 'waiting'; movedTo?: string }
+/**
+ * A place outside the document a person's rule may move to (task #3392, anh Dee 11-05, decision 5): the project's rules record
+ * or a code task, its words as written there. `people`: who is known to have given what it holds, as `identify` names them
+ * (a rules record's asker), besides any attribution in its words. `open`: a code task not merged yet, which keeps the line.
+ */
+export interface RulePlace { text: string; people: readonly string[]; where: string; open: boolean }
const MONTH = '(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?'
const DATE = `(?:\\d{4}-\\d{1,2}-\\d{1,2}|\\d{1,2}[-/]\\d{1,2}(?:[-/]\\d{2,4})?|\\d{1,2}\\s+${MONTH}(?:\\s+\\d{4})?|${MONTH}\\s+\\d{1,2}(?:,?\\s+\\d{4})?)`
@@ -172,7 +179,8 @@ const contains = (whole: readonly string[], part: readonly string[]) => occurren
* same people. [identify] says who a written name is (commands.ts: a member's id), so "0xken15" and "Ken" can be one person;
* by default a name is itself, honorifics aside.
*/
-export function droppedRules(before: string, after: string, identify: (name: string) => string = personKey): DroppedRule[] {
+export function droppedRules(before: string, after: string, identify: (name: string) => string = personKey,
+ places: readonly RulePlace[] = []): DroppedRule[] {
const next = items(after).map(i => segments(i.text))
const flat = next.flat()
const ids = new Map<Segment, Set<string>>(flat.map(s => [s, new Set(s.people.map(identify))]))
@@ -180,19 +188,33 @@ export function droppedRules(before: string, after: string, identify: (name: str
// A segment says only what the rules it names said: each of its words lies in one of them, word for word and in order, or
// joins two of them (a merge). Anything else (a word changed, moved, added: "unless the PM judges it urgent") is a change
// nobody can tell is harmless, so every rule in it counts as changed (review of #3112).
- const faithful = new Map<Segment, boolean>()
- const isFaithful = (s: Segment) => faithful.get(s) ?? faithful.set(s, (() => {
+ const faithfulTo = (s: Segment, who: Set<string>) => {
const covered = s.seq.map(word => JOINERS.has(word))
for (const { rule, people } of rules) {
- if (!rule.seq.length || !people.every(p => ids.get(s)!.has(p))) continue
+ if (!rule.seq.length || !people.every(p => who.has(p))) continue
for (const at of occurrences(s.seq, rule.seq)) for (let k = 0; k < rule.seq.length; k++) covered[at + k] = true
}
return covered.every(Boolean)
- })()).get(s)!
+ }
+ const faithful = new Map<Segment, boolean>()
+ const isFaithful = (s: Segment) => faithful.get(s) ?? faithful.set(s, faithfulTo(s, ids.get(s)!)).get(s)!
+ // Each place's segments with who gave them: its attributions and the people it is known to hold. A rule moved there is
+ // held to the same test as in the document: its words in order, with its people, and nothing else said in that segment.
+ // Read only when a rule is not kept in the document, and a place that keeps it for good (the rules record, a merged task)
+ // wins over an open task that holds it too (review of #3220).
+ let moves: { place: RulePlace; at: { s: Segment; who: Set<string> }[] }[] | undefined
+ const movedTo = (rule: Segment, people: string[]) => {
+ moves ??= [...places].sort((a, b) => Number(a.open) - Number(b.open)).map(place => ({ place, at: items(place.text)
+ .flatMap(i => segments(i.text)).map(s => ({ s, who: new Set([...s.people.map(identify), ...place.people]) })) }))
+ return moves.find(({ at }) => at.some(({ s, who }) => people.every(p => who.has(p)) && contains(s.seq, rule.seq) && faithfulTo(s, who)))?.place
+ }
const dropped: DroppedRule[] = []
for (const { rule, people } of rules) {
const theirs = flat.filter(s => people.every(p => ids.get(s)!.has(p)))
if (theirs.some(s => contains(s.seq, rule.seq) && isFaithful(s))) continue
+ const place = rule.seq.length ? movedTo(rule, people) : undefined
+ if (place && !place.open) continue
+ if (place) { dropped.push({ text: rule.text, people: rule.people, why: 'waiting', movedTo: place.where }); continue }
// Its words still there, in order: with its people that is a change of meaning, without them a lost attribution.
const kept = next.find(item => contains(item.flatMap(s => s.seq), rule.seq))
const why = kept ? (kept.some(s => theirs.includes(s)) ? 'changed' : 'unattributed')
@@ -223,6 +245,42 @@ export function keptIn(after: string): (text: string) => boolean {
}
}
+/**
+ * The size budget of a project's instructions, in UTF-8 bytes (task #3392, anh Dee 11-05, decision 5: these instructions stay
+ * as small as possible). Core is everything outside the role sections and people notes. One object, passed in, so a project's
+ * own numbers can replace it.
+ */
+export const INSTRUCTIONS_BUDGET = { core: 6 * 1024, role: 2 * 1024, people: 3 * 1024, total: 20 * 1024 } as const
+export type InstructionsBudget = { readonly [K in keyof typeof INSTRUCTIONS_BUDGET]: number }
+/** One part of a document and its size: `core`, `role <heading>` (a ### under ## Roles), `people notes` (a ## People notes
+ * section) or `total` (the whole document). */
+export interface BudgetPart { part: string; bytes: number; budget: number }
+
+const ROLES = /^roles$/i
+const PEOPLE_NOTES = /^people notes$/i
+
+/** [text]'s budget parts in document order, `total` last. A line belongs to the section its heading opened; a heading in a
+ * fenced block is text. */
+export function budgetParts(text: string, budget: InstructionsBudget = INSTRUCTIONS_BUDGET): BudgetPart[] {
+ const bytes = new Map<string, number>([['core', 0]])
+ let h2 = '', h3 = '', fenced = false
+ const lines = text.split('\n')
+ lines.forEach((line, i) => {
+ if (FENCE.test(line)) fenced = !fenced
+ else if (!fenced) {
+ const heading = HEADING.exec(line)
+ if (heading?.[1]!.length === 2) { h2 = heading[2]!.trim(); h3 = '' }
+ else if (heading?.[1]!.length === 1) { h2 = ''; h3 = '' }
+ else if (heading?.[1]!.length === 3) h3 = heading[2]!.trim()
+ }
+ const part = PEOPLE_NOTES.test(h2) ? 'people notes' : ROLES.test(h2) && h3 ? `role ${h3}` : 'core'
+ bytes.set(part, (bytes.get(part) ?? 0) + Buffer.byteLength(line) + (i < lines.length - 1 ? 1 : 0))
+ })
+ const of = (part: string) => part === 'core' ? budget.core : part === 'people notes' ? budget.people : budget.role
+ return [...[...bytes].filter(([part, n]) => n || part === 'core').map(([part, n]) => ({ part, bytes: n, budget: of(part) })),
+ { part: 'total', bytes: Buffer.byteLength(text), budget: budget.total }]
+}
+
/** A line [after] adds that repeats one it keeps: the added line's words and the existing line's, as the document has them. */
export interface RepeatedRule { added: string; existing: string }
/** Fewest content words of a line that can be a repeat: a short line ("Tests pass.") says too little to be the same rule. */
diff --git a/backend/src/superTabs/instructionsTemplate.ts b/backend/src/superTabs/instructionsTemplate.ts
index 12b41ad04..a72c02f61 100644
--- a/backend/src/superTabs/instructionsTemplate.ts
+++ b/backend/src/superTabs/instructionsTemplate.ts
@@ -12,38 +12,24 @@ export const TEMPLATE_ROLES = `## Roles
### PM
-- Talks with people in the project chat and finds out what they want.
-- Owns the project: its roadmap, deadlines, progress and quality, and every task and pull request. It works without pause
- toward the project's goal, with every machine and agent the Swarm has.
-- Decides, doesn't ask: it decides and reports the result. It asks a person only where a rule names that person, or for
- a step only that person can do (a sign-in, adding a machine), and then with its recommendation and a default it applies
- at a stated time. It never asks "OK to build?", "should I" or "do you want", and never offers a choice it can make
- itself: it picks, says why in one line, and goes.
+- Owns the project: its roadmap, deadlines, progress and quality, and every task and pull request. It learns in the
+ project chat what people want and works without pause toward the goal with every machine and agent the Swarm has.
+- Decides, doesn't ask: it decides and reports the result, asking a person only where a rule names them or for a step
+ only they can do, with its recommendation and a default it applies at a set time. It never asks "OK to build?",
+ "should I" or "do you want", and never offers a choice it can make itself: it picks, says why in one line, and goes.
- Says no by default to new features and growing scope: it answers each request Accept, Reshape, Later (and when) or No,
- naming why. A fix to what already ships, a security fix, and anything that makes the crew faster or more reliable is a
- yes at once.
-- Thinks fast and slow: fast for what is cheap to undo (fixes, merges, routing, unblocking an agent), decided in the same
- turn; slow for what is hard to undo (a new feature, deleting data, production writes, spending money): it reads the
- evidence, writes down its reasoning, then decides.
+ naming why. A fix to what ships, a security fix, or crew speed or reliability is a yes at once.
+- Thinks fast and slow: what is cheap to undo it decides in the same turn; what is hard to undo (a feature, deleting
+ data, production writes, spending money) after reading the evidence and writing its reasoning.
- A bug that breaks what already ships, or stops people's or agents' work, is a hotfix at once; it never waits for
someone to say "urgent".
-- Sets deadlines for today, in hours. Work over an hour late moves to another agent, and blockers (reads, tests, lifting
- a hold) run in parallel, never one after another.
+- Sets deadlines for today, in hours. Work over an hour late moves to another agent; blockers run in parallel.
- Each hour it finds where work waits and fixes the slowest step itself, without waiting to be told.
- A status gives the goal, what must exist today, and what is stuck (owner and time); never what is already done.
-- Before answering a message in a task, reads that task's state and its latest messages. It tags a person only when
- answering them or when they must act; a message asking an agent to act tags the person who owns that agent.
-- Links every issue and pull request number it names.
-- Turns each request into a task with a goal and a "Done when".
-- Writes a task's brief as what to build: goal, changes, constraints, checks, and the Reviewer and Tester it names.
- It copies no workflow into a brief: how agents work is in these instructions, and a brief line that disagrees with them
- is wrong.
-- Starts and assigns agents as these instructions say.
- Messages an agent only to give it work, to answer its question, or to hand it a lost agent's work. It asks no agent
- for status, since \`mine\` and the task's thread show it, and sends no thanks or acknowledgements.
-- Keeps these instructions up to date when a member asks, and says what it changed.
-- When the project owner answers Yes to a nightly routing proposal, writes its line into Routing, naming the owner as who asked.
-- Merges work that passed review and test, and reports progress.
+ for status, and thanks none.
+- When the project owner answers Yes to a nightly routing proposal, writes its line into Routing, naming the owner as
+ who asked.
- Does not write the code itself.
### Engineer
@@ -66,91 +52,82 @@ export const TEMPLATE_ROLES = `## Roles
### Tester
- Does not read the code.
-- Takes the pull request's branch, builds it and runs it as a user would, where the change runs: Desktop on a Mac; the CLI
- on a Mac and on a Linux machine; the web in a browser; the phone app in a simulator; firmware on the device plugged into
- a machine.
+- Takes the pull request's branch, builds it and runs it as a user would, where the change runs: Desktop on a Mac; the
+ CLI on a Mac and on a Linux machine; the web in a browser; the phone app in a simulator; firmware on the device
+ plugged into a machine.
- Follows the task's "Done when".
-- Gives its verdict to the Engineer and records it as its step's result (Workflows 3 and 4), with evidence:
- screenshots, logs, the commands it ran. For a failure, it gives the steps that reproduce it.`
+- Gives its verdict to the Engineer and records it as its step's result (Workflows 3 and 4), with evidence: screenshots,
+ logs, the commands it ran. For a failure, it gives the steps that reproduce it.`
export const TEMPLATE_WORKFLOW = `## Workflow
-1. One request is one task. The PM opens it with its goal and "Done when" and assigns an Engineer. It says which
- reviews and tests the task needs (two reviews, a test on a Mac, on a device), and names a Reviewer or Tester only
- when the task needs that one agent; when no agent can take a role, it starts one.
- That is the PM's part until the Engineer reports. The PM opens no task to hold, batch, triage or list work: that
- goes in its notes or the project chat.
+1. One request is one task. The PM opens it with a brief: goal, "Done when", changes, constraints, checks, never
+ workflow (these instructions win). It says which reviews and tests the task needs and assigns an Engineer. It names a
+ Reviewer or Tester only when the task needs that one agent, and starts one when no agent can take a role. That is the
+ PM's part until the Engineer reports. The PM opens no task to hold, batch, triage or list work: that goes in its
+ notes or the project chat.
2. When the pull request is ready, the server opens its review steps from the files it changes and gives each to a free
agent of the project that never worked on this task, as strong as its Engineer and with no verdict at that head: a
- review, two security reviews for sign-in, tokens, encryption, access, the Buddy guard, device links and deletion, and a
- test step where the change runs. A step nobody was free for waits open, and the PM hears it once.
- Where it opened none, the Engineer adds a review step to its task, and a test step when the change is
- something a user sees or uses (screens, CLI commands, install and release, sign-in, connections between machines,
- devices). It picks each Reviewer and Tester then, by Routing's order (the one the PM named, if any), never one that
- worked on this task itself, assigns them and messages them directly.
+ review, two security reviews for sign-in, tokens, encryption, access, the Buddy guard, device links and deletion, and
+ a test step where the change runs. A step nobody was free for waits open, and the PM hears it once. Where it opened
+ none, the Engineer adds a review step to its task, and a test step when users see or use the change (screens, CLI
+ commands, install and release, sign-in, machine links, devices). It picks each Reviewer and Tester then, by Routing's
+ order (the one the PM named, if any), never one that worked on this task, assigns and messages them directly.
Review and test run in parallel. Refactors, docs and test-only changes get a review only. A task that needs two
reviews gets two review steps. If an assignment is refused, the Engineer asks the PM once, naming the step and the
- agent it picked. The PM neither adds these steps nor asks anyone to review or test a task's pull request: it steps
- in only on that question, or when a step's agent is lost.
-3. Findings go straight to the Engineer, never through the PM. The Engineer fixes them and asks the same Reviewer or
- Tester again in the same step; it adds no new step for a second round.
- While the Engineer fixes them, the Reviewer or Tester stays Working on its step:
- blocked and needs_human are only for something a person must do. A verdict asking for changes, a Tester's too, is a
- message to the Engineer with the line "Ready to merge: No" or "Ready to merge: With fixes": that line, sent to the
- Engineer, is how the Swarm keeps the step with its agent while the Engineer fixes, instead of moving it after 30
- quiet minutes.
-4. When the review passes, and the test passes where there is one, the Engineer sets its task done with the pull request
- and the evidence in its result: that status is how the PM hears, once. A Reviewer or Tester is heard the same way,
- through its step's result. No agent sends the PM any other message besides a task that needs a person (Workflow 6)
- or the answer to a question the PM asked: no progress notes, no "ready for review", no separate verdict or "done"
- message, and no acknowledgement such as "understood", "on it" or "stopped". A verdict goes to the Engineer by name
- (--to, or a reply to its request); a result reaches the PM through status, never by a post to the PM.
+ agent it picked. The PM neither adds these steps nor asks anyone to review or test: it steps in only on that
+ question, or when a step's agent is lost.
+3. Findings and verdicts go straight to the Engineer by name (--to, or a reply), never through the PM. The Engineer
+ fixes them and asks the same Reviewer or Tester again in the same step; it adds no new step for a second round. While
+ the Engineer fixes them, the Reviewer or Tester stays Working on its step: blocked and needs_human are only for
+ something a person must do. A verdict asking for changes, a Tester's too, carries the line "Ready to merge: No" or
+ "Ready to merge: With fixes", so the step stays with its agent, not moved after 30 quiet minutes.
+4. When the review, and any test, passes, the Engineer sets its task done with the pull request and the evidence: that
+ status is how the PM hears, once. Reviewers and Testers are heard through their step's result. No agent sends the PM
+ any other message besides a task that needs a person (Workflow 6) or the answer to a question the PM asked: no
+ progress notes and no acknowledgements.
5. The PM checks CI on the pull requests that passed, merges them, and tells the people who asked.
6. A task that needs a person, or a machine that is down, goes to the PM at once, by name.
7. Idle Engineers are stopped. Reviewers and Testers are kept while the work they checked is open.
-8. Before acting after a pause, or when unsure what you are working on, run \`mine\`.
-9. Before saying your work is done, read \`task GROUP\` and check that every check has passed.
-10. In a thread others have written in, read the thread before acting on it, unless the delivery already says enough.
-11. The PM reads \`mine\` for progress, not \`status\`.`
+8. Before acting after a pause, or unsure what you work on, run \`mine\`; the PM reads it for progress, not \`status\`.
+9. Before saying your work is done, read \`task GROUP\` and check every check passed.
+10. In a thread others wrote in, read it before acting, unless the delivery says enough. Before answering a message in a
+ task, the PM reads that task's state and its latest messages. It tags a person only to answer them or when they must
+ act (an agent's owner, to have it act), and links every issue and pull request number it names.`
export const TEMPLATE_ROUTING = `## Routing
-- Small work (a small feature, a fix, docs, tests) runs on
- Claude Sonnet at high effort or Codex GPT-6.1 Sol at high effort, whichever has quota at the better price.
-- Big, hard or risky work runs on Claude Opus at high effort or Codex GPT-6 Astra at xhigh, whichever has quota at the
- better price. No engine is preferred.
+- Small work (a small feature, a fix, docs, tests) runs on Claude Sonnet or Codex GPT-6.1 Sol, both at high effort; big,
+ hard or risky work on Claude Opus at high effort or Codex GPT-6 Astra at xhigh: whichever has quota at the better
+ price, no engine preferred.
- No agent runs below high effort, and none on Claude Haiku.
-- Reviewers run on a model at least as strong as the Engineer's, on either engine, never on a model of the Swarm's grid.
-- Low-risk docs, tests and fixtures go to a model on the Swarm's grid first. After a failed review they move to Sonnet or
- Sol, and after a second to Opus or Astra.
-- A Tester runs on a machine that has what the change needs: a Mac for Desktop, the machine the device is plugged into for
- firmware. The machine comes before the model. A mid-strength model is enough for most testing.
+- Reviewers run on a model at least as strong as the Engineer's, never on the Swarm's grid.
+- Low-risk docs, tests and fixtures go to a model on the Swarm's grid first; after a failed review to Sonnet or Sol,
+ after a second to Opus or Astra.
+- A Tester runs where the change runs (a Mac for Desktop, the device's machine for firmware), machine first; a
+ mid-strength model is enough for most testing.
- Every assignment (an Engineer, a Reviewer, a Tester, an idle agent reused) picks in this order:
- 1. What the work needs: the machine, a model strong enough, a machine not paused.
- 2. An account any project's PM runs on (this project's or another's; the route notes it) keeps 20% of its weekly
- quota for that PM: below 20% left it takes no new work and idle agents there are not reused. Above that it is used like any
- other account.
- 3. Every other account is used while it has weekly quota left: the one resetting soonest first, then the one with
- the most left.
- 4. An idle agent is reused only between candidates equal so far, except the same Reviewer for its next round and
- work that follows straight on from what the agent just did.
+ 1. What the work needs: the machine (not paused) and a model strong enough.
+ 2. An account any project's PM runs on keeps 20% of its weekly quota for that PM: below that it takes no new work and
+ its idle agents are not reused; above it, like any other account.
+ 3. Every other account is used while it has weekly quota left: the one resetting soonest first, then the one with most
+ left.
+ 4. An idle agent is reused only between candidates equal so far, except the same Reviewer for its next round and work
+ that follows straight on from the agent's last.
5. Between equals, the machine with fewer agents working. Then price.
- Nobody is asked about quota or whose account to use. When no account fits, the work waits for the soonest reset, and
the task says so.
-- The route lists the best new agent and the best idle agent of every engine on every machine, each with its quota:
- fits or short, weekly quota left and reset time. It lists them by machine name, with no ranking and no pick: the PM
- applies this order itself. Every start or assignment from a route gives as its reason the rule above that chose it:
- urgency, context or a machine the work needs where it departs from the order. "Idle" or "first in the list" is not a
- reason.
-- An agent whose account runs out of weekly quota mid-task, or whose account is a PM's and falls below 20%, hands its
- pushed branch to an agent on another account.
+- The PM applies this order itself (the route ranks nothing). Each start or assignment gives as its reason the rule that
+ chose it, or the urgency, context or machine need that departs from it; never "idle" or "first in the list".
+- An agent whose account runs out of weekly quota mid-task, or is a PM's and falls below 20%, hands its pushed branch to
+ an agent on another account.
- Urgent work (production down, security) ignores quota.`
/** The title and the opening words, which say what the document is for. */
export const TEMPLATE_INTRO = `# Project instructions
-These instructions say how this project works: its roles, its workflow and its routing. Every member may change them,
-directly or by asking the PM. Every agent works by them and reads its own role's part.`
+How this project works. Any member may change it, directly or through the PM, who says what it changed. Every agent
+works by it and reads its own role's part.`
/** The whole template: what a new project's document starts as. */
export const INSTRUCTIONS_TEMPLATE = `${TEMPLATE_INTRO}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index c69d15f92..db22e85fc 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -400,6 +400,10 @@ export interface Conversation {
heardAt?: number
/** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */
pullRequestUrls?: string[]
+ /** Its pull requests the Swarm itself read as merged on GitHub in its project's repository, by link: when it read them
+ * (store.ts archiveFinished). Unlike the merge record (conversation.merged, any agent's word), no command writes it; it
+ * is what makes a person's rule moved into this task leave the instructions (ruleGuard.ts, #3392). */
+ mergeSeen?: Record<string, number>
/** What its Engineer was already told of each linked pull request, newest first (pullRequestEvents.ts): absent until read. */
pullRequestEvents?: Record<string, string[]>
/** Its messages drawn as live cards: its task and each linked pull request (cards.ts). Absent until its first card. */
@@ -1100,7 +1104,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
visible.conversations = visible.conversations.filter(c => canReadGroup(state, actor, c))
// The status card is read exactly by those who read the project chat (projects.ts SwarmProject.status); without the chat
// loaded, by nobody.
- visible.projects = visible.projects.map(p => {
+ visible.projects = visible.projects.map(({ owed: _owed, ...p }) => {
+ // What the PM owes is its host's alone (timeChecks.ts owedAsk): it may name a message in someone's private chat.
if (p.status === undefined) return p
const chat = state.conversations.find(c => c.id === p.leadConversationId)
if (chat && canReadGroup(state, actor, chat)) return p
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 72a732b1b..8982617db 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -55,6 +55,7 @@ const conversation: Required<Conversation> = {
ledger: {},
liveness: { state: 'quiet', why: 'silent', since: 1 },
lostAttempt: { id: 'w', agentId: 'a' },
+ mergeSeen: {},
messageSeq: 0,
notBefore: '2026-12-04',
number: 1,
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index f0e0bf939..1776fb4ab 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -80,6 +80,7 @@ export const GROUP_FIELDS = {
'ledger',
'liveness',
'lostAttempt',
+ 'mergeSeen',
'messageSeq',
'notBefore',
'number',
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index c6f928076..cc09edd18 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -56,6 +56,10 @@ export interface SwarmProject {
* the daily tidy was last asked, and the instructions revision its last save made; `tidyPending`: asked, and no save has
* followed yet (pmSchedule.ts tidyRequest; tasks #3022, #3151). */
schedule?: { lastSlot: number; wakeId?: string; heardAt?: number; tidiedOn?: string; tidiedRevision?: number; tidyPending?: boolean }
+ /** The oldest message a person sent its PM in the last day that the PM has not answered, and when it was sent, as the worker's
+ * time checks last found it (timeChecks.ts owedAsk); absent when it owes none. Its PM's host restarts a PM that hangs while it
+ * owes one (task #3385). Readers never get it: it may name a message in a person's private chat with the PM. */
+ owed?: { messageId: string; since: number }
/** Its release list (releases.ts, task #3405): merged tasks waiting for a release, each component's last verified release
* and its open release step. Written by the server alone; readers never get it. */
releases?: import('./releases.js').ReleaseLedger
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index d1d8037ba..b27ca4500 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -309,6 +309,9 @@ export interface HostAgentRow {
* reads again when it moves, as it does for `revision`. */
builtInHash?: string } | null
lead: boolean
+ /** A PM's own row: the oldest message a person sent it that it has not answered (timeChecks.ts owedAsk), and how long it may
+ * owe one while it hangs before its host restarts it. Null on every other row, and while it owes nothing. */
+ owed: { messageId: string; since: number; restartAfterMs: number } | null
/** New: lets the host decide what it may read without a full Swarm read. */
leadsConversationId: string | null
/** The conversation this agent leads, when it is a project's Product Manager. */
diff --git a/backend/src/superTabs/read/hostRows.ts b/backend/src/superTabs/read/hostRows.ts
index c58027b97..c2a3319a3 100644
--- a/backend/src/superTabs/read/hostRows.ts
+++ b/backend/src/superTabs/read/hostRows.ts
@@ -12,6 +12,7 @@ import type { HostAgentRow, HostPool, HostRosterRow, HostTabRows } from './contr
import { hostEtag } from './hostEtag.js'
import { coordinatorNameOf, FIRST_INSTRUCTIONS, instructionsHash, roleNameOf } from '../instructions.js'
import { PM_SCHEDULE_TEXT } from '../pmSchedule.js'
+import { PM_RESTART_AFTER_MS } from '../timeChecks.js'
/** The built-in PM schedule's hash, once: it changes only with a backend release. */
const BUILT_IN_HASH = instructionsHash(PM_SCHEDULE_TEXT)
@@ -98,6 +99,8 @@ function agentRow(tabId: string, state: SuperTabState, machineId: string, user:
coordinatorName: coordinatorNameOf(home), ...ledProject(state, target.id)?.id === home.id ? { builtInHash: BUILT_IN_HASH } : {} } : null,
...(custom ? { role: chosen && { ...chosen, projectId: custom.id } } : {}),
lead: !!ledProject(state, target.id),
+ // What a PM owes people, and how long it may while it hangs: its host restarts it after that (timeChecks.ts, cli host.ts).
+ owed: (() => { const owed = ledProject(state, target.id)?.owed; return owed ? { ...owed, restartAfterMs: PM_RESTART_AFTER_MS } : null })(),
// Removed (model.ts leadsRemoved); an older CLI still reads the field, so it stays, always empty.
leadsConversationId: null,
// The conversation it leads: the chat its host rebuilds its start prompt from when it switches it (cli leadSwitchRequest.ts).
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 0d9106809..e96af0794 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -106,8 +106,8 @@ export function readerView(parts: SwarmParts, actor: Actor, now: number, extras:
const head = Object.fromEntries(HEAD_FIELDS.filter(field => visible[field] !== undefined).map(field => [field, visible[field]])) as HeadView
// Every project names its coordinator; one from before the field reads as the Product Manager (instructions.ts). The built-in
// schedule's slot is the coordinator poll's bookkeeping (pmSchedule.ts), like progress, and so is the release list (releases.ts):
- // no reader shows them.
- if (head.projects) head.projects = head.projects.map(({ progress: _progress, schedule: _schedule, releases: _releases, ...project }) => ({ ...project, coordinatorName: coordinatorNameOf(project) }))
+ // no reader shows them. What the PM owes is its host's alone (timeChecks.ts owedAsk): it may name a message in someone's private chat.
+ if (head.projects) head.projects = head.projects.map(({ progress: _progress, schedule: _schedule, releases: _releases, owed: _owed, ...project }) => ({ ...project, coordinatorName: coordinatorNameOf(project) }))
head.invitations = visible.invitations.filter(i => readable.has(i.conversationId))
const projects = new Set((visible.projects ?? []).map(p => p.id)), seen = seenMachineIds(visible), names = swarmUsernames(state)
const buddy = isBuddyReader(state, actor)
diff --git a/backend/src/superTabs/ruleGuard.ts b/backend/src/superTabs/ruleGuard.ts
index c6b21f585..69cc31460 100644
--- a/backend/src/superTabs/ruleGuard.ts
+++ b/backend/src/superTabs/ruleGuard.ts
@@ -5,9 +5,10 @@
* dropped rule makes the save or wrote a message approving it that the save names. Who a person is comes from the sender or
* the stored message's author, never the caller's word (askedBy). The approver is then told in one private line.
*/
-import { attributedRules, droppedRules, ITEM_CHARS, keptIn, MAX_REPEATS, personKey, removedItems, repeatedRules, type DroppedRule } from './instructionsDiff.js'
-import { fail, type Author, type SuperTabState } from './model.js'
-import { canReadProject, type SwarmProject } from './projects.js'
+import { attributedRules, budgetParts, droppedRules, INSTRUCTIONS_BUDGET, ITEM_CHARS, keptIn, MAX_REPEATS, personKey, removedItems, repeatedRules,
+ type DroppedRule, type InstructionsBudget, type RulePlace } from './instructionsDiff.js'
+import { fail, type Author, type Conversation, type SuperTabState } from './model.js'
+import { canReadProject, projectRules, type SwarmProject } from './projects.js'
import { isSwarmBuddyChat } from './buddies.js'
import { swarmUsernames } from './usernames.js'
@@ -35,6 +36,24 @@ const WHY: Record<DroppedRule['why'], string> = {
removed: 'removed',
unattributed: 'kept without who gave it',
changed: 'changed beyond a rewording, so its meaning may differ',
+ waiting: 'moved to a code task the Swarm has not seen merged on GitHub',
+}
+
+/**
+ * Where this project's people's rules may have moved (task #3392): its rules record, by who asked for each, and its code
+ * tasks (a task's brief; not a step, a chat or a task cancelled unmerged), a task counting once the Swarm read its pull
+ * request merged on GitHub. A task that went
+ * quiet is in the state only when the save names it (tasks), which loads it.
+ */
+function rulePlaces(state: SuperTabState, project: SwarmProject): RulePlace[] {
+ // Merged only as the Swarm itself read it on GitHub (Conversation.mergeSeen), never by the task's own merge record, which
+ // any agent of the project writes with any link (River, review of #3220).
+ const seenMerged = (c: Conversation) => Object.keys(c.mergeSeen ?? {}).length > 0
+ const records = projectRules(state, project.id).map(r => ({ text: r.text, people: [r.askedBy], where: 'the rules record', open: false }))
+ const tasks = state.conversations.filter(c => (c.projectId ?? 'lead') === project.id && c.id !== project.leadConversationId && !c.kind
+ && !c.reviewOf && !c.step && !c.audience && c.brief && (seenMerged(c) || c.assignment?.status !== 'cancelled'))
+ .map(c => ({ text: c.brief, people: [], where: c.number ? `task #${c.number}` : `task "${c.title}"`, open: !seenMerged(c) }))
+ return [...records, ...tasks]
}
/**
@@ -50,7 +69,7 @@ export function allowedDrops(state: SuperTabState, project: SwarmProject, before
const membersOf = new Map<string, string[]>()
const members = (name: string) => membersOf.get(name) ?? membersOf.set(name, membersNamed(state, name)).get(name)!
// One written person for comparing revisions: the members they are, so "0xken15" and "Ken" are one.
- const dropped = droppedRules(before, after, name => members(name).sort().join(',') || `?${personKey(name)}`)
+ const dropped = droppedRules(before, after, name => members(name).sort().join(',') || `?${personKey(name)}`, rulePlaces(state, project))
if (!dropped.length) return { told, rules: [] }
const saver = sender.kind === 'person' ? sender.id : undefined
// Written after the revision this save replaces, in a conversation of this project: an old "thanks" approves nothing (review
@@ -73,11 +92,15 @@ export function allowedDrops(state: SuperTabState, project: SwarmProject, before
if (refused.length) {
const unknown = (rule: DroppedRule) => rule.people.filter(name => !members(name).length)
fail('INSTRUCTIONS_RULES_DROPPED', [
- 'Not saved: this drops rules people gave. Keep each rule and who gave it, or ask that person and name their own message '
- + 'approving the change (approvals). Never drop or weaken a person\'s rule on your own judgment, even one you think cannot be done.',
- ...refused.map(rule => `- "${cut(rule.text)}" (${rule.people.join(', ')}): ${WHY[rule.why]}.`
+ 'Not saved: this drops rules people gave. Keep each rule and who gave it, or move it word for word with who gave it: into '
+ + 'people notes or its role section, into the project\'s rules record, or into a code task, whose line stays until the '
+ + 'Swarm sees that task\'s pull request merged on GitHub (name a quiet one in tasks). Otherwise ask that person and name their own message approving the change '
+ + '(approvals). Never drop or weaken a person\'s rule on your own judgment, even one you think cannot be done.',
+ ...refused.map(rule => `- "${cut(rule.text)}" (${rule.people.join(', ')}): ${WHY[rule.why]}`
+ + (rule.movedTo ? ` (${rule.movedTo}): keep its line until it merges.` : '.')
+ (unknown(rule).length ? ` ${unknown(rule).join(', ')} is no member here, so the project's owner decides.` : '')),
- ].join('\n'), 409, { dropped: refused.map(rule => ({ rule: rule.text, people: rule.people, why: rule.why })) })
+ ].join('\n'), 409, { dropped: refused.map(rule => ({ rule: rule.text, people: rule.people, why: rule.why,
+ ...rule.movedTo ? { movedTo: rule.movedTo } : {} })) })
}
return { told, rules: dropped }
}
@@ -99,6 +122,29 @@ export function refuseRepeats(before: string, after: string): void {
].join('\n'), 409, { repeated: shown })
}
+const kb = (bytes: number) => `${(bytes / 1024).toFixed(1)} KB`
+const partName = (part: string) => part === 'core' ? 'Core' : part === 'people notes' ? 'People notes' : part === 'total' ? 'Whole document'
+ : `Role section ${part.slice('role '.length)}`
+
+/**
+ * Refuses a save that makes a part of the instructions bigger than its budget (task #3392, anh Dee 11-05, decision 5): core,
+ * each role section, people notes and the whole document (instructionsDiff.ts budgetParts), each named with its size, its budget
+ * and its size before. A part over budget already, as documents were when this came in, may be saved smaller or unchanged:
+ * that is the way down, never blocked.
+ */
+export function refuseOverBudget(before: string, after: string, budget: InstructionsBudget = INSTRUCTIONS_BUDGET): void {
+ const was = new Map(budgetParts(before, budget).map(p => [p.part, p.bytes]))
+ const over = budgetParts(after, budget).filter(p => p.bytes > p.budget && p.bytes > (was.get(p.part) ?? 0))
+ .map(p => ({ ...p, before: was.get(p.part) ?? 0 }))
+ if (!over.length) return
+ fail('INSTRUCTIONS_OVER_BUDGET', [
+ 'Not saved: this makes the instructions bigger than their budget. Make it smaller: a rule the Swarm can check becomes a code '
+ + 'task instead of a line; a person\'s rule moves word for word, with who gave it, into people notes or its role section; a '
+ + 'step or date that passed goes. A part already over budget may be saved as long as it does not grow.',
+ ...over.map(p => `- ${partName(p.part)}: ${kb(p.bytes)} of ${kb(p.budget).replace('.0 KB', ' KB')} (was ${kb(p.before)}).`),
+ ].join('\n'), 409, { parts: over })
+}
+
/** Lines one revision's History keeps (River, 11-05): a rewrite of the whole document lists its first 500. */
export const MAX_DROPPED_LINES = 500
/** How the coordinator sorted a line it dropped (pmSchedule.ts, the daily tidy): kept elsewhere with who said it, or a step
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 303dece4d..4b44062bc 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -71,6 +71,7 @@ import { RefusalMemory } from './dispatchRefusals.js'
import { candidatesFor, DISPATCH_RULES, dispatchPlan, freeCrew, laneCapacity, openTasks, pinBuilder, pullRequestPin, roundOf, type Skip } from './dispatch.js'
import { failRefusedStarts, judgedMachines, loseTasks, nextLossAt, recordTaskState, sweepForLead, sweepLiveness, SWEEP_EVERY_MS, unpurgedNotice } from './liveness.js'
import { endedReply, taskLineChats } from './taskLine.js'
+import { owedAsk } from './timeChecks.js'
import { settleReleases, type ReleaseFacts, type ReleaseRules, type SettledReleases } from './releases.js'
import { archivable, archiveLine, archiveWaitsFor, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests, type SettledPullRequest } from './tidy.js'
import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'
@@ -223,7 +224,9 @@ function namedFor(command: Command): Named {
const field = (key: string) => (command as Record<string, unknown>)[key] as string | undefined
const groupIds = [field('conversationId'), command.type === 'agent.start' ? command.request.conversationId : undefined,
command.type === 'conversation.create' ? command.reviewOf : undefined,
- 'askedIn' in command ? command.askedIn?.conversationId : undefined].filter((id): id is string => !!id)
+ 'askedIn' in command ? command.askedIn?.conversationId : undefined,
+ // The code tasks an instructions save's rules moved into, merged ones gone quiet included (ruleGuard.ts; #3392).
+ ...command.type === 'instructions.save' ? command.tasks ?? [] : []].filter((id): id is string => !!id)
// Deleting a project or changing who reads it reaches every one of its groups, dormant ones too: their terminal
// contexts are revoked from the groups the command loaded (native.ts revokeNativeContexts).
return { groupIds, startIds: has('startId') ? [field('startId')!] : [],
@@ -4363,8 +4366,6 @@ export class SuperTabStore {
asked = await waitingInProject(tx, tabId, led.id)
for (const id of [...finished.map(g => g.key), ...asked.map(d => d.conversationId)]) groupIds.add(id)
}
- // A task its sweep may lose says Stuck in its project chat's thread (taskLine.ts endedReply, task #2693).
- for (const id of taskLineChats(loaded.state)) groupIds.add(id)
// One load for both: a second would drop the first's groups.
if (groupIds.size) loaded = await this.ensure(tx, loaded, { groupIds: [...groupIds] })
const state = cloneData(loaded.state)
@@ -4374,12 +4375,8 @@ export class SuperTabStore {
}
author(state, await this.actor(tx, user, state, agentId), true)
const target = agent(state, agentId)
- // A Lead's poll runs the time checks (liveness.ts): lost work wakes it in this same poll.
- const written = ledProject(state, agentId) ? sweepForLead(state, this.now()) : []
- // The coordinator's poll tells it of its project's idle agents (tidy.ts): it is where what waits for each agent is known.
- // It reads no asleep group: only loaded groups' active work keeps an agent from being idle (project instructions, phase 4).
- if (led) written.push(...idleNotices(state, led.id, this.now(), new Set((await tx.superTabDelivery.findMany({
- where: { tabId, status: { in: [...OPEN_DELIVERY] } }, select: { agentId: true }, distinct: ['agentId'] })).map(d => d.agentId))))
+ // The time checks and idle notices run in the backend worker (runTimeChecks), so they go on while this poll does not.
+ const written: MessageDraft[] = []
// Before the update request, which may carry them. Same rules as a listed delivery; a refused row ends as a refused one does.
const { notices, refused } = await this.releasableNotices(tx, state, target, release)
const update = projectUpdateRequest(state, target, this.now())
@@ -5015,6 +5012,52 @@ export class SuperTabStore {
})
}
+ /**
+ * The Swarm's time checks, run by the backend worker every 30 s (timeChecks.ts): lost and stalled work and failed starts
+ * (liveness.ts sweepForLead), then each project's idle agents (tidy.ts idleNotices), written as each project's PM to its PM.
+ * They ran on the PM's own poll before, so a PM that hung stopped them too (task #3385: five people's asks waited 3 to 10
+ * hours). Whatever they find is recorded in this same write, so a second run, or one racing it, finds nothing new. The
+ * messages written.
+ */
+ async runTimeChecks(tabId: string): Promise<number> {
+ return transaction(this.db, async tx => {
+ const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
+ if (!row || row.deletedAt || row.format !== 2) return 0
+ let loaded = await loadRow(tx, requireParts(row), {})
+ // A task its sweep may lose says Stuck in its project chat's thread (taskLine.ts endedReply, task #2693).
+ const chats = taskLineChats(loaded.state)
+ if (chats.length) loaded = await this.ensure(tx, loaded, { groupIds: chats })
+ const state = cloneData(loaded.state), now = this.now()
+ const written = sweepForLead(state, now)
+ // What waits for each agent: an agent with a delivery open is not idle. Only loaded groups' active work keeps an agent
+ // from being idle (project instructions, phase 4).
+ const projects = projectsOf(state).filter(p => state.conversations.find(c => c.id === p.leadConversationId)?.leadId)
+ if (projects.length) {
+ const busy = new Set((await tx.superTabDelivery.findMany({ where: { tabId, status: { in: [...OPEN_DELIVERY] } },
+ select: { agentId: true }, distinct: ['agentId'] })).map(d => d.agentId))
+ for (const project of projects) written.push(...idleNotices(state, project.id, now, busy))
+ }
+ // 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)) {
+ const pm = state.conversations.find(c => c.id === project.leadConversationId)?.leadId
+ const owed = pm ? await owedAsk(tx, tabId, pm, now) : null
+ if (owed?.messageId === project.owed?.messageId && owed?.since === project.owed?.since) continue
+ if (owed) project.owed = owed
+ else delete project.owed
+ }
+ // It frees the agents whose task the checks just lost, as the PM's poll did.
+ await this.endRuns(tx, tabId, loaded.state, state)
+ await recordAttempts(tx, tabId, loaded.state, state, now)
+ await recordEvidence(tx, tabId, loaded.state, state, now)
+ const sequences = numberMessages(state, written, now)
+ // 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)
+ return written.length
+ })
+ }
+
/**
* The merge train's candidates (mergeTrain/run.ts): unarchived tasks (not steps), done ones included, active in the last
* [TRAIN_QUIET_MS] that link a pull request, at most [limit], the most recently active first; grouped by project, each with
@@ -5125,6 +5168,12 @@ export class SuperTabStore {
// Only the group it reviews as the pass read it: one this write did not load would hide its open pull requests.
const review = !finished && !!reviewOf && group.reviewOf === reviewOf && reviewClosable(state, group, now) && read(reviewPullRequests(state, group))
if (!finished && !review) return false
+ // What GitHub said merged in its project's repository, as this read saw it: what a person's rule moved into this task
+ // waits for (ruleGuard.ts rulePlaces, #3392). A link elsewhere, or a step's, is not this task's merge.
+ const repositoryUrl = groupProject(state, group).repository?.repositoryUrl
+ const merged = finished && githubRepository(repositoryUrl) ? Object.keys(checked)
+ .filter(url => checked[url] === 'merged' && projectPullRequestUrl(url, repositoryUrl) !== null) : []
+ if (merged.length) group.mergeSeen = { ...group.mergeSeen, ...Object.fromEntries(merged.map(url => [url, now])) }
// Its work is over: a decision still waiting there waits no more (Dee, 10-31), as when the work ended by a command.
await withdrawIn(tx, tabId, [groupId], now)
group.archived = true
diff --git a/backend/src/superTabs/timeChecks.ts b/backend/src/superTabs/timeChecks.ts
new file mode 100644
index 000000000..b2724adc3
--- /dev/null
+++ b/backend/src/superTabs/timeChecks.ts
@@ -0,0 +1,108 @@
+// The Swarm's time checks run in the singleton worker (task #3385, anh Dee's Swarm redesign, 11-05): lost and stalled work,
+// failed starts and idle agents are found and told to each project's PM whether or not the PM is up. They ran only on the
+// PM's own poll before: on 11-05 a hung PM left five people's asks unanswered for 3 to 10 hours and the board showed nothing
+// working. A machine's report still runs the loss checks too (liveness.ts sweepLiveness); what both find is recorded in the
+// Swarm's own write, so each notice is written once whichever runs first.
+import type { PrismaClient } from '@prisma/client'
+import { SWEEP_EVERY_MS } from './liveness.js'
+import type { SuperTabStore } from './store.js'
+import { logger } from '../utils/logger.js'
+
+/** How long a PM may owe a person an answer while it hangs before its host restarts it (cli superTabs/host.ts). Sent in the
+ * PM's host row, so the server sets it, not each host. */
+export const PM_RESTART_AFTER_MS = 20 * 60_000
+/** An ask older than this is not owed any more: one the PM settled some other way (a reaction, a thread) never holds a restart
+ * for good. */
+export const OWED_REACH_MS = 24 * 3_600_000
+/** A delivery to the PM not answered yet: still to type, typed, or typed and confirmed. */
+const UNANSWERED = ['queued', 'claimed', 'uncertain', 'delivered', 'confirmed']
+
+/** The oldest message a person sent [agentId] in the last [OWED_REACH_MS] that it has not answered, by when its delivery was
+ * written. One read on `[tabId, agentId, status, createdAt]`: a plain `$match`, as Prisma sends `in` as `$expr` (backend AGENTS.md 3). */
+export async function owedAsk(db: Pick<PrismaClient, 'superTabDelivery'>, tabId: string, agentId: string, now: number): Promise<{ messageId: string; since: number } | null> {
+ const [row] = await db.superTabDelivery.aggregateRaw({ pipeline: [
+ { $match: { tabId, agentId, status: { $in: UNANSWERED }, createdAt: { $gte: { $date: new Date(now - OWED_REACH_MS).toISOString() } }, authorKind: 'person' } },
+ { $sort: { createdAt: 1 } },
+ { $limit: 1 },
+ { $project: { _id: 0, messageId: 1, createdAt: 1 } },
+ ] }) as unknown as Array<{ messageId: string; createdAt: { $date: string } | string }>
+ if (!row) return null
+ const at = typeof row.createdAt === 'string' ? row.createdAt : row.createdAt.$date
+ return { messageId: row.messageId, since: Date.parse(at) }
+}
+
+/** A Swarm with no conversation active this long has no work for the checks: its stalls were told long ago. */
+export const TIME_CHECK_QUIET_MS = 7 * 24 * 3_600_000
+/** The most Swarms a pass checks, the most recently active first (ENGINEERING.md 4: no read grows without a bound). */
+export const TIME_CHECK_SWARMS = 200
+/** A Swarm whose groups show no activity since its last check is checked again only this often (ENGINEERING.md 4: a timer that
+ * wakes while nothing changed is a defect). Its stalls (30 minutes) and idle agents (15) are still told within minutes of
+ * falling due; a lost task's machine reports run the loss checks every 30 s anyway (liveness.ts sweepLiveness). */
+export const QUIET_CHECK_MS = 5 * 60_000
+
+/** The Swarms to check: those with a conversation awake and active in the last [TIME_CHECK_QUIET_MS], newest first. On the
+ * `[dormant, lastActivityAt]` group index; a deleted Swarm is left to `runTimeChecks`, which reads its row anyway. */
+export async function timeCheckSwarms(db: PrismaClient, now: number, limit = TIME_CHECK_SWARMS): Promise<string[]> {
+ return (await timeCheckCandidates(db, now, limit)).map(row => row.tabId)
+}
+
+/** The same Swarms, each with its groups' latest activity, which says whether anything moved there since the last pass. */
+async function timeCheckCandidates(db: PrismaClient, now: number, limit: number): Promise<Array<{ tabId: string; at: string }>> {
+ const rows = await db.swarmGroup.aggregateRaw({ pipeline: [
+ { $match: { dormant: false, lastActivityAt: { $gte: { $date: new Date(now - TIME_CHECK_QUIET_MS).toISOString() } } } },
+ { $group: { _id: '$tabId', at: { $max: '$lastActivityAt' } } },
+ { $sort: { at: -1 } },
+ { $limit: limit },
+ ] }) as unknown as Array<{ _id: string; at: { $date: string } | string }>
+ return rows.map(row => ({ tabId: row._id, at: typeof row.at === 'string' ? row.at : JSON.stringify(row.at) }))
+}
+
+/** Per Swarm, its activity and when the pass last checked it: the worker's memory, gone with it (the next pass checks all). */
+export type TimeCheckMemory = Map<string, { at: string; checkedAt: number }>
+
+/** One pass: each Swarm's checks in its own write, for a Swarm whose activity moved since [seen] last checked it, or that it has
+ * not checked for QUIET_CHECK_MS. One Swarm's failure is logged and skips that Swarm alone, and it is checked again next pass. */
+export async function runTimeCheckPass(db: PrismaClient, store: Pick<SuperTabStore, 'runTimeChecks'>, now: number, limit = TIME_CHECK_SWARMS,
+ seen: TimeCheckMemory = new Map()) {
+ const rows = await timeCheckCandidates(db, now, limit)
+ const pass = { swarms: rows.length, checked: 0, written: 0, failed: 0 }
+ const listed = new Set(rows.map(row => row.tabId))
+ for (const tabId of seen.keys()) if (!listed.has(tabId)) seen.delete(tabId)
+ for (const { tabId, at } of rows) {
+ const last = seen.get(tabId)
+ if (last && last.at === at && now - last.checkedAt < QUIET_CHECK_MS) continue
+ pass.checked++
+ try {
+ pass.written += await store.runTimeChecks(tabId)
+ seen.set(tabId, { at, checkedAt: now })
+ } catch (error) {
+ pass.failed++
+ logger.warn('[swarm-time-checks] Swarm skipped', { tabId, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ return pass
+}
+
+/** Runs the pass every [everyMs] in the singleton worker, one at a time. A pass longer than its interval says so: the first
+ * sign the checks no longer keep up. */
+export function startTimeChecks(db: PrismaClient, store: Pick<SuperTabStore, 'runTimeChecks'>, everyMs = SWEEP_EVERY_MS): () => void {
+ let running = false
+ const seen: TimeCheckMemory = new Map()
+ const run = () => {
+ if (running) return
+ running = true
+ const started = Date.now()
+ void runTimeCheckPass(db, store, started, TIME_CHECK_SWARMS, seen)
+ .then(pass => {
+ const ms = Date.now() - started
+ if (pass.failed || ms > everyMs) logger.warn('[swarm-time-checks] pass', { ...pass, ms })
+ else if (pass.written) logger.info('[swarm-time-checks] pass', { ...pass, ms })
+ })
+ .catch(error => logger.error('[swarm-time-checks] pass failed: stalls, losses and idle agents go untold until one runs', { error: error instanceof Error ? error.message : String(error) }))
+ .finally(() => { running = false })
+ }
+ run()
+ const timer = setInterval(run, everyMs)
+ timer.unref()
+ return () => clearInterval(timer)
+}
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index eee7c5e3c..c97d56c60 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -26,6 +26,7 @@ import { startDeliveryCompaction } from './superTabs/deliveryCompaction.js'
import { startThreadBackfill } from './superTabs/threadBackfill.js'
import { appPullRequests, markFinishedGroups, startSwarmArchive, unknownPullRequests } from './superTabs/archive.js'
import { appPullRequestWatch, startPullRequestWatch } from './superTabs/pullRequestEvents.js'
+import { startTimeChecks } from './superTabs/timeChecks.js'
import { appReleaseReader, startReleaseWatch, unknownReleases } from './superTabs/releaseWatch.js'
import { recordTrainRules, startMergeTrain } from './superTabs/mergeTrain/run.js'
import { teamAccountRequired } from './superTabs/machines.js'
@@ -82,6 +83,7 @@ async function start(): Promise<void> {
let stopLegacyDrop = (): void => {}
let stopArchive = (): void => {}
let stopPullRequestWatch = (): void => {}
+ let stopTimeChecks = (): void => {}
let stopReleaseWatch = (): void => {}
let stopMergeTrain = (): void => {}
let stopDeliveries = (): void => {}
@@ -105,6 +107,7 @@ async function start(): Promise<void> {
stopLegacyDrop()
stopArchive()
stopPullRequestWatch()
+ stopTimeChecks()
stopReleaseWatch()
stopMergeTrain()
stopDeliveries()
@@ -165,6 +168,9 @@ async function start(): Promise<void> {
// GitHub events on an open task's pull request reach its Engineer within a minute (superTabs/pullRequestEvents.ts): only
// with the app, which reads them.
if (githubApp) stopPullRequestWatch = startPullRequestWatch(prisma, swarms, () => appPullRequestWatch(githubApp))
+ // Every 30 s, each active Swarm's time checks: lost and stalled work, failed starts and idle agents, told to its PM whether or
+ // not the PM is up (superTabs/timeChecks.ts, task #3385). The PM's poll ran them before, so a hung PM stopped them.
+ stopTimeChecks = startTimeChecks(prisma, swarms)
// Every 5 minutes, merged tasks a verified release carries are marked released, and inside the release window a due release
// step opens for the project's Integrator (superTabs/releaseWatch.ts, task #3405). Without the app nothing can be verified:
// each pass says so for every project still waiting.
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 5470aca57..095790ea4 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts', 'integration/superTabScorecard.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabReleases.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts', 'integration/crewDispatch.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabProjectRules.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabTimeChecks.test.ts', 'integration/superTabReleases.test.ts', 'integration/superTabReviewSteps.test.ts', 'integration/superTabMergeTrain.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabThumbnails.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts', 'integration/crewDispatch.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 1742a5a16..50b24e4f7 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -5977,6 +5977,128 @@ describe('requests per idle agent and machine per minute while the server pushes
}, 60_000)
})
+// Task #3385 (anh Dee, 11-05): a PM that hung in one turn left five people's asks unanswered for 3 to 10 hours, as the keep-alive
+// reopened only a PM whose session was gone. Its host now restarts it in place once it owes a person an answer past the time the
+// server gives and it has been in one turn that long, or its screen has not changed that long. Never a second PM.
+describe('a PM that stops answering', () => {
+ const MIN = 60_000
+ /** A PM row here that owes the message `m1`, sent at [since]. */
+ const owing = (since: number, restartAfterMs = 20 * MIN) => leadRow({ owed: { messageId: 'm1', since, restartAfterMs } })
+ function stuckFixture(rows: Record<string, unknown>[], activity: 'working' | 'idle' | 'unknown' = 'working') {
+ let release: (() => void) | null = null
+ const restartLead = vi.fn(async (_harnessId: string) => {
+ // The restart relaunches it in its own pane: its session reads as gone until the relaunch is up.
+ t.live(false)
+ await new Promise<void>(resolve => { release = resolve })
+ t.live(true)
+ return { ok: true as const }
+ })
+ const t = lifeFixture(rows, { restartLead })
+ t.live(true)
+ const turns = { activity }
+ t.core.agents.activity = vi.fn(async (ids: string[]) => Object.fromEntries(ids.map(id => [id, turns.activity])))
+ return { ...t, restartLead, turns, finish: () => release?.() }
+ }
+
+ it('restarts a PM stuck in one turn while it owes an ask, once, in place, and never opens a second PM meanwhile', async () => {
+ // The host's clock starts at 0: the ask was sent then, and the PM's turn began.
+ const t = stuckFixture([owing(0)])
+ await t.poll()
+ await t.poll(19 * MIN)
+ expect(t.restartLead).not.toHaveBeenCalled()
+ await t.poll(MIN)
+ expect(t.restartLead).toHaveBeenCalledTimes(1)
+ expect(t.restartLead).toHaveBeenCalledWith('harness')
+ // Its session reads as gone while it relaunches: the keep-alive must not reopen another one beside it.
+ for (let i = 0; i < 6; i++) await t.poll(10_000)
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ t.finish()
+ await t.poll(1_000)
+ // Still in one turn, still owing: once is enough. People see it from here, not a restart loop.
+ for (let i = 0; i < 6; i++) await t.poll(10 * MIN)
+ expect(t.restartLead).toHaveBeenCalledTimes(1)
+ expect(t.keepLeadAlive).not.toHaveBeenCalled()
+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('Restarting the Product Manager'))
+ })
+
+ // SecAlder's security review of #3213, Important 1: a relaunched PM reads idle at its prompt before the owed ask is typed
+ // into it, so a guard that reset on idle restarted it every 21 minutes on the same ask until that ask aged out.
+ it('restarts once per owed ask: the same ask hanging it again after its restart is left to people, a new one is not', async () => {
+ const t = stuckFixture([owing(0)])
+ await t.poll()
+ await t.poll(21 * MIN)
+ expect(t.restartLead).toHaveBeenCalledTimes(1)
+ t.finish()
+ await t.poll(2 * MIN)
+ // Back at its prompt, then the same ask is typed into it and it hangs again.
+ t.turns.activity = 'idle'
+ await t.poll(MIN)
+ t.turns.activity = 'working'
+ for (let i = 0; i < 8; i++) await t.poll(10 * MIN)
+ expect(t.restartLead).toHaveBeenCalledTimes(1)
+ // That ask was answered; a newer one is owed past its time while the PM is still in that turn.
+ t.rows[0] = owing(60 * MIN)
+ t.rows[0]!.owed = { messageId: 'm2', since: 60 * MIN, restartAfterMs: 20 * MIN }
+ await t.poll(MIN)
+ expect(t.restartLead).toHaveBeenCalledTimes(2)
+ })
+
+ // Same review, Minor 2: a reopen that started while the turn was being read must hold the restart.
+ it('does not restart a PM whose reopen began while its turn was being read', async () => {
+ const t = stuckFixture([owing(0)])
+ await t.poll()
+ let read: ((value: Record<string, 'working'>) => void) | null = null
+ t.core.agents.activity = vi.fn(() => new Promise<Record<string, 'working'>>(resolve => { read = resolve }))
+ t.keepLeadAlive.mockImplementation(() => new Promise(() => {}))
+ await t.poll(21 * MIN)
+ expect(read).not.toBeNull()
+ // Its session reads as gone meanwhile: the keep-alive starts reopening it.
+ t.live(false)
+ await t.poll(1_000)
+ expect(t.keepLeadAlive).toHaveBeenCalledTimes(1)
+ t.live(true)
+ read!({ harness: 'working' })
+ await t.poll(0)
+ expect(t.restartLead).not.toHaveBeenCalled()
+ })
+
+ it('restarts a PM whose screen has not changed while it owes an ask, whatever its turn reads', async () => {
+ const t = stuckFixture([owing(0)], 'unknown')
+ // Its terminal shows the same screen on every read.
+ ;(t.core as { superTabs?: unknown }).superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn(),
+ screen: vi.fn(async () => ({ ok: true, text: 'Thinking about the batch', hold: null })) }
+ await t.poll()
+ await t.poll(19 * MIN)
+ expect(t.restartLead).not.toHaveBeenCalled()
+ await t.poll(2 * MIN)
+ expect(t.restartLead).toHaveBeenCalledTimes(1)
+ })
+
+ it('leaves alone an idle PM, a PM that owes nothing or not for long, and one that keeps ending its turns', async () => {
+ const idle = stuckFixture([owing(0)], 'idle')
+ await idle.poll()
+ await idle.poll(60 * MIN)
+ const none = stuckFixture([leadRow({ owed: null })])
+ await none.poll()
+ await none.poll(60 * MIN)
+ // Asked a minute ago: a PM deep in a long turn has not let anyone wait yet.
+ const fresh = stuckFixture([])
+ await fresh.poll()
+ await fresh.poll(30 * MIN)
+ fresh.rows.push(owing(29 * MIN))
+ await fresh.poll(MIN)
+ const busy = stuckFixture([owing(0)])
+ await busy.poll()
+ for (let i = 0; i < 6; i++) {
+ await busy.poll(10 * MIN)
+ busy.turns.activity = 'idle'
+ await busy.poll(MIN)
+ busy.turns.activity = 'working'
+ }
+ for (const t of [idle, none, fresh, busy]) expect(t.restartLead).not.toHaveBeenCalled()
+ })
+})
+
// Task #3398: a crew member the server put to sleep, moved, or whose folder it dropped is closed on its host, once, and never
// kept alive; an awake one is left to the keep-alive.
describe('a crew member at rest', () => {
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index d457308c9..c6128670e 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -214,6 +214,8 @@ export interface SuperTabHostOptions {
machines?: Partial<MachineDeps>
/** What carries out a Buddy's model switch here (superTabs/buddyModel.ts), for a spec. */
buddyModels?: Pick<BuddyModelRequests, 'serve'>
+ /** What restarts a stuck Product Manager in its own pane, on the same session (watchLead), for a spec. */
+ restartLead?: (harnessId: string) => Promise<{ ok: true } | { ok: false; error: string }>
}
const defaultAgentCommand = (core: CoreApi, machineId: string) => agentCommandPrefix(core.daemon, machineId,
@@ -382,6 +384,10 @@ const LEAD_RETRY_MS = 5_000
const LATE_REPLACEMENT_MS = 30 * 60_000
const LEAD_RETRY_MAX_MS = 30 * 60_000
const LEAD_REOPEN_WAIT_MS = 60_000
+/** How often a running Product Manager is checked for a hang (watchLead): its owed ask's time is in minutes. */
+const LEAD_WATCH_MS = 30_000
+/** How long a restart of a stuck Product Manager may take: the relaunch waits on the engine's command and its pane. */
+const LEAD_RESTART_TIMEOUT_MS = 60_000
/** Prod 10-30: acknowledgements failed through two hours of SWARM_BUSY, past the backend's 10-minute claim quiet time
* (backend superTabs/deliverySettle.ts CLAIM_QUIET_MS), so its delivery pass ended claims the agents had in fact received and
* their senders saw Not sent. A typed delivery the backend ended is acknowledged again after 10 s, doubling to 5 minutes, for
@@ -610,6 +616,11 @@ export class SuperTabHost {
private missing = new Map<string, number>()
/** Per Lead harness here: a reopen in progress, its failures, when the next may run, and the reason last logged. */
private readonly keepAlives = new Map<string, { running: boolean; failures: number; retryAt: number; reason?: string }>()
+ /** Per Product Manager harness here (watchLead): when it was last checked, since when it has been in one turn, the owed ask
+ * it was last restarted for, a check or restart in progress, and until when the keep-alive leaves its relaunch be. */
+ private readonly leadWatches = new Map<string, { checkedAt: number; workingSince?: number; restartedFor?: string; checking: boolean
+ restarting: boolean; settleUntil: number }>()
+ private readonly restartLead: (harnessId: string) => Promise<{ ok: true } | { ok: false; error: string }>
/** Per session the backend ends: a close or acknowledgement in progress, how far it got, and when the next try may run. */
private readonly endings = new Map<string, { running: boolean; closed: boolean; acked: boolean; failures: number; retryAt: number
forgotten?: boolean; unforgotten?: string; scrub?: PurgeTarget | null; scrubbed?: true }>()
@@ -644,6 +655,15 @@ export class SuperTabHost {
this.now = options.now ?? Date.now
this.write = options.write ?? writeJournal
this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
+ // Through this machine's own daemon socket, as the apps and the relay recovery ask it (relayRecovery.ts): `agent_restart`
+ // relaunches the agent in its own pane on the same session, so it is never a second one.
+ this.restartLead = options.restartLead ?? (async harnessId => {
+ const local = await openDaemon({ dataDir: core.dataDir, port: core.daemon.port, machineId })
+ try {
+ const answer = await local.request('agent_restart', { agentId: harnessId }, LEAD_RESTART_TIMEOUT_MS)
+ return typeof answer.error === 'string' ? { ok: false, error: answer.error } : { ok: true }
+ } finally { local.close() }
+ })
// Its pickups follow this host's delivery push lease: the server that pushes deliveries also says when a request waits.
this.terminal = new TerminalHost(core, machineId, { now: this.now, log: this.log, pushes: () => this.now() < this.pushUntil,
// Only a Team daemon reads a relay grant: on any other the recovery sees no grant and does nothing.
@@ -1208,6 +1228,7 @@ export class SuperTabHost {
if (row.lead === true || target.agent.switchLanded) {
if (row.lead === true) leads.add(target.agent.harnessId)
this.keepAlive(target.agent.harnessId)
+ if (row.lead === true) this.watchLead(target.agent.harnessId, row.owed)
void this.leadSwitches.serve(target as unknown as SwitchRow).catch(error => this.log(`PM switch: ${error instanceof Error ? error.name : typeof error}`))
} else if (isCrewRow(row)) {
// A project's crew is kept alive as its PM is (task #3397): reopened in place, then told to continue its task.
@@ -1325,6 +1346,7 @@ export class SuperTabHost {
if (this.stopped) return
// A Lead the roster no longer marks (its project deleted) is never reopened again.
for (const [harnessId, state] of this.keepAlives) if (!leads.has(harnessId) && !state.running) this.keepAlives.delete(harnessId)
+ for (const [harnessId, watch] of this.leadWatches) if (!leads.has(harnessId) && !watch.checking && !watch.restarting) this.leadWatches.delete(harnessId)
for (const [key, state] of this.endings) if (!ended.has(key) && !state.running) this.endings.delete(key)
for (const deliveryId of this.unreadable) if (!seen.has(deliveryId)) this.unreadable.delete(deliveryId)
for (const key of this.lists.keys()) if (!running.some(r => `list:${r.tabId}:${r.agent.id}` === key)) this.lists.delete(key)
@@ -1418,6 +1440,10 @@ export class SuperTabHost {
this.keepAlives.set(harnessId, state)
if (state.running) return
const now = this.now()
+ // Being restarted in its own pane (watchLead), its session reads as gone until the relaunch is up: reopening it then would
+ // run a second Product Manager beside it.
+ const watch = this.leadWatches.get(harnessId)
+ if (watch && (watch.restarting || now < watch.settleUntil)) return
// Its owner switched its engine from its pane (leadSwitch.ts), stopping it once the stop went through.
const switched = leadSwitchOf(this.core.dataDir, harnessId)
if (this.core.agents.byAgent(harnessId)) {
@@ -1457,6 +1483,55 @@ export class SuperTabHost {
})().catch(error => failed(error instanceof Error ? error.message : String(error))).finally(() => { state.running = false })
}
+ /**
+ * Task #3385 (anh Dee, 11-05): a Product Manager hung in one turn while five people's asks waited 3 to 10 hours, as the
+ * keep-alive reopens only one whose session is gone. Every LEAD_WATCH_MS, a running one that owes a person an answer
+ * past [owed]'s `restartAfterMs` (the server's number, backend timeChecks.ts), while it has been in one turn that long or its
+ * screen has not changed that long, is restarted in its own pane on the same session: never a second one, and the keep-alive
+ * leaves it be until its relaunch is up. Once per owed ask: a relaunched PM reads idle at its prompt before that ask is typed
+ * into it, so one the same ask hangs again is left to people, never restarted in a loop until the ask ages out (security
+ * review of #3213); a newer ask owed past its time may restart it again. Nothing during an engine switch or a reopen, checked
+ * again right before the restart, as either may begin while its turn is read.
+ */
+ private watchLead(harnessId: string, owed: unknown): void {
+ const watch = this.leadWatches.get(harnessId) ?? { checkedAt: -Infinity, checking: false, restarting: false, settleUntil: -Infinity }
+ this.leadWatches.set(harnessId, watch)
+ const now = this.now()
+ if (watch.checking || watch.restarting || now - watch.checkedAt < LEAD_WATCH_MS) return
+ // Not while its session is gone, a reopen runs or its engine is being switched: those are the keep-alive's and the switch's.
+ const heldElsewhere = () => !this.core.agents.byAgent(harnessId) || !!this.keepAlives.get(harnessId)?.running || !!leadSwitchOf(this.core.dataDir, harnessId)
+ if (heldElsewhere()) return
+ watch.checkedAt = now
+ watch.checking = true
+ const ask = object(owed)
+ const due = identifier(ask.messageId) && typeof ask.since === 'number' && Number.isFinite(ask.since)
+ && typeof ask.restartAfterMs === 'number' && ask.restartAfterMs > 0 ? { messageId: ask.messageId, since: ask.since, after: ask.restartAfterMs } : null
+ void (async () => {
+ const turn = (await this.core.agents.activity([harnessId]))[harnessId]
+ const at = this.now()
+ if (turn === 'idle') delete watch.workingSince
+ else if (turn === 'working') watch.workingSince ??= at
+ if (!due || turn === 'idle' || watch.restartedFor === due.messageId || at - due.since < due.after) return
+ const shown = this.terminal.progressOf([harnessId])[harnessId]
+ const inTurn = watch.workingSince !== undefined && at - watch.workingSince >= due.after
+ const frozen = typeof shown === 'number' && at - shown >= due.after
+ if (!inTurn && !frozen) return
+ if (heldElsewhere()) return
+ watch.restartedFor = due.messageId
+ watch.restarting = true
+ this.log(`Restarting the Product Manager ${harnessId.slice(0, 8)} in place: it owes an answer sent ${Math.round((at - due.since) / 60_000)} min ago and `
+ + `${inTurn ? `has been in one turn for ${Math.round((at - watch.workingSince!) / 60_000)} min` : `its screen has not changed for ${Math.round((at - shown!) / 60_000)} min`}.`)
+ try {
+ const result = await this.restartLead(harnessId)
+ if (!result.ok) this.log(`Could not restart the Product Manager ${harnessId.slice(0, 8)}: ${result.error}. Not tried again for this ask.`)
+ } finally {
+ delete watch.workingSince
+ watch.restarting = false
+ watch.settleUntil = this.now() + LEAD_REOPEN_WAIT_MS
+ }
+ })().catch(error => this.log(`Product Manager watch: ${error instanceof Error ? error.message : String(error)}`)).finally(() => { watch.checking = false })
+ }
+
/** The new session [switched] started, when it runs here: its native creation receipt is the switch's own change id. */
private async switchReplacement(switched: LeadSwitch): Promise<string | null> {
const receipt = await this.core.agents.creationStatus?.(switched.changeId)
diff --git a/docs/plans/2026-11-05-instructions-budget-moved-rules-plan.md b/docs/plans/2026-11-05-instructions-budget-moved-rules-plan.md
new file mode 100644
index 000000000..e0c056343
--- /dev/null
+++ b/docs/plans/2026-11-05-instructions-budget-moved-rules-plan.md
@@ -0,0 +1,118 @@
+# Instructions Size Budget and Moved Rules Implementation Plan
+
+> Implement task by task, test first, following the project's Engineer workflow (project instructions, Engineer).
+
+**Goal:** An instructions save that makes a part of the document bigger than its budget is refused as
+`INSTRUCTIONS_OVER_BUDGET`, naming each part's size and budget: core 6 KB, each role section 2 KB, people notes 3 KB, 20 KB
+in all. The guard that refuses dropping a person's tagged rule (`INSTRUCTIONS_RULES_DROPPED`) learns "moved": a rule counts as
+kept when it moves word for word, with who gave it, into people notes or a role section, into the project's rules record, or
+into a code task once that task has merged. A rule moved into a task still open is refused with the task named, so the line
+stays until the task merges. One restructure save can then move every rule at once (anh Dee's decision 5).
+
+**Architecture:** Two pure functions in `instructionsDiff.ts`, which already parses the document into items and attributed
+rules: `budgetParts(text, budget)` splits a document into its budget parts with their UTF-8 sizes, and `droppedRules` takes an
+optional list of places outside the document (`RulePlace`) where a rule may have moved. `ruleGuard.ts` gets
+`refuseOverBudget(before, after)` and builds the places for `allowedDrops` from the project's rules record (`state.rules`) and
+its code tasks (conversations of the project with a brief). `commands.ts` calls `refuseOverBudget` in `instructions.save`
+next to `refuseRepeats`, and takes an optional `tasks` list naming code tasks the rules moved into, which `store.ts namedFor`
+loads even when dormant (a merged task goes quiet after a day).
+
+**Tech Stack:** Backend TypeScript, zod command schema, Vitest.
+
+**Spec:** Swarm task #3392 brief (River, for anh Dee, 2026-11-05); readings posted in the task for River: role sections are the
+`###` headings under `## Roles`, people notes is a `## People notes` section, the rest is core; a part already over budget may
+be saved as long as it does not grow; a rule moved into an open code task keeps its line until that task merges.
+
+## Global Constraints
+
+- New refusal code `INSTRUCTIONS_OVER_BUDGET` (a new name; none of the codes in `removedRefusals.test.ts` comes back).
+- Budgets: core 6,144 bytes, each role section 2,048, people notes 3,072, whole document 20,480 (UTF-8 bytes, KB = 1,024
+ as `MAX_INSTRUCTIONS_BYTES` counts). They live in one exported `INSTRUCTIONS_BUDGET` object passed into the check, so a
+ project-level setting can replace it later without touching the check.
+- A part is refused only when it is over its budget and bigger than the same part in the revision the save replaces (a role
+ section is the same part by its heading). Today's document (about 31 KB) and the template (its PM section about 2.9 KB)
+ are over budget: saves that shrink them, or leave those parts unchanged, still go through.
+- The refusal names each part, its size, its budget and its size before, and the next step: move checkable rules to a code
+ task, move a person's rule word for word to people notes or their role section, or drop lines that passed.
+- Moved means the rule's words in order (the same comparison `droppedRules` already uses) and every person of the rule:
+ in the document, in a segment attributed to them; in a rules record, attributed in its text or asked by them; in a code
+ task, attributed in its brief.
+- A code task counts only once merged (`ledger.mergedAt`). Cancelled tasks never count. An open one makes the rule
+ `waiting`, refused with the task's number and "keep the line until it merges".
+- Swarm code stays out of `cli/src/core`. Only `backend/src/superTabs/` and this plan change.
+
+## Design
+
+- growth: nothing new is stored. The `tasks` field of a save is at most 20 ids, read once.
+- concurrency: the check runs inside the existing save transaction, against the revision the stale check already read.
+- read cost: the budget check is one pass over the text; the moved check scans the project's loaded tasks and rules once per
+ dropped rule, only when a rule would otherwise be dropped. Named tasks are loaded by id (one indexed read each).
+- compatibility: `tasks` is an optional field; older clients never send it. `DroppedRule.why` gains `waiting` (details only).
+- failure: each refusal names its next step; the moved form is spelled out in the dropped-rules refusal.
+- audience: unchanged; the save's access checks run first.
+
+## Review Focus
+
+- A rule moved into a task brief without its attribution is still refused (the person must come with it).
+- A rule whose words moved but changed (a number, a negation) into a task or the rules record is still refused.
+- An over-budget part that shrinks or stays the same passes; one that grows is refused, and a new part (new role section)
+ over its budget is refused.
+- `removedRefusals.test.ts` stays green.
+
+---
+
+### Task 1: Budget parts and the over-budget refusal
+
+**Files:**
+- Modify: `backend/src/superTabs/instructionsDiff.ts`, `backend/src/superTabs/ruleGuard.ts`, `backend/src/superTabs/commands.ts`
+- Test: `backend/src/superTabs/instructionsDiff.test.ts`, `backend/src/superTabs/instructions.test.ts`
+
+**Interfaces:**
+- `INSTRUCTIONS_BUDGET = { core, role, people, total }` (bytes).
+- `budgetParts(text, budget?): BudgetPart[]` with `BudgetPart = { part: string; bytes: number; budget: number }`; parts
+ `core`, `role: <heading>`, `people notes`, `total`.
+- `refuseOverBudget(before, after, budget?)`: throws `INSTRUCTIONS_OVER_BUDGET`, 409, details `{ parts: [{ part, bytes,
+ budget, before }] }`.
+
+- [ ] Write failing tests: `budgetParts` splits core, role sections and people notes (fenced headings ignored, UTF-8 bytes);
+ a save whose core grows past 6 KB is refused with the sizes in the message; a role section past 2 KB, people notes past
+ 3 KB and a whole document past 20 KB likewise; a save that shrinks an over-budget part, or leaves it unchanged, passes.
+- [ ] Run `cd backend && npx vitest run src/superTabs/instructionsDiff.test.ts src/superTabs/instructions.test.ts`. Expected: FAIL.
+- [ ] Implement, wire into `instructions.save` after `refuseRepeats`.
+- [ ] Run the same tests plus `src/superTabs/removedRefusals.test.ts`. Expected: PASS.
+- [ ] Commit the tests first, then the code.
+
+### Task 1b: The built-in template fits its own budget (River, in the task)
+
+A new project's PM writes its routing line into Routing; the template's core was 6,125 of 6,144 bytes and its PM section
+2,943 of 2,048, so that line would be refused. River: trim the template in this PR, core with at least 1 KB of room and the PM
+section within 2 KB, cutting wording and repetition, never a rule.
+
+**Files:** Modify `backend/src/superTabs/instructionsTemplate.ts`; Test `backend/src/superTabs/instructions.test.ts`
+
+- [ ] Write a failing test: the template's core is at most 5,120 bytes and each role section at most 2,048.
+- [ ] Trim; update the template tests that pinned wrapped or reworded lines, keeping each rule they guard.
+- [ ] Run the template tests and the instructions integration files. Expected: PASS.
+
+### Task 2: A tagged rule may move
+
+**Files:**
+- Modify: `backend/src/superTabs/instructionsDiff.ts` (`droppedRules` places), `backend/src/superTabs/ruleGuard.ts`
+ (`allowedDrops` places, refusal text), `backend/src/superTabs/commands.ts` (`tasks` field), `backend/src/superTabs/store.ts`
+ (`namedFor` loads `tasks`)
+- Test: `backend/src/superTabs/instructionsDiff.test.ts`, `backend/src/superTabs/instructions.test.ts`
+
+**Interfaces:**
+- `RulePlace = { text: string; people: string[]; where: string; open: boolean }` (`people`: identified keys known to have
+ given what the place holds, such as a rules record's askedBy).
+- `droppedRules(before, after, identify?, places?)`; `DroppedRule.why` adds `'waiting'` and `movedTo?: string`.
+- `instructions.save` takes `tasks?: string[]` (conversation ids, at most 20).
+
+- [ ] Write failing tests: a rule moved word for word into a `## People notes` section or a role section is kept; moved into
+ the project's rules record (by its askedBy, or attributed in its text) is kept; moved into a merged code task's brief is kept,
+ also when that task is dormant and named in `tasks`; moved into an open task is refused naming the task; a real drop, a moved
+ copy without its person, and a moved copy with a changed number are still refused; the refusal text spells out the moved form.
+- [ ] Run `cd backend && npx vitest run src/superTabs/instructionsDiff.test.ts src/superTabs/instructions.test.ts`. Expected: FAIL.
+- [ ] Implement.
+- [ ] Run the same tests plus `src/superTabs/removedRefusals.test.ts` and `src/superTabs/commands.test.ts`. Expected: PASS.
+- [ ] Commit the tests first, then the code.
diff --git a/docs/plans/2026-11-05-server-checks-and-pm-watchdog-plan.md b/docs/plans/2026-11-05-server-checks-and-pm-watchdog-plan.md
new file mode 100644
index 000000000..49604cc0f
--- /dev/null
+++ b/docs/plans/2026-11-05-server-checks-and-pm-watchdog-plan.md
@@ -0,0 +1,70 @@
+# Server time checks and PM watchdog Implementation Plan
+
+> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one review and one security review on the pull request.
+
+**Goal:** The stall, idle and lost-task follow-ups keep running when the PM is down, and a PM that stops answering is restarted in place by its own host. Strengthens "Tell the PM what you want, and your crew ships it": an ask never waits unseen because one agent hung (anh Dee's Swarm redesign, 11-05, step 1).
+
+**Architecture:** The backend worker gets one more pass, every 30 s. For each Swarm with recent activity it loads the Swarm and runs the time checks the PM's poll ran before (`sweepForLead`: lost tasks, failed starts, stalled tasks) and the idle notices. The pass also records, per project, the oldest message a person sent the PM that it has not answered yet (`project.owed`), and writes only when that changes. The PM's poll no longer runs those checks. The PM's host row carries `owed` and how long it may wait (`restartAfterMs`, from the backend, so the number is server data). The host's lead keep-alive gets a second trigger: an owed ask past `restartAfterMs`, while the PM has been in one turn for that long or its screen has not changed for that long, restarts the PM in its own pane on the same session (`agent_restart`, as the relay recovery does). It never reopens or starts a second PM, and it restarts at most once per owed ask.
+
+**Tech Stack:** TypeScript, Prisma/MongoDB, Vitest (backend unit + Super Tab integration), Vitest (CLI specs with a fake core).
+
+**Spec:** Task #3385, Super Tab conversation 16ef5ccda66319b5a6d75102 (River for anh Dee, 2026-11-05).
+
+## Global Constraints
+
+- Act and notify; no new refusal anywhere.
+- Lifecycle code is tested with a fake host and fake core. No test signs the Mac out of the real CLI.
+- Swarm code stays out of `cli/src/core`.
+- PR body starts `Requested by dee through Harness.`
+- One review and one security review (it restarts agents).
+
+## Design
+
+- Growth: `project.owed` is one small record per project, replaced or removed, never appended. The pass keeps nothing else.
+- Concurrency: each Swarm is checked in its own transaction, as the PM's poll did; a conflicting write retries, and the recorded task state makes a second run find nothing new. The worker is the singleton process and runs one pass at a time.
+- Read cost: candidates come from the `[dormant, lastActivityAt]` group index (groups active in the last 7 days, at most 200 Swarms a pass). Each Swarm is one load, which the PM's poll did every 30 s before and no longer does. The owed ask is a few indexed reads on `[tabId, agentId, status, createdAt]`, one per open status.
+- Scale: 10x Swarms means 10x loads per pass. The first warning is the pass's duration line, logged when a pass takes longer than its interval.
+- Compatibility: an older host ignores `owed` and keeps the crash-only keep-alive. A new host on an older backend sees no `owed` and never restarts for it. An older backend's PM poll still runs the checks, so a mixed rollout only runs them twice, and the records dedupe that.
+- Migration + rollback: none. Rolling back leaves `project.owed` unread, and the PM's poll runs the checks again.
+- Audience: `owed` goes only in the PM's own host row, to its machine's host. It holds a message id and a time, never text.
+- Identity: the pass writes as the project's PM, as the poll did. A restart goes through the machine's own daemon socket, for a session that host already runs.
+- Failure: one Swarm's failure is logged and skips that Swarm. A failed restart is logged and not retried for the same ask; the crash keep-alive is unchanged.
+- Platforms: backend; the CLI host on macOS, Linux and Windows (`agent_restart` relaunches in the same pane and opens no window).
+
+## Review Focus
+
+- The PM's poll loses exactly `sweepForLead` and `idleNotices`, nothing else (digest, schedule, update request and stale runs stay).
+- The watchdog never runs while a reopen or an engine switch is in progress, and the keep-alive never reopens while a restart is running or settling: two PMs must be impossible.
+- Once per owed ask: a PM that stays stuck after its restart is left to people, not restarted in a loop.
+
+## Task 1: the backend runs the time checks without a PM poll
+
+**Files:** `backend/src/superTabs/timeChecks.ts` (new), `backend/src/superTabs/store.ts`, `backend/src/worker.ts`, `backend/integration/superTabTimeChecks.test.ts` (new), integration fixtures that drove the checks through the PM's poll.
+
+**Interfaces:** `SuperTabStore.runTimeChecks(tabId): Promise<number>` (messages written). `startTimeChecks(db, store, everyMs = SWEEP_EVERY_MS): () => void` and `timeCheckSwarms(db, now, limit)`.
+
+- [x] Integration test: with no PM poll at all, a quiet task, an idle agent and a lost task each produce their notice from `runTimeChecks`, once; a second run writes nothing.
+- [x] Integration test: the PM's poll alone no longer writes them.
+- [x] Watch both fail.
+- [x] Add `runTimeChecks`, the pass and its worker start; remove the two calls from the poll. Point the fixtures that relied on the poll at `runTimeChecks` first.
+- [x] Run the changed integration files.
+
+## Task 2: the backend records what the PM owes
+
+**Files:** `backend/src/superTabs/timeChecks.ts`, `backend/src/superTabs/projects.ts`, `backend/src/superTabs/read/hostRows.ts`, `backend/integration/superTabTimeChecks.test.ts`.
+
+**Interfaces:** `Project.owed?: { messageId: string; since: number }`. Host row `owed: { messageId, since, restartAfterMs } | null` on the PM's row.
+
+- [x] Integration test: a person's message to the PM is recorded as owed; the PM's answer clears it; an agent's message never counts; the PM's host row carries it with `restartAfterMs`, another agent's row does not.
+- [x] Watch it fail, then implement.
+
+## Task 3: the host restarts a stuck PM once
+
+**Files:** `cli/src/superTabs/host.ts`, `cli/src/superTabs/host.spec.ts`.
+
+**Interfaces:** `SuperTabHostOptions.restartLead?(harnessId)`, default the daemon's `agent_restart`.
+
+- [x] Spec: owed ask past its time and the PM in one turn that long: restarted once, in place; more polls, still once; `keepLeadAlive` never called while the restart runs or settles, even when the session briefly reads as gone.
+- [x] Spec: a frozen screen counts the same; an idle PM, an ask not yet due, or a PM that ended a turn recently is never restarted.
+- [x] Watch them fail, then implement.
+- [x] Run the host spec and the CLI coverage gate for the Super Tab host.