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.

Check PR history when a task becomes ready for review (#3443)

harness-for-autonomous[bot]081ddcc1cb67
diff --git a/backend/integration/superTabReviewSteps.test.ts b/backend/integration/superTabReviewSteps.test.ts
index 017aae143..3d1eed636 100644
--- a/backend/integration/superTabReviewSteps.test.ts
+++ b/backend/integration/superTabReviewSteps.test.ts
@@ -75,6 +75,22 @@ describe('a Ready through the store', () => {
expect([...listed ?? []].sort()).toEqual(opened.sort())
})
+ it('persists history evidence in every review brief on Ready', async () => {
+ const head = 'a'.repeat(40)
+ const { tab, execute, task, dev, assignment } = await swarm({ pullRequestFiles: async (_repository, urls) => ({ urls, head,
+ files: ['backend/src/routes/auth.ts'], heads: [{ url: `${REPO}/pull/7`, head, base: 'main', history: { head,
+ planFirst: 'pass', testBeforeCode: 'fail', productionLines: 42, totalLines: 64, commits: 3, merges: 0, missingTests: ['b'.repeat(40)] } }] }) })
+ await execute({ type: 'work.status', conversationId: task, assignmentId: assignment, status: 'review', result: `Ready: ${REPO}/pull/7` }, host, dev)
+ const rows = await db.swarmGroup.findMany({ where: { tabId: tab } })
+ const steps = rows.map(row => row.data as { reviewOf?: string; brief?: string }).filter(group => group.reviewOf === task)
+ expect(steps).toHaveLength(2)
+ for (const step of steps) {
+ expect(step.brief).toContain('Plan first: pass')
+ expect(step.brief).toContain('Test before code: fail')
+ expect(step.brief).toContain('42 production lines')
+ }
+ })
+
it('plans by the project\'s saved rules record', async () => {
const pullRequestFiles = vi.fn(async (_repository: string | null, urls: string[]) => ({ urls, head: 'abc1234', files: ['docs/a.md'] }))
const { tab, execute, task, dev, assignment } = await swarm({ pullRequestFiles })
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 92672ec76..a3b200ca9 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,3 +1,4 @@
+import type { PullRequestFilesRead } from './pullRequestFiles.js'
import { migrateLegacyProposals, type LegacyProposalAsk, pmAcceptsMessage, applyProposalAction, authorizeProposalAction, authorizePersonProposal, cardPriority, createPersonProposal, createProposalCard, proposalCreateSchema, proposalFields, proposalRoot } from './proposalCards.js'
import { pulseProjectOf, recordPulse, owe, settleDeleted, settleReaction, settleReply, settleRequest } from './pulse.js'
import { applyPushOrigin, failPushUnknown, failTeamWritten, mainAccountMembers, markTeamWritten, mayName, requireTeamWrittenAccount, requireTeamWrittenMachine, stepMark, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
@@ -23,7 +24,7 @@ import {
} from './model.js'
import { jobKindOf } from './evidence/jobKind.js'
import { endSteps, stepEndedRows, isStep, stepName, stepsOf, taskOwner } from './steps.js'
-import { reviewPlan, stepBrief, stepCheck, type PlannedStep, type StepKind } from './reviewTable.js'
+import { reviewPlan, stepBrief, stepCheck, refreshStepBrief, type PlannedStep, type StepKind } from './reviewTable.js'
import { builtBy, reviewerCandidates } from './reviewerPick.js'
import { recordCheckVerdict } from './checkVerdicts.js'
import { routeRecordSchema, routeTitle, startedAs, type KeptCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
@@ -698,7 +699,7 @@ export interface CommandContext {
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 }> }
+ pullRequestFiles?: PullRequestFilesRead
/** Whether the Harness GitHub App reaches the project's repository, read before an agent.start or work.assign (store.ts repositoryReachFor). */
repositoryReach?: RepositoryReach
/** The person's role in the Swarm's Workspace, read by the store for invitations (workspaces.ts); absent outside a Workspace. */
@@ -1882,7 +1883,11 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
for (const planned of reviewPlan(read.files, context.projectRules?.rules)) {
const free = (step: Conversation) => !taken.has(step.id)
let step = existing.find(s => free(s) && stepName(s) === planned.name) ?? existing.find(s => free(s) && stepKind(s) === planned.kind)
- if (step) taken.add(step.id)
+ if (step) {
+ taken.add(step.id)
+ step.brief = refreshStepBrief(step.brief ?? '', planned, { number: task.number!, title: task.title,
+ pulls: read.heads ?? read.urls.map((url, i) => ({ url, head: i === 0 ? read.head : null })) })
+ }
if (step && activeWork(step)) continue
// A step whose every check passed at this very head keeps its verdict: a repeated Ready (a CI rerun) asks nothing again.
if (step && read.head && step.checks.length && step.checks.every(check => check.passedBy
diff --git a/backend/src/superTabs/prHistory.test.ts b/backend/src/superTabs/prHistory.test.ts
new file mode 100644
index 000000000..8c3d10f2d
--- /dev/null
+++ b/backend/src/superTabs/prHistory.test.ts
@@ -0,0 +1,75 @@
+import { execFileSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { describe, expect, it } from 'vitest'
+import { checkPrHistory } from './prHistory.js'
+
+const sha = (n: number) => n.toString(16).padStart(40, '0')
+const file = (filename: string, additions = 1, deletions = 0, extra = {}) => ({ filename, additions, deletions, status: 'added', ...extra })
+const commit = (n: number, files: ReturnType<typeof file>[], parents = [sha(n - 1)]) => ({ sha: sha(n), parents, files })
+const plan = file('docs/plans/2026-11-06-example-plan.md')
+const test = file('backend/src/example.test.ts', 7)
+const code = file('backend/src/example.ts', 12, 3)
+const good = () => ({ head: sha(3), commits: [commit(1, [plan]), commit(2, [test]), commit(3, [code])], files: [plan, test, code] })
+
+describe('PR history checks', () => {
+ it('reports a plan first, prior test-only commit and net production size', () => {
+ expect(checkPrHistory(good())).toMatchObject({ planFirst: 'pass', testBeforeCode: 'pass', productionLines: 15, totalLines: 23,
+ commits: 3, missingTests: [] })
+ })
+
+ it.each([
+ { commits: [commit(1, [code]), commit(2, [plan]), commit(3, [test])] },
+ { commits: [commit(1, [plan, test]), commit(2, [test]), commit(3, [code])] },
+ { commits: [commit(1, [file(plan.filename, 1, 0, { status: 'modified' })]), commit(2, [test]), commit(3, [code])] },
+ ])('does not accept a late, mixed or pre-existing plan', ({ commits }) => {
+ expect(checkPrHistory({ ...good(), commits }).planFirst).toBe('fail')
+ })
+
+ it('does not treat tests in the implementation commit or later as prior tests', () => {
+ const together = { ...good(), head: sha(2), commits: [commit(1, [plan]), commit(2, [test, code])] }
+ expect(checkPrHistory(together)).toMatchObject({ testBeforeCode: 'fail', missingTests: [sha(2)] })
+ const late = { ...good(), commits: [commit(1, [plan]), commit(2, [code]), commit(3, [test])] }
+ expect(checkPrHistory(late)).toMatchObject({ testBeforeCode: 'fail', missingTests: [sha(2)] })
+ })
+
+ it('needs another test-only commit before another production commit', () => {
+ const input = { ...good(), head: sha(4), commits: [...good().commits, commit(4, [code])] }
+ expect(checkPrHistory(input)).toMatchObject({ testBeforeCode: 'fail', missingTests: [sha(4)] })
+ })
+
+ it('does not borrow a test from a sibling branch', () => {
+ const input = { ...good(), commits: [commit(1, [plan]), commit(2, [test]), commit(3, [code], [sha(1)])] }
+ expect(checkPrHistory(input)).toMatchObject({ testBeforeCode: 'fail', missingTests: [sha(3)] })
+ })
+
+ it('reports docs-only changes as not needing production ordering', () => {
+ expect(checkPrHistory({ head: sha(1), commits: [commit(1, [file('README.md')])], files: [file('README.md')] }))
+ .toMatchObject({ planFirst: 'not-needed', testBeforeCode: 'not-needed', productionLines: 0, totalLines: 1 })
+ })
+
+ it('flags merges for a resolution read rather than declaring their test order passed', () => {
+ expect(checkPrHistory({ ...good(), head: sha(4), commits: [...good().commits, commit(4, [code], [sha(3), sha(99)])] }))
+ .toMatchObject({ planFirst: 'pass', testBeforeCode: 'unknown', merges: 1 })
+ })
+
+ it('classifies both sides of a rename and does not count repeated commit churn as net size', () => {
+ const renamed = file('docs/example.md', 4, 2, { status: 'renamed', previousFilename: 'backend/src/example.ts' })
+ expect(checkPrHistory({ ...good(), files: [renamed] })).toMatchObject({ productionLines: 6, totalLines: 6 })
+ expect(checkPrHistory({ ...good(), head: sha(5), commits: [...good().commits, commit(4, [test]), commit(5, [code])] }).productionLines).toBe(15)
+ })
+
+ it.each([null, {}, { ...good(), commits: [] }, { ...good(), head: sha(9) },
+ { ...good(), commits: [...good().commits].reverse() }, { ...good(), files: [file('x.ts', -1)] },
+ { ...good(), files: Array.from({ length: 301 }, () => code) },
+ { ...good(), commits: Array.from({ length: 51 }, (_, n) => commit(n + 1, [test])) },
+ ])('never passes malformed, missing or excessive input', input => {
+ expect(checkPrHistory(input)).toMatchObject({ planFirst: 'unknown', testBeforeCode: 'unknown', productionLines: null })
+ })
+
+ it('runs the scripts entry point on sample JSON without executing repository code', () => {
+ const script = fileURLToPath(new URL('../../../scripts/check-pr-history.ts', import.meta.url))
+ const output = execFileSync(process.execPath, ['--import', import.meta.resolve('tsx'), script],
+ { input: JSON.stringify(good()), encoding: 'utf8', timeout: 10_000, windowsHide: true })
+ expect(JSON.parse(output)).toMatchObject({ planFirst: 'pass', testBeforeCode: 'pass', productionLines: 15 })
+ })
+})
diff --git a/backend/src/superTabs/prHistory.ts b/backend/src/superTabs/prHistory.ts
new file mode 100644
index 000000000..b4a991c94
--- /dev/null
+++ b/backend/src/superTabs/prHistory.ts
@@ -0,0 +1,68 @@
+/** Ready's history evidence (#3597). Paths and ancestry prove order, never a test's failure or semantic coverage. */
+import { z } from 'zod'
+
+export const HISTORY_COMMITS = 50
+export const HISTORY_FILES = 300
+const sha = z.string().regex(/^[a-f0-9]{40}$/)
+const path = z.string().min(1).max(1024).refine(value => !value.startsWith('/') && !value.split('/').includes('..'))
+const file = z.object({ filename: path, previousFilename: path.optional(), status: z.string().min(1).max(20),
+ additions: z.number().int().min(0).max(1_000_000_000), deletions: z.number().int().min(0).max(1_000_000_000) })
+const history = z.object({ head: sha, commits: z.array(z.object({ sha, parents: z.array(sha).max(2),
+ files: z.array(file).max(HISTORY_FILES) })).min(1).max(HISTORY_COMMITS), files: z.array(file).max(HISTORY_FILES) })
+type File = z.infer<typeof file>
+export type HistoryState = 'pass' | 'fail' | 'unknown' | 'not-needed'
+export interface HistoryReport {
+ head: string | null
+ planFirst: HistoryState
+ testBeforeCode: HistoryState
+ productionLines: number | null
+ totalLines: number | null
+ commits: number | null
+ merges: number | null
+ missingTests: string[]
+}
+export const unknownHistory = (head: string | null = null): HistoryReport => ({ head, planFirst: 'unknown', testBeforeCode: 'unknown',
+ productionLines: null, totalLines: null, commits: null, merges: null, missingTests: [] })
+
+function pathKind(name: string): 'docs' | 'test' | 'code' {
+ if (/(^|\/)(?:__tests__|tests?|integration|e2e|fixtures)(\/|$)|(?:^|\/)test_[^/]+\.[^/]+$|\.(?:test|spec|test-support)\.[^/]+$|_test\.dart$/i.test(name)) return 'test'
+ return /^docs\//.test(name) || /\.(?:md|rst|txt)$/i.test(name) ? 'docs' : 'code'
+}
+function kind(file: File): ReturnType<typeof pathKind> {
+ const kinds = [file.filename, ...file.previousFilename ? [file.previousFilename] : []].map(pathKind)
+ return kinds.includes('code') ? 'code' : kinds.includes('test') ? 'test' : 'docs'
+}
+
+/** Commit order is oldest first and checked against local parents. Size is the net PR diff, never commit churn. */
+export function checkPrHistory(input: unknown): HistoryReport {
+ // Reject excessive lists before schema validation walks their contents.
+ const value = input as z.infer<typeof history> | null
+ if (!value || !Array.isArray(value.commits) || value.commits.length > HISTORY_COMMITS || !Array.isArray(value.files)
+ || value.files.length > HISTORY_FILES || value.commits.some(c => !c || !Array.isArray(c.files) || c.files.length > HISTORY_FILES)) return unknownHistory()
+ const parsed = history.safeParse(input)
+ if (!parsed.success) return unknownHistory()
+ const { head, commits, files } = parsed.data
+ const bySha = new Map(commits.map((commit, index) => [commit.sha, { ...commit, index }]))
+ if (bySha.size !== commits.length || commits.at(-1)!.sha !== head || commits.some((commit, index) =>
+ commit.parents.some(parent => bySha.has(parent) && bySha.get(parent)!.index >= index))) return unknownHistory(head)
+ const hasCode = (commit: typeof commits[number]) => commit.files.some(f => kind(f) === 'code')
+ const production = commits.filter(c => c.parents.length < 2 && hasCode(c))
+ const merges = commits.filter(c => c.parents.length === 2).length
+ const needsOrder = production.length > 0 || files.some(f => kind(f) === 'code')
+ const first = commits.find(c => c.parents.length < 2)
+ const planFirst = !needsOrder ? 'not-needed' : first && first.files.every(f => kind(f) === 'docs')
+ && first.files.some(f => /^docs\/plans\/[^/]+-plan\.md$/.test(f.filename) && f.status === 'added') ? 'pass' : 'fail'
+ const missingTests: string[] = []
+ for (const commit of production) {
+ let parent = bySha.get(commit.parents[0] ?? '')
+ let priorTest = false
+ while (parent && parent.parents.length < 2 && !hasCode(parent)) {
+ if (parent.files.some(f => kind(f) === 'test')) { priorTest = true; break }
+ parent = bySha.get(parent.parents[0] ?? '')
+ }
+ if (!priorTest) missingTests.push(commit.sha)
+ }
+ return { head, planFirst, testBeforeCode: !needsOrder ? 'not-needed' : missingTests.length ? 'fail' : merges ? 'unknown' : 'pass',
+ productionLines: files.filter(f => kind(f) === 'code').reduce((sum, f) => sum + f.additions + f.deletions, 0),
+ totalLines: files.reduce((sum, f) => sum + f.additions + f.deletions, 0), commits: commits.length, merges, missingTests }
+}
diff --git a/backend/src/superTabs/prHistoryRead.test.ts b/backend/src/superTabs/prHistoryRead.test.ts
new file mode 100644
index 000000000..5220881e2
--- /dev/null
+++ b/backend/src/superTabs/prHistoryRead.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from 'vitest'
+import { readPrHistory } from './prHistoryRead.js'
+import { githubRepository } from '../github/repository.js'
+
+const repository = githubRepository('https://github.com/acme/app')!
+const sha = (n: number) => n.toString(16).padStart(40, '0')
+const file = (filename: string, additions = 1) => ({ filename, additions, deletions: 0, status: 'added' })
+const files = [file('docs/plans/example-plan.md'), file('src/a.test.ts'), file('src/a.ts', 4)]
+function fixture() {
+ const get = vi.fn(async (path: string, _token: string): Promise<{ status: number; body: unknown; next?: string }> => {
+ if (path === '/repos/acme/app/pulls/7') return { status: 200, body: { head: { sha: sha(3) }, commits: 3, changed_files: 3 } }
+ if (path === '/repos/acme/app/pulls/7/commits?per_page=100&page=1') return { status: 200,
+ body: files.map((_, n) => ({ sha: sha(n + 1), parents: [{ sha: sha(n) }] })) }
+ if (path === '/repos/acme/app/pulls/7/files?per_page=100&page=1') return { status: 200, body: files }
+ const match = /^\/repos\/acme\/app\/commits\/([a-f0-9]{40})\?per_page=100&page=1$/.exec(path)
+ if (match) { const n = Number.parseInt(match[1]!, 16); return { status: 200, body: { sha: sha(n), files: [files[n - 1]] } } }
+ throw new Error('Unexpected endpoint')
+ })
+ return { get, run: () => readPrHistory(get, repository, 7, 'private-token', sha(3)) }
+}
+
+describe('Ready reads bounded history facts', () => {
+ it('computes a report from GitHub commit ancestry and net PR counts', async () => {
+ expect(await fixture().run()).toMatchObject({ head: sha(3), planFirst: 'pass', testBeforeCode: 'pass', productionLines: 4 })
+ })
+
+ it.each([
+ { head: { sha: sha(9) }, commits: 3, changed_files: 3 },
+ { head: { sha: sha(3) }, commits: 51, changed_files: 3 },
+ { head: { sha: sha(3) }, commits: 3, changed_files: 301 },
+ { head: { sha: sha(3) }, commits: 4, changed_files: 3 },
+ { head: { sha: sha(3) }, commits: 3, changed_files: 4 },
+ ])('marks a different head, excessive or incomplete list unknown', async meta => {
+ const f = fixture(), original = f.get.getMockImplementation()!
+ f.get.mockImplementation(async (path, token) => path.endsWith('/pulls/7') ? { status: 200, body: meta } : original(path, token))
+ expect(await f.run()).toMatchObject({ planFirst: 'unknown', testBeforeCode: 'unknown', productionLines: null })
+ })
+
+ it('rejects incomplete commit files and reports API errors without including their contents', async () => {
+ const f = fixture(), original = f.get.getMockImplementation()!
+ f.get.mockImplementation(async (path, token) => path.includes('/commits/000') ? { status: 200,
+ body: { sha: sha(1), files: Array.from({ length: 100 }, () => files[0]) }, next: '/untrusted' } : original(path, token))
+ expect(await f.run()).toMatchObject({ planFirst: 'unknown' })
+ f.get.mockRejectedValue(new Error('private-token'))
+ expect(JSON.stringify(await f.run())).not.toContain('private-token')
+ })
+
+ it('does not start any read once the read budget is exhausted', async () => {
+ const f = fixture()
+ expect(await readPrHistory(f.get, repository, 7, 'private-token', sha(3), 0)).toMatchObject({ planFirst: 'unknown' })
+ expect(f.get).not.toHaveBeenCalled()
+ })
+})
+
+
+it('paginates through fixed paths, ignoring an untrusted next URL', async () => {
+ const f = fixture(), original = f.get.getMockImplementation()!
+ const docs = Array.from({ length: 101 }, (_, n) => file(`docs/page-${n}.md`))
+ f.get.mockImplementation(async (path, token) => {
+ if (path.endsWith('/pulls/7')) return { status: 200, body: { head: { sha: sha(3) }, commits: 3, changed_files: 101 } }
+ if (path.includes('/pulls/7/files?')) return path.endsWith('page=1')
+ ? { status: 200, body: docs.slice(0, 100), next: 'https://untrusted.invalid/private-token' }
+ : { status: 200, body: docs.slice(100) }
+ if (path.includes(`/commits/${sha(1)}?`)) return path.endsWith('page=1')
+ ? { status: 200, body: { sha: sha(1), files: docs.slice(0, 100) }, next: 'https://untrusted.invalid/private-token' }
+ : { status: 200, body: { sha: sha(1), files: docs.slice(100) } }
+ return original(path, token)
+ })
+ expect(await f.run()).toMatchObject({ planFirst: 'fail', testBeforeCode: 'pass', totalLines: 101 })
+ expect(f.get.mock.calls.every(([path]) => path.startsWith('/repos/acme/app/'))).toBe(true)
+ expect(f.get).toHaveBeenCalledWith(`/repos/acme/app/commits/${sha(1)}?per_page=100&page=2`, 'private-token')
+})
+
+it('rejects malformed commit details rather than reporting a partial pass', async () => {
+ const f = fixture(), original = f.get.getMockImplementation()!
+ f.get.mockImplementation(async (path, token) => path.includes(`/commits/${sha(3)}?`)
+ ? { status: 200, body: { sha: sha(3), files: [{ ...file('src/a.ts'), additions: -1 }] } } : original(path, token))
+ expect(await f.run()).toMatchObject({ planFirst: 'unknown', productionLines: null })
+})
diff --git a/backend/src/superTabs/prHistoryRead.ts b/backend/src/superTabs/prHistoryRead.ts
new file mode 100644
index 000000000..ec6dc9aef
--- /dev/null
+++ b/backend/src/superTabs/prHistoryRead.ts
@@ -0,0 +1,59 @@
+/** Read metadata only from the project's GitHub repository. Never run PR code or follow caller-supplied pagination URLs. */
+import { z } from 'zod'
+import type { GitHubApp } from '../github/app.js'
+import type { GitHubRepository } from '../github/repository.js'
+import { checkPrHistory, HISTORY_COMMITS, HISTORY_FILES, unknownHistory, type HistoryReport } from './prHistory.js'
+
+export const HISTORY_READ_MS = 10_000
+const sha = z.string().regex(/^[a-f0-9]{40}$/)
+const meta = z.object({ head: z.object({ sha }), commits: z.number().int().min(1).max(HISTORY_COMMITS),
+ changed_files: z.number().int().min(0).max(HISTORY_FILES) })
+const commit = z.object({ sha, parents: z.array(z.object({ sha })).max(2) })
+
+/** The API has a ten-second timeout per call; stop starting reads after a shared ten-second Ready budget.
+ * Four concurrent commit reads, three file pages each at most. A partial read is always unknown. */
+export async function readPrHistory(get: GitHubApp['get'], repository: GitHubRepository, number: number, token: string,
+ head: string, until = Date.now() + HISTORY_READ_MS): Promise<HistoryReport> {
+ const unknown = () => unknownHistory(head)
+ const base = `/repos/${repository.owner}/${repository.name}`
+ const read = async (path: string) => Date.now() >= until ? null : await get(path, token)
+ try {
+ const pull = await read(`${base}/pulls/${number}`)
+ const parsed = meta.safeParse(pull?.status === 200 ? pull.body : null)
+ if (!parsed.success || parsed.data.head.sha !== head) return unknown()
+ const listed = await read(`${base}/pulls/${number}/commits?per_page=100&page=1`)
+ if (listed?.status !== 200 || listed.next || !Array.isArray(listed.body) || listed.body.length !== parsed.data.commits) return unknown()
+ const commits = z.array(commit).max(HISTORY_COMMITS).safeParse(listed.body)
+ if (!commits.success || commits.data.at(-1)?.sha !== head) return unknown()
+ const files = async (path: string, at?: string): Promise<unknown[] | null> => {
+ const kept: unknown[] = []
+ for (let page = 1; page <= HISTORY_FILES / 100; page++) {
+ const answer = await read(`${path}?per_page=100&page=${page}`)
+ if (answer?.status !== 200) return null
+ const body = answer.body as { sha?: unknown; files?: unknown } | null
+ const rows = at ? body?.sha === at ? body.files : null : answer.body
+ if (!Array.isArray(rows) || rows.length > 100) return null
+ kept.push(...rows)
+ if (!answer.next) return kept
+ }
+ return null
+ }
+ const net = await files(`${base}/pulls/${number}/files`)
+ if (!net || net.length !== parsed.data.changed_files) return unknown()
+ const facts: Array<{ sha: string; parents: string[]; files: unknown[] }> = []
+ for (let i = 0; i < commits.data.length; i += 4) {
+ const batch = await Promise.all(commits.data.slice(i, i + 4).map(async c => ({ sha: c.sha, parents: c.parents.map(p => p.sha),
+ files: await files(`${base}/commits/${c.sha}`, c.sha) })))
+ if (batch.some(c => c.files === null)) return unknown()
+ facts.push(...batch as typeof facts)
+ }
+ // Normalize the API's snake-case rename field without copying patches, messages or author data.
+ const clean = (rows: unknown[]) => rows.map(value => {
+ const f = value as Record<string, unknown> | null
+ return { filename: f?.filename, previousFilename: f?.previous_filename, status: f?.status, additions: f?.additions, deletions: f?.deletions }
+ })
+ return checkPrHistory({ head, commits: facts.map(c => ({ ...c, files: clean(c.files) })), files: clean(net) })
+ } catch {
+ return unknown()
+ }
+}
diff --git a/backend/src/superTabs/pullRequestFiles.test.ts b/backend/src/superTabs/pullRequestFiles.test.ts
index f776d21eb..d2be3a6b6 100644
--- a/backend/src/superTabs/pullRequestFiles.test.ts
+++ b/backend/src/superTabs/pullRequestFiles.test.ts
@@ -19,12 +19,22 @@ describe('projectPullRequestFiles', () => {
it('reads the head and the file names of the project\'s own pull requests, then revokes its token', async () => {
const app = fakeApp({ 7: ['a.ts', 'b.ts'], 8: ['b.ts', 'c.ts'] }, { 7: 'abc1234', 8: 'def5678' })
const read = await projectPullRequestFiles(app)(REPO, [`${REPO}/pull/7`, `${REPO}/pull/8`, 'https://github.com/other/repo/pull/9'])
- expect(read).toEqual({ urls: [`${REPO}/pull/7`, `${REPO}/pull/8`], head: 'abc1234', files: ['a.ts', 'b.ts', 'c.ts'],
+ expect(read).toMatchObject({ urls: [`${REPO}/pull/7`, `${REPO}/pull/8`], head: 'abc1234', files: ['a.ts', 'b.ts', 'c.ts'],
heads: [{ url: `${REPO}/pull/7`, head: 'abc1234', base: 'main' }, { url: `${REPO}/pull/8`, head: 'def5678', base: 'main' }] })
expect(app.pullRequestFiles).toHaveBeenCalledTimes(2)
expect(app.revoke).toHaveBeenCalledWith('read-token')
})
+ it('attaches unknown history when it cannot be read, preserving the files and revoking the read-only token', async () => {
+ const app = fakeApp({ 7: ['a.ts'] }, { 7: 'a'.repeat(40) })
+ Object.assign(app, { get: vi.fn(async () => { throw new Error('history unavailable') }) })
+ const read = await projectPullRequestFiles(app)(REPO, [`${REPO}/pull/7`])
+ expect(read?.files).toEqual(['a.ts'])
+ expect(read?.heads?.[0]?.history).toMatchObject({ head: 'a'.repeat(40), planFirst: 'unknown', productionLines: null })
+ expect(app.createToken).toHaveBeenCalledWith(1, expect.anything(), expect.objectContaining({ contents: 'read', pull_requests: 'read' }))
+ expect(app.revoke).toHaveBeenCalledWith('read-token')
+ })
+
it('reads the files nothing pushed over: a head that moved while they were listed reads as unreadable', async () => {
const app = fakeApp({ 7: ['a.ts'] }, { 7: 'abc1234' })
let reads = 0
@@ -60,3 +70,38 @@ describe('projectPullRequestFiles', () => {
expect(broken.revoke).toHaveBeenCalled()
})
})
+
+
+function historyApp() {
+ const h = (n: number) => String(n).repeat(40)
+ const app = fakeApp({ 7: ['docs/a.md'], 8: ['src/a.ts'] }, { 7: h(7), 8: h(8) })
+ app.get = vi.fn(async path => {
+ const number = path.includes('/pulls/7') || path.includes(h(7)) ? 7 : 8
+ const filename = number === 7 ? 'docs/a.md' : 'src/a.ts'
+ const files = [{ filename, additions: number, deletions: 0, status: 'added' }]
+ if (/\/pulls\/\d+$/.test(path)) return { status: 200, body: { head: { sha: h(number) }, commits: 1, changed_files: 1 } }
+ if (path.includes('/pulls/') && path.includes('/commits?')) return { status: 200, body: [{ sha: h(number), parents: [] }] }
+ if (path.includes('/pulls/')) return { status: 200, body: files }
+ return { status: 200, body: { sha: h(number), files } }
+ })
+ return app
+}
+
+it('collects distinct complete history reports for multiple project PRs', async () => {
+ const read = await projectPullRequestFiles(historyApp())(REPO, [`${REPO}/pull/7`, `${REPO}/pull/8`])
+ expect(read?.heads).toMatchObject([
+ { head: '7'.repeat(40), history: { head: '7'.repeat(40), planFirst: 'not-needed', productionLines: 0, totalLines: 7 } },
+ { head: '8'.repeat(40), history: { head: '8'.repeat(40), planFirst: 'fail', productionLines: 8, totalLines: 8 } },
+ ])
+})
+
+it.each(['head', 'base'])('invalidates complete history if the %s moves during collection', async field => {
+ const app = historyApp()
+ let watches = 0
+ app.watchPullRequest = vi.fn(async () => ++watches === 1 ? { head: '7'.repeat(40), base: 'main' }
+ : { head: field === 'head' ? '9'.repeat(40) : '7'.repeat(40), base: field === 'base' ? 'other' : 'main' })
+ const read = await projectPullRequestFiles(app)(REPO, [`${REPO}/pull/7`])
+ expect(app.get).toHaveBeenCalled()
+ expect(read?.heads?.[0]?.history).toMatchObject({ planFirst: 'unknown', productionLines: null })
+ if (field === 'head') expect(read?.files).toBeNull()
+})
diff --git a/backend/src/superTabs/pullRequestFiles.ts b/backend/src/superTabs/pullRequestFiles.ts
index b45c57c00..c16a92616 100644
--- a/backend/src/superTabs/pullRequestFiles.ts
+++ b/backend/src/superTabs/pullRequestFiles.ts
@@ -5,10 +5,13 @@
*/
import { PULL_WATCH_PERMISSIONS, type GitHubApp } from '../github/app.js'
import { githubRepository, type GitHubRepository } from '../github/repository.js'
+import { HISTORY_READ_MS, readPrHistory } from './prHistoryRead.js'
+import { unknownHistory, type HistoryReport } from './prHistory.js'
import { logger } from '../utils/logger.js'
/** What this read needs of the app: the pull request's head from its watch read, and its files (github/app.ts). */
export interface PullRequestFilesApp {
+ get?: GitHubApp['get']
resolve: GitHubApp['resolve']
createToken: GitHubApp['createToken']
revoke: GitHubApp['revoke']
@@ -18,7 +21,7 @@ export interface PullRequestFilesApp {
/** What the store gives a Ready's command: the pull requests read, the first one's head (what a verdict is held to), each
* one's own head, and every file they change. */
-export interface PullRequestFilesRead { urls: string[]; head: string | null; files: string[] | null; heads?: Array<{ url: string; head: string | null; base?: string | null }> }
+export interface PullRequestFilesRead { urls: string[]; head: string | null; files: string[] | null; heads?: Array<{ url: string; head: string | null; base?: string | null; history?: HistoryReport }> }
const MAX_PULLS = 5
const PULL = /^https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/([1-9][0-9]*)$/
@@ -41,17 +44,21 @@ export const projectPullRequestFiles = (app: PullRequestFilesApp) =>
try {
const resolved = await app.resolve(repository)
if (!resolved) return read
- token = (await app.createToken(resolved.installation, resolved.repository, PULL_WATCH_PERMISSIONS)).token
+ token = (await app.createToken(resolved.installation, resolved.repository, { ...PULL_WATCH_PERMISSIONS, contents: 'read' })).token
const files = new Set<string>(), heads: NonNullable<PullRequestFilesRead['heads']> = []
+ const until = Date.now() + HISTORY_READ_MS
for (const [i, pull] of own.entries()) {
// The files of the head the watch read: when a push moved it while they were listed, they read as unreadable.
const watch = await app.watchPullRequest(resolved.repository, pull.number, token)
if (i === 0) read.head = watch?.head ?? null
- heads.push({ url: pull.url, head: watch?.head ?? null, base: watch?.base ?? null })
const listed = watch ? await app.pullRequestFiles(resolved.repository, pull.number, token) : null
+ const history = watch && listed && app.get
+ ? await readPrHistory(app.get.bind(app), resolved.repository, pull.number, token, watch.head, until) : unknownHistory(watch?.head ?? null)
const after = listed ? await app.watchPullRequest(resolved.repository, pull.number, token) : null
const changed = listed && after?.head === watch!.head ? listed : null
- if (!changed) return { ...read, files: null }
+ heads.push({ url: pull.url, head: watch?.head ?? null, base: watch?.base ?? null,
+ history: changed && after?.base === watch?.base ? history : unknownHistory(watch?.head ?? null) })
+ if (!changed) return { ...read, files: null, heads }
for (const file of changed) files.add(file.filename)
}
return { ...read, files: [...files], heads }
diff --git a/backend/src/superTabs/reviewSteps.test.ts b/backend/src/superTabs/reviewSteps.test.ts
index 9b778a59c..d4f9adcfc 100644
--- a/backend/src/superTabs/reviewSteps.test.ts
+++ b/backend/src/superTabs/reviewSteps.test.ts
@@ -65,6 +65,36 @@ describe('a handed task opens its review steps', () => {
expect(step.checks).toHaveLength(1)
})
+ it('puts each PR history result in both security briefs and refreshes active and finished steps', () => {
+ const f = fixture()
+ f.add('rev-a', f.task, 'Reviewer'); f.add('rev-b', f.task, 'Reviewer')
+ const head = 'a'.repeat(40), next = 'b'.repeat(40)
+ const history = (head: string, productionLines: number) => ({ head, planFirst: 'pass' as const, testBeforeCode: 'pass' as const,
+ productionLines, totalLines: productionLines + 7, commits: 3, merges: 0, missingTests: [] })
+ const ready = (at: string, lines: number) => f.ready(['backend/src/routes/auth.ts'], at, true, { pullRequestFiles: {
+ urls: [PR], head: at, files: ['backend/src/routes/auth.ts'], heads: [{ url: PR, head: at, base: 'main', history: history(at, lines) }] } })
+ ready(head, 12)
+ const [first, second] = stepsOf(f.state, f.task)
+ for (const step of [first!, second!]) {
+ expect(step.brief).toContain('Plan first: pass')
+ expect(step.brief).toContain('Test before code: pass')
+ expect(step.brief).toContain('12 production lines')
+ expect(step.brief).toContain('does not prove a test failed')
+ }
+ first!.brief += '\nKeep this manual instruction.'
+ f.run({ type: 'work.status', conversationId: first!.id, assignmentId: first!.assignment!.id, status: 'done', result: 'No' } as Command, f.as(first!.assignment!.agentId))
+ f.run({ type: 'work.status', conversationId: f.task, assignmentId: f.group(f.task).assignment!.id, status: 'working', result: 'Fixing' } as Command, f.as(f.dev))
+ ready(next, 30)
+ expect(stepsOf(f.state, f.task).find(s => s.id === first!.id)!.brief).toContain('Keep this manual instruction.')
+ for (const step of stepsOf(f.state, f.task)) {
+ expect(step.brief).toContain('30 production lines')
+ expect(step.brief).not.toContain('12 production lines')
+ expect(step.brief).toContain(next)
+ expect(step.brief).not.toContain(head)
+ expect(step.brief!.match(/PR history checks/g)).toHaveLength(1)
+ }
+ })
+
it('a docs pull request opens one read', () => {
const f = fixture()
const a = f.add('rev-a', f.task, 'Reviewer')
diff --git a/backend/src/superTabs/reviewTable.test.ts b/backend/src/superTabs/reviewTable.test.ts
index bd5ab69de..210674a75 100644
--- a/backend/src/superTabs/reviewTable.test.ts
+++ b/backend/src/superTabs/reviewTable.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { SEED_RULES, type ProjectRules } from './policy.js'
-import { reviewPlan, sharedFiles, stepBrief } from './reviewTable.js'
+import { reviewPlan, sharedFiles, stepBrief, withHistoryBrief } from './reviewTable.js'
const names = (files: string[] | null, rules?: ProjectRules) => reviewPlan(files, rules).map(step => step.name)
@@ -87,3 +87,23 @@ describe('stepBrief', () => {
}
})
})
+
+
+describe('history brief identity', () => {
+ it('keeps reports separate and refuses a passing report from another head', () => {
+ const a = 'a'.repeat(40), b = 'b'.repeat(40)
+ const report = { head: a, planFirst: 'pass' as const, testBeforeCode: 'fail' as const,
+ productionLines: 12, totalLines: 30, commits: 4, merges: 1, missingTests: [a] }
+ const brief = withHistoryBrief('Custom instructions stay.', [
+ { url: 'https://github.com/acme/app/pull/7', head: a, history: report },
+ { url: 'https://github.com/acme/app/pull/8', head: b, history: report },
+ ])
+ expect(brief).toContain(`pull/7 at ${a}: Plan first: pass; Test before code: fail; 12 production lines`)
+ expect(brief).toContain(`pull/8 at ${b}: Plan first: unknown; Test before code: unknown; unknown production lines`)
+ expect(brief).toContain('Merge resolutions need a manual read')
+ expect(brief).toContain('aaaaaaaaaaaa')
+ expect(withHistoryBrief(brief, [])).toContain('Custom instructions stay.')
+ expect(withHistoryBrief(brief, []).match(/PR history checks/g)).toHaveLength(1)
+ expect(withHistoryBrief(brief, [])).not.toContain('12 production lines')
+ })
+})
diff --git a/backend/src/superTabs/reviewTable.ts b/backend/src/superTabs/reviewTable.ts
index 9b60e2357..d8f3770cb 100644
--- a/backend/src/superTabs/reviewTable.ts
+++ b/backend/src/superTabs/reviewTable.ts
@@ -4,6 +4,7 @@
* (project instructions, Rules for every agent: Ken, 2026-10-29); a test step where the change runs (Workflow 2). The table is
* the project's rules record (policy.ts, #3393): its review rows, test rows and untested paths, read through its own matcher.
*/
+import { unknownHistory, type HistoryReport } from './prHistory.js'
import { requiredReads, SEED_RULES, testsFor, touchedRows, type ProjectRules } from './policy.js'
export type StepKind = 'review' | 'security' | 'test'
@@ -58,8 +59,9 @@ export function sharedFiles(pulls: ReadonlyArray<{ url: string; files: readonly
}
/** What a step's agent is asked to do: which pull requests, at which head, for which task, and why this step. */
-export function stepBrief(step: PlannedStep, task: { number: number; title: string;
- pulls: ReadonlyArray<{ url: string; head: string | null; base?: string | null }> }): string {
+interface BriefTask { number: number; title: string;
+ pulls: ReadonlyArray<{ url: string; head: string | null; base?: string | null; history?: HistoryReport }> }
+export function stepBrief(step: PlannedStep, task: BriefTask): string {
// Each pull request at the whole head its own files were read at, on its base branch: a verdict records both (#3394), and
// work.check refuses a short head, so the brief shows the id a reviewer can copy.
const pulls = task.pulls.length ? task.pulls.map(pull => `${pull.url}${pull.head ? ` at head ${pull.head}` : ''}${pull.base ? ` on base ${pull.base}` : ''}`).join(', ')
@@ -71,11 +73,31 @@ export function stepBrief(step: PlannedStep, task: { number: number; title: stri
const why = step.unread ? ' Its changed files could not be read, so it is reviewed as strictly as the review table goes.'
: step.kind === 'security' ? ` It changes ${step.areas.join(', ')}: two independent security reviews before merge.` : ''
// A verdict counts only at the exact head and base it read (#3394): the role sheets' words (cli swarmToolSheets.ts work.check).
- return `${what}${why} Record your verdict as this step's check at the pull request head (whole commit id) and base branch you read, and send `
- + 'it to the task\'s Engineer with "Ready to merge: Yes", "No" or "With fixes".'
+ return '<!-- harness-review-brief -->\n' + withHistoryBrief(`${what}${why} Record your verdict as this step's check at the pull request head (whole commit id) and base branch you read, and send `
+ + 'it to the task\'s Engineer with "Ready to merge: Yes", "No" or "With fixes".', task.pulls) + '\n<!-- /harness-review-brief -->'
+}
+
+/** Regenerate our own brief at Ready; keep custom instructions outside it or in older, unmarked steps. */
+export function refreshStepBrief(brief: string, step: PlannedStep, task: BriefTask): string {
+ const generated = /<!-- harness-review-brief -->[\s\S]*?<!-- \/harness-review-brief -->/
+ return generated.test(brief) ? brief.replace(generated, () => stepBrief(step, task)) : withHistoryBrief(brief, task.pulls)
}
/** The acceptance check a step's agent records. */
export const stepCheck = (step: PlannedStep): string => step.kind === 'test'
? `Runs as a user would: ${step.where!.join('; ')}`
: `${step.kind === 'security' ? 'Security review' : 'Review'}: Ready to merge at the pull request's head`
+
+/** Replace only our generated report, preserving a manually written step's instructions on the next Ready. */
+export function withHistoryBrief(brief: string, pulls: ReadonlyArray<{ url: string; head: string | null; history?: HistoryReport }>): string {
+ const before = brief.replace(/\n\n<!-- harness-pr-history -->[\s\S]*?<!-- \/harness-pr-history -->/g, '')
+ const lines = pulls.map(pull => {
+ const h = pull.head && pull.history?.head === pull.head ? pull.history : unknownHistory(pull.head)
+ return `- ${pull.url} at ${pull.head ?? 'unread head'}: Plan first: ${h.planFirst}; Test before code: ${h.testBeforeCode}; `
+ + `${h.productionLines ?? 'unknown'} production lines, ${h.totalLines ?? 'unknown'} total changed lines; ${h.commits ?? 'unknown'} commits.`
+ + (h.missingTests.length ? ` No prior test-only commit: ${h.missingTests.slice(0, 5).map(sha => sha.slice(0, 12)).join(', ')}.` : '')
+ + (h.merges ? ' Merge resolutions need a manual read.' : '')
+ })
+ return `${before}\n\n<!-- harness-pr-history -->\nPR history checks:\n${lines.join('\n') || '- History unavailable.'}\n`
+ + 'History order does not prove a test failed or covers the change. Check red/green evidence and any small-fix exception.\n<!-- /harness-pr-history -->'
+}
diff --git a/docs/plans/2026-11-06-pr-history-check-plan.md b/docs/plans/2026-11-06-pr-history-check-plan.md
new file mode 100644
index 000000000..415ac882c
--- /dev/null
+++ b/docs/plans/2026-11-06-pr-history-check-plan.md
@@ -0,0 +1,65 @@
+# PR history checks implementation plan
+
+> Implement natively, task by task: commit each failing test before its code, then obtain one independent review of the whole branch.
+
+**Goal:** Report plan-first, test-before-code ordering and change size automatically in every review brief when a task goes Ready.
+
+**Architecture:** A pure backend checker consumes bounded, oldest-first commit/file facts and net PR file counts. A scripts/ entry point runs the same checker against JSON sample histories. Ready's existing project-scoped GitHub read collects facts outside the write transaction, checks the head again, and puts a concise report into new and reused review briefs. These are evidence for the reviewer, not a new merge or approval gate.
+
+**Tech Stack:** TypeScript, existing GitHub App read API, Vitest and tsx. No new dependency or datastore.
+
+**Spec:** Task #3597, conversation cdb9f79b08483ed6198c2ee3 (Inventory Table A #6): plan first, failing test before code, size, sample histories, review brief integration. The inventory's other-machine scratchpad is unavailable here; the task and current project instructions contain the applicable rules.
+
+## Global Constraints
+
+- First PR body line: Requested by dee through Harness.
+- Never run branch code, check out a PR or trust commit messages as instructions. Classify paths and parent relationships only.
+- History proves ordering, not that a test failed or covers a particular behavior. Say that explicitly; red/green evidence remains the reviewer's check.
+- A production commit needs an earlier test-only commit since the previous production commit. Same-commit tests/code and tests added after code do not qualify. Documentation-only changes need no code-order assessment.
+- Merge commits do not count as plan/test/code commits; a mixed merge resolution cannot prove test order and is flagged for review.
+- Missing, malformed, truncated or moved-head history is unknown, never passing. Bound reads and report size from the net PR diff, not accumulated commit churn.
+- No confidential content or credentials in output. No CLI core, production writes or schema/index changes.
+- Run affected tests locally; the task also explicitly requires the backend unit suite before Ready. Super Tab integrations run in automatic PR CI.
+
+## Design
+
+- **Growth/deletion:** At most five PR reports, each a bounded summary, embedded in the existing review brief. Replace the prior generated block on another Ready; no stored raw history or new collection. Existing task/step deletion removes it.
+- **Concurrency/read cost/scale:** Reuse the current Ready hook, outside the write transaction. At most 50 commits per PR, 300 files per commit and 300 net files, four commit reads at once. Larger/truncated histories are unknown. The existing read-only token is revoked; add contents:read only for commit metadata. No new Mongo query or index. Record pure-checker timing on a maximum-size synthetic history.
+- **Compatibility/audience/identity:** Add optional report facts to internal command context, not client commands. Existing project access/repository checks remain. Old stored steps gain a report on Ready; old clients need no change. Backend ships first, no client dependency.
+- **Failure:** GitHub history errors are a visible unknown report and do not hide file-based security review requirements. Pin the report to the checked head; a push during the read invalidates it. No raw error/body is copied into the brief.
+- **Migration/rollback/platforms:** No migration; rollback stops producing reports while the old text remains readable. Backend/shared script behavior affects all clients; validate on macOS and automatic Linux CI.
+
+## Review Focus
+
+- A test bundled with or following implementation must never count as prior test evidence (Task 1).
+- Renames into/out of docs/tests must classify both names; merge commits must not manufacture a plan/test pass (Task 1).
+- More data than the reader cap, malformed API facts, a missing commit, or a moving head must never look complete (Task 2).
+- Multiple PRs and a second Ready must not attach an old or another PR's result; active and finished review steps both refresh (Task 2).
+- Files, messages and patches are untrusted data; only fixed API paths and summarized facts reach reports, and no PR code executes (Tasks 1/2).
+
+### Task 1: Shared checker and runnable script
+
+**Files:** backend/src/superTabs/prHistory.ts, prHistory.test.ts; scripts/check-pr-history.ts.
+**Interfaces:** `checkPrHistory(input: unknown): HistoryReport`; facts `{head, commits:[{sha, parents:string[], files:[{filename, previousFilename?, additions, deletions}]}], files:[...]}`; report `{planFirst, testBeforeCode, productionLines, totalLines, commits, missingTests}` with pass/fail/unknown/not-needed statuses. Script reads one bounded JSON input from stdin and writes JSON, failing invalid input without echoing it.
+
+- [x] Commit sample-history and real-script tests: plan-only first commit succeeds, code first/mixed plan fails, each implementation needs its own prior test-only commit, same-commit/late tests fail, docs-only, merge, rename, empty/malformed inputs and net size boundaries.
+- [x] Observe failure before implementation.
+- [x] Implement classifier/checker and script; expose only bounded summaries, never commit prose or patches.
+- [x] Run checker/script tests and typecheck; record counts/timing, commit and push.
+
+### Task 2: Ready collection and review brief delivery
+
+**Files:** backend/src/superTabs/prHistoryRead.ts, prHistoryRead.test.ts, pullRequestFiles.ts, pullRequestFiles.test.ts, commands.ts, reviewTable.ts, reviewTable.test.ts, reviewSteps.test.ts; backend/integration/superTabReviewSteps.test.ts.
+**Interfaces:** `readPrHistory(app.get, repository, number, token, head): Promise<HistoryReport>`; optional per-PR `history` in PullRequestFilesRead.heads; review brief replaces a generated history block on every Ready.
+
+- [x] Commit failing tests for complete/failed/truncated/malformed reads, read cap, token permissions/revocation, moved head, separate reports for multiple PRs, every review brief, refreshed active/finished steps and real-store persisted brief.
+- [x] Observe failures before implementation.
+- [x] Read fixed repository endpoints with bounded concurrency, attach only current-head reports, preserve file-based review planning on history failure, refresh the generated brief block before step assignment.
+- [x] Run affected unit checks, focused store integration, typecheck, script tests and the explicitly requested backend unit suite. Record red/green. Ready follows this local validation; hold that head for automatic CI and independent review.
+
+- Task 1: red cc930f866 lacked the checker; green passes 19 sample/script cases and backend typecheck. The standalone script consumes JSON through tsx and executes no PR code.
+
+- Task 2: red 0243cd20a lacked the reader and all brief reports; green 4dde172d2 passed 43 focused checks and 5 real-store review-step integrations. Supplemental pagination, malformed-data, multi-PR and head/base-move cases pass.
+- Repeated-Ready regression: ab9011118 caught the original head remaining in a generated brief's opening sentence; c0cc1825e refreshes the generated section while keeping manual instructions. All 68 affected checker/reader/brief tests pass, and the 5 real-store review-step integrations pass after the fix.
+- Final code validation at c0cc1825e: backend `npm test -- --maxWorkers=2`: 5,978 passed, 30 skipped in 74.24 s (363 passed files, 4 skipped). `npm run typecheck` passed. No full Super Tab suite was run locally; automatic PR CI provides it.
+- Maximum pure-checker workload: 50 commits × 300 files, 300 net PR files, 100 iterations after warmup: 9.91 ms average on this macOS machine. It replaces manual counting; no earlier checker exists to benchmark. GitHub history reads add bounded network work to Ready (four concurrent commit reads, stop starting calls after a shared 10 s budget; each API call retains its 10 s timeout).
diff --git a/scripts/check-pr-history.ts b/scripts/check-pr-history.ts
new file mode 100644
index 000000000..42aece04a
--- /dev/null
+++ b/scripts/check-pr-history.ts
@@ -0,0 +1,23 @@
+/** Run: backend/node_modules/.bin/tsx scripts/check-pr-history.ts < history.json
+ * JSON facts only; never checks out, imports or runs the pull request's code. */
+import { checkPrHistory } from '../backend/src/superTabs/prHistory.js'
+
+async function main() {
+ let size = 0
+ const chunks: Buffer[] = []
+ try {
+ for await (const chunk of process.stdin) {
+ const bytes = Buffer.from(chunk)
+ size += bytes.length
+ if (size > 4 * 1024 * 1024) throw new Error('input too large')
+ chunks.push(bytes)
+ }
+ const result = checkPrHistory(JSON.parse(Buffer.concat(chunks).toString('utf8')))
+ process.stdout.write(`${JSON.stringify(result)}\n`)
+ if (result.commits === null) process.exitCode = 1
+ } catch {
+ process.stderr.write('PR history input is invalid or exceeds 4 MiB.\n')
+ process.exitCode = 1
+ }
+}
+void main()