Merge build/402-gate-markers-internals-repair-text: an answer's stage-1 refusals arrive all at once, each with its line and how to repair it
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 650cb35, 8f6891a · Browse files · 14 files·+1395 added−163 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+1395 added−163 removed
- tests:+733 added−38 removed
- other:+662 added−125 removed
Provenance
- Commit
f76d27f- Tree
44ce693- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
650cb35- Parent 2
8f6891a
14 files changed+1395 added−163 removed
modified:docs/reference/refusals.md+5 added-5 removed
96 unmodified lines97 - Retryable: no98 - Next: `myr check`99 - Fields:100 - `paths`: `readonly [string, ...Array<string>]`101-- Reason, for example: changes paths outside the ask's territory: src/a.ts101+- Reason, for example: changes paths outside the ask's territory: src/a.ts; put those files back, or flag the ask if the want needs them102 103 ### TouchedJudge104 105 - Retryable: no106 - Next: `myr check`107 - Fields:108 - `paths`: `readonly [string, ...Array<string>]`109-- Reason, for example: changes files that decide what the checks do: src/a.ts109+- Reason, for example: changes files that decide what the checks do: src/a.ts; the checks are fixed for this ask, so put them back, or flag the ask if a check is wrong110 111 ### Weakened112 113 - Retryable: no114 - Next: `myr check`115 - Fields:116 - `weakening`: `{ readonly "marker": string, readonly "reason"?: string } | { readonly "after": number, readonly "before": number, readonly "ratchet": string, readonly "territory": string }`117-- Reason, for example: adds it.skip, with the reason "flaky on CI"117+- Reason, for example: adds it.skip, with the reason "flaky on CI"; it waits for a decider because it raises this territory's escapes118 119 ### PrivatePathInPublicTree120 121 - Retryable: no122 - Next: `myr check`123 - Fields:124 - `paths`: `readonly [string, ...Array<string>]`125-- Reason, for example: would put held-back paths in a public tree: src/a.ts125+- Reason, for example: would put held-back paths in a public tree: src/a.ts; those paths belong to a layer, so remove them from the answer126 127 ### ReachedInternals128 129 - Retryable: no130 - Next: `myr check`131 - Fields:132 - `from`: `string`133 - `to`: `string`134-- Reason, for example: src/a.ts reaches into @datekit/format/src/internal.ts, which its module does not export134+- Reason, for example: src/a.ts reaches into @datekit/format/src/internal.ts, which its module does not export; import it through that module's public exports instead135 136 ## Merge137 138 ### StaleBase219 unmodified linesmodified:packages/gate/src/stages/ratchet.ts+3 added-3 removed
10 unmodified lines111213141515161718197 unmodified lines272829303131323334356 unmodified lines4243444546464748495026 unmodified lines10 unmodified linesimport { Option } from "effect";
import type { PushFacts } from "../facts.ts";import { matchAny } from "../glob.ts";import { findMarkers, markersOf } from "../markers.ts";import { markersOf, scanMarkers } from "../markers.ts";
/** A territory's paths: a module's, by its name, or the territory read as a glob. */const pathsOf = (policy: Policy, territory: string): readonly string[] => policy.modules.find((module) => module.module === territory)?.paths ?? [7 unmodified lines}
/** Refuses each raised ratchet, or turns it into a `RaiseRatchet` decision. */export const ratchet = (facts: PushFacts): RatchetAnswer => { const escapes = findMarkers(markersOf(facts.policy), facts.addedLines).filter( const escapes = scanMarkers(facts.addedLines, markersOf(facts.policy)).filter( (hit) => Option.isSome(hit.reason) );
// A raise waits for a decider only when the answer adds a reasoned escape6 unmodified lines count, explained: Option.isSome(facts.ask) && escapes.some((hit) => matchAny(pathsOf(facts.policy, count.territory), hit.at.path) matchAny(pathsOf(facts.policy, count.territory), hit.path) ), name, }, ]26 unmodified linesmodified:packages/gate/src/stages/shape.ts+81 added-78 removed
8 unmodified lines9 import type { Ask } from "@repo/protocol/domain/ask";10 import { CheckSpec } from "@repo/protocol/domain/check";11 import { RepoPath } from "@repo/protocol/ids";12 import {13+ groups,14 OutOfScope,15 PrivatePathInPublicTree,16 ReachedInternals,17 TouchedJudge,1 unmodified line19 } from "@repo/protocol/refusal";20 import type { Refusal } from "@repo/protocol/refusal";21 import { Array, Effect, Option, Order } from "effect";22 22-import type { PushFacts } from "../facts.ts";23+import type { AddedLine, PushFacts } from "../facts.ts";24 import { matchAny } from "../glob.ts";24-import { findMarkers, markersOf } from "../markers.ts";25+import { importSpecifiers, reachedInternals as reachInto } from "../imports.ts";26+import { markersOf, scanMarkers } from "../markers.ts";27 import type { Stage } from "../stage.ts";28 29 /** The one JSON pointer the gate is told about: whether the scripts changed. */30 const SCRIPTS = "package.json#/scripts";77 unmodified lines108 }109 );110 };111 110-/** Every marker added with no reason; a reasoned one is the ratchet stage's. */112+/** Every marker added with no reason; a reasoned one is an escape, for `escapeDecisions`. */113 const weakened = (facts: PushFacts): readonly Refusal[] =>114+ scanMarkers(facts.addedLines, markersOf(facts.policy)).flatMap(112- findMarkers(markersOf(facts.policy), facts.addedLines).flatMap((hit) =>113- Option.isNone(hit.reason)114- ? [new Weakened({ at: hit.at, weakening: { marker: hit.marker } })]115- : []115+ ({ line, marker, path, reason }) =>116+ Option.isNone(reason)117+ ? [new Weakened({ at: { line, path }, weakening: { marker } })]118+ : []119 );120 121 /** Added or changed paths a layer holds: nothing from a layer enters a public tree. */122 const privatePaths = (facts: PushFacts): readonly Refusal[] =>10 unmodified lines133 onSome: (paths) => [new PrivatePathInPublicTree({ paths })],134 }135 );136 134-// A module specifier on an import or re-export line: `from "…"` (also the135-// last line of a multi-line import, ` pad } from "…"`), a bare136-// `import "…"`, or `import("…")`.137-const SPECIFIERS = [138- /(?:^\s*(?:import|export)\b.*?|\}\s*)\bfrom\s*["'](?<specifier>[^"']+)["']/u,139- /^\s*import\s*["'](?<specifier>[^"']+)["']/u,140- /\bimport\s*\(\s*["'](?<specifier>[^"']+)["']\s*\)/u,141-];137+// The files whose imports are read: JavaScript and TypeScript sources.138+const SCRIPT = /\.[cm]?[jt]sx?$/u;139 143-const specifierIn = (text: string) =>144- Array.findFirst(SPECIFIERS, (pattern) =>145- Option.fromNullishOr(pattern.exec(text)?.groups?.specifier)146- );140+/**141+ * Each run of consecutive added lines as one text, with the number of the142+ * line before it, so an import over several lines is read whole.143+ */144+const runsOf = (lines: readonly AddedLine[]) => {145+ // Consecutive lines keep the same difference from their place in order.146+ const placed = lines147+ .toSorted((one, other) => one.line - other.line)148+ .map((added, index) => ({ ...added, run: added.line - index }));149 148-/** `from`'s folder joined with a relative specifier, `.` and `..` resolved. */149-const resolve = (from: string, specifier: string) => {150- const parts = from.split("/").slice(0, -1);151-152- for (const part of specifier.split("/")) {153- if (part === "..") {154- parts.pop();155- } else if (part !== "." && part !== "") {156- parts.push(part);157- }158- }159-160- return parts.join("/");150+ return Array.isReadonlyArrayNonEmpty(placed)151+ ? Array.groupWith(placed, (one, other) => one.run === other.run).map(152+ (run) => ({153+ offset: Array.headNonEmpty(run).line - 1,154+ text: run.map((added) => added.text).join("\n"),155+ })156+ )157+ : [];158 };159 163-/** A module file's path with its extension and a trailing `/index` dropped. */164-const bare = (path: string) =>165- path.replace(/\.[cm]?[jt]sx?$/u, "").replace(/\/index$/u, "");166-160 /**168- * Whether `target` is a file of a module other than `own` that the module169- * does not export. A module that lists no public files is not judged.161+ * Imports the answer adds to a script inside its territory that reach into162+ * another module's internals, each on its line. A push that answers no ask163+ * (a decider's own landing) is not judged.164 */171-const isInternal = (facts: PushFacts, own: string, target: string) =>172- facts.policy.modules.some(173- (module) =>174- module.module !== own &&175- module.publicFiles !== undefined &&176- matchAny(module.paths, target) &&177- !module.publicFiles.some((file) => bare(file) === bare(target))178- );179-180-/**181- * Imports the answer adds, inside its territory, of another module's file182- * that the module does not export. W2's rule reads relative specifiers only.183- */165 const reachedInternals = (facts: PushFacts): readonly Refusal[] =>166 Option.match(facts.ask, {167 onNone: () => [],168 onSome: ({ territory }) =>169 [...facts.addedLines]189- .toSorted(([one], [other]) => Order.String(one, other))190- .filter(([path]) => matchAny(territory.paths, path))170+ .filter(171+ ([path]) => SCRIPT.test(path) && matchAny(territory.paths, path)172+ )173 .flatMap(([from, lines]) =>192- lines193- .toSorted((one, other) => one.line - other.line)194- .flatMap(({ line, text }) =>195- Option.match(specifierIn(text), {196- onNone: () => [],197- onSome: (to) =>198- to.startsWith(".") &&199- isInternal(facts, territory.module, resolve(from, to))200- ? [201- new ReachedInternals({202- at: { line, path: from },203- from,204- to,205- }),206- ]207- : [],208- })174+ runsOf(lines).flatMap(({ offset, text }) =>175+ importSpecifiers(text).flatMap(({ line, specifier }) =>176+ Option.match(177+ reachInto({178+ from,179+ modules: facts.policy.modules,180+ specifier,181+ }),182+ {183+ onNone: () => [],184+ onSome: ({ to }) => [185+ new ReachedInternals({186+ at: { line: offset + line, path: from },187+ from,188+ to,189+ }),190+ ],191+ }192+ )193 )194+ )195 ),196 });197 213-/** Stage 1: every problem the push's changes have, in the union's Shape order. */198+// The Shape group's tags, in union order.199+const unionOrder: readonly string[] =200+ groups201+ .find((group) => group.name === "Shape")202+ ?.members.map((member) => member.identifier) ?? [];203+204+/** Union group order, then path, then line. */205+const byUnionOrder = Order.combineAll<Refusal>([206+ Order.mapInput(Order.Number, (refusal) => unionOrder.indexOf(refusal._tag)),207+ Order.mapInput(Order.String, (refusal) => refusal.at?.path ?? ""),208+ Order.mapInput(Order.Number, (refusal) => refusal.at?.line ?? 0),209+]);210+211+/**212+ * Stage 1: every problem the push's changes have, in the union's Shape213+ * order, then by path, then by line.214+ */215 export const scan: Stage<never> = {216 accumulate: true,217 name: "shape",218 run: (facts) =>218- Effect.succeed([219- ...outOfScope(facts),220- ...touchedJudge(facts),221- ...weakened(facts),222- ...privatePaths(facts),223- ...reachedInternals(facts),224- ]),219+ Effect.succeed(220+ [221+ ...outOfScope(facts),222+ ...touchedJudge(facts),223+ ...weakened(facts),224+ ...privatePaths(facts),225+ ...reachedInternals(facts),226+ ].toSorted(byUnionOrder)227+ ),228 };added:packages/gate/src/escapes.ts+108 added
1+/**2+ * Reasoned escapes: a marker with a reason after ` -- ` is not refused but3+ * counted against its territory's escape ratchet (FE §8.4 B2, B3). The4+ * ratchet is incremental, with no command: its count moves by the reasoned5+ * markers an answer adds minus those it removes. An answer that would take a6+ * territory past its baseline waits for a decider, one `Waiver` per reasoned7+ * marker it adds there, instead of landing or being refused.8+ *9+ * This is a pure function beside the stages, not a stage: a waiting answer10+ * is not refused, so the caller (the Answer workflow, 417) opens the11+ * decisions.12+ */13+import type { Ask } from "@repo/protocol/domain/ask";14+import { DecisionSubject } from "@repo/protocol/domain/decision";15+import type { Policy } from "@repo/protocol/domain/policy";16+import { RatchetName } from "@repo/protocol/ids";17+import type { RepoPath } from "@repo/protocol/ids";18+import { Option } from "effect";19+20+import type { PushFacts } from "./facts.ts";21+import { matchAny } from "./glob.ts";22+import { markersOf, scanMarkers } from "./markers.ts";23+import type { MarkerHit } from "./markers.ts";24+25+/** A `Waiver` decision's subject. */26+export type Waiver = Extract<DecisionSubject, { readonly _tag: "Waiver" }>;27+28+/**29+ * The escape ratchet of `territory`: `escapes-` and the territory's name in30+ * lowercase words joined by `-` (`@datekit/parse` is `escapes-datekit-parse`);31+ * a territory with no such words, the root's `.`, is `escapes-root`.32+ */33+export const escapeRatchet = (territory: string): RatchetName =>34+ RatchetName.make(35+ `escapes-${36+ territory37+ .toLowerCase()38+ .split(/[^a-z0-9]+/u)39+ .filter((word) => word !== "")40+ .join("-") || "root"41+ }`42+ );43+44+/** A marker hit whose line gives a reason. */45+interface Escape extends MarkerHit {46+ readonly given: string;47+}48+49+const escapesIn = (50+ lines: PushFacts["addedLines"],51+ markers: readonly string[]52+): readonly Escape[] =>53+ scanMarkers(lines, markers).flatMap((hit) =>54+ Option.match(hit.reason, {55+ onNone: () => [],56+ onSome: (given) => [{ ...hit, given }],57+ })58+ );59+60+/**61+ * The territory a path counts against: the first module holding it, or the62+ * ask's territory for a path no module holds (a root manifest the ask may63+ * change).64+ */65+const territoryOf = (policy: Policy, ask: Ask, path: RepoPath) =>66+ policy.modules.find((module) => matchAny(module.paths, path))?.module ??67+ ask.territory.module;68+69+/**70+ * One `Waiver` per reasoned marker the push adds, in each territory whose71+ * escape count after the push (its count on main, plus the reasoned markers72+ * added there, less those removed) exceeds its baseline; ordered by path,73+ * then line. A push that answers no ask has nothing to wait on.74+ */75+export const escapeDecisions = (facts: PushFacts): readonly Waiver[] =>76+ Option.match(facts.ask, {77+ onNone: () => [],78+ onSome: (ask) => {79+ const markers = markersOf(facts.policy);80+ const added = escapesIn(facts.addedLines, markers);81+ const removed = escapesIn(facts.removedLines ?? new Map(), markers);82+83+ const territory = (hit: Escape) =>84+ territoryOf(facts.policy, ask, hit.path);85+86+ const raises = (name: string) => {87+ const ratchet = escapeRatchet(name);88+ const baseline = facts.ratchetBaselines?.get(ratchet) ?? 0;89+ const onMain = facts.escapeCounts?.get(ratchet) ?? baseline;90+91+ const moved = (hits: readonly Escape[]) =>92+ hits.filter((hit) => territory(hit) === name).length;93+94+ return onMain + moved(added) - moved(removed) > baseline;95+ };96+97+ return added98+ .filter((hit) => raises(territory(hit)))99+ .map(({ given, line, marker, path }) =>100+ DecisionSubject.cases.Waiver.make({101+ ask: ask.id,102+ at: { line, path },103+ marker,104+ reason: given,105+ })106+ );107+ },108+ });modified:packages/gate/src/facts.ts+19 added
90 unmodified lines91929394959697989910010110210310410510610710810911011111211311490 unmodified lines * Whether the push opens `ask` (a decider's `openAsk`) rather than answers * it. Only then are the ask's own file and check file the push's to write. */ readonly opensAsk: boolean; /** * Each ratchet's baseline, from the project's `ratchets` rows: the most a * count may be. A territory's escape ratchet is named by `escapeRatchet`. * Absent, or with no row for a ratchet, the baseline is 0. */ readonly ratchetBaselines?: ReadonlyMap<RatchetName, number>; /** * The lines a push removes, by their 1-based number in the old file, so a * removed escape offsets an added one. Absent, a push removes none, which * only errs toward asking a decider. */ readonly removedLines?: ReadonlyMap<RepoPath, readonly AddedLine[]>; /** * Each territory's count of reasoned escapes on main, by its escape * ratchet, when the caller keeps it apart from the baseline: a decider's * accepted `Waiver` raises the baseline before the answer lands, so the * answer, checked again, is within it. Absent, the baseline stands for it. */ readonly escapeCounts?: ReadonlyMap<RatchetName, number>;}added:packages/gate/src/imports.ts+386 added
1+/**2+ * Imports read from text, for `ReachedInternals`: stage 1 reads the module3+ * specifiers an answer adds and judges each against the modules' public4+ * files, with no compiler and no file system. Full resolution (path aliases,5+ * `exports` conditions, a re-export that leaks an internal) is stage 3's,6+ * through `tsc`.7+ */8+import type { Policy } from "@repo/protocol/domain/policy";9+import type { RepoPath } from "@repo/protocol/ids";10+import { Array, Option } from "effect";11+12+import { matchAny } from "./glob.ts";13+14+/** One module specifier a text imports, and the 1-based line it sits on. */15+export interface ImportSpecifier {16+ readonly specifier: string;17+ readonly line: number;18+}19+20+type Mode = "code" | "comment" | "block" | "quote" | "template" | "regex";21+22+// After one of these, a `/` opens a regular expression, not a division.23+const OPENS_REGEX = new Set("(,=:[!&|?{};+-*%<>~^");24+25+// A postfix `++` or `--` ends an operand, so the `/` after it divides.26+const POSTFIX = /(?:\+\+|--)$/u;27+28+const KEYWORD_BEFORE_REGEX =29+ /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/u;30+31+/**32+ * `text` with its comments blanked, and the contents of its strings,33+ * templates and regular expressions filled with `_`, so what is left to read34+ * is code and the bare delimiters of its strings. Lines and offsets stay35+ * where they were. A line whose code opens with `*` reads as the inside of a36+ * block comment: an answer's added lines can start after the comment opened.37+ */38+const maskOf = (text: string): string => {39+ let out = "";40+ let mode: Mode = "code";41+ let quote = "";42+ let inClass = false;43+ // The last of the code read so far, its whitespace kept: what a `/` follows.44+ let tail = "";45+ // Whether the current line holds nothing but whitespace so far.46+ let blankLine = true;47+ // Each open `${`, with how many braces are open inside it.48+ const expressions: number[] = [];49+50+ const emit = (chars: string, as: "blank" | "fill") => {51+ for (const char of chars) {52+ if (char === "\n") {53+ out += char;54+ blankLine = true;55+ } else {56+ out += as === "blank" ? " " : "_";57+ }58+ }59+ };60+61+ const keep = (chars: string) => {62+ out += chars;63+ tail = (tail + chars).slice(-32);64+ blankLine = chars.endsWith("\n") || (blankLine && chars.trim() === "");65+ };66+67+ /** Ends the current mode on `char`, which stays as code. */68+ const close = (char: string) => {69+ mode = "code";70+ keep(char);71+ };72+73+ // Each step reads the character at hand (and the next, for pairs) in its74+ // mode, and answers with how many characters it read.75+ const inComment = (char: string) => {76+ if (char === "\n") {77+ mode = "code";78+ }79+80+ emit(char, "blank");81+82+ return 1;83+ };84+85+ const inBlock = (char: string, next: string) => {86+ if (char === "*" && next === "/") {87+ mode = "code";88+ emit("*/", "blank");89+90+ return 2;91+ }92+93+ emit(char, "blank");94+95+ return 1;96+ };97+98+ const inQuote = (char: string, next: string) => {99+ if (char === "\\") {100+ emit(char + next, "fill");101+102+ return 2;103+ }104+105+ if (char === quote || char === "\n") {106+ close(char);107+ } else {108+ emit(char, "fill");109+ }110+111+ return 1;112+ };113+114+ const inTemplate = (char: string, next: string) => {115+ if (char === "\\") {116+ emit(char + next, "fill");117+118+ return 2;119+ }120+121+ if (char === "$" && next === "{") {122+ expressions.push(0);123+ close("${");124+125+ return 2;126+ }127+128+ if (char === "`") {129+ close(char);130+ } else {131+ emit(char, "fill");132+ }133+134+ return 1;135+ };136+137+ const inRegex = (char: string, next: string) => {138+ if (char === "\\") {139+ emit(char + next, "fill");140+141+ return 2;142+ }143+144+ if (char === "\n" || (char === "/" && !inClass)) {145+ close(char);146+ } else {147+ inClass = char === "[" || (inClass && char !== "]");148+ emit(char, "fill");149+ }150+151+ return 1;152+ };153+154+ /** Whether a `/` here opens a regular expression rather than divides. */155+ const opensRegex = () => {156+ const before = tail.trimEnd();157+158+ return (159+ before === "" ||160+ (OPENS_REGEX.has(before.slice(-1)) && !POSTFIX.test(before)) ||161+ KEYWORD_BEFORE_REGEX.test(before)162+ );163+ };164+165+ /** What a character of code opens: a string, a template, a regular expression, or nothing. */166+ const opened = (char: string): Mode => {167+ if (char === '"' || char === "'") {168+ quote = char;169+170+ return "quote";171+ }172+173+ if (char === "`") {174+ return "template";175+ }176+177+ if (char === "/" && opensRegex()) {178+ inClass = false;179+180+ return "regex";181+ }182+183+ return "code";184+ };185+186+ /** Counts braces inside a template's `${`; its closing one resumes the template. */187+ const brace = (char: string) => {188+ const open = expressions.pop();189+190+ if (open === undefined) {191+ return;192+ }193+194+ if (char === "}" && open === 0) {195+ mode = "template";196+ } else {197+ expressions.push(open + (char === "{" ? 1 : 0) - (char === "}" ? 1 : 0));198+ }199+ };200+201+ const inCode = (char: string, next: string) => {202+ if (char === "/" && (next === "/" || next === "*")) {203+ mode = next === "/" ? "comment" : "block";204+ emit(char + next, "blank");205+206+ return 2;207+ }208+209+ if (char === "*" && blankLine) {210+ mode = "comment";211+ emit(char, "blank");212+213+ return 1;214+ }215+216+ mode = opened(char);217+218+ if (mode === "code" && (char === "{" || char === "}")) {219+ brace(char);220+ }221+222+ keep(char);223+224+ return 1;225+ };226+227+ const steps = {228+ block: inBlock,229+ code: inCode,230+ comment: inComment,231+ quote: inQuote,232+ regex: inRegex,233+ template: inTemplate,234+ } as const satisfies Record<Mode, (char: string, next: string) => number>;235+236+ let at = 0;237+238+ while (at < text.length) {239+ at += steps[mode](text.charAt(at), text.charAt(at + 1));240+ }241+242+ return out;243+};244+245+// Each form of import, read in the masked text: `… from "x"` (an import or246+// re-export, or the last line of one), `import "x"`, `import("x")` and247+// `require("x")`. A string's contents read as `_`. A call may also name its248+// module by a template with no `${}`, which is as fixed as a string; one with249+// a substitution keeps its `${`, so it never matches.250+const FORMS = [251+ /(?<![\w$.])from\s*(?<quote>["'])(?<contents>_+)\k<quote>/gu,252+ /(?<![\w$.])import\s*(?<quote>["'])(?<contents>_+)\k<quote>/gu,253+ /(?<![\w$.])import\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,254+ /(?<![\w$.])require\s*\(\s*(?<quote>["'`])(?<contents>_+)\k<quote>/gu,255+];256+257+/**258+ * Every module specifier `text` imports: static imports and re-exports259+ * (`… from "x"`, over any number of lines), side-effect imports, dynamic260+ * `import("x")` and `require("x")` (their specifier a string or a template261+ * with no substitution), each on the line its specifier sits on, in the262+ * order they appear. Comments, strings, templates and regular expressions263+ * import nothing.264+ */265+export const importSpecifiers = (text: string): readonly ImportSpecifier[] => {266+ const masked = maskOf(text);267+268+ return FORMS.flatMap((form) =>269+ [...masked.matchAll(form)].map((match) => {270+ const contents = match.groups?.contents ?? "";271+ // The contents end one character before the match does, at the quote.272+ const start = match.index + match[0].length - 1 - contents.length;273+274+ return {275+ line: text.slice(0, start).split("\n").length,276+ specifier: text.slice(start, start + contents.length),277+ start,278+ };279+ })280+ )281+ .toSorted((one, other) => one.start - other.start)282+ .map(({ line, specifier }) => ({ line, specifier }));283+};284+285+// A specifier relative to the importing file: `./x`, `../x`, `.` or `..`.286+const RELATIVE = /^\.\.?(?:\/|$)/u;287+288+// The folders a package subpath may not name: they hold a module's insides.289+const INSIDES = new Set(["src", "test", "internal"]);290+291+type Module = Policy["modules"][number];292+293+const moduleOf = (modules: Policy["modules"], path: string) =>294+ Array.findFirst(modules, (module) => matchAny(module.paths, path));295+296+/** `from`'s folder joined with a relative specifier; none when it leaves the repo. */297+const resolve = (from: string, specifier: string): Option.Option<string> => {298+ const parts = from.split("/").slice(0, -1);299+300+ for (const part of specifier.split("/")) {301+ if (part === "..") {302+ if (parts.length === 0) {303+ return Option.none();304+ }305+306+ parts.pop();307+ } else if (part !== "." && part !== "") {308+ parts.push(part);309+ }310+ }311+312+ return Option.some(parts.join("/"));313+};314+315+/** A module file's path with its extension and a trailing `/index` dropped. */316+const bare = (path: string) =>317+ path.replace(/\.[cm]?[jt]sx?$/u, "").replace(/\/index$/u, "");318+319+/** The folders a module's globs name: `packages/b/**` is `packages/b`. */320+const rootsOf = (module: Module) =>321+ module.paths.map((glob) =>322+ glob.replace(/^\//u, "").replace(/\/(?:\*\*)?$/u, "")323+ );324+325+/**326+ * Whether `target` is a file of `module` that it does not export. A folder327+ * import of the module's root goes through its manifest, so it is public; a328+ * module that lists no public files is not judged.329+ */330+const isInternal = (module: Module, target: string) =>331+ module.publicFiles !== undefined &&332+ !rootsOf(module).includes(target) &&333+ !module.publicFiles.some((file) => bare(file) === bare(target));334+335+/** The module a relative specifier lands in, when it is internal there. */336+const relative = (337+ from: string,338+ specifier: string,339+ modules: Policy["modules"]340+) =>341+ Option.flatMap(resolve(from, specifier), (target) =>342+ Option.filter(moduleOf(modules, target), (module) =>343+ isInternal(module, target)344+ )345+ );346+347+/**348+ * The module a package specifier names, when its subpath names a folder that349+ * holds the module's insides: `@scope/b/src/internal`. Only the project's own350+ * modules are judged; a dependency's insides are its own business.351+ */352+const subpath = (specifier: string, modules: Policy["modules"]) => {353+ const segments = specifier.split("/");354+ const length = specifier.startsWith("@") ? 2 : 1;355+ const name = segments.slice(0, length).join("/");356+357+ return segments.slice(length).some((segment) => INSIDES.has(segment))358+ ? Array.findFirst(modules, (module) => module.module === name)359+ : Option.none();360+};361+362+/**363+ * Whether an import of `specifier` from `from` reaches into another module's364+ * internals: a relative import that lands on a file of another module that365+ * the module does not export, or a package subpath of another module that366+ * names its `src`, `test` or `internal` folder. Imports inside the importing367+ * file's own module are its own.368+ */369+export const reachedInternals = (input: {370+ readonly from: RepoPath;371+ readonly specifier: string;372+ readonly modules: Policy["modules"];373+}): Option.Option<{ readonly from: RepoPath; readonly to: string }> => {374+ const { from, modules, specifier } = input;375+ const own = Option.map(moduleOf(modules, from), (module) => module.module);376+377+ const reached = RELATIVE.test(specifier)378+ ? relative(from, specifier, modules)379+ : subpath(specifier, modules);380+381+ return Option.flatMap(reached, (module) =>382+ Option.contains(own, module.module)383+ ? Option.none()384+ : Option.some({ from, to: specifier })385+ );386+};modified:packages/gate/src/markers.ts+52 added-32 removed
1 /**2 * Weakening markers: text an answer adds that turns a check off. A marker3 * with no reason after ` -- ` is refused at shape; one with a reason is an4- * escape, counted against its territory's ratchet (FE §8.4).4+ * escape, counted against its territory's escape ratchet (FE §8.4).5 */6-import type { At } from "@repo/protocol/domain/common";6 import type { Policy } from "@repo/protocol/domain/policy";7+import type { RepoPath } from "@repo/protocol/ids";8 import { Option, Order } from "effect";9 10 import type { PushFacts } from "./facts.ts";11 12+/** One marker, and the kind of check it turns off. */13+export interface Marker {14+ readonly text: string;15+ readonly family:16+ | "test"17+ | "lint"18+ | "types"19+ | "effect"20+ | "coverage"21+ | "python"22+ | "rust"23+ | "go";24+}25+26 /** The markers every project starts with (spec §4.2); a project may add more. */13-export const defaultMarkers: readonly string[] = [14- ".skip(",15- ".only(",16- ".todo(",17- "eslint-disable",18- "oxlint-disable",19- "biome-ignore",20- "@ts-ignore",21- "@ts-expect-error",22- "@ts-nocheck",23- "@effect-diagnostics",24- "# noqa",25- "# type: ignore",26- "#[allow(",27- "//nolint",28- "istanbul ignore",29- "c8 ignore",27+export const defaultMarkers: readonly Marker[] = [28+ { family: "test", text: ".skip(" },29+ { family: "test", text: ".only(" },30+ { family: "test", text: ".todo(" },31+ { family: "lint", text: "eslint-disable" },32+ { family: "lint", text: "oxlint-disable" },33+ { family: "lint", text: "biome-ignore" },34+ { family: "types", text: "@ts-ignore" },35+ { family: "types", text: "@ts-expect-error" },36+ { family: "types", text: "@ts-nocheck" },37+ { family: "effect", text: "@effect-diagnostics" },38+ { family: "python", text: "# noqa" },39+ { family: "python", text: "# type: ignore" },40+ { family: "rust", text: "#[allow(" },41+ { family: "go", text: "//nolint" },42+ { family: "coverage", text: "istanbul ignore" },43+ { family: "coverage", text: "c8 ignore" },44 ];45 46 /** The defaults and the markers the project adds, each once. */47 export const markersOf = (policy: Policy): readonly string[] => [34- ...new Set([...defaultMarkers, ...policy.weakening.markers]),48+ ...new Set([49+ ...defaultMarkers.map((marker) => marker.text),50+ ...policy.weakening.markers,51+ ]),52 ];53 37-/** One marker on one added line, with the reason written after it, if any. */54+/** One marker on one line, with the reason written after it, if any. */55 export interface MarkerHit {56+ readonly path: RepoPath;57+ readonly line: number;58 readonly marker: string;40- readonly at: At;59 readonly reason: Option.Option<string>;60 }61 62 // The ` -- ` that starts a reason, as the debt ledger reads it.18 unmodified lines81 return reason === "" ? Option.none() : Option.some(reason);82 };83 84 /**67- * Every marker in `markers` that an added line holds, once per line, ordered68- * by path, then line. A marker is plain text: it is found in any file, a69- * string in a README included.85+ * Every marker in `markers` that a line holds, once per line, ordered by86+ * path, then line. A marker is plain text: it is found in any file, a string87+ * in a README included; a project decides by adding to or trimming its list.88+ * The lines are an answer's added lines, or its removed ones.89 */71-export const findMarkers = (72- markers: readonly string[],73- added: PushFacts["addedLines"]90+export const scanMarkers = (91+ lines: PushFacts["addedLines"],92+ markers: readonly string[]93 ): readonly MarkerHit[] =>75- [...added]94+ [...lines]95 .toSorted(([one], [other]) => Order.String(one, other))77- .flatMap(([path, lines]) =>78- lines96+ .flatMap(([path, each]) =>97+ each98 .toSorted((one, other) => one.line - other.line)99 .flatMap(({ line, text }) =>100 markers.flatMap((marker) => {101 const index = text.indexOf(marker);1 unmodified line103 return index === -1104 ? []105 : [106 {88- at: { line, path },107+ line,108 marker,109+ path,110 reason: reasonIn(text.slice(index + marker.length)),111 },112 ];113 })2 unmodified linesadded:packages/gate/test/escapes.test.ts+126 added
1+import { describe, expect, it } from "@effect/vitest";2+import { DecisionSubject } from "@repo/protocol/domain/decision";3+import { RatchetName, RepoPath } from "@repo/protocol/ids";4+import { Option } from "effect";5+6+import { escapeDecisions, escapeRatchet } from "../src/escapes.ts";7+import { addedLines, ask, testFacts } from "./facts.ts";8+9+const week = "packages/parse/src/week.ts";10+11+const lex = "packages/parse/src/lex.ts";12+13+const pad = "packages/format/src/pad.ts";14+15+const cast =16+ "// oxlint-disable-next-line no-explicit-any -- the parser's one cast";17+18+const generated = "/* eslint-disable no-console -- generated tables */";19+20+const parseEscapes = RatchetName.make("escapes-datekit-parse");21+22+/** The `Waiver` for the escape `marker` with `reason` at `path:line`. */23+const waiver = (path: string, line: number, marker: string, reason: string) =>24+ DecisionSubject.cases.Waiver.make({25+ ask: ask.id,26+ at: { line, path: RepoPath.make(path) },27+ marker,28+ reason,29+ });30+31+describe(escapeRatchet, () => {32+ it.each([33+ ["@datekit/parse", "escapes-datekit-parse"],34+ ["packages/parser", "escapes-packages-parser"],35+ ["Parse_Kit", "escapes-parse-kit"],36+ [".", "escapes-root"],37+ ])("names %s's escape ratchet %s", (territory, name) => {38+ expect(escapeRatchet(territory)).toBe(name);39+ });40+});41+42+describe(escapeDecisions, () => {43+ it("asks a decider about a reasoned escape in a territory with none yet", () => {44+ expect(45+ escapeDecisions(testFacts({ addedLines: addedLines([week, 4, cast]) }))46+ ).toStrictEqual([47+ waiver(week, 4, "oxlint-disable", "the parser's one cast"),48+ ]);49+ });50+51+ it("asks about every reasoned escape in a territory the push raises", () => {52+ expect(53+ escapeDecisions(54+ testFacts({55+ addedLines: addedLines([week, 9, generated], [week, 4, cast]),56+ ratchetBaselines: new Map([[parseEscapes, 1]]),57+ })58+ )59+ ).toStrictEqual([60+ waiver(week, 4, "oxlint-disable", "the parser's one cast"),61+ waiver(week, 9, "eslint-disable", "generated tables"),62+ ]);63+ });64+65+ it("asks nothing when the baseline already covers the territory's escapes after the push", () => {66+ // A decider accepted a waiver for this answer: the baseline rose to 367+ // while main still holds 2, so the answer, checked again, is within it.68+ expect(69+ escapeDecisions(70+ testFacts({71+ addedLines: addedLines([week, 4, cast]),72+ escapeCounts: new Map([[parseEscapes, 2]]),73+ ratchetBaselines: new Map([[parseEscapes, 3]]),74+ })75+ )76+ ).toStrictEqual([]);77+ });78+79+ it("asks nothing when the push removes as many escapes from the territory as it adds", () => {80+ expect(81+ escapeDecisions(82+ testFacts({83+ addedLines: addedLines([week, 4, cast]),84+ ratchetBaselines: new Map([[parseEscapes, 1]]),85+ removedLines: addedLines([lex, 12, generated]),86+ })87+ )88+ ).toStrictEqual([]);89+ });90+91+ it("counts a removed escape only against its own territory", () => {92+ expect(93+ escapeDecisions(94+ testFacts({95+ addedLines: addedLines([week, 4, cast]),96+ ratchetBaselines: new Map([97+ [escapeRatchet("@datekit/format"), 1],98+ [parseEscapes, 1],99+ ]),100+ removedLines: addedLines([pad, 3, generated], [lex, 7, "// x"]),101+ })102+ )103+ ).toStrictEqual([104+ waiver(week, 4, "oxlint-disable", "the parser's one cast"),105+ ]);106+ });107+108+ it("asks nothing about a marker with no reason, which shape refuses", () => {109+ expect(110+ escapeDecisions(111+ testFacts({ addedLines: addedLines([week, 4, "// @ts-ignore"]) })112+ )113+ ).toStrictEqual([]);114+ });115+116+ it("asks nothing for a push that answers no ask", () => {117+ expect(118+ escapeDecisions(119+ testFacts({120+ addedLines: addedLines([week, 4, cast]),121+ ask: Option.none(),122+ })123+ )124+ ).toStrictEqual([]);125+ });126+});added:packages/gate/test/imports.test.ts+237 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Territory } from "@repo/protocol/domain/territory";3+import { RepoPath } from "@repo/protocol/ids";4+import { Option, Schema } from "effect";5+6+import { importSpecifiers, reachedInternals } from "../src/imports.ts";7+8+/** The text of `lines`, one per line. */9+const text = (...lines: readonly string[]) => lines.join("\n");10+11+describe(importSpecifiers, () => {12+ it.each([13+ {14+ found: [{ line: 1, specifier: "./week.ts" }],15+ name: "a static import",16+ text: 'import { week } from "./week.ts";',17+ },18+ {19+ found: [{ line: 1, specifier: "@scope/b" }],20+ name: "a type-only import, in single quotes",21+ text: "import type { B } from '@scope/b';",22+ },23+ {24+ found: [{ line: 4, specifier: "../format/src/pad.ts" }],25+ name: "an import over several lines, on the line of its specifier",26+ text: text(27+ "import {",28+ " pad,",29+ " trim,",30+ '} from "../format/src/pad.ts";'31+ ),32+ },33+ {34+ found: [35+ { line: 1, specifier: "./x.ts" },36+ { line: 2, specifier: "./y.ts" },37+ { line: 3, specifier: "./z.ts" },38+ ],39+ name: "re-exports",40+ text: text(41+ 'export { x } from "./x.ts";',42+ 'export * from "./y.ts";',43+ 'export * as z from "./z.ts";'44+ ),45+ },46+ {47+ found: [{ line: 1, specifier: "./polyfill.ts" }],48+ name: "a side-effect import",49+ text: 'import "./polyfill.ts";',50+ },51+ {52+ found: [53+ { line: 1, specifier: "./lazy.ts" },54+ { line: 3, specifier: "./later.ts" },55+ ],56+ name: "dynamic imports, one over several lines",57+ text: text(58+ 'const lazy = await import("./lazy.ts");',59+ "const later = await import(",60+ ' "./later.ts"',61+ ");"62+ ),63+ },64+ {65+ found: [66+ { line: 1, specifier: "node:fs" },67+ { line: 2, specifier: "./config.cjs" },68+ ],69+ name: "require calls",70+ text: text(71+ 'const fs = require("node:fs");',72+ "import config = require('./config.cjs');"73+ ),74+ },75+ {76+ found: [77+ { line: 1, specifier: "../b/src/internal.ts" },78+ { line: 2, specifier: "../b/src/cache.ts" },79+ ],80+ name: "a dynamic import and a require whose specifier is a template with no substitution",81+ text: text(82+ "const lazy = await import(`../b/src/internal.ts`);",83+ "const cache = require(`../b/src/cache.ts`);"84+ ),85+ },86+ {87+ found: [],88+ name: "nothing for a template specifier with a substitution, which only stage 3 resolves",89+ text: `const locale = await import(\`./locales/\${lang}.ts\`);`,90+ },91+ {92+ found: [93+ { line: 1, specifier: "./lazy.ts" },94+ { line: 2, specifier: "./later.ts" },95+ ],96+ name: "an import after a division by a postfix increment or decrement",97+ text: text(98+ 'const half = n++ / 2, lazy = import("./lazy.ts");',99+ 'const rest = m-- / 2, later = import("./later.ts");'100+ ),101+ },102+ {103+ found: [{ line: 1, specifier: "../b/src/internal.ts" }],104+ name: "the last line of an import whose first line is not in the text",105+ text: ' trim } from "../b/src/internal.ts";',106+ },107+ {108+ found: [{ line: 7, specifier: "./after.ts" }],109+ name: "nothing in a comment",110+ text: text(111+ '// import { a } from "./line.ts";',112+ '/* import("./block.ts") */',113+ "/**",114+ ' * import { b } from "./doc.ts";',115+ ' * require("./doc.cjs")',116+ " */",117+ 'import "./after.ts"; // import "./trailing.ts"'118+ ),119+ },120+ {121+ found: [],122+ name: "nothing in a doc comment whose opening line is not in the text",123+ text: text(' * import { b } from "./doc.ts";', " */"),124+ },125+ {126+ found: [{ line: 3, specifier: "./real.ts" }],127+ name: "nothing in a string, and no comment opened by one",128+ text: text(129+ "const said = \"import { a } from './quoted.ts'\";",130+ 'const slashes = "// not a comment", star = "/* nor this";',131+ 'import { real } from "./real.ts";'132+ ),133+ },134+ {135+ found: [{ line: 2, specifier: "./after.ts" }],136+ name: "nothing in a regular expression",137+ text: text(138+ 'const quote = /["\']/u, fake = /import\\("x"\\)/u;',139+ 'import { after } from "./after.ts";'140+ ),141+ },142+ {143+ found: [],144+ name: "nothing that only looks like an import",145+ text: text(146+ 'const chars = Array.from("abc");',147+ 'const doc = `import x from "./template.ts"`;',148+ 'const message = "copied from \\"./quoted.ts\\"";'149+ ),150+ },151+ ])("finds $name", ({ found, text: source }) => {152+ expect(importSpecifiers(source)).toStrictEqual(found);153+ });154+});155+156+const modules = Schema.decodeSync(Schema.Array(Territory))([157+ {158+ module: "@scope/a",159+ paths: ["packages/a/**"],160+ publicFiles: ["packages/a/src/index.ts"],161+ },162+ {163+ module: "@scope/b",164+ paths: ["packages/b/**"],165+ publicFiles: ["packages/b/src/index.ts", "packages/b/src/public.ts"],166+ },167+ { module: "@scope/c", paths: ["packages/c/**"] },168+]);169+170+const from = RepoPath.make("packages/a/src/x.ts");171+172+const reached = (specifier: string) =>173+ reachedInternals({ from, modules, specifier });174+175+describe(reachedInternals, () => {176+ it.each([177+ "../../b/src/internal.ts",178+ "../../b/src/deep/internal",179+ "../../b/test/fixtures.ts",180+ "../../b/package.json",181+ ])("refuses %s, a file of another module it does not export", (specifier) => {182+ expect(reached(specifier)).toStrictEqual(183+ Option.some({ from, to: specifier })184+ );185+ });186+187+ it.each([188+ "@scope/b/src/internal",189+ "@scope/b/src/index.ts",190+ "@scope/b/test/fixtures",191+ "@scope/b/internal/cache",192+ ])(193+ "refuses %s, a subpath of another module naming its src, test or internal folder",194+ (specifier) => {195+ expect(reached(specifier)).toStrictEqual(196+ Option.some({ from, to: specifier })197+ );198+ }199+ );200+201+ it.each([202+ "../../b/src/public.ts",203+ "../../b/src/public.js",204+ "../../b/src/index",205+ "../../b/src",206+ "../../b",207+ "../../b/",208+ ])(209+ "allows %s, which lands on a file the other module exports",210+ (specifier) => {211+ expect(reached(specifier)).toStrictEqual(Option.none());212+ }213+ );214+215+ it.each(["./y.ts", "../test/helper.ts", "../package.json", "@scope/a/src/y"])(216+ "allows %s, inside the same module",217+ (specifier) => {218+ expect(reached(specifier)).toStrictEqual(Option.none());219+ }220+ );221+222+ it.each([223+ "@scope/b",224+ "@scope/b/format",225+ "effect",226+ "effect/src/internal/core",227+ "node:fs",228+ "#internal/cache",229+ "../../c/src/anything.ts",230+ "../../../scripts/gen.ts",231+ ])(232+ "allows %s: a package's exports, a module listing no public files, or no module",233+ (specifier) => {234+ expect(reached(specifier)).toStrictEqual(Option.none());235+ }236+ );237+});modified:packages/gate/test/markers.test.ts+58 added-22 removed
1 import { describe, expect, it } from "@effect/vitest";2 import { RepoPath } from "@repo/protocol/ids";3 import { Option } from "effect";4 5-import { defaultMarkers, findMarkers } from "../src/markers.ts";6-import { addedLines } from "./facts.ts";5+import { defaultMarkers, markersOf, scanMarkers } from "../src/markers.ts";6+import { addedLines, policy } from "./facts.ts";7 8-const at = (path: string, line: number) => ({9- line,10- path: RepoPath.make(path),11-});8+const texts = defaultMarkers.map((marker) => marker.text);9 10 // One added line per default marker in spec §4.2, as each tool writes it.11 const lines: readonly (readonly [string, string])[] = [12 [".skip(", ' it.skip("parses week 53", () => {'],13 unmodified lines26 ["istanbul ignore", "/* istanbul ignore next */"],27 ["c8 ignore", "/* c8 ignore next */"],28 ];29 33-describe(findMarkers, () => {30+describe(markersOf, () => {31+ it("starts from the spec's default list, each marker with the kind of check it turns off", () => {32+ expect(33+ defaultMarkers.map(({ family, text }) => `${family} ${text}`)34+ ).toStrictEqual([35+ "test .skip(",36+ "test .only(",37+ "test .todo(",38+ "lint eslint-disable",39+ "lint oxlint-disable",40+ "lint biome-ignore",41+ "types @ts-ignore",42+ "types @ts-expect-error",43+ "types @ts-nocheck",44+ "effect @effect-diagnostics",45+ "python # noqa",46+ "python # type: ignore",47+ "rust #[allow(",48+ "go //nolint",49+ "coverage istanbul ignore",50+ "coverage c8 ignore",51+ ]);52+ });53+54+ it("adds the markers a project adds to the defaults, each once", () => {55+ expect(56+ markersOf({57+ ...policy,58+ weakening: { markers: ["vi.mock(", ".skip("] },59+ })60+ ).toStrictEqual([...texts, "vi.mock("]);61+ });62+});63+64+describe(scanMarkers, () => {65 it.each(lines)("finds %s where a tool writes it", (marker, text) => {35- const hits = findMarkers(defaultMarkers, addedLines(["src/x.ts", 5, text]));66+ const hits = scanMarkers(addedLines(["src/x.ts", 5, text]), texts);67 68 expect(hits.map((hit) => hit.marker)).toContain(marker);69 });70 71 it("finds a marker in any file, a README's prose included", () => {41- const hits = findMarkers(42- defaultMarkers,43- addedLines(["README.md", 40, "Run `it.only(` to focus a test."])72+ const hits = scanMarkers(73+ addedLines(["README.md", 40, "Run `it.only(` to focus a test."]),74+ texts75 );76 77 expect(hits).toStrictEqual([47- { at: at("README.md", 40), marker: ".only(", reason: Option.none() },78+ {79+ line: 40,80+ marker: ".only(",81+ path: RepoPath.make("README.md"),82+ reason: Option.none(),83+ },84 ]);85 });86 87 it("reads the reason after ` -- `, without the comment's closer", () => {52- const hits = findMarkers(53- defaultMarkers,88+ const hits = scanMarkers(89 addedLines(90 ["src/a.ts", 1, "// oxlint-disable-next-line no-x -- reason given"],91 ["src/a.ts", 2, "/* eslint-disable no-y -- generated code */"],92 ["src/a.ts", 3, "// @ts-expect-error -- "],93 ["src/a.ts", 4, "it.skip(--flag)"]59- )94+ ),95+ texts96 );97 98 expect(hits.map((hit) => hit.reason)).toStrictEqual([99 Option.some("reason given"),3 unmodified lines103 ]);104 });105 106 it("orders what it finds by path, then line", () => {71- const hits = findMarkers(72- defaultMarkers,107+ const hits = scanMarkers(108 addedLines(109 ["src/b.ts", 9, "it.only("],110 ["src/b.ts", 3, "it.skip("],111 ["src/a.ts", 7, "// @ts-ignore"]77- )112+ ),113+ texts114 );115 80- expect(hits.map((hit) => hit.at)).toStrictEqual([81- at("src/a.ts", 7),82- at("src/b.ts", 3),83- at("src/b.ts", 9),116+ expect(hits.map(({ line, path }) => `${path}:${line}`)).toStrictEqual([117+ "src/a.ts:7",118+ "src/b.ts:3",119+ "src/b.ts:9",120 ]);121 });122 });modified:packages/gate/test/shape.test.ts+194 added-3 removed
1 import { describe, expect, it } from "@effect/vitest";2+import { Glob } from "@repo/protocol/domain/common";3+import { Territory } from "@repo/protocol/domain/territory";4 import { RepoPath } from "@repo/protocol/ids";5 import {6 groups,7 OutOfScope,2 unmodified lines10 TouchedJudge,11 Weakened,12 } from "@repo/protocol/refusal";13 import type { Refusal } from "@repo/protocol/refusal";12-import { Array, Effect } from "effect";14+import { Array, Effect, Option, Schema } from "effect";15 16 import type { PushFacts } from "../src/facts.ts";17 import { scan } from "../src/stages/shape.ts";18 import {41 unmodified lines60 ],61 { layerPaths: new Set([RepoPath.make("docs/guide.md")]) }62 );63 64+// The language service reads its directive anywhere in a source file, so65+// the marker is joined at run time (spec §7.4).66+const effectDiagnostics = ["@effect", "-diagnostics"].join("");67+68+// Two modules, `a` and `b`; the ask's territory is `a`, and the judge69+// closure also holds the lint config.70+const [moduleA, moduleB] = Schema.decodeSync(71+ Schema.Tuple([Territory, Territory])72+)([73+ {74+ module: "a",75+ paths: ["packages/a/**"],76+ publicFiles: ["packages/a/src/index.ts"],77+ },78+ {79+ module: "b",80+ paths: ["packages/b/**"],81+ publicFiles: ["packages/b/src/index.ts"],82+ },83+]);84+85+const x = "packages/a/src/x.ts";86+87+const xTest = "packages/a/test/x.test.ts";88+89+/** A push answering an ask in module `a`. */90+const pushToA = (91+ files: readonly string[],92+ lines: readonly (readonly [string, number, string])[] = []93+) =>94+ push(files, lines, {95+ ask: Option.some({ ...ask, territory: moduleA }),96+ policy: {97+ ...policy,98+ judge: {99+ ...policy.judge,100+ paths: [...policy.judge.paths, Glob.make("oxlint.config.*")],101+ },102+ modules: [moduleA, moduleB],103+ },104+ });105+106+// Every default marker in spec §4.2, as a tool writes it on an added line.107+const markerLines: readonly (readonly [string, string])[] = [108+ [".skip(", ' it.skip("parses week 53", () => {'],109+ [".only(", ' describe.only("weeks", () => {'],110+ [".todo(", ' it.todo("parses week 54");'],111+ ["eslint-disable", "/* eslint-disable no-console */"],112+ ["oxlint-disable", "// oxlint-disable-next-line no-explicit-any"],113+ ["biome-ignore", "// biome-ignore lint/style: generated"],114+ ["@ts-ignore", "// @ts-ignore"],115+ ["@ts-expect-error", "// @ts-expect-error"],116+ ["@ts-nocheck", "// @ts-nocheck"],117+ [effectDiagnostics, `// ${effectDiagnostics} floatingEffect:off`],118+ ["# noqa", "import os # noqa"],119+ ["# type: ignore", "x = parse(y) # type: ignore"],120+ ["#[allow(", "#[allow(dead_code)]"],121+ ["//nolint", "func parse() { //nolint"],122+ ["istanbul ignore", "/* istanbul ignore next */"],123+ ["c8 ignore", "/* c8 ignore next */"],124+];125+126+const pad = "../../format/src/pad.ts";127+128+/** ReachedInternals for an import of `to` on line `line` of `week`. */129+const reachedFromWeek = (line: number, to: string) =>130+ new ReachedInternals({ at: at(week, line), from: RepoPath.make(week), to });131+132 // Each row is one push. Shape reports every problem the push has, in the133 // order of the refusal union's Shape group.134 const rows: readonly {135 readonly name: string;83 unmodified lines219 facts: push(220 [week],221 [[week, 7, "// oxlint-disable-next-line no-x -- reason given"]]222 ),153- name: "an added escape with a reason (counted by the ratchet stage)",223+ name: "an added escape with a reason (counted by escapeDecisions)",224 refusals: [],225 },226 {227 facts: push([weekTest], [[weekTest, 2, 'vi.mock("../src/week.ts");']], {62 unmodified lines290 [week],291 [292 [week, 1, 'import { pad } from "../../format/src/index.ts";'],293 [week, 2, 'import { lex } from "./lex.ts";'],224- [week, 3, 'import { Array, Effect } from "effect";'],294+ [week, 3, 'import { Array, Effect, Option, Schema } from "effect";'],295 ]296 ),297 name: "imports of another module's public file, its own files and a package",298 refusals: [],299 },300 {301+ facts: pushToA(302+ [x],303+ [[x, 12, `// ${effectDiagnostics} floatingEffect:off`]]304+ ),305+ name: "an added Effect diagnostics directive with no reason",306+ refusals: [307+ new Weakened({308+ at: at(x, 12),309+ weakening: { marker: effectDiagnostics },310+ }),311+ ],312+ },313+ {314+ facts: pushToA(315+ [x],316+ [317+ [318+ x,319+ 12,320+ `// ${effectDiagnostics} floatingEffect:off -- the Worker's fetch is the one HTTP client`,321+ ],322+ ]323+ ),324+ name: "an added Effect diagnostics directive with a reason",325+ refusals: [],326+ },327+ {328+ facts: pushToA(329+ ["packages/b/src/y.ts", xTest, "oxlint.config.ts", x],330+ [331+ [xTest, 9, ' it.only("reads y", () => {'],332+ [x, 1, 'import { y } from "../../b/src/internal.ts";'],333+ [xTest, 3, ' it.skip("reads x", () => {'],334+ ]335+ ),336+ name: "a push out of scope, touching the judge, weakening twice and reaching into internals, all at once",337+ refusals: [338+ new OutOfScope({ paths: paths("packages/b/src/y.ts") }),339+ new TouchedJudge({ paths: paths("oxlint.config.ts") }),340+ new Weakened({ at: at(xTest, 3), weakening: { marker: ".skip(" } }),341+ new Weakened({ at: at(xTest, 9), weakening: { marker: ".only(" } }),342+ new ReachedInternals({343+ at: at(x, 1),344+ from: RepoPath.make(x),345+ to: "../../b/src/internal.ts",346+ }),347+ ],348+ },349+ ...markerLines.map(([marker, text]) => ({350+ facts: push([week], [[week, 5, text]]),351+ name: `the default marker ${marker}`,352+ refusals: [new Weakened({ at: at(week, 5), weakening: { marker } })],353+ })),354+ {355+ facts: push(356+ ["packages/parse/README.md"],357+ [["packages/parse/README.md", 40, 'Focus one test with `it.only("…")`.']]358+ ),359+ name: "a marker inside a string in a README",360+ refusals: [361+ new Weakened({362+ at: at("packages/parse/README.md", 40),363+ weakening: { marker: ".only(" },364+ }),365+ ],366+ },367+ {368+ facts: push(369+ [week],370+ [371+ [week, 2, `const pad = await import("${pad}");`],372+ [week, 6, `const { trim } = require("${pad}");`],373+ ]374+ ),375+ name: "a dynamic import and a require of another module's internal file",376+ refusals: [reachedFromWeek(2, pad), reachedFromWeek(6, pad)],377+ },378+ {379+ facts: push([week], [[week, 4, `const pad = await import(\`${pad}\`);`]]),380+ name: "a dynamic import of another module's internal file, its specifier a template",381+ refusals: [reachedFromWeek(4, pad)],382+ },383+ {384+ facts: push(385+ [week],386+ [387+ [388+ week,389+ 1,390+ `import a from "../../format/src/a.ts"; import b from "${pad}";`,391+ ],392+ ]393+ ),394+ name: "two imports of internal files on one line",395+ refusals: [396+ reachedFromWeek(1, "../../format/src/a.ts"),397+ reachedFromWeek(1, pad),398+ ],399+ },400+ {401+ facts: push(402+ [week],403+ [[week, 1, 'import { pad } from "@datekit/format/src/pad";']]404+ ),405+ name: "a package subpath into another module's src folder",406+ refusals: [reachedFromWeek(1, "@datekit/format/src/pad")],407+ },408+ {409+ facts: push(410+ [week, "packages/parse/README.md"],411+ [412+ [week, 1, `// import { pad } from "${pad}";`],413+ [week, 2, 'import { pad } from "../../format";'],414+ [week, 3, 'import { trim } from "@datekit/format";'],415+ ["packages/parse/README.md", 1, `import { pad } from "${pad}";`],416+ ]417+ ),418+ name: "an import in a comment, of a module's root or package, or in prose",419+ refusals: [],420+ },421+ {422 facts: everyProblem,423 name: "every shape problem at once",424 refusals: [425 new OutOfScope({ paths: paths("docs/guide.md") }),36 unmodified linesmodified:packages/git/test/gateway.test.ts+1 added-1 removed
245 unmodified lines246 );247 248 expect(pushed.exitCode).toBe(1);249 expect(remoteLines(pushed.stderr)).toContain(250- "remote: OutOfScope: changes paths outside the ask's territory: src/a.ts"250+ "remote: OutOfScope: changes paths outside the ask's territory: src/a.ts; put those files back, or flag the ask if the want needs them"251 );252 expect(pushed.stderr).toContain(253 " ! [remote rejected] HEAD -> answer (OutOfScope)"254 );112 unmodified linesmodified:packages/protocol/src/render.ts+8 added-7 removed
9 unmodified lines10 11 const list = (items: readonly string[]) => items.join(", ");12 13 // Reasons name only what the refusal's reader may see: held-back checks give14-// their area and suite, never a case or an input.14+// their area and suite, never a case or an input. A shape refusal's reason15+// ends with how to repair it, after its first clause; `next` stays the command.16 const reason = Match.typeTags<Refusal, string>()({17 AskBlocked: ({ ask, blockedBy }) =>18 `${ask} waits on ${list(blockedBy)} to land first`,19 AskFull: ({ ask }) => `someone else holds the claim on ${ask}`,26 unmodified lines46 NotSensitive: ({ key }) =>47 `${key} is not @sensitive, so it holds no write-only value`,48 NotVouched: () => "no member of this project has vouched for you",49 OutOfScope: ({ paths }) =>49- `changes paths outside the ask's territory: ${list(paths)}`,50+ `changes paths outside the ask's territory: ${list(paths)}; put those files back, or flag the ask if the want needs them`,51 PostureChange: ({ from, to }) =>52 `landing would change the posture from ${from} to ${to}, which takes a decider`,53 PrivatePathInPublicTree: ({ paths }) =>53- `would put held-back paths in a public tree: ${list(paths)}`,54+ `would put held-back paths in a public tree: ${list(paths)}; those paths belong to a layer, so remove them from the answer`,55 ProjectExists: ({ project }) => `a project named ${project} already exists`,56 ReachedInternals: ({ from, to }) =>56- `${from} reaches into ${to}, which its module does not export`,57+ `${from} reaches into ${to}, which its module does not export; import it through that module's public exports instead`,58 RepoBusy: () => "the repo was busy with another push",59 SecretInOutput: ({ item, where }) =>60 `the write-only value ${item} appeared in the ${where}`,61 StaleBase: ({ base, conflicts, main }) =>2 unmodified lines64 : `main moved to ${short(main)}, past your base ${short(base)}; conflicts in ${list(conflicts)}`,65 StaleLayer: ({ layer }) =>66 `the ${layer} layer moved since this answer was checked; it will be checked again`,67 TouchedJudge: ({ paths }) =>67- `changes files that decide what the checks do: ${list(paths)}`,68+ `changes files that decide what the checks do: ${list(paths)}; the checks are fixed for this ask, so put them back, or flag the ask if a check is wrong`,69 UnknownAsk: ({ ask }) => `this project has no ask named ${ask}`,70 UnknownCommit: ({ sha }) => `this project has no commit ${sha}`,71 UnknownDecision: ({ decision }) => `this project has no decision ${decision}`,72 UnknownEnvItem: ({ key }) => `the env shape has no item ${key}`,10 unmodified lines83 return `raises the ${weakening.ratchet} ratchet in ${weakening.territory} from ${weakening.before} to ${weakening.after}`;84 }85 86 return weakening.reason === undefined86- ? `adds ${weakening.marker} without a reason`87- : `adds ${weakening.marker}, with the reason "${weakening.reason}"`;87+ ? `adds ${weakening.marker} without a reason; remove it, or give a reason after " -- " for a decider to weigh`88+ : `adds ${weakening.marker}, with the reason "${weakening.reason}"; it waits for a decider because it raises this territory's escapes`;89 },90 });91 92 const block = (refusal: Refusal) => [54 unmodified linesmodified:packages/protocol/test/render.test.ts+117 added-12 removed
7 unmodified lines8 DecisionId,9 EnvKey,10 LandedSha,11 ProjectName,12+ RepoPath,13 RequestId,14 } from "../src/ids.ts";15 import {16 DirectPush,17 OutOfScope,18+ PrivatePathInPublicTree,19+ ReachedInternals,20 StaleBase,21 TouchedJudge,22 ValueTooShort,23 Weakened,38 unmodified lines62 weakening: { marker: "it.skip" },63 }),64 ])65 ).toStrictEqual([63- "Weakened: adds it.skip without a reason",66+ 'Weakened: adds it.skip without a reason; remove it, or give a reason after " -- " for a decider to weigh',67 " at: src/a.ts:3",68 ` next: ${Brand.cli} check`,69 " retryable: no",70 ]);71 });72 70- it("lists every refusal, in order", () => {71- expect(72- explain([outOfScope, touchedJudge]).filter(73- (line) => !line.startsWith(" ")74- )75- ).toStrictEqual([76- "OutOfScope: changes paths outside the ask's territory: src/a.ts",77- "TouchedJudge: changes files that decide what the checks do: src/a.ts",78- ]);79- });80-73 it.each(examples)("explains $_tag, opening with its tag", (refusal) => {74 expect(explain([refusal])[0]).toMatch(75 new RegExp(`^${refusal._tag}: \\S`, "u")76 );7 unmodified lines84 );85 }86 );87 88+ // Each shape refusal says how to repair it, after the reason's first clause.89+ it.each([90+ {91+ ends: "; put those files back, or flag the ask if the want needs them",92+ refusal: outOfScope,93+ starts: "OutOfScope: changes paths outside the ask's territory: src/a.ts",94+ },95+ {96+ ends: "; the checks are fixed for this ask, so put them back, or flag the ask if a check is wrong",97+ refusal: touchedJudge,98+ starts:99+ "TouchedJudge: changes files that decide what the checks do: src/a.ts",100+ },101+ {102+ ends: '; remove it, or give a reason after " -- " for a decider to weigh',103+ refusal: new Weakened({104+ at: { line: 3, path },105+ weakening: { marker: ".skip(" },106+ }),107+ starts: "Weakened: adds .skip( without a reason",108+ },109+ {110+ ends: "; it waits for a decider because it raises this territory's escapes",111+ refusal: new Weakened({112+ at: { line: 3, path },113+ weakening: { marker: "oxlint-disable", reason: "generated code" },114+ }),115+ starts: 'Weakened: adds oxlint-disable, with the reason "generated code"',116+ },117+ {118+ ends: "; import it through that module's public exports instead",119+ refusal: new ReachedInternals({120+ at: { line: 1, path },121+ from: path,122+ to: "../../b/src/internal.ts",123+ }),124+ starts:125+ "ReachedInternals: src/a.ts reaches into ../../b/src/internal.ts, which its module does not export",126+ },127+ {128+ ends: "; those paths belong to a layer, so remove them from the answer",129+ refusal: new PrivatePathInPublicTree({ paths: [path] }),130+ starts:131+ "PrivatePathInPublicTree: would put held-back paths in a public tree: src/a.ts",132+ },133+ ])(134+ "ends $refusal._tag's reason with how to repair it",135+ ({ ends, refusal, starts }) => {136+ expect(explain([refusal])[0]).toBe(`${starts}${ends}`);137+ }138+ );139+140+ it("explains every refusal of one push in the gate's order, each with its line", () => {141+ const a = RepoPath.make("packages/a/src/x.ts");142+ const test = RepoPath.make("packages/a/test/x.test.ts");143+144+ const refusals = [145+ new OutOfScope({ paths: [RepoPath.make("packages/b/src/y.ts")] }),146+ new TouchedJudge({ paths: [RepoPath.make("oxlint.config.ts")] }),147+ new Weakened({148+ at: { line: 3, path: test },149+ weakening: { marker: ".skip(" },150+ }),151+ new Weakened({152+ at: { line: 9, path: test },153+ weakening: { marker: ".only(" },154+ }),155+ new ReachedInternals({156+ at: { line: 1, path: a },157+ from: a,158+ to: "../../b/src/internal.ts",159+ }),160+ ] as const;161+162+ expect(explain(refusals)).toStrictEqual([163+ "OutOfScope: changes paths outside the ask's territory: packages/b/src/y.ts; put those files back, or flag the ask if the want needs them",164+ ` next: ${Brand.cli} check`,165+ " retryable: no",166+ "TouchedJudge: changes files that decide what the checks do: oxlint.config.ts; the checks are fixed for this ask, so put them back, or flag the ask if a check is wrong",167+ ` next: ${Brand.cli} check`,168+ " retryable: no",169+ 'Weakened: adds .skip( without a reason; remove it, or give a reason after " -- " for a decider to weigh',170+ " at: packages/a/test/x.test.ts:3",171+ ` next: ${Brand.cli} check`,172+ " retryable: no",173+ 'Weakened: adds .only( without a reason; remove it, or give a reason after " -- " for a decider to weigh',174+ " at: packages/a/test/x.test.ts:9",175+ ` next: ${Brand.cli} check`,176+ " retryable: no",177+ "ReachedInternals: packages/a/src/x.ts reaches into ../../b/src/internal.ts, which its module does not export; import it through that module's public exports instead",178+ " at: packages/a/src/x.ts:1",179+ ` next: ${Brand.cli} check`,180+ " retryable: no",181+ ]);182+ });183+184+ it("leaves a raised ratchet's reason as it was", () => {185+ expect(186+ explain([187+ new Weakened({188+ weakening: {189+ after: 4,190+ before: 3,191+ ratchet: "no-explicit-any",192+ territory: "parser",193+ },194+ }),195+ ])[0]196+ ).toBe(197+ "Weakened: raises the no-explicit-any ratchet in parser from 3 to 4"198+ );199+ });200+201 it("tells a direct push to main where answers go instead", () => {202 expect(explain([new DirectPush({ ref: "refs/heads/main" })])).toStrictEqual(203 [204 "DirectPush: main moves only by a landing, so refs/heads/main takes no direct push; push your answer to your claim's fork",66 unmodified lines