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).
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
Provenance
- Commit
b2c2b51- Tree
c883ca9- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
3b0df19
4 files changed+613 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+136 added
1+import { describe, expect, it } from "@effect/vitest";2+3+import type { Repo } from "./agents-table.ts";4+import {5+ loadAgentsTable,6+ missingEnforcers,7+ principleRows,8+} from "./agents-table.ts";9+10+/** A repo with one enforcer of each kind, and nothing else. */11+const 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+};29+30+/** A file whose principles table has one row, principle 4, held by `cell`. */31+const 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");44+45+const audit = (cell: string) =>46+ principleRows(plantedTable(cell)).flatMap((row) =>47+ missingEnforcers(row, plantedRepo)48+ );49+50+describe("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+ });64+65+ 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+ });77+78+ 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+ });85+86+ 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+ });91+92+ 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");113+114+ expect(principleRows(markdown)).toStrictEqual([115+ { enforcers: ["verify"], principle: "1" },116+ { enforcers: ["a|b", "gen:check"], principle: "2" },117+ ]);118+ });119+});120+121+// 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.123+const { repo, rows } = await loadAgentsTable();124+125+describe("AGENTS.md's principles table", () => {126+ it("is under ## Principles, with a Held by column", () => {127+ expect(rows).not.toHaveLength(0);128+ });129+130+ 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+ */23+import { NodeServices } from "@effect/platform-node";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+}51+52+type Kind =53+ | "file"54+ | "script"55+ | "lint rule"56+ | "diagnostic"57+ | "config key"58+ | "refusal"59+ | "id";60+61+const CUT = "No fence yet";62+63+const HELD_BY = "Held by";64+65+const SECTION = /^## Principles\s*$/u;66+67+const HEADING = /^#{1,2} /u;68+69+const BACKTICKED = /`(?<enforcer>[^`]+)`/gu;70+71+const UNESCAPED_PIPE = /(?<!\\)\|/u;72+73+const BUN_RUN = /^bun run (?<script>\S+)/u;74+75+const PLUGIN_RULE = /^(?<plugin>[a-z][a-z0-9-]*)\/[a-z][a-z0-9-]*$/u;76+77+const GLOB = /[*?{]/u;78+79+const EXTENSION = /\.[a-z0-9]+$/u;80+81+const SCRIPT = /^[a-z][a-z0-9]*(?::[a-z0-9-]+)*$/u;82+83+const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)+$/u;84+85+const CAMEL = /^[a-z][a-z0-9]*(?:[A-Z][A-Za-z0-9]*)+$/u;86+87+const PASCAL = /^[A-Z][A-Za-z0-9]*$/u;88+89+/** A table line's cells, trimmed, with `\|` read as a pipe inside a cell. */90+const cellsOf = (line: string) =>91+ line92+ .trim()93+ .replace(/^\|/u, "")94+ .replace(/\|$/u, "")95+ .split(UNESCAPED_PIPE)96+ .map((cell) => cell.trim().replaceAll(String.raw`\|`, "|"));97+98+/** The backticked enforcers in a "Held by" cell, before "No fence yet". */99+const enforcersIn = (cell: string) =>100+ Array.from(101+ (cell.split(CUT)[0] ?? "").matchAll(BACKTICKED),102+ (match) => match.groups?.enforcer ?? ""103+ );104+105+/**106+ * Each row of the first table under `## Principles` whose header has a107+ * "Held by" column. No such table: no rows.108+ */109+export const principleRows = (markdown: string): readonly Row[] => {110+ const lines = markdown.split("\n");111+ const start = lines.findIndex((line) => SECTION.test(line));112+113+ if (start === -1) {114+ return [];115+ }116+117+ const end = lines.findIndex(118+ (line, index) => index > start && HEADING.test(line)119+ );120+121+ const section = lines.slice(start + 1, end === -1 ? undefined : end);122+123+ const header = section.findIndex(124+ (line) => line.startsWith("|") && cellsOf(line).includes(HELD_BY)125+ );126+127+ if (header === -1) {128+ return [];129+ }130+131+ 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("|"));136+137+ 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+};145+146+const GLOB_PART = /\{[^{}]*\}|\*\*\/|\*\*|\*|\?|[.+^$()|[\]{}\\]/gu;147+148+const WILDCARDS = new Map([149+ ["*", "[^/]*"],150+ ["**", ".*"],151+ ["**/", "(?:.*/)?"],152+ ["?", "[^/]"],153+]);154+155+const escapeRegExp = (text: string) =>156+ text.replaceAll(/[.+^$()|[\]{}\\*?]/gu, String.raw`\$&`);157+158+/** One part of a glob as a pattern: a wildcard, `{a,b}`, or one literal character. */159+const globPart = (part: string) => {160+ const wildcard = WILDCARDS.get(part);161+162+ if (wildcard !== undefined) {163+ return wildcard;164+ }165+166+ return part.length > 1167+ ? `(?:${part.slice(1, -1).split(",").map(escapeRegExp).join("|")})`168+ : escapeRegExp(part);169+};170+171+/** `*` and `?` stay inside one folder, `**` crosses folders, `{a,b}` is either. */172+const globPattern = (glob: string) =>173+ new RegExp(`^${glob.replaceAll(GLOB_PART, globPart)}$`, "u");174+175+/** A path matches itself, a folder (with or without its slash) its files. */176+const matchesFile = (token: string, files: readonly string[]) => {177+ if (GLOB.test(token)) {178+ const pattern = globPattern(token);179+180+ return files.some((file) => pattern.test(file));181+ }182+183+ const folder = token.endsWith("/") ? token : `${token}/`;184+185+ return files.some((file) => file === token || file.startsWith(folder));186+};187+188+/** `fence/no-x` matches itself; a bare `no-x` matches it under any plugin. */189+const matchesRule = (token: string, rules: readonly string[]) =>190+ rules.some((rule) => rule === token || rule.endsWith(`/${token}`));191+192+const 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+};202+203+const 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+};212+213+/** What an enforcer could be, by its shape alone; none if it has no known shape. */214+const kindsOf = (token: string, repo: Repo): readonly Kind[] => {215+ if (BUN_RUN.test(token)) {216+ return ["script"];217+ }218+219+ if (/\s/u.test(token)) {220+ return [];221+ }222+223+ const plugin = PLUGIN_RULE.exec(token)?.groups?.plugin;224+225+ if (plugin !== undefined && repo.lintPlugins.includes(plugin)) {226+ return ["lint rule"];227+ }228+229+ if (230+ token.includes("/") ||231+ token.startsWith(".") ||232+ GLOB.test(token) ||233+ EXTENSION.test(token)234+ ) {235+ return ["file"];236+ }237+238+ if (SCRIPT.test(token)) {239+ return ["script"];240+ }241+242+ if (KEBAB.test(token)) {243+ return ["lint rule", "script"];244+ }245+246+ if (CAMEL.test(token)) {247+ return ["diagnostic", "config key"];248+ }249+250+ return PASCAL.test(token) ? ["refusal", "id"] : [];251+};252+253+/** One line for each enforcer in `row` that the repo doesn't hold. */254+export const missingEnforcers = (row: Row, repo: Repo): readonly string[] =>255+ row.enforcers.flatMap((token) => {256+ const kinds = kindsOf(token, repo);257+258+ if (kinds.length === 0) {259+ return [260+ `unclassified enforcer \`${token}\` in principle ${row.principle}; name a file, script, rule, diagnostic or tag`,261+ ];262+ }263+264+ 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+ });272+273+const isError = (setting: DummyRule | undefined) => {274+ const severity = Array.isArray(setting) ? setting[0] : setting;275+276+ return severity === "error" || severity === "deny" || severity === 2;277+};278+279+/** A config, then each config it extends, innermost first. */280+const layersOf = (config: OxlintConfig): readonly OxlintConfig[] => [281+ ...(config.extends ?? []).flatMap(layersOf),282+ config,283+];284+285+/** The rules oxlint runs at error: top level (a later layer wins) or in an override. */286+const rulesAtError = (config: OxlintConfig) => {287+ const layers = layersOf(config);288+289+ const topLevel = new Map(290+ layers.flatMap((layer) => Object.entries(layer.rules ?? {}))291+ );292+293+ const overridden = layers.flatMap((layer) =>294+ (layer.overrides ?? []).flatMap((override) =>295+ Object.entries(override.rules ?? {})296+ )297+ );298+299+ return [...topLevel, ...overridden].flatMap(([rule, setting]) =>300+ isError(setting) ? [rule] : []301+ );302+};303+304+/** Built-in plugins each layer turns on, and each JavaScript plugin's name. */305+const 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+ ]);312+313+const isJsonArray = Schema.is(Schema.Array(Schema.Json));314+315+const isJsonObject = Schema.is(Schema.JsonObject);316+317+/** Every key in a JSON document, except the diagnostics' names. */318+const keysOf = (json: Schema.Json): readonly string[] => {319+ if (isJsonArray(json)) {320+ return json.flatMap(keysOf);321+ }322+323+ if (isJsonObject(json)) {324+ return Object.entries(json).flatMap(([key, value]) => [325+ key,326+ ...(key === "diagnosticSeverity" ? [] : keysOf(value)),327+ ]);328+ }329+330+ return [];331+};332+333+const RootPackage = Schema.Struct({334+ scripts: Schema.Record(Schema.String, Schema.String),335+});336+337+const 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+});348+349+const REFUSAL_CLASS =350+ /\bclass\s+(?<name>[A-Z][A-Za-z0-9]*)\s+extends\s+Schema\.TaggedError\b/gu;351+352+const EXPORTED =353+ /^export\s+(?:const|type|interface|class)\s+(?<name>[A-Z][A-Za-z0-9]*)/gmu;354+355+const namesIn = (source: string, pattern: RegExp) => [356+ ...new Set(357+ Array.from(source.matchAll(pattern), (match) => match.groups?.name ?? "")358+ ),359+];360+361+/** AGENTS.md's text, and what the repo holds, read from the repo root. */362+export 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));369+370+ const lsFiles = (...args: readonly string[]) =>371+ spawner.lines(372+ ChildProcess.make("git", ["ls-files", ...args], { cwd: root })373+ );374+375+ 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+ );386+387+ const listed = yield* lsFiles(388+ "--cached",389+ "--others",390+ "--exclude-standard",391+ "--deduplicate"392+ );393+394+ const deleted = new Set(yield* lsFiles("--deleted"));395+396+ const { scripts } = yield* Schema.decodeEffect(397+ Schema.fromJsonString(RootPackage)398+ )(rootPackage);399+400+ const tsconfig = yield* Schema.decodeEffect(401+ Schema.fromJsonString(Schema.Json)402+ )(tsconfigText);403+404+ const { compilerOptions } =405+ yield* Schema.decodeUnknownEffect(TsconfigBase)(tsconfig);406+407+ 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+ };421+422+ return { repo, rows: principleRows(agents) };423+});424+425+/**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+ */430+export const loadAgentsTable = () =>431+ Effect.runPromise(readAgentsTable.pipe(Effect.provide(NodeServices.layer)));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. Principle 1's test fails on any the repo lacks, so write everything else in the cell as plain text. 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