Merge build/108-agents-table: AGENTS.md names only fences that exist, held by a table test
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 3b0df19, 44d40e8 · Browse files · 4 files·+765 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+765 added−18 removed
- tests:+719 added−0 removed
- other:+46 added−18 removed
Provenance
- Commit
c234e81- Tree
e28e58b- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
3b0df19- Parent 2
44d40e8
4 files changed+765 added−18 removed
modified:docs/adr/0011-the-fence.md+3 added-2 removed
6 unmodified lines789101111121314151617171819206 unmodified linesEach rule this repo keeps is held by the strongest enforcer available. First, make the mistake unrepresentable in types; then catch it with lint; then with a test; prose is the last rung. Git hooks are early feedback only; `bun run verify` and CI are the authority. The repo is built fast and mostly by agents, and a rule nothing checks drifts under that load. The fence also dogfoods the product: its judge closure, weakening and ratchet apply to this repo first.
## Considered Options
- **The full test suite in pre-commit.** Too slow for an agent sprint. Hooks run lint, format check and typecheck; tests run in `verify` and CI.- **The full test suite in pre-commit.** Too slow for an agent sprint. Git hooks, when they come, run lint, format check and typecheck; tests run in `verify` and CI.- **A `no-comments` lint rule.** Rejected: agents need room for workaround notes.
## Consequences
- Every escape (`oxlint-disable`, `@effect-diagnostics`, `@ts-expect-error`) carries a reason after ` -- `. `scripts/debt.ts` counts escapes against `debt.baseline.json` in `verify`, and the count rises only with the maintainer's sign-off.- One hook policy refuses the usual ways around hooks: `--no-verify`, `commit -n`, `core.hooksPath` overrides, `LEFTHOOK=0` and `lefthook uninstall`. It is wired into each agent harness the repo uses.- One hook policy (`scripts/hooks/vcs-policy.ts`), wired into Claude Code, Cursor and pi, refuses the usual ways around hooks (`--no-verify`, `commit -n`, `core.hooksPath` overrides, `LEFTHOOK=0` and `lefthook uninstall`), `git push`, `wrangler delete`, cf `delete` and `revoke`, cf's project commands and reads of the closed `.env` files.- Until the deadline there is no lefthook and no CI workflow: the harness hooks give the early feedback, `bun run verify` is the authority, and `scripts/acceptance.ts` stands in for CI by running `verify` on a cold install.- A deploy is never a way around a red gate: `infra/deploy.ts` refuses without an explicit stage and runs smoke tests after.- `AGENTS.md` lists each principle with the check that holds it. Where the check and the prose disagree, the check wins.added:packages/config/test/agents-table.test.ts+248 added
1+import { NodeServices } from "@effect/platform-node";2+import { describe, expect, it } from "@effect/vitest";3+import { Effect } from "effect";4+5+import type { Repo, Sources } from "./agents-table.ts";6+import {7+ missingEnforcers,8+ principleRows,9+ readAgentsTable,10+ repoOf,11+} from "./agents-table.ts";12+13+/** A repo with one enforcer of each kind, and nothing else. */14+const plantedRepo: Repo = {15+ configKeys: ["allowedUnstableApis"],16+ diagnosticsAtError: ["globalDate"],17+ files: [18+ ".pi/extensions/vcs-policy/index.ts",19+ "apps/cli/src/surfaces.ts",20+ "debt.baseline.json",21+ "scripts/gen.ts",22+ ],23+ ids: ["AskId"],24+ lintPlugins: ["eslint", "fence"],25+ lintRulesAtError: [26+ "fence/no-module-level-mutable-state",27+ "no-restricted-imports",28+ ],29+ refusals: ["StaleBase"],30+ scripts: ["gen:check", "verify"],31+};32+33+/** A file whose principles table has one row, principle 4, held by `cell`. */34+const plantedTable = (cell: string) =>35+ [36+ "# A repo",37+ "",38+ "## Principles",39+ "",40+ "| # | Principle | Held by |",41+ "| --- | --- | --- |",42+ `| 4 | **One schema, many surfaces.** | ${cell} |`,43+ "",44+ "## Fence",45+ "",46+ ].join("\n");47+48+const audit = (cell: string) =>49+ principleRows(plantedTable(cell)).flatMap((row) =>50+ missingEnforcers(row, plantedRepo)51+ );52+53+describe("the agents-table check, over a planted table", () => {54+ it("fails each enforcer the repo lacks, naming its row", () => {55+ expect(56+ audit(57+ "`scripts/nope.ts`; `nope:check`; `fence/nope`; `globalNope`; `NopeRefusal`"58+ )59+ ).toStrictEqual([60+ "principle 4 names `scripts/nope.ts`, but the repo has no such file",61+ "principle 4 names `nope:check`, but the repo has no such root package.json script",62+ "principle 4 names `fence/nope`, but the repo has no such lint rule at error in oxlint.config.ts",63+ "principle 4 names `globalNope`, but the repo has no such Effect diagnostic at error in tsconfig.base.json or key in tsconfig.base.json",64+ "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",65+ ]);66+ });67+68+ it("passes an enforcer of each kind that exists", () => {69+ expect(70+ audit(71+ [72+ "`scripts/gen.ts`, `apps/*/src/surfaces.ts`, `scripts/{debt,gen}.ts`, `.pi/extensions/vcs-policy/` and `debt.baseline.json`;",73+ "`bun run verify` and `gen:check`;",74+ "`fence/no-module-level-mutable-state`, `no-module-level-mutable-state` and `no-restricted-imports`;",75+ "`globalDate` and `allowedUnstableApis`; `StaleBase` and `AskId`",76+ ].join(" ")77+ )78+ ).toStrictEqual([]);79+ });80+81+ it("reads nothing after No fence yet", () => {82+ expect(83+ audit(84+ "`gen:check`. No fence yet: `scripts/nope.ts` and `nope:check` (W9 901)"85+ )86+ ).toStrictEqual([]);87+ });88+89+ it("fails a row that names no enforcer and says no fence is coming", () => {90+ expect(audit("The union test and an MCP tools/call test")).toStrictEqual([91+ "principle 4 names no enforcer; name one, or what will hold it after No fence yet:",92+ ]);93+ });94+95+ it("passes a row whose every enforcer is still to come", () => {96+ expect(audit("No fence yet: the union test (W9 901)")).toStrictEqual([]);97+ });98+99+ it("fails an enforcer it cannot classify", () => {100+ expect(audit("`git push --force`")).toStrictEqual([101+ "unclassified enforcer `git push --force` in principle 4; name a file, script, rule, diagnostic or tag",102+ ]);103+ });104+105+ it("reads only the Held by cells of the table under Principles", () => {106+ const markdown = [107+ "# A repo",108+ "",109+ "Prose names `scripts/prose.ts`.",110+ "",111+ "## Principles",112+ "",113+ "A preamble names `scripts/preamble.ts`.",114+ "",115+ "| # | Principle | Held by |",116+ "| --- | --- | --- |",117+ "| 1 | **A rule** named in `scripts/principle.ts`. | `verify` |",118+ "| 2 | **Another rule.** | `a\\|b` and `gen:check` |",119+ "",120+ "## Fence",121+ "",122+ "| # | Rule | Held by |",123+ "| --- | --- | --- |",124+ "| 3 | Another table. | `scripts/elsewhere.ts` |",125+ ].join("\n");126+127+ expect(principleRows(markdown)).toStrictEqual([128+ { enforcers: ["verify"], principle: "1", waiting: false },129+ { enforcers: ["a|b", "gen:check"], principle: "2", waiting: false },130+ ]);131+ });132+});133+134+/**135+ * Sources shaped like the repo's: a lint preset our config extends and136+ * overrides, and a test-file override that turns on its own plugin.137+ */138+const plantedSources: Sources = {139+ files: [],140+ idsSource: [141+ 'export const AskId = Schema.String.pipe(Schema.brand("AskId"));',142+ "export type AskId = typeof AskId.Type;",143+ ].join("\n"),144+ oxlint: {145+ extends: [146+ {147+ plugins: ["eslint", "typescript"],148+ rules: { "no-alert": "error", "no-console": "error" },149+ },150+ ],151+ overrides: [152+ {153+ files: ["**/*.test.ts"],154+ plugins: ["vitest"],155+ rules: { "vitest/no-disabled-tests": ["error"] },156+ },157+ ],158+ rules: { "no-console": "off", "typescript/no-explicit-any": "warn" },159+ },160+ refusalSource: [161+ 'export class StaleBase extends Schema.TaggedError<StaleBase>()("StaleBase", {}) {}',162+ "export const Refusal = Schema.Union([StaleBase]);",163+ ].join("\n"),164+ rootPackage: JSON.stringify({ scripts: { verify: "bun run check" } }),165+ tsconfig: JSON.stringify({166+ compilerOptions: {167+ plugins: [168+ {169+ allowedUnstableApis: ["effect/rpc"],170+ diagnosticSeverity: { globalDate: "error", globalRandom: "off" },171+ name: "@effect/language-service",172+ },173+ ],174+ },175+ }),176+};177+178+const auditSources = (cell: string) =>179+ Effect.map(repoOf(plantedSources), (repo) =>180+ principleRows(plantedTable(cell)).flatMap((row) =>181+ missingEnforcers(row, repo)182+ )183+ );184+185+describe("what the repo holds, read from planted sources", () => {186+ it.effect(187+ "counts a lint rule as on only at error after every layer, overrides included",188+ () =>189+ Effect.gen(function* () {190+ expect(191+ yield* auditSources(192+ "`no-alert`, `no-console`, `typescript/no-explicit-any` and `vitest/no-disabled-tests`"193+ )194+ ).toStrictEqual([195+ "principle 4 names `no-console`, but the repo has no such lint rule at error in oxlint.config.ts or root package.json script",196+ "principle 4 names `typescript/no-explicit-any`, but the repo has no such lint rule at error in oxlint.config.ts",197+ ]);198+ })199+ );200+201+ it.effect(202+ "counts a diagnostic as on only at error, and never as a config key",203+ () =>204+ Effect.gen(function* () {205+ expect(206+ yield* auditSources(207+ "`globalDate`, `globalRandom` and `allowedUnstableApis`"208+ )209+ ).toStrictEqual([210+ "principle 4 names `globalRandom`, but the repo has no such Effect diagnostic at error in tsconfig.base.json or key in tsconfig.base.json",211+ ]);212+ })213+ );214+215+ it.effect(216+ "reads root scripts, refusal classes and exported ids, and nothing else",217+ () =>218+ Effect.gen(function* () {219+ expect(220+ yield* auditSources("`verify`, `StaleBase`, `AskId` and `Refusal`")221+ ).toStrictEqual([222+ "principle 4 names `Refusal`, but the repo has no such refusal class in packages/protocol/src/refusal.ts or id exported from packages/protocol/src/ids.ts",223+ ]);224+ })225+ );226+});227+228+// The rows are known only once a test has read AGENTS.md, so one test checks229+// every row; each line it reports names its principle.230+describe("AGENTS.md's principles table", () => {231+ it.live("is under ## Principles, with a Held by column", () =>232+ Effect.gen(function* () {233+ const { rows } = yield* readAgentsTable;234+235+ expect(rows).not.toHaveLength(0);236+ }).pipe(Effect.provide(NodeServices.layer))237+ );238+239+ it.live("names, in every row, only enforcers the repo has", () =>240+ Effect.gen(function* () {241+ const { repo, rows } = yield* readAgentsTable;242+243+ expect(rows.flatMap((row) => missingEnforcers(row, repo))).toStrictEqual(244+ []245+ );246+ }).pipe(Effect.provide(NodeServices.layer))247+ );248+});added:packages/config/test/agents-table.ts+471 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. So does a row that names no22+ * enforcer and says nothing after "No fence yet": prose alone holds nothing.23+ */24+import { Effect, FileSystem, Path, Schema } from "effect";25+import { ChildProcess, ChildProcessSpawner } from "effect/process";26+import type { DummyRule, OxlintConfig } from "oxlint";27+28+import oxlintConfig from "../../../oxlint.config.ts";29+30+/** What the repo holds that a "Held by" cell may name. */31+export 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+}45+46+/** One principle's row: its number and the enforcers it claims. */47+export interface Row {48+ readonly principle: string;49+ readonly enforcers: readonly string[];50+ /** The cell says, after "No fence yet", what will hold the rest. */51+ readonly waiting: boolean;52+}53+54+type Kind =55+ | "file"56+ | "script"57+ | "lint rule"58+ | "diagnostic"59+ | "config key"60+ | "refusal"61+ | "id";62+63+const CUT = "No fence yet";64+65+const HELD_BY = "Held by";66+67+const SECTION = /^## Principles\s*$/u;68+69+const HEADING = /^#{1,2} /u;70+71+const BACKTICKED = /`(?<enforcer>[^`]+)`/gu;72+73+const UNESCAPED_PIPE = /(?<!\\)\|/u;74+75+const BUN_RUN = /^bun run (?<script>\S+)/u;76+77+const PLUGIN_RULE = /^(?<plugin>[a-z][a-z0-9-]*)\/[a-z][a-z0-9-]*$/u;78+79+const GLOB = /[*?{]/u;80+81+const EXTENSION = /\.[a-z0-9]+$/u;82+83+const SCRIPT = /^[a-z][a-z0-9]*(?::[a-z0-9-]+)*$/u;84+85+const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/u;86+87+const CAMEL = /^[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+$/u;88+89+const PASCAL = /^[A-Z][A-Za-z0-9]*$/u;90+91+/** A table line's cells, trimmed, with `\|` read as a pipe inside a cell. */92+const cellsOf = (line: string) =>93+ line94+ .trim()95+ .replace(/^\|/u, "")96+ .replace(/\|$/u, "")97+ .split(UNESCAPED_PIPE)98+ .map((cell) => cell.trim().replaceAll(String.raw`\|`, "|"));99+100+/** The backticked enforcers in a "Held by" cell, before "No fence yet". */101+const enforcersIn = (cell: string) =>102+ Array.from(103+ (cell.split(CUT)[0] ?? "").matchAll(BACKTICKED),104+ (match) => match.groups?.enforcer ?? ""105+ );106+107+/**108+ * Each row of the first table under `## Principles` whose header has a109+ * "Held by" column. No such table: no rows.110+ */111+export const principleRows = (markdown: string): readonly Row[] => {112+ const lines = markdown.split("\n");113+ const start = lines.findIndex((line) => SECTION.test(line));114+115+ if (start === -1) {116+ return [];117+ }118+119+ const end = lines.findIndex(120+ (line, index) => index > start && HEADING.test(line)121+ );122+123+ const section = lines.slice(start + 1, end === -1 ? undefined : end);124+125+ const header = section.findIndex(126+ (line) => line.startsWith("|") && cellsOf(line).includes(HELD_BY)127+ );128+129+ if (header === -1) {130+ return [];131+ }132+133+ const columns = cellsOf(section[header] ?? "");134+ const heldBy = columns.indexOf(HELD_BY);135+ const numbered = columns.indexOf("#");136+ const body = section.slice(header + 2);137+ const last = body.findIndex((line) => !line.startsWith("|"));138+139+ return body140+ .slice(0, last === -1 ? undefined : last)141+ .map(cellsOf)142+ .map((cells, index) => ({143+ enforcers: enforcersIn(cells[heldBy] ?? ""),144+ principle: cells[numbered] ?? String(index + 1),145+ waiting: (cells[heldBy] ?? "").includes(CUT),146+ }));147+};148+149+const GLOB_PART = /\{[^{}]*\}|\*\*\/|\*\*|\*|\?|[.+^$()|[\]{}\\]/gu;150+151+const WILDCARDS = new Map([152+ ["*", "[^/]*"],153+ ["**", ".*"],154+ ["**/", "(?:.*/)?"],155+ ["?", "[^/]"],156+]);157+158+const escapeRegExp = (text: string) =>159+ text.replaceAll(/[.+^$()|[\]{}\\*?]/gu, String.raw`\$&`);160+161+/** One part of a glob as a pattern: a wildcard, `{a,b}`, or one literal character. */162+const globPart = (part: string) => {163+ const wildcard = WILDCARDS.get(part);164+165+ if (wildcard !== undefined) {166+ return wildcard;167+ }168+169+ return part.length > 1170+ ? `(?:${part.slice(1, -1).split(",").map(escapeRegExp).join("|")})`171+ : escapeRegExp(part);172+};173+174+/** `*` and `?` stay inside one folder, `**` crosses folders, `{a,b}` is either. */175+const globPattern = (glob: string) =>176+ new RegExp(`^${glob.replaceAll(GLOB_PART, globPart)}$`, "u");177+178+/** A path matches itself, a folder (with or without its slash) its files. */179+const matchesFile = (token: string, files: readonly string[]) => {180+ if (GLOB.test(token)) {181+ const pattern = globPattern(token);182+183+ return files.some((file) => pattern.test(file));184+ }185+186+ const folder = token.endsWith("/") ? token : `${token}/`;187+188+ return files.some((file) => file === token || file.startsWith(folder));189+};190+191+/** `fence/no-x` matches itself; a bare `no-x` matches it under any plugin. */192+const matchesRule = (token: string, rules: readonly string[]) =>193+ rules.some((rule) => rule === token || rule.endsWith(`/${token}`));194+195+const holds: Readonly<Record<Kind, (token: string, repo: Repo) => boolean>> = {196+ "config key": (token, repo) => repo.configKeys.includes(token),197+ diagnostic: (token, repo) => repo.diagnosticsAtError.includes(token),198+ file: (token, repo) => matchesFile(token, repo.files),199+ id: (token, repo) => repo.ids.includes(token),200+ "lint rule": (token, repo) => matchesRule(token, repo.lintRulesAtError),201+ refusal: (token, repo) => repo.refusals.includes(token),202+ script: (token, repo) =>203+ repo.scripts.includes(BUN_RUN.exec(token)?.groups?.script ?? token),204+};205+206+const described: Readonly<Record<Kind, string>> = {207+ "config key": "key in tsconfig.base.json",208+ diagnostic: "Effect diagnostic at error in tsconfig.base.json",209+ file: "file",210+ id: "id exported from packages/protocol/src/ids.ts",211+ "lint rule": "lint rule at error in oxlint.config.ts",212+ refusal: "refusal class in packages/protocol/src/refusal.ts",213+ script: "root package.json script",214+};215+216+/** What an enforcer could be, by its shape alone; none if it has no known shape. */217+const kindsOf = (token: string, repo: Repo): readonly Kind[] => {218+ if (BUN_RUN.test(token)) {219+ return ["script"];220+ }221+222+ if (/\s/u.test(token)) {223+ return [];224+ }225+226+ const plugin = PLUGIN_RULE.exec(token)?.groups?.plugin;227+228+ if (plugin !== undefined && repo.lintPlugins.includes(plugin)) {229+ return ["lint rule"];230+ }231+232+ if (233+ token.includes("/") ||234+ token.startsWith(".") ||235+ GLOB.test(token) ||236+ EXTENSION.test(token)237+ ) {238+ return ["file"];239+ }240+241+ if (SCRIPT.test(token)) {242+ return ["script"];243+ }244+245+ if (KEBAB.test(token)) {246+ return ["lint rule", "script"];247+ }248+249+ if (CAMEL.test(token)) {250+ return ["diagnostic", "config key"];251+ }252+253+ return PASCAL.test(token) ? ["refusal", "id"] : [];254+};255+256+/**257+ * One line for each enforcer in `row` that the repo doesn't hold, or one line258+ * when the row names no enforcer and no fence still to come.259+ */260+export const missingEnforcers = (row: Row, repo: Repo): readonly string[] => {261+ if (row.enforcers.length === 0 && !row.waiting) {262+ return [263+ `principle ${row.principle} names no enforcer; name one, or what will hold it after ${CUT}:`,264+ ];265+ }266+267+ return row.enforcers.flatMap((token) => {268+ const kinds = kindsOf(token, repo);269+270+ if (kinds.length === 0) {271+ return [272+ `unclassified enforcer \`${token}\` in principle ${row.principle}; name a file, script, rule, diagnostic or tag`,273+ ];274+ }275+276+ return kinds.some((kind) => holds[kind](token, repo))277+ ? []278+ : [279+ `principle ${row.principle} names \`${token}\`, but the repo has no such ${kinds280+ .map((kind) => described[kind])281+ .join(" or ")}`,282+ ];283+ });284+};285+286+const isError = (setting: DummyRule | undefined) => {287+ const severity = Array.isArray(setting) ? setting[0] : setting;288+289+ return severity === "error" || severity === "deny" || severity === 2;290+};291+292+/** A config, then each config it extends, innermost first. */293+const layersOf = (config: OxlintConfig): readonly OxlintConfig[] => [294+ ...(config.extends ?? []).flatMap(layersOf),295+ config,296+];297+298+/** The rules oxlint runs at error: top level (a later layer wins) or in an override. */299+const rulesAtError = (config: OxlintConfig) => {300+ const layers = layersOf(config);301+302+ const topLevel = new Map(303+ layers.flatMap((layer) => Object.entries(layer.rules ?? {}))304+ );305+306+ const overridden = layers.flatMap((layer) =>307+ (layer.overrides ?? []).flatMap((override) =>308+ Object.entries(override.rules ?? {})309+ )310+ );311+312+ return [...topLevel, ...overridden].flatMap(([rule, setting]) =>313+ isError(setting) ? [rule] : []314+ );315+};316+317+/**318+ * Built-in plugins each layer or override turns on, and each JavaScript319+ * plugin's name: the vitest plugin, for one, is on only for test files.320+ */321+const pluginsOf = (config: OxlintConfig) =>322+ layersOf(config)323+ .flatMap((layer) => [layer, ...(layer.overrides ?? [])])324+ .flatMap((scope) => [325+ ...(scope.plugins ?? []),326+ ...(scope.jsPlugins ?? []).map((plugin) =>327+ Schema.is(Schema.String)(plugin) ? plugin : plugin.name328+ ),329+ ]);330+331+const isJsonArray = Schema.is(Schema.Array(Schema.Json));332+333+const isJsonObject = Schema.is(Schema.JsonObject);334+335+/** Every key in a JSON document, except the diagnostics' names. */336+const keysOf = (json: Schema.Json): readonly string[] => {337+ if (isJsonArray(json)) {338+ return json.flatMap(keysOf);339+ }340+341+ if (isJsonObject(json)) {342+ return Object.entries(json).flatMap(([key, value]) => [343+ key,344+ ...(key === "diagnosticSeverity" ? [] : keysOf(value)),345+ ]);346+ }347+348+ return [];349+};350+351+const RootPackage = Schema.Struct({352+ scripts: Schema.Record(Schema.String, Schema.String),353+});354+355+const TsconfigBase = Schema.Struct({356+ compilerOptions: Schema.Struct({357+ plugins: Schema.Array(358+ Schema.Struct({359+ diagnosticSeverity: Schema.optionalKey(360+ Schema.Record(Schema.String, Schema.String)361+ ),362+ })363+ ),364+ }),365+});366+367+const REFUSAL_CLASS =368+ /\bclass\s+(?<name>[A-Z][A-Za-z0-9]*)\s+extends\s+Schema\.TaggedError\b/gu;369+370+const EXPORTED =371+ /^export\s+(?:const|type|interface|class)\s+(?<name>[A-Z][A-Za-z0-9]*)/gmu;372+373+const namesIn = (source: string, pattern: RegExp) => [374+ ...new Set(375+ Array.from(source.matchAll(pattern), (match) => match.groups?.name ?? "")376+ ),377+];378+379+/** The texts and config a "Held by" cell is checked against. */380+export interface Sources {381+ /** Every file git tracks or would add, relative to the repo root. */382+ readonly files: readonly string[];383+ /** The root `package.json`. */384+ readonly rootPackage: string;385+ readonly oxlint: OxlintConfig;386+ /** `tsconfig.base.json`. */387+ readonly tsconfig: string;388+ /** `packages/protocol/src/refusal.ts`. */389+ readonly refusalSource: string;390+ /** `packages/protocol/src/ids.ts`. */391+ readonly idsSource: string;392+}393+394+/** What the repo holds, out of its sources. */395+export const repoOf = (sources: Sources) =>396+ Effect.gen(function* () {397+ const { scripts } = yield* Schema.decodeEffect(398+ Schema.fromJsonString(RootPackage)399+ )(sources.rootPackage);400+401+ const tsconfig = yield* Schema.decodeEffect(402+ Schema.fromJsonString(Schema.Json)403+ )(sources.tsconfig);404+405+ const { compilerOptions } =406+ yield* Schema.decodeUnknownEffect(TsconfigBase)(tsconfig);407+408+ const repo: Repo = {409+ configKeys: [...new Set(keysOf(tsconfig))],410+ diagnosticsAtError: compilerOptions.plugins.flatMap((plugin) =>411+ Object.entries(plugin.diagnosticSeverity ?? {}).flatMap(412+ ([diagnostic, severity]) => (severity === "error" ? [diagnostic] : [])413+ )414+ ),415+ files: sources.files,416+ ids: namesIn(sources.idsSource, EXPORTED),417+ lintPlugins: [...new Set(pluginsOf(sources.oxlint))],418+ lintRulesAtError: [...new Set(rulesAtError(sources.oxlint))],419+ refusals: namesIn(sources.refusalSource, REFUSAL_CLASS),420+ scripts: Object.keys(scripts),421+ };422+423+ return repo;424+ });425+426+/** AGENTS.md's principle rows, and what the repo holds, read from the repo root. */427+export const readAgentsTable = Effect.gen(function* () {428+ const fs = yield* FileSystem.FileSystem;429+ const path = yield* Path.Path;430+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;431+ // Vitest runs in the package's folder, two below the repo root.432+ const root = path.resolve("..", "..");433+ const read = (file: string) => fs.readFileString(path.join(root, file));434+435+ const lsFiles = (...args: readonly string[]) =>436+ spawner.lines(437+ ChildProcess.make("git", ["ls-files", ...args], { cwd: root })438+ );439+440+ const [agents, rootPackage, tsconfig, refusalSource, idsSource] =441+ yield* Effect.all(442+ [443+ read("AGENTS.md"),444+ read("package.json"),445+ read("tsconfig.base.json"),446+ read("packages/protocol/src/refusal.ts"),447+ read("packages/protocol/src/ids.ts"),448+ ],449+ { concurrency: "unbounded" }450+ );451+452+ const listed = yield* lsFiles(453+ "--cached",454+ "--others",455+ "--exclude-standard",456+ "--deduplicate"457+ );458+459+ const deleted = new Set(yield* lsFiles("--deleted"));460+461+ const repo = yield* repoOf({462+ files: listed.filter((file) => file.length > 0 && !deleted.has(file)),463+ idsSource,464+ oxlint: oxlintConfig,465+ refusalSource,466+ rootPackage,467+ tsconfig,468+ });469+470+ return { repo, rows: principleRows(agents) };471+});modified:AGENTS.md+43 added-16 removed
12345567895 unmodified lines151617181920212221222324252627282930313223242526272829303132333435363736383940414213 unmodified lines565758596061626364656667686970717273747576777879808182838410 unmodified lines9596979876991001011021038110410510610710810911011111240 unmodified lines# Myr
Myr is a whole Git platform on Cloudflare. Everything a project ships is public, the contribution process is typed code, and a push lands only by passing a typed gate. It is our entry to Cloudflare's "Build the next GitHub" competition, which closes Wed Oct 14, 11:59 PM PDT.
**Day 0.** Every script, package and check named below is planned, not built. Until a rule's fence exists, review holds it: build the fence, then rely on it.**W1's fences exist, and `bun run verify` runs them.** The principles table says which rules still wait for theirs; until a rule's fence lands, review holds it.
The plan is the synthesis: `~/Developer/projects/wanted-explainer/notes/git-platform-research/zoom-out/synthesis.md`, published at https://plans.gneiss.run/wanted-explainer/zoom-out/synthesis.html. Read the section your task touches:
- the concept: §3;5 unmodified lines## Principles
Fence wins over prose: if this file and an enforced check disagree, the check wins; fix this file. A rule held by "No fence yet" is debt: give it a fence.
In "Held by", each code-formatted name before "No fence yet:" is an enforcer: a file, a root script, a lint rule, an Effect diagnostic, a tsconfig key, a refusal tag or a branded id. Write everything else in the cell as plain text. Principle 1's test fails on an enforcer the repo lacks, and on a row with neither an enforcer nor "No fence yet:". After "No fence yet:", name what will hold the rule and the wave that builds it.
| # | Principle | Held by || --- | --- | --- || 1 | **Encode lessons in structure; prose is the last rung.** When a mistake repeats, make it unrepresentable, then a lint or test, then a skill. | `packages/config/test/agents-table.test.ts`: every enforcer named here exists || 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | Effect diagnostics map at `error`; anti-slop Effect rules; `env` typed by the generated `worker-configuration.d.ts`, with no `as` on `env` || 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a static `retryable`, a `next` command and an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | Union test; `gen:check` on `docs/reference/refusals.md`; an MCP `tools/call` test || 4 | **One schema, many surfaces.** Change `packages/protocol`, then run `bun run gen`. `skills/`, `plugins/` and `docs/reference/` are generated. Projections live only in `apps/*/src/surfaces.ts`. | `gen:check` (`git diff --exit-code` after gen); per-package `allowedUnstableApis` || 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` in `verify`; `scripts/acceptance.ts` renames the brand at random || 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. | Scoped `allowedUnstableApis`; `no-module-level-mutable-state`. No fence yet: import direction (apps never import apps, Worker code stays host-free, `alchemy/*` only in `infra/`) || 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree` and snapshot-order tests; a type test that `apps/web/worker-configuration.d.ts` has no `ARTIFACTS_PRIVATE` || 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at `error`; replay-twice and dedupe tests; lifecycle model tests || 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Off limits: `effect/unstable/*`, v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; oxlint `no-restricted-imports`; `no-manual-effect-runtime-in-tests` || 10 | **Escapes need a reason and only shrink.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries a reason after `--` and is counted. The count rises only with sign-off. | `scripts/debt.ts` against `debt.baseline.json` in `verify`; unused directives at `error` || 11 | **Hooks are early feedback; `bun run verify` and CI are the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `scripts/hooks/vcs-policy.ts` and its bypass-variant tests; `infra/deploy.ts` refuses without a stage and runs `scripts/smoke.ts`. No fence yet: git hooks; CI on a cold install || 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | Model tests over `effect/Arbitrary` histories with one planted bug. No fence yet: a lint banning `Effect.sleep` and `setTimeout` in `packages/project` || 1 | **Encode lessons in structure; prose is the last rung.** When a mistake repeats, make it unrepresentable, then a lint or test, then a skill. | `packages/config/test/agents-table.test.ts`: every enforcer this column names exists and is on || 2 | **Parse at the boundary, trust inside.** Decode every external input (HTTP, git, DO RPC, WebSocket, rule facts, env) with Effect Schema; inside, use branded types (`AskId`, `LandedSha`, `PatchId`). Decode the Worker `env` once, in one Layer. | The Effect diagnostics at error in `tsconfig.base.json`; `anti-slop/no-unknown-parameters`, `anti-slop/no-widen-then-assert` and `anti-slop/require-safety-comment-for-type-assertion`; the generated `apps/platform/worker-configuration.d.ts` types the env, and `apps/platform/test/platform.test.ts` proves a bad env fails at start. No fence yet: the decoded bindings equal `wrangler.jsonc`'s, with no `as` on `env` (`apps/platform/test/bindings.test.ts`, W3 317) || 3 | **Refusals are a closed `Schema.TaggedError` union and a public contract.** Handle them with `Match.exhaustive` or `catchTags`. Each carries a static `retryable`, a `next` command and an optional `at`, and no `message` field. A `_tag` is renamed only with an alias. `protocol/render` is the one renderer for git `remote:`, CLI and MCP text. Stage-1 refusals accumulate. | `packages/protocol/test/refusal.test.ts` (the tag list is closed; each refusal reaches MCP as JSON with retryable and next); `packages/protocol/test/render.test.ts`; `packages/protocol/test/mcp.test.ts` (a refusal from tools/call keeps its tag); `gen:check` on `docs/reference/refusals.md`; `anti-slop-effect/prefer-effect-match` and `anti-slop-effect/no-manual-tag-comparison`. No fence yet: the gate's stage-1 test that every refusal accumulates (W2 206); a `tools/call` test per refusing contract (W4 408) || 4 | **One schema, many surfaces.** Change `packages/protocol`, then run `bun run gen`. `skills/`, `plugins/` and `docs/reference/` are generated. Projections live only in `apps/*/src/surfaces.ts`. | `gen:check` (`scripts/gen.ts`, tested by `packages/config/test/gen.test.ts`) fails on a stale, missing or hand-written generated file; per-package `allowedUnstableApis` with `unstableApiUsage` at error keep Rpc and Tool construction in protocol and the apps || 5 | **The name lives only in `packages/brand`.** Internal packages use `@repo/*`. DO classes, Workflows, queues and databases carry job names. | `brand:check` (`scripts/brand.ts`, tested by `packages/brand/test/leaks.test.ts`) in `verify`. No fence yet: `scripts/acceptance.ts` renames the brand at random on a cold clone and runs `verify` (W7 714) || 6 | **Pure core, thin hosts.** Only `@repo/artifacts` calls Artifacts. Each beta dependency sits behind one job-named port with a `/memory` adapter in the owning package. Apps import packages only. Worker code stays free of `node:child_process`, `@effect/platform-bun` and OpenTUI. `rules` and `gate` run in both Workers and Bun. `alchemy/*` stays in `infra/`. | `imports:check` (`scripts/imports.ts`, tested by `packages/config/test/imports.test.ts`): the package matrix, apps never importing apps, host-free Worker code, adapters only through their subpaths, alchemy only in infra; scoped `allowedUnstableApis`; `fence/no-module-level-mutable-state`. No fence yet: Artifacts and each other beta dependency behind one port with a `/memory` adapter, composed from the decoded env (W2 202; W3 317 `apps/platform/src/ports.ts`) || 7 | **Deny by default for visibility.** Land the answer's tree, never the composed tree. Nothing from a layer enters a public tree. Snapshot before held-back files are written. Public-serving Workers have no private-namespace binding. Public commits, trailers, notes and errors name public paths only. | `PrivatePathInPublicTree` in the closed refusal union. No fence yet: the stage-1 path checks that raise it (W2 206 gate, W6 606 gateway); the web `Env` type test, no `ARTIFACTS_PRIVATE` (W5 501 `apps/web/test/env.test-d.ts`); the snapshot-order test (W3 315, W6 605) || 8 | **Deterministic and idempotent.** Rule evaluation sees frozen time and randomness and only injected facts. Re-running an operation converges. Check results are keyed by (tree SHA, check version), push events deduped by (repo, sha), and land requests carry a `requestId`. | `globalDate`, `globalRandom`, `globalTimers` and `cryptoRandomUUID` at error, with their in-Effect twins. No fence yet: the rules replay-twice test (W2 204); dedupe by `requestId` and event id (W2 210, W3 313); the Answer Workflow's replay test (W3 304); lifecycle model tests (W2 209, 219) || 9 | **Effect v4 only.** Read `node_modules/effect/src` as API truth. Off limits: `effect/unstable/*`, v3 `@effect/platform` and `@effect/cli`, and `effect/workflow` or `effect/cluster` on Workers. | `outdatedApi`; `no-restricted-imports`; `fence/no-manual-effect-runtime-in-tests` || 10 | **Escapes need a reason and only shrink.** Every `oxlint-disable`, `@effect-diagnostics` or `@ts-expect-error` carries a reason after `--` and is counted. The count rises only with sign-off. | `debt` (`scripts/debt.ts` over `oxlint.debt.config.ts`, tested by `packages/config/test/debt.test.ts`) against `debt.baseline.json` in `verify`; `check` fails on an unused directive || 11 | **Hooks are early feedback; `bun run verify` and CI are the authority.** Deploy only to an explicit stage, after `verify`, with smoke after. A red gate is fixed, never deployed around. | `scripts/hooks/vcs-policy.ts`, wired into Claude Code (`.claude/settings.json`), Cursor (`.cursor/hooks.json`) and pi (`.pi/extensions/vcs-policy/`), refusing every bypass variant in `packages/config/test/vcs-policy.test.ts`; `verify`. No fence yet: `infra/deploy.ts` refuses without a stage and runs `scripts/smoke.ts` (W3 308); `scripts/acceptance.ts` runs `verify` on a cold install in place of CI (W7 714) || 12 | **Lifecycles are pure transitions.** `transition(state, command, now)`. Per DO call: hydrate, transition, persist, settle. Deadlines run on DO alarms. Call them lifecycles. | `globalTimers` and `globalTimersInEffect` refuse JavaScript timers outside and inside Effect. No fence yet: lifecycle model tests over `effect/Arbitrary` histories with one planted bug (W2 209, 219); a lint banning `Effect.sleep` in `packages/project` (no wave yet) |
## Fence
`bun run verify` is the gate: the lockfile check, lint and format (`check`), typecheck, test, `gen:check` and `brand:check`. Run it before you stop. When a hook or check fails, fix the cause. Loosening, skipping or disabling a check needs the user's sign-off.`bun run verify` is the gate (see Commands). Run it before you stop. When a hook or check fails, fix the cause. Loosening, skipping or disabling a check needs the user's sign-off.
**Safe by default:**
- new or tightened tests;13 unmodified lines- deleting any Cloudflare resource;- any deploy during a recording;- removing a credit from `PROVENANCE.md`.
## Commands
Run each as `bun run <name>` from the repo root.
- `verify`: the gate. It runs `lockfile:check`, `check`, `typecheck`, `test`, `gen:check`, `imports:check`, `debt`, `brand:check` and `bytes:check`, and stops at the first failure.- `check`: lints and checks formatting; an unused escape directive fails it.- `fix`: applies lint fixes and formatting. Run it before `verify`.- `typecheck`: type-checks every workspace and the root's scripts, Effect diagnostics included.- `test`: runs every workspace's tests.- `gen`: rewrites `docs/reference/`, `skills/` and `plugins/` from `packages/protocol`.- `gen:check`: fails when a generated file is stale, missing or written by hand.- `imports:check`: fails on an import that crosses a line principle 6 draws.- `debt`: fails when an escape has no reason, or a kind's count rises above `debt.baseline.json`. `debt -- --lower` lowers the baseline to the count, never raises it.- `brand:check`: fails when the name appears outside `packages/brand` and prose.- `bytes:check`: fails when a Worker's bundle grows past its byte budget.- `lockfile:check`: fails when `bun.lock` is out of date with the manifests.- `env:check`: shows the env with its values redacted.- `ops -- <command>`: runs cf with the ops credentials (see Boundaries).
`bash scripts/vendor-agent-sources.sh` clones the source of the pinned Effect and Wrangler into `.agent_sources/`, the API truth to read.
## Nouns
Each code noun has one home:
10 unmodified lines## Boundaries
- **Competition rules apply to repo text.** Describe rival projects by mechanism, neutrally. All of this repo's code is public; no part of the submission lives in a private layer.- **Env.** To see the env, run `bun run env:check` (`varlock load --agent`, values redacted). That is the only way to read it: `.env`, `.env.local` and `.env.*.local` stay closed. To add a variable, edit the `.env.schema` that owns it (`infra/` for tool credentials, an app's for its Worker) and ask the user to set the value. Product code reads a project's `.env.schema` only through `@repo/visibility`'s parser, and never resolves it.- **Deploy and ops.** Deploy with Wrangler, through `infra/deploy.ts`. `cf` handles read-mostly API operations, run as `bun run ops -- <command>`. Find a command with `bun run ops -- cli search "…"` and `bun run ops -- schema <command>`, and try it with `--dry-run` before a real call. Leave cf's project commands (`dev`, `build`, `deploy`, `init`, `migrate`, `previews`) and the global `cf` alone. Ask the user before any cf `delete` or `revoke`, and keep `apps/platform` undeployed while a recording runs.- **Deploy and ops.** Deploy with Wrangler, through `infra/deploy.ts`. `cf` handles read-mostly API operations, run as `bun run ops -- <command>`. Find a command with `bun run ops -- cli search "…"` and `bun run ops -- schema <command>`, and try it with `--dry-run` before a real call. Leave cf's project commands (`dev`, `build`, `deploy`, `init`, `migrate`, `previews`) and the global `cf` alone. Ask the user before any cf `delete` or `revoke`, and keep `apps/platform` undeployed while a recording runs. `wrangler delete` auto-confirms in a non-interactive shell, so never run it without the user's OK (the hook policy refuses it); cf deletes need `--force` when non-interactive.- **Ported code is ours.** Change ported files freely and record each change in `PROVENANCE.md`. Upstream `main` is never synced in. Borrowed code stays under 15% of the codebase (aim for about 5%).
## Effect traps
Wire schemas in `protocol` use `Schema.Int` or `Schema.Finite` in place of bare `Schema.Number`, and `Schema.optionalKey` in place of `Schema.optional`. The bare forms put `"Infinity"` strings and `null` into JSON Schema and MCP tool schemas.- Wire schemas in `protocol` use `Schema.Int` or `Schema.Finite` in place of bare `Schema.Number`, and `Schema.optionalKey` in place of `Schema.optional`. The bare forms put `"Infinity"` strings and `null` into JSON Schema and MCP tool schemas.- Promises and web streams enter Effect through `Effect.tryPromise` and `Stream.fromReadableStream`/`toReadableStream`; the `asyncFunction` diagnostic bans `async`.- Tests that spawn processes or open sockets use `it.live`; `it.effect` runs on the TestClock.- `McpServer.layerStdio` interrupts the fiber that started it when stdin ends; in tests, fork the server and await it.- The RPC HTTP client carries Rpc headers inside the body, so send a credential as a plain HTTP header.
## Rejected dependencies
Each was weighed and turned down; re-adding one needs sign-off.40 unmodified lines