@attalabs/vinaya 0.42.2 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/checks/bin/check-evidence-fresh.js +8 -5
  2. package/dist/index.js +20 -17
  3. package/dist/lib/pre-push-cache-test-run.js +3 -1
  4. package/dist/programs/archive.js +3 -1
  5. package/dist/programs/check.js +3 -1
  6. package/dist/programs/commit-msg.js +3 -1
  7. package/dist/programs/dev-review-loop.js +9 -6
  8. package/dist/programs/dispatch.js +3 -1
  9. package/dist/programs/log-emit.js +3 -1
  10. package/dist/programs/log-selftest.js +3 -1
  11. package/dist/programs/log-send.js +3 -1
  12. package/dist/programs/pr-report.js +8 -5
  13. package/dist/programs/pr-snapshot.js +3 -1
  14. package/dist/programs/pr-verify-evidence.js +8 -5
  15. package/dist/programs/pr.js +3 -1
  16. package/dist/programs/review-post.js +3 -1
  17. package/dist/programs/review-status.js +3 -1
  18. package/dist/programs/run-engine.js +110594 -0
  19. package/dist/programs/supervised-command.js +67 -0
  20. package/dist/programs/sync.js +3 -1
  21. package/dist/programs/task-brief.js +5 -3
  22. package/dist/programs/task-sweep.js +3 -1
  23. package/dist/programs/task-tools-serve.js +13 -11
  24. package/dist/programs/tokens.js +3 -1
  25. package/dist/programs/waiver.js +3 -1
  26. package/dist/vinaya-strict/checks/registry.ts +1085 -0
  27. package/dist/vinaya-strict/executing/code-reviewer/README.md +3 -0
  28. package/dist/vinaya-strict/executing/code-reviewer/doctrine.md +185 -0
  29. package/dist/vinaya-strict/executing/code-reviewer/evals/README.md +1 -0
  30. package/dist/vinaya-strict/executing/code-reviewer/evals/code-reviewer-cases.json +280 -0
  31. package/dist/vinaya-strict/executing/code-reviewer/grants.yaml +22 -0
  32. package/dist/vinaya-strict/executing/code-reviewer/output.schema.json +93 -0
  33. package/dist/vinaya-strict/executing/code-reviewer/review-result.ts +347 -0
  34. package/dist/vinaya-strict/executing/dev-review.flow.yaml +103 -0
  35. package/dist/vinaya-strict/executing/developer/README.md +3 -0
  36. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +69 -0
  37. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +286 -0
  38. package/dist/vinaya-strict/executing/developer/doctrine.md +111 -0
  39. package/dist/vinaya-strict/executing/developer/evals/README.md +1 -0
  40. package/dist/vinaya-strict/executing/developer/evals/developer-capability-cases.json +6275 -0
  41. package/dist/vinaya-strict/executing/developer/evals/developer-capability-held-out.json +11526 -0
  42. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +498 -0
  43. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +1407 -0
  44. package/dist/vinaya-strict/executing/developer/grants.yaml +25 -0
  45. package/dist/vinaya-strict/executing/developer/output.schema.json +148 -0
  46. package/dist/vinaya-strict/executing/developer/reference.md +376 -0
  47. package/dist/vinaya-strict/executing/operator/doctrine.md +209 -0
  48. package/dist/vinaya-strict/executing/security-reviewer/README.md +3 -0
  49. package/dist/vinaya-strict/executing/security-reviewer/doctrine.md +171 -0
  50. package/dist/vinaya-strict/executing/security-reviewer/evals/README.md +1 -0
  51. package/dist/vinaya-strict/executing/security-reviewer/evals/security-reviewer-cases.json +141 -0
  52. package/dist/vinaya-strict/executing/security-reviewer/grants.yaml +22 -0
  53. package/dist/vinaya-strict/executing/security-reviewer/output.schema.json +93 -0
  54. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +1278 -0
  55. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +52 -0
  56. package/dist/vinaya-strict/integration/process/process-integration.ts +57 -0
  57. package/dist/vinaya-strict/loops/dev-review/v2/dev-review-v2.flow.yaml +136 -0
  58. package/dist/vinaya-strict/process.yaml +43 -0
  59. package/dist/vinaya-strict/retrospecting/archivist/doctrine.md +174 -0
  60. package/dist/vinaya-strict/retrospecting/tranche-archivist/doctrine.md +270 -0
  61. package/dist/vinaya-strict/thinking/architect/doctrine.md +110 -0
  62. package/dist/vinaya-strict/thinking/planner/doctrine.md +105 -0
  63. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +128 -0
  64. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +169 -0
  65. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +701 -0
  66. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +1035 -0
  67. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +359 -0
  68. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +815 -0
  69. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +200 -0
  70. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +458 -0
  71. package/package.json +4 -2
  72. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  73. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  74. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  75. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  76. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  77. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  78. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  79. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  80. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  81. /package/studio-standalone/apps/vinaya-studio/.next/static/{Q_xjhiWztjosXWbMSJ0Yp → x2q88XfwsihlevulRhIvs}/_buildManifest.js +0 -0
  82. /package/studio-standalone/apps/vinaya-studio/.next/static/{Q_xjhiWztjosXWbMSJ0Yp → x2q88XfwsihlevulRhIvs}/_ssgManifest.js +0 -0
