Skip to content
Myr

Merge build/205-checks-kinds-finder-judge: the platform finds a project's own commands and knows which files judge an answer

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

authored by oscabriel · committed by oscabriel · parents 84a8001, 5a542ac · Browse files · 7 files+2491 added−0 removed
This commit

State

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

Diff stats

7 files+2491 added−0 removed

  • tests:+923 added−0 removed
  • other:+1568 added−0 removed

7 files+2491 added−0 removed

added:packages/checks/src/finder.ts+1010 added
1/**2 * The command finder: a project's own commands (how to set up, how to run3 * one test file, and the lanes every answer must pass), read from the files4 * it already has: GitHub and Forgejo workflows, lefthook, husky, pre-commit5 * and `package.json` scripts. Pure: it reads the contents it is given and6 * runs nothing. A maintainer confirms what it finds at init.7 */8import type { RunBlock } from "@repo/protocol/domain/run";9import { LaneName } from "@repo/protocol/ids";10import { Array as Arr, Option, Result, Schema } from "effect";11import { parse } from "yaml";1213import { PATH_PLACEHOLDER } from "./kinds.ts";1415/** The run block as it travels before decoding. */16export type RunBlockEncoded = typeof RunBlock.Encoded;1718/** One file of a repo, by its path from the root. */19export interface RepoFile {20 readonly content: string;21 readonly path: string;22}2324/**25 * What the finder found: a partial run block, and where each part came from26 * (`checks.lint from .github/workflows/ci.yml`), plus every file it skipped27 * and why (`skipped <path>: <reason>`). The shape `@repo/rules`'28 * `Finishers.findRunBlock` takes.29 */30export interface FoundRunBlock {31 readonly run: Partial<RunBlockEncoded>;32 readonly sources: readonly string[];33}3435/** The lane names the finder prefers; any other lane takes its script's name. */36type Canonical = "build" | "format" | "lint" | "types" | "unit";3738const isLaneName = Schema.is(LaneName);3940const words = (command: string): readonly string[] =>41 command.trim().split(/\s+/u).filter(Boolean);4243const startsWith = (tokens: readonly string[], prefix: readonly string[]) =>44 prefix.every((word, index) => tokens[index] === word);4546const hasAny = (tokens: readonly string[], flags: readonly string[]) =>47 tokens.some((token) =>48 flags.some((flag) => token === flag || token.startsWith(`${flag}=`))49 );5051// --- What a command is --------------------------------------------------5253const SETUP: readonly (readonly string[])[] = [54 ["corepack", "enable"],55 ["npm", "ci"],56 ["npm", "install"],57 ["npm", "i"],58 ["pnpm", "install"],59 ["pnpm", "i"],60 ["yarn", "install"],61 ["bun", "install"],62 ["bun", "i"],63 ["pip", "install"],64 ["pip3", "install"],65 ["python", "-m", "pip", "install"],66 ["python3", "-m", "pip", "install"],67 ["uv", "sync"],68 ["uv", "pip", "install"],69 ["poetry", "install"],70 ["pipenv", "install"],71 ["pdm", "install"],72 ["go", "mod", "download"],73 ["cargo", "fetch"],74 ["bundle", "install"],75 ["pre-commit", "install-hooks"],76];7778// Leading `NAME=value` words set the environment; they aren't the command.79const withoutEnv = (tokens: readonly string[]) => {80 const first = tokens.findIndex((token) => !/^\w+=/u.test(token));8182 return first === -1 ? [] : tokens.slice(first);83};8485const isSetup = (command: string) => {86 const tokens = withoutEnv(words(command));8788 return (89 (tokens.length === 1 && tokens[0] === "yarn") ||90 SETUP.some((prefix) => startsWith(tokens, prefix))91 );92};9394// Words that run a tool rather than being one: `npx eslint`, `uv run pytest`.95const RUNNERS: readonly (readonly string[])[] = [96 ["npx"],97 ["bunx"],98 ["pnpm", "exec"],99 ["pnpm", "dlx"],100 ["yarn", "exec"],101 ["yarn", "dlx"],102 ["npm", "exec", "--"],103 ["npm", "exec"],104 ["uv", "run"],105 ["poetry", "run"],106 ["pipenv", "run"],107 ["pdm", "run"],108 ["hatch", "run"],109 ["python", "-m"],110 ["python3", "-m"],111 // pnpm and yarn run a package's binary by its bare name: `pnpm vitest`.112 ["pnpm"],113 ["yarn"],114];115116/** Where the tool starts in a command's words, past env and runner words. */117const toolIndex = (tokens: readonly string[]): number => {118 let at = tokens.length - withoutEnv(tokens).length;119120 for (121 let runner = RUNNERS.find((prefix) => startsWith(tokens.slice(at), prefix));122 runner !== undefined;123 runner = RUNNERS.find((prefix) => startsWith(tokens.slice(at), prefix))124 ) {125 at += runner.length;126 }127128 return at;129};130131const CHECK_FLAGS = ["--check", "-c", "--list-different", "-l"];132133/** A tool's words, the lane it checks, and whether these arguments check. */134const TOOLS: readonly {135 readonly lane: Canonical;136 readonly tool: readonly string[];137 readonly when?: (args: readonly string[]) => boolean;138}[] = [139 { lane: "unit", tool: ["vitest"] },140 { lane: "unit", tool: ["jest"] },141 { lane: "unit", tool: ["mocha"] },142 { lane: "unit", tool: ["ava"] },143 { lane: "unit", tool: ["bun", "test"] },144 { lane: "unit", tool: ["node", "--test"] },145 { lane: "unit", tool: ["deno", "test"] },146 { lane: "unit", tool: ["pytest"] },147 { lane: "unit", tool: ["go", "test"] },148 { lane: "unit", tool: ["cargo", "test"] },149 { lane: "unit", tool: ["zig", "build", "test"] },150 { lane: "lint", tool: ["eslint"] },151 { lane: "lint", tool: ["oxlint"] },152 { lane: "lint", tool: ["biome", "lint"] },153 { lane: "lint", tool: ["biome", "check"] },154 { lane: "lint", tool: ["biome", "ci"] },155 { lane: "lint", tool: ["ruff", "check"] },156 {157 lane: "format",158 tool: ["ruff", "format"],159 when: (args) => hasAny(args, CHECK_FLAGS),160 },161 // Bare `ruff` is `ruff check`; `ruff format` without `--check` rewrites.162 { lane: "lint", tool: ["ruff"], when: (args) => args[0] !== "format" },163 { lane: "lint", tool: ["flake8"] },164 { lane: "lint", tool: ["pylint"] },165 { lane: "lint", tool: ["golangci-lint"] },166 { lane: "lint", tool: ["go", "vet"] },167 { lane: "lint", tool: ["cargo", "clippy"] },168 { lane: "lint", tool: ["stylelint"] },169 { lane: "lint", tool: ["next", "lint"] },170 { lane: "lint", tool: ["deno", "lint"] },171 { lane: "lint", tool: ["shellcheck"] },172 {173 lane: "build",174 tool: ["tsc"],175 when: (args) => hasAny(args, ["-b", "--build"]),176 },177 { lane: "types", tool: ["tsc"] },178 { lane: "types", tool: ["tsgo"] },179 { lane: "types", tool: ["vue-tsc"] },180 { lane: "types", tool: ["mypy"] },181 { lane: "types", tool: ["pyright"] },182 { lane: "types", tool: ["basedpyright"] },183 { lane: "types", tool: ["deno", "check"] },184 {185 lane: "format",186 tool: ["prettier"],187 when: (args) => hasAny(args, CHECK_FLAGS),188 },189 {190 lane: "format",191 tool: ["oxfmt"],192 when: (args) => hasAny(args, ["--check"]),193 },194 {195 lane: "format",196 tool: ["biome", "format"],197 when: (args) => !hasAny(args, ["--write"]),198 },199 {200 lane: "format",201 tool: ["black"],202 when: (args) => hasAny(args, ["--check"]),203 },204 {205 lane: "format",206 tool: ["cargo", "fmt"],207 when: (args) => hasAny(args, ["--check"]),208 },209 { lane: "format", tool: ["gofmt"], when: (args) => hasAny(args, ["-l"]) },210 {211 lane: "format",212 tool: ["deno", "fmt"],213 when: (args) => hasAny(args, ["--check"]),214 },215 { lane: "build", tool: ["vite", "build"] },216 { lane: "build", tool: ["next", "build"] },217 { lane: "build", tool: ["tsup"] },218 { lane: "build", tool: ["tsdown"] },219 { lane: "build", tool: ["cargo", "build"] },220 { lane: "build", tool: ["go", "build"] },221 { lane: "build", tool: ["zig", "build"] },222];223224/** Script, task and hook names that say their lane outright. */225const NAMED: readonly { readonly lane: Canonical; readonly names: RegExp }[] = [226 { lane: "unit", names: /^(?:tests?|unit|tests?[:-](?:unit|ci))$/u },227 { lane: "lint", names: /^(?:lint|lint[:-](?:check|ci)|eslint|oxlint)$/u },228 {229 lane: "types",230 names:231 /^(?:types?|typecheck|type-check|tsc|(?:check[:-])types|types?[:-]check|typecheck[:-]ci)$/u,232 },233 {234 lane: "format",235 names: /^(?:(?:format|fmt|prettier)[:-]check|check[:-](?:format|fmt))$/u,236 },237 { lane: "build", names: /^build$/u },238];239240// Names that are never a check, even when a workflow runs them.241const NEVER_A_LANE =242 /(?:^|[:-])(?:dev|start|serve|preview|watch|deploy|release|publish|prepare|install|clean|version|fix|docs)(?:$|[:-])/u;243244const namedLane = (name: string): Option.Option<Canonical> =>245 Option.fromNullishOr(NAMED.find(({ names }) => names.test(name))?.lane);246247/** A name as a lane name: `test:e2e` → `test-e2e`. */248const asLaneName = (name: string): Option.Option<string> =>249 Option.liftPredicate(250 name.replaceAll(/[^A-Za-z0-9-]+/gu, "-").replaceAll(/^-+|-+$/gu, ""),251 isLaneName252 );253254/** A script or task's name as a lane, unless the name says it checks nothing. */255const scriptLane = (name: string): Option.Option<string> =>256 NEVER_A_LANE.test(name) ? Option.none() : asLaneName(name);257258const FIXERS = ["--fix", "--write"];259260/** Whether a command, or any command a script chains, rewrites files. */261const fixes = (body: string) =>262 body.split("&&").some((part) => hasAny(words(part), FIXERS));263264/** The lane a tool command checks: `npx eslint .` → `lint`. Fixers check nothing. */265const toolLane = (command: string): Option.Option<Canonical> => {266 const tokens = words(command);267 const rest = tokens.slice(toolIndex(tokens));268269 if (hasAny(rest, FIXERS)) {270 return Option.none();271 }272273 return Option.fromNullishOr(274 TOOLS.find(275 ({ tool, when }) =>276 startsWith(rest, tool) && (when?.(rest.slice(tool.length)) ?? true)277 )?.lane278 );279};280281// --- Scripts -------------------------------------------------------------282283type PackageManager = "bun" | "npm" | "pnpm" | "yarn";284285const MANAGERS: readonly PackageManager[] = ["bun", "npm", "pnpm", "yarn"];286287const isManager = (word: string | undefined): word is PackageManager =>288 MANAGERS.some((manager) => manager === word);289290/** What the repo's root `package.json` says: its scripts and package manager. */291interface Scripts {292 readonly byName: ReadonlyMap<string, string>;293 readonly manager: Option.Option<PackageManager>;294}295296/**297 * The script a command runs, if it runs one: `npm test`, `bun run lint`,298 * `pnpm typecheck` (a pnpm or yarn word that names a script).299 */300const scriptOf = (command: string, scripts: Scripts): Option.Option<string> => {301 const [manager, verb, name] = withoutEnv(words(command));302303 if (!isManager(manager)) {304 return Option.none();305 }306307 if (verb === "test" || verb === "t") {308 return manager === "bun" && verb === "test"309 ? Option.none()310 : Option.some("test");311 }312313 if ((verb === "run" || verb === "run-script") && name !== undefined) {314 return Option.some(name);315 }316317 return manager !== "npm" && verb !== undefined && scripts.byName.has(verb)318 ? Option.some(verb)319 : Option.none();320};321322// Task runners name a task the way a script is named: `make test`,323// `just lint`, `turbo run typecheck`; several turbo tasks make one lane.324const TASKS: readonly (readonly string[])[] = [325 ["make"],326 ["just"],327 ["task"],328 ["mise", "run"],329 ["turbo", "run"],330 ["turbo"],331];332333const taskOf = (command: string): Option.Option<string> => {334 const tokens = withoutEnv(words(command));335 const runner = TASKS.find((prefix) => startsWith(tokens, prefix)) ?? [];336337 const names = tokens338 .slice(runner.length)339 .filter((word) => !word.startsWith("-"));340341 return runner.length > 0 && names.length > 0342 ? Option.some(names.join("-"))343 : Option.none();344};345346const segments = (body: string) => body.split("&&").map((part) => part.trim());347348/** A script's body, followed through scripts that only run another script. */349const bodyOf = (350 name: string,351 scripts: Scripts,352 depth = 0353): Option.Option<string> =>354 Option.flatMap(Option.fromNullishOr(scripts.byName.get(name)), (body) => {355 const [only, ...more] = segments(body);356357 const inner =358 only === undefined || more.length > 0 || depth > 3359 ? Option.none()360 : scriptOf(only, scripts);361362 return Option.isSome(inner) && inner.value !== name363 ? Option.orElse(bodyOf(inner.value, scripts, depth + 1), () =>364 Option.some(body)365 )366 : Option.some(body);367 });368369/** How the repo's package manager runs a script: `pnpm run build`, `npm test`. */370const runScript = (manager: PackageManager, name: string) =>371 manager === "npm" && name === "test" ? "npm test" : `${manager} run ${name}`;372373// --- One test file ------------------------------------------------------374375const insertBefore = (376 tokens: readonly string[],377 marker: string,378 added: readonly string[]379) => {380 const at = tokens.indexOf(marker);381382 return at === -1383 ? [...tokens, ...added]384 : [...tokens.slice(0, at), ...added, ...tokens.slice(at)];385};386387/** A `go test` package pattern: `.`, `./pkg`, `./...`, `example.com/m/...`. */388const isGoPackages = (arg: string) =>389 arg === "." ||390 arg.startsWith("./") ||391 arg.startsWith("../") ||392 arg.includes("...");393394/**395 * The command that runs one test file, for runners that can: `vitest run`396 * → `vitest run {path}`. Go runs a package and Cargo a test target, so theirs397 * name the file's directory or stem through the shell.398 */399const oneFile = (command: string): Option.Option<string> => {400 const tokens = words(command);401 const at = toolIndex(tokens);402 const head = tokens.slice(0, at);403 const rest = tokens.slice(at);404405 const write = (...parts: readonly string[]) =>406 Option.some([...head, ...parts].join(" "));407408 if (startsWith(rest, ["vitest"])) {409 const args = rest[1] === "run" ? rest.slice(2) : rest.slice(1);410411 return write("vitest", "run", ...args, PATH_PLACEHOLDER);412 }413414 if (415 ["jest", "mocha", "ava", "pytest"].some((tool) => rest[0] === tool) ||416 [417 ["bun", "test"],418 ["node", "--test"],419 ["deno", "test"],420 ].some((tool) => startsWith(rest, tool))421 ) {422 return write(...rest, PATH_PLACEHOLDER);423 }424425 if (startsWith(rest, ["go", "test"])) {426 // Keep every flag and its value (`-run TestX`); drop the packages.427 const flags = rest.slice(2).filter((arg) => !isGoPackages(arg));428429 return write("go", "test", ...flags, `"./$(dirname ${PATH_PLACEHOLDER})"`);430 }431432 if (startsWith(rest, ["cargo", "test"])) {433 return write(434 ...insertBefore(rest, "--", [435 "--test",436 `"$(basename ${PATH_PLACEHOLDER} .rs)"`,437 ])438 );439 }440441 return Option.none();442};443444// --- Reading sources ----------------------------------------------------445446/** A command a source runs, with the name the source gives it, if any. */447interface Step {448 readonly command: string;449 readonly name: Option.Option<string>;450}451452/** A lane a source offers: its command, and the file its test runner was read from. */453interface Offer {454 readonly command: string;455 readonly fallback: Option.Option<string>;456 readonly lane: string;457 readonly path: string;458 readonly runner: { readonly body: string; readonly path: string };459}460461/** One source file, read: its setup commands and lanes, or why it was skipped. */462interface Read {463 readonly offers: readonly Offer[];464 readonly path: string;465 readonly setup: readonly string[];466}467468const PACKAGE_JSON = "package.json";469470// An error's message on one line, for a `skipped …` source.471const oneLine = (message: string) =>472 message473 .split("\n")474 .map((line) => line.trim())475 .filter(Boolean)476 .join(" ");477478/**479 * A YAML file decoded by `schema`, or why not. YAML errors keep their first480 * line (the rest is a code frame); schema errors keep every line.481 */482const readYaml = <A>(483 schema: Schema.ConstraintDecoder<A>,484 content: string485): Result.Result<A, string> =>486 Result.try({487 catch: (thrown) => String(thrown).split("\n")[0] ?? "unreadable YAML",488 try: () =>489 Schema.decodeUnknownResult(schema)(490 parse(content, { logLevel: "error", strict: false })491 ),492 }).pipe(493 Result.flatMap((decoded) =>494 Result.mapError(decoded, (issue) => oneLine(issue.message))495 )496 );497498// A shell line split into the commands it chains; comments and blank lines499// dropped, `\` continuations joined.500const shellCommands = (text: string): readonly string[] =>501 text502 .replaceAll("\\\n", " ")503 .split("\n")504 .map((line) => line.trim())505 .filter((line) => line !== "" && !line.startsWith("#"))506 .flatMap(segments)507 .filter((command) => command !== "");508509const Workflow = Schema.Struct({510 jobs: Schema.Record(511 Schema.String,512 Schema.Struct({513 steps: Schema.optionalKey(514 Schema.Array(Schema.Struct({ run: Schema.optionalKey(Schema.String) }))515 ),516 })517 ),518});519520const workflowSteps = (content: string) =>521 readYaml(Workflow, content).pipe(522 Result.map((workflow) =>523 Object.values(workflow.jobs)524 .flatMap((job) => job.steps ?? [])525 .flatMap((step) => shellCommands(step.run ?? ""))526 // A workflow expression has no value until the workflow runs.527 .filter((command) => !command.includes("${{"))528 .map((command): Step => ({ command, name: Option.none() }))529 )530 );531532const LefthookHook = Schema.Struct({533 commands: Schema.optionalKey(534 Schema.Record(535 Schema.String,536 Schema.Struct({ run: Schema.optionalKey(Schema.String) })537 )538 ),539 jobs: Schema.optionalKey(540 Schema.Array(541 Schema.Struct({542 name: Schema.optionalKey(Schema.String),543 run: Schema.optionalKey(Schema.String),544 })545 )546 ),547});548549const Lefthook = Schema.Struct({550 "pre-commit": Schema.optionalKey(LefthookHook),551 "pre-push": Schema.optionalKey(LefthookHook),552});553554// Lefthook fills these with the files a commit touches; a check runs on all.555const lefthookFiles = (command: string) =>556 command.replaceAll(/\{(?:staged_files|push_files|all_files|files)\}/gu, ".");557558const lefthookSteps = (content: string) =>559 readYaml(Lefthook, content).pipe(560 Result.map((config) =>561 [config["pre-commit"], config["pre-push"]].flatMap((hook) => [562 ...Object.entries(hook?.commands ?? {}).flatMap(([name, { run }]) =>563 shellCommands(lefthookFiles(run ?? "")).map((command): Step => ({564 command,565 name: Option.some(name),566 }))567 ),568 ...(hook?.jobs ?? []).flatMap(({ name, run }) =>569 shellCommands(lefthookFiles(run ?? "")).map((command): Step => ({570 command,571 name: Option.fromNullishOr(name),572 }))573 ),574 ])575 )576 );577578// Husky's own lines source its helper; they aren't the project's commands.579const huskySteps = (content: string): readonly Step[] =>580 shellCommands(content)581 .filter((line) => !/^(?:\.|source)\s/u.test(line))582 .map((command) => ({ command, name: Option.none() }));583584const PreCommit = Schema.Struct({585 repos: Schema.Array(586 Schema.Struct({587 hooks: Schema.Array(588 Schema.Struct({589 id: Schema.NonEmptyString,590 stages: Schema.optionalKey(Schema.Array(Schema.String)),591 })592 ),593 })594 ),595});596597const PRE_COMMIT_STAGES: ReadonlySet<string> = new Set([598 "commit",599 "pre-commit",600]);601602/** pre-commit's hook ids that name a canonical lane. */603const HOOKS: ReadonlyMap<string, Canonical> = new Map([604 ["ruff", "lint"],605 ["ruff-check", "lint"],606 ["flake8", "lint"],607 ["pylint", "lint"],608 ["eslint", "lint"],609 ["golangci-lint", "lint"],610 ["ruff-format", "format"],611 ["black", "format"],612 ["prettier", "format"],613 ["isort", "format"],614 ["mypy", "types"],615 ["pyright", "types"],616 ["pytest", "unit"],617]);618619const fileNamed = (path: string) => (file: RepoFile) => file.path === path;620621const workflowFile = /^\.(?:github|forgejo)\/workflows\/[^/]+\.ya?ml$/u;622623const isWorkflow = (file: RepoFile) => workflowFile.test(file.path);624625const huskyFile = /^\.husky\/pre-(?:commit|push)$/u;626627// Every name lefthook reads its config from, as the judge closure lists them.628const LEFTHOOK: ReadonlySet<string> = new Set([629 "lefthook.yml",630 "lefthook.yaml",631 ".lefthook.yml",632 ".lefthook.yaml",633]);634635const PRE_COMMIT = ".pre-commit-config.yaml";636637const byPath = (left: RepoFile, right: RepoFile) =>638 left.path < right.path ? -1 : Number(left.path > right.path);639640const PackageJson = Schema.fromJsonString(641 Schema.Struct({642 packageManager: Schema.optionalKey(Schema.String),643 scripts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),644 })645);646647const LOCKFILES: readonly (readonly [string, PackageManager])[] = [648 ["bun.lock", "bun"],649 ["bun.lockb", "bun"],650 ["pnpm-lock.yaml", "pnpm"],651 ["yarn.lock", "yarn"],652 ["package-lock.json", "npm"],653];654655// --- Putting it together ------------------------------------------------656657const offerFromStep = (658 step: Step,659 path: string,660 scripts: Scripts661): Option.Option<Offer> => {662 const script = scriptOf(step.command, scripts);663 const body = Option.flatMap(script, (name) => bodyOf(name, scripts));664665 const runner = Option.match(body, {666 onNone: () => ({ body: step.command, path }),667 onSome: (text) => ({ body: text, path: PACKAGE_JSON }),668 });669670 const task = Option.orElse(script, () => taskOf(step.command));671 const ownName = Option.orElse(step.name, () => task);672 const byBody = Option.firstSomeOf(segments(runner.body).map(toolLane));673674 const lane = Option.isSome(task)675 ? Option.orElse(namedLane(task.value), () => byBody)676 : Option.orElse(toolLane(step.command), () =>677 Option.flatMap(step.name, namedLane)678 );679680 const fallback = Option.flatMap(ownName, scriptLane);681682 // A dev server, deploy or release is no check, whatever tool its body runs.683 const neverALane = [step.name, task].some((name) =>684 Option.exists(name, (text) => NEVER_A_LANE.test(text))685 );686687 return neverALane || fixes(runner.body)688 ? Option.none()689 : Option.map(690 Option.orElse(lane, () => fallback),691 (name) => ({692 command: step.command,693 fallback,694 lane: name,695 path,696 runner,697 })698 );699};700701const readSteps = (702 file: RepoFile,703 steps: readonly Step[],704 scripts: Scripts705): Read => ({706 offers: steps.flatMap((step) =>707 isSetup(step.command)708 ? []709 : Option.toArray(offerFromStep(step, file.path, scripts))710 ),711 path: file.path,712 setup: steps.flatMap(({ command }) => (isSetup(command) ? [command] : [])),713});714715const readPreCommit = (file: RepoFile) =>716 readYaml(PreCommit, file.content).pipe(717 Result.map((config): Read => ({718 offers: config.repos719 .flatMap(({ hooks }) => hooks)720 .filter(721 ({ stages }) =>722 stages === undefined ||723 stages.some((stage) => PRE_COMMIT_STAGES.has(stage))724 )725 .flatMap(({ id }) => {726 const command = `pre-commit run ${id} --all-files`;727 const fallback = asLaneName(id);728729 return Option.toArray(730 Option.map(731 Option.orElse(732 Option.fromNullishOr(HOOKS.get(id)),733 () => fallback734 ),735 (lane) => ({736 command,737 fallback,738 lane,739 path: file.path,740 runner: { body: command, path: file.path },741 })742 )743 );744 }),745 path: file.path,746 setup: [],747 }))748 );749750// Root scripts that name or run a check become lanes, run the repo's way.751const readScripts = (manager: PackageManager, scripts: Scripts): Read => ({752 offers: [...scripts.byName].flatMap(([name, body]) => {753 const lane = Option.orElse(namedLane(name), () =>754 Option.firstSomeOf(segments(body).map(toolLane))755 );756757 return fixes(body) || NEVER_A_LANE.test(name)758 ? []759 : Option.toArray(760 Option.map(lane, (found) => ({761 command: runScript(manager, name),762 fallback: scriptLane(name),763 lane: found,764 path: PACKAGE_JSON,765 runner: {766 body: Option.getOrElse(bodyOf(name, scripts), () => body),767 path: PACKAGE_JSON,768 },769 }))770 );771 }),772 path: PACKAGE_JSON,773 setup: [],774});775776/** Lanes by name, in the order found, each with its offer. */777type Lanes = ReadonlyMap<string, Offer>;778779// One group's offers, merged under the lanes already found by the groups780// before it. Inside a group a second offer for a lane takes its own name;781// a later group only fills lanes the earlier ones lack.782const mergeGroup = (found: Lanes, group: readonly Read[]): Lanes => {783 const added = new Map<string, Offer>();784 const commands = new Set([...found.values()].map(({ command }) => command));785786 for (const offer of group.flatMap(({ offers }) => offers)) {787 const free = (lane: string) => !found.has(lane) && !added.has(lane);788789 const repeated = [...added.values()].some(790 ({ command }) => command === offer.command791 );792793 if (!commands.has(offer.command) && !repeated && !found.has(offer.lane)) {794 const lane = free(offer.lane)795 ? Option.some(offer.lane)796 : Option.filter(offer.fallback, free);797798 if (Option.isSome(lane)) {799 added.set(lane.value, offer);800 }801 }802 }803804 return new Map([...found, ...added]);805};806807const managerOf = (808 files: readonly RepoFile[],809 scripts: Scripts,810 setup: readonly string[]811): PackageManager =>812 Option.firstSomeOf([813 scripts.manager,814 Option.fromNullishOr(815 LOCKFILES.find(([lockfile]) => files.some(fileNamed(lockfile)))?.[1]816 ),817 Option.fromNullishOr(818 setup.map((command) => words(command)[0]).find(isManager)819 ),820 ]).pipe(Option.getOrElse((): PackageManager => "npm"));821822const INSTALL = {823 bun: "bun install --frozen-lockfile",824 npm: "npm ci",825 pnpm: "pnpm install --frozen-lockfile",826 yarn: "yarn install --frozen-lockfile",827} as const satisfies Record<PackageManager, string>;828829const skip = (path: string, reason: string) => `skipped ${path}: ${reason}`;830831/** Each file read, and a `skipped …` line for each one that wasn't. */832const readEach = (833 files: readonly RepoFile[],834 read: (file: RepoFile) => Result.Result<Read, string>835) => {836 const results = files.map((file) =>837 Result.mapError(read(file), (reason) => skip(file.path, reason))838 );839840 return {841 reads: Arr.getSuccesses(results),842 skipped: Arr.getFailures(results),843 };844};845846/** The root `package.json`'s scripts and package manager, or why it can't be read. */847const readPackage = (files: readonly RepoFile[]) =>848 Option.map(849 Option.fromNullishOr(files.find(fileNamed(PACKAGE_JSON))),850 (file) =>851 Result.mapError(Schema.decodeResult(PackageJson)(file.content), (issue) =>852 skip(PACKAGE_JSON, oneLine(issue.message))853 )854 );855856const scriptsOf = (root: Option.Option<typeof PackageJson.Type>): Scripts => ({857 byName: new Map(858 Object.entries(Option.getOrUndefined(root)?.scripts ?? {}).filter(859 ([, body]) => body.trim() !== ""860 )861 ),862 manager: Option.flatMap(root, ({ packageManager = "" }) =>863 Option.fromNullishOr(864 MANAGERS.find((manager) => packageManager.startsWith(`${manager}@`))865 )866 ),867});868869/** Setup commands with the file each came from, deduplicated, in order. */870type Setup = readonly (readonly [command: string, path: string])[];871872// The install commands of the source group setup comes from, plus the hook873// environments pre-commit's lanes need before the network closes.874const setupOf = (reads: readonly Read[], lanes: Lanes): Setup => {875 const found = reads.flatMap(({ path, setup }) =>876 setup.map((command) => [command, path] as const)877 );878879 const hooks = [...lanes.values()].some(({ path }) => path === PRE_COMMIT)880 ? [["pre-commit install-hooks", PRE_COMMIT] as const]881 : [];882883 return [...new Map([...found, ...hooks])];884};885886/** The one-file test command, and where its runner was read. */887const testOf = (lanes: Lanes) =>888 Option.map(Option.fromNullishOr(lanes.get("unit")), (unit) =>889 Option.match(Option.firstSomeOf(segments(unit.runner.body).map(oneFile)), {890 onNone: () => ({ command: unit.command, path: unit.path }),891 onSome: (command) => ({ command, path: unit.runner.path }),892 })893 );894895/**896 * Finds a project's run block in its files. Sources rank CI workflows first,897 * then lefthook, husky and pre-commit hooks, then root `package.json`898 * scripts; a lower source only adds lanes the higher ones lack. Lanes are899 * named `lint`, `types`, `unit`, `build` and `format` when the finder knows900 * the tool or the name, else by their script's name; a dev server, deploy,901 * release or fixer is never a lane. `test` runs one file (`{path}`) for902 * runners it knows (vitest, jest, bun test, pytest, go test, cargo test, and903 * a few more); otherwise it is the unit lane's command as found. Setup is the904 * install commands the top source runs, or else the package manager's905 * install, frozen only when a lockfile is committed. A file that doesn't906 * parse is skipped with its reason in `sources`; nothing found leaves `run`907 * and `sources` empty.908 */909export const findRunBlock = (files: readonly RepoFile[]): FoundRunBlock => {910 const sorted = files.toSorted(byPath);911 const root = readPackage(sorted);912 const rootPackage = Option.flatMap(root, Result.getSuccess);913 const scripts = scriptsOf(rootPackage);914915 const workflows = readEach(sorted.filter(isWorkflow), (file) =>916 Result.map(workflowSteps(file.content), (steps) =>917 readSteps(file, steps, scripts)918 )919 );920921 const lefthook = readEach(922 sorted.filter(({ path }) => LEFTHOOK.has(path)).slice(0, 1),923 (file) =>924 Result.map(lefthookSteps(file.content), (steps) =>925 readSteps(file, steps, scripts)926 )927 );928929 const husky = sorted.flatMap((file) =>930 huskyFile.test(file.path)931 ? [readSteps(file, huskySteps(file.content), scripts)]932 : []933 );934935 const preCommit = readEach(936 sorted.filter(fileNamed(PRE_COMMIT)),937 readPreCommit938 );939940 const hooks = [...lefthook.reads, ...husky, ...preCommit.reads];941942 // Setup comes from the highest-ranked group that installs anything.943 const installing =944 [workflows.reads, hooks].find((reads) =>945 reads.some(({ setup }) => setup.length > 0)946 ) ?? [];947948 const manager = managerOf(949 sorted,950 scripts,951 installing.flatMap(({ setup }) => setup)952 );953954 let lanes: Lanes = new Map();955956 for (const group of [957 workflows.reads,958 hooks,959 Option.isSome(rootPackage) ? [readScripts(manager, scripts)] : [],960 ]) {961 lanes = mergeGroup(lanes, group);962 }963964 const setup = setupOf(installing, lanes);965966 const lockfile = LOCKFILES.find(967 ([name, owner]) => owner === manager && sorted.some(fileNamed(name))968 );969970 // A frozen install refuses to run without a lockfile, so none means a plain one.971 const inferred =972 setup.length === 0 && Option.isSome(rootPackage)973 ? Option.some(974 lockfile === undefined975 ? { command: `${manager} install`, from: PACKAGE_JSON }976 : { command: INSTALL[manager], from: lockfile[0] }977 )978 : Option.none();979980 const commands = [981 ...setup.map(([command]) => command),982 ...Option.toArray(Option.map(inferred, ({ command }) => command)),983 ];984985 const test = testOf(lanes);986987 return {988 run: {989 ...(lanes.size > 0 && {990 checks: Object.fromEntries(991 [...lanes].map(([lane, { command }]) => [lane, command])992 ),993 }),994 ...(commands.length > 0 && { setup: commands.join(" && ") }),995 ...(Option.isSome(test) && { test: test.value.command }),996 },997 sources: [998 ...new Set(setup.map(([, path]) => `setup from ${path}`)),999 ...Option.toArray(1000 Option.map(inferred, ({ from }) => `setup inferred from ${from}`)1001 ),1002 ...Option.toArray(Option.map(test, ({ path }) => `test from ${path}`)),1003 ...[...lanes].map(([lane, { path }]) => `checks.${lane} from ${path}`),1004 ...Option.toArray(Option.flatMap(root, Result.getFailure)),1005 ...workflows.skipped,1006 ...lefthook.skipped,1007 ...preCommit.skipped,1008 ],1009 };1010};
added:packages/checks/src/judge.ts+376 added
1/**2 * The judge closure: every file that decides what an answer's checks do, so3 * no answer may change it (GLOSSARY "Judge closure"). It is data: globs, plus4 * JSON pointers into files an answer may still edit elsewhere, such as5 * `package.json#/scripts` beside its dependencies. Pure; it reads only the6 * file contents it is given.7 */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 { Equal, Option, Predicate, Result, Schema } from "effect";1314import type { RepoFile } from "./finder.ts";1516/** A closure glob that starts with this takes paths back out of the closure. */17const EXCLUDE = "!";1819/**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.25 */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/**",45 "lefthook.yml",46 "lefthook.yaml",47 ".lefthook.yml",48 ".lefthook.yaml",49 ".husky/**",50 ".pre-commit-config.yaml",51 ".claude/settings*.json",52 ".cursor/hooks.json",53 ".pi/**",54 ".agents/skills/*-contribute/**",55 ".claude/skills/*-contribute/**",56].map((glob) => Glob.make(glob));5758const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");5960// One path segment against one glob segment: `*` is any run of characters61// and `?` is one, never a `/`. Greedy, backing up to the last `*` on a miss.62const matchSegment = (pattern: string, text: string): boolean => {63 let at = 0;64 let from = 0;65 let star = -1;66 let resume = 0;6768 while (from < text.length) {69 const wanted = pattern[at];7071 if (wanted === "?" || (wanted !== "*" && wanted === text[from])) {72 at += 1;73 from += 1;74 } else if (wanted === "*") {75 star = at;76 resume = from;77 at += 1;78 } else if (star === -1) {79 return false;80 } else {81 at = star + 1;82 resume += 1;83 from = resume;84 }85 }8687 while (pattern[at] === "*") {88 at += 1;89 }9091 return at === pattern.length;92};9394const matchSegments = (95 globs: readonly string[],96 parts: readonly string[]97): boolean => {98 const [glob, ...restGlobs] = globs;99100 if (glob === undefined) {101 return parts.length === 0;102 }103104 if (glob === "**") {105 return [...parts.keys(), parts.length].some((skip) =>106 matchSegments(restGlobs, parts.slice(skip))107 );108 }109110 const [part, ...restParts] = parts;111112 return (113 part !== undefined &&114 matchSegment(glob, part) &&115 matchSegments(restGlobs, restParts)116 );117};118119/**120 * Whether a repo path matches a glob: `**` as a whole segment is any number121 * of directories (none included), `*` is any run of characters within a122 * segment and `?` one character. A leading dot is matched like any other123 * character, so `*` reaches dotfiles. No braces, no classes, no negation.124 * Pure and dependency-free, so the gate can copy it.125 */126export const matchGlob = (glob: string, path: string): boolean =>127 matchSegments(128 withoutDotSlash(glob).split("/"),129 withoutDotSlash(path).split("/")130 );131132/**133 * Whether an answer that changes `path` changes the judge: some closure glob134 * matches it and no `!` glob takes it back out. A JSON pointer never judges a135 * whole file (`package.json` stays editable); `touchedPointers` reads those.136 */137export const isJudged = (closure: Policy["judge"], path: string): boolean => {138 const excluded = closure.paths.some(139 (glob) =>140 glob.startsWith(EXCLUDE) && matchGlob(glob.slice(EXCLUDE.length), path)141 );142143 return (144 !excluded &&145 closure.paths.some(146 (glob) => !glob.startsWith(EXCLUDE) && matchGlob(glob, path)147 )148 );149};150151const Extends = Schema.fromJsonString(152 Schema.Struct({153 extends: Schema.optionalKey(154 Schema.Union([Schema.String, Schema.Array(Schema.String)])155 ),156 })157);158159const decodeExtends = Schema.decodeOption(Extends);160161const dirname = (path: string) => path.split("/").slice(0, -1).join("/");162163// `a/b` joined with `../c` is `c`; `..` above the root leaves the repo.164const join = (dir: string, relative: string): Option.Option<string> => {165 const parts: string[] = dir === "" ? [] : dir.split("/");166167 for (const part of relative.split("/")) {168 if (part === "..") {169 if (parts.pop() === undefined) {170 return Option.none();171 }172 } else if (part !== "." && part !== "") {173 parts.push(part);174 }175 }176177 return Option.some(parts.join("/"));178};179180// `./base` names `base.json` when only that exists, as TypeScript resolves it.181const resolveExtends = (182 from: string,183 specifier: string,184 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))190 )191 )192 : Option.none();193194/**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.198 */199const extendsChain = (200 start: string,201 contents: ReadonlyMap<string, string>202): readonly string[] => {203 const seen = new Set<string>();204 const queue = [start];205206 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[] => [])211 );212213 for (const specifier of parent) {214 const resolved = resolveExtends(next, specifier, contents);215216 if (Option.isSome(resolved) && !seen.has(resolved.value)) {217 seen.add(resolved.value);218 queue.push(resolved.value);219 }220 }221 }222223 return [...seen];224};225226// A command's words that could name a file: split on whitespace and shell227// operators, unquoted, and the value of a `--flag=value`.228const wordsOf = (command: string): readonly string[] =>229 command230 .split(/[\s;&|()<>]+/u)231 .map((word) => word.replaceAll(/^["']|["']$/gu, ""))232 .flatMap((word) => [word, word.slice(word.indexOf("=") + 1)])233 .map(withoutDotSlash);234235const isPackageJson = (path: string) => matchGlob("**/package.json", path);236237const SCRIPTS = "#/scripts";238239/**240 * A judge closure as data, the shape `Policy.judge` stores: globs (a `!` glob241 * takes paths back out), and `<file>#<JSON pointer>` parts of files.242 */243export interface JudgeClosure {244 readonly paths: readonly Glob[];245 readonly pointers: readonly string[];246}247248/**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 shape252 * is `@repo/rules`' `Finishers.judgeClosure`, so the platform passes it in.253 */254export const judgeClosure = (255 run: RunBlock,256 files: readonly RepoFile[]257): JudgeClosure => {258 const contents = new Map(259 files.map((file) => [withoutDotSlash(file.path), file.content])260 );261262 const commands = [263 run.setup,264 run.doctor,265 run.test,266 ...Object.values(run.checks),267 ].filter(Predicate.isNotUndefined);268269 // 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));273274 const chains = [...contents.keys()]275 .filter((path) => matchGlob("**/tsconfig*.json", path))276 .flatMap((path) => extendsChain(path, contents));277278 const defaults = new Set<string>(defaultJudgeGlobs);279280 const added = [...new Set([...named, ...chains])]281 .filter((path) => !defaults.has(path))282 .toSorted()283 .map((path) => Glob.make(path));284285 const packages = [...contents.keys()].filter(isPackageJson).toSorted();286287 const pointers = [288 ...packages.filter((path) => path === "package.json"),289 ...packages.filter((path) => path !== "package.json"),290 ].map((path) => `${path}${SCRIPTS}`);291292 return { paths: [...defaultJudgeGlobs, ...added], pointers };293};294295const decodeJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));296297const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>298 Predicate.isObject(value);299300// RFC 6901: `/a~1b` is the key `a/b`; `~0` is `~`.301const pointerTokens = (pointer: string): readonly string[] =>302 pointer === ""303 ? []304 : pointer305 .slice(1)306 .split("/")307 .map((token) => token.replaceAll("~1", "/").replaceAll("~0", "~"));308309const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>310 Array.isArray(value);311312// One step down a JSON value: an object's own key, or an array's index.313const childAt = (314 value: Schema.Json,315 token: string316): Option.Option<Schema.Json> => {317 if (isJsonArray(value)) {318 return /^(?:0|[1-9]\d*)$/u.test(token)319 ? Option.fromNullishOr(value[Number(token)])320 : Option.none();321 }322323 return isJsonObject(value) && Object.hasOwn(value, token)324 ? Option.fromNullishOr(value[token])325 : Option.none();326};327328const valueAt = (329 json: Schema.Json,330 tokens: readonly string[]331): Option.Option<Schema.Json> => {332 let value = Option.some(json);333334 for (const token of tokens) {335 value = Option.flatMap(value, (current) => childAt(current, token));336 }337338 return value;339};340341// What one side of a change holds at a pointer: nothing (no file, or no such342// key), the value, or the text of a file that isn't JSON.343const read = (344 file: RepoFile | undefined,345 target: string,346 tokens: readonly string[]347): Option.Option<Result.Result<Schema.Json, string>> =>348 file === undefined || !matchGlob(target, file.path)349 ? Option.none()350 : Option.match(decodeJson(file.content), {351 onNone: () => Option.some(Result.fail(file.content)),352 onSome: (json) => Option.map(valueAt(json, tokens), Result.succeed),353 });354355/**356 * The closure's pointers whose value differs between a file's two versions:357 * `["package.json#/scripts"]` when a script changed, `[]` for a dependency358 * edit. Values compare as JSON, so moving a key or reformatting is no change.359 * A file added (no `before`), deleted (no `after`), or no longer valid JSON360 * counts as a change.361 */362export const touchedPointers = (363 closure: Policy["judge"],364 before: RepoFile | undefined,365 after?: RepoFile366): readonly string[] =>367 closure.pointers.filter((pointer) => {368 const hash = pointer.indexOf("#");369 const target = hash === -1 ? pointer : pointer.slice(0, hash);370 const tokens = pointerTokens(hash === -1 ? "" : pointer.slice(hash + 1));371372 return !Equal.equals(373 read(before, target, tokens),374 read(after, target, tokens)375 );376 });
added:packages/checks/src/kinds.ts+182 added
1/**2 * Check kinds: what each kind of ask check runs, and the version that keys3 * its cached verdicts together with the tree SHA (principle 8).4 */5import { CheckSpec } from "@repo/protocol/domain/check";6import type { RatchetSpec } from "@repo/protocol/domain/check";7import { Command } from "@repo/protocol/domain/common";8import type { CheckKind } from "@repo/protocol/domain/kind";9import type { RunBlock } from "@repo/protocol/domain/run";10import { CheckVersion, LaneName } from "@repo/protocol/ids";11import { Option, Predicate } from "effect";12import type { Schema } from "effect";1314/** The placeholder a run block's `test` holds for the one check file it runs. */15export const PATH_PLACEHOLDER = "{path}";1617/** The check kind a check is of, as an ask kind names it: `RedThenGreen` → `redThenGreen`. */18export const checkKindOf = (spec: CheckSpec): CheckKind =>19 CheckSpec.match(spec, {20 LintToZero: (): CheckKind => "lintToZero",21 Migrate: (): CheckKind => "migrate",22 Ratchet: (): CheckKind => "ratchet",23 RedThenGreen: (): CheckKind => "redThenGreen",24 SymbolAbsent: (): CheckKind => "symbolAbsent",25 });2627// Bare when the shell would read it as one word, single-quoted otherwise.28const shellWord = (path: string) =>29 /^[\w./@+-]+$/u.test(path) ? path : `'${path.replaceAll("'", `'\\''`)}'`;3031const declared = (32 ratchets: readonly RatchetSpec[],33 name: string34): Option.Option<RatchetSpec> =>35 Option.fromNullishOr(ratchets.find((ratchet) => ratchet.name === name));3637/**38 * The command an ask's check runs, and the lane its result is reported as39 * (the check kind's name, which no project lane shadows in practice).40 * `redThenGreen` fills the run block's `{path}` with the check file;41 * `lintToZero`, `migrate` and `symbolAbsent` run their own command; a42 * `ratchet` runs the measure its policy declares. `None` when the check can't43 * run: a `test` command with no `{path}`, or an undeclared ratchet.44 */45export const commandFor = (46 spec: CheckSpec,47 run: RunBlock,48 ratchets: readonly RatchetSpec[] = []49): Option.Option<{ readonly command: Command; readonly lane: LaneName }> =>50 CheckSpec.match(spec, {51 LintToZero: ({ command }) => Option.some(command),52 Migrate: ({ count }) => Option.some(count),53 Ratchet: ({ ratchet }) =>54 Option.map(declared(ratchets, ratchet), ({ measure }) => measure.command),55 RedThenGreen: ({ path }) =>56 run.test.includes(PATH_PLACEHOLDER)57 ? Option.some(58 Command.make(run.test.replaceAll(PATH_PLACEHOLDER, shellWord(path)))59 )60 : Option.none(),61 SymbolAbsent: ({ count }) => Option.some(count),62 }).pipe(63 Option.map((command) => ({64 command,65 lane: LaneName.make(checkKindOf(spec)),66 }))67 );6869const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>70 Array.isArray(value);7172const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>73 Predicate.isObject(value);7475// JSON with every object's keys sorted, so equal data hashes equally.76const canonicalJson = (value: Schema.Json): string => {77 if (isJsonArray(value)) {78 return `[${value.map(canonicalJson).join(",")}]`;79 }8081 if (isJsonObject(value)) {82 const entries = Object.keys(value)83 .toSorted()84 .flatMap((key) => {85 const field = value[key];8687 return field === undefined88 ? []89 : [`${JSON.stringify(key)}:${canonicalJson(field)}`];90 });9192 return `{${entries.join(",")}}`;93 }9495 return JSON.stringify(value);96};9798// UTF-8 bytes of a string, without the DOM's TextEncoder: percent-encoding99// writes each byte that isn't a plain ASCII character as `%XX`. The text is100// JSON.stringify's, which never holds a lone surrogate.101const utf8 = (text: string): readonly number[] => {102 const encoded = encodeURIComponent(text);103 const bytes: number[] = [];104105 for (let at = 0; at < encoded.length; at += 1) {106 if (encoded[at] === "%") {107 bytes.push(Number.parseInt(encoded.slice(at + 1, at + 3), 16));108 at += 2;109 } else {110 bytes.push(encoded.codePointAt(at) ?? 0);111 }112 }113114 return bytes;115};116117const FNV_OFFSET = 0xcb_f2_9c_e4_84_22_23_25n;118119const FNV_PRIME = 0x1_00_00_00_01_b3n;120121const TWO_TO_64 = 2n ** 64n;122123// `hash ^ byte`: only the low byte changes, so XOR it bit by bit. Plain124// arithmetic, since the lint config refuses bitwise operators.125const xorLowByte = (hash: bigint, byte: number): bigint => {126 const low = Number(hash % 256n);127 let mixed = 0;128129 for (let bit = 1; bit < 256; bit *= 2) {130 if (Math.floor(low / bit) % 2 !== Math.floor(byte / bit) % 2) {131 mixed += bit;132 }133 }134135 return hash - BigInt(low) + BigInt(mixed);136};137138// FNV-1a, 64-bit, as 16 hex digits. A cache key, not a commitment, so it139// needs no WebCrypto and stays synchronous.140const fnv1a64 = (text: string) => {141 let hash = FNV_OFFSET;142143 for (const byte of utf8(text)) {144 hash = (xorLowByte(hash, byte) * FNV_PRIME) % TWO_TO_64;145 }146147 return hash.toString(16).padStart(16, "0");148};149150/**151 * The version of a check run: `<checkKind>@<sdkVersion>+<runHash>`, where152 * the run hash covers everything the run executes and nothing else: the153 * check itself and its command (a ratchet's declared measure included), every154 * lane, setup, its egress and the image. `doctor` judges nothing, so it is155 * left out. A verdict is reused only for the same tree and the same version.156 */157export const checkVersion = (158 spec: CheckSpec,159 sdkVersion: string,160 run: RunBlock,161 ratchets: readonly RatchetSpec[] = []162): CheckVersion => {163 const runs: Schema.Json = {164 check: spec,165 checks: run.checks,166 command: Option.getOrNull(167 Option.map(commandFor(spec, run, ratchets), ({ command }) => command)168 ),169 image: run.image ?? null,170 measure: CheckSpec.guards.Ratchet(spec)171 ? Option.getOrNull(172 Option.map(declared(ratchets, spec.ratchet), ({ measure }) => measure)173 )174 : null,175 setup: run.setup ?? null,176 setupEgress: run.setupEgress ?? null,177 };178179 return CheckVersion.make(180 `${checkKindOf(spec)}@${sdkVersion}+${fnv1a64(canonicalJson(runs))}`181 );182};
added:packages/checks/test/fixtures/finder/repos.ts+227 added
1/**2 * Fixture repos for the command finder, as the in-memory file lists the3 * platform reads at a landed commit. Each one is shaped like a real project's4 * CI, hook and script files.5 */6import type { RepoFile } from "../../../src/finder.ts";78const file = (path: string, ...lines: readonly string[]): RepoFile => ({9 content: `${lines.join("\n")}\n`,10 path,11});1213/** A Bun workspace whose GitHub workflow installs, lints and tests. */14export const bunWorkspace: readonly RepoFile[] = [15 file(16 "package.json",17 "{",18 ' "name": "parsekit",',19 ' "private": true,',20 ' "workspaces": ["packages/*"],',21 ' "scripts": {',22 ' "dev": "vite",',23 ' "lint": "oxlint",',24 ' "typecheck": "tsc --noEmit",',25 ' "test": "vitest run"',26 " }",27 "}"28 ),29 file(30 "packages/parse/package.json",31 "{",32 ' "name": "@parsekit/parse",',33 ' "scripts": { "test": "vitest run" }',34 "}"35 ),36 file(37 ".github/workflows/ci.yml",38 "name: CI",39 "on:",40 " pull_request:",41 " push:",42 " branches: [main]",43 "jobs:",44 " check:",45 " runs-on: ubuntu-latest",46 " steps:",47 " - uses: actions/checkout@v4",48 " - uses: oven-sh/setup-bun@v2",49 " - run: bun install --frozen-lockfile",50 " - name: Lint",51 " run: bun run lint",52 " - name: Test",53 " run: bun run test"54 ),55 file("src/index.ts", "export const parse = (text: string) => text;"),56];5758/** A pnpm library on Forgejo, with lefthook running lint and types before a commit. */59export const forgejoLefthook: readonly RepoFile[] = [60 file(61 "package.json",62 "{",63 ' "name": "tidy-dates",',64 ' "packageManager": "pnpm@9.12.0",',65 ' "scripts": {',66 ' "build": "tsc -p tsconfig.build.json",',67 ' "test": "jest"',68 " }",69 "}"70 ),71 file(72 ".forgejo/workflows/test.yml",73 "on: [push, pull_request]",74 "jobs:",75 " test:",76 " runs-on: docker",77 " container:",78 " image: node:22",79 " steps:",80 " - uses: actions/checkout@v4",81 " - run: corepack enable",82 " - run: pnpm install --frozen-lockfile",83 " - run: pnpm test"84 ),85 file(86 "lefthook.yml",87 "pre-commit:",88 " parallel: true",89 " commands:",90 " lint:",91 ' glob: "*.{js,ts}"',92 " run: pnpm exec eslint {staged_files}",93 " types:",94 " run: pnpm exec tsc --noEmit",95 "pre-push:",96 " commands:",97 " test:",98 " run: pnpm test"99 ),100];101102/** An npm package with husky hooks and no CI. */103export const huskyOnly: readonly RepoFile[] = [104 file(105 "package.json",106 "{",107 ' "name": "slugger",',108 ' "scripts": {',109 ' "prepare": "husky",',110 ' "test": "jest"',111 " },",112 ' "lint-staged": { "*.js": "eslint --fix" }',113 "}"114 ),115 file("package-lock.json", "{}"),116 file(".husky/pre-commit", "npx lint-staged", "npm test"),117 file(".husky/_/husky.sh", "#!/usr/bin/env sh", "exit 0"),118];119120/** A Python project: pre-commit runs ruff and mypy, and the workflow runs pytest. */121export const python: readonly RepoFile[] = [122 file(123 ".pre-commit-config.yaml",124 "repos:",125 " - repo: https://github.com/astral-sh/ruff-pre-commit",126 " rev: v0.6.9",127 " hooks:",128 " - id: ruff",129 " args: [--fix]",130 " - id: ruff-format",131 " - repo: https://github.com/pre-commit/mirrors-mypy",132 " rev: v1.11.2",133 " hooks:",134 " - id: mypy"135 ),136 file(137 ".github/workflows/test.yml",138 "on: [push, pull_request]",139 "jobs:",140 " test:",141 " runs-on: ubuntu-latest",142 " strategy:",143 " matrix:",144 ' python-version: ["3.11", "3.12"]',145 " steps:",146 " - uses: actions/checkout@v4",147 " - uses: actions/setup-python@v5",148 " with:",149 ` python-version: \${{ matrix.python-version }}`,150 " - run: |",151 " python -m pip install --upgrade pip",152 ' pip install -e ".[dev]"',153 " - run: pytest"154 ),155 file("pyproject.toml", "[project]", 'name = "fossil"'),156];157158/** A repo with nothing the finder reads. */159export const nothing: readonly RepoFile[] = [160 file("README.md", "# wrec"),161 file("src/main.zig", "pub fn main() void {}"),162];163164/** A broken workflow beside a good one: the broken one is skipped, not thrown. */165export const brokenWorkflow: readonly RepoFile[] = [166 file(".github/workflows/bad.yml", "jobs: [unclosed", " steps: {"),167 file(".github/workflows/shape.yml", "jobs: just a string"),168 file(169 ".github/workflows/good.yml",170 "jobs:",171 " test:",172 " steps:",173 " - run: go test ./..."174 ),175];176177/** A fence-shaped monorepo with no CI: its root scripts are its gate, run by turbo. */178export const turboMonorepo: readonly RepoFile[] = [179 file(180 "package.json",181 JSON.stringify({182 scripts: {183 check: "oxlint && oxfmt --check .",184 dev: "vitest",185 fix: "oxlint --fix && oxfmt .",186 test: "turbo run test",187 typecheck: "turbo run typecheck",188 },189 })190 ),191 file("bun.lock", "{}"),192 file(193 "packages/parse/package.json",194 JSON.stringify({ scripts: { test: "vitest run" } })195 ),196];197198/**199 * A workflow that runs a fixer, a deploy that builds first, a dev server, an200 * unknown script and both kinds of `ruff format`.201 */202export const mixedWorkflow: readonly RepoFile[] = [203 file(204 "package.json",205 JSON.stringify({206 scripts: {207 deploy: "vite build && wrangler deploy",208 dev: "vitest",209 "gen:check": "node scripts/gen.js --check",210 },211 })212 ),213 file(214 ".github/workflows/ci.yml",215 "jobs:",216 " ci:",217 " steps:",218 " - run: npm ci",219 " - run: npx prettier --write .",220 " - run: npm run gen:check",221 " - run: npm run deploy",222 " - run: npm run dev",223 " - run: ruff format .",224 " - run: ruff format --check .",225 " - run: echo done"226 ),227];
added:packages/checks/test/finder.test.ts+229 added
1import { describe, expect, it } from "@effect/vitest";23import { findRunBlock } from "../src/finder.ts";4import {5 brokenWorkflow,6 bunWorkspace,7 turboMonorepo,8 forgejoLefthook,9 huskyOnly,10 mixedWorkflow,11 nothing,12 python,13} from "./fixtures/finder/repos.ts";1415describe(findRunBlock, () => {16 it("finds a Bun workspace's setup, one-file test and lanes from its workflow and scripts", () => {17 expect(findRunBlock(bunWorkspace)).toStrictEqual({18 run: {19 checks: {20 lint: "bun run lint",21 types: "bun run typecheck",22 unit: "bun run test",23 },24 setup: "bun install --frozen-lockfile",25 test: "vitest run {path}",26 },27 sources: [28 "setup from .github/workflows/ci.yml",29 "test from package.json",30 "checks.lint from .github/workflows/ci.yml",31 "checks.unit from .github/workflows/ci.yml",32 "checks.types from package.json",33 ],34 });35 });3637 it("reads a Forgejo workflow first, then lefthook's commands, then the scripts", () => {38 expect(findRunBlock(forgejoLefthook)).toStrictEqual({39 run: {40 checks: {41 build: "pnpm run build",42 lint: "pnpm exec eslint .",43 types: "pnpm exec tsc --noEmit",44 unit: "pnpm test",45 },46 setup: "corepack enable && pnpm install --frozen-lockfile",47 test: "jest {path}",48 },49 sources: [50 "setup from .forgejo/workflows/test.yml",51 "test from package.json",52 "checks.unit from .forgejo/workflows/test.yml",53 "checks.lint from lefthook.yml",54 "checks.types from lefthook.yml",55 "checks.build from package.json",56 ],57 });58 });5960 it("reads husky hooks, leaves lint-staged out, and infers setup from the lockfile", () => {61 expect(findRunBlock(huskyOnly)).toStrictEqual({62 run: {63 checks: { unit: "npm test" },64 setup: "npm ci",65 test: "jest {path}",66 },67 sources: [68 "setup inferred from package-lock.json",69 "test from package.json",70 "checks.unit from .husky/pre-commit",71 ],72 });73 });7475 it("finds a Python project's pytest from its workflow and its lint and types from pre-commit", () => {76 expect(findRunBlock(python)).toStrictEqual({77 run: {78 checks: {79 format: "pre-commit run ruff-format --all-files",80 lint: "pre-commit run ruff --all-files",81 types: "pre-commit run mypy --all-files",82 unit: "pytest",83 },84 setup:85 'python -m pip install --upgrade pip && pip install -e ".[dev]" && pre-commit install-hooks',86 test: "pytest {path}",87 },88 sources: [89 "setup from .github/workflows/test.yml",90 "setup from .pre-commit-config.yaml",91 "test from .github/workflows/test.yml",92 "checks.unit from .github/workflows/test.yml",93 "checks.lint from .pre-commit-config.yaml",94 "checks.format from .pre-commit-config.yaml",95 "checks.types from .pre-commit-config.yaml",96 ],97 });98 });99100 it("takes a repo's checking scripts as lanes when it has no CI, and leaves fixers and dev servers out", () => {101 expect(findRunBlock(turboMonorepo)).toStrictEqual({102 run: {103 checks: {104 lint: "bun run check",105 types: "bun run typecheck",106 unit: "bun run test",107 },108 setup: "bun install --frozen-lockfile",109 test: "bun run test",110 },111 sources: [112 "setup inferred from bun.lock",113 "test from package.json",114 "checks.lint from package.json",115 "checks.unit from package.json",116 "checks.types from package.json",117 ],118 });119 });120121 it("infers a plain install when the repo commits no lockfile, since a frozen one would refuse", () => {122 expect(123 findRunBlock([124 {125 content: JSON.stringify({ scripts: { test: "vitest run" } }),126 path: "package.json",127 },128 ])129 ).toStrictEqual({130 run: {131 checks: { unit: "npm test" },132 setup: "npm install",133 test: "vitest run {path}",134 },135 sources: [136 "setup inferred from package.json",137 "test from package.json",138 "checks.unit from package.json",139 ],140 });141 });142143 it("names a lane by its script when the tool is unknown, and never takes a fixer or a deploy", () => {144 expect(findRunBlock(mixedWorkflow)).toStrictEqual({145 run: {146 checks: {147 format: "ruff format --check .",148 "gen-check": "npm run gen:check",149 },150 setup: "npm ci",151 },152 sources: [153 "setup from .github/workflows/ci.yml",154 "checks.gen-check from .github/workflows/ci.yml",155 "checks.format from .github/workflows/ci.yml",156 ],157 });158 });159160 it.each(["lefthook.yml", "lefthook.yaml", ".lefthook.yml", ".lefthook.yaml"])(161 "reads lefthook's commands from %s, a name the judge closure holds",162 (path) => {163 expect(164 findRunBlock([165 {166 content:167 "pre-commit:\n commands:\n lint:\n run: npx eslint {staged_files}\n",168 path,169 },170 ])171 ).toStrictEqual({172 run: { checks: { lint: "npx eslint ." } },173 sources: [`checks.lint from ${path}`],174 });175 }176 );177178 it("finds nothing in a repo with no scripts, CI or hooks", () => {179 expect(findRunBlock(nothing)).toStrictEqual({ run: {}, sources: [] });180 });181182 it("skips a workflow it can't read, with the reason, and keeps the rest", () => {183 const found = findRunBlock(brokenWorkflow);184185 expect(found.run).toStrictEqual({186 checks: { unit: "go test ./..." },187 test: 'go test "./$(dirname {path})"',188 });189 expect(found.sources).toHaveLength(4);190 expect(found.sources.slice(0, 2)).toStrictEqual([191 "test from .github/workflows/good.yml",192 "checks.unit from .github/workflows/good.yml",193 ]);194 expect(found.sources[2]).toMatch(195 /^skipped \.github\/workflows\/bad\.yml: \S/u196 );197 expect(found.sources[3]).toMatch(198 /^skipped \.github\/workflows\/shape\.yml: \S/u199 );200 });201202 it.each([203 ["npx vitest", "npx vitest run {path}"],204 ["bunx vitest run --reporter=dot", "bunx vitest run --reporter=dot {path}"],205 ["npx jest --ci", "npx jest --ci {path}"],206 ["bun test", "bun test {path}"],207 ["uv run pytest -q", "uv run pytest -q {path}"],208 ["python -m pytest", "python -m pytest {path}"],209 ["go test -race ./...", 'go test -race "./$(dirname {path})"'],210 [211 "go test -tags integration -run TestWeek ./pkg/...",212 'go test -tags integration -run TestWeek "./$(dirname {path})"',213 ],214 [215 "cargo test --all-features",216 'cargo test --all-features --test "$(basename {path} .rs)"',217 ],218 ["make test", "make test"],219 ])("turns the test command %s into %s", (command, test) => {220 const found = findRunBlock([221 {222 content: `jobs:\n test:\n steps:\n - run: ${command}\n`,223 path: ".github/workflows/test.yml",224 },225 ]);226227 expect(found.run).toStrictEqual({ checks: { unit: command }, test });228 });229});
added:packages/checks/test/judge.test.ts+257 added
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { Command } from "@repo/protocol/domain/common";4import type { RunBlock } from "@repo/protocol/domain/run";5import { LaneName } from "@repo/protocol/ids";67import type { RepoFile } from "../src/finder.ts";8import {9 defaultJudgeGlobs,10 isJudged,11 judgeClosure,12 matchGlob,13 touchedPointers,14} from "../src/judge.ts";1516const file = (path: string, content = ""): RepoFile => ({ content, path });1718/** A fence-shaped monorepo: root scripts, a tsconfig chain, a lint config, a hook config. */19const fence: readonly RepoFile[] = [20 file(21 "package.json",22 JSON.stringify({23 dependencies: { effect: "4.0.1" },24 scripts: {25 lint: "oxlint",26 test: "turbo run test",27 typecheck: "tsc --noEmit",28 },29 })30 ),31 file("tsconfig.json", JSON.stringify({ extends: "./tsconfig.base.json" })),32 file("tsconfig.base.json", JSON.stringify({ compilerOptions: {} })),33 file(34 "packages/parse/package.json",35 JSON.stringify({ scripts: { test: "vitest run" } })36 ),37 file(38 "packages/parse/tsconfig.json",39 JSON.stringify({ extends: ["../../configs/strict", "@tsconfig/node24"] })40 ),41 file("configs/strict.json", JSON.stringify({ extends: "./base.json" })),42 file("configs/base.json", JSON.stringify({ compilerOptions: {} })),43 file("packages/parse/vitest.config.ts", "export default {};"),44 file("oxlint.config.ts", "export default {};"),45 file("lefthook.yml", "pre-commit:\n commands: {}\n"),46 file(".github/workflows/ci.yml", "jobs: {}\n"),47 file("test.sh", "#!/bin/sh\nbun test\n"),48 file("scripts/count.ts", "export {};"),49 file("src/a.ts", "export const a = 1;"),50];5152const run: RunBlock = {53 checks: {54 [LaneName.make("lint")]: Command.make("bun run lint"),55 [LaneName.make("ratchet")]: Command.make(56 "bun scripts/count.ts --json --manifest=package.json"57 ),58 [LaneName.make("unit")]: Command.make("./test.sh"),59 },60 setup: Command.make("bun install --frozen-lockfile"),61 test: Command.make("bun test {path}"),62};6364const closure = judgeClosure(run, fence);6566describe(judgeClosure, () => {67 it("holds every default glob the spec names", () => {68 expect(closure.paths).toStrictEqual(69 expect.arrayContaining([70 `${Brand.configDir}/**`,71 "**/.env.schema",72 "**/.env.*",73 "!**/.env.local",74 "!**/.env.*.local",75 ".github/workflows/**",76 ".forgejo/**",77 "**/vitest.config.*",78 "**/oxlint.config.*",79 "**/tsconfig*.json",80 "lefthook.yml",81 ".husky/**",82 ".pre-commit-config.yaml",83 ".claude/settings*.json",84 ".cursor/hooks.json",85 ".pi/**",86 ".agents/skills/*-contribute/**",87 ])88 );89 expect(90 defaultJudgeGlobs.filter((glob) => !closure.paths.includes(glob))91 ).toStrictEqual([]);92 });9394 it("adds the files the run commands name, and only files that exist", () => {95 expect(closure.paths).toContain("test.sh");96 expect(closure.paths).toContain("scripts/count.ts");97 expect(closure.paths).not.toContain("--json");98 expect(closure.paths).not.toContain("{path}");99 });100101 it("follows a tsconfig's extends chain to files the defaults miss, and skips package specifiers", () => {102 expect(closure.paths).toContain("tsconfig.base.json");103 expect(closure.paths).toContain("configs/strict.json");104 expect(closure.paths).toContain("configs/base.json");105 expect(106 closure.paths.filter((glob) => glob.includes("@tsconfig"))107 ).toStrictEqual([]);108 });109110 it("judges each package.json's scripts by pointer, never the whole file", () => {111 expect(closure.pointers).toStrictEqual([112 "package.json#/scripts",113 "packages/parse/package.json#/scripts",114 ]);115 expect(closure.paths).not.toContain("package.json");116 });117118 it("gives the same closure for the same files in any order", () => {119 expect(judgeClosure(run, fence.toReversed())).toStrictEqual(closure);120 });121});122123describe(isJudged, () => {124 it.each([125 [".github/workflows/ci.yml", true],126 [`${Brand.configDir}/project.ts`, true],127 [`${Brand.configDir}/asks/fix-week.ask.ts`, true],128 [".env.schema", true],129 ["apps/web/.env.schema", true],130 [".env.production", true],131 [".env.local", false],132 [".env.production.local", false],133 ["packages/parse/vitest.config.ts", true],134 ["packages/parse/tsconfig.json", true],135 ["configs/strict.json", true],136 ["test.sh", true],137 [".husky/pre-commit", true],138 [".claude/settings.local.json", true],139 [".agents/skills/parsekit-contribute/SKILL.md", true],140 [".agents/skills/other/SKILL.md", false],141 ["package.json", false],142 ["packages/parse/package.json", false],143 ["src/a.ts", false],144 ["README.md", false],145 ])("%s is judged: %s", (path, judged) => {146 expect(isJudged(closure, path)).toBe(judged);147 });148});149150describe(touchedPointers, () => {151 const before = file(152 "package.json",153 JSON.stringify({154 dependencies: { effect: "4.0.1" },155 scripts: { lint: "oxlint", test: "vitest run" },156 })157 );158159 it("leaves dependency edits alone", () => {160 const after = file(161 "package.json",162 JSON.stringify({163 dependencies: { effect: "4.0.1", yaml: "2.9.1" },164 scripts: { lint: "oxlint", test: "vitest run" },165 })166 );167168 expect(touchedPointers(closure, before, after)).toStrictEqual([]);169 });170171 it("names the scripts pointer when a script changes", () => {172 const after = file(173 "package.json",174 JSON.stringify({ scripts: { lint: "oxlint", test: "true" } })175 );176177 expect(touchedPointers(closure, before, after)).toStrictEqual([178 "package.json#/scripts",179 ]);180 });181182 it("ignores scripts that only moved, or reformatting", () => {183 const after = file(184 "package.json",185 JSON.stringify(186 {187 dependencies: { effect: "4.0.1" },188 scripts: { lint: "oxlint", test: "vitest run" },189 },190 null,191 2192 )193 );194195 expect(touchedPointers(closure, before, after)).toStrictEqual([]);196 });197198 it("counts a deleted, added or unreadable package.json as touched", () => {199 expect(touchedPointers(closure, before)).toStrictEqual([200 "package.json#/scripts",201 ]);202 expect(touchedPointers(closure, undefined, before)).toStrictEqual([203 "package.json#/scripts",204 ]);205 expect(206 touchedPointers(closure, before, file("package.json", "{ broken"))207 ).toStrictEqual(["package.json#/scripts"]);208 });209210 it("matches a workspace package's pointer by its own path only", () => {211 const nested = (test: string) =>212 file(213 "packages/parse/package.json",214 JSON.stringify({ scripts: { test } })215 );216217 expect(218 touchedPointers(closure, nested("vitest run"), nested("exit 0"))219 ).toStrictEqual(["packages/parse/package.json#/scripts"]);220 expect(221 touchedPointers(closure, file("src/a.ts", "1"), file("src/a.ts", "2"))222 ).toStrictEqual([]);223 });224});225226describe(matchGlob, () => {227 it.each([228 [".github/workflows/**", ".github/workflows/ci.yml", true],229 [".github/workflows/**", ".github/workflows/nested/x.yml", true],230 [".github/workflows/**", ".github/ci.yml", false],231 ["**/tsconfig*.json", "tsconfig.json", true],232 ["**/tsconfig*.json", "packages/a/tsconfig.build.json", true],233 ["**/tsconfig*.json", "packages/a/tsconfig.json.bak", false],234 ["src/*.ts", "src/a.ts", true],235 ["src/*.ts", "src/a/b.ts", false],236 ["src/?.ts", "src/a.ts", true],237 ["src/?.ts", "src/ab.ts", false],238 ["**/.env.*", ".env.production", true],239 ["**/.env.*", "apps/web/.env.schema", true],240 ["*", ".hidden", true],241 ["a/**/b", "a/b", true],242 ["a/**/b", "a/x/y/b", true],243 ["a/**/b", "a/x/y/c", false],244 ["./lefthook.yml", "lefthook.yml", true],245 ["lefthook.yml", "./lefthook.yml", true],246 ["lefthook.yml", "sub/lefthook.yml", false],247 [248 ".agents/skills/*-contribute/**",249 ".agents/skills/x-contribute/SKILL.md",250 true,251 ],252 ["a.b", "axb", false],253 ["(x)[y]+", "(x)[y]+", true],254 ])("%s matches %s: %s", (glob, path, matches) => {255 expect(matchGlob(glob, path)).toBe(matches);256 });257});
added:packages/checks/test/kinds.test.ts+210 added
1import { describe, expect, it } from "@effect/vitest";2import {3 CheckSpec,4 RatchetMeasure,5 RatchetSpec,6} from "@repo/protocol/domain/check";7import { Command, SymbolName } from "@repo/protocol/domain/common";8import { RunBlock } from "@repo/protocol/domain/run";9import { RatchetName, RepoPath } from "@repo/protocol/ids";10import { Option, Schema } from "effect";1112import { checkKindOf, checkVersion, commandFor } from "../src/kinds.ts";1314const runBlock = Schema.decodeUnknownSync(RunBlock);1516const encodedRun = {17 checks: { lint: "bun run lint", types: "bun run typecheck" },18 setup: "bun install --frozen-lockfile",19 test: "bun test {path}",20};2122const run = runBlock(encodedRun);2324const redThenGreenOn = (path: string) =>25 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });2627const redThenGreen = redThenGreenOn("packages/parse/test/week.test.ts");2829const lintToZero = CheckSpec.cases.LintToZero.make({30 command: Command.make("oxlint --format json"),31 rule: "no-console",32});3334const migrate = CheckSpec.cases.Migrate.make({35 count: Command.make("bun scripts/count.ts dayjs"),36 from: SymbolName.make("dayjs"),37});3839const symbolAbsent = CheckSpec.cases.SymbolAbsent.make({40 count: Command.make("bun scripts/count.ts dayjs"),41 symbol: SymbolName.make("dayjs"),42});4344const ratchet = CheckSpec.cases.Ratchet.make({45 ratchet: RatchetName.make("anyCount"),46});4748const countingRule = (rule: string) => [49 RatchetSpec.make({50 measure: RatchetMeasure.cases.Count.make({51 command: Command.make("oxlint --format json"),52 rule,53 }),54 name: RatchetName.make("anyCount"),55 }),56];5758const ratchets = countingRule("typescript/no-explicit-any");5960const reversed = <V>(record: Readonly<Record<string, V>>) =>61 Object.fromEntries(Object.entries(record).toReversed());6263describe(checkVersion, () => {64 it("has the form <checkKind>@<sdkVersion>+<runHash>", () => {65 expect(checkVersion(redThenGreen, "0.3.1", run)).toMatch(66 /^redThenGreen@0\.3\.1\+[0-9a-f]{16}$/u67 );68 });6970 it("is equal for equal inputs, whatever their key order", () => {71 const reordered = runBlock({72 ...reversed(encodedRun),73 checks: reversed(encodedRun.checks),74 });7576 expect(Object.keys(reordered.checks)).toStrictEqual(["types", "lint"]);77 expect(checkVersion(redThenGreen, "0.3.1", reordered)).toBe(78 checkVersion(redThenGreen, "0.3.1", run)79 );80 });8182 it("stays the same across releases, since cached verdicts are keyed by it", () => {83 // Pinned: a change here makes every cached verdict miss once. Computed84 // apart from this code: FNV-1a 64 over the sorted-key JSON85 // {"check":{"_tag":"RedThenGreen","path":"packages/parse/test/week.test.ts"},86 // "checks":{"lint":"bun run lint","types":"bun run typecheck"},87 // "command":"bun test packages/parse/test/week.test.ts","image":null,88 // "measure":null,"setup":"bun install --frozen-lockfile","setupEgress":null}89 expect(checkVersion(redThenGreen, "0.3.1", run)).toBe(90 "redThenGreen@0.3.1+6cf6757a65e87235"91 );92 });9394 it("hashes a non-ASCII command by its UTF-8 bytes", () => {95 // Computed the same way, with "command": "bun test packages/parse/test/week.test.ts # é→✓ 🦀".96 expect(97 checkVersion(98 redThenGreen,99 "0.3.1",100 runBlock({ ...encodedRun, test: "bun test {path} # é→✓ 🦀" })101 )102 ).toBe("redThenGreen@0.3.1+3f7420049367e696");103 });104105 it.each([106 ["the test command", { ...encodedRun, test: "bun test --bail {path}" }],107 ["the setup command", { ...encodedRun, setup: "bun install" }],108 [109 "a lane's command",110 {111 ...encodedRun,112 checks: { ...encodedRun.checks, lint: "oxlint -D all" },113 },114 ],115 [116 "a new lane",117 {118 ...encodedRun,119 checks: { ...encodedRun.checks, build: "bun run build" },120 },121 ],122 ["the image", { ...encodedRun, image: "node:24-trixie-slim" }],123 [124 "the setup egress",125 { ...encodedRun, setupEgress: ["registry.npmjs.org"] },126 ],127 ])("differs when %s changes", (_what, changed) => {128 expect(checkVersion(redThenGreen, "0.3.1", runBlock(changed))).not.toBe(129 checkVersion(redThenGreen, "0.3.1", run)130 );131 });132133 it("differs by the check file, the SDK version and the check kind", () => {134 const version = checkVersion(redThenGreen, "0.3.1", run);135 const otherFile = redThenGreenOn("packages/parse/test/day.test.ts");136137 expect(checkVersion(otherFile, "0.3.1", run)).not.toBe(version);138 expect(checkVersion(redThenGreen, "0.3.2", run)).not.toBe(version);139 expect(checkVersion(lintToZero, "0.3.1", run)).not.toBe(version);140 });141142 it("is unchanged by the doctor command, which judges nothing", () => {143 const withDoctor = runBlock({ ...encodedRun, doctor: "bun --version" });144145 expect(checkVersion(redThenGreen, "0.3.1", withDoctor)).toBe(146 checkVersion(redThenGreen, "0.3.1", run)147 );148 });149150 it("follows a ratchet's measure, not just its name", () => {151 expect(152 checkVersion(ratchet, "0.3.1", run, countingRule("no-console"))153 ).not.toBe(checkVersion(ratchet, "0.3.1", run, ratchets));154 });155});156157describe(commandFor, () => {158 it("runs the run block's test on the ask's check file for redThenGreen", () => {159 expect(commandFor(redThenGreen, run)).toStrictEqual(160 Option.some({161 command: "bun test packages/parse/test/week.test.ts",162 lane: "redThenGreen",163 })164 );165 });166167 it("quotes a check file whose path the shell would split", () => {168 expect(169 commandFor(redThenGreenOn("test/it's a week.test.ts"), run)170 ).toStrictEqual(171 Option.some({172 command: String.raw`bun test 'test/it'\''s a week.test.ts'`,173 lane: "redThenGreen",174 })175 );176 });177178 it("can't run redThenGreen when the test command has no {path}", () => {179 expect(180 commandFor(redThenGreen, runBlock({ ...encodedRun, test: "make test" }))181 ).toStrictEqual(Option.none());182 });183184 it.each([185 [lintToZero, "oxlint --format json", "lintToZero"],186 [migrate, "bun scripts/count.ts dayjs", "migrate"],187 [symbolAbsent, "bun scripts/count.ts dayjs", "symbolAbsent"],188 ])("runs %o's own command", (spec, command, lane) => {189 expect(commandFor(spec, run)).toStrictEqual(Option.some({ command, lane }));190 });191192 it("runs a ratchet's measure command, and nothing for a ratchet the policy doesn't declare", () => {193 expect(commandFor(ratchet, run, ratchets)).toStrictEqual(194 Option.some({ command: "oxlint --format json", lane: "ratchet" })195 );196 expect(commandFor(ratchet, run)).toStrictEqual(Option.none());197 });198});199200describe(checkKindOf, () => {201 it.each([202 [redThenGreen, "redThenGreen"],203 [lintToZero, "lintToZero"],204 [ratchet, "ratchet"],205 [migrate, "migrate"],206 [symbolAbsent, "symbolAbsent"],207 ])("names %o's check kind %s", (spec, kind) => {208 expect(checkKindOf(spec)).toBe(kind);209 });210});