Skip to content
Myr

Merge build/206-gate: a push is parsed by a cost-ordered gate, and one push hears every shape problem at once

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

authored by oscabriel · committed by oscabriel · parents a61af0e, 9f64082 · Browse files · 20 files+2139 added−10 removed
This commit

State

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

Diff stats

20 files+2139 added−10 removed

  • tests:+1223 added−10 removed
  • other:+916 added−0 removed

20 files+2139 added−10 removed

added:packages/gate/src/stages/parse.ts+145 added
1/**2 * Stage 0, parse: who may push what. It reads only the push's target, the3 * pusher, the policy and the claim, so it is free; the first rule a push4 * breaks is its one refusal.5 */6import type { Policy } from "@repo/protocol/domain/policy";7import type { Handle } from "@repo/protocol/ids";8import { Principal } from "@repo/protocol/principal";9import {10 CapReached,11 ClaimLapsed,12 Denounced,13 DirectPush,14 NoAsk,15 NotClaimed,16 NotVouched,17} from "@repo/protocol/refusal";18import type { Refusal } from "@repo/protocol/refusal";19import { Array, Effect, Option } from "effect";20import type { Data } from "effect";2122import { PushTarget } from "../facts.ts";23import type { PushFacts } from "../facts.ts";24import type { Stage } from "../stage.ts";2526type Rule = (facts: PushFacts) => Option.Option<Refusal>;2728/** Handles name one person however their sign-in provider cases them. */29const sameHandle = (one: Handle, other: Handle) =>30 one.toLowerCase() === other.toLowerCase();3132const handleOf = (pusher: Principal): Option.Option<Handle> =>33 Principal.guards.Person(pusher) ? Option.some(pusher.handle) : Option.none();3435const isPusher = (facts: PushFacts, handle: Handle) =>36 Option.exists(handleOf(facts.pusher), (pusher) => sameHandle(pusher, handle));3738/**39 * Where a person stands by the vouch file: a line names them vouched or40 * denounced. Deciders vouch for others, so a decider with no line is vouched.41 */42const standingOf = (policy: Policy, handle: Handle) => {43 const line = policy.vouches.find((vouch) => sameHandle(vouch.handle, handle));4445 if (line !== undefined) {46 return line.denounced ? "denounced" : "vouched";47 }4849 const decides = policy.deciders.some((decider) =>50 decider.handles.some((each) => sameHandle(each, handle))51 );5253 return decides ? "vouched" : "unknown";54};5556/**57 * Main moves only by a landing (spec D1): no push reaches a canonical ref.58 * A working fork takes pushes from its owner only, and a layer's repo takes59 * none here: its writers arrive with the visibility cartridge (W6).60 */61const directPush: Rule = (facts) =>62 PushTarget.$match(facts.target, {63 Canonical: () => Option.some(new DirectPush({ ref: facts.ref })),64 ClaimFork: () => Option.none(),65 Layer: () => Option.some(new DirectPush({ ref: facts.ref })),66 WorkingFork: ({ owner }) =>67 isPusher(facts, owner)68 ? Option.none()69 : Option.some(new DirectPush({ ref: facts.ref })),70 });7172/** A denounced person pushes nothing; an unvouched one only when the mode says so. */73const trust: Rule = (facts) =>74 Option.flatMap(handleOf(facts.pusher), (handle) => {75 const standing = standingOf(facts.policy, handle);7677 if (standing === "denounced") {78 return Option.some<Refusal>(new Denounced({}));79 }8081 return standing === "unknown" && facts.policy.vouch.mode !== "bansOnly"82 ? Option.some(new NotVouched({}))83 : Option.none();84 });8586/** The rules for a push to a claim's fork, in order. */87const claimFork = (88 facts: PushFacts,89 fork: Data.TaggedEnum.Value<PushTarget, "ClaimFork">90): Option.Option<Refusal> => {91 const open = Option.filter(92 facts.ask,93 (ask) =>94 ask.project === fork.project &&95 ask.id === fork.ask &&96 ask.state !== "closed"97 );9899 if (Option.isNone(open)) {100 return Option.some(new NoAsk({}));101 }102103 // The fork is named for its claimant, who must hold the ask's claim.104 const held = Option.filter(105 facts.claim,106 (claim) =>107 claim.ask === fork.ask &&108 claim.state !== "released" &&109 claim.state !== "answered" &&110 sameHandle(claim.claimant, fork.claimant) &&111 isPusher(facts, claim.claimant)112 );113114 if (Option.isNone(held)) {115 return Option.some(NotClaimed.of(fork.ask));116 }117118 if (held.value.state === "lapsed") {119 return Option.some(ClaimLapsed.of(fork.ask));120 }121122 // A landing may lower the cap after the pusher claimed.123 const cap = facts.policy.caps.claimsPerPerson;124125 return facts.claimsHeld > cap126 ? Option.some(new CapReached({ cap }))127 : Option.none();128};129130const claims: Rule = (facts) =>131 PushTarget.$is("ClaimFork")(facts.target)132 ? claimFork(facts, facts.target)133 : Option.none();134135const rules: readonly Rule[] = [directPush, trust, claims];136137/** Parse: the first rule the push breaks, or nothing. */138export const parse: Stage<never> = {139 accumulate: false,140 name: "parse",141 run: (facts) =>142 Effect.succeed(143 Option.toArray(Array.findFirst(rules, (rule) => rule(facts)))144 ),145};
added:packages/gate/src/stages/ratchet.ts+76 added
added:packages/gate/src/stages/shape.ts+225 added
1/**2 * Stage 1, shape: what the push's changes do, read from the change list and3 * the added lines alone. It accumulates, so one push hears about every4 * problem at once, in the order of the refusal union's Shape group.5 *6 * The stage's value is `scan` (lint keeps "shape" out of symbol names); its7 * `name` is the stage's, `shape`.8 */9import type { Ask } from "@repo/protocol/domain/ask";10import { CheckSpec } from "@repo/protocol/domain/check";11import { RepoPath } from "@repo/protocol/ids";12import {13 OutOfScope,14 PrivatePathInPublicTree,15 ReachedInternals,16 TouchedJudge,17 Weakened,18} from "@repo/protocol/refusal";19import type { Refusal } from "@repo/protocol/refusal";20import { Array, Effect, Option, Order } from "effect";2122import type { PushFacts } from "../facts.ts";23import { matchAny } from "../glob.ts";24import { findMarkers, markersOf } from "../markers.ts";25import type { Stage } from "../stage.ts";2627/** The one JSON pointer the gate is told about: whether the scripts changed. */28const SCRIPTS = "package.json#/scripts";2930/** The ask's own files: its file in the config folder, and its check's file. */31const ownFiles = (ask: Ask): ReadonlySet<string> =>32 new Set([33 ask.file,34 ...(CheckSpec.guards.RedThenGreen(ask.check) ? [ask.check.path] : []),35 ]);3637/** Each path once, in a fixed order, if there are any. */38const someOf = (39 paths: Iterable<RepoPath>40): Option.Option<Array.NonEmptyReadonlyArray<RepoPath>> => {41 const each = [...new Set(paths)].toSorted();4243 return Array.isReadonlyArrayNonEmpty(each)44 ? Option.some(each)45 : Option.none();46};4748/**49 * Whether a path judges the push. An answer may not touch its ask's own50 * files, which judge it; a decider opening the ask writes them.51 */52const judges = (facts: PushFacts) => (path: RepoPath) => {53 const own = Option.exists(facts.ask, (ask) => ownFiles(ask).has(path));5455 return facts.opensAsk && own56 ? false57 : own || matchAny(facts.policy.judge.paths, path);58};5960/**61 * Whether a path is the push's to change: inside the ask's territory, or one62 * of the ask's own files when a decider opens it. With no ask (a decider's63 * own landing) there is no territory to leave.64 */65const inScope = (facts: PushFacts) => (path: RepoPath) =>66 Option.match(facts.ask, {67 onNone: () => true,68 onSome: (ask) =>69 matchAny(ask.territory.paths, path) ||70 (facts.opensAsk && ownFiles(ask).has(path)),71 });7273/** Changed paths outside the territory. A judged path is TouchedJudge's to name. */74const outOfScope = (facts: PushFacts): readonly Refusal[] => {75 const judged = judges(facts);76 const allowed = inScope(facts);7778 return Option.match(79 someOf(80 facts.changes81 .map((change) => change.path)82 .filter((path) => !allowed(path) && !judged(path))83 ),84 {85 onNone: () => [],86 onSome: (paths) => [new OutOfScope({ paths })],87 }88 );89};9091/** Changed paths in the judge closure, and the scripts pointer when it moved. */92const touchedJudge = (facts: PushFacts): readonly Refusal[] => {93 const scripts =94 facts.scriptsChanged && facts.policy.judge.pointers.includes(SCRIPTS)95 ? [RepoPath.make(SCRIPTS)]96 : [];9798 return Option.match(99 someOf([100 ...facts.changes.map((change) => change.path).filter(judges(facts)),101 ...scripts,102 ]),103 {104 onNone: () => [],105 onSome: (paths) => [new TouchedJudge({ paths })],106 }107 );108};109110/** Every marker added with no reason; a reasoned one is the ratchet stage's. */111const weakened = (facts: PushFacts): readonly Refusal[] =>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 : []116 );117118/** Added or changed paths a layer holds: nothing from a layer enters a public tree. */119const privatePaths = (facts: PushFacts): readonly Refusal[] =>120 Option.match(121 someOf(122 facts.changes.flatMap((change) =>123 change.status !== "deleted" && facts.layerPaths.has(change.path)124 ? [change.path]125 : []126 )127 ),128 {129 onNone: () => [],130 onSome: (paths) => [new PrivatePathInPublicTree({ paths })],131 }132 );133134// 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("…")`.137const 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];142143const specifierIn = (text: string) =>144 Array.findFirst(SPECIFIERS, (pattern) =>145 Option.fromNullishOr(pattern.exec(text)?.groups?.specifier)146 );147148/** `from`'s folder joined with a relative specifier, `.` and `..` resolved. */149const resolve = (from: string, specifier: string) => {150 const parts = from.split("/").slice(0, -1);151152 for (const part of specifier.split("/")) {153 if (part === "..") {154 parts.pop();155 } else if (part !== "." && part !== "") {156 parts.push(part);157 }158 }159160 return parts.join("/");161};162163/** A module file's path with its extension and a trailing `/index` dropped. */164const bare = (path: string) =>165 path.replace(/\.[cm]?[jt]sx?$/u, "").replace(/\/index$/u, "");166167/**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.170 */171const 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 );179180/**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 */184const reachedInternals = (facts: PushFacts): readonly Refusal[] =>185 Option.match(facts.ask, {186 onNone: () => [],187 onSome: ({ territory }) =>188 [...facts.addedLines]189 .toSorted(([one], [other]) => Order.String(one, other))190 .filter(([path]) => matchAny(territory.paths, path))191 .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 })209 )210 ),211 });212213/** Stage 1: every problem the push's changes have, in the union's Shape order. */214export const scan: Stage<never> = {215 accumulate: true,216 name: "shape",217 run: (facts) =>218 Effect.succeed([219 ...outOfScope(facts),220 ...touchedJudge(facts),221 ...weakened(facts),222 ...privatePaths(facts),223 ...reachedInternals(facts),224 ]),225};
added:packages/gate/src/classify.ts+85 added
1/**2 * Classifying a failing lane (CAA §2.B): the gate never charges an answerer3 * for its own trouble, nor for a main that moved underneath them. Only a4 * lane that passes on main and fails on the merged tree, in a file the5 * answer changed or in none it can name, is the answer's failure.6 */7import type { LaneResult } from "@repo/protocol/domain/answer";8import type { CommitSha, LaneName, RepoPath } from "@repo/protocol/ids";9import {10 ChecksFailed,11 Flake,12 StaleBase,13 VerifierBlocked,14} from "@repo/protocol/refusal";15import { Option } from "effect";1617/** What the platform saw of one lane on main, on the merged tree and on a fresh run. */18export interface LaneEvidence {19 readonly lane: LaneName;20 readonly onMain: LaneResult["result"];21 readonly onMerged: LaneResult["result"];22 /** The lane's fresh run on the same merged tree, once one has run. */23 readonly rerun: Option.Option<LaneResult["result"]>;24 /** The files the failure points at, when the lane's output names any. */25 readonly failingPaths: readonly RepoPath[];26 readonly logRef: string;27 /** The command that reproduces the lane: a refusal's `next`. */28 readonly command: string;29 /** Whether this is the run block's `doctor`, which checks the checker itself. */30 readonly isDoctor: boolean;31}3233/** Whether a result is the platform's own trouble, not the code's: a flake, or a checker that never started. */34const isTrouble = (result: LaneResult["result"]) =>35 result === "flaked" || result === "blocked";3637/**38 * How a lane's failure counts, or `None` when the lane passed on the merged39 * tree. A lane red on main too is `VerifierBlocked`. A checker that never40 * started on a tree whose main passes earns one fresh run (`Flake`); an41 * identical second failure means it was never a flake, so it counts as the42 * answer's (CAA §2.B). A failure only outside the diff is `StaleBase`.43 */44export const classifyFailure = (45 evidence: LaneEvidence,46 changedPaths: ReadonlySet<RepoPath>,47 merge: { readonly base: CommitSha; readonly main: CommitSha }48): Option.Option<ChecksFailed | Flake | VerifierBlocked | StaleBase> => {49 if (evidence.isDoctor && evidence.onMain !== "passed") {50 return Option.some(new VerifierBlocked({}));51 }5253 if (evidence.onMerged === "passed") {54 return Option.none();55 }5657 // The result that stands: the fresh run's, once there is one.58 const result = Option.getOrElse(evidence.rerun, () => evidence.onMerged);5960 if (Option.isSome(evidence.rerun) && result === "passed") {61 return Option.some(new Flake({ lane: evidence.lane }));62 }6364 if (evidence.onMain !== "passed") {65 return Option.some(new VerifierBlocked({}));66 }6768 if (isTrouble(result) && Option.isNone(evidence.rerun)) {69 return Option.some(new Flake({ lane: evidence.lane }));70 }7172 const outsideOnly =73 evidence.failingPaths.length > 0 &&74 evidence.failingPaths.every((path) => !changedPaths.has(path));7576 return Option.some(77 outsideOnly78 ? new StaleBase({ base: merge.base, conflicts: [], main: merge.main })79 : new ChecksFailed({80 lane: evidence.lane,81 logRef: evidence.logRef,82 next: evidence.command,83 })84 );85};
added:packages/gate/src/facts.ts+95 added
1/**2 * What the gate knows about one push: the facts its stages decide over. The3 * gate never reads a repo or computes a diff; its callers (the project4 * service, the CLI's local check) gather these and hand them in.5 */6import type { Ask } from "@repo/protocol/domain/ask";7import type { ClaimView } from "@repo/protocol/domain/claim";8import type { RefNameText } from "@repo/protocol/domain/common";9import type { Policy } from "@repo/protocol/domain/policy";10import type {11 AskId,12 BlobSha,13 CommitSha,14 Handle,15 LandedSha,16 LayerName,17 ProjectName,18 RatchetName,19 RepoPath,20} from "@repo/protocol/ids";21import type { Principal } from "@repo/protocol/principal";22import { Data } from "effect";23import type { Option } from "effect";2425/** One path an answer changes, with its blob before and after. */26export interface Change {27 readonly path: RepoPath;28 readonly status: "added" | "modified" | "deleted";29 readonly before?: BlobSha;30 readonly after?: BlobSha;31}3233/** One line an answer adds to a file, by its 1-based number in the new file. */34export interface AddedLine {35 readonly line: number;36 readonly text: string;37}3839/** A ratchet's count on main and on the answer, and the territory it counts. */40export interface RatchetCount {41 readonly before: number;42 readonly after: number;43 readonly territory: string;44}4546/**47 * Where a push goes, read from the repo's name (spec §4.5): the canonical48 * repo `<project>`, a claim's fork `<project>--<ask>--<handle>`, a person's49 * working fork `<project>--me--<handle>`, or a layer's repo50 * `<project>--<layer>`.51 */52export type PushTarget = Data.TaggedEnum<{53 Canonical: { readonly project: ProjectName };54 ClaimFork: {55 readonly project: ProjectName;56 readonly ask: AskId;57 readonly claimant: Handle;58 };59 Layer: { readonly project: ProjectName; readonly layer: LayerName };60 WorkingFork: { readonly project: ProjectName; readonly owner: Handle };61}>;6263/** Constructors and matchers for `PushTarget`. */64export const PushTarget = Data.taggedEnum<PushTarget>();6566/** Everything the gate's stages decide one push over. */67export interface PushFacts {68 /** The policy at the landed SHA: the only place rules are read from. */69 readonly policy: Policy;70 /** The ask the push answers (or opens), if one is open. */71 readonly ask: Option.Option<Ask>;72 /** The claim on that ask, whoever holds it. */73 readonly claim: Option.Option<ClaimView>;74 readonly pusher: Principal;75 readonly target: PushTarget;76 readonly ref: RefNameText;77 readonly base: CommitSha;78 readonly head: CommitSha;79 readonly landed: LandedSha;80 readonly changes: readonly Change[];81 readonly addedLines: ReadonlyMap<RepoPath, readonly AddedLine[]>;82 /** Whether `package.json#/scripts` differs; the caller compares the two JSON pointers. */83 readonly scriptsChanged: boolean;84 /** Paths that belong to a layer, which no public tree may carry (W6; empty before). */85 readonly layerPaths: ReadonlySet<RepoPath>;86 /** Each ratchet's count on main and on the answer, after the cheap lane. */87 readonly ratchetCounts: ReadonlyMap<RatchetName, RatchetCount>;88 /** How many live claims the pusher holds, for `CapReached`. */89 readonly claimsHeld: number;90 /**91 * Whether the push opens `ask` (a decider's `openAsk`) rather than answers92 * it. Only then are the ask's own file and check file the push's to write.93 */94 readonly opensAsk: boolean;95}
added:packages/gate/src/gate.ts+42 added
added:packages/gate/src/glob.ts+77 added
added:packages/gate/src/markers.ts+95 added
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).5 */6import type { At } from "@repo/protocol/domain/common";7import type { Policy } from "@repo/protocol/domain/policy";8import { Option, Order } from "effect";910import type { PushFacts } from "./facts.ts";1112/** The markers every project starts with (spec §4.2); a project may add more. */13export 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",30];3132/** The defaults and the markers the project adds, each once. */33export const markersOf = (policy: Policy): readonly string[] => [34 ...new Set([...defaultMarkers, ...policy.weakening.markers]),35];3637/** One marker on one added line, with the reason written after it, if any. */38export interface MarkerHit {39 readonly marker: string;40 readonly at: At;41 readonly reason: Option.Option<string>;42}4344// The ` -- ` that starts a reason, as the debt ledger reads it.45const REASON_MARK = /\s--(?=\s|$)/u;4647// What closes a comment after its reason: `*/`, `-->`.48const CLOSER = /\s*(?:\*\/|-->)\s*$/u;4950/** The reason written after a marker on its line, if there is one. */51const reasonIn = (rest: string): Option.Option<string> => {52 const mark = REASON_MARK.exec(rest);5354 if (mark === null) {55 return Option.none();56 }5758 const reason = rest59 .slice(mark.index + mark[0].length)60 .replace(CLOSER, "")61 .trim();6263 return reason === "" ? Option.none() : Option.some(reason);64};6566/**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.70 */71export const findMarkers = (72 markers: readonly string[],73 added: PushFacts["addedLines"]74): readonly MarkerHit[] =>75 [...added]76 .toSorted(([one], [other]) => Order.String(one, other))77 .flatMap(([path, lines]) =>78 lines79 .toSorted((one, other) => one.line - other.line)80 .flatMap(({ line, text }) =>81 markers.flatMap((marker) => {82 const index = text.indexOf(marker);8384 return index === -185 ? []86 : [87 {88 at: { line, path },89 marker,90 reason: reasonIn(text.slice(index + marker.length)),91 },92 ];93 })94 )95 );
added:packages/gate/src/stage.ts+18 added
added:packages/gate/src/verdict.ts+58 added
added:packages/gate/test/classify.test.ts+139 added
1import { describe, expect, it } from "@effect/vitest";2import { LaneName, RepoPath } from "@repo/protocol/ids";3import {4 ChecksFailed,5 Flake,6 StaleBase,7 VerifierBlocked,8} from "@repo/protocol/refusal";9import type { Refusal } from "@repo/protocol/refusal";10import { Option } from "effect";1112import { classifyFailure } from "../src/classify.ts";13import type { LaneEvidence } from "../src/classify.ts";14import { base, main, wire } from "./facts.ts";1516const unit = LaneName.make("unit");1718const week = RepoPath.make("packages/parse/src/week.ts");1920const pad = RepoPath.make("packages/format/src/pad.ts");2122/** The answer changed `week.ts` only. */23const changed: ReadonlySet<RepoPath> = new Set([week]);2425/** The unit lane, green on main and red on the merged tree in `week.ts`. */26const red: LaneEvidence = {27 command: "bun run test",28 failingPaths: [week],29 isDoctor: false,30 lane: unit,31 logRef: "logs/datekit/unit-2222222",32 onMain: "passed",33 onMerged: "failed",34 rerun: Option.none(),35};3637// The CAA §2.B table: the platform never charges the answerer for its own38// trouble, nor for a main that moved underneath them.39const rows: readonly {40 readonly name: string;41 readonly evidence: LaneEvidence;42 readonly refusal: Option.Option<Refusal>;43}[] = [44 {45 evidence: red,46 name: "passes on main, fails on merged inside the diff",47 refusal: Option.some(48 new ChecksFailed({49 lane: unit,50 logRef: "logs/datekit/unit-2222222",51 next: "bun run test",52 })53 ),54 },55 {56 evidence: { ...red, rerun: Option.some("failed") },57 name: "fails again the same way on a fresh run",58 refusal: Option.some(59 new ChecksFailed({60 lane: unit,61 logRef: "logs/datekit/unit-2222222",62 next: "bun run test",63 })64 ),65 },66 {67 evidence: { ...red, failingPaths: [] },68 name: "fails on merged with no file named",69 refusal: Option.some(70 new ChecksFailed({71 lane: unit,72 logRef: "logs/datekit/unit-2222222",73 next: "bun run test",74 })75 ),76 },77 {78 evidence: { ...red, rerun: Option.some("passed") },79 name: "fails, then passes on a fresh run of the same tree",80 refusal: Option.some(new Flake({ lane: unit })),81 },82 {83 evidence: { ...red, onMerged: "blocked" },84 name: "the checker could not start, which earns one fresh run",85 refusal: Option.some(new Flake({ lane: unit })),86 },87 {88 evidence: { ...red, onMerged: "blocked", rerun: Option.some("blocked") },89 name: "the checker could not start twice on a tree whose main passes",90 refusal: Option.some(91 new ChecksFailed({92 lane: unit,93 logRef: "logs/datekit/unit-2222222",94 next: "bun run test",95 })96 ),97 },98 {99 evidence: { ...red, onMain: "blocked", onMerged: "blocked" },100 name: "the checker could not start on main either, so no fresh run is spent",101 refusal: Option.some(new VerifierBlocked({})),102 },103 {104 evidence: {105 ...red,106 command: "bun run doctor",107 isDoctor: true,108 lane: LaneName.make("doctor"),109 onMain: "failed",110 },111 name: "the doctor lane fails on main",112 refusal: Option.some(new VerifierBlocked({})),113 },114 {115 evidence: { ...red, onMain: "failed" },116 name: "the lane fails on main too",117 refusal: Option.some(new VerifierBlocked({})),118 },119 {120 evidence: { ...red, failingPaths: [pad] },121 name: "fails on merged outside the diff, on a lane that passes on main",122 refusal: Option.some(new StaleBase({ base, conflicts: [], main })),123 },124 {125 evidence: { ...red, onMerged: "passed" },126 name: "passes on merged",127 refusal: Option.none(),128 },129];130131describe(classifyFailure, () => {132 it.each(rows)("$name", ({ evidence, refusal }) => {133 const found = classifyFailure(evidence, changed, { base, main });134135 expect(Option.map(found, (one) => wire([one]))).toStrictEqual(136 Option.map(refusal, (one) => wire([one]))137 );138 });139});
added:packages/gate/test/facts.ts+205 added
1/**2 * A push's facts for the gate's tests. One project, `datekit`, has two3 * modules, `parse` and `format`. Its ask `iso-week` has `parse` (and the root4 * manifest, for a dependency bump) as its territory, and bob holds a live5 * claim on it. By default bob pushes one change inside the territory to his6 * claim's fork, which every stage lets through; each test overrides only what7 * it is about: `testFacts({ changes: modified("docs/guide.md") })`.8 */9import { Ask } from "@repo/protocol/domain/ask";10import { CheckSpec } from "@repo/protocol/domain/check";11import { ClaimView } from "@repo/protocol/domain/claim";12import { RefNameText } from "@repo/protocol/domain/common";13import { Policy, PolicyInput } from "@repo/protocol/domain/policy";14import { CommitSha, Handle, LandedSha, RepoPath } from "@repo/protocol/ids";15import { Person } from "@repo/protocol/principal";16import { Refusal } from "@repo/protocol/refusal";17import { Option, Schema } from "effect";1819import { PushTarget } from "../src/facts.ts";20import type { AddedLine, Change, PushFacts } from "../src/facts.ts";2122// The gate takes no brand dependency (spec §4.1), so the tests read the23// config folder's name where protocol's policy defaults put the vouch file.24const { vouch } = Schema.decodeSync(25 Schema.Struct({ vouch: PolicyInput.fields.vouch })26)({});2728/** The config folder's name, as `Brand.configDir` spells it. */29export const configDir = vouch.file.slice(0, vouch.file.indexOf("/"));3031/** A decider for every path, who is in no line of the vouch file. */32export const alice = Handle.make("alice");3334/** Vouched for, and the holder of the claim on `iso-week`. */35export const bob = Handle.make("bob");3637/** Vouched for, with no claim. */38export const carol = Handle.make("carol");3940/** In no line of the vouch file. */41export const dana = Handle.make("dana");4243/** Denounced by the vouch file. */44export const mallory = Handle.make("mallory");4546export const base = CommitSha.make("1111111111111111111111111111111111111111");4748export const head = CommitSha.make("2222222222222222222222222222222222222222");4950export const main = CommitSha.make("3333333333333333333333333333333333333333");5152const landedSha = "4444444444444444444444444444444444444444";5354export const landed = LandedSha.make(CommitSha.make(landedSha));5556export const checkPath = "packages/parse/test/iso-week.test.ts";5758const parseModule = {59 module: "@datekit/parse",60 paths: ["packages/parse/**"],61 publicFiles: ["packages/parse/src/index.ts"],62} as const;6364const formatModule = {65 module: "@datekit/format",66 paths: ["packages/format/**"],67 publicFiles: ["packages/format/src/index.ts"],68} as const;6970const askWire = {71 askedBy: alice,72 blockedBy: [],73 brief: { want: "An ISO week date parses to the Monday of that week." },74 check: Schema.encodeSync(CheckSpec)(75 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(checkPath) })76 ),77 file: `${configDir}/asks/iso-week.ask.ts`,78 id: "iso-week",79 kind: "fix",80 openedAt: "2026-10-07T12:00:00.000Z",81 openedIn: landedSha,82 project: "datekit",83 state: "claimed",84 territory: { ...parseModule, paths: ["packages/parse/**", "/package.json"] },85} as const;8687/** The ask bob answers. */88export const ask = Schema.decodeSync(Ask)(askWire);8990/** Bob's live claim on `iso-week`. */91export const claim = Schema.decodeSync(ClaimView)({92 ask: askWire.id,93 base,94 checkCommand: `bun test ${checkPath}`,95 claimant: bob,96 fork: "datekit--iso-week--bob",97 lapsesAt: "2026-10-08T12:00:00.000Z",98 openedAt: "2026-10-07T12:00:00.000Z",99 project: askWire.project,100 remote: "https://platform.example/datekit--iso-week--bob.git",101 state: "live",102 warnsAt: "2026-10-07T14:00:00.000Z",103});104105/** The policy at the landed SHA. */106export const policy = Schema.decodeSync(Policy)({107 agents: "trailer",108 asks: [askWire],109 at: landedSha,110 budget: { decisionsPerDay: 5, expireDays: 14 },111 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },112 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },113 deciders: [{ handles: [alice], paths: "**" }],114 functions: { admit: false, opensAlone: false },115 judge: {116 paths: [117 `${configDir}/**`,118 ".github/workflows/**",119 "vitest.config.*",120 ".env.*",121 "!.env.*.local",122 ],123 pointers: ["package.json#/scripts"],124 },125 kinds: [126 {127 checkKind: "redThenGreen",128 claimers: "vouched",129 finish: "optional",130 name: "fix",131 oneWay: false,132 race: 1,133 requires: ["want", "check", "territory"],134 strength: "assertion",135 },136 ],137 modules: [parseModule, formatModule],138 ratchets: [],139 record: { countsAfterDays: 30, windowDays: 365 },140 run: {141 checks: { lint: "bun run lint", unit: "bun run test" },142 doctor: "bun run doctor",143 test: "bun test {path}",144 },145 source: "config",146 vouch: { file: vouch.file, mode: "forCode" },147 vouches: [148 { denounced: false, handle: bob },149 { denounced: false, handle: carol },150 { denounced: true, handle: mallory, note: "spam" },151 ],152 weakening: { markers: [] },153});154155/** The paths, each changed in place. */156export const modified = (...paths: readonly string[]): readonly Change[] =>157 paths.map((path) => ({ path: RepoPath.make(path), status: "modified" }));158159/** The lines a push adds, as `[path, line, text]`, grouped by path. */160export const addedLines = (161 ...lines: readonly (readonly [string, number, string])[]162): ReadonlyMap<RepoPath, readonly AddedLine[]> => {163 const byPath = new Map<RepoPath, AddedLine[]>();164165 for (const [path, line, text] of lines) {166 const key = RepoPath.make(path);167168 byPath.set(key, [...(byPath.get(key) ?? []), { line, text }]);169 }170171 return byPath;172};173174/** Bob's clean push to his claim's fork, with `overrides` applied. */175export const testFacts = (overrides: Partial<PushFacts> = {}): PushFacts => ({176 addedLines: addedLines([177 "packages/parse/src/week.ts",178 3,179 "export const isoWeek = 1;",180 ]),181 ask: Option.some(ask),182 base,183 changes: modified("packages/parse/src/week.ts"),184 claim: Option.some(claim),185 claimsHeld: 1,186 head,187 landed,188 layerPaths: new Set(),189 opensAsk: false,190 policy,191 pusher: Person.make({ handle: bob }),192 ratchetCounts: new Map(),193 ref: RefNameText.make("refs/heads/main"),194 scriptsChanged: false,195 target: PushTarget.ClaimFork({196 ask: ask.id,197 claimant: bob,198 project: ask.project,199 }),200 ...overrides,201});202203/** Refusals as they cross the wire, so a test compares their fields. */204export const wire = (refusals: readonly Refusal[]) =>205 refusals.map((refusal) => Schema.encodeSync(Refusal)(refusal));
added:packages/gate/test/gate.test.ts+94 added
1import { describe, expect, it } from "@effect/vitest";2import { RepoPath } from "@repo/protocol/ids";3import { NotClaimed, OutOfScope, TouchedJudge } from "@repo/protocol/refusal";4import type { Refusal } from "@repo/protocol/refusal";5import { Effect, Option } from "effect";67import { pushStages, runGate } from "../src/gate.ts";8import type { Stage } from "../src/stage.ts";9import { ask, modified, testFacts, wire } from "./facts.ts";1011/** What the gate answered, as it crosses the wire; `None` stays `None`. */12const wired = (answer: Option.Option<readonly Refusal[]>) =>13 Option.map(answer, wire);1415/** A stage that answers every push with `refusals`. */16const always = (17 accumulate: boolean,18 refusals: readonly Refusal[]19): Stage<never> => ({20 accumulate,21 name: "cheap",22 run: () => Effect.succeed(refusals),23});2425const outside = new OutOfScope({ paths: [RepoPath.make("docs/guide.md")] });2627const judged = new TouchedJudge({28 paths: [RepoPath.make(".github/workflows/ci.yml")],29});3031describe(runGate, () => {32 it.effect("stops after parse when parse refuses, so shape is not heard", () =>33 Effect.gen(function* () {34 const answer = yield* runGate(35 pushStages,36 testFacts({37 changes: modified("docs/guide.md"),38 claim: Option.none(),39 })40 );4142 expect(wired(answer)).toStrictEqual(43 Option.some(wire([NotClaimed.of(ask.id)]))44 );45 })46 );4748 it.effect(49 "returns every shape refusal when parse lets the push through",50 () =>51 Effect.gen(function* () {52 const answer = yield* runGate(53 pushStages,54 testFacts({55 changes: modified("docs/guide.md", ".github/workflows/ci.yml"),56 })57 );5859 expect(wired(answer)).toStrictEqual(60 Option.some(wire([outside, judged]))61 );62 })63 );6465 it.effect("returns None when every stage lets the push through", () =>66 Effect.gen(function* () {67 const answer = yield* runGate(pushStages, testFacts());6869 expect(answer).toStrictEqual(Option.none());70 })71 );7273 it.effect("stops a stage that does not accumulate at its first refusal", () =>74 Effect.gen(function* () {75 const answer = yield* runGate(76 [always(false, [outside, judged]), always(true, [judged])],77 testFacts()78 );7980 expect(wired(answer)).toStrictEqual(Option.some(wire([outside])));81 })82 );8384 it.effect("keeps every refusal of a stage that accumulates", () =>85 Effect.gen(function* () {86 const answer = yield* runGate(87 [always(true, []), always(true, [outside, judged])],88 testFacts()89 );9091 expect(wired(answer)).toStrictEqual(Option.some(wire([outside, judged])));92 })93 );94});
added:packages/gate/test/glob.test.ts+41 added
added:packages/gate/test/markers.test.ts+86 added
1import { describe, expect, it } from "@effect/vitest";2import { RepoPath } from "@repo/protocol/ids";3import { Option } from "effect";45import { defaultMarkers, findMarkers } from "../src/markers.ts";6import { addedLines } from "./facts.ts";78const at = (path: string, line: number) => ({9 line,10 path: RepoPath.make(path),11});1213// One added line per default marker in spec §4.2, as each tool writes it.14const lines: readonly (readonly [string, string])[] = [15 [".skip(", ' it.skip("parses week 53", () => {'],16 [".only(", ' describe.only("weeks", () => {'],17 [".todo(", ' it.todo("parses week 54");'],18 ["eslint-disable", "/* eslint-disable no-console */"],19 ["oxlint-disable", "// oxlint-disable-next-line no-explicit-any"],20 ["biome-ignore", "// biome-ignore lint/style: generated"],21 ["@ts-ignore", "// @ts-ignore"],22 ["@ts-expect-error", "// @ts-expect-error"],23 ["@ts-nocheck", "// @ts-nocheck"],24 ["@effect-diagnostics", "// @effect-diagnostics-next-line"],25 ["# noqa", "import os # noqa"],26 ["# type: ignore", "x = parse(y) # type: ignore"],27 ["#[allow(", "#[allow(dead_code)]"],28 ["//nolint", "func parse() { //nolint"],29 ["istanbul ignore", "/* istanbul ignore next */"],30 ["c8 ignore", "/* c8 ignore next */"],31];3233describe(findMarkers, () => {34 it.each(lines)("finds %s where a tool writes it", (marker, text) => {35 const hits = findMarkers(defaultMarkers, addedLines(["src/x.ts", 5, text]));3637 expect(hits.map((hit) => hit.marker)).toContain(marker);38 });3940 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."])44 );4546 expect(hits).toStrictEqual([47 { at: at("README.md", 40), marker: ".only(", reason: Option.none() },48 ]);49 });5051 it("reads the reason after ` -- `, without the comment's closer", () => {52 const hits = findMarkers(53 defaultMarkers,54 addedLines(55 ["src/a.ts", 1, "// oxlint-disable-next-line no-x -- reason given"],56 ["src/a.ts", 2, "/* eslint-disable no-y -- generated code */"],57 ["src/a.ts", 3, "// @ts-expect-error -- "],58 ["src/a.ts", 4, "it.skip(--flag)"]59 )60 );6162 expect(hits.map((hit) => hit.reason)).toStrictEqual([63 Option.some("reason given"),64 Option.some("generated code"),65 Option.none(),66 Option.none(),67 ]);68 });6970 it("orders what it finds by path, then line", () => {71 const hits = findMarkers(72 defaultMarkers,73 addedLines(74 ["src/b.ts", 9, "it.only("],75 ["src/b.ts", 3, "it.skip("],76 ["src/a.ts", 7, "// @ts-ignore"]77 )78 );7980 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),84 ]);85 });86});
added:packages/gate/test/parse.test.ts+207 added
1import { describe, expect, it } from "@effect/vitest";2import { RefNameText } from "@repo/protocol/domain/common";3import { LayerName, ProjectName } from "@repo/protocol/ids";4import { Anonymous, Person } from "@repo/protocol/principal";5import {6 CapReached,7 ClaimLapsed,8 Denounced,9 DirectPush,10 NoAsk,11 NotClaimed,12 NotVouched,13} from "@repo/protocol/refusal";14import type { Refusal } from "@repo/protocol/refusal";15import { Effect, Option } from "effect";1617import { PushTarget } from "../src/facts.ts";18import type { PushFacts } from "../src/facts.ts";19import { parse } from "../src/stages/parse.ts";20import {21 alice,22 ask,23 bob,24 carol,25 claim,26 dana,27 mallory,28 policy,29 testFacts,30 wire,31} from "./facts.ts";3233/** Dana's own live claim on the ask, and her push to its fork. */34const danasPush = (mode: PushFacts["policy"]["vouch"]["mode"]) =>35 testFacts({36 claim: Option.some({ ...claim, claimant: dana }),37 policy: { ...policy, vouch: { ...policy.vouch, mode } },38 pusher: Person.make({ handle: dana }),39 target: PushTarget.ClaimFork({40 ask: ask.id,41 claimant: dana,42 project: ask.project,43 }),44 });4546const main = RefNameText.make("refs/heads/main");4748// Each row is one push; parse answers with at most one refusal, the first49// rule the push breaks.50const rows: readonly {51 readonly name: string;52 readonly facts: PushFacts;53 readonly refusals: readonly Refusal[];54}[] = [55 {56 facts: testFacts(),57 name: "the claimant's push to their fork",58 refusals: [],59 },60 {61 facts: testFacts({ claim: Option.none() }),62 name: "a push to an ask no one has claimed",63 refusals: [NotClaimed.of(ask.id)],64 },65 {66 facts: testFacts({ claim: Option.some({ ...claim, state: "lapsed" }) }),67 name: "a push on a lapsed claim",68 refusals: [ClaimLapsed.of(ask.id)],69 },70 {71 facts: testFacts({ pusher: Person.make({ handle: carol }) }),72 name: "a push to someone else's claim fork",73 refusals: [NotClaimed.of(ask.id)],74 },75 {76 facts: testFacts({77 pusher: Person.make({ handle: carol }),78 target: PushTarget.ClaimFork({79 ask: ask.id,80 claimant: carol,81 project: ask.project,82 }),83 }),84 name: "a push to a fork in the pusher's name while another holds the claim",85 refusals: [NotClaimed.of(ask.id)],86 },87 {88 facts: testFacts({ claim: Option.some({ ...claim, state: "released" }) }),89 name: "a push on a released claim",90 refusals: [NotClaimed.of(ask.id)],91 },92 {93 facts: testFacts({ pusher: Anonymous.make({}) }),94 name: "a push with no person behind it",95 refusals: [NotClaimed.of(ask.id)],96 },97 {98 facts: testFacts({ pusher: Person.make({ handle: mallory }) }),99 name: "a push by a denounced person",100 refusals: [new Denounced({})],101 },102 {103 facts: danasPush("forCode"),104 name: "a push by an unvouched person when code needs a vouch",105 refusals: [new NotVouched({})],106 },107 {108 facts: danasPush("all"),109 name: "a push by an unvouched person when everything needs a vouch",110 refusals: [new NotVouched({})],111 },112 {113 facts: danasPush("bansOnly"),114 name: "a push by an unvouched person when only denouncements count",115 refusals: [],116 },117 {118 facts: testFacts({119 pusher: Person.make({ handle: mallory }),120 target: PushTarget.Canonical({ project: ask.project }),121 }),122 name: "a push to canonical main, even by a denounced person",123 refusals: [new DirectPush({ ref: main })],124 },125 {126 facts: testFacts({127 pusher: Person.make({ handle: alice }),128 ref: RefNameText.make("refs/heads/release"),129 target: PushTarget.Canonical({ project: ask.project }),130 }),131 name: "a decider's push to another canonical branch",132 refusals: [new DirectPush({ ref: "refs/heads/release" })],133 },134 {135 facts: testFacts({ ask: Option.none() }),136 name: "a push to a claim fork whose ask is not open",137 refusals: [new NoAsk({})],138 },139 {140 facts: testFacts({ ask: Option.some({ ...ask, state: "closed" }) }),141 name: "a push to a claim fork whose ask has closed",142 refusals: [new NoAsk({})],143 },144 {145 facts: testFacts({146 target: PushTarget.ClaimFork({147 ask: ask.id,148 claimant: bob,149 project: ProjectName.make("timekit"),150 }),151 }),152 name: "a push to another project's fork of an ask with the same name",153 refusals: [new NoAsk({})],154 },155 {156 facts: testFacts({ claimsHeld: 4 }),157 name: "a push by a claimant above the cap a landing lowered",158 refusals: [new CapReached({ cap: 3 })],159 },160 {161 facts: testFacts({ claimsHeld: 3 }),162 name: "a push by a claimant at the cap",163 refusals: [],164 },165 {166 facts: testFacts({167 ask: Option.none(),168 claim: Option.none(),169 pusher: Person.make({ handle: alice }),170 target: PushTarget.WorkingFork({ owner: alice, project: ask.project }),171 }),172 name: "a decider's push to their own working fork (deciders vouch, so need none)",173 refusals: [],174 },175 {176 facts: testFacts({177 ask: Option.none(),178 claim: Option.none(),179 target: PushTarget.WorkingFork({ owner: alice, project: ask.project }),180 }),181 name: "a push to another person's working fork",182 refusals: [new DirectPush({ ref: main })],183 },184 {185 facts: testFacts({186 ask: Option.none(),187 claim: Option.none(),188 pusher: Person.make({ handle: alice }),189 target: PushTarget.Layer({190 layer: LayerName.make("maintainers"),191 project: ask.project,192 }),193 }),194 name: "a push to a layer's repo, which W6 opens to its writers",195 refusals: [new DirectPush({ ref: main })],196 },197];198199describe("parse: who may push what", () => {200 it.effect.each(rows)("$name", ({ facts, refusals }) =>201 Effect.gen(function* () {202 const found = yield* parse.run(facts);203204 expect(wire(found)).toStrictEqual(wire(refusals));205 })206 );207});
added:packages/gate/test/ratchet.test.ts+101 added
1import { describe, expect, it } from "@effect/vitest";2import { DecisionSubject } from "@repo/protocol/domain/decision";3import { RatchetName } from "@repo/protocol/ids";4import { Weakened } from "@repo/protocol/refusal";5import { Option } from "effect";67import type { RatchetCount } from "../src/facts.ts";8import { ratchet } from "../src/stages/ratchet.ts";9import { addedLines, ask, testFacts, wire } from "./facts.ts";1011const escapes = RatchetName.make("escapes");1213const week = "packages/parse/src/week.ts";1415const pad = "packages/format/src/pad.ts";1617const reasoned = "// oxlint-disable-next-line no-x -- the parser's one cast";1819/** The escapes ratchet in the parse module, from `before` to `after`. */20const counted = (before: number, after: number) =>21 new Map<RatchetName, RatchetCount>([22 [escapes, { after, before, territory: "@datekit/parse" }],23 ]);2425describe("ratchet: a raised count is refused, or waits for a decider", () => {26 it("lets a push through that keeps or lowers every ratchet", () => {27 const { decisions, refusals } = ratchet(28 testFacts({29 addedLines: addedLines([week, 4, reasoned]),30 ratchetCounts: counted(3, 2),31 })32 );3334 expect([decisions, refusals]).toStrictEqual([[], []]);35 });3637 it("refuses a raise that no reasoned escape accounts for", () => {38 const { decisions, refusals } = ratchet(39 testFacts({ ratchetCounts: counted(3, 4) })40 );4142 expect(decisions).toStrictEqual([]);43 expect(wire(refusals)).toStrictEqual(44 wire([45 new Weakened({46 weakening: {47 after: 4,48 before: 3,49 ratchet: escapes,50 territory: "@datekit/parse",51 },52 }),53 ])54 );55 });5657 it("asks a decider about a raise that a reasoned escape in its territory makes", () => {58 const { decisions, refusals } = ratchet(59 testFacts({60 addedLines: addedLines([week, 4, reasoned]),61 ratchetCounts: counted(3, 4),62 })63 );6465 expect(refusals).toStrictEqual([]);66 expect(decisions).toStrictEqual([67 DecisionSubject.cases.RaiseRatchet.make({68 after: 4,69 ask: ask.id,70 before: 3,71 ratchet: escapes,72 territory: "@datekit/parse",73 }),74 ]);75 });7677 it("refuses a raise whose only reasoned escape is in another territory", () => {78 const { decisions, refusals } = ratchet(79 testFacts({80 addedLines: addedLines([pad, 4, reasoned]),81 ratchetCounts: counted(3, 4),82 })83 );8485 expect(decisions).toStrictEqual([]);86 expect(refusals.map((refusal) => refusal._tag)).toStrictEqual(["Weakened"]);87 });8889 it("refuses a raise on a decider's own landing, which has no ask to wait on", () => {90 const { decisions, refusals } = ratchet(91 testFacts({92 addedLines: addedLines([week, 4, reasoned]),93 ask: Option.none(),94 ratchetCounts: counted(3, 4),95 })96 );9798 expect(decisions).toStrictEqual([]);99 expect(refusals.map((refusal) => refusal._tag)).toStrictEqual(["Weakened"]);100 });101});
added:packages/gate/test/shape.test.ts+270 added
1import { describe, expect, it } from "@effect/vitest";2import { RepoPath } from "@repo/protocol/ids";3import {4 groups,5 OutOfScope,6 PrivatePathInPublicTree,7 ReachedInternals,8 TouchedJudge,9 Weakened,10} from "@repo/protocol/refusal";11import type { Refusal } from "@repo/protocol/refusal";12import { Array, Effect } from "effect";1314import type { PushFacts } from "../src/facts.ts";15import { scan } from "../src/stages/shape.ts";16import {17 addedLines,18 ask,19 checkPath,20 configDir,21 modified,22 policy,23 testFacts,24 wire,25} from "./facts.ts";2627const paths = (...each: readonly [string, ...string[]]) =>28 Array.map(each, (path) => RepoPath.make(path));2930const at = (path: string, line: number) => ({31 line,32 path: RepoPath.make(path),33});3435const week = "packages/parse/src/week.ts";3637const weekTest = "packages/parse/test/week.test.ts";3839/** A push that changes `files` and adds `lines` to them. */40const push = (41 files: readonly string[],42 lines: readonly (readonly [string, number, string])[] = [],43 overrides: Partial<PushFacts> = {}44) =>45 testFacts({46 addedLines: addedLines(...lines),47 changes: modified(...files),48 ...overrides,49 });5051/** One push with every problem shape knows. */52const everyProblem = push(53 [week, "docs/guide.md", ".github/workflows/ci.yml"],54 [55 [week, 1, 'export { pad } from "../../format/src/pad";'],56 [week, 4, "// @ts-ignore"],57 [week, 9, "it.only("],58 ],59 { layerPaths: new Set([RepoPath.make("docs/guide.md")]) }60);6162// Each row is one push. Shape reports every problem the push has, in the63// order of the refusal union's Shape group.64const rows: readonly {65 readonly name: string;66 readonly facts: PushFacts;67 readonly refusals: readonly Refusal[];68}[] = [69 { facts: push([week]), name: "a change inside the territory", refusals: [] },70 {71 facts: push([week, "packages/format/src/pad.ts", "docs/guide.md"]),72 name: "changes outside the territory, every one named",73 refusals: [74 new OutOfScope({75 paths: paths("docs/guide.md", "packages/format/src/pad.ts"),76 }),77 ],78 },79 {80 facts: push([".github/workflows/ci.yml"]),81 name: "a change to a CI workflow",82 refusals: [new TouchedJudge({ paths: paths(".github/workflows/ci.yml") })],83 },84 {85 facts: push([`${configDir}/project.ts`]),86 name: "a change to the config folder",87 refusals: [new TouchedJudge({ paths: paths(`${configDir}/project.ts`) })],88 },89 {90 facts: push(["vitest.config.ts", "packages/parse/vitest.config.ts"]),91 name: "a change to a test runner's config, at the root or in the territory",92 refusals: [93 new TouchedJudge({94 paths: paths("packages/parse/vitest.config.ts", "vitest.config.ts"),95 }),96 ],97 },98 {99 facts: push([".env.production", "apps/web/.env.production.local"]),100 name: "a committed env file is judged, and a local one is only out of scope",101 refusals: [102 new OutOfScope({ paths: paths("apps/web/.env.production.local") }),103 new TouchedJudge({ paths: paths(".env.production") }),104 ],105 },106 {107 facts: push(["packages/format/package.json"]),108 name: "the territory's root manifest is no other package's manifest",109 refusals: [110 new OutOfScope({ paths: paths("packages/format/package.json") }),111 ],112 },113 {114 facts: push(["package.json"]),115 name: "a change to package.json's dependencies only",116 refusals: [],117 },118 {119 facts: push(["package.json"], [], { scriptsChanged: true }),120 name: "a change to package.json's scripts",121 refusals: [new TouchedJudge({ paths: paths("package.json#/scripts") })],122 },123 {124 facts: push([checkPath]),125 name: "an answer's change to its own ask's check, inside the territory",126 refusals: [new TouchedJudge({ paths: paths(checkPath) })],127 },128 {129 facts: push([ask.file, checkPath], [], { opensAsk: true }),130 name: "a decider opening the ask writes its file and its check",131 refusals: [],132 },133 {134 facts: push([ask.file, `${configDir}/project.ts`], [], { opensAsk: true }),135 name: "opening an ask still may not touch the rest of the judge",136 refusals: [new TouchedJudge({ paths: paths(`${configDir}/project.ts`) })],137 },138 {139 facts: push(140 [weekTest],141 [[weekTest, 12, ' it.skip("parses week 53", () => {']]142 ),143 name: "an added .skip( with no reason",144 refusals: [145 new Weakened({ at: at(weekTest, 12), weakening: { marker: ".skip(" } }),146 ],147 },148 {149 facts: push(150 [week],151 [[week, 7, "// oxlint-disable-next-line no-x -- reason given"]]152 ),153 name: "an added escape with a reason (counted by the ratchet stage)",154 refusals: [],155 },156 {157 facts: push([weekTest], [[weekTest, 2, 'vi.mock("../src/week.ts");']], {158 policy: { ...policy, weakening: { markers: ["vi.mock("] } },159 }),160 name: "a marker the project adds to the defaults",161 refusals: [162 new Weakened({ at: at(weekTest, 2), weakening: { marker: "vi.mock(" } }),163 ],164 },165 {166 facts: push([week], [], {167 layerPaths: new Set([RepoPath.make(week)]),168 }),169 name: "a path a layer holds",170 refusals: [new PrivatePathInPublicTree({ paths: paths(week) })],171 },172 {173 facts: push(174 [week],175 [[week, 1, 'import { pad } from "../../format/src/pad.ts";']]176 ),177 name: "an import of another module's internal file",178 refusals: [179 new ReachedInternals({180 at: at(week, 1),181 from: RepoPath.make(week),182 to: "../../format/src/pad.ts",183 }),184 ],185 },186 {187 facts: push(188 [week],189 [190 [week, 1, "import {"],191 [week, 2, " pad,"],192 [week, 3, ' trim } from "../../format/src/pad.ts";'],193 ]194 ),195 name: "an import of another module's internal file, over several lines",196 refusals: [197 new ReachedInternals({198 at: at(week, 3),199 from: RepoPath.make(week),200 to: "../../format/src/pad.ts",201 }),202 ],203 },204 {205 facts: push(206 [week],207 [[week, 1, 'export * from "../../format/src/pad.ts";']]208 ),209 name: "a re-export of another module's internal file",210 refusals: [211 new ReachedInternals({212 at: at(week, 1),213 from: RepoPath.make(week),214 to: "../../format/src/pad.ts",215 }),216 ],217 },218 {219 facts: push(220 [week],221 [222 [week, 1, 'import { pad } from "../../format/src/index.ts";'],223 [week, 2, 'import { lex } from "./lex.ts";'],224 [week, 3, 'import { Array, Effect } from "effect";'],225 ]226 ),227 name: "imports of another module's public file, its own files and a package",228 refusals: [],229 },230 {231 facts: everyProblem,232 name: "every shape problem at once",233 refusals: [234 new OutOfScope({ paths: paths("docs/guide.md") }),235 new TouchedJudge({ paths: paths(".github/workflows/ci.yml") }),236 new Weakened({ at: at(week, 4), weakening: { marker: "@ts-ignore" } }),237 new Weakened({ at: at(week, 9), weakening: { marker: ".only(" } }),238 new PrivatePathInPublicTree({ paths: paths("docs/guide.md") }),239 new ReachedInternals({240 at: at(week, 1),241 from: RepoPath.make(week),242 to: "../../format/src/pad",243 }),244 ],245 },246];247248describe("shape: every problem a push's changes have", () => {249 it.effect.each(rows)("$name", ({ facts, refusals }) =>250 Effect.gen(function* () {251 const found = yield* scan.run(facts);252253 expect(wire(found)).toStrictEqual(wire(refusals));254 })255 );256257 it.effect("reports in the order of the union's Shape group", () =>258 Effect.gen(function* () {259 const found = yield* scan.run(everyProblem);260261 const order = groups262 .find((group) => group.name === "Shape")263 ?.members.map((member) => member.identifier);264265 expect([...new Set(found.map((refusal) => refusal._tag))]).toStrictEqual(266 order267 );268 })269 );270});
deleted:packages/gate/test/smoke.test.ts-10 removed
added:packages/gate/test/verdict.test.ts+80 added
1import { describe, expect, it } from "@effect/vitest";2import { Verdict } from "@repo/protocol/domain/answer";3import { Outcome } from "@repo/protocol/domain/outcome";4import { CheckVersion, LaneName, PatchId, TreeSha } from "@repo/protocol/ids";5import { DateTime, Option, Result, Schema } from "effect";67import { verdictOf } from "../src/verdict.ts";8import type { VerdictInput } from "../src/verdict.ts";9import { ask, base, head, testFacts } from "./facts.ts";1011const now = DateTime.makeUnsafe("2026-10-07T15:30:00.000Z");1213const input: VerdictInput = {14 checkVersion: CheckVersion.make("redThenGreen@0.0.0+0a1b2c3d4e5f6a7b"),15 facts: testFacts(),16 heldBack: [],17 lanes: [18 {19 command: "bun run test",20 durationMs: 4210,21 lane: LaneName.make("unit"),22 result: "passed",23 },24 ],25 now,26 outcome: Outcome.cases.Checking.make({ stage: "heldBack" }),27 patchId: PatchId.make("ab".repeat(32)),28 stage: "checks",29 tree: TreeSha.make("5555555555555555555555555555555555555555"),30};3132describe(verdictOf, () => {33 it("records the run on the answer, and decodes as a Verdict", () => {34 const verdict = verdictOf(input);3536 const wire = Result.map(verdict, Schema.encodeSync(Verdict));3738 expect(wire).toStrictEqual(39 Result.succeed({40 ask: "iso-week",41 at: "2026-10-07T15:30:00.000Z",42 base,43 checkVersion: "redThenGreen@0.0.0+0a1b2c3d4e5f6a7b",44 head,45 heldBack: [],46 lanes: [47 {48 command: "bun run test",49 durationMs: 4210,50 lane: "unit",51 result: "passed",52 },53 ],54 outcome: Schema.encodeSync(Outcome)(input.outcome),55 patchId: "ab".repeat(32),56 project: ask.project,57 stage: "checks",58 tree: "5555555555555555555555555555555555555555",59 verifier: "platform",60 })61 );62 expect(63 Result.map(wire, (each) => Schema.decodeSync(Verdict)(each))64 ).toStrictEqual(verdict);65 });6667 it("is NoAsk for a push that answers no ask", () => {68 const verdict = verdictOf({69 ...input,70 facts: testFacts({ ask: Option.none() }),71 });7273 expect(74 Result.match(verdict, {75 onFailure: (refusal) => refusal._tag,76 onSuccess: () => "a verdict",77 })78 ).toBe("NoAsk");79 });80});