Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

agent-lint-feedback.mjs

356 lines12.5 KB

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 */
36import { execFileSync } from 'node:child_process'
37import { existsSync, readFileSync } from 'node:fs'
38import { isAbsolute, join, relative, resolve, sep } from 'node:path'
39import { fileURLToPath } from 'node:url'
40import { parseArgs } from 'node:util'
41import tsParser from '@typescript-eslint/parser'
42import { ESLint } from 'eslint'
43import oraclePlugin from './eslint-plugin-oracle/index.js'
44import { resolveImportedTestModule } from './eslint-plugin-oracle/rules/no-unit-test.js'
45import {
46 describeLoweredRunBudget,
47 isOracleFile,
48 loweredRunBudgets,
49 mergeBase,
50} from './check-oracle-run-counts.mjs'
51​
52const root = fileURLToPath(new URL(`../`, import.meta.url))
53​
54const { values: options, positionals } = parseArgs({
55 options: {
56 format: { type: `string`, default: `text` },
57 event: { type: `string`, default: `edit` },
58 all: { type: `boolean`, default: false },
59 },
60 allowPositionals: true,
61})
62​
63const formats = new Set([`claude`, `codex`, `gemini`, `copilot`, `text`])
64if (!formats.has(options.format)) {
65 throw new Error(`--format must be one of ${[...formats].join(`, `)}`)
67if (![`edit`, `stop`].includes(options.event)) {
68 throw new Error(`--event must be edit or stop`)
70const isHook = options.format !== `text`
71​
72function git(...args) {
73 return execFileSync(`git`, args, { cwd: root, encoding: `utf8` }).trim()
75​
76function repositoryFiles(...outputs) {
77 return outputs
78 .flatMap((output) => output.split(`\n`))
79 .filter(Boolean)
80 .map((file) => join(root, file))
82​
83/**
84 * Every oracle file in the working tree, tracked or new. A new file that an
85 * agent has not added yet is linted like any other. Git leaves out ignored
86 * builds, and lists another checkout nested in this one, such as a worktree
87 * under `.worktrees/`, as a directory, which is not an oracle file.
88 */
89function oracleFilesInTree() {
90 return repositoryFiles(
91 git(`ls-files`, `--cached`, `--others`, `--exclude-standard`),
92 ).filter((file) => isOracleFile(file))
94​
95// A relative import or re-export. Reading too much is harmless: a specifier
96// that names no test module resolves to nothing.
97const relativeSpecifier =
98 /\b(?:from|import|require)\s*\(?\s*['"](\.{1,2}\/[^'"\n]*)['"]/g
99const dependencies = new Map()
100​
101/** The test modules that a file imports or re-exports, as the rule resolves them. */
102function testModuleDependencies(file) {
103 if (!dependencies.has(file)) {
104 const found = existsSync(file)
105 ? [...readFileSync(file, `utf8`).matchAll(relativeSpecifier)]
106 .map(([, specifier]) => resolveImportedTestModule(file, specifier))
107 .filter((dependency) => dependency !== undefined)
108 : []
109 dependencies.set(file, found)
110 }
111 return dependencies.get(file)
113​
114/** Whether an oracle file is edited, or reaches an edited file through test modules. */
115function reachesEdited(oracle, edited) {
116 const seen = new Set([oracle])
117 const pending = [oracle]
118 while (pending.length > 0) {
119 const current = pending.pop()
120 if (edited.has(current)) return true
121 for (const dependency of testModuleDependencies(current)) {
122 if (!seen.has(dependency)) {
123 seen.add(dependency)
124 pending.push(dependency)
125 }
126 }
127 }
128 return false
130​
131const pluginSources = join(root, `scripts`, `eslint-plugin-oracle`) + sep
132​
133/**
134 * The oracle files that a lint of `files` must cover. The rule reads relative
135 * imports of test modules, so an oracle file is covered when it is named, or
136 * when it reaches a named file through test modules. Production files select
137 * nothing, because the rule does not follow them. A change to the rule's own
138 * sources changes every oracle result, so it selects every oracle file.
139 */
140function affectedOracleFiles(files) {
141 const edited = new Set(files)
142 const oracles = new Set(
143 [...oracleFilesInTree(), ...files].filter((file) => isOracleFile(file)),
144 )
145 if ([...edited].some((file) => file.startsWith(pluginSources)))
146 return [...oracles]
147 return [...oracles].filter((oracle) => reachesEdited(oracle, edited))
149​
150/**
151 * Every file that the branch adds or changes, including uncommitted work.
152 * `mergeBase` fails without a main branch, instead of linting only the
153 * uncommitted work.
154 */
155function changedFiles() {
156 const base = mergeBase()
157 return repositoryFiles(
158 git(`diff`, `--name-only`, `--diff-filter=ACMR`, base),
159 git(`ls-files`, `--others`, `--exclude-standard`),
160 )
162​
163const pathKeys = /^(file_?path|filePath|path|absolute_path|target_file)$/i
164const patchHeader = /^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm
165​
166/**
167 * The files that a hook input names. Harnesses put the path in different
168 * fields, and Codex sends the text of an `apply_patch` call instead, so this
169 * searches the whole input for path fields and patch headers.
170 */
171function editedFiles(input) {
172 const base = typeof input.cwd === `string` ? input.cwd : root
173 const found = new Set()
174 const visit = (value, key) => {
175 if (typeof value === `string`) {
176 if (key !== undefined && pathKeys.test(key)) found.add(value)
177 for (const match of value.matchAll(patchHeader))
178 found.add(match[1].trim())
179 // Copilot's tool arguments can arrive as a JSON string.
180 if (/^\s*\{/.test(value)) {
181 try {
182 visit(JSON.parse(value))
183 } catch {
184 // Not JSON; already searched as text.
185 }
186 }
187 } else if (Array.isArray(value)) {
188 for (const item of value) visit(item)
189 } else if (value !== null && typeof value === `object`) {
190 for (const [childKey, child] of Object.entries(value))
191 visit(child, childKey)
192 }
193 }
194 visit(input.tool_input ?? input.toolArgs ?? input)
195 return [...found].map((file) =>
196 isAbsolute(file) ? file : resolve(base, file),
197 )
199​
200function readHookInput() {
201 if (!isHook) return {}
202 const text = readFileSync(0, `utf8`)
203 return text.trim() === `` ? {} : JSON.parse(text)
205​
206function createLinter() {
207 return new ESLint({
208 cwd: root,
209 overrideConfigFile: true,
210 overrideConfig: [
211 { ignores: [`**/dist/**`] },
212 {
213 files: [`**/*.ts`, `**/*.tsx`, `**/*.js`, `**/*.mjs`, `**/*.jsx`],
214 languageOptions: { parser: tsParser },
215 },
216 { linterOptions: { noInlineConfig: true } },
217 // `lint` passes only oracle files, chosen by `isOracleFile`, so the rules
218 // apply to every file that it passes.
219 {
220 ...oraclePlugin.configs.recommended,
221 files: [`**/*.ts`, `**/*.tsx`, `**/*.js`, `**/*.mjs`, `**/*.jsx`],
222 },
223 ],
224 })
226​
227/** Lints the oracle files among `files`. */
228async function lint(eslint, files) {
229 const lintable = []
230 for (const file of new Set(files)) {
231 if (!existsSync(file) || relative(root, file).startsWith(`..`)) continue
232 if (!isOracleFile(file)) continue
233 if (await eslint.isPathIgnored(file)) continue
234 lintable.push(file)
235 }
236 if (lintable.length === 0) return []
237 const results = await eslint.lintFiles(lintable)
238 // Keep oracle reports and files that cannot be parsed. This drops the
239 // notices that the ignored directives have no effect.
240 return results.map((result) => ({
241 ...result,
242 messages: result.messages.filter(
243 (message) => message.fatal || message.ruleId?.startsWith(`oracle/`),
244 ),
245 }))
247​
248function reportText(results) {
249 const lines = []
250 for (const result of results) {
251 for (const message of result.messages) {
252 if (message.severity < 2) continue
253 lines.push(
254 `${relative(root, result.filePath)}:${message.line}:${message.column} ` +
255 `${message.message} (${message.ruleId ?? `parse`})`,
256 )
257 }
258 }
259 return lines.join(`\n`)
261​
262/**
263 * Writes the report in the harness's format. A post-edit report reaches the
264 * model beside the tool result. A stop report makes the agent take another
265 * turn, once: when the harness says a stop hook already continued this turn,
266 * the report is left for the pre-commit hook and CI, so a report the agent
267 * cannot fix does not loop.
268 */
269function respond(report, input, scope) {
270 const { format, event } = options
271 if (!isHook) {
272 if (report !== ``) {
273 process.stderr.write(`${report}\n`)
274 process.exitCode = 1
275 }
276 return
277 }
278 const header =
279 scope === `edited`
280 ? `Oracle lint reports for the file you edited, and the oracle files that depend on it:`
281 : `Oracle lint reports in this branch's changed files. Fix them before finishing:`
282 const reason = `${header}\n${report}\nSee "How oracle work is scored" in AGENTS.md.`
283 if (report === `` || (event === `stop` && input.stop_hook_active === true)) {
284 // Codex requires JSON on stdout when a stop hook exits 0.
285 if (format === `codex` && event === `stop`) process.stdout.write(`{}\n`)
286 return
287 }
288 if (format === `claude` || format === `codex`) {
289 // Exit code 2 returns stderr to the model in both harnesses.
290 process.stderr.write(`${reason}\n`)
291 process.exitCode = 2
292 return
293 }
294 if (format === `gemini`) {
295 const output =
296 event === `stop`
297 ? { decision: `deny`, reason }
298 : {
299 hookSpecificOutput: {
300 hookEventName: `AfterTool`,
301 additionalContext: reason,
302 },
303 }
304 process.stdout.write(`${JSON.stringify(output)}\n`)
305 return
306 }
307 // Copilot treats a nonzero exit as a warning, so it needs JSON on stdout.
308 const output =
309 event === `stop`
310 ? { decision: `block`, reason }
311 : { additionalContext: reason }
312 process.stdout.write(`${JSON.stringify(output)}\n`)
314​
315/**
316 * The oracle files to lint: every oracle file, or those that the named, edited,
317 * or changed files affect.
318 */
319function selectFiles(input) {
320 if (options.all) return { scope: `all`, files: oracleFilesInTree() }
321 if (positionals.length > 0) {
322 return {
323 scope: `named`,
324 files: affectedOracleFiles(positionals.map((file) => resolve(file))),
325 }
326 }
327 const edited = options.event === `edit` && isHook ? editedFiles(input) : []
328 return edited.length > 0
329 ? { scope: `edited`, files: affectedOracleFiles(edited) }
330 : { scope: `changed`, files: affectedOracleFiles(changedFiles()) }
332​
333/**
334 * Lowered and removed run budgets, for a report over the branch's changed
335 * files. Either can be deliberate, so it is a report for review, not a lint
336 * error.
337 */
338function runBudgetReport(scope) {
339 if (scope !== `changed`) return ``
340 return loweredRunBudgets()
341 .map(
342 (budget) =>
343 `${budget.file}: ${describeLoweredRunBudget(budget)}. Restore it, or explain why in the pull request.`,
344 )
345 .join(`\n`)
347​
348const input = readHookInput()
349const { scope, files } = selectFiles(input)
350const report = [
351 reportText(await lint(createLinter(), files)),
352 runBudgetReport(scope),
354 .filter(Boolean)
355 .join(`\n`)
356respond(report, input, scope)