Merge build/403-lint-to-zero-and-ratchets: ratchets count the project's own lint output, move down by themselves, and rise only by a decision
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents f76d27f, 5c1b17d · Browse files · 15 files·+1844 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
15 files+1844 added−0 removed
- tests:+1150 added−0 removed
- other:+694 added−0 removed
Provenance
- Commit
a560b12- Tree
2026d3e- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
f76d27f- Parent 2
5c1b17d
15 files changed+1844 added−0 removed
added:packages/checks/src/kinds/lint-count.ts+263 added
1+/**2+ * Lint counts: how many findings a project's own linter reports, read from3+ * the JSON it prints (oxlint's `--format json` or ESLint's `--format json`),4+ * per path, for one rule or all, within a territory. Pure: the linter runs5+ * elsewhere, and this reads what it printed, exactly as it printed it.6+ */7+import type { Glob } from "@repo/protocol/domain/common";8+import { RepoPath } from "@repo/protocol/ids";9+import { Option, Order, Result, Schema } from "effect";10+11+import { matchGlob } from "../judge.ts";12+13+/** The JSON a linter prints: oxlint's report object, or ESLint's array of files. */14+export type LintFormat = "oxlint" | "eslint";15+16+/** A lint count: the findings in all, and per repo path (only paths with any). */17+export interface LintCount {18+ readonly total: number;19+ readonly byPath: ReadonlyMap<RepoPath, number>;20+}21+22+/** How much of an unreadable output a `CountUnreadable` keeps. */23+const HEAD_LENGTH = 200;24+25+/**26+ * A counter's output held no count the platform can read: not JSON, not the27+ * shape its format prints, or no integer where a metric's path points. It28+ * keeps the output's first 200 characters, so the answerer and the deciders29+ * see what the command printed instead.30+ */31+export class CountUnreadable extends Schema.TaggedError<CountUnreadable>()(32+ "CountUnreadable",33+ { head: Schema.String }34+) {35+ static readonly of = (output: string) =>36+ new CountUnreadable({ head: output.slice(0, HEAD_LENGTH) });37+}38+39+// `oxlint --format json`: one object; each diagnostic names its file and,40+// unless it is a parse error or a directive report, its rule as41+// `plugin(rule)`.42+const OxlintReport = Schema.Struct({43+ diagnostics: Schema.Array(44+ Schema.Struct({45+ code: Schema.optionalKey(Schema.String),46+ filename: Schema.NonEmptyString,47+ })48+ ),49+});50+51+// `eslint --format json`: one entry per file, each with its messages; a52+// parse error or a directive report has a null `ruleId`.53+const EslintReport = Schema.Array(54+ Schema.Struct({55+ filePath: Schema.NonEmptyString,56+ messages: Schema.Array(57+ Schema.Struct({58+ ruleId: Schema.optionalKey(Schema.NullOr(Schema.String)),59+ })60+ ),61+ })62+);63+64+/** One finding: the file it is in, and the rule that reported it, if one did. */65+interface Finding {66+ readonly path: string;67+ readonly rule: Option.Option<string>;68+}69+70+const readOxlint = Schema.decodeOption(Schema.fromJsonString(OxlintReport));71+72+const readEslint = Schema.decodeOption(Schema.fromJsonString(EslintReport));73+74+const findingsOf = (75+ output: string,76+ format: LintFormat77+): Option.Option<readonly Finding[]> =>78+ format === "oxlint"79+ ? Option.map(readOxlint(output), ({ diagnostics }) =>80+ diagnostics.map(({ code, filename }) => ({81+ path: filename,82+ rule: Option.fromNullishOr(code),83+ }))84+ )85+ : Option.map(readEslint(output), (files) =>86+ files.flatMap(({ filePath, messages }) =>87+ messages.map(({ ruleId }) => ({88+ path: filePath,89+ rule: Option.fromNullishOr(ruleId),90+ }))91+ )92+ );93+94+/**95+ * A rule, as either tool or a maintainer writes it: oxlint's code form96+ * `typescript(no-explicit-any)`, a config's `typescript/no-explicit-any`,97+ * ESLint's `@typescript-eslint/no-explicit-any`, or a bare `no-debugger`.98+ * `plugin` is `None` for a bare name.99+ */100+interface RuleName {101+ readonly plugin: Option.Option<string>;102+ readonly name: string;103+}104+105+// `plugin(rule)`, oxlint's code form.106+const CODE_FORM = /^(?<plugin>[^()]+)\((?<name>[^()]+)\)$/u;107+108+// The core rules' plugin: oxlint prints them as `eslint(no-debugger)`, ESLint109+// as a bare `no-debugger`.110+const CORE = "eslint";111+112+// One plugin under the names the two tools and their configs use for it:113+// `@typescript-eslint`, `typescript-eslint` and `typescript` are one plugin,114+// and `eslint-plugin-unicorn` is `unicorn`.115+const pluginOf = (written: string) => {116+ const unscoped = written.replace(/^@/u, "").replace(/^eslint-plugin-/u, "");117+118+ return unscoped === "typescript-eslint" ? "typescript" : unscoped;119+};120+121+const ruleNameOf = (written: string): RuleName => {122+ const code = CODE_FORM.exec(written)?.groups;123+124+ if (code?.plugin !== undefined && code.name !== undefined) {125+ return { name: code.name, plugin: Option.some(pluginOf(code.plugin)) };126+ }127+128+ const slash = written.lastIndexOf("/");129+130+ return slash === -1131+ ? { name: written, plugin: Option.none() }132+ : {133+ name: written.slice(slash + 1),134+ plugin: Option.some(pluginOf(written.slice(0, slash))),135+ };136+};137+138+/**139+ * Whether a finding's rule is the one asked for. A bare name asks for that140+ * rule in any plugin (`no-explicit-any` counts typescript's); a finding's141+ * bare name is a core rule. A finding with no rule (a file the linter could142+ * not parse, an unused directive) is counted only when no rule is asked for.143+ */144+const isRule =145+ (wanted: RuleName) =>146+ (finding: Finding): boolean =>147+ Option.match(finding.rule, {148+ onNone: () => false,149+ onSome: (written) => {150+ const found = ruleNameOf(written);151+152+ return (153+ found.name === wanted.name &&154+ Option.match(wanted.plugin, {155+ onNone: () => true,156+ onSome: (plugin) =>157+ plugin === Option.getOrElse(found.plugin, () => CORE),158+ })159+ );160+ },161+ });162+163+/** A path relative to the repo: without `root`'s prefix and any leading `./`. */164+const repoPathOf = (path: string, root: Option.Option<string>): string => {165+ const inside = Option.match(root, {166+ onNone: () => path,167+ onSome: (dir) => {168+ const prefix = dir.endsWith("/") ? dir : `${dir}/`;169+170+ return path.startsWith(prefix) && path.length > prefix.length171+ ? path.slice(prefix.length)172+ : path;173+ },174+ });175+176+ return inside.replace(/^(?:\.\/)+(?=.)/u, "");177+};178+179+const EXCLUDE = "!";180+181+/** Whether a path is in a territory: some glob matches it, and no `!` glob takes it back. */182+const within = (territory: readonly Glob[], path: string) =>183+ territory.some(184+ (glob) => !glob.startsWith(EXCLUDE) && matchGlob(glob, path)185+ ) &&186+ !territory.some(187+ (glob) =>188+ glob.startsWith(EXCLUDE) && matchGlob(glob.slice(EXCLUDE.length), path)189+ );190+191+const totalOf = (byPath: ReadonlyMap<RepoPath, number>) =>192+ [...byPath.values()].reduce((sum, count) => sum + count, 0);193+194+/**195+ * The part of a count inside a territory: the paths its globs match, with196+ * `!` globs taking paths back out. One linter run counted once serves every197+ * territory a ratchet keeps a baseline for.198+ */199+export const countWithin = (200+ count: LintCount,201+ territory: readonly Glob[]202+): LintCount => {203+ const byPath = new Map(204+ [...count.byPath].filter(([path]) => within(territory, path))205+ );206+207+ return { byPath, total: totalOf(byPath) };208+};209+210+/** The format an output is in, by its JSON's shape: an array is ESLint's. */211+const detect = (output: string): LintFormat =>212+ output.trimStart().startsWith("[") ? "eslint" : "oxlint";213+214+/**215+ * Counts a linter's findings from its JSON output, per repo path. `rule`216+ * keeps one rule's (in either tool's spelling); `territory` keeps the paths217+ * its globs match (with `!` taking paths back out); `root` is stripped from218+ * the front of each path, since ESLint prints absolute ones. The format is219+ * read from the output when not given. Output it can't read, in the format220+ * given or detected, is a `CountUnreadable`, never a thrown error.221+ */222+export const countLint = (input: {223+ readonly output: string;224+ readonly format?: LintFormat | undefined;225+ readonly rule?: string | undefined;226+ readonly territory?: readonly Glob[] | undefined;227+ readonly root?: string | undefined;228+}): Result.Result<LintCount, CountUnreadable> => {229+ const root = Option.fromNullishOr(input.root);230+ const wanted = Option.map(Option.fromNullishOr(input.rule), ruleNameOf);231+232+ return Result.fromOption(233+ findingsOf(input.output, input.format ?? detect(input.output)),234+ () => CountUnreadable.of(input.output)235+ ).pipe(236+ Result.map((findings) => {237+ const counts = new Map<RepoPath, number>();238+239+ for (const finding of findings) {240+ const counted = Option.match(wanted, {241+ onNone: () => true,242+ onSome: (rule) => isRule(rule)(finding),243+ });244+245+ if (counted) {246+ const path = RepoPath.make(repoPathOf(finding.path, root));247+248+ counts.set(path, (counts.get(path) ?? 0) + 1);249+ }250+ }251+252+ const byPath = new Map(253+ [...counts].toSorted(([one], [other]) => Order.String(one, other))254+ );255+256+ const count = { byPath, total: totalOf(byPath) };257+258+ return input.territory === undefined259+ ? count260+ : countWithin(count, input.territory);261+ })262+ );263+};added:packages/checks/src/kinds/lint-to-zero.ts+13 added
12345678910111213/** * The `lintToZero` check kind: a lint rule's count in a territory is the * test. It is red while the rule reports anything there and green at zero, * so an ask of this kind fails on main by the count itself (CAA E). The count * comes from `countLint`, with the rule and territory already applied. */import type { LintCount } from "./lint-count.ts";
/** Red: the rule still reports something in the territory. */export const lintToZeroRed = (count: LintCount): boolean => count.total > 0;
/** Green: the rule reports nothing in the territory. */export const lintToZeroGreen = (count: LintCount): boolean => count.total === 0;added:packages/checks/src/kinds/metric.ts+94 added
1+/**2+ * A ratchet's metric: one integer a project's own command prints in its JSON,3+ * found by a small JSONPath (`$`, `.key`, `[index]`, nothing more). Pure: the4+ * command runs elsewhere, and this reads what it printed.5+ */6+import type { JsonPath } from "@repo/protocol/domain/common";7+import { Option, Predicate, Result, Schema } from "effect";8+9+import { CountUnreadable } from "./lint-count.ts";10+11+/** One step down a JSON value: an object's key, or an array's index. */12+type Step = string | number;13+14+// One step at the start of what is left of a path: `.key` or `[index]`.15+const STEP = /^(?:\.(?<key>[\w$-]+)|\[(?<index>\d+)\])/u;16+17+/** A path's steps, or `None` when it leaves the supported subset. */18+const stepsOf = (path: string): Option.Option<readonly Step[]> => {19+ if (!path.startsWith("$")) {20+ return Option.none();21+ }22+23+ const steps: Step[] = [];24+ let rest = path.slice(1);25+26+ while (rest.length > 0) {27+ const found = STEP.exec(rest);28+ const key = found?.groups?.key;29+ const index = found?.groups?.index;30+31+ if (found === null) {32+ return Option.none();33+ }34+35+ steps.push(key ?? Number(index));36+ rest = rest.slice(found[0].length);37+ }38+39+ return Option.some(steps);40+};41+42+const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>43+ Array.isArray(value);44+45+const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>46+ Predicate.isObject(value);47+48+/** The value one step down, if the value has it: a key on an object, an index on an array. */49+const down = (value: Schema.Json, step: Step): Option.Option<Schema.Json> => {50+ if (Predicate.isNumber(step)) {51+ return isJsonArray(value)52+ ? Option.fromNullishOr(value[step])53+ : Option.none();54+ }55+56+ return isJsonObject(value) && Object.hasOwn(value, step)57+ ? Option.fromNullishOr(value[step])58+ : Option.none();59+};60+61+/** The value at the end of a path's steps, if the value has every one. */62+const walk = (63+ value: Schema.Json,64+ steps: readonly Step[]65+): Option.Option<Schema.Json> => {66+ const [step, ...rest] = steps;67+68+ return step === undefined69+ ? Option.some(value)70+ : Option.flatMap(down(value, step), (next) => walk(next, rest));71+};72+73+const decodeJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));74+75+const isCount = (value: Schema.Json): value is number =>76+ Predicate.isNumber(value) && Number.isSafeInteger(value);77+78+/**79+ * The integer at `path` in a command's JSON output. Output that isn't JSON,80+ * a path outside the subset, a path the output lacks, or anything there but81+ * an integer is a `CountUnreadable` holding the output's head.82+ */83+export const readMetric = (84+ output: string,85+ path: JsonPath86+): Result.Result<number, CountUnreadable> =>87+ Result.fromOption(88+ Option.flatMap(stepsOf(path), (steps) =>89+ Option.flatMap(decodeJson(output), (json) =>90+ Option.filter(walk(json, steps), isCount)91+ )92+ ),93+ () => CountUnreadable.of(output)94+ );added:packages/checks/src/kinds/ratchet.ts+117 added
1+/**2+ * The `ratchet` check kind's measure: run a ratchet's declared command once3+ * and read its number per territory, exactly as the project's own tool4+ * reports it. A lint count splits by path, so it yields one count per5+ * territory (per-territory baselines, so the children of a split land on6+ * their own; FE §8.4 B3); a metric is one number, so it yields one. The7+ * command runs through the runner it is given, never here.8+ */9+import { RatchetMeasure } from "@repo/protocol/domain/check";10+import type { RatchetSpec } from "@repo/protocol/domain/check";11+import { Glob } from "@repo/protocol/domain/common";12+import type { Territory } from "@repo/protocol/domain/territory";13+import type { RatchetName } from "@repo/protocol/ids";14+import { Effect } from "effect";15+16+import { countLint, countWithin } from "./lint-count.ts";17+import type { CountUnreadable } from "./lint-count.ts";18+import { readMetric } from "./metric.ts";19+20+/** A ratchet's number in one territory, as one run measured it. */21+export interface RatchetCount {22+ readonly ratchet: RatchetName;23+ readonly territory: string;24+ readonly count: number;25+}26+27+/**28+ * The territory a ratchet counts when it names none and the project has no29+ * modules, and the one a metric counts when it names none: the whole project,30+ * named as a single-package repo's module is.31+ */32+export const WHOLE_PROJECT = ".";33+34+/** A territory a count is split by: its name, and the globs of its paths. */35+interface Counted {36+ readonly name: string;37+ readonly paths: readonly Glob[];38+}39+40+const ALL_PATHS: readonly Glob[] = [Glob.make("**")];41+42+/**43+ * A territory a spec names: a module by its name, or else the name read as a44+ * glob, as the gate reads a ratchet's territory.45+ */46+const named = (47+ territories: readonly Territory[],48+ territory: string49+): Counted => ({50+ name: territory,51+ paths: territories.find(({ module }) => module === territory)?.paths ?? [52+ Glob.make(territory),53+ ],54+});55+56+/** The territories a spec's count is split by. */57+const countedIn = (58+ spec: RatchetSpec,59+ territories: readonly Territory[]60+): readonly Counted[] => {61+ if (spec.territory !== undefined) {62+ return [named(territories, spec.territory)];63+ }64+65+ return territories.length === 066+ ? [{ name: WHOLE_PROJECT, paths: ALL_PATHS }]67+ : territories.map(({ module, paths }) => ({ name: module, paths }));68+};69+70+/**71+ * Runs a ratchet's command once and reads its count per territory. A `Count`72+ * reads the linter's JSON (oxlint's or ESLint's, detected; `root` makes73+ * absolute paths repo-relative) for the spec's rule and yields one count per74+ * territory: the one the spec names, else each module, else the whole75+ * project. A `Metric` reads one integer at its path and yields one count, for76+ * the territory the spec names or the whole project. The command's exit code77+ * is not read (a linter with findings exits 1); output with no count in it78+ * fails with `CountUnreadable`.79+ */80+export const measure = <E, R>(81+ spec: RatchetSpec,82+ run: (83+ command: string84+ ) => Effect.Effect<{ readonly code: number; readonly stdout: string }, E, R>,85+ territories: readonly Territory[],86+ options: { readonly root?: string } = {}87+): Effect.Effect<readonly RatchetCount[], E | CountUnreadable, R> =>88+ RatchetMeasure.match(spec.measure, {89+ Count: ({ command, rule }) =>90+ run(command).pipe(91+ Effect.flatMap(({ stdout }) =>92+ Effect.fromResult(93+ countLint({ output: stdout, root: options.root, rule })94+ )95+ ),96+ Effect.map((count) =>97+ countedIn(spec, territories).map(({ name, paths }) => ({98+ count: countWithin(count, paths).total,99+ ratchet: spec.name,100+ territory: name,101+ }))102+ )103+ ),104+ Metric: ({ command, path }) =>105+ run(command).pipe(106+ Effect.flatMap(({ stdout }) =>107+ Effect.fromResult(readMetric(stdout, path))108+ ),109+ Effect.map((count) => [110+ {111+ count,112+ ratchet: spec.name,113+ territory: spec.territory ?? WHOLE_PROJECT,114+ },115+ ])116+ ),117+ });added:packages/checks/test/fixtures/lint/eslint.stdout+1 added
1+[{"filePath":"/srv/fixture/packages/lexer/src/lex.ts","messages":[{"ruleId":"@typescript-eslint/no-explicit-any","severity":2,"message":"Unexpected any. Specify a different type.","line":1,"column":47,"nodeType":"TSAnyKeyword","messageId":"unexpectedAny","endLine":1,"endColumn":50,"suggestions":[{"messageId":"suggestUnknown","fix":{"range":[46,49],"text":"unknown"},"desc":"Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."},{"messageId":"suggestNever","fix":{"range":[46,49],"text":"never"},"desc":"Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."}]}],"suppressedMessages":[],"errorCount":1,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"source":"export const lex = (source: string): readonly any[] => source.split(\" \");\n","usedDeprecatedRules":[]},{"filePath":"/srv/fixture/packages/parser/src/date.ts","messages":[{"ruleId":"@typescript-eslint/no-explicit-any","severity":2,"message":"Unexpected any. Specify a different type.","line":1,"column":31,"nodeType":"TSAnyKeyword","messageId":"unexpectedAny","endLine":1,"endColumn":34,"suggestions":[{"messageId":"suggestUnknown","fix":{"range":[30,33],"text":"unknown"},"desc":"Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."},{"messageId":"suggestNever","fix":{"range":[30,33],"text":"never"},"desc":"Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."}]}],"suppressedMessages":[],"errorCount":1,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"source":"export const toDate = (value: any) => new Date(String(value));\n","usedDeprecatedRules":[]},{"filePath":"/srv/fixture/packages/parser/src/parse.ts","messages":[{"ruleId":"@typescript-eslint/no-explicit-any","severity":2,"message":"Unexpected any. Specify a different type.","line":1,"column":30,"nodeType":"TSAnyKeyword","messageId":"unexpectedAny","endLine":1,"endColumn":33,"suggestions":[{"messageId":"suggestUnknown","fix":{"range":[29,32],"text":"unknown"},"desc":"Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."},{"messageId":"suggestNever","fix":{"range":[29,32],"text":"never"},"desc":"Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."}]},{"ruleId":"@typescript-eslint/no-explicit-any","severity":2,"message":"Unexpected any. Specify a different type.","line":1,"column":36,"nodeType":"TSAnyKeyword","messageId":"unexpectedAny","endLine":1,"endColumn":39,"suggestions":[{"messageId":"suggestUnknown","fix":{"range":[35,38],"text":"unknown"},"desc":"Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."},{"messageId":"suggestNever","fix":{"range":[35,38],"text":"never"},"desc":"Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."}]},{"ruleId":"@typescript-eslint/no-explicit-any","severity":2,"message":"Unexpected any. Specify a different type.","line":2,"column":17,"nodeType":"TSAnyKeyword","messageId":"unexpectedAny","endLine":2,"endColumn":20,"suggestions":[{"messageId":"suggestUnknown","fix":{"range":[60,63],"text":"unknown"},"desc":"Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct."},{"messageId":"suggestNever","fix":{"range":[60,63],"text":"never"},"desc":"Use `never` instead, this is useful when instantiating generic type parameters that you don't need to know the type of."}]},{"ruleId":"no-debugger","severity":2,"message":"Unexpected 'debugger' statement.","line":3,"column":3,"nodeType":"DebuggerStatement","messageId":"unexpected","endLine":3,"endColumn":12}],"suppressedMessages":[],"errorCount":4,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"source":"export const parse = (input: any): any => {\n const tokens: any[] = [];\n debugger;\n return { input, tokens };\n};\n","usedDeprecatedRules":[]},{"filePath":"/srv/fixture/packages/printer/src/print.ts","messages":[{"ruleId":"no-debugger","severity":2,"message":"Unexpected 'debugger' statement.","line":2,"column":3,"nodeType":"DebuggerStatement","messageId":"unexpected","endLine":2,"endColumn":12}],"suppressedMessages":[],"errorCount":1,"fatalErrorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0,"source":"export const print = (text: string) => {\n debugger;\n return text.trim();\n};\n","usedDeprecatedRules":[]}]added:packages/checks/test/fixtures/lint/oxlint-clean.stdout+7 added
1+{ "diagnostics": [],2+ "number_of_files": 1,3+ "number_of_rules": 1,4+ "threads_count": 16,5+ "start_time": 0.0102836946+ }7+ added:packages/checks/test/fixtures/lint/oxlint-default.stdout+7 added
1+packages/parser/src/date.ts:1:31: error typescript(no-explicit-any): Unexpected `any`. Specify a different type. help: Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.2+packages/parser/src/parse.ts:1:30: error typescript(no-explicit-any): Unexpected `any`. Specify a different type. help: Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.3+packages/parser/src/parse.ts:1:36: error typescript(no-explicit-any): Unexpected `any`. Specify a different type. help: Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.4+packages/parser/src/parse.ts:2:17: error typescript(no-explicit-any): Unexpected `any`. Specify a different type. help: Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.5+packages/parser/src/parse.ts:3:3: error eslint(no-debugger): `debugger` statement is not allowed help: Remove the debugger statement6+packages/printer/src/print.ts:2:3: error eslint(no-debugger): `debugger` statement is not allowed help: Remove the debugger statement7+packages/lexer/src/lex.ts:1:47: error typescript(no-explicit-any): Unexpected `any`. Specify a different type. help: Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.added:packages/checks/test/fixtures/lint/oxlint.stdout+13 added
1+{ "diagnostics": [{"message": "Unexpected `any`. Specify a different type.","code": "typescript(no-explicit-any)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html","help": "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.","filename": "packages/parser/src/date.ts","labels": [{"span": {"offset": 30,"length": 3,"line": 1,"column": 31}}]},2+{"message": "Unexpected `any`. Specify a different type.","code": "typescript(no-explicit-any)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html","help": "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.","filename": "packages/parser/src/parse.ts","labels": [{"span": {"offset": 29,"length": 3,"line": 1,"column": 30}}]},3+{"message": "Unexpected `any`. Specify a different type.","code": "typescript(no-explicit-any)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html","help": "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.","filename": "packages/parser/src/parse.ts","labels": [{"span": {"offset": 35,"length": 3,"line": 1,"column": 36}}]},4+{"message": "Unexpected `any`. Specify a different type.","code": "typescript(no-explicit-any)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html","help": "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.","filename": "packages/parser/src/parse.ts","labels": [{"span": {"offset": 60,"length": 3,"line": 2,"column": 17}}]},5+{"message": "`debugger` statement is not allowed","code": "eslint(no-debugger)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-debugger.html","help": "Remove the debugger statement","filename": "packages/parser/src/parse.ts","labels": [{"span": {"offset": 74,"length": 9,"line": 3,"column": 3}}]},6+{"message": "Unexpected `any`. Specify a different type.","code": "typescript(no-explicit-any)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/typescript/no-explicit-any.html","help": "Use `unknown` instead, this will force you to explicitly, and safely, assert the type is correct.","filename": "packages/lexer/src/lex.ts","labels": [{"span": {"offset": 46,"length": 3,"line": 1,"column": 47}}]},7+{"message": "`debugger` statement is not allowed","code": "eslint(no-debugger)","severity": "error","url": "https://oxc.rs/docs/guide/usage/linter/rules/eslint/no-debugger.html","help": "Remove the debugger statement","filename": "packages/printer/src/print.ts","labels": [{"span": {"offset": 43,"length": 9,"line": 2,"column": 3}}]}],8+ "number_of_files": 4,9+ "number_of_rules": 2,10+ "threads_count": 16,11+ "start_time": 0.01518029812+ }13+ added:packages/checks/test/kinds/lint-count.test.ts+254 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Glob } from "@repo/protocol/domain/common";3+import { RepoPath } from "@repo/protocol/ids";4+import { Effect, Option, Result } from "effect";5+6+import { countLint } from "../../src/kinds/lint-count.ts";7+import type {8+ CountUnreadable,9+ LintCount,10+ LintFormat,11+} from "../../src/kinds/lint-count.ts";12+import { recorded } from "./recorded.ts";13+14+// Recorded stdout, byte for byte, from one fixture repo of four files:15+//16+// packages/parser/src/parse.ts 3 `any`, 1 `debugger`17+// packages/parser/src/date.ts 1 `any`18+// packages/lexer/src/lex.ts 1 `any`19+// packages/printer/src/print.ts 1 `debugger`20+//21+// `oxlint.stdout`: this repo's oxlint 1.87.0, run in the fixture's root as22+// `oxlint --format json -A all -D typescript/no-explicit-any -D no-debugger23+// packages`. `oxlint-clean.stdout`: the same, `-D typescript/no-explicit-any`24+// over `packages/printer` alone. `oxlint-default.stdout`: the first command25+// without `--format json`. `eslint.stdout`: ESLint 9.39.5 with26+// typescript-eslint 8.63.0 (`@typescript-eslint/no-explicit-any` and27+// `no-debugger` at error), `eslint --format json packages`; ESLint prints28+// absolute paths, and the scratch folder it ran in is rewritten to29+// `/srv/fixture`.30+31+const ESLINT_ROOT = "/srv/fixture";32+33+const parse = RepoPath.make("packages/parser/src/parse.ts");34+35+const date = RepoPath.make("packages/parser/src/date.ts");36+37+const lex = RepoPath.make("packages/lexer/src/lex.ts");38+39+const print = RepoPath.make("packages/printer/src/print.ts");40+41+const counted = (entries: readonly (readonly [RepoPath, number])[]) =>42+ Result.succeed<LintCount>({43+ byPath: new Map(entries),44+ total: entries.reduce((sum, [, count]) => sum + count, 0),45+ });46+47+const anys = counted([48+ [parse, 3],49+ [date, 1],50+ [lex, 1],51+]);52+53+const debuggers = counted([54+ [parse, 1],55+ [print, 1],56+]);57+58+const globs = (...patterns: readonly string[]) =>59+ patterns.map((pattern) => Glob.make(pattern));60+61+/** What an unreadable count kept of the output, or `None` when it counted. */62+const unreadHead = (result: Result.Result<LintCount, CountUnreadable>) =>63+ Result.match(result, {64+ onFailure: ({ head }) => Option.some(head),65+ onSuccess: () => Option.none(),66+ });67+68+/** Both recordings, each with what makes its paths repo-relative. */69+const both = Effect.all({70+ eslint: recorded("eslint").pipe(71+ Effect.map((output) => ({ output, root: ESLINT_ROOT }))72+ ),73+ oxlint: recorded("oxlint").pipe(Effect.map((output) => ({ output }))),74+});75+76+/** How many `any`s a recording counts within a territory's globs. */77+const anysWithin = (78+ input: { readonly output: string; readonly root?: string },79+ territory: readonly string[]80+) =>81+ Result.map(82+ countLint({83+ ...input,84+ rule: "typescript/no-explicit-any",85+ territory: globs(...territory),86+ }),87+ (count) => count.total88+ );89+90+describe(countLint, () => {91+ it.effect("counts every finding in oxlint's JSON, per path", () =>92+ Effect.gen(function* () {93+ const output = yield* recorded("oxlint");94+95+ expect(countLint({ output })).toStrictEqual(96+ counted([97+ [parse, 4],98+ [date, 1],99+ [lex, 1],100+ [print, 1],101+ ])102+ );103+ })104+ );105+106+ it.effect("counts every finding in ESLint's JSON, per repo path", () =>107+ Effect.gen(function* () {108+ const output = yield* recorded("eslint");109+110+ expect(countLint({ output, root: ESLINT_ROOT })).toStrictEqual(111+ counted([112+ [parse, 4],113+ [date, 1],114+ [lex, 1],115+ [print, 1],116+ ])117+ );118+ })119+ );120+121+ it.effect("keeps ESLint's absolute paths when no root is given", () =>122+ Effect.gen(function* () {123+ const output = yield* recorded("eslint");124+ const count = Result.getOrThrow(countLint({ output }));125+126+ expect([...count.byPath.keys()]).toContain(127+ `${ESLINT_ROOT}/packages/lexer/src/lex.ts`128+ );129+ })130+ );131+132+ it.effect.each([133+ "typescript/no-explicit-any",134+ "@typescript-eslint/no-explicit-any",135+ "typescript-eslint(no-explicit-any)",136+ "typescript(no-explicit-any)",137+ "no-explicit-any",138+ ])("counts one rule written as %s, in either tool's output", (rule) =>139+ Effect.gen(function* () {140+ const { eslint, oxlint } = yield* both;141+142+ expect(countLint({ ...oxlint, rule })).toStrictEqual(anys);143+ expect(countLint({ ...eslint, rule })).toStrictEqual(anys);144+ })145+ );146+147+ it.effect.each(["no-debugger", "eslint/no-debugger", "eslint(no-debugger)"])(148+ "counts a core rule written as %s, in either tool's output",149+ (rule) =>150+ Effect.gen(function* () {151+ const { eslint, oxlint } = yield* both;152+153+ expect(countLint({ ...oxlint, rule })).toStrictEqual(debuggers);154+ expect(countLint({ ...eslint, rule })).toStrictEqual(debuggers);155+ })156+ );157+158+ it.effect("counts nothing for a rule in another plugin", () =>159+ Effect.gen(function* () {160+ const { eslint, oxlint } = yield* both;161+ const rule = "unicorn/no-explicit-any";162+163+ expect(countLint({ ...oxlint, rule })).toStrictEqual(counted([]));164+ expect(countLint({ ...eslint, rule })).toStrictEqual(counted([]));165+ })166+ );167+168+ it.effect.each<readonly [string, readonly string[], LintCount["total"]]>([169+ ["one package", ["packages/parser/**"], 4],170+ ["two packages", ["packages/parser/**", "packages/lexer/**"], 5],171+ ["all but one", ["packages/**", "!packages/lexer/**"], 4],172+ ["one file", ["packages/parser/src/date.ts"], 1],173+ ["a package with none", ["packages/printer/**"], 0],174+ ])("counts within a territory: %s", ([, territory, total]) =>175+ Effect.gen(function* () {176+ const { eslint, oxlint } = yield* both;177+178+ expect(anysWithin(oxlint, territory)).toStrictEqual(179+ Result.succeed(total)180+ );181+ expect(anysWithin(eslint, territory)).toStrictEqual(182+ Result.succeed(total)183+ );184+ })185+ );186+187+ it.effect("names only the territory's paths", () =>188+ Effect.gen(function* () {189+ const output = yield* recorded("oxlint");190+191+ expect(192+ countLint({ output, territory: globs("packages/parser/**") })193+ ).toStrictEqual(194+ counted([195+ [parse, 4],196+ [date, 1],197+ ])198+ );199+ })200+ );201+202+ it.effect("reads a clean run as zero", () =>203+ Effect.gen(function* () {204+ const output = yield* recorded("oxlint-clean");205+206+ expect(countLint({ output })).toStrictEqual(counted([]));207+ expect(countLint({ format: "oxlint", output })).toStrictEqual(208+ counted([])209+ );210+ // ESLint over no files prints an empty array.211+ expect(countLint({ output: "[]\n" })).toStrictEqual(counted([]));212+ })213+ );214+215+ it.effect.each<readonly [LintFormat, string]>([216+ ["oxlint", "eslint"],217+ ["eslint", "oxlint"],218+ ])("refuses %s's format for %s's output", ([format, other]) =>219+ Effect.gen(function* () {220+ const output = yield* recorded(other);221+222+ expect(unreadHead(countLint({ format, output }))).toStrictEqual(223+ Option.some(output.slice(0, 200))224+ );225+ })226+ );227+228+ it.effect("keeps the first 200 characters of oxlint's text output", () =>229+ Effect.gen(function* () {230+ const output = yield* recorded("oxlint-default");231+232+ expect(output.length).toBeGreaterThan(200);233+ expect(unreadHead(countLint({ output }))).toStrictEqual(234+ Option.some(output.slice(0, 200))235+ );236+ })237+ );238+239+ it.each([240+ ["nothing", ""],241+ ["a crash", "Segmentation fault (core dumped)\n"],242+ ["JSON of another shape", '{"total": 3}'],243+ [244+ "a finding with no path",245+ '{"diagnostics": [{"code": "eslint(no-debugger)"}]}',246+ ],247+ ["ESLint's shape with no messages", '[{"filePath": "/srv/a.ts"}]'],248+ ["a bare number", "7"],249+ ])("never throws on %s, and keeps what it printed", (_label, output) => {250+ expect(unreadHead(countLint({ output }))).toStrictEqual(251+ Option.some(output)252+ );253+ });254+});added:packages/checks/test/kinds/lint-to-zero.test.ts+65 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import { describe, expect, it } from "@effect/vitest";import { Glob } from "@repo/protocol/domain/common";import { Effect, Result } from "effect";
import { countLint } from "../../src/kinds/lint-count.ts";import { lintToZeroGreen, lintToZeroRed,} from "../../src/kinds/lint-to-zero.ts";import { recorded } from "./recorded.ts";
// The recordings `lint-count.test.ts` describes: oxlint over a fixture with// `any` in `packages/parser` and `packages/lexer`, none in `packages/printer`.
const anysIn = (output: string, territory: string) => Result.getOrThrow( countLint({ output, rule: "typescript/no-explicit-any", territory: [Glob.make(territory)], }) );
describe("a lintToZero check", () => { it.effect.each(["packages/parser/**", "packages/lexer/**"])( "is red while the rule reports anything in %s", (territory) => Effect.gen(function* () { const count = anysIn(yield* recorded("oxlint"), territory);
expect(lintToZeroRed(count)).toBeTruthy(); expect(lintToZeroGreen(count)).toBeFalsy(); }) );
it.effect("is green where the rule reports nothing in its territory", () => Effect.gen(function* () { const count = anysIn(yield* recorded("oxlint"), "packages/printer/**");
expect(lintToZeroGreen(count)).toBeTruthy(); expect(lintToZeroRed(count)).toBeFalsy(); }) );
it.effect("is green on a clean run", () => Effect.gen(function* () { const count = anysIn(yield* recorded("oxlint-clean"), "packages/**");
expect(lintToZeroGreen(count)).toBeTruthy(); expect(lintToZeroRed(count)).toBeFalsy(); }) );
it("is red at one finding", () => { const count = Result.getOrThrow( countLint({ output: '{"diagnostics": [{"code": "eslint(no-debugger)", "filename": "src/a.ts"}]}', }) );
expect(lintToZeroRed(count)).toBeTruthy(); expect(lintToZeroGreen(count)).toBeFalsy(); });});added:packages/checks/test/kinds/metric.test.ts+72 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { describe, expect, it } from "@effect/vitest";import { JsonPath } from "@repo/protocol/domain/common";import { Option, Result } from "effect";
import type { CountUnreadable } from "../../src/kinds/lint-count.ts";import { readMetric } from "../../src/kinds/metric.ts";
const report = '{"total": 412, "parts": [{"kb": 3}, {"kb": 9}]}';
const read = (output: string, path: string) => readMetric(output, JsonPath.make(path));
/** What an unreadable count kept of the output, or `None` when it read one. */const unreadHead = (result: Result.Result<number, CountUnreadable>) => Result.match(result, { onFailure: ({ head }) => Option.some(head), onSuccess: () => Option.none(), });
describe(readMetric, () => { it.each([ ["$.total", 412], ["$.parts[0].kb", 3], ["$.parts[1].kb", 9], ])("reads %s from a command's JSON", (path, expected) => { expect(read(report, path)).toStrictEqual(Result.succeed(expected)); });
it("reads `$` as the whole output when the command prints one number", () => { expect(read("17\n", "$")).toStrictEqual(Result.succeed(17)); });
it.each([ ["a key the output lacks", "$.missing"], ["an index past the array's end", "$.parts[2].kb"], ["a key on an array", "$.parts.kb"], ["an index on an object", "$[0]"], ])("finds no count at %s", (_label, path) => { expect(unreadHead(read(report, path))).toStrictEqual(Option.some(report)); });
it.each([ ["a fraction", '{"total": 4.5}'], ["a string", '{"total": "412"}'], ["null", '{"total": null}'], ["an object", '{"total": {"lines": 3}}'], ])("refuses %s as a count", (_label, output) => { expect(unreadHead(read(output, "$.total"))).toStrictEqual( Option.some(output) ); });
it.each([ ["no leading $", "total"], ["recursive descent", "$..total"], ["a wildcard", "$.parts[*].kb"], ["a bracketed key", "$['total']"], ["a filter", "$.parts[?(@.kb > 1)].kb"], ["a negative index", "$.parts[-1].kb"], ["a trailing dot", "$.total."], ])("reads no path beyond `$`, `.key` and `[index]`: %s", (_label, path) => { expect(unreadHead(read(report, path))).toStrictEqual(Option.some(report)); });
it("keeps the first 200 characters of output that isn't JSON", () => { const output = `Error: counter crashed\n${"at frame\n".repeat(40)}`;
expect(unreadHead(read(output, "$.total"))).toStrictEqual( Option.some(output.slice(0, 200)) ); });});added:packages/checks/test/kinds/ratchet.test.ts+178 added
1+import { describe, expect, it } from "@effect/vitest";2+import { RatchetMeasure, RatchetSpec } from "@repo/protocol/domain/check";3+import { Command, Glob, JsonPath } from "@repo/protocol/domain/common";4+import type { Territory } from "@repo/protocol/domain/territory";5+import { RatchetName } from "@repo/protocol/ids";6+import { Effect, Exit, Ref } from "effect";7+8+import { CountUnreadable } from "../../src/kinds/lint-count.ts";9+import { measure } from "../../src/kinds/ratchet.ts";10+import { recorded } from "./recorded.ts";11+12+// The recordings `lint-count.test.ts` describes: `any` three times in13+// parse.ts and once in date.ts (packages/parser), once in lex.ts14+// (packages/lexer), never in packages/printer.15+16+const module = (name: string, folder: string): Territory => ({17+ module: name,18+ paths: [Glob.make(`${folder}/**`)],19+});20+21+const territories = [22+ module("@fixture/parser", "packages/parser"),23+ module("@fixture/lexer", "packages/lexer"),24+ module("@fixture/printer", "packages/printer"),25+];26+27+const anyCount = RatchetName.make("anyCount");28+29+const lintCommand = "oxlint --format json";30+31+/** Counts `any` with the project's linter, in every territory. */32+const counting = RatchetSpec.make({33+ measure: RatchetMeasure.cases.Count.make({34+ command: Command.make(lintCommand),35+ rule: "typescript/no-explicit-any",36+ }),37+ name: anyCount,38+});39+40+/** Counts `any` in the one territory the spec names. */41+const countingIn = (territory: string) =>42+ RatchetSpec.make({ ...counting, territory });43+44+const bundleKb = RatchetName.make("bundleKb");45+46+const bundleCommand = "bun scripts/bundle-size.ts --json";47+48+/** Reads one number from a bundle report, for the whole project. */49+const bundle = RatchetSpec.make({50+ measure: RatchetMeasure.cases.Metric.make({51+ command: Command.make(bundleCommand),52+ path: JsonPath.make("$.parts[1].kb"),53+ }),54+ name: bundleKb,55+});56+57+/** A fake runner that prints `stdout` for any command, exiting 1 as a linter with findings does, and keeps what it was asked to run. */58+const printing = (stdout: string) =>59+ Effect.gen(function* () {60+ const ran = yield* Ref.make<readonly string[]>([]);61+62+ const run = (command: string) =>63+ Ref.update(ran, (commands) => [...commands, command]).pipe(64+ Effect.as({ code: 1, stdout })65+ );66+67+ return { ran, run };68+ });69+70+describe(measure, () => {71+ it.effect("counts once per territory, from one run of the command", () =>72+ Effect.gen(function* () {73+ const { ran, run } = yield* printing(yield* recorded("oxlint"));74+75+ expect(yield* measure(counting, run, territories)).toStrictEqual([76+ { count: 4, ratchet: anyCount, territory: "@fixture/parser" },77+ { count: 1, ratchet: anyCount, territory: "@fixture/lexer" },78+ { count: 0, ratchet: anyCount, territory: "@fixture/printer" },79+ ]);80+ expect(yield* Ref.get(ran)).toStrictEqual([lintCommand]);81+ })82+ );83+84+ it.effect("counts only the territory a spec names, by its module", () =>85+ Effect.gen(function* () {86+ const { run } = yield* printing(yield* recorded("oxlint"));87+88+ expect(89+ yield* measure(countingIn("@fixture/lexer"), run, territories)90+ ).toStrictEqual([91+ { count: 1, ratchet: anyCount, territory: "@fixture/lexer" },92+ ]);93+ })94+ );95+96+ it.effect("reads a territory no module names as a glob", () =>97+ Effect.gen(function* () {98+ const { run } = yield* printing(yield* recorded("oxlint"));99+100+ expect(101+ yield* measure(countingIn("packages/parser/src/parse.ts"), run, [])102+ ).toStrictEqual([103+ {104+ count: 3,105+ ratchet: anyCount,106+ territory: "packages/parser/src/parse.ts",107+ },108+ ]);109+ })110+ );111+112+ it.effect("counts a project with no modules as one territory, `.`", () =>113+ Effect.gen(function* () {114+ const { run } = yield* printing(yield* recorded("oxlint"));115+116+ expect(yield* measure(counting, run, [])).toStrictEqual([117+ { count: 5, ratchet: anyCount, territory: "." },118+ ]);119+ })120+ );121+122+ it.effect("makes ESLint's absolute paths repo-relative against a root", () =>123+ Effect.gen(function* () {124+ const { run } = yield* printing(yield* recorded("eslint"));125+126+ expect(127+ yield* measure(counting, run, territories, { root: "/srv/fixture" })128+ ).toStrictEqual([129+ { count: 4, ratchet: anyCount, territory: "@fixture/parser" },130+ { count: 1, ratchet: anyCount, territory: "@fixture/lexer" },131+ { count: 0, ratchet: anyCount, territory: "@fixture/printer" },132+ ]);133+ })134+ );135+136+ it.effect("reads a metric as one count, for the territory it names", () =>137+ Effect.gen(function* () {138+ const { ran, run } = yield* printing(139+ '{"total": 412, "parts": [{"kb": 3}, {"kb": 9}]}'140+ );141+142+ expect(143+ yield* measure(144+ RatchetSpec.make({ ...bundle, territory: "@fixture/printer" }),145+ run,146+ territories147+ )148+ ).toStrictEqual([149+ { count: 9, ratchet: bundleKb, territory: "@fixture/printer" },150+ ]);151+ expect(yield* measure(bundle, run, territories)).toStrictEqual([152+ { count: 9, ratchet: bundleKb, territory: "." },153+ ]);154+ expect(yield* Ref.get(ran)).toStrictEqual([bundleCommand, bundleCommand]);155+ })156+ );157+158+ it.effect("fails with CountUnreadable when the output holds no count", () =>159+ Effect.gen(function* () {160+ const output = yield* recorded("oxlint-default");161+ const { run } = yield* printing(output);162+163+ expect(164+ yield* Effect.exit(measure(counting, run, territories))165+ ).toStrictEqual(Exit.fail(CountUnreadable.of(output)));166+ })167+ );168+169+ it.effect("passes the runner's own failure through", () =>170+ Effect.gen(function* () {171+ const exit = yield* Effect.exit(172+ measure(counting, () => Effect.fail("no checker" as const), [])173+ );174+175+ expect(exit).toStrictEqual(Exit.fail("no checker"));176+ })177+ );178+});added:packages/checks/test/kinds/recorded.ts+17 added
1234567891011121314151617/** * The recorded linter output the kinds' tests read: stdout byte for byte, * from `test/fixtures/lint/<name>.stdout`. `lint-count.test.ts` describes * the fixture repo and the commands that printed each one. */import { NodeServices } from "@effect/platform-node";import { Effect, FileSystem } from "effect";
/** One recording's stdout, by its name without `.stdout`. */export const recorded = (name: string) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem;
return yield* fs.readFileString( `${import.meta.dirname}/../fixtures/lint/${name}.stdout` ); }).pipe(Effect.orDie, Effect.provide(NodeServices.layer));added:packages/project/src/ratchets.ts+207 added
1+/**2+ * Ratchets' baselines, and the rules that move them (GLOSSARY "Ratchet"):3+ * a baseline per (ratchet, territory), recorded at landing and lowered by a4+ * landing with no one asking; an answer that raises one is refused, unless5+ * it asks a decider to raise it; the only way up is a `RaiseRatchet`6+ * decision a decider accepts. Pure: the counts come from7+ * `@repo/checks/kinds/ratchet`'s `measure`, and the baselines live in the8+ * Project DO's `ratchets` rows (no suppressions file in the tree; FE §8.4 B3).9+ */10+import type { RatchetCount } from "@repo/checks/kinds/ratchet";11+import { DecisionSubject } from "@repo/protocol/domain/decision";12+import type { Choice } from "@repo/protocol/domain/decision";13+import type { AskId, LandedSha, RatchetName } from "@repo/protocol/ids";14+import { Weakened } from "@repo/protocol/refusal";15+import { Array, Option } from "effect";16+17+/** A ratchet's baseline in one territory, and the landed SHA that set it. */18+export interface RatchetBaseline {19+ readonly ratchet: RatchetName;20+ readonly territory: string;21+ readonly count: number;22+ readonly setAt: LandedSha;23+}24+25+/** An answer asking a decider to raise one ratchet in one territory, and why. */26+export interface RaiseRequest {27+ readonly ratchet: RatchetName;28+ readonly territory: string;29+ readonly reason: string;30+}31+32+/** The decision a raise waits on. */33+export type RaiseRatchet = Extract<DecisionSubject, { _tag: "RaiseRatchet" }>;34+35+/** A baseline a landing lowered, from what to what. */36+export interface Lowered {37+ readonly ratchet: RatchetName;38+ readonly territory: string;39+ readonly before: number;40+ readonly after: number;41+}42+43+/** What judging an answer's counts gives: its refusals, and the raises it waits on. */44+export interface RatchetJudgement {45+ readonly refusals: readonly Weakened[];46+ readonly decisions: readonly RaiseRatchet[];47+}48+49+/** The baselines after a landing, and the ones it lowered. */50+export interface BaselinesAfterLanding {51+ readonly baselines: readonly RatchetBaseline[];52+ readonly lowered: readonly Lowered[];53+}54+55+interface Keyed {56+ readonly ratchet: RatchetName;57+ readonly territory: string;58+}59+60+/** Whether two rows name one ratchet in one territory. */61+const sameRatchet =62+ (one: Keyed) =>63+ (other: Keyed): boolean =>64+ one.ratchet === other.ratchet && one.territory === other.territory;65+66+const baselineOf = (baselines: readonly RatchetBaseline[], key: Keyed) =>67+ Array.findFirst(baselines, sameRatchet(key));68+69+/**70+ * Judges an answer's counts against the baselines. A count at or under its71+ * baseline passes; one over it is refused with `Weakened{ratchet}`, unless72+ * the answer asks to raise that ratchet in that territory: then it is not73+ * refused, and waits on a `RaiseRatchet` decision instead. A ratchet with no74+ * baseline yet is not judged (its first landing sets it).75+ */76+export const judgeRatchets = (input: {77+ readonly baselines: readonly RatchetBaseline[];78+ readonly measured: readonly RatchetCount[];79+ readonly ask: AskId;80+ readonly raises: readonly RaiseRequest[];81+}): RatchetJudgement => {82+ const raised = input.measured.flatMap((measured) =>83+ Option.match(baselineOf(input.baselines, measured), {84+ onNone: () => [],85+ onSome: (held) =>86+ measured.count > held.count87+ ? [88+ {89+ after: measured.count,90+ asked: input.raises.some(sameRatchet(measured)),91+ before: held.count,92+ ratchet: measured.ratchet,93+ territory: measured.territory,94+ },95+ ]96+ : [],97+ })98+ );99+100+ return {101+ decisions: raised102+ .filter(({ asked }) => asked)103+ .map(({ after, before, ratchet, territory }) =>104+ DecisionSubject.cases.RaiseRatchet.make({105+ after,106+ ask: input.ask,107+ before,108+ ratchet,109+ territory,110+ })111+ ),112+ refusals: raised113+ .filter(({ asked }) => !asked)114+ .map(115+ ({ after, before, ratchet, territory }) =>116+ new Weakened({ weakening: { after, before, ratchet, territory } })117+ ),118+ };119+};120+121+/**122+ * The baselines after a landing measured `measured` at `landed`: each count123+ * under its baseline lowers it (and is named in `lowered`), a ratchet with no124+ * baseline yet takes its count, and nothing else moves. A landing never125+ * raises a baseline: an accepted `RaiseRatchet` already set it.126+ */127+export const afterLanding = (128+ baselines: readonly RatchetBaseline[],129+ measured: readonly RatchetCount[],130+ landed: LandedSha131+): BaselinesAfterLanding => {132+ // Each baseline reads the landing's first count for its key, as `first`133+ // does for a ratchet with none yet.134+ const lowered = baselines.flatMap((held) =>135+ Array.findFirst(measured, sameRatchet(held)).pipe(136+ Option.filter(({ count }) => count < held.count),137+ Option.map(({ count }): Lowered => ({138+ after: count,139+ before: held.count,140+ ratchet: held.ratchet,141+ territory: held.territory,142+ })),143+ Option.toArray144+ )145+ );146+147+ const kept = baselines.map((held) =>148+ Option.match(Array.findFirst(lowered, sameRatchet(held)), {149+ onNone: () => held,150+ onSome: ({ after }) => ({ ...held, count: after, setAt: landed }),151+ })152+ );153+154+ const first = Array.dedupeWith(155+ measured.filter((count) => Option.isNone(baselineOf(baselines, count))),156+ (one, other) => sameRatchet(one)(other)157+ ).map(({ count, ratchet, territory }) => ({158+ count,159+ ratchet,160+ setAt: landed,161+ territory,162+ }));163+164+ return { baselines: [...kept, ...first], lowered };165+};166+167+/** Whether a choice gives a raise its way: `accept` (or `adopt`) does, `decline` and `revert` don't. */168+const raisesOn = {169+ accept: true,170+ adopt: true,171+ decline: false,172+ revert: false,173+} as const satisfies Record<Choice, boolean>;174+175+/**176+ * The baselines after a decider answered a `RaiseRatchet`: accepted, the177+ * ratchet's baseline in that territory rises to the raised count, set at178+ * `landed`; declined, nothing moves. The one way a baseline rises. An179+ * accepted raise never lowers one: when another accepted raise already took180+ * the baseline past this one's count, main may count that much, and a lower181+ * baseline would refuse every later answer for a count it did not raise.182+ */183+export const decideRaise = (184+ baselines: readonly RatchetBaseline[],185+ subject: RaiseRatchet,186+ choice: Choice,187+ landed: LandedSha188+): readonly RatchetBaseline[] => {189+ if (!raisesOn[choice]) {190+ return baselines;191+ }192+193+ const raised = {194+ count: subject.after,195+ ratchet: subject.ratchet,196+ setAt: landed,197+ territory: subject.territory,198+ };199+200+ return Option.match(baselineOf(baselines, subject), {201+ onNone: () => [...baselines, raised],202+ onSome: (held) =>203+ held.count >= subject.after204+ ? baselines205+ : baselines.map((row) => (sameRatchet(subject)(row) ? raised : row)),206+ });207+};added:packages/project/test/ratchets.test.ts+536 added
1+import { describe, expect, it } from "@effect/vitest";2+import type { RatchetCount } from "@repo/checks/kinds/ratchet";3+import { Choice, DecisionSubject } from "@repo/protocol/domain/decision";4+import { AskId, LandedSha, RatchetName } from "@repo/protocol/ids";5+import { Weakened } from "@repo/protocol/refusal";6+import { Arbitrary, Array, Effect, Option, Result, Schema } from "effect";7+8+import { afterLanding, decideRaise, judgeRatchets } from "../src/ratchets.ts";9+import type {10+ RaiseRatchet,11+ RaiseRequest,12+ RatchetBaseline,13+} from "../src/ratchets.ts";14+15+const hex = (n: number) => n.toString(16).padStart(40, "0");16+17+const shaAt = (step: number) => LandedSha.make(hex(0x1_00_00 + step));18+19+const noExplicitAny = RatchetName.make("no-explicit-any");20+21+const parser = "packages/parser";22+23+const ask = AskId.make("parse-dates");24+25+const baseline = (count: number, setAt = shaAt(0)): RatchetBaseline => ({26+ count,27+ ratchet: noExplicitAny,28+ setAt,29+ territory: parser,30+});31+32+const measuring = (count: number): RatchetCount => ({33+ count,34+ ratchet: noExplicitAny,35+ territory: parser,36+});37+38+const raising: RaiseRequest = {39+ ratchet: noExplicitAny,40+ reason: "the parser's one cast, until the date types land",41+ territory: parser,42+};43+44+const wire = (refusals: readonly Weakened[]) =>45+ refusals.map((refusal) => Schema.encodeSync(Weakened)(refusal));46+47+const raiseTo = (after: number): RaiseRatchet =>48+ DecisionSubject.cases.RaiseRatchet.make({49+ after,50+ ask,51+ before: 14,52+ ratchet: noExplicitAny,53+ territory: parser,54+ });55+56+describe(judgeRatchets, () => {57+ it("refuses an answer that raises a ratchet with Weakened", () => {58+ const { decisions, refusals } = judgeRatchets({59+ ask,60+ baselines: [baseline(14)],61+ measured: [measuring(15)],62+ raises: [],63+ });64+65+ expect(decisions).toStrictEqual([]);66+ expect(wire(refusals)).toStrictEqual(67+ wire([68+ new Weakened({69+ weakening: {70+ after: 15,71+ before: 14,72+ ratchet: noExplicitAny,73+ territory: parser,74+ },75+ }),76+ ])77+ );78+ });79+80+ it.each([14, 12, 0])("lets an answer through at %i", (count) => {81+ expect(82+ judgeRatchets({83+ ask,84+ baselines: [baseline(14)],85+ measured: [measuring(count)],86+ raises: [],87+ })88+ ).toStrictEqual({ decisions: [], refusals: [] });89+ });90+91+ it("turns an asked-for raise into one RaiseRatchet decision, not a refusal", () => {92+ expect(93+ judgeRatchets({94+ ask,95+ baselines: [baseline(14)],96+ measured: [measuring(15)],97+ raises: [raising],98+ })99+ ).toStrictEqual({ decisions: [raiseTo(15)], refusals: [] });100+ });101+102+ it("refuses a raise asked for in another territory", () => {103+ const { decisions, refusals } = judgeRatchets({104+ ask,105+ baselines: [baseline(14)],106+ measured: [measuring(15)],107+ raises: [{ ...raising, territory: "packages/lexer" }],108+ });109+110+ expect(decisions).toStrictEqual([]);111+ expect(refusals.map(({ weakening }) => weakening)).toStrictEqual([112+ { after: 15, before: 14, ratchet: noExplicitAny, territory: parser },113+ ]);114+ });115+116+ it("judges nothing a ratchet has no baseline for yet", () => {117+ expect(118+ judgeRatchets({119+ ask,120+ baselines: [],121+ measured: [measuring(15)],122+ raises: [],123+ })124+ ).toStrictEqual({ decisions: [], refusals: [] });125+ });126+127+ it("judges each territory against its own baseline", () => {128+ const lexer = "packages/lexer";129+130+ const { refusals } = judgeRatchets({131+ ask,132+ baselines: [baseline(14), { ...baseline(2), territory: lexer }],133+ measured: [measuring(14), { ...measuring(3), territory: lexer }],134+ raises: [],135+ });136+137+ expect(refusals.map(({ weakening }) => weakening)).toStrictEqual([138+ { after: 3, before: 2, ratchet: noExplicitAny, territory: lexer },139+ ]);140+ });141+});142+143+describe(afterLanding, () => {144+ it("lowers a baseline to a landing's lower count, by itself", () => {145+ expect(146+ afterLanding([baseline(14)], [measuring(12)], shaAt(1))147+ ).toStrictEqual({148+ baselines: [baseline(12, shaAt(1))],149+ lowered: [150+ { after: 12, before: 14, ratchet: noExplicitAny, territory: parser },151+ ],152+ });153+ });154+155+ it.each([14, 15])("keeps the baseline when a landing counts %i", (count) => {156+ expect(157+ afterLanding([baseline(14)], [measuring(count)], shaAt(1))158+ ).toStrictEqual({ baselines: [baseline(14)], lowered: [] });159+ });160+161+ it("sets a ratchet with no baseline yet to the first landing's count", () => {162+ expect(afterLanding([], [measuring(9)], shaAt(1))).toStrictEqual({163+ baselines: [baseline(9, shaAt(1))],164+ lowered: [],165+ });166+ });167+168+ it("keeps the baselines a landing did not measure", () => {169+ const lexer = { ...baseline(2), territory: "packages/lexer" };170+171+ expect(172+ afterLanding([baseline(14), lexer], [measuring(12)], shaAt(1))173+ ).toStrictEqual({174+ baselines: [baseline(12, shaAt(1)), lexer],175+ lowered: [176+ { after: 12, before: 14, ratchet: noExplicitAny, territory: parser },177+ ],178+ });179+ });180+});181+182+describe(decideRaise, () => {183+ it.each<Choice>(["accept", "adopt"])(184+ "sets the raised baseline when a decider chooses %s",185+ (choice) => {186+ expect(187+ decideRaise([baseline(14)], raiseTo(15), choice, shaAt(2))188+ ).toStrictEqual([baseline(15, shaAt(2))]);189+ }190+ );191+192+ it.each<Choice>(["decline", "revert"])(193+ "leaves the baseline when a decider chooses %s",194+ (choice) => {195+ expect(196+ decideRaise([baseline(14)], raiseTo(15), choice, shaAt(2))197+ ).toStrictEqual([baseline(14)]);198+ }199+ );200+201+ // Two answers asked to raise from 14; the raise to 18 was accepted first,202+ // so main may already count 18. Accepting the stale raise to 15 must not203+ // sink the baseline under main's count, or every later answer is refused.204+ it("never lowers a baseline a later accepted raise overtook", () => {205+ expect(206+ decideRaise([baseline(18, shaAt(2))], raiseTo(15), "accept", shaAt(3))207+ ).toStrictEqual([baseline(18, shaAt(2))]);208+ });209+210+ it("sets a baseline for a ratchet that has none yet", () => {211+ expect(decideRaise([], raiseTo(15), "accept", shaAt(2))).toStrictEqual([212+ baseline(15, shaAt(2)),213+ ]);214+ });215+216+ it("touches no other ratchet or territory", () => {217+ const lexer = { ...baseline(2), territory: "packages/lexer" };218+219+ expect(220+ decideRaise([baseline(14), lexer], raiseTo(15), "accept", shaAt(2))221+ ).toStrictEqual([baseline(15, shaAt(2)), lexer]);222+ });223+});224+225+// The model drives a project's ratchets through generated histories of226+// landings, answers and decisions on the answers' raises, and after every227+// step checks that no baseline rose but by an accepted RaiseRatchet.228+229+const ratchets = [noExplicitAny, RatchetName.make("escapes")] as const;230+231+const territories = [parser, "packages/lexer"] as const;232+233+/** Every (ratchet, territory) pair the histories touch, by index. */234+const keys = ratchets.flatMap((ratchet) =>235+ territories.map((territory) => ({ ratchet, territory }))236+);237+238+const KeyIndex = Schema.Int.check(239+ Schema.isBetween({ maximum: keys.length - 1, minimum: 0 })240+);241+242+const longest = 40;243+244+/**245+ * One move of a history: a landing or an answer measures some keys (a key246+ * counted twice keeps its first count, as `measure` yields one per247+ * territory); an answer may ask to raise some; a decision answers one of the248+ * raises still waiting, picked by `pick`.249+ */250+const Move = Schema.Struct({251+ choice: Choice,252+ counts: Schema.Array(253+ Schema.Struct({254+ count: Schema.Int.check(Schema.isBetween({ maximum: 20, minimum: 0 })),255+ key: KeyIndex,256+ })257+ ),258+ kind: Schema.Literals(["Land", "Answer", "Decide"]),259+ pick: Schema.Int.check(Schema.isBetween({ maximum: 9, minimum: 0 })),260+ raises: Schema.Array(KeyIndex),261+});262+263+type Move = typeof Move.Type;264+265+const histories = Arbitrary.array(Arbitrary.schema(Move), {266+ maxLength: longest,267+});268+269+interface Model {270+ readonly baselines: readonly RatchetBaseline[];271+ /** Raises answers asked for, waiting on a decider. */272+ readonly waiting: readonly RaiseRatchet[];273+}274+275+const sameKey =276+ (one: { readonly ratchet: RatchetName; readonly territory: string }) =>277+ (other: { readonly ratchet: RatchetName; readonly territory: string }) =>278+ one.ratchet === other.ratchet && one.territory === other.territory;279+280+const baselineOf = (281+ baselines: readonly RatchetBaseline[],282+ key: { readonly ratchet: RatchetName; readonly territory: string }283+) => Array.findFirst(baselines, sameKey(key));284+285+const measuredBy = (move: Move): readonly RatchetCount[] =>286+ Array.dedupeWith(287+ move.counts.flatMap(({ count, key }) =>288+ Option.match(Array.get(keys, key), {289+ onNone: () => [],290+ onSome: (found) => [{ ...found, count }],291+ })292+ ),293+ (one, other) => sameKey(one)(other)294+ );295+296+const raisesBy = (move: Move): readonly RaiseRequest[] =>297+ move.raises.flatMap((key) =>298+ Option.match(Array.get(keys, key), {299+ onNone: () => [],300+ onSome: (found) => [{ ...found, reason: "explained in the answer" }],301+ })302+ );303+304+const approves = (choice: Choice) => choice === "accept" || choice === "adopt";305+306+/** What one step did: its new model, and the subject it decided, if it decided one. */307+interface Stepped {308+ readonly model: Model;309+ readonly decided: Option.Option<{310+ readonly subject: RaiseRatchet;311+ readonly choice: Choice;312+ }>;313+ readonly broken: Option.Option<string>;314+ /** How many raises the step refused. */315+ readonly refused: number;316+}317+318+const step = (model: Model, move: Move, at: number): Stepped => {319+ const landed = shaAt(at);320+ const measured = measuredBy(move);321+322+ if (move.kind === "Land") {323+ const after = afterLanding(model.baselines, measured, landed);324+325+ const wrong = after.lowered.find(326+ (lowered) =>327+ !Option.match(baselineOf(model.baselines, lowered), {328+ onNone: () => false,329+ onSome: ({ count }) =>330+ count === lowered.before && lowered.after < lowered.before,331+ })332+ );333+334+ return {335+ broken: Option.fromNullishOr(wrong).pipe(336+ Option.map(() => "a landing reported a lowering it did not make")337+ ),338+ decided: Option.none(),339+ model: { ...model, baselines: after.baselines },340+ refused: 0,341+ };342+ }343+344+ if (move.kind === "Answer") {345+ const raises = raisesBy(move);346+347+ const judged = judgeRatchets({348+ ask,349+ baselines: model.baselines,350+ measured,351+ raises,352+ });353+354+ const raised = measured.filter((count) =>355+ Option.match(baselineOf(model.baselines, count), {356+ onNone: () => false,357+ onSome: (held) => count.count > held.count,358+ })359+ );360+361+ const asked = raised.filter((count) => raises.some(sameKey(count)));362+363+ return {364+ broken:365+ judged.refusals.length + judged.decisions.length === raised.length &&366+ judged.decisions.length === asked.length367+ ? Option.none()368+ : Option.some(369+ "an answer's raises were not each refused or put to a decider"370+ ),371+ decided: Option.none(),372+ model: { ...model, waiting: [...model.waiting, ...judged.decisions] },373+ refused: judged.refusals.length,374+ };375+ }376+377+ const picked = Array.get(378+ model.waiting,379+ move.pick % Math.max(model.waiting.length, 1)380+ );381+382+ return Option.match(picked, {383+ onNone: () => ({384+ broken: Option.none(),385+ decided: Option.none(),386+ model,387+ refused: 0,388+ }),389+ onSome: (subject) => {390+ const baselines = decideRaise(391+ model.baselines,392+ subject,393+ move.choice,394+ landed395+ );396+397+ // An accepted raise another accepted raise overtook must not lower the398+ // baseline: main may already count the higher one.399+ const sank = Option.exists(baselineOf(model.baselines, subject), (held) =>400+ Option.exists(401+ baselineOf(baselines, subject),402+ (now) => now.count < held.count403+ )404+ );405+406+ return {407+ broken: sank408+ ? Option.some("a decision on a raise lowered a baseline")409+ : Option.none(),410+ decided: Option.some({ choice: move.choice, subject }),411+ model: {412+ baselines,413+ waiting: model.waiting.filter((waiting) => waiting !== subject),414+ },415+ refused: 0,416+ };417+ },418+ });419+};420+421+/** The first baseline that rose in a step, unless an accepted raise of it set it. */422+const roseUnasked = (before: Model, stepped: Stepped): Option.Option<string> =>423+ Array.findFirst(stepped.model.baselines, (now) =>424+ Option.match(baselineOf(before.baselines, now), {425+ onNone: () => false,426+ onSome: (held) =>427+ now.count > held.count &&428+ !Option.exists(429+ stepped.decided,430+ ({ choice, subject }) =>431+ approves(choice) &&432+ sameKey(subject)(now) &&433+ subject.after === now.count434+ ),435+ })436+ ).pipe(437+ Option.map(438+ ({ count, ratchet, territory }) =>439+ `${ratchet} in ${territory} rose to ${count} with no accepted raise`440+ )441+ );442+443+/** A history's end, and what happened on the way. */444+interface Run {445+ readonly model: Model;446+ readonly lowered: number;447+ readonly accepted: number;448+ readonly refused: number;449+}450+451+const begin: Model = { baselines: [], waiting: [] };452+453+/** How many baselines moved down from one model to the next. */454+const loweredBetween = (before: Model, after: Model) =>455+ after.baselines.filter((now) =>456+ Option.exists(457+ baselineOf(before.baselines, now),458+ (held) => now.count < held.count459+ )460+ ).length;461+462+/** Runs a history; fails with the first broken rule and where it broke. */463+const run = (moves: readonly Move[]): Result.Result<Run, string> => {464+ let ran: Run = { accepted: 0, lowered: 0, model: begin, refused: 0 };465+466+ for (const [at, move] of moves.entries()) {467+ const before = ran.model;468+ const stepped = step(before, move, at + 1);469+470+ const violation = Option.orElse(stepped.broken, () =>471+ roseUnasked(before, stepped)472+ );473+474+ if (Option.isSome(violation)) {475+ return Result.fail(476+ `step ${at}: ${violation.value}, on ${JSON.stringify(move)}`477+ );478+ }479+480+ ran = {481+ accepted:482+ ran.accepted +483+ (Option.exists(stepped.decided, ({ choice }) => approves(choice))484+ ? 1485+ : 0),486+ lowered: ran.lowered + loweredBetween(before, stepped.model),487+ model: stepped.model,488+ refused: ran.refused + stepped.refused,489+ };490+ }491+492+ return Result.succeed(ran);493+};494+495+const holds = (moves: readonly Move[]) =>496+ Result.match(run(moves), {497+ onFailure: (violation) => Effect.fail(violation),498+ onSuccess: () => Effect.succeed(true),499+ });500+501+describe("ratchets over generated histories", () => {502+ it.effect("no baseline rises but through an accepted RaiseRatchet", () =>503+ Effect.gen(function* () {504+ const result = yield* Arbitrary.checkEffect(histories, holds, {505+ runs: 2000,506+ seed: 403,507+ size: longest,508+ });509+510+ expect(Arbitrary.formatCheckFailure(result)).toBeUndefined();511+ })512+ );513+514+ // A model whose histories never lower, refuse or raise proves nothing.515+ it.effect("lowers, refuses and accepts raises in the histories it runs", () =>516+ Effect.gen(function* () {517+ const sample = yield* Arbitrary.sampleEffect(histories, {518+ count: 500,519+ seed: 403,520+ size: longest,521+ });522+523+ const runs = sample.flatMap((moves) =>524+ Result.match(run(moves), {525+ onFailure: () => [],526+ onSuccess: (ran) => [ran],527+ })528+ );529+530+ expect(runs).toHaveLength(sample.length);531+ expect(runs.some(({ lowered }) => lowered > 0)).toBeTruthy();532+ expect(runs.some(({ refused }) => refused > 0)).toBeTruthy();533+ expect(runs.some(({ accepted }) => accepted > 0)).toBeTruthy();534+ })535+ );536+});