Skip to content
Myr

Merge build/411-judge-closure-breadth: the judge closure covers lint plugin sources, rule fixtures, the tsconfig chain and every hook config

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

authored by oscabriel · committed by oscabriel · parents cc390dd, c6c000f · Browse files · 2 files+1883 added−94 removed
This commit

State

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

Diff stats

2 files+1883 added−94 removed

  • tests:+767 added−2 removed
  • other:+1116 added−92 removed

2 files+1883 added−94 removed

modified:packages/checks/src/judge.ts+1116 added-92 removed
7 unmodified lines
8import { Brand } from "@repo/brand";9import { Glob } from "@repo/protocol/domain/common";10import type { Policy } from "@repo/protocol/domain/policy";11import type { RunBlock } from "@repo/protocol/domain/run";12import { RepoPath } from "@repo/protocol/ids";13import { Equal, Option, Predicate, Result, Schema } from "effect";14import { parse } from "yaml";1516import type { RepoFile } from "./finder.ts";1718/** A closure glob that starts with this takes paths back out of the closure. */19const EXCLUDE = "!";2021/**20 * What every project's judge holds before its run block adds to it: the21 * config folder, the env schema and committed env files (never `*.local`22 * ones), CI, test and lint config, the tsconfig files, git and harness hook23 * config, and generated contribute skills. Lint plugin sources and rule24 * fixtures are not in it yet.22 * Where each harness and git hook manager the platform knows keeps its hooks:23 * Claude Code, Cursor, Codex, GitHub Copilot, Gemini CLI, pi, OpenCode and24 * Amp; lefthook (and its scripts folder), husky and pre-commit. A hook runs in25 * every contributor's session, so an answer may not change one.26 */26export const defaultJudgeGlobs: readonly Glob[] = [27 `${Brand.configDir}/**`,28 "**/.env.schema",29 "**/.env.*",30 `${EXCLUDE}**/.env.local`,31 `${EXCLUDE}**/.env.*.local`,32 ".github/workflows/**",33 ".github/actions/**",34 ".forgejo/**",35 "**/vitest.config.*",36 "**/vitest.workspace.*",37 "**/vite.config.*",38 "**/oxlint.config.*",39 "**/.oxlintrc*",40 "**/eslint.config.*",41 "**/.eslintrc*",42 "**/biome.json*",43 "**/tsconfig*.json",44 "tools/oxlint/**",27export const hookConfigGlobs: readonly Glob[] = [28 ".claude/settings*.json",29 ".cursor/hooks.json",30 ".codex/hooks.json",31 ".codex/config.toml",32 ".github/hooks/*.json",33 ".github/copilot/settings.json",34 ".gemini/settings.json",35 ".pi/**",36 ".opencode/plugins/**",37 ".amp/plugins/**",38 "lefthook.yml",39 "lefthook.yaml",40 ".lefthook.yml",41 ".lefthook.yaml",42 ".lefthook/**",43 ".husky/**",44 ".pre-commit-config.yaml",51 ".claude/settings*.json",52 ".cursor/hooks.json",53 ".pi/**",54 ".agents/skills/*-contribute/**",55 ".claude/skills/*-contribute/**",45].map((glob) => Glob.make(glob));4647/**48 * The workspace and task-runner policy files, and formatter config: what a49 * package manager, a task runner or a formatter check reads before it runs50 * anything (bun's and pnpm's install policy, turbo's and nx's task graph,51 * yarn's own release and plugins). `.editorconfig` is not one: no check52 * reads it.53 */54export const policyFileGlobs: readonly Glob[] = [55 "**/bunfig.toml",56 "pnpm-workspace.yaml",57 "**/turbo.json",58 "**/turbo.jsonc",59 "nx.json",60 ".yarnrc.yml",61 ".yarn/plugins/**",62 ".yarn/releases/**",63 "**/oxfmt.config.*",64 "**/.oxfmtrc*",65 "**/biome.json*",66 "**/.prettierrc*",67 "**/prettier.config.*",68].map((glob) => Glob.make(glob));6970/**71 * What every project's judge holds before its run block adds to it: the72 * config folder, the env schema and committed env files (never `*.local`73 * ones), CI, test and lint config, the tsconfig files, generated contribute74 * skills, the workspace and task-runner policy files, and every hook config.75 */76export const defaultJudgeGlobs: readonly Glob[] = [77 ...[78 `${Brand.configDir}/**`,79 "**/.env.schema",80 "**/.env.*",81 `${EXCLUDE}**/.env.local`,82 `${EXCLUDE}**/.env.*.local`,83 ".github/workflows/**",84 ".github/actions/**",85 ".forgejo/**",86 "**/vitest.config.*",87 "**/vitest.*.config.*",88 "**/vitest.workspace.*",89 "**/vite.config.*",90 "**/oxlint.config.*",91 "**/oxlint.*.config.*",92 "**/.oxlintrc*",93 "**/eslint.config.*",94 "**/eslint.*.config.*",95 "**/.eslintrc*",96 "**/tsconfig*.json",97 "tools/oxlint/**",98 ".agents/skills/*-contribute/**",99 ".claude/skills/*-contribute/**",100 ].map((glob) => Glob.make(glob)),101 ...policyFileGlobs,102 ...hookConfigGlobs,103];104105const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");106107// One path segment against one glob segment: `*` is any run of characters108// and `?` is one, never a `/`. Greedy, backing up to the last `*` on a miss.
85 unmodified lines
194 )195 );196};197151const Extends = Schema.fromJsonString(152 Schema.Struct({153 extends: Schema.optionalKey(154 Schema.Union([Schema.String, Schema.Array(Schema.String)])155 ),156 })157);198const decodeJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));199159const decodeExtends = Schema.decodeOption(Extends);200const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>201 Array.isArray(value);202203const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>204 Predicate.isObject(value) && !isJsonArray(value);205206// The index just past the string literal whose quote is at `at`; an207// unclosed string runs to the end.208const stringEnd = (text: string, at: number): number => {209 const quote = text.charAt(at);210 let next = at + 1;211212 while (next < text.length && text.charAt(next) !== quote) {213 next += text.charAt(next) === "\\" ? 2 : 1;214 }215216 return Math.min(next + 1, text.length);217};218219/** Where the comment that opens at `at` ends, if one opens there. */220type CommentEnd = (text: string, at: number) => Option.Option<number>;221222// The index just past the comment that opens at `at`, if one does.223const commentEnd: CommentEnd = (text, at) => {224 if (text.startsWith("//", at)) {225 const end = text.indexOf("\n", at);226227 return Option.some(end === -1 ? text.length : end);228 }229230 if (text.startsWith("/*", at)) {231 const end = text.indexOf("*/", at + 2);232233 return Option.some(end === -1 ? text.length : end + 2);234 }235236 return Option.none();237};238239// The index just past the `#` comment (TOML's) that opens at `at`, if one does.240const hashCommentEnd: CommentEnd = (text, at) => {241 if (text.charAt(at) !== "#") {242 return Option.none();243 }244245 const end = text.indexOf("\n", at);246247 return Option.some(end === -1 ? text.length : end);248};249250const QUOTES = new Set(['"', "'", "`"]);251252/**253 * Text with each comment outside a string as one space: `//` and `/* *\/`254 * ones by default (JavaScript, JSONC), or those `opens` finds.255 */256const withoutComments = (257 text: string,258 opens: CommentEnd = commentEnd259): string => {260 let kept = "";261 let at = 0;262263 while (at < text.length) {264 const char = text.charAt(at);265266 if (QUOTES.has(char)) {267 const end = stringEnd(text, at);268269 kept += text.slice(at, end);270 at = end;271 } else {272 const end = opens(text, at);273274 kept += Option.isSome(end) ? " " : char;275 at = Option.isSome(end) ? end.value : at + 1;276 }277 }278279 return kept;280};281282const isSpace = (char: string) => /\s/u.test(char);283284// Whether the next character after `at` that isn't space closes a bracket.285const closesNext = (text: string, at: number) => {286 let peek = at;287288 while (isSpace(text.charAt(peek))) {289 peek += 1;290 }291292 return peek < text.length && "]}".includes(text.charAt(peek));293};294295/** JSON text with each comma that closes nothing (`[1, 2,]`) left out. */296const withoutTrailingCommas = (text: string): string => {297 let kept = "";298 let at = 0;299300 while (at < text.length) {301 const char = text.charAt(at);302 const end = char === '"' ? stringEnd(text, at) : at + 1;303304 kept += char === "," && closesNext(text, end) ? "" : text.slice(at, end);305 at = end;306 }307308 return kept;309};310311/**312 * JSONC (tsconfig, `.oxlintrc.json`, harness settings) read as JSON: its313 * comments and trailing commas are dropped first. Pure and dependency-free.314 */315const decodeJsonc = (text: string): Option.Option<Schema.Json> =>316 decodeJson(withoutTrailingCommas(withoutComments(text)));317318const UNREADABLE =319 "not JSON, even with comments and trailing commas removed; the walk stops here";320321const UNREAD = "not among the files read; judged unread";322323const dirname = (path: string) => path.split("/").slice(0, -1).join("/");324325// `a/b` joined with `../c` is `c`; `..` above the root leaves the repo.326const join = (dir: string, relative: string): Option.Option<string> => {
8 unmodified lines
335 parts.push(part);336 }337 }338177 return Option.some(parts.join("/"));339 return parts.length === 0 ? Option.none() : Option.some(parts.join("/"));340};341180// `./base` names `base.json` when only that exists, as TypeScript resolves it.181const resolveExtends = (182 from: string,183 specifier: string,342const isRelative = (specifier: string) =>343 specifier === "." ||344 specifier === ".." ||345 specifier.startsWith("./") ||346 specifier.startsWith("../");347348const isPackageJson = (path: string) => matchGlob("**/package.json", path);349350/** Each workspace package's name and folder, from the manifests given. */351const workspacesOf = (352 contents: ReadonlyMap<string, string>185): Option.Option<string> =>186 specifier.startsWith(".")187 ? Option.flatMap(join(dirname(from), specifier), (path) =>188 Option.fromNullishOr(189 [path, `${path}.json`].find((candidate) => contents.has(candidate))353): ReadonlyMap<string, string> =>354 new Map(355 [...contents]356 .filter(([path]) => isPackageJson(path))357 .flatMap(([path, content]) =>358 decodeJson(content).pipe(359 Option.filter(isJsonObject),360 Option.flatMapNullishOr((manifest) => manifest.name),361 Option.filter(Predicate.isString),362 Option.filter((name) => name.length > 0),363 Option.match({364 onNone: () => [],365 onSome: (name) => [[name, dirname(path)] as const],366 })367 )368 )192 : Option.none();369 );370371/**195 * The files a tsconfig extends, followed until the chain ends or leaves the196 * repo. A package specifier (`@tsconfig/node24`) is a dependency, not a path.197 * A file that doesn't parse as plain JSON (JSONC, say) ends its branch.372 * A package specifier read as a workspace package's own file: `@repo/x/y`373 * is `y` inside the folder of the package named `@repo/x`, the longest name374 * winning. A package no workspace declares is a dependency, not a path.375 */199const extendsChain = (376const inWorkspace = (377 specifier: string,378 workspaces: ReadonlyMap<string, string>379): Option.Option<{ readonly dir: string; readonly rest: string }> =>380 Option.fromNullishOr(381 [...workspaces]382 .filter(383 ([name]) => specifier === name || specifier.startsWith(`${name}/`)384 )385 .toSorted(([left], [right]) => right.length - left.length)386 .map(([name, dir]) => ({ dir, rest: specifier.slice(name.length + 1) }))387 .at(0)388 );389390// `./base` names `base.json` when only that exists, as TypeScript resolves391// it; a target not among the files keeps the name tsc would read.392const configFile = (path: string, contents: ReadonlyMap<string, string>) =>393 [path, `${path}.json`].find((candidate) => contents.has(candidate)) ??394 (path.endsWith(".json") ? path : `${path}.json`);395396/**397 * Where a tsconfig's `extends` entry points: a relative path from the file's398 * folder, or a file of a workspace package (a bare package name is its399 * `tsconfig.json`). Any other package (`@tsconfig/node24`) is a dependency.400 */401const resolveExtends = (402 from: string,403 specifier: string,404 contents: ReadonlyMap<string, string>,405 workspaces: ReadonlyMap<string, string>406): Option.Option<string> => {407 if (isRelative(specifier)) {408 return Option.map(join(dirname(from), specifier), (path) =>409 configFile(path, contents)410 );411 }412413 return Option.flatMap(inWorkspace(specifier, workspaces), ({ dir, rest }) =>414 Option.map(join(dir, rest === "" ? "tsconfig.json" : rest), (path) =>415 configFile(path, contents)416 )417 );418};419420const extendsOf = (config: Schema.Json): readonly string[] => {421 const value = isJsonObject(config) ? config.extends : undefined;422423 return [value ?? []].flat().filter(Predicate.isString);424};425426/** A path the walk could not read past, and why. */427const note = (path: string, reason: string) => `${path}: ${reason}`;428429const chainFrom = (430 start: string,201 contents: ReadonlyMap<string, string>202): readonly string[] => {203 const seen = new Set<string>();204 const queue = [start];431 contents: ReadonlyMap<string, string>,432 workspaces: ReadonlyMap<string, string>433) => {434 const chain = [start];435 const notes: string[] = [];436206 for (let next = queue.shift(); next !== undefined; next = queue.shift()) {207 const parent = decodeExtends(contents.get(next) ?? "").pipe(208 Option.flatMapNullishOr((config) => config.extends),209 Option.map((specifiers) => [specifiers].flat()),210 Option.getOrElse((): readonly string[] => [])437 for (const next of chain) {438 const content = contents.get(next);439 const config = Option.flatMap(Option.fromNullishOr(content), decodeJsonc);440441 if (content === undefined) {442 notes.push(note(next, UNREAD));443 } else if (Option.isNone(config)) {444 notes.push(note(next, UNREADABLE));445 }446447 const parents = Option.match(config, {448 onNone: () => [],449 onSome: extendsOf,450 }).flatMap((specifier) =>451 Option.toArray(resolveExtends(next, specifier, contents, workspaces))452 );453213 for (const specifier of parent) {214 const resolved = resolveExtends(next, specifier, contents);454 chain.push(...parents.filter((parent) => !chain.includes(parent)));455 }456216 if (Option.isSome(resolved) && !seen.has(resolved.value)) {217 seen.add(resolved.value);218 queue.push(resolved.value);457 return { chain: chain.map((path) => RepoPath.make(path)), notes };458};459460/**461 * A tsconfig and every file its `extends` reaches, in the order tsc reads462 * them: string and array forms, relative paths (`.json` added as tsc adds463 * it) and workspace packages' files. Files are read as JSONC. A file that464 * still doesn't parse ends its branch and stays in the chain, as does a465 * target not among `files`; each says why in `notes`.466 */467export const tsconfigChain = (468 start: RepoPath,469 files: ReadonlyMap<string, string>470): {471 readonly chain: readonly RepoPath[];472 readonly notes: readonly string[];473} => chainFrom(start, files, workspacesOf(files));474475/** A token of JavaScript or JSON text, its comments dropped. */476interface Token {477 readonly kind: "mark" | "string" | "word";478 readonly text: string;479}480481const isWordChar = (char: string) => /[\w$]/u.test(char);482483// A string literal's value; a template with `${…}` in it is no one value.484const literal = (quote: string, body: string): Token =>485 quote === "`" && body.includes("${")486 ? { kind: "mark", text: quote }487 : { kind: "string", text: body.replaceAll(/\\(?<char>.)/gu, "$<char>") };488489/**490 * Source text as words, string literals and single marks, comments491 * dropped (JavaScript's by default; TOML passes its `#`). Enough to read492 * imports and literal arrays without running the file; a regex literal that493 * holds a quote can mislead it.494 */495const tokensOf = (496 source: string,497 comments: CommentEnd = commentEnd498): readonly Token[] => {499 const text = withoutComments(source, comments);500 const tokens: Token[] = [];501 let at = 0;502503 while (at < text.length) {504 const char = text.charAt(at);505 let end = at + 1;506507 if (QUOTES.has(char)) {508 end = stringEnd(text, at);509 tokens.push(literal(char, text.slice(at + 1, end - 1)));510 } else if (isWordChar(char)) {511 while (end < text.length && isWordChar(text.charAt(end))) {512 end += 1;513 }514515 tokens.push({ kind: "word", text: text.slice(at, end) });516 } else if (!isSpace(char)) {517 tokens.push({ kind: "mark", text: char });518 }519520 at = end;521 }522223 return [...seen];523 return tokens;524};525526// Words a module path follows as a call's first argument: `import("…")`,527// `require("…")`, `require.resolve("…")`, `new URL("…", import.meta.url)`.528const LOADERS = new Set(["URL", "import", "require", "resolve"]);529530/** The module specifiers source text imports, exports from or requires. */531const importSpecifiers = (tokens: readonly Token[]): readonly string[] =>532 tokens.flatMap((token, at) => {533 const next = tokens[at + 1];534 const after = tokens[at + 2];535536 if (token.kind !== "word" || next === undefined) {537 return [];538 }539540 if (541 (token.text === "from" || token.text === "import") &&542 next.kind === "string"543 ) {544 return [next.text];545 }546547 return LOADERS.has(token.text) &&548 next.text === "(" &&549 after?.kind === "string"550 ? [after.text]551 : [];552 });553554// Marks that open and close a nesting level in source text.555const OPENS = new Set(["(", "[", "{"]);556557const CLOSES = new Set([")", "]", "}"]);558559/** What a `jsPlugins` key in source text holds, as far as its text says. */560interface PluginList {561 /** Each plugin string in a literal array, or an object's `specifier:` string. */562 readonly specifiers: readonly string[];563 /** Whether some `jsPlugins` holds something other than a literal array. */564 readonly opaque: boolean;565}566567// The strings of one `jsPlugins: [...]` array that starts at token `at`.568const listedAt = (tokens: readonly Token[], at: number): readonly string[] => {569 const found: string[] = [];570 let depth = 0;571572 for (let index = at; index < tokens.length; index += 1) {573 const token = tokens[index];574575 if (token?.kind === "mark" && OPENS.has(token.text)) {576 depth += 1;577 } else if (token?.kind === "mark" && CLOSES.has(token.text)) {578 depth -= 1;579580 if (depth === 0) {581 return found;582 }583 } else if (584 token?.kind === "string" &&585 (depth === 1 ||586 (tokens[index - 2]?.text === "specifier" &&587 tokens[index - 1]?.text === ":"))588 ) {589 found.push(token.text);590 }591 }592593 return found;594};595596/**597 * The `jsPlugins` arrays of an oxlint config's source, read as text: a key's598 * (`jsPlugins: [...]`) or a variable's (`const jsPlugins = [...]`).599 */600const jsPluginsInSource = (tokens: readonly Token[]): PluginList => {601 const starts = tokens.flatMap((token, at) =>602 token.text === "jsPlugins" &&603 (tokens[at + 1]?.text === ":" || tokens[at + 1]?.text === "=")604 ? [at + 2]605 : []606 );607608 return {609 opaque: starts.some((at) => tokens[at]?.text !== "["),610 specifiers: starts611 .filter((at) => tokens[at]?.text === "[")612 .flatMap((at) => listedAt(tokens, at)),613 };614};615616/** The `jsPlugins` of a JSON oxlint config: strings, or `{specifier}` objects. */617const jsPluginsInJson = (config: Schema.Json): readonly string[] => {618 const list = isJsonObject(config) ? config.jsPlugins : undefined;619620 return (list !== undefined && isJsonArray(list) ? list : []).flatMap(621 (entry) => {622 if (Predicate.isString(entry)) {623 return [entry];624 }625626 const specifier = isJsonObject(entry) ? entry.specifier : undefined;627628 return Predicate.isString(specifier) ? [specifier] : [];629 }630 );631};632633const basename = (path: string) => path.split("/").at(-1) ?? path;634635// `.oxlintrc.json`, `.oxlintrc`, `.eslintrc.json`: configs written as JSONC.636const isJsonConfig = (path: string) =>637 /\.jsonc?$/u.test(path) || basename(path) === ".oxlintrc";638639/** The lint configs whose plugins and imports judge: oxlint's and eslint's. */640const lintConfigGlobs = [641 "**/oxlint.config.*",642 "**/oxlint.*.config.*",643 "**/.oxlintrc*",644 "**/eslint.config.*",645 "**/eslint.*.config.*",646 "**/.eslintrc*",647];648649const isLintConfig = (path: string) =>650 lintConfigGlobs.some((glob) => matchGlob(glob, path));651652/** What one lint config names: its plugins, and the modules it imports or extends. */653interface LintNames {654 readonly imports: readonly string[];655 readonly notes: readonly string[];656 readonly plugins: readonly string[];657}658659const lintNames = (config: RepoFile): LintNames => {660 if (isJsonConfig(config.path)) {661 return Option.match(decodeJsonc(config.content), {662 onNone: () => ({663 imports: [],664 notes: [note(config.path, UNREADABLE)],665 plugins: [],666 }),667 onSome: (json) => ({668 imports: extendsOf(json),669 notes: [],670 plugins: jsPluginsInJson(json),671 }),672 });673 }674675 const tokens = tokensOf(config.content);676 const plugins = jsPluginsInSource(tokens);677678 return {679 imports: importSpecifiers(tokens),680 notes: plugins.opaque681 ? [682 note(683 config.path,684 "jsPlugins is not a literal array; its plugins are unknown"685 ),686 ]687 : [],688 plugins: plugins.specifiers,689 };690};691692// Relative specifiers, as paths from the repo root.693const relativeFrom = (694 from: string,695 specifiers: readonly string[]696): readonly RepoPath[] =>697 specifiers698 .filter(isRelative)699 .flatMap((specifier) => Option.toArray(join(dirname(from), specifier)))700 .map((path) => RepoPath.make(path));701702/**703 * The local plugins an oxlint config loads, as repo paths: each `jsPlugins`704 * entry of a `.oxlintrc*.json` (a string or `{specifier}`), or each string in705 * an `oxlint.config.*`'s `jsPlugins` array, read as text and never run.706 * Relative to the config's folder; a package name (`eslint-plugin-foo`) is a707 * dependency, not a path. A config that doesn't parse names none.708 */709export const jsPluginSpecifiers = (config: RepoFile): readonly RepoPath[] =>710 relativeFrom(config.path, lintNames(config).plugins);711712/**713 * The local modules an eslint config imports or requires (plugins and shared714 * configs alike), as repo paths from the config's folder, read as text and715 * never run. Packages are dependencies, not paths.716 */717export const eslintLocalPlugins = (config: RepoFile): readonly RepoPath[] =>718 relativeFrom(config.path, lintNames(config).imports);719720const MODULE_EXTENSIONS = [721 ".ts",722 ".tsx",723 ".mts",724 ".cts",725 ".js",726 ".jsx",727 ".mjs",728 ".cjs",729 ".json",730];731732const isIndex = (path: string) => /^index\.[cm]?[jt]sx?$/u.test(basename(path));733734const hasExtension = (path: string) => /\.[^./]+$/u.test(basename(path));735736const TWINS = new Map([737 [".cjs", [".cts"]],738 [".js", [".ts", ".tsx"]],739 [".mjs", [".mts"]],740]);741742// TypeScript's ESM habit: `./x.js` names `x.ts` when only that exists.743const sourceTwins = (path: string): readonly string[] => {744 const dot = path.lastIndexOf(".");745 const stem = path.slice(0, dot);746747 return (TWINS.get(path.slice(dot)) ?? []).map((ext) => `${stem}${ext}`);748};749750/**751 * What a module path turns out to be among the repo's files: a file (an752 * `index.*` brings its whole folder), a folder (`./rules` with753 * `rules/index.js`), or, when it is neither, the path, its extensions and754 * its folder, so a file an answer adds there is judged too.755 */756interface Settled {757 /** The plugin's own path: its file, or its folder for a folder plugin. */758 readonly anchor: string;759 /** The file to read next, when one exists. */760 readonly file: Option.Option<string>;761 readonly globs: readonly string[];762}763764const settledFile = (file: string): Settled => {765 const folder = dirname(file);766767 return isIndex(file) && folder !== ""768 ? { anchor: folder, file: Option.some(file), globs: [`${folder}/**`] }769 : { anchor: file, file: Option.some(file), globs: [file] };770};771772const settle = (path: string, paths: ReadonlySet<string>): Settled => {773 const found = [774 path,775 ...MODULE_EXTENSIONS.map((ext) => `${path}${ext}`),776 ...sourceTwins(path),777 ].find((candidate) => paths.has(candidate));778779 if (found !== undefined) {780 return settledFile(found);781 }782783 const index = MODULE_EXTENSIONS.map((ext) => `${path}/index${ext}`).find(784 (candidate) => paths.has(candidate)785 );786787 const folder = `${path}/`;788789 if (790 index !== undefined ||791 [...paths].some((candidate) => candidate.startsWith(folder))792 ) {793 return {794 anchor: path,795 file: Option.fromNullishOr(index),796 globs: [`${path}/**`],797 };798 }799800 return hasExtension(path)801 ? settledFile(path)802 : {803 anchor: path,804 file: Option.none(),805 globs: [path, `${path}.*`, `${path}/**`],806 };807};808809// A command's words that could name a file: split on whitespace and shell227// operators, unquoted, and the value of a `--flag=value`.810// operators, quotes dropped, a leading `$VAR/` or `${VAR}/` dropped (the811// project folder a harness exports), a `--flag=value`'s value, and a path812// after `$(…)` read from the root.813const wordsOf = (command: string): readonly string[] =>814 command230 .split(/[\s;&|()<>]+/u)231 .map((word) => word.replaceAll(/^["']|["']$/gu, ""))815 .split(/[\s;&|()<>`]+/u)816 .map((word) =>817 word.replaceAll(/["']/gu, "").replace(/^\$(?:\{\w+\}|\w+)\//u, "")818 )819 .flatMap((word) => [word, word.slice(word.indexOf("=") + 1)])820 .flatMap((word) => [word, word.replace(/^\/+/u, "")])821 .map(withoutDotSlash);822235const isPackageJson = (path: string) => matchGlob("**/package.json", path);823/**824 * Manifests, lockfiles and dependency lists. A command may name one (`pip825 * install -r requirements.txt`), and it stays editable all the same:826 * dependency edits are allowed, as they are in `package.json`, whose scripts827 * alone judge, by pointer.828 */829const dependencyFileGlobs = [830 "**/package.json",831 "**/bun.lock",832 "**/bun.lockb",833 "**/package-lock.json",834 "**/npm-shrinkwrap.json",835 "**/yarn.lock",836 "**/pnpm-lock.yaml",837 "**/requirements*.txt",838 "**/constraints*.txt",839 "**/poetry.lock",840 "**/uv.lock",841 "**/Pipfile.lock",842 "**/Cargo.lock",843 "**/go.sum",844 "**/Gemfile.lock",845 "**/composer.lock",846];847848const isDependencyFile = (path: string) =>849 dependencyFileGlobs.some((glob) => matchGlob(glob, path));850851/**852 * The tracked files commands run or read, from the words that name one:853 * `bun "${CLAUDE_PROJECT_DIR}/scripts/hooks/x.ts"` → `scripts/hooks/x.ts`.854 * A manifest, lockfile or dependency list is never one (dependency edits stay855 * allowed). Sorted.856 */857export const commandScripts = (858 commands: readonly string[],859 files: ReadonlySet<string>860): readonly RepoPath[] =>861 [862 ...new Set(863 commands864 .flatMap(wordsOf)865 .filter((word) => files.has(word) && !isDependencyFile(word))866 ),867 ]868 .toSorted()869 .map((path) => RepoPath.make(path));870871const isShell = (path: string) =>872 /\.(?:ba|z)?sh$/u.test(path) || !hasExtension(path);873874const CODE = /\.[cm]?[jt]sx?$/u;875876// What one file runs, as repo paths: a code file's relative imports and877// `jsPlugins` strings, or the tracked files a shell script's lines name.878const runsFrom = (879 path: string,880 content: string,881 paths: ReadonlySet<string>882): readonly string[] => {883 if (CODE.test(path)) {884 const tokens = tokensOf(content);885886 return relativeFrom(path, [887 ...importSpecifiers(tokens),888 ...jsPluginsInSource(tokens).specifiers,889 ]);890 }891892 return isShell(path) ? commandScripts(content.split("\n"), paths) : [];893};894895/**896 * Every module the seeds reach by relative imports, and every script a897 * shell script among them runs, settled to globs: what a lint plugin, a hook898 * script or a check script runs is judged with it. Packages, workspace ones899 * included, are not followed, nor any path `follows` refuses. A file without900 * contents ends its branch.901 */902const walkImports = (903 seeds: readonly string[],904 contents: ReadonlyMap<string, string>,905 paths: ReadonlySet<string>,906 follows: (path: string) => boolean = () => true907): readonly string[] => {908 const queue = [...seeds];909 const globs: string[] = [];910911 for (const path of queue) {912 const content = contents.get(path);913914 if (content !== undefined) {915 const targets = runsFrom(path, content, paths)916 .filter(follows)917 .map((target) => settle(target, paths));918919 globs.push(...targets.flatMap((target) => target.globs));920 queue.push(921 ...targets922 .flatMap((target) => Option.toArray(target.file))923 .filter((file) => !queue.includes(file))924 );925 }926 }927928 return globs;929};930931/** The lint sources a repo's lint configs name, and where they stand. */932interface LintSources {933 /** Each plugin's own path, for its rule fixtures. */934 readonly anchors: readonly string[];935 readonly globs: readonly string[];936 readonly notes: readonly string[];937}938939/**940 * Every lint config's plugins and imports, settled: relative paths, and941 * workspace packages by their folders (a package a lint config names is942 * lint source too). Then what those modules import, relatively.943 */944const lintSources = (945 contents: ReadonlyMap<string, string>,946 paths: ReadonlySet<string>,947 workspaces: ReadonlyMap<string, string>948): LintSources => {949 const configs = [...paths].filter(isLintConfig).toSorted();950951 const named = configs.map((path) => {952 const names = lintNames({ content: contents.get(path) ?? "", path });953954 const targets = [...names.plugins, ...names.imports].flatMap((specifier) =>955 isRelative(specifier)956 ? Option.toArray(join(dirname(path), specifier))957 : Option.toArray(958 Option.flatMap(959 inWorkspace(specifier, workspaces),960 ({ dir, rest }) => join(dir, rest)961 )962 )963 );964965 return {966 notes: names.notes,967 settled: targets.map((target) => settle(target, paths)),968 };969 });970971 const settled = named.flatMap((config) => config.settled);972 const files = settled.flatMap((target) => Option.toArray(target.file));973974 return {975 anchors: settled.map((target) => target.anchor),976 globs: [977 ...settled.flatMap((target) => target.globs),978 ...walkImports(files, contents, paths),979 ],980 notes: named.flatMap((config) => config.notes),981 };982};983984// A whole folder (`a/b/**`) the closure holds makes any other glob or path985// under it redundant.986const withoutCovered = (globs: readonly string[]): readonly string[] => {987 const folders = globs.flatMap((glob) =>988 glob.endsWith("/**") && !glob.slice(0, -3).includes("*")989 ? [glob.slice(0, -2)]990 : []991 );992993 return globs.filter(994 (glob) =>995 !folders.some(996 (folder) => glob !== `${folder}**` && glob.startsWith(folder)997 )998 );999};10001001const FIXTURE_FOLDERS = ["__fixtures__", "test", "tests"];10021003const TEST_FILE =1004 /(?:^|\/)(?:__fixtures__|__tests__|tests?)\/|\.(?:spec|test)\.[cm]?[jt]sx?$/u;10051006// A path without its file's extension: `lint/plugin.mjs` is `lint/plugin`.1007const stemOf = (path: string) =>1008 hasExtension(path) ? path.slice(0, path.lastIndexOf(".")) : path;10091010/** A plugin as a test can name it: its folder, or its file with or without extension. */1011interface PluginName {1012 readonly folder: boolean;1013 readonly path: string;1014}10151016const namesPlugin = (candidate: string, plugin: PluginName) =>1017 plugin.folder1018 ? candidate === plugin.path || candidate.startsWith(`${plugin.path}/`)1019 : stemOf(candidate) === stemOf(plugin.path);10201021// The paths a string in a test at `from` can mean: relative to the test,1022// and, for `./x` or a bare path, from the repo root (a config written inline).1023const readingsOf = (from: string, text: string): readonly string[] => {1024 if (text.startsWith("../")) {1025 return Option.toArray(join(dirname(from), text));1026 }10271028 const rooted = withoutDotSlash(text);10291030 return text.startsWith("./")1031 ? [...Option.toArray(join(dirname(from), text)), rooted]1032 : [rooted];1033};10341035/**1036 * The rule fixture tests of local lint plugins: the `test/`, `tests/` and1037 * `__fixtures__/` folders beside each plugin (beside a plugin file, or beside1038 * a plugin's folder; never at the repo root, where they hold the project's1039 * own tests), any `*-rule.test.*`, and every test file whose text names a1040 * plugin's path, by import or as a string from the root. Plugins are given1041 * as their entry files (an `index.*` stands for its folder) or folders.1042 */1043export const ruleFixtures = (1044 pluginPaths: readonly string[],1045 files: readonly string[],1046 contents: ReadonlyMap<string, string>1047): readonly Glob[] => {1048 const plugins = pluginPaths.map((plugin): PluginName =>1049 isIndex(plugin)1050 ? { folder: true, path: dirname(plugin) }1051 : {1052 folder: files.some((path) => path.startsWith(`${plugin}/`)),1053 path: plugin,1054 }1055 );10561057 // A plugin's folder sits beside its fixtures as a plugin file does.1058 const beside = plugins.flatMap((plugin) => {1059 const folder = dirname(plugin.path);10601061 return folder === ""1062 ? []1063 : FIXTURE_FOLDERS.map((name) => `${folder}/${name}/**`);1064 });10651066 // Cheap first: a test that never spells a plugin's last name can't name it.1067 const lastNames = plugins.map((plugin) => basename(stemOf(plugin.path)));10681069 const naming = files.filter((path) => {1070 const content = contents.get(path) ?? "";10711072 return (1073 TEST_FILE.test(path) &&1074 lastNames.some((name) => content.includes(name)) &&1075 tokensOf(content).some(1076 (token) =>1077 token.kind === "string" &&1078 readingsOf(path, token.text).some((reading) =>1079 plugins.some((plugin) => namesPlugin(reading, plugin))1080 )1081 )1082 );1083 });10841085 const named =1086 plugins.length === 0 ? [] : ["**/*-rule.spec.*", "**/*-rule.test.*"];10871088 return withoutCovered([...new Set([...beside, ...named, ...naming])])1089 .toSorted()1090 .map((glob) => Glob.make(glob));1091};10921093// Keys whose strings a hook manager runs: Claude Code, Cursor, Codex and1094// Gemini's `command` (with `args`), Copilot's `bash` and `powershell`,1095// lefthook's `run` and `script`, pre-commit's `entry`.1096const COMMAND_KEYS = new Set([1097 "args",1098 "bash",1099 "command",1100 "commands",1101 "entry",1102 "powershell",1103 "run",1104 "script",1105]);11061107// Every string under a command key, at any depth of a JSON or YAML value.1108const commandsIn = (1109 value: Schema.Json,1110 underKey: boolean1111): readonly string[] => {1112 if (Predicate.isString(value)) {1113 return underKey ? [value] : [];1114 }11151116 if (isJsonArray(value)) {1117 return value.flatMap((item) => commandsIn(item, underKey));1118 }11191120 return isJsonObject(value)1121 ? Object.entries(value).flatMap(([key, item]) =>1122 commandsIn(item, COMMAND_KEYS.has(key))1123 )1124 : [];1125};11261127const decodeAnyJson = Schema.decodeUnknownOption(Schema.Json);11281129// YAML that `yaml` can't parse, or that holds a value JSON can't, is None.1130const decodeYaml = (text: string): Option.Option<Schema.Json> =>1131 Option.flatten(1132 Option.liftThrowable((source: string) =>1133 decodeAnyJson(parse(source, { logLevel: "error", strict: false }))1134 )(text)1135 );11361137/** What one hook config runs, as command lines, and why it could not be read. */1138interface HookCommands {1139 readonly commands: readonly string[];1140 readonly notes: readonly string[];1141}11421143const unreadable = (path: string, reason: string): HookCommands => ({1144 commands: [],1145 notes: [note(path, reason)],1146});11471148/**1149 * The commands a hook config runs: the strings under command keys of a JSON1150 * (JSONC) or YAML config, the strings of a TOML config or a code plugin, and1151 * every line of a shell hook. Other files (a README) run nothing.1152 */1153const hookCommands = (hook: RepoFile): HookCommands => {1154 const { content, path } = hook;11551156 if (/\.jsonc?$/u.test(path)) {1157 return Option.match(decodeJsonc(content), {1158 onNone: () => unreadable(path, UNREADABLE),1159 onSome: (json) => ({ commands: commandsIn(json, false), notes: [] }),1160 });1161 }11621163 if (/\.ya?ml$/u.test(path)) {1164 return Option.match(decodeYaml(content), {1165 onNone: () => unreadable(path, "not YAML; the walk stops here"),1166 onSome: (yaml) => ({ commands: commandsIn(yaml, false), notes: [] }),1167 });1168 }11691170 if (CODE.test(path) || path.endsWith(".toml")) {1171 return {1172 commands: tokensOf(1173 content,1174 path.endsWith(".toml") ? hashCommentEnd : commentEnd1175 )1176 .filter((token) => token.kind === "string")1177 .map((token) => token.text),1178 notes: [],1179 };1180 }11811182 return { commands: isShell(path) ? content.split("\n") : [], notes: [] };1183};11841185/**1186 * The hook configs among the files, the scripts their commands name, and1187 * what those scripts and code plugins (pi, OpenCode, Amp) import.1188 */1189const hookSources = (1190 contents: ReadonlyMap<string, string>,1191 paths: ReadonlySet<string>,1192 sorted: readonly string[]1193) => {1194 const configs = sorted.filter((path) =>1195 hookConfigGlobs.some((glob) => matchGlob(glob, path))1196 );11971198 const read = configs.map((path) =>1199 hookCommands({ content: contents.get(path) ?? "", path })1200 );12011202 const scripts = commandScripts(1203 read.flatMap((hook) => hook.commands),1204 paths1205 );12061207 const code = configs.filter((path) => CODE.test(path));12081209 return {1210 globs: [...scripts, ...walkImports([...scripts, ...code], contents, paths)],1211 notes: read.flatMap((hook) => hook.notes),1212 };1213};12141215const SCRIPTS = "#/scripts";12161217/**1218 * A judge closure as data, the shape `Policy.judge` stores: globs (a `!` glob
1 unmodified line
1220 */1221export interface JudgeClosure {1222 readonly paths: readonly Glob[];1223 readonly pointers: readonly string[];1224 /** Where the walk stopped early (a file that isn't JSONC, one not read), and why. */1225 readonly notes?: readonly string[];1226}12271228/**249 * The judge closure for a run block over a repo's files: the defaults, every250 * existing file a run command names (`./test.sh` → `test.sh`), each tsconfig's251 * `extends` chain, and each `package.json`'s scripts as a pointer. Its shape1229 * What the scripts run commands name import and run in turn, inside each1230 * script's own folder only: a check script's helpers sit beside it, while1231 * what it imports from elsewhere is the product it checks, which an answer1232 * must stay free to change. A script at the root follows nothing.1233 */1234const checkScripts = (1235 scripts: readonly string[],1236 contents: ReadonlyMap<string, string>,1237 paths: ReadonlySet<string>1238): readonly string[] =>1239 scripts.flatMap((script) => {1240 const folder = dirname(script);12411242 return folder === ""1243 ? []1244 : walkImports([script], contents, paths, (path) =>1245 path.startsWith(`${folder}/`)1246 );1247 });12481249/**1250 * The judge closure for a run block over a repo's files: the defaults (the1251 * policy files and every hook config among them); every file a run command1252 * names (`./test.sh` → `test.sh`) and what it imports or runs from its own1253 * folder; every script a hook command names, with all it imports or runs;1254 * each tsconfig's `extends` chain; every lint plugin and module a lint config1255 * loads, with what it imports and its rule fixture tests; and each1256 * `package.json`'s scripts as a pointer. Manifests, lockfiles and dependency1257 * lists stay editable. Files are read as text, never run; one that doesn't1258 * parse is still judged, and `notes` says where the walk stopped. Its shape1259 * is `@repo/rules`' `Finishers.judgeClosure`, so the platform passes it in.1260 */1261export const judgeClosure = (1262 run: RunBlock,
2 unmodified lines
1265 const contents = new Map(1266 files.map((file) => [withoutDotSlash(file.path), file.content])1267 );12681269 const paths = new Set(contents.keys());1270 const sorted = [...paths].toSorted();1271 const workspaces = workspacesOf(contents);12721273 const commands = [1274 run.setup,1275 run.doctor,1276 run.test,1277 ...Object.values(run.checks),1278 ].filter(Predicate.isNotUndefined);1279269 // A `package.json` a command names stays editable: only its scripts judge.270 const named = commands271 .flatMap(wordsOf)272 .filter((word) => contents.has(word) && !isPackageJson(word));1280 const named = commandScripts(commands, paths);1281274 const chains = [...contents.keys()]275 .filter((path) => matchGlob("**/tsconfig*.json", path))276 .flatMap((path) => extendsChain(path, contents));1282 const chains = sorted.flatMap((path) =>1283 matchGlob("**/tsconfig*.json", path)1284 ? [chainFrom(path, contents, workspaces)]1285 : []1286 );12871288 const lint = lintSources(contents, paths, workspaces);1289 const hooks = hookSources(contents, paths, sorted);12901291 const derived = [1292 ...named,1293 ...checkScripts(named, contents, paths),1294 ...hooks.globs,1295 ...chains.flatMap(({ chain }) => chain.slice(1)),1296 ...lint.globs,1297 ...ruleFixtures(lint.anchors, sorted, contents),1298 ];12991300 const defaults = new Set<string>(defaultJudgeGlobs);1301280 const added = [...new Set([...named, ...chains])]281 .filter((path) => !defaults.has(path))1302 const added = withoutCovered([...new Set(derived)])1303 .filter((path) => !defaults.has(path) && !isDependencyFile(path))1304 .toSorted()1305 .map((path) => Glob.make(path));1306285 const packages = [...contents.keys()].filter(isPackageJson).toSorted();1307 const packages = sorted.filter(isPackageJson);13081309 const pointers = [1310 ...packages.filter((path) => path === "package.json"),1311 ...packages.filter((path) => path !== "package.json"),1312 ].map((path) => `${path}${SCRIPTS}`);1313292 return { paths: [...defaultJudgeGlobs, ...added], pointers };293};1314 const notes = [1315 ...new Set([1316 ...chains.flatMap((walk) => walk.notes),1317 ...lint.notes,1318 ...hooks.notes,1319 ]),1320 ].toSorted();1321295const decodeJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));1322 const closure = { paths: [...defaultJudgeGlobs, ...added], pointers };1323297const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>298 Predicate.isObject(value);1324 return notes.length === 0 ? closure : { ...closure, notes };1325};13261327// RFC 6901: `/a~1b` is the key `a/b`; `~0` is `~`.1328const pointerTokens = (pointer: string): readonly string[] =>1329 pointer === ""
2 unmodified lines
1332 .slice(1)1333 .split("/")1334 .map((token) => token.replaceAll("~1", "/").replaceAll("~0", "~"));1335309const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>310 Array.isArray(value);3111336// One step down a JSON value: an object's own key, or an array's index.1337const childAt = (1338 value: Schema.Json,1339 token: string
61 unmodified lines
modified:packages/checks/test/judge.test.ts+767 added-2 removed
1import { NodeServices } from "@effect/platform-node";1import { describe, expect, it } from "@effect/vitest";2import { describe, expect, it, layer } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { Command } from "@repo/protocol/domain/common";5import type { RunBlock } from "@repo/protocol/domain/run";5import { LaneName } from "@repo/protocol/ids";6import { LaneName, RepoPath } from "@repo/protocol/ids";7import { gitOk } from "@repo/testkit/git";8import { Context, Effect, FileSystem, Layer, Path } from "effect";910import type { RepoFile } from "../src/finder.ts";11import {12 commandScripts,13 defaultJudgeGlobs,14 eslintLocalPlugins,15 isJudged,16 jsPluginSpecifiers,17 judgeClosure,18 matchGlob,19 ruleFixtures,20 touchedPointers,21 tsconfigChain,22} from "../src/judge.ts";23import type { JudgeClosure } from "../src/judge.ts";2425const file = (path: string, content = ""): RepoFile => ({ content, path });2627/** A fence-shaped monorepo: root scripts, a tsconfig chain, a lint config, a hook config. */
98 unmodified lines
126127 it("gives the same closure for the same files in any order", () => {128 expect(judgeClosure(run, fence.toReversed())).toStrictEqual(closure);129 });130131 it("walks a check script's own folder, never into the product it checks", () => {132 const judge = judgeClosure(133 {134 checks: {135 [LaneName.make("api")]: Command.make("bun scripts/check-api.ts"),136 [LaneName.make("unit")]: Command.make("bun test test/parse.test.ts"),137 [LaneName.make("root")]: Command.make("node check.mjs"),138 },139 test: Command.make("bun test {path}"),140 },141 [142 file(143 "scripts/check-api.ts",144 'import * as api from "../src/index.ts";\nimport { snap } from "./lib/snap.ts";'145 ),146 file("scripts/lib/snap.ts"),147 file(148 "test/parse.test.ts",149 'import { parse } from "../src/parse.ts";\nimport { cases } from "./cases.ts";'150 ),151 file("test/cases.ts"),152 file("check.mjs", 'import "./src/parse.ts";'),153 file("src/index.ts", 'export * from "./parse.ts";'),154 file("src/parse.ts"),155 ]156 );157158 expect(159 [160 "scripts/check-api.ts",161 "scripts/lib/snap.ts",162 "test/parse.test.ts",163 "test/cases.ts",164 "check.mjs",165 "src/index.ts",166 "src/parse.ts",167 ].filter((path) => isJudged(judge, path))168 ).toStrictEqual([169 "scripts/check-api.ts",170 "scripts/lib/snap.ts",171 "test/parse.test.ts",172 "test/cases.ts",173 "check.mjs",174 ]);175 });176});177178describe(isJudged, () => {179 it.each([
97 unmodified lines
277 ).toStrictEqual([]);278 });279});280281const contentsOf = (...files: readonly RepoFile[]) =>282 new Map(files.map((one) => [one.path, one.content]));283284describe(tsconfigChain, () => {285 it("follows a three-level chain written as JSONC, from a package to the root", () => {286 const files = contentsOf(287 file(288 "packages/a/tsconfig.json",289 '{\n // the package\n "extends": "../../tsconfig.lib.json",\n}\n'290 ),291 file(292 "tsconfig.lib.json",293 '{ "extends": "./tsconfig.base.json", /* the library */ }'294 ),295 file(296 "tsconfig.base.json",297 '{ "$schema": "https://json.schemastore.org/tsconfig", "compilerOptions": { "strict": true, }, }'298 )299 );300301 expect(302 tsconfigChain(RepoPath.make("packages/a/tsconfig.json"), files)303 ).toStrictEqual({304 chain: [305 "packages/a/tsconfig.json",306 "tsconfig.lib.json",307 "tsconfig.base.json",308 ],309 notes: [],310 });311 });312313 it("follows every entry of an array extends, and a package extends is not a path", () => {314 const files = contentsOf(315 file(316 "tsconfig.json",317 JSON.stringify({ extends: ["./a.json", "@tsconfig/node24", "./b"] })318 ),319 file("a.json", JSON.stringify({ extends: "./b.json" })),320 file("b.json", JSON.stringify({ extends: "./a.json" }))321 );322323 expect(tsconfigChain(RepoPath.make("tsconfig.json"), files)).toStrictEqual({324 chain: ["tsconfig.json", "a.json", "b.json"],325 notes: [],326 });327 });328329 it("finds a workspace package's config by the package's folder", () => {330 const files = contentsOf(331 file(332 "apps/web/tsconfig.json",333 JSON.stringify({ extends: "@repo/typescript-config/nextjs.json" })334 ),335 file(336 "packages/typescript-config/package.json",337 JSON.stringify({ name: "@repo/typescript-config" })338 ),339 file(340 "packages/typescript-config/nextjs.json",341 JSON.stringify({ extends: "./base.json" })342 ),343 file("packages/typescript-config/base.json", "{}")344 );345346 expect(347 tsconfigChain(RepoPath.make("apps/web/tsconfig.json"), files).chain348 ).toStrictEqual([349 "apps/web/tsconfig.json",350 "packages/typescript-config/nextjs.json",351 "packages/typescript-config/base.json",352 ]);353 });354355 it("stops at a malformed file, keeps it in the chain, and says why", () => {356 const files = contentsOf(357 file("tsconfig.json", JSON.stringify({ extends: "./broken.json" })),358 file("broken.json", '{ "extends": "./never.json"')359 );360361 expect(tsconfigChain(RepoPath.make("tsconfig.json"), files)).toStrictEqual({362 chain: ["tsconfig.json", "broken.json"],363 notes: [364 "broken.json: not JSON, even with comments and trailing commas removed; the walk stops here",365 ],366 });367 });368369 it("keeps a target it was not given, named as tsc would read it", () => {370 const files = contentsOf(371 file("tsconfig.json", JSON.stringify({ extends: "./configs/strict" }))372 );373374 expect(tsconfigChain(RepoPath.make("tsconfig.json"), files)).toStrictEqual({375 chain: ["tsconfig.json", "configs/strict.json"],376 notes: ["configs/strict.json: not among the files read; judged unread"],377 });378 });379});380381describe("the judge closure over tsconfig chains", () => {382 it("judges every file of a three-level and an array chain, and no package", () => {383 const judge = judgeClosure(run, [384 file(385 "packages/a/tsconfig.json",386 '{ "extends": "../../configs/lib.json", }'387 ),388 file("configs/lib.json", '{ "extends": "./base" /* tsc adds .json */ }'),389 file("configs/base.json", "{}"),390 file(391 "tsconfig.json",392 JSON.stringify({393 extends: ["./a.json", "./b.json", "@tsconfig/node24"],394 })395 ),396 file("a.json", "{}"),397 file("b.json", "{}"),398 file("c.json", "{}"),399 ]);400401 expect(402 [403 "configs/lib.json",404 "configs/base.json",405 "a.json",406 "b.json",407 "c.json",408 ].filter((path) => isJudged(judge, path))409 ).toStrictEqual([410 "configs/lib.json",411 "configs/base.json",412 "a.json",413 "b.json",414 ]);415 expect(416 judge.paths.filter((glob) => glob.includes("@tsconfig"))417 ).toStrictEqual([]);418 expect(judge.notes).toBeUndefined();419 });420});421422describe(jsPluginSpecifiers, () => {423 it("reads an .oxlintrc.json's jsPlugins, strings and objects, from its folder; a package name is no path", () => {424 expect(425 jsPluginSpecifiers(426 file(427 "packages/web/.oxlintrc.json",428 `{429 // local rules first430 "jsPlugins": [431 "./lint/plugin.mjs",432 "eslint-plugin-foo",433 { "name": "shared", "specifier": "../../tools/shared/index.js" },434 ],435 }`436 )437 )438 ).toStrictEqual(["packages/web/lint/plugin.mjs", "tools/shared/index.js"]);439 });440441 it("scans an oxlint.config.ts's jsPlugins array as text, skipping comments", () => {442 const config = `import { defineConfig } from "oxlint";443 export default defineConfig({444 jsPlugins: [445 { name: "anti-slop", specifier: "./tools/oxlint/anti-slop/index.ts" },446 // { name: "old", specifier: "./tools/oxlint/old/index.ts" },447 { name: "fence", specifier: "./tools/oxlint/fence/index.ts" },448 "oxlint-plugin-package",449 ],450 rules: { "fence/rule": "error" },451 });`;452453 expect(jsPluginSpecifiers(file("oxlint.config.ts", config))).toStrictEqual([454 "tools/oxlint/anti-slop/index.ts",455 "tools/oxlint/fence/index.ts",456 ]);457 });458459 it("reads a jsPlugins array the config assigns to a variable first", () => {460 const config = `const jsPlugins = ["./lint/plugin.mjs", "oxlint-plugin-package"];461 export default defineConfig({ jsPlugins });`;462463 expect(jsPluginSpecifiers(file("oxlint.config.ts", config))).toStrictEqual([464 "lint/plugin.mjs",465 ]);466 });467468 it("finds nothing in a malformed .oxlintrc.json", () => {469 expect(470 jsPluginSpecifiers(file(".oxlintrc.json", '{ "jsPlugins": ["./a.mjs"'))471 ).toStrictEqual([]);472 });473});474475describe(eslintLocalPlugins, () => {476 it("names every relative module an eslint config imports or requires", () => {477 const config = `import js from "@eslint/js";478 import local from "./eslint/rules/index.js";479 // import gone from "./eslint/gone.js";480 const base = require("../shared/eslint-base.cjs");481 export default [js.configs.recommended, local, base];`;482483 expect(484 eslintLocalPlugins(file("web/eslint.config.js", config))485 ).toStrictEqual(["web/eslint/rules/index.js", "shared/eslint-base.cjs"]);486 });487});488489describe("the judge closure over lint plugins", () => {490 const oxlintRun: RunBlock = {491 checks: { [LaneName.make("lint")]: Command.make("oxlint") },492 test: Command.make("vitest run {path}"),493 };494495 it("judges an oxlint plugin's source, what it imports and its fixture folders, never a package plugin", () => {496 const judge = judgeClosure(oxlintRun, [497 file(498 ".oxlintrc.json",499 JSON.stringify({500 jsPlugins: ["./lint/plugin.mjs", "eslint-plugin-foo"],501 })502 ),503 file("lint/plugin.mjs", 'import rule from "./rules/no-foo.mjs";'),504 file("lint/rules/no-foo.mjs", "export default {};"),505 file("lint/test/plugin.test.mjs"),506 file("lint/tests/cases.json"),507 file("lint/__fixtures__/bad.js"),508 file("lint/notes.md"),509 file("src/a.ts"),510 ]);511512 expect(513 [514 "lint/plugin.mjs",515 "lint/rules/no-foo.mjs",516 "lint/test/plugin.test.mjs",517 "lint/tests/cases.json",518 "lint/__fixtures__/bad.js",519 "lint/notes.md",520 "src/a.ts",521 ].filter((path) => isJudged(judge, path))522 ).toStrictEqual([523 "lint/plugin.mjs",524 "lint/rules/no-foo.mjs",525 "lint/test/plugin.test.mjs",526 "lint/tests/cases.json",527 "lint/__fixtures__/bad.js",528 ]);529 expect(530 judge.paths.filter((glob) => glob.includes("eslint-plugin-foo"))531 ).toStrictEqual([]);532 });533534 it("judges an eslint config's local plugin folder whole, and a workspace lint package", () => {535 const judge = judgeClosure(oxlintRun, [536 file(537 "eslint.config.js",538 'import local from "./eslint/rules/index.js";\nimport shared from "@repo/eslint-config/base";'539 ),540 file("eslint/rules/index.js", 'export * from "./no-bar.js";'),541 file("eslint/rules/no-bar.js"),542 file(543 "packages/eslint-config/package.json",544 JSON.stringify({ name: "@repo/eslint-config" })545 ),546 file("packages/eslint-config/base.js"),547 ]);548549 expect(judge.paths).toContain("eslint/rules/**");550 expect(isJudged(judge, "eslint/rules/no-bar.js")).toBeTruthy();551 expect(isJudged(judge, "packages/eslint-config/base.js")).toBeTruthy();552 });553554 it("judges a malformed .oxlintrc.json and says why the walk stopped there", () => {555 const judge = judgeClosure(oxlintRun, [556 file(".oxlintrc.json", '{ "jsPlugins": ["./lint/plugin.mjs"'),557 file("tsconfig.json", "{ broken"),558 ]);559560 expect(isJudged(judge, ".oxlintrc.json")).toBeTruthy();561 expect(isJudged(judge, "tsconfig.json")).toBeTruthy();562 expect(judge.notes).toStrictEqual([563 ".oxlintrc.json: not JSON, even with comments and trailing commas removed; the walk stops here",564 "tsconfig.json: not JSON, even with comments and trailing commas removed; the walk stops here",565 ]);566 });567});568569describe(ruleFixtures, () => {570 const tree = contentsOf(571 file("tools/lint/index.ts", 'export * from "./rules/no-x.ts";'),572 file("tools/lint/rules/no-x.ts"),573 file("tools/test/no-x.test.ts"),574 file("lint/plugin.mjs"),575 file("lint/test/plugin.test.mjs", 'import plugin from "../plugin.mjs";'),576 file(577 "packages/config/test/lint-rules.test.ts",578 'import { rule } from "../../../tools/lint/rules/no-x.ts";'579 ),580 file(581 "packages/config/test/wiring.test.ts",582 'const plugin = { name: "local", specifier: "./lint/plugin.mjs" };'583 ),584 file(585 "packages/config/test/paths.ts",586 'export const fixtures = "tools/lint/fixtures";'587 ),588 file("packages/a/test/no-sort-rule.test.ts"),589 file(590 "packages/a/test/a.test.ts",591 'import "../lint/plugin.mjs";\nconst other = "eslint/plugin.mjs";\nconst near = "tools/linter/x.ts";'592 ),593 file(594 "packages/a/src/uses-lint.ts",595 'import "../../../tools/lint/index.ts";'596 )597 );598599 it("names the folders beside each plugin, *-rule tests, and every test that names a plugin", () => {600 expect(601 ruleFixtures(602 [603 RepoPath.make("tools/lint/index.ts"),604 RepoPath.make("lint/plugin.mjs"),605 ],606 [...tree.keys()].map((path) => RepoPath.make(path)),607 tree608 )609 ).toStrictEqual([610 "**/*-rule.spec.*",611 "**/*-rule.test.*",612 "lint/__fixtures__/**",613 "lint/test/**",614 "lint/tests/**",615 "packages/config/test/lint-rules.test.ts",616 "packages/config/test/paths.ts",617 "packages/config/test/wiring.test.ts",618 "tools/__fixtures__/**",619 "tools/test/**",620 "tools/tests/**",621 ]);622 });623624 it("names nothing when the repo has no local plugin", () => {625 expect(626 ruleFixtures(627 [],628 [...tree.keys()].map((path) => RepoPath.make(path)),629 tree630 )631 ).toStrictEqual([]);632 });633});634635describe(commandScripts, () => {636 it("names the tracked files commands run, through quotes and a project-dir variable", () => {637 const tracked = new Set([638 "scripts/hooks/x.ts",639 ".husky/y.mjs",640 ".claude/hooks/stop.sh",641 "scripts/pre-push.sh",642 "package.json",643 "bun.lock",644 "requirements-dev.txt",645 ]);646647 expect(648 commandScripts(649 [650 `bun "\${CLAUDE_PROJECT_DIR}/scripts/hooks/x.ts"`,651 "node .husky/y.mjs --strict",652 '"$CLAUDE_PROJECT_DIR"/.claude/hooks/stop.sh',653 "bash $(git rev-parse --show-toplevel)/scripts/pre-push.sh",654 "bun run lint",655 "jq .scripts package.json && cat bun.lock",656 "pip install -r requirements-dev.txt",657 ],658 tracked659 )660 ).toStrictEqual([661 ".claude/hooks/stop.sh",662 ".husky/y.mjs",663 "scripts/hooks/x.ts",664 "scripts/pre-push.sh",665 ]);666 });667});668669describe("the judge closure over harness hooks", () => {670 const hooks: readonly RepoFile[] = [671 file(672 ".codex/hooks.json",673 JSON.stringify({674 hooks: {675 PreToolUse: [676 { hooks: [{ command: "bun scripts/hooks/x.ts", type: "command" }] },677 ],678 },679 })680 ),681 file(682 ".codex/config.toml",683 '# The Stop hook reads src/*.ts (Codex\'s own)\n[[hooks.Stop]]\ncommand = "bash tools/stop.sh"\n'684 ),685 file(686 ".github/hooks/policy.json",687 JSON.stringify({688 hooks: {689 preToolUse: [690 {691 bash: "./tools/guard.sh",692 powershell: "tools/guard.ps1",693 type: "command",694 },695 ],696 },697 version: 1,698 })699 ),700 file(".github/copilot/settings.json", "{}"),701 file(702 ".gemini/settings.json",703 JSON.stringify({704 hooks: {705 BeforeTool: [706 {707 hooks: [708 {709 args: ["tools/gemini-guard.mjs"],710 command: "node",711 type: "command",712 },713 ],714 },715 ],716 },717 })718 ),719 file(720 ".opencode/plugins/guard.ts",721 'import { decide } from "../../scripts/hooks/lib/policy.ts";\nexport const guard = "bun tools/opencode.ts";'722 ),723 file(".amp/plugins/guard.ts"),724 file(725 ".claude/settings.local.json",726 `{727 // this machine's own728 "hooks": { "Stop": [{ "hooks": [{ "type": "command", "command": "\\"$CLAUDE_PROJECT_DIR\\"/.claude/hooks/stop.sh" }] }] },729 "permissions": { "allow": ["Read(src/a.ts)"] },730 }`731 ),732 file(".husky/pre-commit", "node .husky/y.mjs\nbun run lint\n"),733 file(".husky/y.mjs"),734 file(735 "lefthook.yml",736 "pre-push:\n commands:\n guard:\n run: bash scripts/pre-push.sh\n"737 ),738 file(739 ".pre-commit-config.yaml",740 "repos:\n - repo: local\n hooks:\n - id: guard\n entry: tools/pre-commit.sh\n"741 ),742 file(".lefthook/pre-commit/check.sh"),743 file(".pi/extensions/guard/README.md", "Runs src/b.ts on every edit."),744 file("scripts/hooks/x.ts", 'import { decide } from "./lib/policy.ts";'),745 file("scripts/hooks/lib/policy.ts"),746 file("scripts/pre-push.sh", "#!/bin/sh\nbun scripts/hooks/push.ts\n"),747 file("scripts/hooks/push.ts", 'import "./lib/push-rules.ts";'),748 file("scripts/hooks/lib/push-rules.ts"),749 ...[750 "tools/stop.sh",751 "tools/guard.sh",752 "tools/guard.ps1",753 "tools/gemini-guard.mjs",754 "tools/opencode.ts",755 "tools/pre-commit.sh",756 ".claude/hooks/stop.sh",757 "tools/unrelated.sh",758 "src/a.ts",759 "src/b.ts",760 ].map((path) => file(path)),761 ];762763 const judge = judgeClosure(run, hooks);764765 it.each([766 ".codex/hooks.json",767 ".codex/config.toml",768 ".github/hooks/policy.json",769 ".github/copilot/settings.json",770 ".gemini/settings.json",771 ".opencode/plugins/guard.ts",772 ".amp/plugins/guard.ts",773 ".claude/settings.local.json",774 ".lefthook/pre-commit/check.sh",775 ])("%s is a hook config, and judged", (path) => {776 expect(isJudged(judge, path)).toBeTruthy();777 });778779 it("judges the scripts each hook command names, what they import and what they run", () => {780 expect(781 [782 "scripts/hooks/x.ts",783 "scripts/hooks/lib/policy.ts",784 "scripts/hooks/push.ts",785 "scripts/hooks/lib/push-rules.ts",786 "tools/stop.sh",787 "tools/guard.sh",788 "tools/guard.ps1",789 "tools/gemini-guard.mjs",790 "tools/opencode.ts",791 "tools/pre-commit.sh",792 ".claude/hooks/stop.sh",793 "scripts/pre-push.sh",794 ".husky/y.mjs",795 ].filter((path) => !isJudged(judge, path))796 ).toStrictEqual([]);797 });798799 it("leaves alone files a hook config names outside a command", () => {800 expect(801 ["src/a.ts", "src/b.ts", "tools/unrelated.sh"].filter((path) =>802 isJudged(judge, path)803 )804 ).toStrictEqual([]);805 });806});807808describe("the judge closure over workspace and task-runner policy", () => {809 const python: RunBlock = {810 checks: { [LaneName.make("unit")]: Command.make("pytest") },811 setup: Command.make(812 "pip install -r requirements.txt -c constraints.txt && bun install --frozen-lockfile"813 ),814 test: Command.make("pytest {path}"),815 };816817 const judge = judgeClosure(python, [818 file("requirements.txt", "pytest==9.0.0\n"),819 file("constraints.txt"),820 file("bun.lock"),821 file("src/a.ts"),822 ]);823824 it.each([825 ["bunfig.toml", true],826 ["packages/a/bunfig.toml", true],827 ["pnpm-workspace.yaml", true],828 ["turbo.json", true],829 ["packages/a/turbo.json", true],830 ["oxfmt.config.ts", true],831 [".oxfmtrc.json", true],832 ["biome.jsonc", true],833 [".prettierrc", true],834 ["prettier.config.mjs", true],835 ["nx.json", true],836 [".yarnrc.yml", true],837 ["vitest.e2e.config.ts", true],838 [".editorconfig", false],839 ["bun.lock", false],840 ["pnpm-lock.yaml", false],841 ["requirements.txt", false],842 ["constraints.txt", false],843 ["package.json", false],844 ["src/a.ts", false],845 ["README.md", false],846 [".env.local", false],847 ])("%s is judged: %s", (path, judged) => {848 expect(isJudged(judge, path)).toBe(judged);849 });850});851852// The platform reads no file above this size for the closure; here such a853// file keeps its path and is given with empty content.854const MAX_BYTES = 256 * 1024;855856/** This repo's tracked files, as `git ls-files` lists them, and its closure. */857class ThisRepo extends Context.Service<858 ThisRepo,859 { readonly closure: JudgeClosure; readonly tracked: readonly string[] }860>()("checks/test/ThisRepo") {}861862const thisRepo = Layer.effect(863 ThisRepo,864 Effect.gen(function* () {865 const fs = yield* FileSystem.FileSystem;866 const path = yield* Path.Path;867 // Vitest runs in the package's folder, two below the root.868 const root = path.resolve("..", "..");869870 const tracked = (yield* gitOk(root, "ls-files", "-z"))871 .split("\0")872 .filter((name) => name !== "");873874 const files = yield* Effect.forEach(875 tracked,876 (name) =>877 fs.readFileString(path.join(root, name)).pipe(878 Effect.map((content) =>879 file(name, content.length > MAX_BYTES ? "" : content)880 ),881 Effect.orElseSucceed(() => file(name))882 ),883 { concurrency: 16 }884 );885886 const verify: RunBlock = {887 checks: { [LaneName.make("verify")]: Command.make("bun run verify") },888 setup: Command.make("bun install --frozen-lockfile"),889 test: Command.make("bunx vitest run {path}"),890 };891892 return { closure: judgeClosure(verify, files), tracked };893 })894).pipe(Layer.provide(NodeServices.layer));895896layer(thisRepo, { excludeTestServices: true })(897 "the judge closure of this repo, as the fixture",898 (repo) => {899 repo.effect("holds the lint plugin folders its oxlint config loads", () =>900 Effect.gen(function* () {901 const { closure: judge } = yield* ThisRepo;902903 expect(judge.paths).toStrictEqual(904 expect.arrayContaining([905 "tools/oxlint/anti-slop/**",906 "tools/oxlint/fence/**",907 ])908 );909 })910 );911912 repo.effect(913 "holds the tsconfig base, the policy files and the hook configs",914 () =>915 Effect.gen(function* () {916 const { closure: judge } = yield* ThisRepo;917918 expect(judge.paths).toContain("tsconfig.base.json");919 expect(920 [921 "tsconfig.json",922 "tsconfig.base.json",923 "oxlint.config.ts",924 "oxlint.debt.config.ts",925 "oxfmt.config.ts",926 "turbo.json",927 "bunfig.toml",928 ".claude/settings.json",929 ".cursor/hooks.json",930 ].filter((path) => !isJudged(judge, path))931 ).toStrictEqual([]);932 })933 );934935 repo.effect(936 "holds every file of pi's extension, the hook scripts and the fence's fixtures",937 () =>938 Effect.gen(function* () {939 const { closure: judge, tracked } = yield* ThisRepo;940941 for (const folder of [942 ".pi/",943 "scripts/hooks/",944 "tools/oxlint/fence/fixtures/",945 ]) {946 const inside = tracked.filter((path) => path.startsWith(folder));947948 expect(inside.length).toBeGreaterThan(0);949 expect(950 inside.filter((path) => !isJudged(judge, path))951 ).toStrictEqual([]);952 }953 })954 );955956 repo.effect(957 "holds the rule fixture test that imports the fence's rules",958 () =>959 Effect.gen(function* () {960 const { closure: judge } = yield* ThisRepo;961962 expect(judge.paths).toContain(963 "packages/config/test/oxlint-fence.test.ts"964 );965 })966 );967968 repo.effect(969 "leaves the product's code, the manifest and the lockfile editable",970 () =>971 Effect.gen(function* () {972 const { closure: judge } = yield* ThisRepo;973974 expect(975 [976 "package.json",977 "bun.lock",978 "AGENTS.md",979 "packages/checks/src/finder.ts",980 "packages/protocol/src/refusal.ts",981 "apps/platform/src/surfaces.ts",982 "scripts/gen.ts",983 ].filter((path) => isJudged(judge, path))984 ).toStrictEqual([]);985 expect(judge.pointers).toContain("package.json#/scripts");986 })987 );988 }989);990991describe(matchGlob, () => {992 it.each([993 [".github/workflows/**", ".github/workflows/ci.yml", true],994 [".github/workflows/**", ".github/workflows/nested/x.yml", true],
28 unmodified lines