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 k0810: #3284 #3286 (#3289)

0xken1550e82a1c6aff
diff --git a/backend/integration/superTabPullRequestEvents.test.ts b/backend/integration/superTabPullRequestEvents.test.ts
index 29088baca..70c236296 100644
--- a/backend/integration/superTabPullRequestEvents.test.ts
+++ b/backend/integration/superTabPullRequestEvents.test.ts
@@ -48,14 +48,17 @@ function fakeReader() {
/** 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[] = []
+ /** Each head that is git's own merge of another head and main (task #3553), by head: the head it carries. */
+ const merges = new Map<string, 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 },
+ merge: async (_url, head) => merges.get(head) ?? null,
botLogin: async () => 'harness[bot]',
done: async () => {},
}
- return { pulls, asked, patches, patchReads, reader }
+ return { pulls, asked, patches, patchReads, merges, 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
@@ -82,12 +85,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, patches, patchReads, reader } = fakeReader()
+ const { pulls, asked, patches, patchReads, merges, 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, patches, patchReads, 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, merges, reader, pass, told, clock: { get now() { return now }, advance(ms: number) { now += ms } } }
}
describe('pull request events', () => {
@@ -258,6 +261,33 @@ describe('pull request events', () => {
}
})
+ // Task #3553: a head git merged from the reviewed head and main by itself carries the verdict (mergeCarry.ts), though its
+ // patch is new; any other head does not, and a chain of such merges carries it on.
+ it('a clean, automatic main merge keeps it, through a chain of them', async () => {
+ const { f, HEAD3, read } = await reviewed()
+ const MERGE2 = 'eeeeeee5555555eeeeeee5555555eeeeeee55555'
+ f.merges.set(HEAD3, HEAD)
+ f.pulls.set(f.PR, f.pull({ head: HEAD3 }))
+ await f.pass()
+ for (const check of await read()) {
+ expect(check.passedBy).not.toBeNull()
+ expect(check.verdicts!.at(-1)!.stale).toBeUndefined()
+ }
+ f.merges.set(MERGE2, HEAD3)
+ f.pulls.set(f.PR, f.pull({ head: MERGE2 }))
+ await f.pass()
+ for (const check of await read()) expect(check.passedBy).not.toBeNull()
+ })
+
+ it('a main merge of another head, or with a line resolved by hand, makes it stale', async () => {
+ const { f, HEAD3, read } = await reviewed()
+ // Git's merge of some other head carries that head's verdicts, not these.
+ f.merges.set(HEAD3, 'fffffff6666666fffffff6666666fffffff66666')
+ f.pulls.set(f.PR, f.pull({ head: HEAD3 }))
+ await f.pass()
+ for (const check of await read()) expect(check.verdicts!.at(-1)).toMatchObject({ head: HEAD, stale: HEAD3 })
+ })
+
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 }))
diff --git a/backend/integration/superTabTeam.test.ts b/backend/integration/superTabTeam.test.ts
index 58a890d89..ae8277648 100644
--- a/backend/integration/superTabTeam.test.ts
+++ b/backend/integration/superTabTeam.test.ts
@@ -188,7 +188,7 @@ describe('a task a Team agent worked on', () => {
const read = vi.fn(async () => 'team' as const)
const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: read })
const state = await storedState(tab)
- state.conversations.find(c => c.id === clean)!.pullRequestUrls = ['https://github.com/acme/app/pull/7']
+ state.conversations.find(c => c.id === clean)!.codePullRequestUrls = ['https://github.com/acme/app/pull/7']
await saveState(tab, state)
await expect(asked.execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.assign', conversationId: review, agentId: main } }))
.rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
@@ -203,7 +203,7 @@ describe('a task a Team agent worked on', () => {
const { tab, builder } = await fixture()
const clean = await task(tab, 'Owner work'), main = await owners(tab, clean), review = await step(tab, clean)
const state = await storedState(tab)
- state.conversations.find(c => c.id === clean)!.pullRequestUrls = ['https://github.com/acme/app/pull/9']
+ state.conversations.find(c => c.id === clean)!.codePullRequestUrls = ['https://github.com/acme/app/pull/9']
await saveState(tab, state)
const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: async () => 'team' })
await asked.execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.assign', conversationId: review, agentId: builder } })
@@ -233,7 +233,7 @@ describe('a task a Team agent worked on', () => {
const { tab } = await fixture()
const clean = await task(tab, 'Owner work'), main = await owners(tab, clean), review = await step(tab, clean)
const state = await storedState(tab)
- state.conversations.find(c => c.id === clean)!.pullRequestUrls = ['https://github.com/acme/app/pull/8']
+ state.conversations.find(c => c.id === clean)!.codePullRequestUrls = ['https://github.com/acme/app/pull/8']
await saveState(tab, state)
const answer = vi.fn<() => Promise<'unknown' | 'clean'>>().mockResolvedValueOnce('unknown').mockResolvedValueOnce('clean')
const asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: answer })
@@ -249,7 +249,8 @@ describe('a task a Team agent worked on', () => {
const joined = await task(tab, 'Owner work'), main = await owners(tab, joined)
const state = await storedState(tab)
state.projects!.find(p => p.id === 'lead')!.repository = { machineId: 'owner-host', cwd: '/repo', repositoryUrl: 'https://github.com/acme/app' }
- Object.assign(state.conversations.find(c => c.id === joined)!, { teamWritten: true, pullRequestUrls: ['https://github.com/acme/app/pull/3154'] })
+ // A task from before #3554 as well: no code list, so it reads every pull request it recorded.
+ Object.assign(state.conversations.find(c => c.id === joined)!, { teamWritten: true, pullRequestUrls: ['https://github.com/acme/app/pull/3154'], codePullRequestUrls: undefined })
await saveState(tab, state)
const review = await step(tab, joined)
expect((await storedState(tab)).conversations.find(c => c.id === review)?.teamWritten).toBe(true)
@@ -282,6 +283,100 @@ describe('a task a Team agent worked on', () => {
})
})
+// Task #3554 (River, 11-06): #3462 and #3514 were marked Team-written though all their code was the main account's. The push read
+// covered every pull request link posted in the task or its steps (a Team reviewer's verdict, log lines), and a step's Team answer
+// marked its task. The mark rests on the task's own code: its brief, its assignment's results, its checks and its merge.
+describe('a task\'s Team-written mark rests on its own code', () => {
+ const REPO = 'https://github.com/acme/app', OWN = `${REPO}/pull/7`, TEAM_PR = `${REPO}/pull/99`
+ /** GitHub as the store asks it: only the Team agent's pull request was pushed by the bot. */
+ const github = () => vi.fn(async (_repository: string | null, urls: string[]) => urls.includes(TEAM_PR) ? 'team' as const : 'clean' as const)
+ const setup = async () => {
+ const f = await fixture()
+ const state = await storedState(f.tab)
+ state.projects!.find(p => p.id === 'lead')!.repository = { machineId: 'owner-host', cwd: '/repo', repositoryUrl: REPO }
+ await saveState(f.tab, state)
+ const read = github(), asked = new SuperTabStore(db, Date.now, undefined, { pushOrigin: read })
+ const exec = (command: Command, asAgentId?: string) => asked.execute(owner, f.tab, { operationId: randomUUID(), command }, asAgentId)
+ /** As the Team account's agent, from its Team machine. */
+ const execTeam = (command: Command, asAgentId: string) => asked.execute(team, f.tab, { operationId: randomUUID(), command }, asAgentId)
+ const agentOf = async (conversationId: string, name: string) => String((await run(f.tab, { type: 'agent.add', conversationId, machineId: 'owner-host',
+ harnessId: randomUUID(), name, configuration: config, lead: false })).result.agentId)
+ const task = String((await run(f.tab, { type: 'conversation.create', projectId: 'lead', title: 'Owner work', brief: 'Do it', checks: [] })).result.conversationId)
+ const ownBuilder = await agentOf(task, 'Owner Builder')
+ await exec({ type: 'work.assign', conversationId: task, agentId: ownBuilder })
+ const assignment = (await storedState(f.tab)).conversations.find(c => c.id === task)!.assignment!.id
+ // The builder's own pull request, as its status names it.
+ await exec({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'working', result: `Draft PR ${OWN}` }, ownBuilder)
+ /** A main-account agent of the project joining the task: the read River's handover of #3462 met. */
+ const join = async (name: string) => exec({ type: 'conversation.agent', conversationId: task, agentId: await agentOf('lead', name), present: true, lead: false })
+ const marked = async (id: string) => (await storedState(f.tab)).conversations.find(c => c.id === id)?.teamWritten === true
+ return { ...f, read, exec, execTeam, agentOf, join, task, ownBuilder, marked }
+ }
+
+ it('does not read a Team pull request another agent linked in the task, and still reads the task\'s own', async () => {
+ const f = await setup()
+ // A Team agent's log lines in the task, as in #3514.
+ await f.execTeam({ type: 'message.send', conversationId: f.task, text: `Log: CI on ${TEAM_PR} failed at step 3`, replyTo: null, recipientIds: [] }, f.builder)
+ await expect(f.join('Owner Builder 2')).resolves.toBeTruthy()
+ expect(f.read).toHaveBeenLastCalledWith(REPO, [OWN])
+ expect(await f.marked(f.task)).toBe(false)
+ })
+
+ // SecAlder's security review 2 of #3286: the PM, or a person, tells a builder in the task to merge a Team pull request, and a
+ // squash or a rebase leaves only the builder's own commits on its branch. The link they posted is the task's code, and is read.
+ // SecLarch's security review of #3286: a link the task's own builder posts is its code too.
+ it('reads a Team pull request the PM, a person or the task\'s builder linked in the task, and refuses the main account', async () => {
+ for (const poster of ['pm', 'person', 'builder'] as const) {
+ const f = await setup()
+ const text = `Merge ${TEAM_PR} into your branch, please.`
+ if (poster === 'person') await run(f.tab, { type: 'message.send', conversationId: f.task, text, replyTo: null, recipientIds: [] })
+ else await f.exec({ type: 'message.send', conversationId: f.task, text, replyTo: null, recipientIds: [] }, poster === 'pm' ? f.lead : f.ownBuilder)
+ await expect(f.join('Owner Builder 2')).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ expect(await f.marked(f.task)).toBe(true)
+ }
+ })
+
+ it('reads a link a person posted in a task that names no pull request of its own yet', async () => {
+ const f = await setup()
+ const bare = String((await run(f.tab, { type: 'conversation.create', projectId: 'lead', title: 'Owner work 2', brief: 'Do it', checks: [] })).result.conversationId)
+ await run(f.tab, { type: 'message.send', conversationId: bare, text: `Start from ${TEAM_PR}.`, replyTo: null, recipientIds: [] })
+ const next = await f.agentOf('lead', 'Owner Builder 3')
+ await expect(f.exec({ type: 'conversation.agent', conversationId: bare, agentId: next, present: true, lead: false })).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ })
+
+ it('marks a step for a Team pull request its reviewer names in its Ready, never the task; a link posted there marks nothing', async () => {
+ const f = await setup()
+ const review = String((await run(f.tab, { type: 'conversation.create', projectId: 'lead', title: 'Review', brief: 'Read it', reviewOf: f.task, step: 'Review', checks: [] })).result.conversationId)
+ // A Team-account reviewer, as #3462's were.
+ await f.exec({ type: 'work.assign', conversationId: review, agentId: f.builder })
+ const step = (await storedState(f.tab)).conversations.find(c => c.id === review)!
+ await run(f.tab, { type: 'message.send', conversationId: review, text: `Same bug as ${TEAM_PR}.`, replyTo: null, recipientIds: [] })
+ await f.execTeam({ type: 'work.status', conversationId: review, assignmentId: step.assignment!.id, status: 'working', result: 'Reading it' }, f.builder)
+ expect(await f.marked(review)).toBe(false)
+ await f.execTeam({ type: 'work.status', conversationId: review, assignmentId: step.assignment!.id, status: 'review', result: `Ready to merge: Yes. Same bug as ${TEAM_PR}.` }, f.builder)
+ expect(await f.marked(review)).toBe(true)
+ expect(await f.marked(f.task)).toBe(false)
+ await expect(f.join('Owner Builder 2')).resolves.toBeTruthy()
+ })
+
+ it('still marks the task, and refuses the main account, when the bot pushed to its own pull request', async () => {
+ const f = await setup()
+ f.read.mockImplementation(async (_repository, urls) => urls.includes(OWN) ? 'team' : 'clean')
+ await expect(f.join('Owner Builder 2')).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ expect(await f.marked(f.task)).toBe(true)
+ })
+
+ it('reads what a task from before recorded, links included: it loses no protection it had', async () => {
+ const f = await setup()
+ const state = await storedState(f.tab)
+ const legacy = state.conversations.find(c => c.id === f.task)!
+ delete (legacy as { codePullRequestUrls?: string[] }).codePullRequestUrls
+ legacy.pullRequestUrls = [OWN, TEAM_PR]
+ await saveState(f.tab, state)
+ await expect(f.join('Owner Builder 2')).rejects.toMatchObject({ code: 'TEAM_WRITTEN_WORK' })
+ })
+})
+
// Huy's groupme, 2026-11-05 (task #3266): a Team account start for a repository the Harness GitHub App is not on failed
// twice on its machine and suspended Claude there. The store reads the project's GitHub access first and refuses it at once.
describe('a start whose account cannot reach the project repository', () => {
diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.ts
index b6bd0405c..e23d04bd4 100644
--- a/backend/src/github/app.test.ts
+++ b/backend/src/github/app.test.ts
@@ -680,6 +680,53 @@ describe('watching a pull request', () => {
expect(await app.pullRequestPatchFiles(repo, 12, token, head)).toBeNull()
})
+ // Task #3553: what a new head is of the pull request, to judge whether it is git's own merge of its reviewed head and main
+ // (superTabs/mergeCarry.ts): its parents, whether the second is on the branch it merges into, and the three comparisons.
+ it('reads a merge head\'s parents and the three sides of the merge, at the head the pull request names', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo, PULL_PATCH_PERMISSIONS)
+ const M = 'd'.repeat(40), H = 'a'.repeat(40), B = 'b'.repeat(40)
+ // The base's tip as the pull request names it: the second parent is checked against this commit, never the branch name,
+ // which a tag of the same name could shadow (security review of #3284, Important 1).
+ const TIP = 'e'.repeat(40)
+ github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: M }, base: { ref: 'main', sha: TIP }, mergeable: true,
+ html_url: 'https://github.com/acme/app/pull/12' })
+ github.commits.set(`acme/app@${M}`, [H, B])
+ github.compares.set(`acme/app@${B}...${TIP}`, [])
+ github.compareStatus.set(`acme/app@${B}...${TIP}`, 'identical')
+ github.compares.set(`acme/app@${H}...${B}`, [{ filename: 'lib.ts', status: 'modified', sha: 'm2' }])
+ github.compares.set(`acme/app@${B}...${H}`, [{ filename: 'app.ts', status: 'modified', sha: 'p1' }])
+ github.compares.set(`acme/app@${H}...${M}`, [{ filename: 'lib.ts', status: 'modified', sha: 'm2' }])
+ expect(await app.mainMergeSides(repo, 12, token, M)).toEqual({ base: 'main', sides: { parents: [H, B], onBase: true,
+ prSide: [{ filename: 'app.ts', status: 'modified', sha: 'p1' }], mainSide: [{ filename: 'lib.ts', status: 'modified', sha: 'm2' }],
+ mergeSide: [{ filename: 'lib.ts', status: 'modified', sha: 'm2' }] } })
+ expect(github.calls.map(c => c.path)).toContain(`/repos/acme/app/compare/${B}...${TIP}`)
+ expect(github.calls.map(c => c.path).filter(path => path.includes('...main'))).toEqual([])
+ // Its second parent behind the tip is on it; one the tip never had is not.
+ github.compareStatus.set(`acme/app@${B}...${TIP}`, 'ahead')
+ expect((await app.mainMergeSides(repo, 12, token, M))?.sides.onBase).toBe(true)
+ github.compareStatus.set(`acme/app@${B}...${TIP}`, 'diverged')
+ expect((await app.mainMergeSides(repo, 12, token, M))?.sides.onBase).toBe(false)
+ })
+
+ it('reads no merge for a head the pull request no longer names, a commit that is no merge, or a side at its file cap', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo, PULL_PATCH_PERMISSIONS)
+ const M = 'd'.repeat(40), H = 'a'.repeat(40), B = 'b'.repeat(40)
+ github.pulls.set('acme/app#12', { state: 'open', merged_at: null, draft: false, head: { sha: M }, base: { ref: 'main', sha: B }, mergeable: true,
+ html_url: 'https://github.com/acme/app/pull/12' })
+ expect(await app.mainMergeSides(repo, 12, token, 'c'.repeat(40))).toBeNull()
+ // One parent: no comparison is read, and the sides say it is no merge.
+ github.commits.set(`acme/app@${M}`, [H])
+ expect(await app.mainMergeSides(repo, 12, token, M)).toEqual({ base: 'main', sides: { parents: [H], onBase: false, prSide: [], mainSide: [], mergeSide: [] } })
+ github.commits.set(`acme/app@${M}`, [H, B])
+ github.compares.set(`acme/app@${B}...${B}`, [])
+ github.compares.set(`acme/app@${H}...${B}`, Array.from({ length: 300 }, (_, i) => ({ filename: `f${i}.ts`, status: 'added', sha: `s${i}` })))
+ github.compares.set(`acme/app@${B}...${H}`, [])
+ github.compares.set(`acme/app@${H}...${M}`, [])
+ expect(await app.mainMergeSides(repo, 12, token, M)).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 c4e591b10..792db6bdf 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -11,6 +11,7 @@ import { readPushOrigin, type GitHubRead, type PushOrigin } from './pushOrigin.j
import { githubRepository, type GitHubRepository } from './repository.js'
import type { PullRequestWatch } from '../superTabs/pullRequestEvents.js'
import type { PullRequestFile } from '../superTabs/pullRequestPatch.js'
+import type { MergeSides } from '../superTabs/mergeCarry.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. */
@@ -712,6 +713,49 @@ export class GitHubApp {
}
}
+ /** What the head [head] of pull request [number] is, to judge whether it is git's own merge of its reviewed head and main
+ * (superTabs/mergeCarry.ts, task #3553), read with a token of [PULL_PATCH_PERMISSIONS]: its parents (GET /git/commits); for
+ * a two-parent head, whether its second parent is on the branch the pull request merges into (GET /compare/{it}...{tip},
+ * the base commit the same answer names: identical or ahead), and the files of the three comparisons of fixed commits, each GET /compare/{a}...{b} from their merge
+ * base: main's side (first parent to second), the pull request's (second to first) and the merge (first parent to head). Null
+ * unless the pull request still names [head], when GitHub cannot say, or when a side gives as many files as GitHub ever
+ * gives ([COMPARE_FILES_MAX]), as it may have left some out. With the branch from the same answer as the pull request. */
+ async mainMergeSides(repository: GitHubRepository, number: number, token: string, head: string): Promise<{ base: string; sides: MergeSides } | 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
+ const files = async (from: string, to: string) => {
+ const compared = await this.call('GET', `${base}/compare/${from}...${to}?per_page=1`, `Bearer ${token}`)
+ const listed = compared.status === 200 ? (compared.body as { files?: unknown }).files : undefined
+ return Array.isArray(listed) && listed.length < COMPARE_FILES_MAX ? filesOf(listed) : null
+ }
+ 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 } }
+ // The base as a commit, from the same answer (security review of #3284, Important 1): a branch name a tag of the same
+ // name could shadow is never compared against.
+ const at = sha(named.head?.sha), tip = sha(named.base?.sha), branch = typeof named.base?.ref === 'string' ? named.base.ref : ''
+ if (!at || !tip || !branch || at !== head.toLowerCase()) return null
+ const commit = await this.call('GET', `${base}/git/commits/${at}`, `Bearer ${token}`)
+ const listed = commit.status === 200 ? (commit.body as { parents?: unknown }).parents : undefined
+ if (!Array.isArray(listed)) return null
+ const parents = listed.map(p => sha((p as { sha?: unknown })?.sha))
+ if (parents.some(p => p === undefined)) return null
+ const none: MergeSides = { parents: parents as string[], onBase: false, prSide: [], mainSide: [], mergeSide: [] }
+ if (parents.length !== 2) return { base: branch, sides: none }
+ const [parent, merged] = parents as [string, string]
+ const onBranch = await this.call('GET', `${base}/compare/${merged}...${tip}?per_page=1`, `Bearer ${token}`)
+ const status = onBranch.status === 200 ? (onBranch.body as { status?: unknown }).status : undefined
+ if (status !== 'identical' && status !== 'ahead') return { base: branch, sides: none }
+ const [mainSide, prSide, mergeSide] = [await files(parent, merged), await files(merged, parent), await files(parent, at)]
+ if (!mainSide || !prSide || !mergeSide) return null
+ return { base: branch, sides: { parents: [parent, merged], onBase: true, prSide, mainSide, mergeSide } }
+ } 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 6442503ea..8a77d0585 100644
--- a/backend/src/github/fakeGitHub.ts
+++ b/backend/src/github/fakeGitHub.ts
@@ -33,6 +33,10 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
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 comparison's status, by the same key, when not 'ahead' (task #3553: whether a commit is on a branch). */
+ const compareStatus = new Map<string, string>()
+ /** Each commit's parents, by `owner/name@SHA`, lower case: GET /git/commits/{sha} (task #3553). */
+ const commits = new Map<string, 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. */
@@ -149,10 +153,16 @@ 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] ?? '')
+ const compared = /^\/compare\/([0-9A-Za-z._-]+)\.\.\.([0-9A-Za-z._-]+)$/.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 key = `${repoKey}@${compared[1]}...${compared[2]}`
+ const listed = compares.get(key)
+ return listed ? json(200, { status: compareStatus.get(key) ?? 'ahead', files: listed }) : json(404, { message: 'Not Found' })
+ }
+ const commit = /^\/git\/commits\/([0-9a-f]{40})$/.exec(repoPath[3] ?? '')
+ if (commit) {
+ const parents = commits.get(`${repoKey}@${commit[1]}`)
+ return parents ? json(200, { sha: commit[1], parents: parents.map(sha => ({ sha })) }) : json(404, { message: 'Not Found' })
}
const changed = /^\/pulls\/(\d+)\/files$/.exec(repoPath[3] ?? '')
if (changed) {
@@ -175,7 +185,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, compares, revoked, issued, control, actions, permissions }
+ return { fetch, calls, grants, installed, owners, renamed, protection, pulls, checkRuns, checkSuites, reviews, comments, files, compares, compareStatus, commits, revoked, issued, control, actions, permissions }
}
/** A configured app talking to [github]. */
diff --git a/backend/src/github/pushOrigin.test.ts b/backend/src/github/pushOrigin.test.ts
index 9ffd77027..3ac4e82d9 100644
--- a/backend/src/github/pushOrigin.test.ts
+++ b/backend/src/github/pushOrigin.test.ts
@@ -38,6 +38,21 @@ describe('who pushed a pull request', () => {
expect(await origin({ activity: [[push(HEAD), push(BASE_COMMIT, bot)]] })).toBe('team')
})
+ // Task #3554: a branch that merged main carries main's commits, some a Team agent wrote, but GitHub lists a pull request's
+ // commits without what its base holds: only the builder's own commits and its merge commit are read, so it reads clean.
+ it('reads clean for a branch that merged main holding a Team agent\'s commits: GitHub lists none of main\'s', async () => {
+ const MERGE = 'merge-of-main', MAIN_TEAM_COMMIT = 'main-team-commit'
+ expect(await origin({ commits: [commit(HEAD), commit(MERGE)],
+ activity: [[push(HEAD), push(MERGE), { ...push(MAIN_TEAM_COMMIT, bot), ref: 'refs/heads/main' }]] })).toBe('clean')
+ })
+
+ // Task #3554 (River's ruling): a main-account builder told to merge a Team pull request into its branch carries that pull
+ // request's commits, which the bot pushed on the Team branch. The builder pushed its own head, and the read is still team.
+ it('reads team for a main-account builder\'s pull request that merged a Team pull request\'s commits', async () => {
+ const TEAM_COMMIT = 'team-commit'
+ expect(await origin({ commits: [commit(HEAD), commit(TEAM_COMMIT)], activity: [[push(HEAD), { ...push(TEAM_COMMIT, bot), ref: 'refs/heads/team-branch' }]] })).toBe('team')
+ })
+
it('finds a bot\'s push on a later page', async () => {
expect(await origin({ activity: [[push(HEAD), ...Array(99).fill(push('other'))], [push(BASE_COMMIT, bot)]] })).toBe('team')
})
diff --git a/backend/src/superTabs/checkVerdicts.test.ts b/backend/src/superTabs/checkVerdicts.test.ts
index a5aabd7f6..00addbdb1 100644
--- a/backend/src/superTabs/checkVerdicts.test.ts
+++ b/backend/src/superTabs/checkVerdicts.test.ts
@@ -205,3 +205,25 @@ describe('a verdict and the base branch it read against', () => {
expect(c.passedBy).toBe('agent:r')
})
})
+
+// Task #3553: a head that is git's own merge of the reviewed head and main (mergeCarry.ts) carries its verdicts, on the same
+// base only, and through a chain of such merges; any other head does not.
+describe('a verdict at a head a clean main merge carries', () => {
+ const C = 'ccccccc3333333333333333333333333333333cc', D = 'ddddddd4444444444444444444444444444444dd'
+ const on = (head: string, carries: string[] | undefined, base = 'main'): PullRequestHeads => ({ [PR]: { head, patch: 'p9', at: 1, base, ...carries ? { carries } : {} } })
+ const read = (head: string, base = 'main'): CheckVerdict => ({ ...verdict('r', true, head, 'p1'), base })
+
+ it('counts at a head that carries its own', () => {
+ expect(verdictCounts(read(A), on(B, [A]))).toBe(true)
+ // Through a chain: D merged main into C, which merged main into A.
+ expect(verdictCounts(read(A), on(D, [C, A]))).toBe(true)
+ })
+
+ it('counts only on its own base, and never for a head that carries another', () => {
+ expect(verdictCounts(read(A, 'release'), on(B, [A]))).toBe(false)
+ expect(verdictCounts(read(A), on(B, [C]))).toBe(false)
+ expect(verdictCounts(read(A), on(B, undefined))).toBe(false)
+ // Never a shortened head, as at its own head.
+ expect(verdictCounts(read(A.slice(0, 7)), on(B, [A]))).toBe(false)
+ })
+})
diff --git a/backend/src/superTabs/checkVerdicts.ts b/backend/src/superTabs/checkVerdicts.ts
index 5cc5cabd0..a64ff7700 100644
--- a/backend/src/superTabs/checkVerdicts.ts
+++ b/backend/src/superTabs/checkVerdicts.ts
@@ -40,8 +40,10 @@ export function verdictCounts(verdict: CheckVerdict, heads: PullRequestHeads | u
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)
+ // base is watched. A patch id names its base. A head that is git's own merge of its head and main carries it, on that same
+ // base only (mergeCarry.ts, task #3553).
+ const read = sameHead(current.head, verdict.head) || !!current.carries?.some(carried => sameHead(carried, verdict.head!))
+ return (read && 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
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 39b8ad49f..7af70409f 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -14,7 +14,7 @@ import { agentWrittenNameOf, setName, shownNameOf } from './personNames.js'
import { z } from 'zod'
import { tokensByModelSchema } from './costs/tokens.js'
import {
- activeWork, occupiesAgent, actorKey, agent, appendPullRequestUrls, author, projectPullRequestUrl, pullRequestLinks, conversation, crossProjectActive, fail, isLeads, person, stableId, numberConversations, nextConversationNumber, renderWorkTask,
+ activeWork, occupiesAgent, actorKey, agent, appendCodePullRequestUrls, appendPullRequestUrls, author, projectPullRequestUrl, pullRequestLinks, conversation, crossProjectActive, fail, isLeads, person, stableId, numberConversations, nextConversationNumber, renderWorkTask,
finishWorker, seenMachineIds, SuperTabError, swarmGridName, visibleState, AGENT_ONLY, STATUS_LABELS, forRecipients,
type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type BuddySessionEntry, type WorkTask, type Agent, type Author, type Check, type CommandEffects, type Conversation, type SuperTabState,
} from './model.js'
@@ -652,6 +652,8 @@ export interface CommandContext {
pushOrigin?: PushOrigin
/** The pull requests [pushOrigin] read, as the store read them; none for a branch. A clean read clears only a mark it covered (teamWritten.ts). */
pushOriginPulls?: string[]
+ /** For a step, the read of its task's own code alone (store.ts pushOriginFor): only it marks the task (task #3554). */
+ pushOriginTask?: { origin: 'clean' | 'team' | 'unknown'; pulls: string[] }
/** The files a Ready for review's task changes in its pull requests, and the head they were read at, read before the command
* (store.ts pullRequestFilesFor): `files` null when GitHub could not say. Absent with nothing to read: no step opens then. */
pullRequestFiles?: { urls: string[]; head: string | null; files: string[] | null; heads?: Array<{ url: string; head: string | null; base?: string | null }> }
@@ -1131,7 +1133,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
/** What GitHub's read says for an agent about to take [group]'s work (store.ts pushOriginFor): a bot's push marks the task and
* refuses the main account, and the store keeps that mark after this command is refused. Unknown refuses it unmarked. */
const pushedRefusal = (group: Conversation, worker: Agent) => {
- marking(group, () => applyPushOrigin(state, group, context.pushOrigin, context.pushOriginPulls))
+ marking(group, () => applyPushOrigin(state, group, context.pushOrigin, context.pushOriginPulls, context.pushOriginTask))
if (onTeamAccount(state, worker) || ledProject(state, worker.id)?.id === groupProject(state, group).id) return
if (context.pushOrigin === 'unknown') failPushUnknown(unknownPushReason(context.repositoryReach))
if (context.pushOrigin === 'team') failTeamWritten({ pushed: true })
@@ -1758,7 +1760,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
agentIds: leadId ? [leadId] : [], archived: false, brief, reviewOf: task.id,
// A step keeps its task's mark, as conversation.create's does (teamWritten.ts stepMark).
...stepMark(state, task), step: planned.name,
- assignment: null, lastMessageSequence: 0, checks: storedChecks([{ description: stepCheck(planned), independent: true }], id) })
+ assignment: null, lastMessageSequence: 0, codePullRequestUrls: [], 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'))
@@ -2572,7 +2574,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
...(command.reviewOf ? stepMark(state, conversation(state, command.reviewOf)) : {}),
...(command.step ? { step: command.step } : {}),
...(prioritized ? { priority: command.priority ?? (proposal ? proposalPriority(proposalNamed(context.proposal)?.source?.priority) : DEFAULT_PRIORITY) } : {}),
- assignment: null, lastMessageSequence: 0,
+ // Its own code's pull requests, read for its Team-written mark: never a link in a post (task #3554, model.ts).
+ assignment: null, lastMessageSequence: 0, codePullRequestUrls: [],
checks: storedChecks(command.checks, operationId),
})
stampLane(state.conversations.at(-1)!)
@@ -2714,6 +2717,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
?? fail('PULL_REQUEST_REPOSITORY', `This pull request is not in the project's repository (${own!.fullName}).`, 400)
const shippedAt = group.ledger?.shippedAt, linked = group.pullRequestUrls?.includes(pullRequestUrl)
appendPullRequestUrls(group, [pullRequestUrl], repositoryUrl)
+ // The pull request that merged is the task's own code.
+ appendCodePullRequestUrls(group, [pullRequestUrl], repositoryUrl)
recordMerged(group, mergedAt)
// On its project's release list, for the next verified release to mark it shipped (releases.ts, task #3405). A Swarm from
// before projects keeps no list: its one project is not stored.
@@ -2896,7 +2901,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// that names no model runs its engine's own: role defaults live in the project's instructions now.
// So does a start for code a Team agent wrote, whoever's project it is, with its project settings off (audit H2).
const startGroup = conversation(state, command.request.conversationId)
- marking(startGroup, () => applyPushOrigin(state, startGroup, context.pushOrigin, context.pushOriginPulls))
+ marking(startGroup, () => applyPushOrigin(state, startGroup, context.pushOrigin, context.pushOriginPulls, context.pushOriginTask))
const written = teamWrittenTask(state, startGroup)
// Named the Team account's entry itself, which its owner's choice keeps teammates' work off (task #3060). A branch GitHub
// cannot place runs only in a Team account (below), so it counts as Team-written here (security review 2 of #3081).
@@ -4093,7 +4098,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
else effects.result.notAsked = `Not asked ${agentWrittenNameOf(state, person(state, personId).id)}: ${context.openDecisions} decisions you asked them are still open, and at most ${MAX_OPEN_DECISIONS} can be. Wait for answers before asking more.`
}
// A Team agent's push can land on any branch: its Ready reads who pushed (teamWritten.ts, audit H2).
- if (command.status === 'review') marking(group, () => applyPushOrigin(state, group, context.pushOrigin, context.pushOriginPulls))
+ if (command.status === 'review') marking(group, () => applyPushOrigin(state, group, context.pushOrigin, context.pushOriginPulls, context.pushOriginTask))
const changed = assignment.status !== command.status || assignment.result !== command.result || !!command.ask, previous = assignment.status
const waited = waitingForReview(assignment)
assignment.status = command.status
diff --git a/backend/src/superTabs/mergeCarry.test.ts b/backend/src/superTabs/mergeCarry.test.ts
new file mode 100644
index 000000000..7f189df9b
--- /dev/null
+++ b/backend/src/superTabs/mergeCarry.test.ts
@@ -0,0 +1,57 @@
+/**
+ * A verdict carries over a main merge git resolves by itself (task #3553, 11-06): about 40 review rounds overnight only
+ * confirmed that a new head was the reviewed head plus a clean merge of main. A head carries its first parent's verdicts only
+ * when it is exactly git's automatic merge of that parent and a commit of the base branch; any hand-resolved line, any other
+ * change, or any file both sides changed needs a reviewer again.
+ */
+import { describe, expect, it } from 'vitest'
+import { cleanMainMergeOf, type MergeSides } from './mergeCarry.js'
+import type { PullRequestFile } from './pullRequestPatch.js'
+
+const H = 'a'.repeat(40), B = 'b'.repeat(40)
+const file = (filename: string, sha: string, status = 'modified', previousFilename?: string): PullRequestFile =>
+ ({ filename, status, sha, ...previousFilename ? { previousFilename } : {} })
+/** The pull request changed app.ts; main changed README.md and lib.ts; the merge brought exactly main's two files. */
+const clean = (): MergeSides => ({
+ parents: [H, B], onBase: true,
+ prSide: [file('app.ts', 'p1')],
+ mainSide: [file('README.md', 'm1'), file('lib.ts', 'm2')],
+ mergeSide: [file('lib.ts', 'm2'), file('README.md', 'm1')],
+})
+
+describe('a head that is a clean main merge', () => {
+ it('carries its first parent\'s verdicts when it is exactly git\'s automatic merge', () => {
+ expect(cleanMainMergeOf(clean())).toBe(H)
+ // Main added and removed files too: the merge brings them as main has them.
+ expect(cleanMainMergeOf({ ...clean(), mainSide: [file('new.ts', 'n1', 'added'), file('old.ts', 'o1', 'removed')],
+ mergeSide: [file('new.ts', 'n1', 'added'), file('old.ts', 'o1', 'removed')] })).toBe(H)
+ })
+
+ it('carries nothing when a line was resolved or changed by hand in the merge', () => {
+ // lib.ts as main has it is m2; the merge commit has another blob.
+ expect(cleanMainMergeOf({ ...clean(), mergeSide: [file('lib.ts', 'edited'), file('README.md', 'm1')] })).toBeNull()
+ // A file main never changed, changed in the merge commit.
+ expect(cleanMainMergeOf({ ...clean(), mergeSide: [...clean().mergeSide, file('app.ts', 'p2')] })).toBeNull()
+ // A file main changed, left out of the merge.
+ expect(cleanMainMergeOf({ ...clean(), mergeSide: [file('lib.ts', 'm2')] })).toBeNull()
+ // A file listed twice in the merge, standing for another main changed (security review of #3284, Minor 2).
+ expect(cleanMainMergeOf({ ...clean(), mergeSide: [file('lib.ts', 'm2'), file('lib.ts', 'm2')] })).toBeNull()
+ // The same blob with another status (a removal kept, a rename made a copy).
+ expect(cleanMainMergeOf({ ...clean(), mainSide: [file('old.ts', 'o1', 'removed')], mergeSide: [file('old.ts', 'o1', 'modified')] })).toBeNull()
+ })
+
+ it('carries nothing when both sides changed a file: git merges its lines, which needs a reviewer to read', () => {
+ expect(cleanMainMergeOf({ ...clean(), mainSide: [file('app.ts', 'm3')], mergeSide: [file('app.ts', 'm3')] })).toBeNull()
+ // A rename on one side of a file the other changed is both sides too.
+ expect(cleanMainMergeOf({ ...clean(), mainSide: [file('app2.ts', 'm4', 'renamed', 'app.ts')], mergeSide: [file('app2.ts', 'm4', 'renamed', 'app.ts')] })).toBeNull()
+ })
+
+ it('carries nothing for a commit that is not a merge of main', () => {
+ expect(cleanMainMergeOf({ ...clean(), parents: [H] })).toBeNull()
+ expect(cleanMainMergeOf({ ...clean(), parents: [H, B, 'c'.repeat(40)] })).toBeNull()
+ // Its second parent is not on the branch the pull request merges into.
+ expect(cleanMainMergeOf({ ...clean(), onBase: false })).toBeNull()
+ // A merge that brought nothing from main is no main merge.
+ expect(cleanMainMergeOf({ ...clean(), mainSide: [], mergeSide: [] })).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/mergeCarry.ts b/backend/src/superTabs/mergeCarry.ts
new file mode 100644
index 000000000..62598f7c0
--- /dev/null
+++ b/backend/src/superTabs/mergeCarry.ts
@@ -0,0 +1,50 @@
+/**
+ * A verdict carries over a main merge git resolves by itself (task #3553, Dee's Swarm redesign, 11-06): about 40 review rounds
+ * overnight only confirmed that a pull request's new head was its reviewed head plus a clean merge of main. A head carries its
+ * first parent's verdicts (checkVerdicts.ts verdictCounts) only when it is exactly git's automatic merge of that parent and a
+ * commit of the branch the pull request merges into, judged here from GitHub's own comparisons (github/app.ts mainMergeSides),
+ * never from anything the pull request says.
+ *
+ * Exactly git's merge: no file is changed on both sides since their merge base (git would merge its lines, and nobody read
+ * that result), and the merge commit changes from its first parent exactly the files main changed, each to main's own blob
+ * with main's own status. Then every path of the merge holds either the reviewed blob or main's, as git's merge would; any
+ * hand-resolved line, any added change, any file left out, is another blob or another file, and carries nothing. GitHub's
+ * comparisons give no file mode, so a mode alone changed on a file main also changed is not seen (named in #3553's security
+ * review).
+ */
+import type { PullRequestFile } from './pullRequestPatch.js'
+
+/** What GitHub says of a head, to judge it (github/app.ts mainMergeSides): its parents; whether its second parent is on the
+ * branch the pull request merges into; and the files of each side since the merge base of its two parents (the pull
+ * request's side, from it to the first parent; main's, from it to the second), and from the first parent to the head. */
+export interface MergeSides {
+ parents: string[]
+ onBase: boolean
+ prSide: PullRequestFile[]
+ mainSide: PullRequestFile[]
+ mergeSide: PullRequestFile[]
+}
+
+/** Every path a side touches, a rename's old name too: a file renamed on one side and changed on the other is on both. */
+const paths = (files: readonly PullRequestFile[]): Set<string> =>
+ new Set(files.flatMap(f => f.previousFilename ? [f.filename, f.previousFilename] : [f.filename]))
+
+/** A file as its blob, status and old name: what the merge must give it, as main has it. */
+const as = (f: PullRequestFile) => `${f.status}\0${f.previousFilename ?? ''}\0${f.sha}`
+
+/** The head whose verdicts [sides]' head carries, its first parent, when the head is exactly git's automatic merge of it and a
+ * commit of the base branch; else null. */
+export function cleanMainMergeOf(sides: MergeSides): string | null {
+ const [parent, merged] = sides.parents
+ if (sides.parents.length !== 2 || !parent || !merged || !sides.onBase || !sides.mainSide.length) return null
+ // A file both sides changed is merged line by line by git: a reviewer reads that result.
+ const ours = paths(sides.prSide)
+ if ([...paths(sides.mainSide)].some(path => ours.has(path))) return null
+ // The merge changes exactly main's files, each as main has it.
+ if (sides.mergeSide.length !== sides.mainSide.length || new Set(sides.mergeSide.map(f => f.filename)).size !== sides.mergeSide.length) return null
+ const main = new Map(sides.mainSide.map(f => [f.filename, as(f)]))
+ return sides.mergeSide.every(f => main.get(f.filename) === as(f)) && main.size === sides.mainSide.length ? parent : null
+}
+
+/** The most heads one head's verdicts may carry from: a chain of clean main merges, newest first. */
+export const CARRIES_KEPT = 20
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index dfa411ed5..a8daf7df5 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -287,7 +287,10 @@ export interface CheckVerdict { by: string; passed: boolean; evidence: string; a
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 }
+ base?: string
+ /** The heads whose verdicts this one carries, newest first, at most CARRIES_KEPT: it is git's own merge of the first and
+ * main, the first of the next, and so on (mergeCarry.ts, task #3553). Absent on any other head. */
+ carries?: string[] }
export interface Assignment {
id: string
agentId: string
@@ -420,6 +423,10 @@ export interface Conversation {
heardAt?: number
/** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */
pullRequestUrls?: string[]
+ /** The pull requests its own code is in, which GitHub's push read covers for its Team-written mark (teamWritten.ts, task
+ * #3554): those its brief, title, assignment's result, checks' evidence and merge record name, never links in posts. [] from
+ * its creation; absent on a conversation from before, which reads what it recorded instead (codePullRequests). */
+ codePullRequestUrls?: string[]
/** When its brief was last set (conversation.create, work.define): a person's rule moved into this task leaves the
* instructions only for a pull request GitHub says merged after it (ruleGuard.ts rulePlaces, #3463). No command writes
* it otherwise. Absent on a task from before. */
@@ -539,6 +546,20 @@ export function projectPullRequestUrl(url: string, repositoryUrl: string | null
export const pullRequestLinks = (text: string, repositoryUrl?: string | null): string[] => [...new Set([...text.matchAll(/https:\/\/github\.com\/[A-Za-z0-9_-]+\/[A-Za-z0-9_.-]+\/pull\/([1-9][0-9]*)\b/g)]
.filter(match => Number(match[1]) <= Number.MAX_SAFE_INTEGER).flatMap(match => projectPullRequestUrl(match[0], repositoryUrl) ?? []))]
+/** The pull requests [group]'s own code is in (codePullRequestUrls). A conversation from before the list reads every link it
+ * recorded, posts' included: an access rule loses no protection it had (task #3554). */
+export const codePullRequests = (group: Pick<Conversation, 'codePullRequestUrls' | 'pullRequestUrls'>): string[] =>
+ group.codePullRequestUrls ?? group.pullRequestUrls ?? []
+
+/** Adds the pull request links of [texts], its own code's sources, to [group]'s code list, and corrects the ones it holds. A
+ * conversation from before the list gets none: it keeps reading what it recorded (codePullRequests). */
+export function appendCodePullRequestUrls(group: Conversation, texts: Iterable<string | null | undefined>, repositoryUrl?: string | null): void {
+ if (group.codePullRequestUrls === undefined) return
+ const urls = new Set(group.codePullRequestUrls.flatMap(url => projectPullRequestUrl(url, repositoryUrl) ?? []))
+ for (const text of texts) if (text) for (const url of pullRequestLinks(text, repositoryUrl)) urls.add(url)
+ group.codePullRequestUrls = [...urls]
+}
+
/** Adds the pull request links of [texts] to [group] and corrects the ones it holds, by the project's [repositoryUrl]. */
export function appendPullRequestUrls(group: Conversation, texts: Iterable<string | null | undefined>, repositoryUrl?: string | null): void {
const urls = new Set((group.pullRequestUrls ?? []).flatMap(url => projectPullRequestUrl(url, repositoryUrl) ?? []))
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index f785e8573..71f3749b8 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -41,6 +41,7 @@ const conversation: Required<Conversation> = {
buddySessions: [],
cards: {},
checks: [],
+ codePullRequestUrls: [],
dormant: false,
handOutLane: 'Desktop',
heardAt: 0,
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index 25aaecc57..9537d2794 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -70,6 +70,7 @@ export const GROUP_FIELDS = {
'buddySessions',
'cards',
'checks',
+ 'codePullRequestUrls',
'handOutLane',
'heardAt',
'hold',
diff --git a/backend/src/superTabs/pullRequestEvents.ts b/backend/src/superTabs/pullRequestEvents.ts
index ba8eabcd9..3d205b128 100644
--- a/backend/src/superTabs/pullRequestEvents.ts
+++ b/backend/src/superTabs/pullRequestEvents.ts
@@ -7,6 +7,7 @@ import { PULL_PATCH_PERMISSIONS, PULL_WATCH_PERMISSIONS, type GitHubApp } from '
import { githubRepository, type GitHubRepository } from '../github/repository.js'
import type { SuperTabStore } from './store.js'
import type { PullRequestHead } from './model.js'
+import { cleanMainMergeOf } from './mergeCarry.js'
import { patchId } from './pullRequestPatch.js'
import { watchedLinks } from './checkVerdicts.js'
import { logger } from '../utils/logger.js'
@@ -116,6 +117,9 @@ 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>
+ /** The head whose verdicts [head] carries, when it is git's own merge of that head and a commit of [base] (mergeCarry.ts,
+ * task #3553), else null: judged from GitHub's comparisons, never from what the pull request says. */
+ merge(url: string, head: string, base: string): Promise<string | null>
botLogin(): Promise<string | null>
done(): Promise<void>
}
@@ -160,6 +164,12 @@ export function appPullRequestWatch(app: GitHubApp): PullRequestReader {
const read = await app.pullRequestPatchFiles(repository, number, granted, head)
return read && read.base === base ? patchId(read.files, read.base) : null
}),
+ // Whether the head is git's own merge of its first parent and main, against the base the watch saw: an answer naming
+ // another branch carries nothing.
+ merge: (url, head, base) => read(url, PULL_PATCH_PERMISSIONS, async (repository, number, granted) => {
+ const read = await app.mainMergeSides(repository, number, granted, head)
+ return read && read.base === base ? cleanMainMergeOf(read.sides) : null
+ }),
botLogin: () => app.botLogin(),
async done() {
for (const granted of tokens.values()) {
@@ -209,12 +219,21 @@ export async function watchPullRequests(db: PrismaClient, store: Pick<SuperTabSt
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 }> = []
+ // A head new to a task is asked whether it is git's own merge of another head and main (#3553), once a pass.
+ const merges = new Map<string, Promise<string | null>>()
+ const mergeOf = (url: string, head: string, base: string) => {
+ const key = `${url}@${head}@${base}`
+ if (!merges.has(key)) merges.set(key, reader.merge(url, head, base).catch(() => null))
+ return merges.get(key)!
+ }
+ const seen: Array<{ row: typeof rows[number]; watch: PullRequestWatch; patch: string | null | undefined; merged: string | null | undefined }> = []
for (const row of rows) {
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 })
+ const known = row.heads?.[url] ?? undefined, newHead = known?.head !== watch.head || known.base !== watch.base
+ seen.push({ row, watch, patch: patchNeeded(known, watch) ? await patchOf(url, watch.head, watch.base) : undefined,
+ merged: newHead ? await mergeOf(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
@@ -235,10 +254,10 @@ export async function watchPullRequests(db: PrismaClient, store: Pick<SuperTabSt
}
}
let posted = 0
- for (const { row, watch, patch } of seen) {
+ for (const { row, watch, patch, merged } 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)
+ posted += await store.pullRequestSeen(row.tabId, row.key, watch, bot, patch, row.steps ?? lookedUp ?? [], lookedUp !== undefined, merged ?? null)
} catch (error) {
logger.warn('[swarm-pr-events] group skipped', { tabId: row.tabId, group: row.key, error: error instanceof Error ? error.message : String(error) })
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 32b8cf4b3..99b913511 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -55,6 +55,7 @@ import { DELETED_TEXT, type MessageChangeTarget } from './messageEdits.js'
import { isBuddy, isBuddyChat, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'
import { TURN_END_WAIT_MS, waitsForTurnEnd, withTurnEnd } from './turnEnd.js'
import { crewNeedOf } from './crewNeeds.js'
+import { CARRIES_KEPT } from './mergeCarry.js'
import { swarmUsernames } from './usernames.js'
import { crewNeedLine, gathersForInbox, inboxDue, inboxSection, owedLines, personLine, turnInboxHost, type InboxSection } from './inbox.js'
import { lostReasonWithoutMachine } from './lostReason.js'
@@ -103,7 +104,7 @@ import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
import { activeMember, addMember, hasWorkspaceAccess, latestRemovalAt, listWorkspaces, memberId, removedFromWorkspace, WORKSPACE_ACCESS_REVOKED, workspaceForNewSwarm, requireWorkspaceAccess, requireWorkspaceRole, SwarmWorkspaces } from './workspaceStore.js'
import { WORKSPACE_LABEL, workspaceCan, type WorkspaceRole } from './workspaces.js'
import { STATUS_LABELS,
- activeWork, handed, occupiesAgent, actorKey, agent, agentOnly, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,
+ activeWork, handed, occupiesAgent, actorKey, agent, agentOnly, appendCodePullRequestUrls, appendPullRequestUrls, codePullRequests, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,
SuperTabError, isLeads, knownKind, parkLaterConversations, type Actor, type Agent, type Assignment, type Author, type CommandEffects, type Conversation, type MessageDraft, type Person, type SuperTabState,
projectPullRequestUrl, pullRequestLinks,
} from './model.js'
@@ -1553,7 +1554,7 @@ export class SuperTabStore {
* nothing to read, or this reader cannot read that task: the command then refuses as it would. `pulls` are the pull requests
* it read (none for a branch): a clean read clears only a mark it covered (teamWritten.ts applyPushOrigin, #3304).
*/
- private async pushOriginFor(user: AuthUser, tabId: string, command: unknown): Promise<{ origin: PushOrigin; pulls: string[] } | undefined> {
+ private async pushOriginFor(user: AuthUser, tabId: string, command: unknown): Promise<{ origin: PushOrigin; pulls: string[]; task?: { origin: PushOrigin; pulls: string[] } } | undefined> {
const hook = this.hooks.pushOrigin
const asked = command as { type?: unknown; conversationId?: unknown; status?: unknown; result?: unknown; present?: unknown; projectId?: unknown; branchRef?: unknown;
request?: { branchRef?: unknown; conversationId?: unknown } } | null
@@ -1579,15 +1580,28 @@ export class SuperTabStore {
if (!group) return null
const task = group.reviewOf ? state.conversations.find(c => c.id === group.reviewOf) : undefined
const repositoryUrl = groupProject(state, group).repository?.repositoryUrl ?? null
- const urls = [...group.pullRequestUrls ?? [], ...task?.pullRequestUrls ?? [],
- ...[group.brief, group.title, task?.brief, task?.title, typeof asked.result === 'string' ? asked.result : ''].flatMap(text => text ? pullRequestsIn(text, repositoryUrl) : [])]
- return { repositoryUrl, urls: [...new Set(urls)], step: !!group.reviewOf }
+ // Only the code each is in: links posted in a task or a step mark nothing (task #3554, model.ts codePullRequests).
+ const codeOf = (c: Conversation) => [...codePullRequests(c), ...[c.brief, c.title].flatMap(text => text ? pullRequestsIn(text, repositoryUrl) : [])]
+ const named = typeof asked.result === 'string' ? pullRequestsIn(asked.result, repositoryUrl) : []
+ const own = [...new Set(task ? codeOf(task) : [...codeOf(group), ...named])]
+ // A step's own pull requests (its brief, its agent's results) are read apart: they mark the step, not its task.
+ const stepOnly = task ? [...new Set([...codeOf(group), ...named])].filter(url => !own.includes(url)) : []
+ return { repositoryUrl, own, stepOnly, step: !!group.reviewOf }
})
if (!facts) return undefined
// Only what the reader reads covers a mark: the project's own repository's pull requests (pushOrigin.ts projectPushOrigin),
// which answers clean for none of them (security review 2 of #3304).
- const read = githubRepository(facts.repositoryUrl) ? facts.urls.flatMap(url => projectPullRequestUrl(url, facts.repositoryUrl) ?? []) : []
- if (facts.urls.length) return { origin: await hook(facts.repositoryUrl, facts.urls), pulls: read }
+ const covered = (urls: string[]) => githubRepository(facts.repositoryUrl) ? urls.flatMap(url => projectPullRequestUrl(url, facts.repositoryUrl) ?? []) : []
+ const urls = [...facts.own, ...facts.stepOnly]
+ if (!facts.step && urls.length) return { origin: await hook(facts.repositoryUrl, urls), pulls: covered(urls) }
+ if (urls.length) {
+ const [task, step] = await Promise.all([facts.own.length ? hook(facts.repositoryUrl, facts.own) : undefined,
+ facts.stepOnly.length ? hook(facts.repositoryUrl, facts.stepOnly) : undefined])
+ const answers = [task, step].filter((a): a is PushOrigin => !!a)
+ const origin: PushOrigin = answers.includes('team') ? 'team' : answers.includes('unknown') ? 'unknown' : 'clean'
+ // With no code of the task's own named, nothing shows whose it is: the task is read as the step's answer, as before.
+ return { origin, pulls: covered(urls), ...task ? { task: { origin: task, pulls: covered(facts.own) } } : {} }
+ }
// A step reads or runs a branch, and with no pull request named nothing shows whose. It may name one in a sentence no read
// can parse, and then its agent runs `gh pr checkout` itself (security review 2 of #2559).
return facts.step && facts.repositoryUrl && githubRepository(facts.repositoryUrl) ? { origin: 'unknown', pulls: [] } : undefined
@@ -1983,7 +1997,7 @@ export class SuperTabStore {
context.otherWorkspaceMachines = await this.otherWorkspaceMachines(tx, original)
if (this.hooks.teamAccountsIdle) context.teamAccountsIdle = true
}
- if (pushOrigin) Object.assign(context, { pushOrigin: pushOrigin.origin, pushOriginPulls: pushOrigin.pulls })
+ if (pushOrigin) Object.assign(context, { pushOrigin: pushOrigin.origin, pushOriginPulls: pushOrigin.pulls, ...pushOrigin.task ? { pushOriginTask: pushOrigin.task } : {} })
if (repositoryReach) context.repositoryReach = repositoryReach
if (pullRequestFiles && command.type === 'work.status') {
context.pullRequestFiles = pullRequestFiles
@@ -2016,6 +2030,16 @@ export class SuperTabStore {
...shown.filter(message => message.conversationId === group.id).map(message => message.text),
...group.checks.map(check => check.evidence), group.assignment?.result,
], repositoryUrl)
+ // Its own code's sources: what GitHub's push read covers for its Team-written mark (task #3554). In a task, a post by a
+ // person, the project's PM or the task's own builder names its code too: where a builder is told what to merge, or links
+ // its own pull request (security reviews of #3286). Another agent's post (a Team reviewer's verdict, log lines) or one in a
+ // step, the project chat or a private chat never does (River's ruling on #3462 and #3514).
+ const task = !group.reviewOf && !group.kind && !group.audience && !projectsOf(effects.state).some(p => p.leadConversationId === group.id)
+ const codePosts = task ? shown.filter(message => message.conversationId === group.id && (message.author.kind === 'person'
+ || message.author.id === group.assignment?.agentId
+ || (message.author.kind === 'agent' && ledProject(effects.state, message.author.id)?.id === groupProject(effects.state, group).id)))
+ .map(message => message.text) : []
+ appendCodePullRequestUrls(group, [group.brief, group.title, ...group.checks.map(check => check.evidence), group.assignment?.result, ...codePosts], repositoryUrl)
cleanPullRequestLinks(group, repositoryUrl)
}
if (command.type === 'agent.rebind') {
@@ -5030,7 +5054,7 @@ export class SuperTabStore {
* 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> {
+ stepIds: readonly string[] = [], lookedUp = false, merged: string | null = null): 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
@@ -5051,8 +5075,13 @@ export class SuperTabStore {
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.
+ // A new head that is git's own merge of another head and main carries that head's verdicts, and those it carried when
+ // it was the head before, on the same base (mergeCarry.ts, #3553); a head re-read for its patch keeps what it carries.
+ const carries = !newHead ? known!.carries
+ : merged ? [merged, ...known && known.base === watch.base && known.head.toLowerCase() === merged.toLowerCase() ? known.carries ?? [] : []].slice(0, CARRIES_KEPT)
+ : undefined
group.pullRequestHeads = keepHead(group.pullRequestHeads, watch.url, { head: watch.head, base: watch.base, patch: patch ?? null,
- at: patch === undefined ? 0 : now }, group.pullRequestUrls)
+ at: patch === undefined ? 0 : now, ...carries?.length ? { carries } : {} }, 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)
}
diff --git a/backend/src/superTabs/teamWritten.test.ts b/backend/src/superTabs/teamWritten.test.ts
index d2a86341f..1c88a35b4 100644
--- a/backend/src/superTabs/teamWritten.test.ts
+++ b/backend/src/superTabs/teamWritten.test.ts
@@ -3,7 +3,7 @@ import { applyCommand, type Command, type CommandContext } from './commands.js'
import type { ContributedMachine } from './machines.js'
import { createSuperTab, SuperTabError, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
import { LEAD_CAPABILITY } from './leadStart.js'
-import { TEAM_WRITTEN_STOP, TEAM_WRITTEN_WORK, teamWrittenTask } from './teamWritten.js'
+import { applyPushOrigin, TEAM_WRITTEN_STOP, TEAM_WRITTEN_WORK, teamWrittenTask } from './teamWritten.js'
// Audit H2: a branch a Team agent wrote runs only in a Team account, whoever's project it is, so nothing the branch
// carries runs with the main account's rights (docs/plans/2026-11-02-team-written-branch-plan.md).
@@ -378,6 +378,8 @@ describe('a task a Team agent worked on', () => {
const joinMarked = (f: ReturnType<typeof swarm>, recorded: string[]) => {
const task = f.group(), stored = f.state.conversations.find(c => c.id === task)!
stored.teamWritten = true
+ // From before #3554 too: no code list, so it reads every pull request it recorded.
+ delete stored.codePullRequestUrls
stored.pullRequestUrls = recorded
return { task, step: f.group({ reviewOf: task, step: 'Review' }) }
}
@@ -402,7 +404,7 @@ describe('a task a Team agent worked on', () => {
it('keeps the mark of a Team agent assigned to build the task', () => {
const f = swarm(), task = f.written(), stored = f.state.conversations.find(c => c.id === task)!
- stored.pullRequestUrls = [P]
+ stored.codePullRequestUrls = [P]
stored.assignment = null
expect(assignMain(f, f.group({ reviewOf: task, step: 'Review' }), [P])).toBe(TEAM_WRITTEN_WORK)
expect(marked(f, task)).toBe(true)
@@ -410,7 +412,7 @@ describe('a task a Team agent worked on', () => {
it('keeps a bot push\'s mark until it covers the pull requests that push was read on', () => {
const f = swarm(), task = f.group()
- f.state.conversations.find(c => c.id === task)!.pullRequestUrls = [P]
+ f.state.conversations.find(c => c.id === task)!.codePullRequestUrls = [P]
f.run({ type: 'work.teamWritten', conversationId: task }, owner, { pushOrigin: 'team', pushOriginPulls: [P, Q] })
const step = f.group({ reviewOf: task, step: 'Review' })
expect(assignMain(f, step, [P])).toBe(TEAM_WRITTEN_WORK)
@@ -420,7 +422,7 @@ describe('a task a Team agent worked on', () => {
it('keeps the mark of a bot\'s push on a branch a start named', () => {
const f = swarm(), task = f.group()
- f.state.conversations.find(c => c.id === task)!.pullRequestUrls = [P]
+ f.state.conversations.find(c => c.id === task)!.codePullRequestUrls = [P]
f.run({ type: 'agent.start', request: { conversationId: task, machineId: 'mac', engine: 'claude', name: 'Tester', cwd: '/swarm/lead', worktree: true, branchRef: 'refs/remotes/origin/fix', requirements } }, owner, { pushOrigin: 'team' })
expect(assignMain(f, f.group({ reviewOf: task, step: 'Review' }), [P])).toBe(TEAM_WRITTEN_WORK)
expect(marked(f, task)).toBe(true)
@@ -429,7 +431,7 @@ describe('a task a Team agent worked on', () => {
it('keeps a step\'s own mark from a bot\'s push on the pull request it records', () => {
const f = swarm(), { task, step } = joinMarked(f, [P])
const other = f.group({ reviewOf: task, step: 'Test' }), stored = f.state.conversations.find(c => c.id === other)!
- stored.pullRequestUrls = [Q]
+ stored.codePullRequestUrls = [Q]
expect(assignMain(f, step, [P])).toBeNull()
expect(marked(f, task)).toBeUndefined()
expect(marked(f, other)).toBe(true)
@@ -442,3 +444,36 @@ describe('a task a Team agent worked on', () => {
expect(teamWrittenTask(f.state, stored)).toBe(true)
})
})
+
+// Task #3554: a step's own links (a reviewer's verdict citing another pull request) are read for the step alone. The task is marked
+// only by the read of its own code, which the store passes beside the step's.
+describe('a step\'s push read', () => {
+ const OWN = 'https://github.com/acme/app/pull/7', OTHER = 'https://github.com/acme/app/pull/99'
+ const setup = () => {
+ const s = swarm()
+ const task = s.group(), step = s.group({ reviewOf: task, step: 'Review' } as Partial<Extract<Command, { type: 'conversation.create' }>>)
+ const find = (id: string) => s.state.conversations.find(c => c.id === id)!
+ return { s, task: () => find(task), step: () => find(step) }
+ }
+
+ it('marks only the step when its own links read Team and the task\'s code reads clean', () => {
+ const f = setup()
+ applyPushOrigin(f.s.state, f.step(), 'team', [OTHER, OWN], { origin: 'clean', pulls: [OWN] })
+ expect(f.step().teamWritten).toBe(true)
+ expect(f.task().teamWritten).toBeUndefined()
+ })
+
+ it('marks the task and the step when the task\'s own code reads Team', () => {
+ const f = setup()
+ applyPushOrigin(f.s.state, f.step(), 'team', [OWN], { origin: 'team', pulls: [OWN] })
+ expect(f.task().teamWritten).toBe(true)
+ expect(f.task().teamWrittenBy).toEqual({ kind: 'pushed', pulls: [OWN] })
+ expect(f.step().teamWritten).toBe(true)
+ })
+
+ it('marks the task as before when no read of its own code is given', () => {
+ const f = setup()
+ applyPushOrigin(f.s.state, f.step(), 'team', [OTHER])
+ expect(f.task().teamWritten).toBe(true)
+ })
+})
diff --git a/backend/src/superTabs/teamWritten.ts b/backend/src/superTabs/teamWritten.ts
index 87e7fa112..65a602070 100644
--- a/backend/src/superTabs/teamWritten.ts
+++ b/backend/src/superTabs/teamWritten.ts
@@ -10,7 +10,7 @@
* GitHub read covers every pull request it rests on (applyPushOrigin).
*/
import type { PushOrigin } from '../github/pushOrigin.js'
-import { fail, type Agent, type Conversation, type SuperTabState } from './model.js'
+import { codePullRequests, fail, type Agent, type Conversation, type SuperTabState } from './model.js'
import { groupProject, ledProject, onTeamAccount, teamAccountPool } from './projects.js'
export const TEAM_WRITTEN_WORK = 'TEAM_WRITTEN_WORK'
@@ -97,26 +97,32 @@ export function mainAccountMembers(state: SuperTabState, group: Conversation, ex
}
/**
- * GitHub's record of who pushed [pulls], the pull requests the store read (none for a branch). A bot among them marks [group]
- * and its task. A clean read clears a mark only where it covered everything that mark rests on (#3304): every pull request
- * the task and that conversation record, and for a push's mark the pull requests it was read on. An assignment's mark and a
+ * GitHub's record of who pushed [pulls], the pull requests the store read (none for a branch). A bot among them marks [group],
+ * and its task too unless [group] is a step and [taskRead], the read of the task's own code, is not team (#3554). A clean read
+ * clears a mark only where it covered everything that mark rests on (#3304): the code each of the task and that conversation
+ * is in (model.ts codePullRequests), and for a push's mark the pull requests it was read on. An assignment's mark and a
* branch's stay. A pull request recorded after the read was not covered, so it clears nothing.
*/
-export function applyPushOrigin(state: SuperTabState, group: Conversation, origin: PushOrigin | undefined, pulls: readonly string[] = []): void {
+export function applyPushOrigin(state: SuperTabState, group: Conversation, origin: PushOrigin | undefined, pulls: readonly string[] = [],
+ taskRead?: { origin: PushOrigin; pulls: readonly string[] }): void {
const task = taskOf(state, group)
- if (origin === 'team') {
- const cause: Cause = pulls.length ? { kind: 'pushed', pulls: [...new Set(pulls)] } : { kind: 'branch' }
- if (task) mark(task, cause)
- mark(group, cause)
+ // A step's own links (a reviewer citing another pull request, log lines) are read for the step alone; its task is marked by the
+ // read of the task's own code (task #3554: #3462 was marked for its Team reviewers' links). Without that read, as before.
+ const own = group.reviewOf && taskRead ? taskRead : { origin, pulls }
+ const causeOf = (read: readonly string[]): Cause => read.length ? { kind: 'pushed', pulls: [...new Set(read)] } : { kind: 'branch' }
+ if (origin === 'team' || own.origin === 'team') {
+ if (task && own.origin === 'team') mark(task, causeOf(own.pulls))
+ if (origin === 'team') mark(group, causeOf(pulls))
return
}
- if (origin !== 'clean' || !task?.pullRequestUrls?.length) return
+ const code = task ? codePullRequests(task) : []
+ if (origin !== 'clean' || !task || !code.length) return
const read = new Set(pulls.map(url => url.toLowerCase()))
const covers = (urls: readonly string[]) => urls.every(url => read.has(url.toLowerCase()))
- if (!covers(task.pullRequestUrls)) return
+ if (!covers(code)) return
for (const marked of [task, ...state.conversations.filter(c => c.reviewOf === task.id)]) {
const by = marked.teamWrittenBy
- if (!marked.teamWritten || (by && (by.kind !== 'pushed' || !covers(by.pulls))) || !covers(marked.pullRequestUrls ?? [])) continue
+ if (!marked.teamWritten || (by && (by.kind !== 'pushed' || !covers(by.pulls))) || !covers(codePullRequests(marked))) continue
delete marked.teamWritten
delete marked.teamWrittenBy
}
diff --git a/docs/plans/2026-11-06-team-mark-own-code-plan.md b/docs/plans/2026-11-06-team-mark-own-code-plan.md
new file mode 100644
index 000000000..915a4ea75
--- /dev/null
+++ b/docs/plans/2026-11-06-team-mark-own-code-plan.md
@@ -0,0 +1,71 @@
+# A task's Team-written mark rests on its own code, not on links in its chat (task #3554)
+
+> Implemented by its Engineer test first, by superpowers:test-driven-development, as the project's instructions say
+> (Engineer role). No subagent-driven-development and no execution handoff.
+
+**Goal:** A task is marked Team-written only when a Team agent's code is on its own branch: a Team builder, or GitHub's
+record of a bot's push on the task's own pull requests. A link to another pull request posted in the task or in one of
+its steps (a reviewer's verdict, log lines, a batch) no longer marks it. On 11-06 that blocked main-account agents from
+#3462 and #3514, which they had built themselves (River's ruling in #3554).
+
+**As built after the security reviews (SecAlder, SecLarch):** in a task itself, a post by a person, the project's PM or
+the task's own assignee is a code source too: that is where a builder is told what to merge, and a squash or a rebase of a
+Team pull request leaves only the builder's own commits on its branch, which GitHub's read cannot tell from its own. Another
+agent's post (a Team reviewer's verdict, log lines), or any post in a step, the project chat or a private chat, never is.
+
+**Architecture:** Today every message shown in a conversation adds the full pull request links in its text to that
+conversation's `pullRequestUrls` (store.ts execute). The push read before an assignment, a start or a Ready
+(store.ts `pushOriginFor`) asks GitHub about all of them, and for a step about the task's too. A step's Team answer marks
+its task (teamWritten.ts `applyPushOrigin`). The fix gives each conversation a second list, `codePullRequestUrls`: the pull
+requests named in its brief and title, its assignment's result, its checks' evidence and its merge record, never in posts.
+The push read uses that list. For a step it reads the task's code and the step's own separately, and the step's own
+answer marks only the step. `pullRequestUrls` stays as it is for cards, task lines and releases.
+
+**Tech Stack:** TypeScript, vitest; the Super Tab store and command reducer; integration tests on a MongoDB memory replica set.
+
+**Spec:** task #3554's brief and River's ruling of 11-06 in it (build as proposed; two security reviews; both check that a
+main-account builder told to merge a Team pull request into its branch still ends up marked).
+
+## Global Constraints
+
+- An access rule: never weaker for an unknown. A task from before this change (no `codePullRequestUrls`) reads what it
+ recorded before, `pullRequestUrls`, so nothing it was protected by is lost.
+- A Team agent's push on the task's own pull request marks it, as now. GitHub's read is unchanged (github/pushOrigin.ts).
+- Swarm code stays in backend/src/superTabs.
+
+## Design
+
+- growth: one list per conversation, of this project's pull request links; it is deleted with its conversation.
+- concurrency: written inside the command's transaction, like `pullRequestUrls`.
+- read cost: none added for a task; a step's Ready, assign or start asks GitHub twice (its task's code, then its own)
+ where it asked once. Answers are kept per head (github/app.ts), so a repeat costs nothing.
+- scale: at 10x the GitHub read budget warns first (app.ts pushOrigin cache); nothing here grows with posts.
+- compatibility: an older server ignores the field and reads `pullRequestUrls` as before; a task from before reads what
+ it recorded (above).
+- migration + rollback: none. Rolling back reads `pullRequestUrls` again, the old behaviour.
+- audience: the server alone writes and reads the field; no client sends it.
+- identity: GitHub's record of who pushed; never a commit's author or a login.
+- failure: an unreadable answer stays `unknown`, which refuses the main account, as now.
+- platforms: server only.
+
+## Review Focus
+
+- No path where a Team agent's code lands on the task's own branch without the task being marked at the next read:
+ a Team builder, a bot's push on the task's own pull request, and a main-account builder that merged a Team pull request
+ into its branch (its own pull request then holds commits the bot pushed: pushOrigin.ts reads `team`).
+- A step's own links mark the step, so a main-account agent is still refused on it.
+- A task from before keeps its protection.
+
+## Task 1: the push read covers a task's own code
+
+**Files:** `backend/src/superTabs/model.ts`, `store.ts` (execute's link loop, `pushOriginFor`), `commands.ts` (creation,
+`conversation.merged`), `teamWritten.ts` (`applyPushOrigin`); tests `backend/integration/superTabTeam.test.ts`,
+`backend/src/superTabs/teamWritten.test.ts`, `backend/src/github/pushOrigin.test.ts`.
+
+**Interfaces:** `Conversation.codePullRequestUrls?: string[]`; `codePullRequests(group, repositoryUrl)` (model.ts);
+`applyPushOrigin(state, group, origin, pulls, taskRead?)` where `taskRead` is the task's own answer for a step.
+
+- [ ] Failing tests: a link to a Team-pushed pull request posted in a task is not read, and the task's own is; a step's
+ posted links mark the step, not its task; a bot's push on the task's own pull request still marks it; a task from before
+ reads what it recorded; a main-account builder's pull request that took a Team pull request's commits reads `team`.
+- [ ] Implement.
diff --git a/docs/plans/2026-11-06-verdict-carry-main-merge.md b/docs/plans/2026-11-06-verdict-carry-main-merge.md
new file mode 100644
index 000000000..f68b00704
--- /dev/null
+++ b/docs/plans/2026-11-06-verdict-carry-main-merge.md
@@ -0,0 +1,53 @@
+# A verdict carries over git's own main merge (task #3553)
+
+> Requested by Dee through Harness. Built test first: each test commit comes before its code.
+
+**Goal:** about 40 reviewer rounds on the night of 11-05 only confirmed that a pull request's new head was its reviewed head
+plus a merge of main. When git made that merge by itself, the verdict carries to the new head. A merge with any
+hand-resolved line, or any other commit, still needs a reviewer.
+
+## Design
+
+- **Where it is judged:** the PR watch (`superTabs/pullRequestEvents.ts`) asks, for a head that is new to a task, whether the
+ head is git's own merge of another head and main (`reader.merge`). The answer is computed by the server from GitHub,
+ never taken from the pull request.
+- **What GitHub is asked** (`github/app.ts mainMergeSides`, read-only token): the pull request (it must still name the
+ head; its base branch and base commit), the head's parents (`GET /git/commits`), whether the second parent is on the base
+ branch (`GET /compare/{second}...{base commit}` is identical or ahead), and three comparisons of fixed commits. It
+ compares against the commit, never the branch name, which a tag of the same name could shadow (security review,
+ Important 1). Main's side runs from
+ the first parent to the second. The pull request's side runs from the second to the first. The merge side runs from the
+ first parent to the head. A side at GitHub's file cap (300) answers nothing.
+- **The judge** (`superTabs/mergeCarry.ts cleanMainMergeOf`, pure): the head carries its first parent only when all of
+ these hold:
+ - It has exactly two parents, and the second is on the base branch.
+ - Main changed something.
+ - No path (a rename's old name included) was changed on both sides.
+ - The merge changes exactly main's files, each with main's blob, status and old name, and no file is listed twice.
+
+ Then every path of the head holds the reviewed blob or main's, which is git's own merge. A hand-resolved line or an extra
+ change is another blob or another file.
+- **Where it is kept:** `PullRequestHead.carries` (at most 20, newest first). A clean merge of the head the task recorded
+ before, on the same base, carries that head and what it carried, so a chain of clean merges keeps the verdict.
+ `verdictCounts` counts a verdict at a head that carries its own head, on the verdict's own base only, by the full commit
+ id.
+
+## What still needs a reviewer
+
+- Any file both sides changed. Git would merge its lines, and the server can't reproduce that merge from GitHub's API
+ without a checkout. This is the safe side: some clean merges still need a review.
+- Any merge with a hand-resolved line, an added change, or a file left out; any non-merge commit; a merge from a commit
+ not on the base branch; a merge whose sides GitHub can't fully list.
+
+## Residual, for the security review
+
+GitHub's comparisons give each file's blob and status, but not its mode. A mode change alone (an executable bit) made in the
+merge commit on a file main also changed, to the same content, would not be seen. A mode change on any other file adds a
+file to the merge side and carries nothing.
+
+## Cost
+
+- Only for a head new to a task, once per pass: one more pull request read, one commit read, and for a two-parent head
+ whose second parent is on the base, one branch compare and three file compares. All are read-only, through the token
+ the patch read already takes.
+- Nothing changes on a request path. `verdictCounts` adds an in-memory check of at most 20 ids.