Skip to content
Myr

Hold AGENTS.md's principles table to the repo: a named enforcer that doesn't exist fails the tests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- packages/config/test/agents-table.test.ts reads the table under "## Principles", takes each "Held by" cell up to "No fence yet", and checks every backticked name before the cut: a path, glob or folder matches a file git tracks or would add; a root script is a key of package.json's scripts; a lint rule (plugin-prefixed or bare) is at error in oxlint.config.ts, extends and overrides included; a camelCase name is a diagnostic at error in tsconfig.base.json or a key in it; a PascalCase name is a refusal class in refusal.ts or an export of ids.ts. Anything else fails as unclassified. One test per principle row, named by its number, so a failure names the row. - The classifier is pure over a Repo value (test/agents-table.ts), so the self-tests run on a planted table and a planted repo: scripts/nope.ts, nope:check, fence/nope, globalNope and NopeRefusal each fail; each kind that exists passes; names after "No fence yet:" are never read; prose, the principle column and other tables are never read; \| stays in its cell. Red first by assertion on the old table (nine rows failed). - The rows need to be known while vitest collects, and @effect/vitest runs Effects only inside a test, so the helper runs readAgentsTable once with Effect.runPromise and the test file awaits it at top level. The fence rule against hand-run Effects scopes itself to *.test.* files; nothing was loosened (fallback in the issue's Comments). - AGENTS.md: the Day 0 paragraph is one line saying W1's fences exist. Every "Held by" now names only enforcers that exist (gen:check and scripts/gen.ts, imports:check and scripts/imports.ts, fence/no-module-level-mutable-state, fence/no-manual-effect-runtime-in-tests, debt, scripts/debt.ts and debt.baseline.json, vcs-policy and its three harness adapters, the protocol tests behind principle 3). The rest moved after "No fence yet:" with the wave that builds it: the web Env type test (W5 501), snapshot order (W3 315, W6 605), infra/deploy.ts and scripts/smoke.ts (W3 308), scripts/acceptance.ts (W7 714), lifecycle model tests (W2 209, 219). A preamble line states the convention: code-formatted names before the cut are enforcers, the rest plain text. - AGENTS.md gains a Commands section (verify, check, fix, typecheck, test, gen, gen:check, imports:check, debt and debt -- --lower, brand:check, bytes:check, lockfile:check, env:check, ops, the vendor script), the wrangler delete and cf --force line under Deploy and ops, and four Effect traps from the handoff. The Fence section points to Commands instead of a stale list of verify's steps. - ADR 0011: the hook policy is scripts/hooks/vcs-policy.ts, wired into Claude Code, Cursor and pi, with what it refuses; no lefthook and no CI workflow until the deadline, scripts/acceptance.ts standing in for CI on a cold install (spec D4). - ASSUMPTION: the issue's example waves 505 and 705 meant 501 and 714 (the W5 and W7 indexes assign those tests there). - Left open: principle 12's Effect.sleep lint has no wave yet, and the plan link stays for W7 704/707 (both in the issue's Comments).

authored by oscabriel · committed by oscabriel · parent 3b0df19 · Browse files · 4 files+613 added−18 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+613 added−18 removed

  • tests:+567 added−0 removed
  • other:+46 added−18 removed

4 files+613 added−18 removed

modified:docs/adr/0011-the-fence.md+3 added-2 removed
added:packages/config/test/agents-table.test.ts+136 added
1import { describe, expect, it } from "@effect/vitest";23import type { Repo } from "./agents-table.ts";4import {5 loadAgentsTable,6 missingEnforcers,7 principleRows,8} from "./agents-table.ts";910/** A repo with one enforcer of each kind, and nothing else. */11const plantedRepo: Repo = {12 configKeys: ["allowedUnstableApis"],13 diagnosticsAtError: ["globalDate"],14 files: [15 ".pi/extensions/vcs-policy/index.ts",16 "apps/cli/src/surfaces.ts",17 "debt.baseline.json",18 "scripts/gen.ts",19 ],20 ids: ["AskId"],21 lintPlugins: ["eslint", "fence"],22 lintRulesAtError: [23 "fence/no-module-level-mutable-state",24 "no-restricted-imports",25 ],26 refusals: ["StaleBase"],27 scripts: ["gen:check", "verify"],28};2930/** A file whose principles table has one row, principle 4, held by `cell`. */31const plantedTable = (cell: string) =>32 [33 "# A repo",34 "",35 "## Principles",36 "",37 "| # | Principle | Held by |",38 "| --- | --- | --- |",39 `| 4 | **One schema, many surfaces.** | ${cell} |`,40 "",41 "## Fence",42 "",43 ].join("\n");4445const audit = (cell: string) =>46 principleRows(plantedTable(cell)).flatMap((row) =>47 missingEnforcers(row, plantedRepo)48 );4950describe("the agents-table check, over a planted table", () => {51 it("fails each enforcer the repo lacks, naming its row", () => {52 expect(53 audit(54 "`scripts/nope.ts`; `nope:check`; `fence/nope`; `globalNope`; `NopeRefusal`"55 )56 ).toStrictEqual([57 "principle 4 names `scripts/nope.ts`, but the repo has no such file",58 "principle 4 names `nope:check`, but the repo has no such root package.json script",59 "principle 4 names `fence/nope`, but the repo has no such lint rule at error in oxlint.config.ts",60 "principle 4 names `globalNope`, but the repo has no such Effect diagnostic at error in tsconfig.base.json or key in tsconfig.base.json",61 "principle 4 names `NopeRefusal`, but the repo has no such refusal class in packages/protocol/src/refusal.ts or id exported from packages/protocol/src/ids.ts",62 ]);63 });6465 it("passes an enforcer of each kind that exists", () => {66 expect(67 audit(68 [69 "`scripts/gen.ts`, `apps/*/src/surfaces.ts`, `scripts/{debt,gen}.ts`, `.pi/extensions/vcs-policy/` and `debt.baseline.json`;",70 "`bun run verify` and `gen:check`;",71 "`fence/no-module-level-mutable-state`, `no-module-level-mutable-state` and `no-restricted-imports`;",72 "`globalDate` and `allowedUnstableApis`; `StaleBase` and `AskId`",73 ].join(" ")74 )75 ).toStrictEqual([]);76 });7778 it("reads nothing after No fence yet", () => {79 expect(80 audit(81 "`gen:check`. No fence yet: `scripts/nope.ts` and `nope:check` (W9 901)"82 )83 ).toStrictEqual([]);84 });8586 it("fails an enforcer it cannot classify", () => {87 expect(audit("`git push --force`")).toStrictEqual([88 "unclassified enforcer `git push --force` in principle 4; name a file, script, rule, diagnostic or tag",89 ]);90 });9192 it("reads only the Held by cells of the table under Principles", () => {93 const markdown = [94 "# A repo",95 "",96 "Prose names `scripts/prose.ts`.",97 "",98 "## Principles",99 "",100 "A preamble names `scripts/preamble.ts`.",101 "",102 "| # | Principle | Held by |",103 "| --- | --- | --- |",104 "| 1 | **A rule** named in `scripts/principle.ts`. | `verify` |",105 "| 2 | **Another rule.** | `a\\|b` and `gen:check` |",106 "",107 "## Fence",108 "",109 "| # | Rule | Held by |",110 "| --- | --- | --- |",111 "| 3 | Another table. | `scripts/elsewhere.ts` |",112 ].join("\n");113114 expect(principleRows(markdown)).toStrictEqual([115 { enforcers: ["verify"], principle: "1" },116 { enforcers: ["a|b", "gen:check"], principle: "2" },117 ]);118 });119});120121// Vitest registers every test before it runs one, and a test per row needs the122// rows then, so AGENTS.md and the repo are read once, here.123const { repo, rows } = await loadAgentsTable();124125describe("AGENTS.md's principles table", () => {126 it("is under ## Principles, with a Held by column", () => {127 expect(rows).not.toHaveLength(0);128 });129130 it.each(rows)(131 "principle $principle names only enforcers the repo has",132 (row) => {133 expect(missingEnforcers(row, repo)).toStrictEqual([]);134 }135 );136});
added:packages/config/test/agents-table.ts+431 added
1/**2 * The agents-table check's core (AGENTS.md principle 1): every enforcer the3 * principles table names under "Held by" must exist in the repo and be on.4 *5 * Only the table under `## Principles` is read, and in it only the "Held by"6 * cells, each up to "No fence yet". Each backticked enforcer there is7 * classified by its shape, then looked up:8 *9 * - a path, glob or folder (`scripts/gen.ts`, `docs/adr/*.md`,10 * `.pi/extensions/vcs-policy/`): a file git tracks, or a new one it doesn't11 * ignore, matches it;12 * - a root script (`gen:check`, `verify`, `bun run debt`): a key of the root13 * `package.json`'s `scripts`;14 * - a lint rule (`fence/no-x`, or bare `no-x`): set to error in15 * `oxlint.config.ts`, at its top level or in an override;16 * - an Effect diagnostic or a config key (camelCase): at error in17 * `tsconfig.base.json`'s `diagnosticSeverity`, or a key elsewhere in it;18 * - a refusal or an id (PascalCase): a refusal class in `refusal.ts`, or an19 * export of `ids.ts`, in `packages/protocol/src/`.20 *21 * Anything else is unclassified, and fails.22 */23import { NodeServices } from "@effect/platform-node";24import { Effect, FileSystem, Path, Schema } from "effect";25import { ChildProcess, ChildProcessSpawner } from "effect/process";26import type { DummyRule, OxlintConfig } from "oxlint";2728import oxlintConfig from "../../../oxlint.config.ts";2930/** What the repo holds that a "Held by" cell may name. */31export interface Repo {32 /** Every file git tracks or would add, relative to the repo root. */33 readonly files: readonly string[];34 /** The root `package.json`'s script names. */35 readonly scripts: readonly string[];36 /** The plugins oxlint runs, built in or from JavaScript. */37 readonly lintPlugins: readonly string[];38 readonly lintRulesAtError: readonly string[];39 readonly diagnosticsAtError: readonly string[];40 /** Every key in `tsconfig.base.json`, except diagnostics' names. */41 readonly configKeys: readonly string[];42 readonly refusals: readonly string[];43 readonly ids: readonly string[];44}4546/** One principle's row: its number and the enforcers it claims. */47export interface Row {48 readonly principle: string;49 readonly enforcers: readonly string[];50}5152type Kind =53 | "file"54 | "script"55 | "lint rule"56 | "diagnostic"57 | "config key"58 | "refusal"59 | "id";6061const CUT = "No fence yet";6263const HELD_BY = "Held by";6465const SECTION = /^## Principles\s*$/u;6667const HEADING = /^#{1,2} /u;6869const BACKTICKED = /`(?<enforcer>[^`]+)`/gu;7071const UNESCAPED_PIPE = /(?<!\\)\|/u;7273const BUN_RUN = /^bun run (?<script>\S+)/u;7475const PLUGIN_RULE = /^(?<plugin>[a-z][a-z0-9-]*)\/[a-z][a-z0-9-]*$/u;7677const GLOB = /[*?{]/u;7879const EXTENSION = /\.[a-z0-9]+$/u;8081const SCRIPT = /^[a-z][a-z0-9]*(?::[a-z0-9-]+)*$/u;8283const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/u;8485const CAMEL = /^[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+$/u;8687const PASCAL = /^[A-Z][A-Za-z0-9]*$/u;8889/** A table line's cells, trimmed, with `\|` read as a pipe inside a cell. */90const cellsOf = (line: string) =>91 line92 .trim()93 .replace(/^\|/u, "")94 .replace(/\|$/u, "")95 .split(UNESCAPED_PIPE)96 .map((cell) => cell.trim().replaceAll(String.raw`\|`, "|"));9798/** The backticked enforcers in a "Held by" cell, before "No fence yet". */99const enforcersIn = (cell: string) =>100 Array.from(101 (cell.split(CUT)[0] ?? "").matchAll(BACKTICKED),102 (match) => match.groups?.enforcer ?? ""103 );104105/**106 * Each row of the first table under `## Principles` whose header has a107 * "Held by" column. No such table: no rows.108 */109export const principleRows = (markdown: string): readonly Row[] => {110 const lines = markdown.split("\n");111 const start = lines.findIndex((line) => SECTION.test(line));112113 if (start === -1) {114 return [];115 }116117 const end = lines.findIndex(118 (line, index) => index > start && HEADING.test(line)119 );120121 const section = lines.slice(start + 1, end === -1 ? undefined : end);122123 const header = section.findIndex(124 (line) => line.startsWith("|") && cellsOf(line).includes(HELD_BY)125 );126127 if (header === -1) {128 return [];129 }130131 const columns = cellsOf(section[header] ?? "");132 const heldBy = columns.indexOf(HELD_BY);133 const numbered = columns.indexOf("#");134 const body = section.slice(header + 2);135 const last = body.findIndex((line) => !line.startsWith("|"));136137 return body138 .slice(0, last === -1 ? undefined : last)139 .map(cellsOf)140 .map((cells, index) => ({141 enforcers: enforcersIn(cells[heldBy] ?? ""),142 principle: cells[numbered] ?? String(index + 1),143 }));144};145146const GLOB_PART = /\{[^{}]*\}|\*\*\/|\*\*|\*|\?|[.+^$()|[\]{}\\]/gu;147148const WILDCARDS = new Map([149 ["*", "[^/]*"],150 ["**", ".*"],151 ["**/", "(?:.*/)?"],152 ["?", "[^/]"],153]);154155const escapeRegExp = (text: string) =>156 text.replaceAll(/[.+^$()|[\]{}\\*?]/gu, String.raw`\$&`);157158/** One part of a glob as a pattern: a wildcard, `{a,b}`, or one literal character. */159const globPart = (part: string) => {160 const wildcard = WILDCARDS.get(part);161162 if (wildcard !== undefined) {163 return wildcard;164 }165166 return part.length > 1167 ? `(?:${part.slice(1, -1).split(",").map(escapeRegExp).join("|")})`168 : escapeRegExp(part);169};170171/** `*` and `?` stay inside one folder, `**` crosses folders, `{a,b}` is either. */172const globPattern = (glob: string) =>173 new RegExp(`^${glob.replaceAll(GLOB_PART, globPart)}$`, "u");174175/** A path matches itself, a folder (with or without its slash) its files. */176const matchesFile = (token: string, files: readonly string[]) => {177 if (GLOB.test(token)) {178 const pattern = globPattern(token);179180 return files.some((file) => pattern.test(file));181 }182183 const folder = token.endsWith("/") ? token : `${token}/`;184185 return files.some((file) => file === token || file.startsWith(folder));186};187188/** `fence/no-x` matches itself; a bare `no-x` matches it under any plugin. */189const matchesRule = (token: string, rules: readonly string[]) =>190 rules.some((rule) => rule === token || rule.endsWith(`/${token}`));191192const holds: Readonly<Record<Kind, (token: string, repo: Repo) => boolean>> = {193 "config key": (token, repo) => repo.configKeys.includes(token),194 diagnostic: (token, repo) => repo.diagnosticsAtError.includes(token),195 file: (token, repo) => matchesFile(token, repo.files),196 id: (token, repo) => repo.ids.includes(token),197 "lint rule": (token, repo) => matchesRule(token, repo.lintRulesAtError),198 refusal: (token, repo) => repo.refusals.includes(token),199 script: (token, repo) =>200 repo.scripts.includes(BUN_RUN.exec(token)?.groups?.script ?? token),201};202203const described: Readonly<Record<Kind, string>> = {204 "config key": "key in tsconfig.base.json",205 diagnostic: "Effect diagnostic at error in tsconfig.base.json",206 file: "file",207 id: "id exported from packages/protocol/src/ids.ts",208 "lint rule": "lint rule at error in oxlint.config.ts",209 refusal: "refusal class in packages/protocol/src/refusal.ts",210 script: "root package.json script",211};212213/** What an enforcer could be, by its shape alone; none if it has no known shape. */214const kindsOf = (token: string, repo: Repo): readonly Kind[] => {215 if (BUN_RUN.test(token)) {216 return ["script"];217 }218219 if (/\s/u.test(token)) {220 return [];221 }222223 const plugin = PLUGIN_RULE.exec(token)?.groups?.plugin;224225 if (plugin !== undefined && repo.lintPlugins.includes(plugin)) {226 return ["lint rule"];227 }228229 if (230 token.includes("/") ||231 token.startsWith(".") ||232 GLOB.test(token) ||233 EXTENSION.test(token)234 ) {235 return ["file"];236 }237238 if (SCRIPT.test(token)) {239 return ["script"];240 }241242 if (KEBAB.test(token)) {243 return ["lint rule", "script"];244 }245246 if (CAMEL.test(token)) {247 return ["diagnostic", "config key"];248 }249250 return PASCAL.test(token) ? ["refusal", "id"] : [];251};252253/** One line for each enforcer in `row` that the repo doesn't hold. */254export const missingEnforcers = (row: Row, repo: Repo): readonly string[] =>255 row.enforcers.flatMap((token) => {256 const kinds = kindsOf(token, repo);257258 if (kinds.length === 0) {259 return [260 `unclassified enforcer \`${token}\` in principle ${row.principle}; name a file, script, rule, diagnostic or tag`,261 ];262 }263264 return kinds.some((kind) => holds[kind](token, repo))265 ? []266 : [267 `principle ${row.principle} names \`${token}\`, but the repo has no such ${kinds268 .map((kind) => described[kind])269 .join(" or ")}`,270 ];271 });272273const isError = (setting: DummyRule | undefined) => {274 const severity = Array.isArray(setting) ? setting[0] : setting;275276 return severity === "error" || severity === "deny" || severity === 2;277};278279/** A config, then each config it extends, innermost first. */280const layersOf = (config: OxlintConfig): readonly OxlintConfig[] => [281 ...(config.extends ?? []).flatMap(layersOf),282 config,283];284285/** The rules oxlint runs at error: top level (a later layer wins) or in an override. */286const rulesAtError = (config: OxlintConfig) => {287 const layers = layersOf(config);288289 const topLevel = new Map(290 layers.flatMap((layer) => Object.entries(layer.rules ?? {}))291 );292293 const overridden = layers.flatMap((layer) =>294 (layer.overrides ?? []).flatMap((override) =>295 Object.entries(override.rules ?? {})296 )297 );298299 return [...topLevel, ...overridden].flatMap(([rule, setting]) =>300 isError(setting) ? [rule] : []301 );302};303304/** Built-in plugins each layer turns on, and each JavaScript plugin's name. */305const pluginsOf = (config: OxlintConfig) =>306 layersOf(config).flatMap((layer) => [307 ...(layer.plugins ?? []),308 ...(layer.jsPlugins ?? []).map((plugin) =>309 Schema.is(Schema.String)(plugin) ? plugin : plugin.name310 ),311 ]);312313const isJsonArray = Schema.is(Schema.Array(Schema.Json));314315const isJsonObject = Schema.is(Schema.JsonObject);316317/** Every key in a JSON document, except the diagnostics' names. */318const keysOf = (json: Schema.Json): readonly string[] => {319 if (isJsonArray(json)) {320 return json.flatMap(keysOf);321 }322323 if (isJsonObject(json)) {324 return Object.entries(json).flatMap(([key, value]) => [325 key,326 ...(key === "diagnosticSeverity" ? [] : keysOf(value)),327 ]);328 }329330 return [];331};332333const RootPackage = Schema.Struct({334 scripts: Schema.Record(Schema.String, Schema.String),335});336337const TsconfigBase = Schema.Struct({338 compilerOptions: Schema.Struct({339 plugins: Schema.Array(340 Schema.Struct({341 diagnosticSeverity: Schema.optionalKey(342 Schema.Record(Schema.String, Schema.String)343 ),344 })345 ),346 }),347});348349const REFUSAL_CLASS =350 /\bclass\s+(?<name>[A-Z][A-Za-z0-9]*)\s+extends\s+Schema\.TaggedError\b/gu;351352const EXPORTED =353 /^export\s+(?:const|type|interface|class)\s+(?<name>[A-Z][A-Za-z0-9]*)/gmu;354355const namesIn = (source: string, pattern: RegExp) => [356 ...new Set(357 Array.from(source.matchAll(pattern), (match) => match.groups?.name ?? "")358 ),359];360361/** AGENTS.md's text, and what the repo holds, read from the repo root. */362export const readAgentsTable = Effect.gen(function* () {363 const fs = yield* FileSystem.FileSystem;364 const path = yield* Path.Path;365 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;366 // Vitest runs in the package's folder, two below the repo root.367 const root = path.resolve("..", "..");368 const read = (file: string) => fs.readFileString(path.join(root, file));369370 const lsFiles = (...args: readonly string[]) =>371 spawner.lines(372 ChildProcess.make("git", ["ls-files", ...args], { cwd: root })373 );374375 const [agents, rootPackage, tsconfigText, refusalSource, idsSource] =376 yield* Effect.all(377 [378 read("AGENTS.md"),379 read("package.json"),380 read("tsconfig.base.json"),381 read("packages/protocol/src/refusal.ts"),382 read("packages/protocol/src/ids.ts"),383 ],384 { concurrency: "unbounded" }385 );386387 const listed = yield* lsFiles(388 "--cached",389 "--others",390 "--exclude-standard",391 "--deduplicate"392 );393394 const deleted = new Set(yield* lsFiles("--deleted"));395396 const { scripts } = yield* Schema.decodeEffect(397 Schema.fromJsonString(RootPackage)398 )(rootPackage);399400 const tsconfig = yield* Schema.decodeEffect(401 Schema.fromJsonString(Schema.Json)402 )(tsconfigText);403404 const { compilerOptions } =405 yield* Schema.decodeUnknownEffect(TsconfigBase)(tsconfig);406407 const repo: Repo = {408 configKeys: [...new Set(keysOf(tsconfig))],409 diagnosticsAtError: compilerOptions.plugins.flatMap((plugin) =>410 Object.entries(plugin.diagnosticSeverity ?? {}).flatMap(411 ([diagnostic, severity]) => (severity === "error" ? [diagnostic] : [])412 )413 ),414 files: listed.filter((file) => file.length > 0 && !deleted.has(file)),415 ids: namesIn(idsSource, EXPORTED),416 lintPlugins: [...new Set(pluginsOf(oxlintConfig))],417 lintRulesAtError: [...new Set(rulesAtError(oxlintConfig))],418 refusals: namesIn(refusalSource, REFUSAL_CLASS),419 scripts: Object.keys(scripts),420 };421422 return { repo, rows: principleRows(agents) };423});424425/**426 * `readAgentsTable`, run once while vitest collects the tests: a test per427 * principle row needs the rows before any test runs, and `@effect/vitest`428 * runs Effects only inside a test.429 */430export const loadAgentsTable = () =>431 Effect.runPromise(readAgentsTable.pipe(Effect.provide(NodeServices.layer)));
modified:AGENTS.md+43 added-16 removed