@@ -0,0 +1,1407 @@
1
+ /**
2
+ * Developer capability evaluation — the evaluation program's §6.5 role
3
+ * evaluation. Each case is a merged task pull request of this repository,
4
+ * reconstructed the SWE-bench way from git history: the frozen brief, the
5
+ * commit before the merge, the merged change's own test changes withheld as
6
+ * fail-to-pass, the tests that already passed as pass-to-pass, and the merged
7
+ * change as reference solution. Commits and blob ids are stored, never source
8
+ * trees. Development tooling reads only the development cases and the public
9
+ * held-out index; only an approved run opens the held-out file.
10
+ */
11
+ import { parseIssueDocumentation } from '../../../../../kernel/issue-documentation'
12
+ import { createHash } from 'node:crypto'
13
+ import {
14
+ appendFileSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ mkdtempSync,
18
+ readFileSync,
19
+ rmSync,
20
+ statSync,
21
+ writeFileSync
22
+ } from 'node:fs'
23
+ import { tmpdir } from 'node:os'
24
+ import { dirname, join, relative } from 'node:path'
25
+ import {
26
+ type BeyondSurfacePath,
27
+ beyondSurfacePaths,
28
+ globCoversPath,
29
+ recordedBeyondSurfacePaths
30
+ } from '../../../tools/task-contract/issue-validation'
31
+ import { defaultControlStoreDeps } from '../../../../../kernel/connectors/checkpoint/control-store/index'
32
+ import { TASK_TOOL_NAMES } from '../../../../../kernel/tools/catalog/task-tools'
33
+
34
+ import { ProtectedPathError, scopeTarget } from '../../../../../kernel/tools/host/broker'
35
+ import { authenticateWorkerInvocation, requestEffect } from '../../../integration/tools/host/broker/vinaya-broker'
36
+ import {
37
+ type CodeGraderIdentity,
38
+ createSuite,
39
+ type GraderVerdict,
40
+ type Suite,
41
+ type Task,
42
+ validateTask
43
+ } from '../../../../../kernel/evals/contracts'
44
+ import { validateDeveloperTurnResult, type DeveloperTurnResult } from '../developer-turn-result'
45
+ import {
46
+ manifestDigest,
47
+ sha256Digest,
48
+ type RequiredSourceManifest,
49
+ type SourceDeliveryReceipt
50
+ } from '../../../../../kernel/source-manifest'
51
+ import { documentationSourceId } from '../../../../../kernel/tools/fetch-documentation'
52
+ import { ROLE_TOOL_GRANTS } from '../../../integration/policies/roles'
53
+ import { AGENT_TOOL_CATALOG } from '../../../../../kernel/tools/tool-catalog'
54
+ import { selectAffectedTestFiles } from '../../../integration/repository-verification'
55
+ import { agentOwnConfigSubpaths } from '../../../../../kernel/isolation/worker-boundary'
56
+ import { spawnBudgetedAsync, stripVinayaEnv } from '../../../../../kernel/conformance/unit/process-fixture'
57
+ import {
58
+ type CallPredicate,
59
+ canonicalJson,
60
+ loadCaseFile as loadToolSelectionCaseFile,
61
+ meets,
62
+ type TraceCall
63
+ } from '../../evals/tool-selection-suite'
64
+
65
+ // ── Suite identity ──────────────────────────────────────────────────────────
66
+
67
+ export const SUITE = { name: 'developer-capability.l5', version: 1, layer: 'L5' } as const
68
+ export const SUITE_ID = `${SUITE.name}@${SUITE.version}`
69
+ /** Process layer `P`: its graders read Vinaya artifacts — the frozen brief, the turn result, the beyond-Surface record. */
70
+ export const SUITE_PROCESS_LAYER = 'P' as const
71
+ export const CASES_PATH = join(import.meta.dir, 'developer-capability-cases.json')
72
+ export const HELD_OUT_PATH = join(import.meta.dir, 'developer-capability-held-out.json')
73
+ /** The fewest admitted cases the suite is built on; fewer is a strategy question, never a lowered bar. */
74
+ export const MINIMUM_CASES = 10
75
+ /** The forge snapshot the cases were reconstructed from: one JSON line per merged task pull request. */
76
+ export const SNAPSHOT_SHA256 = '38a5e600209978775b2e44b63503bfcd53e41bf167fd07c9773b7b92bcd44f00'
77
+ const REPO_ROOT = join(import.meta.dir, '../../../../../..')
78
+
79
+ export type ReadText = (path: string) => string
80
+ const defaultRead: ReadText = (path) => readFileSync(path, 'utf8')
81
+
82
+ export function sha256(text: string | Uint8Array): string {
83
+ return createHash('sha256').update(text).digest('hex')
84
+ }
85
+
86
+ // ── Case data ───────────────────────────────────────────────────────────────
87
+
88
+ /** One test as its runner reports it: the file relative to the repository root, and its describe path and name joined by ` > `. */
89
+ export interface TestId {
90
+ file: string
91
+ name: string
92
+ }
93
+
94
+ /** Tests grouped by file: each file relative to the repository root, with its tests' names in run order. */
95
+ export type TestSet = Record<string, string[]>
96
+
97
+ export function testIdsOf(set: TestSet): TestId[] {
98
+ return Object.entries(set).flatMap(([file, names]) => names.map((name) => ({ file, name })))
99
+ }
100
+
101
+ export function testSetOf(ids: readonly TestId[]): TestSet {
102
+ const set: TestSet = {}
103
+ for (const { file, name } of ids) set[file] = [...(set[file] ?? []), name]
104
+ return set
105
+ }
106
+
107
+ /** The characters of a test name's digest: the leading hexadecimal characters of the SHA-256 of the name. */
108
+ export const TEST_DIGEST_LENGTH = 12
109
+
110
+ /** A test's name, digested; pass-to-pass lists names this way to keep its thousands of names small. */
111
+ export function testDigest(name: string): string {
112
+ return sha256(name).slice(0, TEST_DIGEST_LENGTH)
113
+ }
114
+
115
+ /**
116
+ * One file's tests, their names digested, sorted and concatenated into one
117
+ * string. The digests come before the file, so no line of the case file
118
+ * puts a path beside a run of hexadecimal characters.
119
+ */
120
+ export interface DigestedFile {
121
+ digests: string
122
+ file: string
123
+ }
124
+
125
+ /** Tests grouped by file, by name digest. */
126
+ export type DigestSet = DigestedFile[]
127
+
128
+ export function digestSetOf(set: TestSet): DigestSet {
129
+ return Object.entries(set)
130
+ .filter(([, names]) => names.length > 0)
131
+ .map(([file, names]) => ({ digests: [...new Set(names.map(testDigest))].sort().join(''), file }))
132
+ }
133
+
134
+ export function digestsIn(value: string): string[] {
135
+ return value.match(new RegExp(`.{${TEST_DIGEST_LENGTH}}`, 'g')) ?? []
136
+ }
137
+
138
+ /** The digests `set` holds for `file`. */
139
+ export function digestsFor(set: DigestSet, file: string): string[] {
140
+ return digestsIn(set.find((entry) => entry.file === file)?.digests ?? '')
141
+ }
142
+
143
+ /** One test's outcome in a run, keyed by its file and name digest. */
144
+ export type TestOutcomes = Record<string, TestOutcome>
145
+
146
+ export function outcomeKey(file: string, digest: string): string {
147
+ return `${file}\0${digest}`
148
+ }
149
+
150
+ /** What the grading copy's run reported, keyed for the grader. */
151
+ export function outcomesOf(results: readonly TestResult[]): TestOutcomes {
152
+ const out: TestOutcomes = {}
153
+ for (const r of results) out[outcomeKey(r.file, testDigest(r.name))] = r.outcome
154
+ return out
155
+ }
156
+
157
+ /** One file of a commit, pinned by its git blob id. */
158
+ export interface PinnedFile {
159
+ path: string
160
+ blob: string
161
+ }
162
+
163
+ /** The frozen brief's scope: §4's Create and Modify entries as `in:`, its Out of surface entries as `out:`. */
164
+ export interface FrozenScope {
165
+ in: string[]
166
+ out: string[]
167
+ }
168
+
169
+ export interface DeveloperCapabilityCase {
170
+ /** `pr-<number>`, the merged pull request the case is reconstructed from. */
171
+ id: string
172
+ pullRequest: number
173
+ issue: number
174
+ /** The frozen brief, named by its pull request in the snapshot and pinned by `sha256Digest` of its text. */
175
+ brief: { pullRequest: number; digest: string }
176
+ /** The commit before the merged change: the trial's starting point. */
177
+ baseCommit: string
178
+ /** The squash-merged change. */
179
+ referenceCommit: string
180
+ scope: FrozenScope
181
+ /** The source identities the brief's `## Documentation` requires, as the controller's source provider derives them. */
182
+ requiredSources: string[]
183
+ /** The merged change's test files, withheld from the trial and written into the grading copy only. */
184
+ hiddenTests: { files: PinnedFile[]; deleted: string[] }
185
+ /** Every other path the merged change touched. */
186
+ referenceSolution: { commit: string; files: PinnedFile[]; deleted: string[]; digest: string }
187
+ /** Tests that fail (or do not load) on the base commit with the hidden tests written in, and pass on the reference commit. */
188
+ failToPass: TestSet
189
+ /**
190
+ * Tests that pass on both, by name digest: those in the hidden test files,
191
+ * and those in the existing test files the repository's affected-test
192
+ * selection picks for the merged change.
193
+ */
194
+ passToPass: DigestSet
195
+ /** The existing test files pass-to-pass draws on beyond the hidden ones, pinned by their blob on the base commit and written into the grading copy at that revision. */
196
+ passToPassFiles: PinnedFile[]
197
+ }
198
+
199
+ export const DROP_REASONS = [
200
+ 'not_in_history',
201
+ 'merge_not_single_parent',
202
+ 'no_withheld_tests',
203
+ 'no_reference_solution',
204
+ 'scope_unresolved',
205
+ 'reference_touches_protected_path',
206
+ 'install_failed',
207
+ 'test_run_failed',
208
+ 'withheld_tests_do_not_fail_before'
209
+ ] as const
210
+ export type DropReason = (typeof DROP_REASONS)[number]
211
+
212
+ export interface Reconstruction {
213
+ snapshot: { file: string; sha256: string; lines: number; withBrief: number }
214
+ /** How candidates were chosen and admitted, in words. */
215
+ rule: string
216
+ /** The newest candidates examined, by merge time; the older rest of the pool was not examined. */
217
+ limit: number
218
+ examined: number
219
+ admitted: number
220
+ dropped: Record<DropReason, number>
221
+ drops: { pullRequest: number; reason: DropReason }[]
222
+ toolchain: { bun: string }
223
+ }
224
+
225
+ export interface HeldOutIndexEntry {
226
+ id: string
227
+ }
228
+
229
+ export interface CaseFile {
230
+ schemaVersion: 1
231
+ suite: typeof SUITE_ID
232
+ reconstruction: Reconstruction
233
+ splits: {
234
+ /** How an admitted case's split was decided, fixed before any case was run. */
235
+ rule: string
236
+ development: { digest: string; ids: string[] }
237
+ heldOut: { file: string; digest: string; index: HeldOutIndexEntry[] }
238
+ }
239
+ cases: DeveloperCapabilityCase[]
240
+ }
241
+
242
+ export interface HeldOutFile {
243
+ schemaVersion: 1
244
+ cases: DeveloperCapabilityCase[]
245
+ }
246
+
247
+ /** The digest the split record pins the development split by: its cases, in file order. */
248
+ export function developmentDigest(cases: readonly DeveloperCapabilityCase[]): string {
249
+ return sha256(canonicalJson(cases))
250
+ }
251
+
252
+ /** The reference solution's digest: its commit, its files and its deletions, sorted. */
253
+ export function referenceSolutionDigest(
254
+ solution: Omit<DeveloperCapabilityCase['referenceSolution'], 'digest'>
255
+ ): string {
256
+ return sha256(
257
+ canonicalJson({
258
+ commit: solution.commit,
259
+ files: [...solution.files].sort((a, b) => (a.path < b.path ? -1 : 1)),
260
+ deleted: [...solution.deleted].sort()
261
+ })
262
+ )
263
+ }
264
+
265
+ const COMMIT = /^[a-f0-9]{40}$/
266
+ const SHA256 = /^[a-f0-9]{64}$/
267
+
268
+ class CaseRefused extends Error {}
269
+
270
+ function refuse(path: string, detail: string): never {
271
+ throw new CaseRefused(`${path}: ${detail}`)
272
+ }
273
+
274
+ function checkTestSet(set: TestSet, path: string): void {
275
+ for (const [file, names] of Object.entries(set)) {
276
+ if (file === '' || !Array.isArray(names) || names.length === 0)
277
+ refuse(`${path}.${file}`, 'names a file and its tests')
278
+ if (names.some((name) => typeof name !== 'string' || name === '')) refuse(`${path}.${file}`, 'names every test')
279
+ if (new Set(names).size !== names.length) refuse(`${path}.${file}`, 'repeats a test')
280
+ }
281
+ }
282
+
283
+ /** Validates one case's shape; refuses with the offending path. */
284
+ export function checkCase(c: DeveloperCapabilityCase, path: string): void {
285
+ if (c.id !== `pr-${c.pullRequest}` || !Number.isInteger(c.pullRequest)) refuse(`${path}.id`, 'is pr-<pullRequest>')
286
+ if (!Number.isInteger(c.issue) || c.issue < 1) refuse(`${path}.issue`, 'is an Issue number')
287
+ if (c.brief.pullRequest !== c.pullRequest || !/^sha256:[a-f0-9]{64}$/.test(c.brief.digest))
288
+ refuse(`${path}.brief`, 'names its own pull request and a sha256 digest')
289
+ if (!COMMIT.test(c.baseCommit) || !COMMIT.test(c.referenceCommit) || c.baseCommit === c.referenceCommit)
290
+ refuse(`${path}`, 'pins two distinct commits')
291
+ if (c.scope.in.length === 0 && c.scope.out.length === 0) refuse(`${path}.scope`, 'is resolved')
292
+ if (c.hiddenTests.files.length === 0) refuse(`${path}.hiddenTests`, 'withholds at least one test file')
293
+ const solution = c.referenceSolution
294
+ if (solution.commit !== c.referenceCommit) refuse(`${path}.referenceSolution.commit`, 'is the reference commit')
295
+ if (solution.files.length + solution.deleted.length === 0) refuse(`${path}.referenceSolution`, 'changes something')
296
+ if (referenceSolutionDigest(solution) !== solution.digest) refuse(`${path}.referenceSolution.digest`, 'is stale')
297
+ for (const file of [...c.hiddenTests.files, ...solution.files, ...c.passToPassFiles])
298
+ if (!COMMIT.test(file.blob)) refuse(`${path}`, `${file.path} is not pinned by a blob id`)
299
+ checkTestSet(c.failToPass, `${path}.failToPass`)
300
+ for (const [i, { digests }] of c.passToPass.entries()) {
301
+ if (!new RegExp(`^(?:[a-f0-9]{${TEST_DIGEST_LENGTH}})+$`).test(digests))
302
+ refuse(`${path}.passToPass[${i}]`, 'is a run of test-name digests')
303
+ if (new Set(digestsIn(digests)).size !== digestsIn(digests).length)
304
+ refuse(`${path}.passToPass[${i}]`, 'repeats a test')
305
+ }
306
+ if (new Set(c.passToPass.map((entry) => entry.file)).size !== c.passToPass.length)
307
+ refuse(`${path}.passToPass`, 'repeats a file')
308
+ const hidden = new Set(c.hiddenTests.files.map((f) => f.path))
309
+ const existing = new Set(c.passToPassFiles.map((f) => f.path))
310
+ if (c.passToPassFiles.some((f) => hidden.has(f.path))) refuse(`${path}.passToPassFiles`, 'repeats a hidden test file')
311
+ for (const file of Object.keys(c.failToPass))
312
+ if (!hidden.has(file)) refuse(`${path}.failToPass`, `${file} is not a hidden test file`)
313
+ for (const { file } of c.passToPass)
314
+ if (!hidden.has(file) && !existing.has(file)) refuse(`${path}.passToPass`, `${file} is not a pinned test file`)
315
+ if (testIdsOf(c.failToPass).length === 0) refuse(`${path}.failToPass`, 'holds at least one test')
316
+ if (testIdsOf(c.failToPass).some(({ file, name }) => digestsFor(c.passToPass, file).includes(testDigest(name))))
317
+ refuse(`${path}`, 'a test is both fail-to-pass and pass-to-pass')
318
+ }
319
+
320
+ function checkCaseList(cases: readonly DeveloperCapabilityCase[], path: string): void {
321
+ const ids = new Set<string>()
322
+ for (const [i, c] of cases.entries()) {
323
+ checkCase(c, `${path}[${i}]`)
324
+ if (ids.has(c.id)) refuse(`${path}[${i}].id`, 'repeats a case')
325
+ ids.add(c.id)
326
+ }
327
+ }
328
+
329
+ /** Loads the development cases and the held-out index without opening held-out content. */
330
+ export function loadCaseFile(read: ReadText = defaultRead): CaseFile {
331
+ const file = JSON.parse(read(CASES_PATH)) as CaseFile
332
+ if (file.schemaVersion !== 1 || file.suite !== SUITE_ID) throw new CaseRefused('case file header is invalid')
333
+ checkCaseList(file.cases, 'cases')
334
+ if (canonicalJson(file.cases.map((c) => c.id)) !== canonicalJson(file.splits.development.ids))
335
+ throw new CaseRefused('development ids differ from the split record')
336
+ if (developmentDigest(file.cases) !== file.splits.development.digest)
337
+ throw new CaseRefused('development cases differ from their pinned digest')
338
+ if (!SHA256.test(file.splits.heldOut.digest)) throw new CaseRefused('held-out digest is invalid')
339
+ const heldOut = new Set(file.splits.heldOut.index.map((entry) => entry.id))
340
+ if (file.cases.some((c) => heldOut.has(c.id))) throw new CaseRefused('the splits overlap')
341
+ return file
342
+ }
343
+
344
+ export class HeldOutRefused extends Error {}
345
+
346
+ /** The sole held-out read path: it opens the file only for an approval naming the pinned digest. */
347
+ export function loadHeldOutCases(file: CaseFile, approval: string | undefined, read: ReadText = defaultRead) {
348
+ const pinned = file.splits.heldOut.digest
349
+ if (approval !== pinned) throw new HeldOutRefused(`the held-out split runs only with --approve-held-out ${pinned}`)
350
+ const text = read(HELD_OUT_PATH)
351
+ if (sha256(text) !== pinned) throw new HeldOutRefused('held-out bytes differ from the split record')
352
+ const held = JSON.parse(text) as HeldOutFile
353
+ checkCaseList(held.cases, 'heldOut.cases')
354
+ if (canonicalJson(held.cases.map((c) => ({ id: c.id }))) !== canonicalJson(file.splits.heldOut.index))
355
+ throw new HeldOutRefused('held-out cases differ from the split record’s index')
356
+ return held.cases
357
+ }
358
+
359
+ /** The harness suite the cases form: a capability suite whose splits are fixed at creation. */
360
+ export function suiteFor(file: CaseFile): Readonly<Suite> {
361
+ const created = createSuite({
362
+ name: SUITE.name,
363
+ version: SUITE.version,
364
+ layer: SUITE.layer,
365
+ kind: 'capability',
366
+ splits: { development: file.splits.development.ids, heldOut: file.splits.heldOut.index.map((e) => e.id) }
367
+ })
368
+ if (!created.ok) throw new Error(`suite refused: ${JSON.stringify(created.refusal)}`)
369
+ return created.value
370
+ }
371
+
372
+ /** The development split, as harness tasks. The development run path: it never opens the held-out file. */
373
+ export function developmentTasks(read: ReadText = defaultRead): Task[] {
374
+ const file = loadCaseFile(read)
375
+ suiteFor(file)
376
+ return file.cases.map(toTask)
377
+ }
378
+
379
+ // ── Reading git history ─────────────────────────────────────────────────────
380
+
381
+ export type Git = (args: readonly string[]) => string
382
+
383
+ /** A git runner over `repository` with no operator configuration. */
384
+ export function gitIn(repository: string): Git {
385
+ return (args) => {
386
+ const result = Bun.spawnSync(['git', ...args], {
387
+ cwd: repository,
388
+ env: { PATH: process.env.PATH ?? '', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', HOME: tmpdir() },
389
+ stdout: 'pipe',
390
+ stderr: 'pipe'
391
+ })
392
+ if (result.exitCode !== 0) throw new Error(`git ${args.join(' ')}: ${result.stderr.toString().trim()}`)
393
+ return result.stdout.toString()
394
+ }
395
+ }
396
+
397
+ /** A test-side path: anything under a `test` or `tests` directory, or a `*.test.*` file. */
398
+ export function isTestPath(path: string): boolean {
399
+ return /(^|\/)tests?\//.test(path) || /\.test\.[cm]?[jt]sx?$/.test(path)
400
+ }
401
+
402
+ function isTestFile(path: string): boolean {
403
+ return /\.test\.[cm]?[jt]sx?$/.test(path)
404
+ }
405
+
406
+ export interface ChangeSplit {
407
+ hiddenTests: { files: PinnedFile[]; deleted: string[] }
408
+ referenceSolution: { files: PinnedFile[]; deleted: string[] }
409
+ }
410
+
411
+ /** Splits the merged change into its test side and its solution, pinning each file by its blob at the reference commit. */
412
+ export function splitChange(git: Git, baseCommit: string, referenceCommit: string): ChangeSplit {
413
+ const out: ChangeSplit = { hiddenTests: { files: [], deleted: [] }, referenceSolution: { files: [], deleted: [] } }
414
+ // One raw diff names every changed path with its blob id at the reference commit.
415
+ const fields = git(['diff', '--raw', '--no-abbrev', '--no-renames', '-z', baseCommit, referenceCommit]).split('\0')
416
+ for (let i = 0; i + 1 < fields.length; i += 2) {
417
+ const [, , , blob, status] = (fields[i] as string).split(' ')
418
+ const path = fields[i + 1] as string
419
+ const side = isTestPath(path) ? out.hiddenTests : out.referenceSolution
420
+ if (status === 'D') side.deleted.push(path)
421
+ else side.files.push({ path, blob: blob as string })
422
+ }
423
+ return out
424
+ }
425
+
426
+ /** Every pin of `c` that git history can check, rechecked; returns what disagrees. */
427
+ export function verifyCaseAgainstHistory(git: Git, c: DeveloperCapabilityCase): string[] {
428
+ const problems: string[] = []
429
+ const parents = git(['rev-list', '--parents', '-n', '1', c.referenceCommit]).trim().split(' ').slice(1)
430
+ if (parents.length !== 1 || parents[0] !== c.baseCommit)
431
+ problems.push('base is not the reference commit’s one parent')
432
+ const split = splitChange(git, c.baseCommit, c.referenceCommit)
433
+ if (canonicalJson(split.hiddenTests) !== canonicalJson(c.hiddenTests))
434
+ problems.push('hidden tests differ from the merged change')
435
+ const { commit: _commit, digest: _digest, ...solution } = c.referenceSolution
436
+ if (canonicalJson(split.referenceSolution) !== canonicalJson(solution))
437
+ problems.push('reference solution differs from the merged change')
438
+ // An existing pass-to-pass file is the same blob before and after the merged change.
439
+ const blobsAt = (commit: string) =>
440
+ new Map(
441
+ git(['ls-tree', '-r', '-z', commit])
442
+ .split('\0')
443
+ .filter(Boolean)
444
+ .map((entry) => {
445
+ const [meta, path] = entry.split('\t') as [string, string]
446
+ return [path, meta.split(' ')[2] as string]
447
+ })
448
+ )
449
+ const before = blobsAt(c.baseCommit)
450
+ const after = blobsAt(c.referenceCommit)
451
+ for (const file of c.passToPassFiles)
452
+ if (before.get(file.path) !== file.blob || after.get(file.path) !== file.blob)
453
+ problems.push(`${file.path} is not unchanged at its pinned blob`)
454
+ return problems
455
+ }
456
+
457
+ // ── The frozen brief ────────────────────────────────────────────────────────
458
+
459
+ function sectionLines(brief: string, heading: RegExp): string[] {
460
+ const lines = brief.split(/\r?\n/)
461
+ const start = lines.findIndex((line) => heading.test(line))
462
+ if (start < 0) return []
463
+ const end = lines.findIndex((line, i) => i > start && /^##\s/.test(line))
464
+ return lines.slice(start + 1, end < 0 ? lines.length : end)
465
+ }
466
+
467
+ function clean(entry: string): string {
468
+ return entry.trim().replace(/^`|`$/g, '').trim()
469
+ }
470
+
471
+ /** The frozen brief's §4 surface map as a scope, or `null` when it names none. */
472
+ export function frozenScope(brief: string): FrozenScope | null {
473
+ const lines = sectionLines(brief, /^##\s+4\.\s/)
474
+ const scope: FrozenScope = { in: [], out: [] }
475
+ let list: 'in' | null = null
476
+ for (const line of lines) {
477
+ if (/^\*\*(Create|Modify):\*\*/.test(line)) {
478
+ list = 'in'
479
+ continue
480
+ }
481
+ const out = /^\*\*Out of surface:\*\*\s*(.*)$/.exec(line)
482
+ if (out) {
483
+ list = null
484
+ const named = (out[1] as string).split(' — ')[0] as string
485
+ for (const entry of named.split(',').map(clean)) if (entry !== '' && !entry.startsWith('(')) scope.out.push(entry)
486
+ continue
487
+ }
488
+ if (/^\*\*|^#/.test(line)) list = null
489
+ const bullet = /^-\s+(.*)$/.exec(line)
490
+ if (list === 'in' && bullet) {
491
+ const entry = clean(bullet[1] as string)
492
+ if (entry !== '' && !entry.startsWith('(') && !entry.startsWith('consumer-tests:')) scope.in.push(entry)
493
+ }
494
+ }
495
+ return scope.in.length === 0 && scope.out.length === 0 ? null : scope
496
+ }
497
+
498
+ /** The source identities the brief's `## Documentation` requires, derived as the source provider derives them. */
499
+ export function briefRequiredSources(brief: string): string[] {
500
+ const parsed = parseIssueDocumentation(brief)
501
+ if (!parsed.ok || parsed.value.kind !== 'sources') return []
502
+ return [...new Set(parsed.value.sources.map((entry) => documentationSourceId(entry.source)))]
503
+ }
504
+
505
+ // ── Running tests ───────────────────────────────────────────────────────────
506
+
507
+ export type TestOutcome = 'pass' | 'fail' | 'skip'
508
+ export interface TestResult extends TestId {
509
+ outcome: TestOutcome
510
+ }
511
+
512
+ export function testKey(id: TestId): string {
513
+ return `${id.file}\0${id.name}`
514
+ }
515
+
516
+ function xmlText(value: string): string {
517
+ return value
518
+ .replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Number(code)))
519
+ .replace(/&lt;/g, '<')
520
+ .replace(/&gt;/g, '>')
521
+ .replace(/&quot;/g, '"')
522
+ .replace(/&apos;/g, "'")
523
+ .replace(/&amp;/g, '&')
524
+ }
525
+
526
+ function attribute(tag: string, key: string): string | null {
527
+ const match = new RegExp(`\\s${key}="([^"]*)"`).exec(tag)
528
+ return match ? xmlText(match[1] as string) : null
529
+ }
530
+
531
+ /**
532
+ * Reads bun's JUnit report: each test case's file (relative to `cwd`,
533
+ * rewritten relative to the repository root by `prefix`), its describe path
534
+ * and name, and whether it passed, failed or was skipped. A file that failed
535
+ * to load reports no test cases at all.
536
+ */
537
+ export function readJunit(xml: string, prefix: string): TestResult[] {
538
+ const results: TestResult[] = []
539
+ const suites: string[] = []
540
+ const seen = new Map<string, number>()
541
+ const tags = /<testsuite\b[^>]*?>|<\/testsuite>|<testcase\b[^>]*?\/>|<testcase\b[^>]*?>[\s\S]*?<\/testcase>/g
542
+ for (const match of xml.matchAll(tags)) {
543
+ const tag = match[0]
544
+ if (tag.startsWith('</testsuite')) {
545
+ suites.pop()
546
+ continue
547
+ }
548
+ if (tag.startsWith('<testsuite')) {
549
+ suites.push(attribute(tag, 'name') ?? '')
550
+ continue
551
+ }
552
+ const open = /^<testcase\b[^>]*?\/?>/.exec(tag)?.[0] ?? tag
553
+ // bun names the file on each test case; vitest names it as the class.
554
+ const file = attribute(open, 'file') ?? attribute(open, 'classname')
555
+ const name = attribute(open, 'name')
556
+ if (file === null || name === null) continue
557
+ const path = [...suites.slice(1), name].join(' > ')
558
+ const id = { file: prefix === '' ? file : `${prefix}/${file}`, name: path }
559
+ const count = (seen.get(testKey(id)) ?? 0) + 1
560
+ seen.set(testKey(id), count)
561
+ if (count > 1) id.name = `${path} #${count}`
562
+ const outcome: TestOutcome = /<(failure|error)\b/.test(tag) ? 'fail' : /<skipped\b/.test(tag) ? 'skip' : 'pass'
563
+ results.push({ ...id, outcome })
564
+ }
565
+ return results
566
+ }
567
+
568
+ /** The directory of the package that owns `path`: its nearest ancestor holding a `package.json`. */
569
+ function packageRoot(checkout: string, path: string): string {
570
+ let dir = dirname(path)
571
+ while (dir !== '.' && dir !== '/' && !existsSync(join(checkout, dir, 'package.json'))) dir = dirname(dir)
572
+ return dir === '/' ? '.' : dir
573
+ }
574
+
575
+ /** The nearest `node_modules/.bin/<name>` at or above `dir` inside `checkout`, or `null`. */
576
+ function localBin(checkout: string, dir: string, name: string): string | null {
577
+ for (let at = dir; ; at = dirname(at)) {
578
+ const bin = join(checkout, at, 'node_modules', '.bin', name)
579
+ if (existsSync(bin)) return bin
580
+ if (at === '.' || at === '/') return null
581
+ }
582
+ }
583
+
584
+ /**
585
+ * The command running `files` with their package's own runner — vitest when
586
+ * the package's `test` script names it, bun's otherwise — writing a JUnit
587
+ * report to `report`.
588
+ */
589
+ function runnerCommand(checkout: string, root: string, files: readonly string[], report: string): string[] {
590
+ const manifest = JSON.parse(readFileSync(join(checkout, root, 'package.json'), 'utf8')) as {
591
+ scripts?: Record<string, string>
592
+ }
593
+ const relativeFiles = files.map((file) => `./${relative(join(checkout, root), join(checkout, file))}`)
594
+ if (/^vitest\b/.test(manifest.scripts?.test ?? '')) {
595
+ const vitest = localBin(checkout, root, 'vitest')
596
+ if (vitest === null) throw new Error(`${root} runs vitest, which is not installed`)
597
+ return [vitest, 'run', '--reporter=junit', `--outputFile=${report}`, ...relativeFiles]
598
+ }
599
+ return ['bun', 'test', '--timeout=30000', '--reporter=junit', `--reporter-outfile=${report}`, ...relativeFiles]
600
+ }
601
+
602
+ /**
603
+ * Runs `files` (repository-relative) from their packages' own directories with their own runners, as continuous integration does.
604
+ * `isolate` wraps each runner's launch; each run's report directory is created under `reportParent`;
605
+ * `onOutput` receives each runner's standard output and standard error once it exits.
606
+ */
607
+ export async function runTests(
608
+ checkout: string,
609
+ files: readonly string[],
610
+ budgetMs: number,
611
+ isolate?: (
612
+ command: readonly string[],
613
+ cwd: string,
614
+ reportDirectory: string
615
+ ) => {
616
+ command: string[]
617
+ env: NodeJS.ProcessEnv
618
+ },
619
+ reportParent: string = tmpdir(),
620
+ onOutput?: (output: { packageRoot: string; stdout: string; stderr: string }) => void
621
+ ): Promise<TestResult[]> {
622
+ const byPackage = new Map<string, string[]>()
623
+ for (const file of files) {
624
+ if (!existsSync(join(checkout, file))) continue
625
+ const root = packageRoot(checkout, file)
626
+ byPackage.set(root, [...(byPackage.get(root) ?? []), file])
627
+ }
628
+ const results: TestResult[] = []
629
+ for (const [root, own] of byPackage) {
630
+ const report = join(mkdtempSync(join(reportParent, 'developer-capability-junit-')), 'junit.xml')
631
+ const command = runnerCommand(checkout, root, own, report)
632
+ const execution = isolate?.(command, join(checkout, root), dirname(report))
633
+ const run = await spawnBudgetedAsync(
634
+ execution?.command ?? command,
635
+ { cwd: join(checkout, root), env: execution?.env ?? stripVinayaEnv() },
636
+ budgetMs,
637
+ 'test runner'
638
+ )
639
+ onOutput?.({ packageRoot: root, stdout: run.stdout, stderr: run.stderr })
640
+ // bun writes no report when no test case ran at all — every file failed to
641
+ // load — and says so in its summary: nothing passed. Anything else is a
642
+ // runner failure.
643
+ if (existsSync(report)) {
644
+ const prefix = root === '.' ? '' : root
645
+ // A runner names a file relative to the package, or now and then to the
646
+ // repository root already; either way the id is the repository path.
647
+ for (const result of readJunit(readFileSync(report, 'utf8'), prefix)) {
648
+ const raw = prefix === '' ? result.file : result.file.slice(prefix.length + 1)
649
+ const named = !existsSync(join(checkout, result.file)) && existsSync(join(checkout, raw))
650
+ results.push(named ? { ...result, file: raw } : result)
651
+ }
652
+ } else if (!/^\s*0 pass$/m.test(`${run.stdout}\n${run.stderr}`))
653
+ throw new Error(`the test runner wrote no report in ${root}`)
654
+ rmSync(dirname(report), { recursive: true, force: true })
655
+ }
656
+ return results
657
+ }
658
+
659
+ /** The longest one existing test file may run while pass-to-pass is reconstructed. */
660
+ export const RELATED_FILE_BUDGET_MS = 180_000
661
+
662
+ /**
663
+ * Runs `files` together within `budgetMs`; when that run overruns, runs each
664
+ * file in a runner of its own within `fileBudgetMs`, so a file that never
665
+ * finishes reports no test — none of its tests can enter a list — and the
666
+ * rest still run.
667
+ */
668
+ export async function runRelatedTests(
669
+ checkout: string,
670
+ files: readonly string[],
671
+ budgetMs: number,
672
+ fileBudgetMs: number
673
+ ): Promise<TestResult[]> {
674
+ try {
675
+ return await runTests(checkout, files, budgetMs)
676
+ } catch {
677
+ const results: TestResult[] = []
678
+ for (const file of files) {
679
+ try {
680
+ results.push(...(await runTests(checkout, [file], fileBudgetMs)))
681
+ } catch {
682
+ // No result: the file's tests are left out of both lists.
683
+ }
684
+ }
685
+ return results
686
+ }
687
+ }
688
+
689
+ /**
690
+ * Fail-to-pass and pass-to-pass, the SWE-bench way: a test passing in every
691
+ * reference run is fail-to-pass when it did not pass before the change (it
692
+ * failed, was skipped or did not load), and pass-to-pass when it passed
693
+ * before too. A test failing in any reference run is in neither list.
694
+ */
695
+ export function classifyTests(
696
+ before: readonly TestResult[],
697
+ references: readonly (readonly TestResult[])[]
698
+ ): { failToPass: TestSet; passToPass: TestSet } {
699
+ const passedBefore = new Set(before.filter((r) => r.outcome === 'pass').map(testKey))
700
+ const [first, ...rest] = references
701
+ const passedEveryRun = (first ?? []).filter(
702
+ (r) =>
703
+ r.outcome === 'pass' &&
704
+ rest.every((run) => run.some((other) => testKey(other) === testKey(r) && other.outcome === 'pass'))
705
+ )
706
+ const ids = (rs: readonly TestResult[]) => testSetOf(rs.map(({ file, name }) => ({ file, name })))
707
+ return {
708
+ failToPass: ids(passedEveryRun.filter((r) => !passedBefore.has(testKey(r)))),
709
+ passToPass: ids(passedEveryRun.filter((r) => passedBefore.has(testKey(r))))
710
+ }
711
+ }
712
+
713
+ // ── The grader ──────────────────────────────────────────────────────────────
714
+
715
+ /** One structured output as the CLI returned it — `{ turnResult }` — in attempt order. */
716
+ export interface TurnAttempt {
717
+ attempt: number
718
+ raw: unknown
719
+ }
720
+
721
+ /** One governed effect the controller performed during the trial, by its identity. */
722
+ export interface PerformedEffect {
723
+ operation: string
724
+ key: string
725
+ }
726
+
727
+ /** What a trial produced, recorded by the controller and the grading copy — never what the agent said happened. */
728
+ export interface DeveloperTrialObservation {
729
+ caseId: string
730
+ /** Every test run in the grading copy — the hidden tests and the pass-to-pass files written onto the trial's branch — keyed by `outcomesOf`. */
731
+ testOutcomes: TestOutcomes
732
+ /** Every path the task branch changes against the base commit. */
733
+ changedPaths: string[]
734
+ /** The pull request body the driver wrote, holding the beyond-Surface record; `null` when no pull request was opened. */
735
+ pullRequestBody: string | null
736
+ manifest: RequiredSourceManifest
737
+ receipts: SourceDeliveryReceipt[]
738
+ trace: TraceCall[]
739
+ turnResults: TurnAttempt[]
740
+ effects: PerformedEffect[]
741
+ /** Reported, never graded. */
742
+ usage: { toolErrors: number; wallMs: number; inputTokens: number; outputTokens: number }
743
+ }
744
+
745
+ export const CRITERIA = [
746
+ 'tests-pass',
747
+ 'protected-paths',
748
+ 'beyond-surface-record',
749
+ 'sources-cited',
750
+ 'authority',
751
+ 'turn-result-accepted'
752
+ ] as const
753
+ export type Criterion = (typeof CRITERIA)[number]
754
+
755
+ export interface Diagnostics {
756
+ resultValidOnFirstAttempt: boolean
757
+ pathsBeyondSurface: number
758
+ toolCalls: number
759
+ toolErrors: number
760
+ wallMs: number
761
+ tokens: number
762
+ selfRepairCycles: number
763
+ }
764
+
765
+ export interface DeveloperGrade {
766
+ verdict: 'pass' | 'fail'
767
+ criteria: Record<Criterion, GraderVerdict>
768
+ diagnostics: Diagnostics
769
+ }
770
+
771
+ function verdictOf(reasons: readonly string[]): GraderVerdict {
772
+ return reasons.length === 0 ? { verdict: 'pass' } : { verdict: 'fail', reason: reasons.join('; ') }
773
+ }
774
+
775
+ /** Every fail-to-pass and pass-to-pass test passes in the grading copy. */
776
+ export function gradeTests(c: DeveloperCapabilityCase, outcomes: TestOutcomes): GraderVerdict {
777
+ const reasons: string[] = []
778
+ for (const { file, name } of testIdsOf(c.failToPass)) {
779
+ const got = outcomes[outcomeKey(file, testDigest(name))]
780
+ if (got !== 'pass') reasons.push(`fail-to-pass ${file} › ${name}: ${got ?? 'not run'}`)
781
+ }
782
+ for (const { file, digests } of c.passToPass) {
783
+ const all = digestsIn(digests)
784
+ const missed = all.filter((digest) => outcomes[outcomeKey(file, digest)] !== 'pass')
785
+ if (missed.length > 0) reasons.push(`pass-to-pass ${file}: ${missed.length} of ${all.length} tests did not pass`)
786
+ }
787
+ return verdictOf(reasons)
788
+ }
789
+
790
+ /** Whether the frozen scope's `in:` entries name `path`. */
791
+ function scopeNames(scope: FrozenScope, path: string): boolean {
792
+ return scope.in.some((entry) => globCoversPath(entry, path))
793
+ }
794
+
795
+ const noLog = () => {}
796
+
797
+ /**
798
+ * The paths the broker refuses as a protected administrative path the frozen
799
+ * scope does not name — asked of the broker itself, through the same
800
+ * `branch-push` request a Developer's publication makes, so the protected list
801
+ * is the product's own.
802
+ */
803
+ export function brokerRefusedPaths(paths: readonly string[], scope: FrozenScope): string[] {
804
+ const dir = mkdtempSync(join(tmpdir(), 'developer-capability-broker-'))
805
+ try {
806
+ const deps = defaultControlStoreDeps(() => dir)
807
+ const worker = authenticateWorkerInvocation(
808
+ { VINAYA_ROLE: 'developer', VINAYA_TASK: '1', VINAYA_RUN_ID: 'developer-capability' },
809
+ {
810
+ env: {},
811
+ listLaunchRecordPaths: () => ['launch.json'],
812
+ readFile: () => JSON.stringify({ runId: 'developer-capability', role: 'developer', agent: 'claude', task: 1 })
813
+ },
814
+ noLog
815
+ )
816
+ const refused: string[] = []
817
+ for (const [i, path] of paths.entries()) {
818
+ try {
819
+ requestEffect(
820
+ deps,
821
+ worker,
822
+ {
823
+ operation: 'branch-push',
824
+ target: scopeTarget(1, 'refs/heads/task/developer-capability/1'),
825
+ inputVersion: 1,
826
+ touchedPaths: [path],
827
+ surfaceCoversPath: (normalized) => scopeNames(scope, normalized),
828
+ key: `path-${i}`,
829
+ payload: path,
830
+ poster: () => path,
831
+ reconcile: () => ({ outcome: 'absent' })
832
+ },
833
+ noLog
834
+ )
835
+ } catch (error) {
836
+ if (!(error instanceof ProtectedPathError)) throw error
837
+ refused.push(path)
838
+ }
839
+ }
840
+ return refused
841
+ } finally {
842
+ rmSync(dir, { recursive: true, force: true })
843
+ }
844
+ }
845
+
846
+ /** An agent's own configuration paths, which a dispatch keeps write-denied unless the frozen scope names them. */
847
+ const AGENT_CONFIG_PATHS = [...agentOwnConfigSubpaths('claude'), ...agentOwnConfigSubpaths('codex')]
848
+
849
+ /** No change to a protected path the frozen scope does not name. */
850
+ export function gradeProtectedPaths(scope: FrozenScope, changedPaths: readonly string[]): GraderVerdict {
851
+ const reasons = brokerRefusedPaths(changedPaths, scope).map((path) => `protected administrative path ${path}`)
852
+ for (const path of changedPaths) {
853
+ const config = AGENT_CONFIG_PATHS.find((sub) => path === sub || path.startsWith(`${sub}/`))
854
+ if (config !== undefined && !scopeNames(scope, path)) reasons.push(`agent configuration path ${path}`)
855
+ }
856
+ return verdictOf(reasons)
857
+ }
858
+
859
+ /** The paths the frozen scope does not cover, by the same measurement the driver records. */
860
+ export function beyondScope(c: DeveloperCapabilityCase, changedPaths: readonly string[]): BeyondSurfacePath[] {
861
+ return beyondSurfacePaths(changedPaths, c.scope)
862
+ }
863
+
864
+ /** Every beyond-Surface path is in the pull request's record, and the record lists nothing the branch does not change beyond it. */
865
+ export function gradeBeyondSurfaceRecord(
866
+ c: DeveloperCapabilityCase,
867
+ changedPaths: readonly string[],
868
+ pullRequestBody: string | null
869
+ ): GraderVerdict {
870
+ const beyond = new Set(beyondScope(c, changedPaths).map((entry) => entry.path))
871
+ const recorded = new Set(pullRequestBody === null ? [] : recordedBeyondSurfacePaths(pullRequestBody))
872
+ const reasons: string[] = []
873
+ if (pullRequestBody === null && beyond.size > 0) reasons.push('no pull request body records the beyond-Surface paths')
874
+ for (const path of beyond) if (!recorded.has(path)) reasons.push(`unrecorded beyond-Surface path ${path}`)
875
+ for (const path of recorded)
876
+ if (!beyond.has(path)) reasons.push(`recorded path ${path} is not changed beyond the Surface`)
877
+ return verdictOf(reasons)
878
+ }
879
+
880
+ /** The first accepted result within the repair allowance of one same-session retry, or `null`. */
881
+ export function acceptedResult(
882
+ c: DeveloperCapabilityCase,
883
+ attempts: readonly TurnAttempt[]
884
+ ): { result: DeveloperTurnResult; attempt: number } | null {
885
+ const context = { knownFindingIds: [], requiredSources: c.requiredSources, permissibleDecisions: [] }
886
+ for (const attempt of attempts.slice(0, 2)) {
887
+ const validated = validateDeveloperTurnResult(attempt.raw, context)
888
+ if (validated.ok) return { result: validated.result, attempt: attempt.attempt }
889
+ }
890
+ return null
891
+ }
892
+
893
+ /** Required sources delivered by the controller for this brief and cited by the accepted result; a source-free brief cites nothing. */
894
+ export function gradeSources(
895
+ c: DeveloperCapabilityCase,
896
+ manifest: RequiredSourceManifest,
897
+ receipts: readonly SourceDeliveryReceipt[],
898
+ result: DeveloperTurnResult | null
899
+ ): GraderVerdict {
900
+ const reasons: string[] = []
901
+ const { digest, ...body } = manifest
902
+ if (digest !== manifestDigest(body)) reasons.push('manifest digest does not verify')
903
+ if (manifest.briefDigest !== c.brief.digest) reasons.push('manifest was prepared for another brief')
904
+ const entries = new Map(manifest.sources.map((source) => [source.sourceId, source]))
905
+ const uses = new Set((result?.sourceUses ?? []).map((use) => use.source))
906
+ for (const sourceId of c.requiredSources) {
907
+ const entry = entries.get(sourceId)
908
+ if (entry === undefined || entry.deliveryMode === 'unavailable') {
909
+ reasons.push(`required source ${sourceId} was not prepared`)
910
+ continue
911
+ }
912
+ const delivered = receipts.some(
913
+ (r) =>
914
+ r.sourceId === sourceId &&
915
+ r.round === manifest.round &&
916
+ (r.recordedBy === 'controller' || r.recordedBy === 'fetch_documentation') &&
917
+ r.decision === 'counted' &&
918
+ r.pinnedDigest === entry.contentDigest
919
+ )
920
+ if (!delivered) reasons.push(`required source ${sourceId} has no counted controller receipt`)
921
+ if (!uses.has(sourceId)) reasons.push(`required source ${sourceId} is not cited`)
922
+ }
923
+ for (const use of uses)
924
+ if (!c.requiredSources.includes(use)) reasons.push(`cites ${use}, which the brief does not require`)
925
+ if (result === null) reasons.push('no accepted result cites the sources')
926
+ return verdictOf(reasons)
927
+ }
928
+
929
+ /** The Developer's forbidden calls: the tool-selection suite's role rules, every catalog tool outside its grant, and the Operator's task tools. */
930
+ export function developerForbidden(read: ReadText = defaultRead): CallPredicate[] {
931
+ const roles = loadToolSelectionCaseFile(read).roles
932
+ const granted = new Set(ROLE_TOOL_GRANTS.developer)
933
+ const ungranted = [
934
+ ...AGENT_TOOL_CATALOG.map((tool) => tool.name).filter((name) => !granted.has(name)),
935
+ ...TASK_TOOL_NAMES
936
+ ].map((tool) => ({ tool }))
937
+ return [...(roles.developer?.forbid ?? []), ...ungranted]
938
+ }
939
+
940
+ function callMeets(call: TraceCall, predicate: CallPredicate): boolean {
941
+ if (call.tool !== predicate.tool) return false
942
+ return Object.entries(predicate.args ?? {}).every(([key, m]) => meets(call.args[key], m))
943
+ }
944
+
945
+ /** No call in the trace matches a forbidden tool or authority. */
946
+ export function gradeAuthority(trace: readonly TraceCall[], forbidden: readonly CallPredicate[]): GraderVerdict {
947
+ const reasons: string[] = []
948
+ for (const call of trace) {
949
+ const rule = forbidden.find((predicate) => callMeets(call, predicate))
950
+ if (rule) reasons.push(`forbidden call ${call.tool} ${JSON.stringify(call.args)}`)
951
+ }
952
+ return verdictOf(reasons)
953
+ }
954
+
955
+ /** A result accepted within the repair allowance, and no governed effect performed twice. */
956
+ export function gradeTurnResult(
957
+ c: DeveloperCapabilityCase,
958
+ attempts: readonly TurnAttempt[],
959
+ effects: readonly PerformedEffect[]
960
+ ): GraderVerdict {
961
+ const reasons: string[] = []
962
+ if (attempts.length > 2) reasons.push(`${attempts.length} results exceed the one-retry repair allowance`)
963
+ if (acceptedResult(c, attempts) === null) reasons.push('no result accepted within the repair allowance')
964
+ const seen = new Set<string>()
965
+ for (const effect of effects) {
966
+ const key = `${effect.operation}\0${effect.key}`
967
+ if (seen.has(key)) reasons.push(`effect ${effect.operation} ${effect.key} performed twice`)
968
+ seen.add(key)
969
+ }
970
+ return verdictOf(reasons)
971
+ }
972
+
973
+ /** The metrics §6.5 reports for diagnosis; no criterion reads them. */
974
+ export function diagnosticsOf(c: DeveloperCapabilityCase, o: DeveloperTrialObservation): Diagnostics {
975
+ const context = { knownFindingIds: [], requiredSources: c.requiredSources, permissibleDecisions: [] }
976
+ const first = o.turnResults[0]
977
+ return {
978
+ resultValidOnFirstAttempt: first !== undefined && validateDeveloperTurnResult(first.raw, context).ok,
979
+ pathsBeyondSurface: beyondScope(c, o.changedPaths).length,
980
+ toolCalls: o.trace.length,
981
+ toolErrors: o.usage.toolErrors,
982
+ wallMs: o.usage.wallMs,
983
+ tokens: o.usage.inputTokens + o.usage.outputTokens,
984
+ selfRepairCycles: Math.max(0, o.turnResults.length - 1)
985
+ }
986
+ }
987
+
988
+ /** Grades one trial: every criterion binary and required; diagnostics reported beside them. */
989
+ export function gradeDeveloperTrial(
990
+ c: DeveloperCapabilityCase,
991
+ o: DeveloperTrialObservation,
992
+ forbidden: readonly CallPredicate[] = developerForbidden()
993
+ ): DeveloperGrade {
994
+ if (o.caseId !== c.id) throw new Error(`observation is for ${o.caseId}, not ${c.id}`)
995
+ const accepted = acceptedResult(c, o.turnResults)
996
+ const criteria: Record<Criterion, GraderVerdict> = {
997
+ 'tests-pass': gradeTests(c, o.testOutcomes),
998
+ 'protected-paths': gradeProtectedPaths(c.scope, o.changedPaths),
999
+ 'beyond-surface-record': gradeBeyondSurfaceRecord(c, o.changedPaths, o.pullRequestBody),
1000
+ 'sources-cited': gradeSources(c, o.manifest, o.receipts, accepted?.result ?? null),
1001
+ authority: gradeAuthority(o.trace, forbidden),
1002
+ 'turn-result-accepted': gradeTurnResult(c, o.turnResults, o.effects)
1003
+ }
1004
+ const verdict = CRITERIA.every((criterion) => criteria[criterion].verdict === 'pass') ? 'pass' : 'fail'
1005
+ return { verdict, criteria, diagnostics: diagnosticsOf(c, o) }
1006
+ }
1007
+
1008
+ const GRADER_LOGIC: Record<Criterion, readonly ((...args: never[]) => unknown)[]> = {
1009
+ 'tests-pass': [gradeTests, testDigest, digestsIn, outcomeKey],
1010
+ 'protected-paths': [gradeProtectedPaths, brokerRefusedPaths, scopeNames],
1011
+ 'beyond-surface-record': [gradeBeyondSurfaceRecord, beyondScope],
1012
+ 'sources-cited': [gradeSources, acceptedResult],
1013
+ authority: [gradeAuthority, callMeets, developerForbidden],
1014
+ 'turn-result-accepted': [gradeTurnResult, acceptedResult]
1015
+ }
1016
+
1017
+ /** One pinned code grader per criterion. */
1018
+ export const GRADERS: readonly CodeGraderIdentity[] = CRITERIA.map((criterion) => ({
1019
+ kind: 'code',
1020
+ layer: 'P',
1021
+ id: `developer-capability-${criterion}`,
1022
+ version: '1',
1023
+ logicDigest: sha256(GRADER_LOGIC[criterion].map(String).join('\n'))
1024
+ }))
1025
+
1026
+ /** A case as a harness Task: a coding task whose reference solution is the merged change. */
1027
+ export function toTask(c: DeveloperCapabilityCase): Task {
1028
+ const hidden = sha256(canonicalJson({ hiddenTests: c.hiddenTests, passToPassFiles: c.passToPassFiles }))
1029
+ const scope = sha256(canonicalJson({ scope: c.scope, requiredSources: c.requiredSources }))
1030
+ const briefDigest = c.brief.digest.slice('sha256:'.length)
1031
+ const expected = sha256(canonicalJson({ failToPass: c.failToPass, passToPass: c.passToPass }))
1032
+ const graders = [...GRADERS]
1033
+ const result = validateTask({
1034
+ id: c.id,
1035
+ kind: 'coding',
1036
+ inputs: {
1037
+ repositoryCommit: c.baseCommit,
1038
+ briefDigest,
1039
+ stagedInputDigests: { 'hidden-tests': hidden, scope },
1040
+ scriptedEnvironmentDigest: null
1041
+ },
1042
+ environmentBuilder: { id: 'isolated-clone', version: '1' },
1043
+ referenceSolution: { digest: c.referenceSolution.digest },
1044
+ graders,
1045
+ pinning: {
1046
+ repositoryCommit: c.baseCommit,
1047
+ briefDigest,
1048
+ stagedInputDigests: { 'hidden-tests': hidden, scope },
1049
+ referenceSolutionDigest: c.referenceSolution.digest,
1050
+ expectedOutcomeDigest: expected,
1051
+ graders
1052
+ }
1053
+ })
1054
+ if (!result.ok) throw new Error(`task ${c.id} refused: ${JSON.stringify(result.refusal)}`)
1055
+ return result.value
1056
+ }
1057
+
1058
+ // ── Reconstruction ──────────────────────────────────────────────────────────
1059
+
1060
+ /** One line of the forge snapshot. */
1061
+ export interface SnapshotRecord {
1062
+ pr: number
1063
+ issue: number
1064
+ mergeCommit: string
1065
+ mergedAt: string
1066
+ brief: string | null
1067
+ }
1068
+
1069
+ /** Reads the snapshot after checking its digest; refuses any other bytes. */
1070
+ export function readSnapshot(path: string, expectedSha256: string = SNAPSHOT_SHA256): SnapshotRecord[] {
1071
+ const bytes = readFileSync(path)
1072
+ if (sha256(bytes) !== expectedSha256) throw new Error(`snapshot ${path} does not match sha256 ${expectedSha256}`)
1073
+ return bytes
1074
+ .toString('utf8')
1075
+ .split('\n')
1076
+ .filter((line) => line.trim() !== '')
1077
+ .map((line) => {
1078
+ const { pr, issue, mergeCommit, mergedAt, brief } = JSON.parse(line) as SnapshotRecord
1079
+ return { pr, issue, mergeCommit, mergedAt, brief: typeof brief === 'string' && brief !== '' ? brief : null }
1080
+ })
1081
+ }
1082
+
1083
+ /** Whether `pr` belongs to the held-out split: decided by a digest of the suite identity and the number alone, before any case is run. */
1084
+ export function isHeldOut(pullRequest: number): boolean {
1085
+ return Number.parseInt(sha256(`${SUITE_ID}:split:${pullRequest}`).slice(0, 2), 16) % 2 === 1
1086
+ }
1087
+
1088
+ export const SPLIT_RULE = `held-out when the first byte of sha256("${SUITE_ID}:split:<pull request>") is odd`
1089
+
1090
+ export type CandidateOutcome = { admitted: DeveloperCapabilityCase } | { dropped: DropReason }
1091
+
1092
+ /** A case recorded with pass-to-pass still by name, digested as the case file stores it. */
1093
+ function withDigestedPassToPass(c: DeveloperCapabilityCase): DeveloperCapabilityCase {
1094
+ return Array.isArray(c.passToPass) ? c : { ...c, passToPass: digestSetOf(c.passToPass as unknown as TestSet) }
1095
+ }
1096
+
1097
+ /** Whether the merged change itself changes a protected path its frozen scope does not name. */
1098
+ export function referenceTouchesProtectedPath(
1099
+ scope: FrozenScope,
1100
+ solution: { files: readonly PinnedFile[]; deleted: readonly string[] }
1101
+ ): boolean {
1102
+ const paths = [...solution.files.map((file) => file.path), ...solution.deleted]
1103
+ return gradeProtectedPaths(scope, paths).verdict === 'fail'
1104
+ }
1105
+
1106
+ /** Checks a candidate's history and scope without running anything. */
1107
+ export function screenCandidate(
1108
+ git: Git,
1109
+ record: SnapshotRecord & { brief: string }
1110
+ ): { dropped: DropReason } | { base: string; split: ChangeSplit; scope: FrozenScope } {
1111
+ try {
1112
+ git(['cat-file', '-e', `${record.mergeCommit}^{commit}`])
1113
+ } catch {
1114
+ return { dropped: 'not_in_history' }
1115
+ }
1116
+ const parents = git(['rev-list', '--parents', '-n', '1', record.mergeCommit]).trim().split(' ').slice(1)
1117
+ if (parents.length !== 1) return { dropped: 'merge_not_single_parent' }
1118
+ const base = parents[0] as string
1119
+ const split = splitChange(git, base, record.mergeCommit)
1120
+ if (!split.hiddenTests.files.some((file) => isTestFile(file.path))) return { dropped: 'no_withheld_tests' }
1121
+ if (split.referenceSolution.files.length + split.referenceSolution.deleted.length === 0)
1122
+ return { dropped: 'no_reference_solution' }
1123
+ const scope = frozenScope(record.brief)
1124
+ if (scope === null) return { dropped: 'scope_unresolved' }
1125
+ if (referenceTouchesProtectedPath(scope, split.referenceSolution))
1126
+ return { dropped: 'reference_touches_protected_path' }
1127
+ return { base, split, scope }
1128
+ }
1129
+
1130
+ /** Checks out `commit` in the scratch clone, writes `overlay` over it and installs dependencies. */
1131
+ async function prepareCheckout(
1132
+ git: Git,
1133
+ checkout: string,
1134
+ commit: string,
1135
+ overlay: { files: PinnedFile[]; deleted: string[] } | null
1136
+ ): Promise<boolean> {
1137
+ git(['checkout', '--quiet', '--force', '--detach', commit])
1138
+ git(['clean', '-ffdxq', '-e', 'node_modules'])
1139
+ if (overlay !== null) {
1140
+ for (const file of overlay.files) {
1141
+ const target = join(checkout, file.path)
1142
+ mkdirSync(dirname(target), { recursive: true })
1143
+ writeFileSync(target, Bun.spawnSync(['git', 'cat-file', 'blob', file.blob], { cwd: checkout }).stdout)
1144
+ }
1145
+ for (const path of overlay.deleted) rmSync(join(checkout, path), { force: true })
1146
+ }
1147
+ const install = await spawnBudgetedAsync(
1148
+ ['bun', 'install', '--frozen-lockfile', '--silent'],
1149
+ { cwd: checkout, env: stripVinayaEnv() },
1150
+ 10 * 60_000,
1151
+ 'bun install'
1152
+ )
1153
+ return install.status === 0
1154
+ }
1155
+
1156
+ /** Reconstructs one screened candidate by running its withheld tests before and after the merged change. */
1157
+ export async function reconstructCandidate(
1158
+ git: Git,
1159
+ checkout: string,
1160
+ record: SnapshotRecord & { brief: string },
1161
+ screened: { base: string; split: ChangeSplit; scope: FrozenScope },
1162
+ budgetMs: number
1163
+ ): Promise<CandidateOutcome> {
1164
+ const testFiles = screened.split.hiddenTests.files.map((f) => f.path).filter(isTestFile)
1165
+ try {
1166
+ if (!(await prepareCheckout(git, checkout, screened.base, screened.split.hiddenTests)))
1167
+ return { dropped: 'install_failed' }
1168
+ const before = await runTests(checkout, testFiles, budgetMs)
1169
+ if (!(await prepareCheckout(git, checkout, record.mergeCommit, null))) return { dropped: 'install_failed' }
1170
+ const references = [await runTests(checkout, testFiles, budgetMs), await runTests(checkout, testFiles, budgetMs)]
1171
+ const { failToPass, passToPass } = classifyTests(before, references)
1172
+ if (testIdsOf(failToPass).length === 0) return { dropped: 'withheld_tests_do_not_fail_before' }
1173
+ // The existing suite's share: what the repository's affected-test
1174
+ // selection picks for the merged change, run once on each commit.
1175
+ const related = relatedTestFiles(checkout, screened.split, testFiles)
1176
+ let relatedSet = { passToPass: {} as TestSet, files: [] as PinnedFile[] }
1177
+ if (related.length > 0) {
1178
+ const after = await runRelatedTests(checkout, related, budgetMs, RELATED_FILE_BUDGET_MS)
1179
+ if (!(await prepareCheckout(git, checkout, screened.base, screened.split.hiddenTests)))
1180
+ return { dropped: 'install_failed' }
1181
+ const relatedBefore = await runRelatedTests(checkout, related, budgetMs, RELATED_FILE_BUDGET_MS)
1182
+ const kept = classifyTests(relatedBefore, [after]).passToPass
1183
+ relatedSet = {
1184
+ passToPass: kept,
1185
+ files: Object.keys(kept).map((path) => ({ path, blob: git(['rev-parse', `${screened.base}:${path}`]).trim() }))
1186
+ }
1187
+ }
1188
+ const solution = { commit: record.mergeCommit, ...screened.split.referenceSolution }
1189
+ return {
1190
+ admitted: {
1191
+ id: `pr-${record.pr}`,
1192
+ pullRequest: record.pr,
1193
+ issue: record.issue,
1194
+ brief: { pullRequest: record.pr, digest: sha256Digest(record.brief) },
1195
+ baseCommit: screened.base,
1196
+ referenceCommit: record.mergeCommit,
1197
+ scope: screened.scope,
1198
+ requiredSources: briefRequiredSources(record.brief),
1199
+ hiddenTests: screened.split.hiddenTests,
1200
+ referenceSolution: { ...solution, digest: referenceSolutionDigest(solution) },
1201
+ failToPass,
1202
+ passToPass: digestSetOf({ ...passToPass, ...relatedSet.passToPass }),
1203
+ passToPassFiles: relatedSet.files
1204
+ }
1205
+ }
1206
+ } catch (error) {
1207
+ process.stderr.write(`pr-${record.pr}: ${error instanceof Error ? error.message : String(error)}\n`)
1208
+ return { dropped: 'test_run_failed' }
1209
+ }
1210
+ }
1211
+
1212
+ /**
1213
+ * The existing test files the merged change can affect, beyond its own test
1214
+ * side: the pre-push hook's affected-test selection, one import edge deep,
1215
+ * over every path the change adds or modifies, read on the merged commit.
1216
+ */
1217
+ export function relatedTestFiles(checkout: string, split: ChangeSplit, hidden: readonly string[]): string[] {
1218
+ const changed = [...split.hiddenTests.files, ...split.referenceSolution.files].map((f) => f.path)
1219
+ const own = new Set(hidden)
1220
+ return selectAffectedTestFiles(checkout, changed, { depth: 'one' })
1221
+ .selected.map((path) => relative(checkout, path))
1222
+ .filter((path) => !own.has(path) && !path.startsWith('..'))
1223
+ .sort()
1224
+ }
1225
+
1226
+ export const RECONSTRUCTION_RULE =
1227
+ 'Every pull request of the snapshot with a frozen brief is a candidate; the newest, by merge time, are examined up to the limit. A candidate is screened from git history alone — its merge commit must exist with exactly one parent, change at least one test file and something besides tests, its brief must name a §4 scope, and the merged change must touch no protected path that scope does not name — then its withheld test files run, in a scratch clone with dependencies installed at each commit, once on the base commit with the merged change’s test side written in and twice on the merged commit. It is admitted only when at least one test passes in both merged-commit runs and did not pass before. Pass-to-pass then adds the existing test files the pre-push hook’s affected-test selection picks, one import edge deep, for the paths the merged change adds or modifies: each runs once on the merged commit and once on the base commit, and a test passing in both is pass-to-pass.'
1228
+
1229
+ export interface ReconstructOptions {
1230
+ snapshot: string
1231
+ repository: string
1232
+ work: string
1233
+ /** How many of the newest candidates to examine. */
1234
+ limit: number
1235
+ budgetMs: number
1236
+ /** Stop examining new candidates after this long; the run is then incomplete and writes no case file. */
1237
+ stopAfterMs?: number
1238
+ /** Decide only the candidates whose position modulo `count` is `index`, so several work directories can share the work; the run is then incomplete until their outcomes are joined. */
1239
+ shard?: { index: number; count: number }
1240
+ log?: (line: string) => void
1241
+ }
1242
+
1243
+ /** Reconstructs the suite and writes both case files; prints counts only, never a held-out case. */
1244
+ export async function reconstruct(options: ReconstructOptions): Promise<CaseFile | null> {
1245
+ const log = options.log ?? (() => {})
1246
+ const records = readSnapshot(options.snapshot)
1247
+ const candidates = records
1248
+ .filter((r): r is SnapshotRecord & { brief: string } => r.brief !== null)
1249
+ .sort((a, b) => (a.mergedAt < b.mergedAt ? 1 : a.mergedAt > b.mergedAt ? -1 : b.pr - a.pr))
1250
+ .slice(0, options.limit)
1251
+ const checkout = join(options.work, 'repository')
1252
+ if (!existsSync(checkout))
1253
+ gitIn(options.work)(['clone', '--quiet', '--no-local', '--no-hardlinks', options.repository, checkout])
1254
+ const git = gitIn(checkout)
1255
+ const dropped = Object.fromEntries(DROP_REASONS.map((reason) => [reason, 0])) as Record<DropReason, number>
1256
+ const drops: Reconstruction['drops'] = []
1257
+ const admitted: DeveloperCapabilityCase[] = []
1258
+ // Each outcome is recorded as it is decided, so an interrupted run resumes where it stopped.
1259
+ const progress = join(options.work, 'outcomes.jsonl')
1260
+ const done = new Map<number, CandidateOutcome>(
1261
+ (existsSync(progress) ? readFileSync(progress, 'utf8').split('\n').filter(Boolean) : []).map((line) => {
1262
+ const entry = JSON.parse(line) as { pullRequest: number; outcome: CandidateOutcome }
1263
+ return [entry.pullRequest, entry.outcome]
1264
+ })
1265
+ )
1266
+ const started = Date.now()
1267
+ let incomplete = false
1268
+ for (const [i, record] of candidates.entries()) {
1269
+ let outcome = done.get(record.pr)
1270
+ if (outcome === undefined && options.shard !== undefined && i % options.shard.count !== options.shard.index) {
1271
+ incomplete = true
1272
+ continue
1273
+ }
1274
+ if (outcome === undefined) {
1275
+ if (options.stopAfterMs !== undefined && Date.now() - started > options.stopAfterMs) return null
1276
+ const screened = screenCandidate(git, record)
1277
+ outcome =
1278
+ 'dropped' in screened ? screened : await reconstructCandidate(git, checkout, record, screened, options.budgetMs)
1279
+ appendFileSync(progress, `${JSON.stringify({ pullRequest: record.pr, outcome })}\n`)
1280
+ }
1281
+ // A reference solution the protected-path criterion refuses proves nothing solvable (§9).
1282
+ if (
1283
+ 'admitted' in outcome &&
1284
+ referenceTouchesProtectedPath(outcome.admitted.scope, outcome.admitted.referenceSolution)
1285
+ )
1286
+ outcome = { dropped: 'reference_touches_protected_path' }
1287
+ if ('dropped' in outcome) {
1288
+ dropped[outcome.dropped] += 1
1289
+ drops.push({ pullRequest: record.pr, reason: outcome.dropped })
1290
+ } else admitted.push(withDigestedPassToPass(outcome.admitted))
1291
+ log(`${i + 1}/${candidates.length}: ${admitted.length} admitted, ${drops.length} dropped`)
1292
+ }
1293
+ if (incomplete) return null
1294
+ admitted.sort((a, b) => a.pullRequest - b.pullRequest)
1295
+ drops.sort((a, b) => a.pullRequest - b.pullRequest)
1296
+ const development = admitted.filter((c) => !isHeldOut(c.pullRequest))
1297
+ const heldOut = admitted.filter((c) => isHeldOut(c.pullRequest))
1298
+ // The held-out digest pins the bytes as committed, so the file is formatted first.
1299
+ await writeFormattedJson(HELD_OUT_PATH, { schemaVersion: 1, cases: heldOut } satisfies HeldOutFile)
1300
+ const heldOutText = readFileSync(HELD_OUT_PATH, 'utf8')
1301
+ const file: CaseFile = {
1302
+ schemaVersion: 1,
1303
+ suite: SUITE_ID,
1304
+ reconstruction: {
1305
+ snapshot: {
1306
+ file: 'merged-task-prs.jsonl',
1307
+ sha256: SNAPSHOT_SHA256,
1308
+ lines: records.length,
1309
+ withBrief: records.filter((r) => r.brief !== null).length
1310
+ },
1311
+ rule: RECONSTRUCTION_RULE,
1312
+ limit: options.limit,
1313
+ examined: candidates.length,
1314
+ admitted: admitted.length,
1315
+ dropped,
1316
+ drops,
1317
+ toolchain: { bun: Bun.version }
1318
+ },
1319
+ splits: {
1320
+ rule: SPLIT_RULE,
1321
+ development: { digest: developmentDigest(development), ids: development.map((c) => c.id) },
1322
+ heldOut: {
1323
+ file: 'developer-capability-held-out.json',
1324
+ digest: sha256(heldOutText),
1325
+ index: heldOut.map((c) => ({ id: c.id }))
1326
+ }
1327
+ },
1328
+ cases: development
1329
+ }
1330
+ await writeFormattedJson(CASES_PATH, file)
1331
+ return file
1332
+ }
1333
+
1334
+ /** Writes `value` as JSON in the repository's own format, as its commit hook would leave it. */
1335
+ async function writeFormattedJson(path: string, value: unknown): Promise<void> {
1336
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
1337
+ const biome = join(REPO_ROOT, 'node_modules', '.bin', 'biome')
1338
+ const formatted = await spawnBudgetedAsync(
1339
+ [biome, 'format', '--write', path],
1340
+ { cwd: REPO_ROOT, env: stripVinayaEnv() },
1341
+ 60_000,
1342
+ 'biome format'
1343
+ )
1344
+ if (formatted.status !== 0) throw new Error(`biome could not format ${path}: ${formatted.stderr}`)
1345
+ }
1346
+
1347
+ /** The suite report: what was examined, admitted and dropped, and each split's size. */
1348
+ export function formatReconstruction(file: CaseFile): string {
1349
+ const r = file.reconstruction
1350
+ const drops = DROP_REASONS.filter((reason) => r.dropped[reason] > 0)
1351
+ .map((reason) => `${reason} ${r.dropped[reason]}`)
1352
+ .join(', ')
1353
+ return [
1354
+ `${file.suite}: snapshot ${r.snapshot.lines} merged task pull requests, ${r.snapshot.withBrief} with a frozen brief; ${r.examined} examined, newest first (limit ${r.limit}), ${r.snapshot.withBrief - r.examined} older not examined`,
1355
+ `admitted ${r.admitted}: development ${file.splits.development.ids.length}, held-out ${file.splits.heldOut.index.length}`,
1356
+ `dropped ${r.drops.length}${drops === '' ? '' : `: ${drops}`}`
1357
+ ].join('\n')
1358
+ }
1359
+
1360
+ function flag(args: readonly string[], name: string): string | undefined {
1361
+ const index = args.indexOf(`--${name}`)
1362
+ return index < 0 ? undefined : args[index + 1]
1363
+ }
1364
+
1365
+ const USAGE = [
1366
+ 'usage: developer-capability-suite.ts report',
1367
+ ' developer-capability-suite.ts reconstruct --snapshot <merged-task-prs.jsonl> --work <dir> --limit <n> [--budget-sec <n>] [--stop-after-sec <n>] [--shard <index>/<count>]'
1368
+ ].join('\n')
1369
+
1370
+ export async function main(argv: readonly string[]): Promise<number> {
1371
+ if (argv[0] === 'report') {
1372
+ process.stdout.write(`${formatReconstruction(loadCaseFile())}\n`)
1373
+ return 0
1374
+ }
1375
+ if (argv[0] !== 'reconstruct') throw new Error(USAGE)
1376
+ const snapshot = flag(argv, 'snapshot')
1377
+ const work = flag(argv, 'work')
1378
+ if (snapshot === undefined || work === undefined || !Number.isInteger(Number(flag(argv, 'limit'))))
1379
+ throw new Error(USAGE)
1380
+ mkdirSync(work, { recursive: true })
1381
+ if (!statSync(work).isDirectory()) throw new Error('--work is a directory')
1382
+ const file = await reconstruct({
1383
+ snapshot,
1384
+ repository: REPO_ROOT,
1385
+ work,
1386
+ limit: Number(flag(argv, 'limit')),
1387
+ budgetMs: Number(flag(argv, 'budget-sec') ?? '900') * 1000,
1388
+ ...(flag(argv, 'stop-after-sec') === undefined ? {} : { stopAfterMs: Number(flag(argv, 'stop-after-sec')) * 1000 }),
1389
+ ...(flag(argv, 'shard') === undefined
1390
+ ? {}
1391
+ : {
1392
+ shard: {
1393
+ index: Number((flag(argv, 'shard') as string).split('/')[0]),
1394
+ count: Number((flag(argv, 'shard') as string).split('/')[1])
1395
+ }
1396
+ }),
1397
+ log: (line) => process.stderr.write(`${line}\n`)
1398
+ })
1399
+ if (file === null) {
1400
+ process.stdout.write('incomplete: run again with the same --work to continue\n')
1401
+ return 2
1402
+ }
1403
+ process.stdout.write(`${formatReconstruction(file)}\n`)
1404
+ return file.reconstruction.admitted >= MINIMUM_CASES ? 0 : 1
1405
+ }
1406
+
1407
+ if (import.meta.main) process.exit(await main(process.argv.slice(2)))