Skip to content
Myr

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

15 files+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 */7import type { Glob } from "@repo/protocol/domain/common";8import { RepoPath } from "@repo/protocol/ids";9import { Option, Order, Result, Schema } from "effect";1011import { matchGlob } from "../judge.ts";1213/** The JSON a linter prints: oxlint's report object, or ESLint's array of files. */14export type LintFormat = "oxlint" | "eslint";1516/** A lint count: the findings in all, and per repo path (only paths with any). */17export interface LintCount {18 readonly total: number;19 readonly byPath: ReadonlyMap<RepoPath, number>;20}2122/** How much of an unreadable output a `CountUnreadable` keeps. */23const HEAD_LENGTH = 200;2425/**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 */31export 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}3839// `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)`.42const OxlintReport = Schema.Struct({43 diagnostics: Schema.Array(44 Schema.Struct({45 code: Schema.optionalKey(Schema.String),46 filename: Schema.NonEmptyString,47 })48 ),49});5051// `eslint --format json`: one entry per file, each with its messages; a52// parse error or a directive report has a null `ruleId`.53const 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);6364/** One finding: the file it is in, and the rule that reported it, if one did. */65interface Finding {66 readonly path: string;67 readonly rule: Option.Option<string>;68}6970const readOxlint = Schema.decodeOption(Schema.fromJsonString(OxlintReport));7172const readEslint = Schema.decodeOption(Schema.fromJsonString(EslintReport));7374const 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 );9394/**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 */100interface RuleName {101 readonly plugin: Option.Option<string>;102 readonly name: string;103}104105// `plugin(rule)`, oxlint's code form.106const CODE_FORM = /^(?<plugin>[^()]+)\((?<name>[^()]+)\)$/u;107108// The core rules' plugin: oxlint prints them as `eslint(no-debugger)`, ESLint109// as a bare `no-debugger`.110const CORE = "eslint";111112// 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`.115const pluginOf = (written: string) => {116 const unscoped = written.replace(/^@/u, "").replace(/^eslint-plugin-/u, "");117118 return unscoped === "typescript-eslint" ? "typescript" : unscoped;119};120121const ruleNameOf = (written: string): RuleName => {122 const code = CODE_FORM.exec(written)?.groups;123124 if (code?.plugin !== undefined && code.name !== undefined) {125 return { name: code.name, plugin: Option.some(pluginOf(code.plugin)) };126 }127128 const slash = written.lastIndexOf("/");129130 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};137138/**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 */144const isRule =145 (wanted: RuleName) =>146 (finding: Finding): boolean =>147 Option.match(finding.rule, {148 onNone: () => false,149 onSome: (written) => {150 const found = ruleNameOf(written);151152 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 });162163/** A path relative to the repo: without `root`'s prefix and any leading `./`. */164const 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}/`;169170 return path.startsWith(prefix) && path.length > prefix.length171 ? path.slice(prefix.length)172 : path;173 },174 });175176 return inside.replace(/^(?:\.\/)+(?=.)/u, "");177};178179const EXCLUDE = "!";180181/** Whether a path is in a territory: some glob matches it, and no `!` glob takes it back. */182const 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 );190191const totalOf = (byPath: ReadonlyMap<RepoPath, number>) =>192 [...byPath.values()].reduce((sum, count) => sum + count, 0);193194/**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 */199export 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 );206207 return { byPath, total: totalOf(byPath) };208};209210/** The format an output is in, by its JSON's shape: an array is ESLint's. */211const detect = (output: string): LintFormat =>212 output.trimStart().startsWith("[") ? "eslint" : "oxlint";213214/**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 */222export 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);231232 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>();238239 for (const finding of findings) {240 const counted = Option.match(wanted, {241 onNone: () => true,242 onSome: (rule) => isRule(rule)(finding),243 });244245 if (counted) {246 const path = RepoPath.make(repoPathOf(finding.path, root));247248 counts.set(path, (counts.get(path) ?? 0) + 1);249 }250 }251252 const byPath = new Map(253 [...counts].toSorted(([one], [other]) => Order.String(one, other))254 );255256 const count = { byPath, total: totalOf(byPath) };257258 return input.territory === undefined259 ? count260 : countWithin(count, input.territory);261 })262 );263};
added:packages/checks/src/kinds/lint-to-zero.ts+13 added
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 */6import type { JsonPath } from "@repo/protocol/domain/common";7import { Option, Predicate, Result, Schema } from "effect";89import { CountUnreadable } from "./lint-count.ts";1011/** One step down a JSON value: an object's key, or an array's index. */12type Step = string | number;1314// One step at the start of what is left of a path: `.key` or `[index]`.15const STEP = /^(?:\.(?<key>[\w$-]+)|\[(?<index>\d+)\])/u;1617/** A path's steps, or `None` when it leaves the supported subset. */18const stepsOf = (path: string): Option.Option<readonly Step[]> => {19 if (!path.startsWith("$")) {20 return Option.none();21 }2223 const steps: Step[] = [];24 let rest = path.slice(1);2526 while (rest.length > 0) {27 const found = STEP.exec(rest);28 const key = found?.groups?.key;29 const index = found?.groups?.index;3031 if (found === null) {32 return Option.none();33 }3435 steps.push(key ?? Number(index));36 rest = rest.slice(found[0].length);37 }3839 return Option.some(steps);40};4142const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>43 Array.isArray(value);4445const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>46 Predicate.isObject(value);4748/** The value one step down, if the value has it: a key on an object, an index on an array. */49const 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 }5556 return isJsonObject(value) && Object.hasOwn(value, step)57 ? Option.fromNullishOr(value[step])58 : Option.none();59};6061/** The value at the end of a path's steps, if the value has every one. */62const walk = (63 value: Schema.Json,64 steps: readonly Step[]65): Option.Option<Schema.Json> => {66 const [step, ...rest] = steps;6768 return step === undefined69 ? Option.some(value)70 : Option.flatMap(down(value, step), (next) => walk(next, rest));71};7273const decodeJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));7475const isCount = (value: Schema.Json): value is number =>76 Predicate.isNumber(value) && Number.isSafeInteger(value);7778/**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 */83export 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 */9import { RatchetMeasure } from "@repo/protocol/domain/check";10import type { RatchetSpec } from "@repo/protocol/domain/check";11import { Glob } from "@repo/protocol/domain/common";12import type { Territory } from "@repo/protocol/domain/territory";13import type { RatchetName } from "@repo/protocol/ids";14import { Effect } from "effect";1516import { countLint, countWithin } from "./lint-count.ts";17import type { CountUnreadable } from "./lint-count.ts";18import { readMetric } from "./metric.ts";1920/** A ratchet's number in one territory, as one run measured it. */21export interface RatchetCount {22 readonly ratchet: RatchetName;23 readonly territory: string;24 readonly count: number;25}2627/**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 */32export const WHOLE_PROJECT = ".";3334/** A territory a count is split by: its name, and the globs of its paths. */35interface Counted {36 readonly name: string;37 readonly paths: readonly Glob[];38}3940const ALL_PATHS: readonly Glob[] = [Glob.make("**")];4142/**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 */46const 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});5556/** The territories a spec's count is split by. */57const countedIn = (58 spec: RatchetSpec,59 territories: readonly Territory[]60): readonly Counted[] => {61 if (spec.territory !== undefined) {62 return [named(territories, spec.territory)];63 }6465 return territories.length === 066 ? [{ name: WHOLE_PROJECT, paths: ALL_PATHS }]67 : territories.map(({ module, paths }) => ({ name: module, paths }));68};6970/**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 */80export 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
1packages/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.2packages/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.3packages/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.4packages/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.5packages/parser/src/parse.ts:3:3: error eslint(no-debugger): `debugger` statement is not allowed help: Remove the debugger statement6packages/printer/src/print.ts:2:3: error eslint(no-debugger): `debugger` statement is not allowed help: Remove the debugger statement7packages/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
1import { describe, expect, it } from "@effect/vitest";2import { Glob } from "@repo/protocol/domain/common";3import { RepoPath } from "@repo/protocol/ids";4import { Effect, Option, Result } from "effect";56import { countLint } from "../../src/kinds/lint-count.ts";7import type {8 CountUnreadable,9 LintCount,10 LintFormat,11} from "../../src/kinds/lint-count.ts";12import { recorded } from "./recorded.ts";1314// 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`.3031const ESLINT_ROOT = "/srv/fixture";3233const parse = RepoPath.make("packages/parser/src/parse.ts");3435const date = RepoPath.make("packages/parser/src/date.ts");3637const lex = RepoPath.make("packages/lexer/src/lex.ts");3839const print = RepoPath.make("packages/printer/src/print.ts");4041const 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 });4647const anys = counted([48 [parse, 3],49 [date, 1],50 [lex, 1],51]);5253const debuggers = counted([54 [parse, 1],55 [print, 1],56]);5758const globs = (...patterns: readonly string[]) =>59 patterns.map((pattern) => Glob.make(pattern));6061/** What an unreadable count kept of the output, or `None` when it counted. */62const unreadHead = (result: Result.Result<LintCount, CountUnreadable>) =>63 Result.match(result, {64 onFailure: ({ head }) => Option.some(head),65 onSuccess: () => Option.none(),66 });6768/** Both recordings, each with what makes its paths repo-relative. */69const 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});7576/** How many `any`s a recording counts within a territory's globs. */77const 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 );8990describe(countLint, () => {91 it.effect("counts every finding in oxlint's JSON, per path", () =>92 Effect.gen(function* () {93 const output = yield* recorded("oxlint");9495 expect(countLint({ output })).toStrictEqual(96 counted([97 [parse, 4],98 [date, 1],99 [lex, 1],100 [print, 1],101 ])102 );103 })104 );105106 it.effect("counts every finding in ESLint's JSON, per repo path", () =>107 Effect.gen(function* () {108 const output = yield* recorded("eslint");109110 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 );120121 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 }));125126 expect([...count.byPath.keys()]).toContain(127 `${ESLINT_ROOT}/packages/lexer/src/lex.ts`128 );129 })130 );131132 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;141142 expect(countLint({ ...oxlint, rule })).toStrictEqual(anys);143 expect(countLint({ ...eslint, rule })).toStrictEqual(anys);144 })145 );146147 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;152153 expect(countLint({ ...oxlint, rule })).toStrictEqual(debuggers);154 expect(countLint({ ...eslint, rule })).toStrictEqual(debuggers);155 })156 );157158 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";162163 expect(countLint({ ...oxlint, rule })).toStrictEqual(counted([]));164 expect(countLint({ ...eslint, rule })).toStrictEqual(counted([]));165 })166 );167168 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;177178 expect(anysWithin(oxlint, territory)).toStrictEqual(179 Result.succeed(total)180 );181 expect(anysWithin(eslint, territory)).toStrictEqual(182 Result.succeed(total)183 );184 })185 );186187 it.effect("names only the territory's paths", () =>188 Effect.gen(function* () {189 const output = yield* recorded("oxlint");190191 expect(192 countLint({ output, territory: globs("packages/parser/**") })193 ).toStrictEqual(194 counted([195 [parse, 4],196 [date, 1],197 ])198 );199 })200 );201202 it.effect("reads a clean run as zero", () =>203 Effect.gen(function* () {204 const output = yield* recorded("oxlint-clean");205206 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 );214215 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);221222 expect(unreadHead(countLint({ format, output }))).toStrictEqual(223 Option.some(output.slice(0, 200))224 );225 })226 );227228 it.effect("keeps the first 200 characters of oxlint's text output", () =>229 Effect.gen(function* () {230 const output = yield* recorded("oxlint-default");231232 expect(output.length).toBeGreaterThan(200);233 expect(unreadHead(countLint({ output }))).toStrictEqual(234 Option.some(output.slice(0, 200))235 );236 })237 );238239 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
added:packages/checks/test/kinds/metric.test.ts+72 added
added:packages/checks/test/kinds/ratchet.test.ts+178 added
1import { describe, expect, it } from "@effect/vitest";2import { RatchetMeasure, RatchetSpec } from "@repo/protocol/domain/check";3import { Command, Glob, JsonPath } from "@repo/protocol/domain/common";4import type { Territory } from "@repo/protocol/domain/territory";5import { RatchetName } from "@repo/protocol/ids";6import { Effect, Exit, Ref } from "effect";78import { CountUnreadable } from "../../src/kinds/lint-count.ts";9import { measure } from "../../src/kinds/ratchet.ts";10import { recorded } from "./recorded.ts";1112// 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.1516const module = (name: string, folder: string): Territory => ({17 module: name,18 paths: [Glob.make(`${folder}/**`)],19});2021const territories = [22 module("@fixture/parser", "packages/parser"),23 module("@fixture/lexer", "packages/lexer"),24 module("@fixture/printer", "packages/printer"),25];2627const anyCount = RatchetName.make("anyCount");2829const lintCommand = "oxlint --format json";3031/** Counts `any` with the project's linter, in every territory. */32const 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});3940/** Counts `any` in the one territory the spec names. */41const countingIn = (territory: string) =>42 RatchetSpec.make({ ...counting, territory });4344const bundleKb = RatchetName.make("bundleKb");4546const bundleCommand = "bun scripts/bundle-size.ts --json";4748/** Reads one number from a bundle report, for the whole project. */49const 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});5657/** 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. */58const printing = (stdout: string) =>59 Effect.gen(function* () {60 const ran = yield* Ref.make<readonly string[]>([]);6162 const run = (command: string) =>63 Ref.update(ran, (commands) => [...commands, command]).pipe(64 Effect.as({ code: 1, stdout })65 );6667 return { ran, run };68 });6970describe(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"));7475 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 );8384 it.effect("counts only the territory a spec names, by its module", () =>85 Effect.gen(function* () {86 const { run } = yield* printing(yield* recorded("oxlint"));8788 expect(89 yield* measure(countingIn("@fixture/lexer"), run, territories)90 ).toStrictEqual([91 { count: 1, ratchet: anyCount, territory: "@fixture/lexer" },92 ]);93 })94 );9596 it.effect("reads a territory no module names as a glob", () =>97 Effect.gen(function* () {98 const { run } = yield* printing(yield* recorded("oxlint"));99100 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 );111112 it.effect("counts a project with no modules as one territory, `.`", () =>113 Effect.gen(function* () {114 const { run } = yield* printing(yield* recorded("oxlint"));115116 expect(yield* measure(counting, run, [])).toStrictEqual([117 { count: 5, ratchet: anyCount, territory: "." },118 ]);119 })120 );121122 it.effect("makes ESLint's absolute paths repo-relative against a root", () =>123 Effect.gen(function* () {124 const { run } = yield* printing(yield* recorded("eslint"));125126 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 );135136 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 );141142 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 );157158 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);162163 expect(164 yield* Effect.exit(measure(counting, run, territories))165 ).toStrictEqual(Exit.fail(CountUnreadable.of(output)));166 })167 );168169 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 );174175 expect(exit).toStrictEqual(Exit.fail("no checker"));176 })177 );178});
added:packages/checks/test/kinds/recorded.ts+17 added
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 */10import type { RatchetCount } from "@repo/checks/kinds/ratchet";11import { DecisionSubject } from "@repo/protocol/domain/decision";12import type { Choice } from "@repo/protocol/domain/decision";13import type { AskId, LandedSha, RatchetName } from "@repo/protocol/ids";14import { Weakened } from "@repo/protocol/refusal";15import { Array, Option } from "effect";1617/** A ratchet's baseline in one territory, and the landed SHA that set it. */18export interface RatchetBaseline {19 readonly ratchet: RatchetName;20 readonly territory: string;21 readonly count: number;22 readonly setAt: LandedSha;23}2425/** An answer asking a decider to raise one ratchet in one territory, and why. */26export interface RaiseRequest {27 readonly ratchet: RatchetName;28 readonly territory: string;29 readonly reason: string;30}3132/** The decision a raise waits on. */33export type RaiseRatchet = Extract<DecisionSubject, { _tag: "RaiseRatchet" }>;3435/** A baseline a landing lowered, from what to what. */36export interface Lowered {37 readonly ratchet: RatchetName;38 readonly territory: string;39 readonly before: number;40 readonly after: number;41}4243/** What judging an answer's counts gives: its refusals, and the raises it waits on. */44export interface RatchetJudgement {45 readonly refusals: readonly Weakened[];46 readonly decisions: readonly RaiseRatchet[];47}4849/** The baselines after a landing, and the ones it lowered. */50export interface BaselinesAfterLanding {51 readonly baselines: readonly RatchetBaseline[];52 readonly lowered: readonly Lowered[];53}5455interface Keyed {56 readonly ratchet: RatchetName;57 readonly territory: string;58}5960/** Whether two rows name one ratchet in one territory. */61const sameRatchet =62 (one: Keyed) =>63 (other: Keyed): boolean =>64 one.ratchet === other.ratchet && one.territory === other.territory;6566const baselineOf = (baselines: readonly RatchetBaseline[], key: Keyed) =>67 Array.findFirst(baselines, sameRatchet(key));6869/**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 */76export 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 );99100 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};120121/**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 */127export 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 );146147 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 );153154 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 }));163164 return { baselines: [...kept, ...first], lowered };165};166167/** Whether a choice gives a raise its way: `accept` (or `adopt`) does, `decline` and `revert` don't. */168const raisesOn = {169 accept: true,170 adopt: true,171 decline: false,172 revert: false,173} as const satisfies Record<Choice, boolean>;174175/**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 */183export 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 }192193 const raised = {194 count: subject.after,195 ratchet: subject.ratchet,196 setAt: landed,197 territory: subject.territory,198 };199200 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
1import { describe, expect, it } from "@effect/vitest";2import type { RatchetCount } from "@repo/checks/kinds/ratchet";3import { Choice, DecisionSubject } from "@repo/protocol/domain/decision";4import { AskId, LandedSha, RatchetName } from "@repo/protocol/ids";5import { Weakened } from "@repo/protocol/refusal";6import { Arbitrary, Array, Effect, Option, Result, Schema } from "effect";78import { afterLanding, decideRaise, judgeRatchets } from "../src/ratchets.ts";9import type {10 RaiseRatchet,11 RaiseRequest,12 RatchetBaseline,13} from "../src/ratchets.ts";1415const hex = (n: number) => n.toString(16).padStart(40, "0");1617const shaAt = (step: number) => LandedSha.make(hex(0x1_00_00 + step));1819const noExplicitAny = RatchetName.make("no-explicit-any");2021const parser = "packages/parser";2223const ask = AskId.make("parse-dates");2425const baseline = (count: number, setAt = shaAt(0)): RatchetBaseline => ({26 count,27 ratchet: noExplicitAny,28 setAt,29 territory: parser,30});3132const measuring = (count: number): RatchetCount => ({33 count,34 ratchet: noExplicitAny,35 territory: parser,36});3738const raising: RaiseRequest = {39 ratchet: noExplicitAny,40 reason: "the parser's one cast, until the date types land",41 territory: parser,42};4344const wire = (refusals: readonly Weakened[]) =>45 refusals.map((refusal) => Schema.encodeSync(Weakened)(refusal));4647const raiseTo = (after: number): RaiseRatchet =>48 DecisionSubject.cases.RaiseRatchet.make({49 after,50 ask,51 before: 14,52 ratchet: noExplicitAny,53 territory: parser,54 });5556describe(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 });6465 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 });7980 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 });9091 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 });101102 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 });109110 expect(decisions).toStrictEqual([]);111 expect(refusals.map(({ weakening }) => weakening)).toStrictEqual([112 { after: 15, before: 14, ratchet: noExplicitAny, territory: parser },113 ]);114 });115116 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 });126127 it("judges each territory against its own baseline", () => {128 const lexer = "packages/lexer";129130 const { refusals } = judgeRatchets({131 ask,132 baselines: [baseline(14), { ...baseline(2), territory: lexer }],133 measured: [measuring(14), { ...measuring(3), territory: lexer }],134 raises: [],135 });136137 expect(refusals.map(({ weakening }) => weakening)).toStrictEqual([138 { after: 3, before: 2, ratchet: noExplicitAny, territory: lexer },139 ]);140 });141});142143describe(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 });154155 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 });160161 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 });167168 it("keeps the baselines a landing did not measure", () => {169 const lexer = { ...baseline(2), territory: "packages/lexer" };170171 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});181182describe(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 );191192 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 );200201 // 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 });209210 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 });215216 it("touches no other ratchet or territory", () => {217 const lexer = { ...baseline(2), territory: "packages/lexer" };218219 expect(220 decideRaise([baseline(14), lexer], raiseTo(15), "accept", shaAt(2))221 ).toStrictEqual([baseline(15, shaAt(2)), lexer]);222 });223});224225// 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.228229const ratchets = [noExplicitAny, RatchetName.make("escapes")] as const;230231const territories = [parser, "packages/lexer"] as const;232233/** Every (ratchet, territory) pair the histories touch, by index. */234const keys = ratchets.flatMap((ratchet) =>235 territories.map((territory) => ({ ratchet, territory }))236);237238const KeyIndex = Schema.Int.check(239 Schema.isBetween({ maximum: keys.length - 1, minimum: 0 })240);241242const longest = 40;243244/**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 */250const 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});262263type Move = typeof Move.Type;264265const histories = Arbitrary.array(Arbitrary.schema(Move), {266 maxLength: longest,267});268269interface Model {270 readonly baselines: readonly RatchetBaseline[];271 /** Raises answers asked for, waiting on a decider. */272 readonly waiting: readonly RaiseRatchet[];273}274275const 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;279280const baselineOf = (281 baselines: readonly RatchetBaseline[],282 key: { readonly ratchet: RatchetName; readonly territory: string }283) => Array.findFirst(baselines, sameKey(key));284285const 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 );295296const 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 );303304const approves = (choice: Choice) => choice === "accept" || choice === "adopt";305306/** What one step did: its new model, and the subject it decided, if it decided one. */307interface 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}317318const step = (model: Model, move: Move, at: number): Stepped => {319 const landed = shaAt(at);320 const measured = measuredBy(move);321322 if (move.kind === "Land") {323 const after = afterLanding(model.baselines, measured, landed);324325 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 );333334 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 }343344 if (move.kind === "Answer") {345 const raises = raisesBy(move);346347 const judged = judgeRatchets({348 ask,349 baselines: model.baselines,350 measured,351 raises,352 });353354 const raised = measured.filter((count) =>355 Option.match(baselineOf(model.baselines, count), {356 onNone: () => false,357 onSome: (held) => count.count > held.count,358 })359 );360361 const asked = raised.filter((count) => raises.some(sameKey(count)));362363 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 }376377 const picked = Array.get(378 model.waiting,379 move.pick % Math.max(model.waiting.length, 1)380 );381382 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 );396397 // 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 );405406 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};420421/** The first baseline that rose in a step, unless an accepted raise of it set it. */422const 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 );442443/** A history's end, and what happened on the way. */444interface Run {445 readonly model: Model;446 readonly lowered: number;447 readonly accepted: number;448 readonly refused: number;449}450451const begin: Model = { baselines: [], waiting: [] };452453/** How many baselines moved down from one model to the next. */454const 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;461462/** Runs a history; fails with the first broken rule and where it broke. */463const run = (moves: readonly Move[]): Result.Result<Run, string> => {464 let ran: Run = { accepted: 0, lowered: 0, model: begin, refused: 0 };465466 for (const [at, move] of moves.entries()) {467 const before = ran.model;468 const stepped = step(before, move, at + 1);469470 const violation = Option.orElse(stepped.broken, () =>471 roseUnasked(before, stepped)472 );473474 if (Option.isSome(violation)) {475 return Result.fail(476 `step ${at}: ${violation.value}, on ${JSON.stringify(move)}`477 );478 }479480 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 }491492 return Result.succeed(ran);493};494495const holds = (moves: readonly Move[]) =>496 Result.match(run(moves), {497 onFailure: (violation) => Effect.fail(violation),498 onSuccess: () => Effect.succeed(true),499 });500501describe("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 });509510 expect(Arbitrary.formatCheckFailure(result)).toBeUndefined();511 })512 );513514 // 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 });522523 const runs = sample.flatMap((moves) =>524 Result.match(run(moves), {525 onFailure: () => [],526 onSuccess: (ran) => [ran],527 })528 );529530 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});