Open History to see the last commit
1#!/usr/bin/env node
2/**
3 * Returns oracle lint reports to a coding agent while it works.
4 *
5 * AGENTS.md forbids the shortcuts that make an oracle pass without enforcing
6 * its law. Prose did not stop them, because nothing made a shortcut visible
7 * while the agent was still working. Each agent harness can run a command
8 * after an edit and at the end of a turn, and can return the command's output
9 * to the model. This script is that command for every harness: a thin
10 * adapter per harness reads its hook input and writes its response format.
11 *
12 * --format=claude|codex|gemini|copilot the harness that runs the hook
13 * --event=edit after an edit: lint the edited files' oracle files, and the
14 * oracle files that reach them through test-module imports
15 * --event=stop at the end of a turn: lint every file the branch changed
16 * --format=text print the reports and exit 1: `pnpm lint:changed` lints
17 * the changed files, `pnpm lint:oracles` (`--all`) every
18 * oracle file, and the pre-commit hook the staged files it
19 * passes as arguments
20 *
21 * Every mode runs only the `oracle/` rules, and ignores inline directives.
22 * The rules have no inline exception, and ESLint cannot protect one rule from
23 * an `eslint-disable` comment, so this pass is where they are enforced. The
24 * root ESLint config also runs them, so editors show them, but a directive can
25 * silence them there. The rules need no type information, so a typical file
26 * takes tens of milliseconds, and the largest about a second. The repository
27 * config builds a TypeScript program and takes several seconds per file,
28 * which is too slow for every edit; `pnpm lint`, the pre-commit hook, and CI
29 * run it.
30 *
31 * An edit hook sees only the harness's own edit tools. An edit made through a
32 * shell command reaches the model at the end of the turn, when the stop hook
33 * lints every changed file. When a harness's hook input names no file that
34 * this script can find, the edit hook lints every changed file as well.
35 *
36 * A hook lints the checkout that the agent works in, which the hook input's
37 * `cwd` names. A harness can run this script from the checkout where the
38 * session started while the agent works in a worktree under `.worktrees/`.
39 * When `cwd` is in another checkout that has its own copy of this script, that
40 * copy runs instead, so a branch is linted by its own rule, as CI lints it.
41 * Without `cwd`, the checkout is the one that holds this script.
42 */
43import { execFileSync, spawnSync } from 'node:child_process'
44import { existsSync, readFileSync, realpathSync } from 'node:fs'
45import { isAbsolute, join, relative, resolve, sep } from 'node:path'
46import { fileURLToPath } from 'node:url'
47import { parseArgs } from 'node:util'
48import tsParser from '@typescript-eslint/parser'
49import { ESLint } from 'eslint'
50import oraclePlugin from './eslint-plugin-oracle/index.js'
51import { resolveImportedTestModule } from './eslint-plugin-oracle/rules/no-unit-test.js'
52import {
53 describeLoweredRunBudget,
54 isOracleFile,
55 loweredRunBudgetsBetween,
56 mergeBase,
57} from './check-oracle-run-counts.mjs'
58
59const { values: options, positionals } = parseArgs({
60 options: {
61 format: { type: `string`, default: `text` },
62 event: { type: `string`, default: `edit` },
63 all: { type: `boolean`, default: false },
64 },
65 allowPositionals: true,
66})
67
68const formats = new Set([`claude`, `codex`, `gemini`, `copilot`, `text`])
69if (!formats.has(options.format)) {
70 throw new Error(`--format must be one of ${[...formats].join(`, `)}`)
71}
72if (![`edit`, `stop`].includes(options.event)) {
73 throw new Error(`--event must be edit or stop`)
74}
75const isHook = options.format !== `text`
76const inputText = isHook ? readFileSync(0, `utf8`) : ``
77const input = inputText.trim() === `` ? {} : JSON.parse(inputText)
78const scriptRoot = realpathSync(fileURLToPath(new URL(`../`, import.meta.url)))
79
80/** The top level of the git checkout that holds `cwd`, or undefined. */
81function checkoutOf(cwd) {
82 try {
83 return realpathSync(
84 execFileSync(`git`, [`rev-parse`, `--show-toplevel`], {
85 cwd,
86 encoding: `utf8`,
87 stdio: [`ignore`, `pipe`, `ignore`],
88 }).trim(),
89 )
90 } catch {
91 return undefined
92 }
93}
94
95const root =
96 (typeof input.cwd === `string` ? checkoutOf(input.cwd) : undefined) ??
97 scriptRoot
98const ownScript = join(root, `scripts`, `agent-lint-feedback.mjs`)
99const delegate = root !== scriptRoot && existsSync(ownScript)
100
101function git(...args) {
102 return execFileSync(`git`, args, { cwd: root, encoding: `utf8` }).trim()
103}
104
105function repositoryFiles(...outputs) {
106 return outputs
107 .flatMap((output) => output.split(`\n`))
108 .filter(Boolean)
109 .map((file) => join(root, file))
110}
111
112/**
113 * Every oracle file in the working tree, tracked or new. A new file that an
114 * agent has not added yet is linted like any other. Git leaves out ignored
115 * files: builds, and `.worktrees/`, where other checkouts and scratch copies
116 * live. A plain directory there has no `.git` entry, so without the ignore rule
117 * git would list each of its files as new work on this branch.
118 */
119function oracleFilesInTree() {
120 return repositoryFiles(
121 git(`ls-files`, `--cached`, `--others`, `--exclude-standard`),
122 ).filter((file) => isOracleFile(file))
123}
124
125// A relative import or re-export. Reading too much is harmless: a specifier
126// that names no test module resolves to nothing.
127const relativeSpecifier =
128 /\b(?:from|import|require)\s*\(?\s*['"](\.{1,2}\/[^'"\n]*)['"]/g
129const dependencies = new Map()
130
131/** The test modules that a file imports or re-exports, as the rule resolves them. */
132function testModuleDependencies(file) {
133 if (!dependencies.has(file)) {
134 const found = existsSync(file)
135 ? [...readFileSync(file, `utf8`).matchAll(relativeSpecifier)]
136 .map(([, specifier]) => resolveImportedTestModule(file, specifier))
137 .filter((dependency) => dependency !== undefined)
138 : []
139 dependencies.set(file, found)
140 }
141 return dependencies.get(file)
142}
143
144/** Whether an oracle file is edited, or reaches an edited file through test modules. */
145function reachesEdited(oracle, edited) {
146 const seen = new Set([oracle])
147 const pending = [oracle]
148 while (pending.length > 0) {
149 const current = pending.pop()
150 if (edited.has(current)) return true
151 for (const dependency of testModuleDependencies(current)) {
152 if (!seen.has(dependency)) {
153 seen.add(dependency)
154 pending.push(dependency)
155 }
156 }
157 }
158 return false
159}
160
161const pluginSources = join(root, `scripts`, `eslint-plugin-oracle`) + sep
162
163/**
164 * The oracle files that a lint of `files` must cover. The rule reads relative
165 * imports of test modules, so an oracle file is covered when it is named, or
166 * when it reaches a named file through test modules. Production files select
167 * nothing, because the rule does not follow them. A change to the rule's own
168 * sources changes every oracle result, so it selects every oracle file.
169 */
170function affectedOracleFiles(files) {
171 const edited = new Set(files)
172 const oracles = new Set(
173 [...oracleFilesInTree(), ...files].filter((file) => isOracleFile(file)),
174 )
175 if ([...edited].some((file) => file.startsWith(pluginSources)))
176 return [...oracles]
177 return [...oracles].filter((oracle) => reachesEdited(oracle, edited))
178}
179
180/**
181 * Every file that the branch adds or changes, including uncommitted work.
182 * `mergeBase` fails without a main branch, instead of linting only the
183 * uncommitted work.
184 */
185function changedFiles() {
186 const base = mergeBase(root)
187 return repositoryFiles(
188 git(`diff`, `--name-only`, `--diff-filter=ACMR`, base),
189 git(`ls-files`, `--others`, `--exclude-standard`),
190 )
191}
192
193const pathKeys = /^(file_?path|filePath|path|absolute_path|target_file)$/i
194const patchHeader = /^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm
195
196/**
197 * The files that a hook input names. Harnesses put the path in different
198 * fields, and Codex sends the text of an `apply_patch` call instead, so this
199 * searches the whole input for path fields and patch headers.
200 */
201function editedFiles(input) {
202 const base = typeof input.cwd === `string` ? input.cwd : root
203 const found = new Set()
204 const visit = (value, key) => {
205 if (typeof value === `string`) {
206 if (key !== undefined && pathKeys.test(key)) found.add(value)
207 for (const match of value.matchAll(patchHeader))
208 found.add(match[1].trim())
209 // Copilot's tool arguments can arrive as a JSON string.
210 if (/^\s*\{/.test(value)) {
211 try {
212 visit(JSON.parse(value))
213 } catch {
214 // Not JSON; already searched as text.
215 }
216 }
217 } else if (Array.isArray(value)) {
218 for (const item of value) visit(item)
219 } else if (value !== null && typeof value === `object`) {
220 for (const [childKey, child] of Object.entries(value))
221 visit(child, childKey)
222 }
223 }
224 visit(input.tool_input ?? input.toolArgs ?? input)
225 return [...found].map((file) =>
226 isAbsolute(file) ? file : resolve(base, file),
227 )
228}
229
230function createLinter() {
231 return new ESLint({
232 cwd: root,
233 overrideConfigFile: true,
234 overrideConfig: [
235 { ignores: [`**/dist/**`] },
236 {
237 files: [`**/*.ts`, `**/*.tsx`, `**/*.js`, `**/*.mjs`, `**/*.jsx`],
238 languageOptions: { parser: tsParser },
239 },
240 { linterOptions: { noInlineConfig: true } },
241 // `lint` passes only oracle files, chosen by `isOracleFile`, so the rules
242 // apply to every file that it passes.
243 {
244 ...oraclePlugin.configs.recommended,
245 files: [`**/*.ts`, `**/*.tsx`, `**/*.js`, `**/*.mjs`, `**/*.jsx`],
246 },
247 ],
248 })
249}
250
251/** Lints the oracle files among `files`. */
252async function lint(eslint, files) {
253 const lintable = []
254 for (const file of new Set(files)) {
255 if (!existsSync(file) || relative(root, file).startsWith(`..`)) continue
256 if (!isOracleFile(file)) continue
257 if (await eslint.isPathIgnored(file)) continue
258 lintable.push(file)
259 }
260 if (lintable.length === 0) return []
261 const results = await eslint.lintFiles(lintable)
262 // Keep oracle reports and files that cannot be parsed. This drops the
263 // notices that the ignored directives have no effect.
264 return results.map((result) => ({
265 ...result,
266 messages: result.messages.filter(
267 (message) => message.fatal || message.ruleId?.startsWith(`oracle/`),
268 ),
269 }))
270}
271
272function reportText(results) {
273 const lines = []
274 for (const result of results) {
275 for (const message of result.messages) {
276 if (message.severity < 2) continue
277 lines.push(
278 `${relative(root, result.filePath)}:${message.line}:${message.column} ` +
279 `${message.message} (${message.ruleId ?? `parse`})`,
280 )
281 }
282 }
283 return lines.join(`\n`)
284}
285
286/**
287 * Writes the report in the harness's format. A post-edit report reaches the
288 * model beside the tool result. A stop report makes the agent take another
289 * turn, once: when the harness says a stop hook already continued this turn,
290 * the report is left for the pre-commit hook and CI, so a report the agent
291 * cannot fix does not loop.
292 */
293function respond(report, input, scope) {
294 const { format, event } = options
295 if (!isHook) {
296 if (report !== ``) {
297 process.stderr.write(`${report}\n`)
298 process.exitCode = 1
299 }
300 return
301 }
302 const header =
303 scope === `edited`
304 ? `Oracle lint reports for the file you edited, and the oracle files that depend on it:`
305 : `Oracle lint reports in this branch's changed files. Fix them before finishing:`
306 const reason = `${header}\n${report}\nSee "How oracle work is scored" in AGENTS.md.`
307 if (report === `` || (event === `stop` && input.stop_hook_active === true)) {
308 // Codex requires JSON on stdout when a stop hook exits 0.
309 if (format === `codex` && event === `stop`) process.stdout.write(`{}\n`)
310 return
311 }
312 if (format === `claude` || format === `codex`) {
313 // Exit code 2 returns stderr to the model in both harnesses.
314 process.stderr.write(`${reason}\n`)
315 process.exitCode = 2
316 return
317 }
318 if (format === `gemini`) {
319 const output =
320 event === `stop`
321 ? { decision: `deny`, reason }
322 : {
323 hookSpecificOutput: {
324 hookEventName: `AfterTool`,
325 additionalContext: reason,
326 },
327 }
328 process.stdout.write(`${JSON.stringify(output)}\n`)
329 return
330 }
331 // Copilot treats a nonzero exit as a warning, so it needs JSON on stdout.
332 const output =
333 event === `stop`
334 ? { decision: `block`, reason }
335 : { additionalContext: reason }
336 process.stdout.write(`${JSON.stringify(output)}\n`)
337}
338
339/**
340 * The oracle files to lint: every oracle file, or those that the named, edited,
341 * or changed files affect.
342 */
343function selectFiles(input) {
344 if (options.all) return { scope: `all`, files: oracleFilesInTree() }
345 if (positionals.length > 0) {
346 return {
347 scope: `named`,
348 files: affectedOracleFiles(positionals.map((file) => resolve(file))),
349 }
350 }
351 const edited = options.event === `edit` && isHook ? editedFiles(input) : []
352 return edited.length > 0
353 ? { scope: `edited`, files: affectedOracleFiles(edited) }
354 : { scope: `changed`, files: affectedOracleFiles(changedFiles()) }
355}
356
357/**
358 * Lowered and removed run budgets, for a report over the branch's changed
359 * files. Either can be deliberate, so it is a report for review, not a lint
360 * error.
361 */
362function runBudgetReport(scope) {
363 if (scope !== `changed`) return ``
364 return loweredRunBudgetsBetween(root, mergeBase(root))
365 .map(
366 (budget) =>
367 `${budget.file}: ${describeLoweredRunBudget(budget)}. Restore it, or explain why in the pull request.`,
368 )
369 .join(`\n`)
370}
371
372if (delegate) {
373 // The session's checkout runs its own copy, which writes the response.
374 const result = spawnSync(
375 process.execPath,
376 [ownScript, ...process.argv.slice(2)],
377 { cwd: root, input: inputText, stdio: [`pipe`, `inherit`, `inherit`] },
378 )
379 process.exitCode = result.status ?? 1
380} else {
381 const { scope, files } = selectFiles(input)
382 const report = [
383 reportText(await lint(createLinter(), files)),
384 runBudgetReport(scope),
385 ]
386 .filter(Boolean)
387 .join(`\n`)
388 respond(report, input, scope)
389}