Skip to content
Myr

Merge build/204-rules: the config folder at a landed SHA evaluates to the same Policy every time

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

authored by oscabriel · committed by oscabriel · parents 6f594b9, 8abb792 · Browse files · 24 files+2339 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

24 files+2339 added−10 removed

  • tests:+1047 added−10 removed
  • other:+1292 added−0 removed

24 files+2339 added−10 removed

added:packages/rules/src/rules-evaluator/bun-main.ts+90 added
1/**2 * The `/bun` adapter's main module, written beside the config modules with a3 * `job.json` that names them. It imports each module in turn, so it can tell4 * a module that would not load (a syntax error, an import that resolves to5 * nothing) from one whose code threw, hands their exports to `entry.ts`, and6 * prints one JSON document as its last line of stdout: `Collected`, `Called`7 * or `Failed`. Plain JavaScript as source text, like the prelude.8 *9 * `job.json`: `{entry, project?: {file, path}, asks: [{file, path}]}` for an10 * evaluation, plus `{rule, facts}` for a call; `file` is where a module was11 * written, `path` its path in the bundle.12 */13export const bunMain = `14import job from "./job.json" with { type: "json" };1516// Taken before any config code runs; the prelude sends its logging to stderr.17const out = process.stdout;1819const loadErrors = new Set(["BuildError", "BuildMessage", "ResolveError", "ResolveMessage", "SyntaxError"]);2021const isLoadError = (error) =>22 error instanceof AggregateError23 ? error.errors.length > 0 && error.errors.every(isLoadError)24 : loadErrors.has(error?.constructor?.name) || error instanceof SyntaxError;2526const describe = (error) =>27 error instanceof AggregateError28 ? error.errors.map(describe).join("; ")29 : error instanceof Error30 ? error.name + ": " + error.message31 : String(error);3233const failed = (where, error, reason) => ({34 _tag: "Failed",35 detail: where + ": " + describe(error),36 reason: reason ?? (isLoadError(error) ? "load" : "threw"),37});3839const load = async ({ file, path }) => {40 try {41 const module = await import(file);42 return { exported: { definition: module.default, path } };43 } catch (error) {44 return { failure: failed(path, error) };45 }46};4748const run = async () => {49 const entry = await import(job.entry);50 const project = job.project === undefined ? undefined : await load(job.project);5152 if (project?.failure !== undefined) {53 return project.failure;54 }5556 if (job.rule !== undefined) {57 try {58 const rule = entry.ruleOf(project?.exported.definition, job.rule);59 return { _tag: "Called", result: rule === undefined ? false : await rule(job.facts) };60 } catch (error) {61 return failed(job.rule, error, "threw");62 }63 }6465 const asks = [];6667 for (const ask of job.asks) {68 const loaded = await load(ask);6970 if (loaded.failure !== undefined) {71 return loaded.failure;72 }7374 asks.push(loaded.exported);75 }7677 try {78 return { _tag: "Collected", ...entry.collect(project?.exported, asks) };79 } catch (error) {80 return failed("the config folder's exports", error, "threw");81 }82};8384const result = JSON.stringify(await run()) + "\\n";8586await new Promise((resolve) => out.write(result, resolve));8788// Config code may leave a timer running; the one result is out.89process.exit(0);90`;
added:packages/rules/src/rules-evaluator/bun-prelude.ts+75 added
added:packages/rules/src/rules-evaluator/bun.ts+383 added
1import {2 Config,3 DateTime,4 Duration,5 Effect,6 FileSystem,7 Layer,8 Path,9 Schema,10 Stream,11} from "effect";12import type { Scope } from "effect";13import { ChildProcess, ChildProcessSpawner } from "effect/process";1415import {16 Collected,17 askModules,18 fromCollected,19 projectModule,20 statedWithoutCode,21} from "../config-folder.ts";22import { defaultPolicyInput } from "../defaults.ts";23import { Finishers, finishPolicy } from "../finish.ts";24import { RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";25import type { ConfigBundle } from "../rules-evaluator.ts";26import { bunMain } from "./bun-main.ts";27import { bunPrelude, clockVariable } from "./bun-prelude.ts";2829/** How the `/bun` adapter runs config code. */30export interface BunOptions {31 /** The bun binary; `bun` on the `PATH` by default. */32 readonly bun?: string;33 /** The module the sdk's imports point at; `@repo/sdk`'s entry by default. */34 readonly sdk?: string;35 /** How long config code may run; 5 seconds by default. */36 readonly timeout?: Duration.Input;37}3839// An import or export of the sdk by either of its names: the workspace one,40// and the published one, `<npm scope>/cli/rules`. The published name is41// matched by its shape, so `rules` never spells the brand; a config folder42// can import nothing else by a bare name anyway.43const SDK_IMPORT =44 /(?<lead>\bfrom\s*|\bimport\s*\(?\s*)(?<quote>["'])(?:@repo\/sdk|@[a-z0-9][\w.-]*\/cli\/rules)\k<quote>/gu;4546/** Points every import of the sdk, by either name, at the module `sdk`. */47const pointSdkAt = (source: string, sdk: string) =>48 source.replaceAll(SDK_IMPORT, `$<lead>${JSON.stringify(sdk)}`);4950/** What the subprocess prints as its last line. */51const Output = Schema.TaggedUnion({52 Called: { result: Schema.Json },53 Collected: Collected.fields,54 Failed: {55 detail: Schema.String,56 reason: Schema.Literals(["load", "threw"]),57 },58});5960type Output = typeof Output.Type;6162const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));6364/** A module the main imports: where it was written, and its path in the bundle. */65interface Written {66 readonly file: string;67 readonly path: string;68}6970/** What the main is asked to do: collect the folder's exports, or call a rule. */71interface Job {72 readonly asks: readonly Written[];73 readonly entry: string;74 readonly facts?: Schema.Json;75 readonly project?: Written;76 readonly rule?: string;77}7879/** The frozen clock and seed the prelude installs. */80interface Clock {81 readonly now: string;82 readonly seed: number;83}8485// Where the clock stands for a call: rule functions get time only through86// the facts they are called with.87const epoch: Clock = { now: "1970-01-01T00:00:00.000Z", seed: 0 };8889const loadFailed = (detail: string) =>90 new RulesFailed({ detail, reason: "load" });9192const surprised = (output: Output) =>93 new RulesFailed({94 detail: `the evaluator answered ${output._tag} to a job it was not given`,95 reason: "decode",96 });9798const fromFailed = ({ detail, reason }: Extract<Output, { _tag: "Failed" }>) =>99 new RulesFailed({ detail, reason });100101// The most of the subprocess's output the host keeps, from the end: config102// code may print without end, the result is stdout's last line, and what103// broke is told at the end of stderr.104const resultLimit = 16 * 1024 * 1024;105106const logLimit = 64 * 1024;107108/** The last `limit` characters a stream prints; the rest is read and dropped. */109const tailOf = <E>(bytes: Stream.Stream<Uint8Array, E>, limit: number) =>110 bytes.pipe(111 Stream.decodeText(),112 // Cut at twice the limit, so each character is copied only a few times.113 Stream.runFold(114 () => "",115 (kept: string, chunk: string) =>116 kept.length + chunk.length > 2 * limit117 ? `${kept}${chunk}`.slice(-limit)118 : `${kept}${chunk}`119 ),120 Effect.map((kept) => kept.slice(-limit))121 );122123/** The project module and ask files, as the main imports them. */124const modulesOf = (125 written: ReadonlyMap<string, string>,126 project: string | undefined,127 asks: readonly string[]128) => {129 const at = (file: string): Written => ({130 file: written.get(file) ?? file,131 path: file,132 });133134 const asksWritten = asks.map(at);135136 return project === undefined137 ? { asks: asksWritten }138 : { asks: asksWritten, project: at(project) };139};140141/**142 * `RulesEvaluator` over a `bun` subprocess. Each evaluation writes the143 * bundle's modules into a scoped temp directory (every import of the sdk144 * pointed at the sdk's own entry), runs `bun --preload <prelude> <main>`145 * with no inherited env beyond `PATH`, frozen time and randomness, and a146 * time limit, and reads one JSON document from its stdout. A bundle with no147 * project module and no asks reads `policy.json`, or gets the defaults,148 * without a subprocess. Then `finishPolicy`, with the caller's `Finishers`.149 */150export const rulesEvaluatorBun = (options: BunOptions = {}) =>151 Layer.effect(152 RulesEvaluator,153 Effect.gen(function* () {154 const fs = yield* FileSystem.FileSystem;155 const path = yield* Path.Path;156 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;157 const finishers = yield* Finishers;158 const bun = options.bun ?? "bun";159 const timeout = Duration.fromInputUnsafe(options.timeout ?? "5 seconds");160161 const searchPath = yield* Effect.orDie(162 Config.String("PATH").pipe(163 Config.withDefault("/usr/local/bin:/usr/bin:/bin")164 )165 );166167 const fromUrl = (url: string) =>168 Effect.orDie(path.fromFileUrl(new URL(url)));169170 const entry = yield* fromUrl(import.meta.resolve("../entry.ts"));171172 const sdk =173 options.sdk ?? (yield* fromUrl(import.meta.resolve("@repo/sdk")));174175 /** Writes `source` at `file` under `root`, refusing a path that leaves it. */176 const writeUnder = (root: string, file: string, source: string) => {177 const target = path.join(root, file);178 const relative = path.relative(root, target);179180 if (181 relative === "" ||182 relative.startsWith("..") ||183 path.isAbsolute(relative)184 ) {185 return Effect.fail(186 loadFailed(`${file}: not a path inside the config folder`)187 );188 }189190 return fs.makeDirectory(path.dirname(target), { recursive: true }).pipe(191 Effect.andThen(fs.writeFileString(target, source)),192 Effect.as(target),193 Effect.mapError((failure) =>194 loadFailed(`${file}: ${failure.message}`)195 )196 );197 };198199 /** Runs the main over the bundle for one job, and reads its result. */200 const run = (201 bundle: ConfigBundle,202 clock: Clock,203 job: (written: ReadonlyMap<string, string>) => Omit<Job, "entry">204 ): Effect.Effect<Output, RulesFailed, Scope.Scope> =>205 Effect.gen(function* () {206 const dir = yield* fs207 .makeTempDirectoryScoped({ prefix: "rules-" })208 .pipe(Effect.mapError((failure) => loadFailed(failure.message)));209210 const root = path.join(dir, "config");211 const written = new Map<string, string>();212213 for (const [file, source] of Object.entries(bundle.modules)) {214 written.set(215 file,216 yield* writeUnder(root, file, pointSdkAt(source, sdk))217 );218 }219220 const request: Job = { ...job(written), entry };221222 yield* writeUnder(dir, "job.json", JSON.stringify(request));223 yield* writeUnder(dir, "main.mjs", bunMain);224 yield* writeUnder(dir, "prelude.mjs", bunPrelude);225226 // Details name the bundle's paths, not where they were written.227 const clean = (detail: string) =>228 detail.replaceAll(`${root}/`, "").trim();229230 const command = ChildProcess.make(231 bun,232 [233 "--preload",234 path.join(dir, "prelude.mjs"),235 path.join(dir, "main.mjs"),236 ],237 {238 cwd: dir,239 env: { [clockVariable]: JSON.stringify(clock), PATH: searchPath },240 extendEnv: false,241 forceKillAfter: "1 second",242 }243 );244245 const child = yield* spawner246 .spawn(command)247 .pipe(248 Effect.mapError((failure) =>249 loadFailed(`could not start ${bun}: ${failure.message}`)250 )251 );252253 const [stdout, stderr, exitCode] = yield* Effect.all(254 [255 tailOf(child.stdout, resultLimit),256 tailOf(child.stderr, logLimit),257 child.exitCode,258 ],259 { concurrency: "unbounded" }260 ).pipe(Effect.mapError((failure) => loadFailed(failure.message)));261262 const last = stdout.trimEnd().split("\n").at(-1) ?? "";263264 if (exitCode !== 0 || last === "") {265 return yield* loadFailed(266 clean(stderr) ||267 `${bun} exited with ${exitCode} and printed no result`268 );269 }270271 const output = yield* decodeOutput(last).pipe(272 Effect.mapError(273 (failure) =>274 new RulesFailed({275 detail: `the evaluator's result: ${failure.message}`,276 reason: "decode",277 })278 )279 );280281 return Schema.is(Output.cases.Failed)(output)282 ? { ...output, detail: clean(output.detail) }283 : output;284 });285286 /** Runs a job in its own scope, within the time limit. */287 const limited = (288 effect: Effect.Effect<Output, RulesFailed, Scope.Scope>289 ) =>290 Effect.scoped(effect).pipe(291 Effect.timeoutOrElse({292 duration: timeout,293 orElse: () =>294 Effect.fail(295 new RulesFailed({296 detail: `the config folder ran past its ${Duration.format(timeout)} limit`,297 reason: "timeout",298 })299 ),300 })301 );302303 return RulesEvaluator.of({304 call: ({ facts, modules, rule }) => {305 const project = projectModule(modules);306307 if (project === undefined) {308 return Effect.succeed(false);309 }310311 return limited(312 run(modules, epoch, (written) => ({313 ...modulesOf(written, project, []),314 facts,315 rule,316 }))317 ).pipe(318 Effect.flatMap(319 Output.match({320 Called: ({ result }) =>321 Schema.decodeUnknownEffect(Schema.Boolean)(result).pipe(322 Effect.mapError(323 (failure) =>324 new RulesFailed({325 detail: `${project}: ${rule} gave ${failure.message}`,326 reason: "decode",327 })328 )329 ),330 Collected: (output) => Effect.fail(surprised(output)),331 Failed: (output) => Effect.fail(fromFailed(output)),332 })333 )334 );335 },336 evaluate: ({ at, facts, modules }) =>337 Effect.gen(function* () {338 const project = projectModule(modules);339 const asks = askModules(modules);340341 const clock: Clock = {342 now: DateTime.formatIso(facts.now),343 seed: facts.seed,344 };345346 // Without a project module, `policy.json` (or the defaults) is the347 // base the ask files join; with one, it is never read.348 const fallback =349 project === undefined350 ? yield* statedWithoutCode(modules)351 : defaultPolicyInput;352353 const policy =354 project === undefined && asks.length === 0355 ? fallback356 : yield* limited(357 run(modules, clock, (written) =>358 modulesOf(written, project, asks)359 )360 ).pipe(361 Effect.flatMap(362 Output.match({363 Called: (output) => Effect.fail(surprised(output)),364 Collected: (collected) =>365 fromCollected({366 collected,367 entry: project ?? modules.entry,368 fallback,369 initializer: facts.initializer,370 }),371 Failed: (output) => Effect.fail(fromFailed(output)),372 })373 )374 );375376 return yield* finishPolicy({ at, facts, finishers, policy });377 }),378 });379 })380 );381382/** The `/bun` adapter with its defaults: `bun` on the `PATH`, a 5-second limit. */383export const RulesEvaluatorBun = rulesEvaluatorBun();
added:packages/rules/src/rules-evaluator/json.ts+27 added
added:packages/rules/src/config-folder.ts+187 added
1import { AskInput, PolicyInput } from "@repo/protocol/domain/policy";2import { AskId, Handle, RepoPath } from "@repo/protocol/ids";3import { Effect, Option, Schema, Struct } from "effect";45import { defaultPolicyInput } from "./defaults.ts";6import { RulesFailed } from "./rules-evaluator.ts";7import type { ConfigBundle } from "./rules-evaluator.ts";89// An ask file: `<id>.ask.ts`, or the `.js` a bundler writes for it.10const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;1112// A module that runs: TypeScript or JavaScript, not JSON or a vouch file.13const SCRIPT = /\.[cm]?[jt]s$/u;1415/**16 * The config folder a bundle holds: its project module's folder. The bundle17 * names it, so `rules` never spells it (the brand lives in `packages/brand`,18 * which `rules` does not import).19 */20const folderOf = (bundle: ConfigBundle) =>21 bundle.entry.slice(0, bundle.entry.lastIndexOf("/") + 1);2223/** Where a committed policy stands in for the TypeScript (the fallback). */24export const policyJsonOf = (bundle: ConfigBundle) =>25 `${folderOf(bundle)}policy.json`;2627/** The bundle's project module, when it has one. */28export const projectModule = (bundle: ConfigBundle): string | undefined =>29 SCRIPT.test(bundle.entry) && Object.hasOwn(bundle.modules, bundle.entry)30 ? bundle.entry31 : undefined;3233/** The bundle's ask files, in path order so evaluation is the same every time. */34export const askModules = (bundle: ConfigBundle): readonly string[] => {35 const asks = `${folderOf(bundle)}asks/`;3637 return Object.keys(bundle.modules)38 .filter((path) => path.startsWith(asks) && ASK_FILE.test(path))39 .toSorted();40};4142/** A decode failure, named by the file it came from. */43export const failedAt =44 (where: string) =>45 (failure: Schema.SchemaError): RulesFailed =>46 new RulesFailed({47 detail: `${where}: ${failure.message}`,48 reason: "decode",49 });5051/** A module whose default export is missing (or `null`) states nothing. */52const noDefault = (path: string, what: string) =>53 new RulesFailed({54 detail: `${path}: its default export is not ${what}`,55 reason: "decode",56 });5758/**59 * The policy a committed `policy.json` states, when the bundle has one. It60 * carries its asks inline.61 */62const fromPolicyJson = (63 bundle: ConfigBundle64): Effect.Effect<Option.Option<PolicyInput>, RulesFailed> => {65 const path = policyJsonOf(bundle);66 const source = bundle.modules[path];6768 return source === undefined69 ? Effect.succeedNone70 : Schema.decodeEffect(Schema.fromJsonString(PolicyInput))(source).pipe(71 Effect.map((policy) =>72 Option.some({ ...policy, source: "config" as const })73 ),74 Effect.mapError(failedAt(path))75 );76};7778/**79 * The policy input a bundle states without running code: its `policy.json`,80 * or else the defaults. Its source is the config folder whenever there is81 * one, and the defaults only when there is none (spec §2.5), so every82 * adapter gives one bundle the same source.83 */84export const statedWithoutCode = (85 bundle: ConfigBundle86): Effect.Effect<PolicyInput, RulesFailed> =>87 Effect.map(88 fromPolicyJson(bundle),89 Option.getOrElse((): PolicyInput =>90 Object.keys(bundle.modules).length === 091 ? defaultPolicyInput92 : { ...defaultPolicyInput, source: "config" }93 )94 );9596/** What the config folder's modules exported, as data, read back from the sandbox. */97export const Collected = Schema.Struct({98 asks: Schema.Array(Schema.Struct({ ask: Schema.Json, path: Schema.String })),99 /** Absent when the bundle has no project module; `null` when it exports nothing. */100 project: Schema.optionalKey(Schema.Json),101});102103export type Collected = typeof Collected.Type;104105/**106 * An ask as its file states it: the path names it (its id and file), and107 * the asker and what blocks it may go unsaid.108 */109const AskFile = Schema.Struct({110 ...Struct.omit(AskInput.fields, ["askedBy", "blockedBy", "file", "id"]),111 askedBy: Schema.optionalKey(Handle),112 blockedBy: Schema.optionalKey(Schema.Array(AskId)),113});114115/** A project module's data: its asks are the ask files, its source the folder. */116const ProjectFile = PolicyInput.mapFields(Struct.omit(["asks", "source"]));117118/** An ask's id: its file's name less `.ask.ts`. */119const idOf = (path: string) =>120 path.slice(path.lastIndexOf("/") + 1).replace(ASK_FILE, "");121122/**123 * An ask file's data as an `AskInput`. The id and file come from the path,124 * whatever the data says; an ask that names no asker was asked by the125 * initializer, and one that names nothing blocking it is blocked by nothing.126 */127const askInputOf = (path: string, data: Schema.Json, initializer: Handle) =>128 Effect.gen(function* () {129 if (data === null) {130 return yield* noDefault(path, "an ask");131 }132133 const ask = yield* Schema.decodeUnknownEffect(AskFile)(data).pipe(134 Effect.mapError(failedAt(path))135 );136137 const id = yield* Schema.decodeEffect(AskId)(idOf(path)).pipe(138 Effect.mapError(failedAt(`${path}'s file name`))139 );140141 return {142 ...ask,143 askedBy: ask.askedBy ?? initializer,144 blockedBy: ask.blockedBy ?? [],145 file: RepoPath.make(path),146 id,147 } satisfies AskInput;148 });149150/**151 * The policy input the config folder's modules give: the project module's152 * data, or `fallback` when the folder has no project module (its153 * `policy.json`, or the defaults), with every ask file's ask after the154 * fallback's own. Its source is the config folder.155 */156export const fromCollected = (input: {157 readonly collected: Collected;158 readonly entry: string;159 readonly fallback: PolicyInput;160 readonly initializer: Handle;161}): Effect.Effect<PolicyInput, RulesFailed> =>162 Effect.gen(function* () {163 const { collected, entry, fallback, initializer } = input;164 const { project } = collected;165166 if (project === null) {167 return yield* noDefault(entry, "a project");168 }169170 const base =171 project === undefined172 ? fallback173 : {174 ...(yield* Schema.decodeUnknownEffect(ProjectFile)(project).pipe(175 Effect.mapError(failedAt(entry))176 )),177 asks: [],178 };179180 const asks: AskInput[] = [...base.asks];181182 for (const { ask, path } of collected.asks) {183 asks.push(yield* askInputOf(path, ask, initializer));184 }185186 return { ...base, asks, source: "config" };187 });
added:packages/rules/src/defaults.ts+61 added
added:packages/rules/src/entry.ts+75 added
added:packages/rules/src/finish.ts+212 added
1import type { Glob } from "@repo/protocol/domain/common";2import { FromCI, Policy } from "@repo/protocol/domain/policy";3import type { PolicyInput } from "@repo/protocol/domain/policy";4import { RunBlock } from "@repo/protocol/domain/run";5import type { LandedSha, RepoPath } from "@repo/protocol/ids";6import { Context, DateTime, Effect, Schema } from "effect";78import { failedAt } from "./config-folder.ts";9import { RulesFailed } from "./rules-evaluator.ts";10import type { EvaluationFacts } from "./rules-evaluator.ts";11import { parseVouchFile } from "./vouch.ts";1213/** A file the finishers read: a CI workflow, a hook config, a manifest. */14export interface FactFile {15 readonly content: string;16 readonly path: string;17}1819/**20 * What `rules` needs from `checks` without importing it: the judge closure21 * and the run-block finder. The caller passes `checks`' own functions; tests22 * pass fakes.23 */24export class Finishers extends Context.Service<25 Finishers,26 {27 readonly findRunBlock: (files: readonly FactFile[]) => {28 readonly run: Partial<typeof RunBlock.Encoded>;29 readonly sources: readonly string[];30 };31 readonly judgeClosure: (32 run: RunBlock,33 files: readonly FactFile[]34 ) => {35 readonly paths: readonly Glob[];36 readonly pointers: readonly string[];37 };38 }39>()("rules/Finishers") {}4041/**42 * Whether a vouch's platform prefix names the platform's own handles. People43 * sign in with GitHub, so `github:alice` is `alice`; a handle on another44 * platform names someone else, so it vouches for no one here.45 */46const isSignInPlatform = (platform: string) => platform === "github";4748/** The run block: the config folder's own, or the one the finder finds in CI. */49const runBlockOf = (50 run: PolicyInput["run"],51 facts: EvaluationFacts,52 finishers: Finishers["Service"]53): Effect.Effect<RunBlock, RulesFailed> => {54 if (!Schema.is(FromCI)(run)) {55 return Effect.succeed(run);56 }5758 const found = finishers.findRunBlock(facts.ci);5960 const where =61 found.sources.length === 062 ? "the project's files"63 : found.sources.join(", ");6465 return Schema.decodeUnknownEffect(RunBlock)({66 checks: {},67 ...found.run,68 }).pipe(Effect.mapError(failedAt(`the run block found in ${where}`)));69};7071/**72 * The vouch file's lines as the policy holds them. A line that names no73 * handle fails the policy, so a typo is reported rather than dropped.74 */75const vouchesOf = (text: string, file: RepoPath) => {76 const { invalid, vouches } = parseVouchFile(text);7778 if (invalid.length > 0) {79 const lines = invalid80 .map(({ line, text: bad }) => `line ${line} ("${bad}")`)81 .join(", ");8283 return Effect.fail(84 new RulesFailed({85 detail: `${file}: no handle on ${lines}`,86 reason: "decode",87 })88 );89 }9091 return Effect.succeed(92 vouches.flatMap(({ denounced, handle, note, platform }) => {93 if (platform !== undefined && !isSignInPlatform(platform)) {94 return [];95 }9697 return note === undefined98 ? [{ denounced, handle }]99 : [{ denounced, handle, note }];100 })101 );102};103104/** A workspace folder as a glob prefix: `./packages/x/` is `packages/x`. */105const folderOf = (dir: string) =>106 dir107 .replace(/^(?:\.\/)+/u, "")108 .replace(/\/+$/u, "")109 .replace(/^\.$/u, "");110111/**112 * The territories answers may change: one per workspace package, its paths113 * its folder, its public files its `exports`; `.` for a single-package repo.114 */115const territoriesOf = (116 workspaces: EvaluationFacts["workspaces"]117): (typeof Policy.Encoded)["modules"] =>118 workspaces.length === 0119 ? [{ module: ".", paths: ["**"] }]120 : workspaces.map(({ dir, exports, name }) => {121 const folder = folderOf(dir);122123 const paths: readonly [string] = [124 folder === "" ? "**" : `${folder}/**`,125 ];126127 return exports.length === 0128 ? { module: name, paths }129 : { module: name, paths, publicFiles: exports };130 });131132/** Fails when two asks share an id: an id names one ask, and one fork per claim. */133const distinctAsks = (asks: PolicyInput["asks"]) => {134 const seen = new Map<string, string>();135136 for (const { file, id } of asks) {137 const other = seen.get(id);138139 if (other !== undefined) {140 return Effect.fail(141 new RulesFailed({142 detail: `${file}: the ask ${id} is also declared in ${other}`,143 reason: "decode",144 })145 );146 }147148 seen.set(id, file);149 }150151 return Effect.void;152};153154/**155 * Turns what the config folder evaluated to into the project's `Policy` at156 * `at`, filling in what the platform knows from the facts: the run block157 * (`fromCI` resolved by the finder), the modules from the workspaces, the158 * judge closure, `owners` as the initializer (spec D20), and the vouch159 * file's lines. Each ask counts as open, opened at `facts.now` in `at`: the160 * Project DO overwrites `openedAt`, `openedIn` and `state` from its own rows.161 * The whole is decoded with `Policy`, so a value the finishers or facts got162 * wrong fails here as `RulesFailed`, not later.163 */164export const finishPolicy = (input: {165 readonly at: LandedSha;166 readonly facts: EvaluationFacts;167 readonly finishers: Finishers["Service"];168 readonly policy: PolicyInput;169}): Effect.Effect<Policy, RulesFailed> =>170 Effect.gen(function* () {171 const { at, facts, finishers, policy } = input;172 const run = yield* runBlockOf(policy.run, facts, finishers);173 const vouches = yield* vouchesOf(facts.vouchFile ?? "", policy.vouch.file);174 const judge = finishers.judgeClosure(run, facts.ci);175 const openedAt = DateTime.formatIso(facts.now);176177 yield* distinctAsks(policy.asks);178179 const candidate = {180 agents: policy.agents,181 asks: policy.asks.map((ask) => ({182 ...ask,183 openedAt,184 openedIn: at,185 project: facts.project,186 state: "open" as const,187 })),188 at,189 budget: policy.budget,190 caps: policy.caps,191 claims: policy.claims,192 deciders: policy.deciders.map(({ handles, paths }) => ({193 handles: handles === "owners" ? [facts.initializer] : handles,194 paths,195 })),196 functions: policy.functions,197 judge,198 kinds: policy.kinds,199 modules: territoriesOf(facts.workspaces),200 ratchets: policy.ratchets,201 record: policy.record,202 run,203 source: policy.source,204 vouch: policy.vouch,205 vouches,206 weakening: policy.weakening,207 } satisfies typeof Policy.Encoded;208209 return yield* Schema.decodeEffect(Policy)(candidate).pipe(210 Effect.mapError(failedAt(`the policy at ${at}`))211 );212 });
added:packages/rules/src/rules-evaluator.ts+102 added
1import type { Policy } from "@repo/protocol/domain/policy";2import type { LandedSha } from "@repo/protocol/ids";3import { Handle, ProjectName, RepoPath } from "@repo/protocol/ids";4import { Context, Schema } from "effect";5import type { Effect } from "effect";67/**8 * The config folder as it stood at one landed commit, ready to evaluate.9 * `modules` maps each file's repo path (`<folder>/project.ts`,10 * `<folder>/asks/<id>.ask.ts`, `<folder>/policy.json`) to its source. An11 * empty `modules` means the project has no config folder, so it runs on the12 * defaults.13 */14export const ConfigBundle = Schema.Struct({15 /**16 * The project module's path, `<folder>/project.ts`, whether or not the17 * folder has one: it names the folder the asks and `policy.json` sit in.18 */19 entry: Schema.NonEmptyString,20 modules: Schema.Record(Schema.String, Schema.String),21 /** The rules package version the folder was written against. */22 sdkVersion: Schema.NonEmptyString,23});2425export type ConfigBundle = typeof ConfigBundle.Type;2627/** One workspace package, as the repo's manifests declare it. */28const Workspace = Schema.Struct({29 /** Its folder, from the repo's root: `packages/parse`. */30 dir: Schema.String,31 /** The files its `exports` name, from the repo's root. */32 exports: Schema.Array(RepoPath),33 name: Schema.NonEmptyString,34});3536/**37 * Everything rule code may know about the project, injected by the platform:38 * rule code never reads the repo, the network or the clock. The same facts39 * always give the same policy (principle 8).40 */41export const EvaluationFacts = Schema.Struct({42 /**43 * The files `checks`' finder and judge closure read, where a `run: fromCI`44 * block is found: CI workflows, hook configs, `package.json`s and the45 * configs that decide what the checks do.46 */47 ci: Schema.Array(Schema.Struct({ content: Schema.String, path: RepoPath })),48 /** The person who made the project; `owners` resolves to them (spec D20). */49 initializer: Handle,50 /** The frozen clock rule code sees, and when its asks count as opened. */51 now: Schema.DateTimeUtcFromString,52 /** The project the asks belong to. */53 project: ProjectName,54 /** The frozen randomness rule code sees. */55 seed: Schema.Int,56 /** The vouch file's text, when the project has one. */57 vouchFile: Schema.optionalKey(Schema.String),58 workspaces: Schema.Array(Workspace),59});6061export type EvaluationFacts = typeof EvaluationFacts.Type;6263/**64 * Why the config folder gave no policy: it would not load, it ran past its65 * time limit, what it exported is not a policy, or its code threw. The66 * policy then stays on the previous landed commit.67 */68export class RulesFailed extends Schema.TaggedError<RulesFailed>()(69 "RulesFailed",70 {71 detail: Schema.String,72 reason: Schema.Literals(["load", "timeout", "decode", "threw"]),73 }74) {}7576/** The function-valued rules, called on demand rather than read as data. */77export const RuleName = Schema.Literals(["opensAlone", "admit"]);7879export type RuleName = typeof RuleName.Type;8081/**82 * Turns the config folder at a landed commit into its `Policy`, the same83 * one every time for the same facts, and calls its function-valued rules on84 * demand. Adapters: `/bun` (a subprocess with frozen time), `/json` (a85 * committed `policy.json`, or the defaults) and, in W3, `/worker`.86 */87export class RulesEvaluator extends Context.Service<88 RulesEvaluator,89 {90 readonly call: (input: {91 readonly at: LandedSha;92 readonly facts: Schema.Json;93 readonly modules: ConfigBundle;94 readonly rule: RuleName;95 }) => Effect.Effect<boolean, RulesFailed>;96 readonly evaluate: (input: {97 readonly at: LandedSha;98 readonly facts: EvaluationFacts;99 readonly modules: ConfigBundle;100 }) => Effect.Effect<Policy, RulesFailed>;101 }102>()("rules/RulesEvaluator") {}
added:packages/rules/src/vouch.ts+80 added
added:packages/rules/test/fixtures/cm/asks/iso-week.ask.ts+5 added
added:packages/rules/test/fixtures/cm/asks/iso-week.json+13 added
added:packages/rules/test/fixtures/cm/asks/leap-year.ask.ts+5 added
added:packages/rules/test/fixtures/cm/asks/leap-year.json+12 added
1{2 "brief": {3 "context": ["February 29 exists only in leap years"],4 "want": "Reject February 29 in a year that is not a leap year"5 },6 "check": {7 "_tag": "RedThenGreen",8 "path": "packages/parse/test/leap-year.repro.test.ts"9 },10 "kind": "fixBug",11 "territory": { "module": "@datekit/parse", "paths": ["packages/parse/**"] }12}
added:packages/rules/test/fixtures/cm/project.json+28 added
1{2 "agents": "trailer",3 "asks": [],4 "budget": { "decisionsPerDay": 5, "expireDays": 14 },5 "caps": { "claimsPerPerson": 3, "proposalsPerPerson": 2 },6 "deciders": [7 { "handles": ["priya"], "paths": "packages/parse/src/public/**" },8 { "handles": "owners", "paths": "**" }9 ],10 "functions": { "admit": false, "opensAlone": true },11 "kinds": [12 {13 "checkKind": "redThenGreen",14 "claimers": { "record": { "area": "packages/parse", "atLeast": 1 } },15 "finish": "optional",16 "name": "fixBug",17 "oneWay": false,18 "race": 1,19 "requires": ["want", "check"],20 "strength": "assertion"21 }22 ],23 "ratchets": [],24 "record": { "countsAfterDays": 30, "windowDays": 365 },25 "run": { "_tag": "FromCI" },26 "source": "config",27 "weakening": { "markers": [".skip(", ".only("] }28}
added:packages/rules/test/fixtures/cm/project.ts+19 added
1import data from "./project.json" with { type: "json" };23/**4 * The convex-merged design's example project (its §3), as the data the sdk's5 * builders encode it to (`project.json`): a `fixBug` kind with a6 * red-then-green check, deciders by glob with the owners for the rest, the7 * budget and caps, `Assisted-by` trailers, and the record window. The run8 * block is the one found in CI; claims and the vouch file keep their9 * defaults.10 *11 * The example's one function-valued rule rides beside the data, where JSON12 * leaves it out: a proposal opens alone for someone who has held three asks.13 */14const project = Object.defineProperty({ ...data }, "opensAlone", {15 enumerable: false,16 value: (facts: { readonly held: number }) => facts.held >= 3,17});1819export default project;
added:packages/rules/test/fixtures/json-only/policy.json+41 added
1{2 "agents": "none",3 "asks": [4 {5 "askedBy": "olivia",6 "blockedBy": [],7 "brief": { "want": "Format durations as ISO 8601" },8 "check": {9 "_tag": "RedThenGreen",10 "path": "test/duration.repro.test.ts"11 },12 "file": "policy.json",13 "id": "iso-duration",14 "kind": "fix",15 "territory": { "module": ".", "paths": ["**"] }16 }17 ],18 "budget": { "decisionsPerDay": 3, "expireDays": 7 },19 "deciders": [{ "handles": "owners", "paths": "**" }],20 "functions": { "admit": false, "opensAlone": false },21 "kinds": [22 {23 "checkKind": "redThenGreen",24 "claimers": "anyone",25 "finish": "never",26 "name": "fix",27 "oneWay": false,28 "race": 1,29 "requires": ["want", "check"],30 "strength": "assertion"31 }32 ],33 "ratchets": [],34 "run": {35 "checks": { "lint": "npm run lint" },36 "setup": "npm ci --ignore-scripts",37 "test": "npx vitest run {path}"38 },39 "source": "config",40 "weakening": { "markers": [".skip("] }41}
added:packages/rules/test/fixtures/sdk-stub.ts+5 added
1/**2 * Stands in for the sdk's entry in the specifier test: config code that3 * imports the sdk by either name must reach this one module.4 */5export const marker = "the sdk";
added:packages/rules/test/evaluate.test.ts+511 added
1import { NodeServices } from "@effect/platform-node";2import { assert, describe, expect, it } from "@effect/vitest";3import { CheckSpec } from "@repo/protocol/domain/check";4import { Policy } from "@repo/protocol/domain/policy";5import { RepoPath } from "@repo/protocol/ids";6import { Duration, Effect, Layer, Result, Schema } from "effect";78import { Finishers } from "../src/finish.ts";9import { RulesEvaluator } from "../src/rules-evaluator.ts";10import type { ConfigBundle } from "../src/rules-evaluator.ts";11import { RulesEvaluatorJson } from "../src/rules-evaluator/json.ts";12import {13 at,14 baseProject,15 bundleOf,16 bunEvaluator,17 configFolder,18 defaultVouchFile,19 facts,20 finishers,21 folder,22 now,23} from "./world.ts";2425/** A red-then-green check on one file, as `CheckSpec` encodes it. */26const redThenGreen = (path: string) =>27 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });2829/** What the platform fills in on every ask: when, where and whose. */30const opened = {31 openedAt: now,32 openedIn: at,33 project: "datekit",34 state: "open",35};3637/** What every policy in these tests derives from the shared facts. */38const fromFacts = {39 at,40 modules: [41 {42 module: "@datekit/parse",43 paths: ["packages/parse/**"],44 publicFiles: ["packages/parse/src/index.ts"],45 },46 { module: "@datekit/format", paths: ["packages/format/**"] },47 ],48 vouches: [49 { denounced: false, handle: "priya" },50 { denounced: true, handle: "mallory", note: "Spam" },51 ],52};5354/** The judge closure the fake finishers give for a run block's test command. */55const judgeFor = (test: string) => ({56 paths: [`${configFolder}/**`, ".github/workflows/ci.yml"],57 pointers: ["package.json#/scripts", `test:${test}`],58});5960/** The run block the fake finder finds in CI. */61const foundRun = { checks: { unit: "bun test" }, test: "bun test {path}" };6263const fixBug = {64 checkKind: "redThenGreen",65 claimers: { record: { area: "packages/parse", atLeast: 1 } },66 finish: "optional",67 name: "fixBug",68 oneWay: false,69 race: 1,70 requires: ["want", "check"],71 strength: "assertion",72};7374/** The convex-merged example's policy, as `Policy` encodes it. */75const exampleEncoded = {76 ...fromFacts,77 agents: "trailer",78 asks: [79 {80 ...opened,81 askedBy: "priya",82 blockedBy: [],83 brief: { want: "Parse ISO week dates such as 2026-W40-6" },84 check: redThenGreen("packages/parse/test/iso-week.repro.test.ts"),85 file: `${configFolder}/asks/iso-week.ask.ts`,86 id: "iso-week",87 kind: "fixBug",88 mentor: "priya",89 reserve: "newcomers",90 territory: { module: "@datekit/parse", paths: ["packages/parse/**"] },91 },92 {93 ...opened,94 askedBy: "olivia",95 blockedBy: [],96 brief: {97 context: ["February 29 exists only in leap years"],98 want: "Reject February 29 in a year that is not a leap year",99 },100 check: redThenGreen("packages/parse/test/leap-year.repro.test.ts"),101 file: `${configFolder}/asks/leap-year.ask.ts`,102 id: "leap-year",103 kind: "fixBug",104 territory: { module: "@datekit/parse", paths: ["packages/parse/**"] },105 },106 ],107 budget: { decisionsPerDay: 5, expireDays: 14 },108 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },109 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },110 deciders: [111 { handles: ["priya"], paths: "packages/parse/src/public/**" },112 { handles: ["olivia"], paths: "**" },113 ],114 functions: { admit: false, opensAlone: true },115 judge: judgeFor("bun test {path}"),116 kinds: [fixBug],117 ratchets: [],118 record: { countsAfterDays: 30, windowDays: 365 },119 run: foundRun,120 source: "config",121 vouch: { file: defaultVouchFile, mode: "forCode" },122 weakening: { markers: [".skip(", ".only("] },123};124125/** The policy a folder holding only `policy.json` states. */126const jsonEncoded = {127 ...fromFacts,128 agents: "none",129 asks: [130 {131 ...opened,132 askedBy: "olivia",133 blockedBy: [],134 brief: { want: "Format durations as ISO 8601" },135 check: redThenGreen("test/duration.repro.test.ts"),136 file: "policy.json",137 id: "iso-duration",138 kind: "fix",139 territory: { module: ".", paths: ["**"] },140 },141 ],142 budget: { decisionsPerDay: 3, expireDays: 7 },143 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },144 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },145 deciders: [{ handles: ["olivia"], paths: "**" }],146 functions: { admit: false, opensAlone: false },147 judge: judgeFor("npx vitest run {path}"),148 kinds: [149 {150 checkKind: "redThenGreen",151 claimers: "anyone",152 finish: "never",153 name: "fix",154 oneWay: false,155 race: 1,156 requires: ["want", "check"],157 strength: "assertion",158 },159 ],160 ratchets: [],161 record: { countsAfterDays: 30, windowDays: 365 },162 run: {163 checks: { lint: "npm run lint" },164 setup: "npm ci --ignore-scripts",165 test: "npx vitest run {path}",166 },167 source: "config",168 vouch: { file: defaultVouchFile, mode: "forCode" },169 weakening: { markers: [".skip("] },170};171172/**173 * The defaults (convex-merged design §3, "no folder means defaults"; the174 * weakening markers from spec §4.2), as `Policy` encodes them.175 */176const defaultsEncoded = {177 ...fromFacts,178 agents: "trailer",179 asks: [],180 budget: { decisionsPerDay: 5, expireDays: 14 },181 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },182 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },183 deciders: [{ handles: ["olivia"], paths: "**" }],184 functions: { admit: false, opensAlone: false },185 judge: judgeFor("bun test {path}"),186 kinds: [187 {188 checkKind: "redThenGreen",189 claimers: "vouched",190 finish: "optional",191 name: "fix",192 oneWay: false,193 race: 1,194 requires: ["want", "check"],195 strength: "assertion",196 },197 ],198 ratchets: [],199 record: { countsAfterDays: 30, windowDays: 365 },200 run: foundRun,201 source: "defaults",202 vouch: { file: defaultVouchFile, mode: "forCode" },203 weakening: {204 markers: [205 ".skip(",206 ".only(",207 ".todo(",208 "eslint-disable",209 "oxlint-disable",210 "biome-ignore",211 "@ts-ignore",212 "@ts-expect-error",213 "@ts-nocheck",214 // The Effect language service would read the whole word as a directive.215 ["@effect", "diagnostics"].join("-"),216 "# noqa",217 "# type: ignore",218 "#[allow(",219 "//nolint",220 "istanbul ignore",221 "c8 ignore",222 ],223 },224};225226/** Evaluates a bundle at `at` with the shared facts, and encodes the policy. */227const evaluated = (modules: ConfigBundle) =>228 Effect.gen(function* () {229 const evaluator = yield* RulesEvaluator;230 const policy = yield* evaluator.evaluate({ at, facts, modules });231232 return yield* Schema.encodeEffect(Policy)(policy);233 });234235/** Evaluates a bundle that must fail, and hands back its `RulesFailed`. */236const failed = (modules: ConfigBundle) =>237 Effect.gen(function* () {238 const evaluator = yield* RulesEvaluator;239240 const result = yield* Effect.result(241 evaluator.evaluate({ at, facts, modules })242 );243244 if (Result.isSuccess(result)) {245 return assert.fail("the config evaluated to a policy");246 }247248 return result.failure;249 });250251/** An ask file whose brief says what happens today, but not what is wanted. */252const noWant = `export default ${JSON.stringify({253 blockedBy: [],254 brief: { current: "Dates parse only in one format" },255 check: redThenGreen("test/formats.repro.test.ts"),256 kind: "fix",257 territory: { module: ".", paths: ["**"] },258})};\n`;259260describe("the /bun adapter", () => {261 it.live("evaluates the example's config folder to its policy", () =>262 Effect.gen(function* () {263 expect(yield* evaluated(yield* folder("cm"))).toStrictEqual(264 exampleEncoded265 );266 }).pipe(Effect.provide(bunEvaluator()))267 );268269 it.live("reads a folder that holds only policy.json", () =>270 Effect.gen(function* () {271 expect(yield* evaluated(yield* folder("json-only"))).toStrictEqual(272 jsonEncoded273 );274 }).pipe(Effect.provide(bunEvaluator()))275 );276277 it.live(278 "adds ask files to the policy.json that stands in for project.ts",279 () =>280 Effect.gen(function* () {281 const json = yield* folder("json-only");282 const example = yield* folder("cm");283284 const askFiles = Object.entries(example.modules).filter(([path]) =>285 path.startsWith(`${configFolder}/asks/`)286 );287288 const policy = yield* evaluated({289 ...json,290 modules: { ...json.modules, ...Object.fromEntries(askFiles) },291 });292293 expect(policy.asks.map(({ id }) => id)).toStrictEqual([294 "iso-duration",295 "iso-week",296 "leap-year",297 ]);298 expect(policy.run).toStrictEqual(jsonEncoded.run);299 }).pipe(Effect.provide(bunEvaluator()))300 );301302 it.live("gives the defaults to a project with no config folder", () =>303 Effect.gen(function* () {304 expect(yield* evaluated(bundleOf({}))).toStrictEqual(defaultsEncoded);305 }).pipe(Effect.provide(bunEvaluator()))306 );307308 it.live("fails to load a config with a syntax error", () =>309 Effect.gen(function* () {310 const failure = yield* failed(311 bundleOf({ "project.ts": "export default {\n" })312 );313314 expect(failure.reason).toBe("load");315 expect(failure.detail).toContain(`${configFolder}/project.ts`);316 }).pipe(Effect.provide(bunEvaluator()))317 );318319 it.live("names the ask file whose ask has no want", () =>320 Effect.gen(function* () {321 const failure = yield* failed(322 bundleOf({323 "asks/formats.ask.ts": noWant,324 "project.ts": yield* baseProject,325 })326 );327328 expect(failure.reason).toBe("decode");329 expect(failure.detail).toContain(`${configFolder}/asks/formats.ask.ts`);330 expect(failure.detail).toContain("want");331 }).pipe(Effect.provide(bunEvaluator()))332 );333334 it.live("stops a config that loops forever at its time limit", () =>335 Effect.gen(function* () {336 const [took, failure] = yield* Effect.timed(337 failed(bundleOf({ "project.ts": "for (;;) {}\nexport default {};\n" }))338 );339340 expect(failure.reason).toBe("timeout");341 expect(Duration.toMillis(took)).toBeLessThan(5000);342 }).pipe(Effect.provide(bunEvaluator({ timeout: "1 second" })))343 );344345 it.live("reports a config whose code throws", () =>346 Effect.gen(function* () {347 const failure = yield* failed(348 bundleOf({ "project.ts": 'throw new Error("no policy today");\n' })349 );350351 expect(failure.reason).toBe("threw");352 expect(failure.detail).toContain("no policy today");353 }).pipe(Effect.provide(bunEvaluator()))354 );355356 it.live("refuses a run block the finder finds without a test command", () =>357 Effect.gen(function* () {358 const failure = yield* failed(yield* folder("cm"));359360 expect(failure.reason).toBe("decode");361 expect(failure.detail).toContain("run block");362 expect(failure.detail).toContain(".github/workflows/ci.yml");363 }).pipe(364 Effect.provide(365 bunEvaluator(366 {},367 Finishers.of({368 ...finishers,369 findRunBlock: (files) => ({370 run: { checks: {} },371 sources: files.map(({ path }) => path),372 }),373 })374 )375 )376 )377 );378379 it.live("points both names of the sdk at the one sdk module", () =>380 Effect.gen(function* () {381 const base = yield* baseProject;382383 const project = [384 'import { marker } from "@repo/sdk";',385 'import { marker as same } from "@some-scope/cli/rules";',386 base.replace("export default ", "const base = "),387 "export default { ...base, weakening: { markers: [marker, same] } };",388 ].join("\n");389390 const policy = yield* evaluated(bundleOf({ "project.ts": project }));391392 expect(policy.weakening).toStrictEqual({393 markers: ["the sdk", "the sdk"],394 });395 }).pipe(396 Effect.provide(397 bunEvaluator({ sdk: `${import.meta.dirname}/fixtures/sdk-stub.ts` })398 )399 )400 );401402 it.live("runs config code with no env beyond PATH, and no fetch", () =>403 Effect.gen(function* () {404 const base = yield* baseProject;405406 const project = [407 base.replace("export default ", "const base = "),408 "const seen = [...Object.keys(process.env).toSorted(), typeof fetch];",409 "export default { ...base, weakening: { markers: seen } };",410 ].join("\n");411412 const policy = yield* evaluated(bundleOf({ "project.ts": project }));413414 expect(policy.weakening).toStrictEqual({415 markers: ["PATH", "undefined"],416 });417 }).pipe(Effect.provide(bunEvaluator()))418 );419420 it.live("keeps only the end of a config's endless output", () =>421 Effect.gen(function* () {422 const failure = yield* failed(423 bundleOf({424 "project.ts": [425 'const flood = "x".repeat(8 * 1024 * 1024) + "the end";',426 "await new Promise((done) => process.stderr.write(flood, done));",427 "process.exit(3);",428 ].join("\n"),429 })430 );431432 expect(failure.detail.length).toBeLessThanOrEqual(64 * 1024);433 expect(failure.detail).toMatch(/x+the end$/u);434 }).pipe(Effect.provide(bunEvaluator()))435 );436437 it.live("calls a function-valued rule with the facts it is given", () =>438 Effect.gen(function* () {439 const evaluator = yield* RulesEvaluator;440 const modules = yield* folder("cm");441442 const call = (rule: "admit" | "opensAlone", held: number) =>443 evaluator.call({ at, facts: { held }, modules, rule });444445 expect(yield* call("opensAlone", 3)).toBeTruthy();446 expect(yield* call("opensAlone", 1)).toBeFalsy();447 expect(yield* call("admit", 3)).toBeFalsy();448 }).pipe(Effect.provide(bunEvaluator()))449 );450});451452describe("the /json adapter", () => {453 const jsonEvaluator = RulesEvaluatorJson.pipe(454 Layer.provide(Layer.succeed(Finishers, finishers)),455 Layer.provideMerge(NodeServices.layer)456 );457458 it.live("reads the committed policy.json", () =>459 Effect.gen(function* () {460 expect(yield* evaluated(yield* folder("json-only"))).toStrictEqual(461 jsonEncoded462 );463 }).pipe(Effect.provide(jsonEvaluator))464 );465466 it.live(467 "gives the defaults, from the folder, when there is no policy.json",468 () =>469 Effect.gen(function* () {470 expect(yield* evaluated(yield* folder("cm"))).toStrictEqual({471 ...defaultsEncoded,472 source: "config",473 });474 }).pipe(Effect.provide(jsonEvaluator))475 );476477 it.live("gives the defaults to a project with no config folder", () =>478 Effect.gen(function* () {479 expect(yield* evaluated(bundleOf({}))).toStrictEqual(defaultsEncoded);480 }).pipe(Effect.provide(jsonEvaluator))481 );482483 it.live("agrees with /bun on a folder that holds no policy", () =>484 Effect.gen(function* () {485 const modules = bundleOf({ "vouched.td": "priya\n" });486 const fromJson = yield* evaluated(modules);487488 const fromBun = yield* evaluated(modules).pipe(489 Effect.provide(bunEvaluator())490 );491492 expect(fromJson).toStrictEqual({ ...defaultsEncoded, source: "config" });493 expect(fromBun).toStrictEqual(fromJson);494 }).pipe(Effect.provide(jsonEvaluator))495 );496497 it.live("has no function-valued rules to call", () =>498 Effect.gen(function* () {499 const evaluator = yield* RulesEvaluator;500501 const called = yield* evaluator.call({502 at,503 facts: { held: 3 },504 modules: yield* folder("cm"),505 rule: "opensAlone",506 });507508 expect(called).toBeFalsy();509 }).pipe(Effect.provide(jsonEvaluator))510 );511});
added:packages/rules/test/finish.test.ts+64 added
1import { describe, expect, it } from "@effect/vitest";2import { CheckSpec } from "@repo/protocol/domain/check";3import { AskInput } from "@repo/protocol/domain/policy";4import { RepoPath } from "@repo/protocol/ids";5import { Effect, Schema } from "effect";67import { defaultPolicyInput } from "../src/defaults.ts";8import { finishPolicy } from "../src/finish.ts";9import { at, facts, finishers } from "./world.ts";1011/** An ask with the given id, declared in `file`. */12const askIn = (id: string, file: string) =>13 Schema.decodeSync(AskInput)({14 askedBy: "olivia",15 blockedBy: [],16 brief: { want: "Parse dates" },17 check: CheckSpec.cases.RedThenGreen.make({18 path: RepoPath.make("test/dates.test.ts"),19 }),20 file,21 id,22 kind: "fix",23 territory: { module: ".", paths: ["**"] },24 });2526describe(finishPolicy, () => {27 it.effect("refuses a vouch file line that names no handle, by its line", () =>28 Effect.gen(function* () {29 const failure = yield* Effect.flip(30 finishPolicy({31 at,32 facts: { ...facts, vouchFile: "priya\n@bob\n" },33 finishers,34 policy: defaultPolicyInput,35 })36 );3738 expect(failure.reason).toBe("decode");39 expect(failure.detail).toContain('line 2 ("@bob")');40 })41 );4243 it.effect("refuses two asks that share an id", () =>44 Effect.gen(function* () {45 const failure = yield* Effect.flip(46 finishPolicy({47 at,48 facts,49 finishers,50 policy: {51 ...defaultPolicyInput,52 asks: [53 askIn("dates", "a/dates.ask.ts"),54 askIn("dates", "b/dates.ask.ts"),55 ],56 },57 })58 );5960 expect(failure.reason).toBe("decode");61 expect(failure.detail).toContain("a/dates.ask.ts");62 })63 );64});
added:packages/rules/test/replay.test.ts+128 added
1import { describe, expect, it } from "@effect/vitest";2import { Policy } from "@repo/protocol/domain/policy";3import { DateTime, Effect, Schema } from "effect";45import { RulesEvaluator } from "../src/rules-evaluator.ts";6import type { ConfigBundle, EvaluationFacts } from "../src/rules-evaluator.ts";7import {8 at,9 baseProject,10 bundleOf,11 bunEvaluator,12 facts,13 folder,14 now,15 nowMs,16} from "./world.ts";1718/** Evaluates a bundle with the given facts, and encodes the policy. */19const evaluated = (modules: ConfigBundle, with_: EvaluationFacts = facts) =>20 Effect.gen(function* () {21 const evaluator = yield* RulesEvaluator;22 const policy = yield* evaluator.evaluate({ at, facts: with_, modules });2324 return yield* Schema.encodeEffect(Policy)(policy);25 });2627/**28 * A config whose `project.ts` reads the clock and randomness while it loads,29 * and puts what it read into an ask's context: the wall clock, a dated30 * `new Date()`, the clock reached through a date's own constructor, a31 * `new Date(0)` that names its time, then `Math.random()`,32 * `crypto.getRandomValues()` and `crypto.randomUUID()`.33 */34const readsTheClock = Effect.map(baseProject, (base) =>35 bundleOf({36 "asks/stamp.ask.ts": [37 'import { stamp } from "../project.ts";',38 "export default {",39 " blockedBy: [],",40 ' brief: { context: stamp, want: "Show the clock config code sees" },',41 ' check: { _tag: "RedThenGreen", path: "test/stamp.repro.test.ts" },',42 ' kind: "fix",',43 ' territory: { module: ".", paths: ["**"] },',44 "};",45 ].join("\n"),46 "project.ts": [47 "export const stamp = [",48 " String(Date.now()),",49 " new Date().toISOString(),",50 " String(new Date().constructor.now()),",51 " new Date(0).toISOString(),",52 " String(Math.random()),",53 ' crypto.getRandomValues(new Uint32Array(2)).join(","),',54 " crypto.randomUUID(),",55 "];",56 base,57 ].join("\n"),58 })59);6061/** What the clock-reading config put into its ask's context. */62const stampOf = (policy: typeof Policy.Encoded) =>63 policy.asks[0]?.brief.context;6465describe("evaluating a config folder twice", () => {66 it.live("gives equal policies for equal facts", () =>67 Effect.gen(function* () {68 for (const modules of [yield* folder("cm"), yield* readsTheClock]) {69 const first = yield* evaluated(modules);70 const second = yield* evaluated(modules);7172 expect(second).toStrictEqual(first);73 }74 }).pipe(Effect.provide(bunEvaluator()))75 );7677 it.live("gives config code the facts' clock, not the wall clock", () =>78 Effect.gen(function* () {79 const modules = yield* readsTheClock;80 const first = stampOf(yield* evaluated(modules));8182 const later = stampOf(83 yield* evaluated(modules, {84 ...facts,85 now: DateTime.makeUnsafe("2027-01-01T00:00:00.000Z"),86 })87 );8889 expect(first?.slice(0, 3)).toStrictEqual([nowMs, now, nowMs]);9091 expect(later?.slice(0, 3)).toStrictEqual([92 "1798761600000",93 "2027-01-01T00:00:00.000Z",94 "1798761600000",95 ]);9697 // A date that names its own time is left alone.98 expect(first?.[3]).toBe("1970-01-01T00:00:00.000Z");99 }).pipe(Effect.provide(bunEvaluator()))100 );101102 it.live("gives config code randomness from the facts' seed", () =>103 Effect.gen(function* () {104 const modules = yield* readsTheClock;105106 // Math.random(), crypto.getRandomValues() and crypto.randomUUID().107 const randomWith = (seed: number) =>108 Effect.map(109 evaluated(modules, { ...facts, seed }),110 (policy) => stampOf(policy)?.slice(4) ?? []111 );112113 const first = yield* randomWith(7);114 const other = yield* randomWith(8);115116 // The same seed gives the same three values; another seed changes each.117 expect({118 again: yield* randomWith(7),119 changed: other.map((value, index) => value !== first[index]),120 }).toStrictEqual({ again: first, changed: [true, true, true] });121 expect(Number(first[0])).toBeGreaterThanOrEqual(0);122 expect(Number(first[0])).toBeLessThan(1);123 expect(first[2]).toMatch(124 /^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/u125 );126 }).pipe(Effect.provide(bunEvaluator()))127 );128});
deleted:packages/rules/test/smoke.test.ts-10 removed
1import { describe, expect, it } from "@effect/vitest";23import manifest from "../package.json" with { type: "json" };45// A skeleton's one test, so vitest finds a file; real tests replace it.6describe("the package", () => {7 it("is @repo/rules", () => {8 expect(manifest.name).toBe("@repo/rules");9 });10});
added:packages/rules/test/vouch.test.ts+76 added
1import { describe, expect, it } from "@effect/vitest";23import { parseVouchFile } from "../src/vouch.ts";45// A vouch file in Ghostty's VOUCHED.td format: its header comment, then one6// handle per line.7const vouchedFile = [8 "# The list of vouched (or actively denounced) users for this repository.",9 "#",10 "# Syntax:",11 "# - One handle per line (without @). Sorted alphabetically.",12 "",13 "00-kat",14 "alice",15 "github:carol",16 "-bob",17 "-github:mallory Refusing to follow the AI policy",18 "dave dave",19 "",20].join("\n");2122describe(parseVouchFile, () => {23 it("reads one handle per line, skipping comments and blank lines", () => {24 expect(parseVouchFile(vouchedFile)).toStrictEqual({25 invalid: [],26 vouches: [27 { denounced: false, handle: "00-kat" },28 { denounced: false, handle: "alice" },29 { denounced: false, handle: "carol", platform: "github" },30 { denounced: true, handle: "bob" },31 {32 denounced: true,33 handle: "mallory",34 note: "Refusing to follow the AI policy",35 platform: "github",36 },37 { denounced: false, handle: "dave", note: "dave" },38 ],39 });40 });4142 it("takes a leading + as an explicit vouch, with or without a space", () => {43 expect(parseVouchFile("+ erin\n+frank").vouches).toStrictEqual([44 { denounced: false, handle: "erin" },45 { denounced: false, handle: "frank" },46 ]);47 });4849 it("reports a line whose handle is not a handle, by its line number", () => {50 expect(parseVouchFile("alice\n@bob\n-\ngithub:\n\n-_x note")).toStrictEqual(51 {52 invalid: [53 { line: 2, text: "@bob" },54 { line: 3, text: "-" },55 { line: 4, text: "github:" },56 { line: 6, text: "-_x note" },57 ],58 vouches: [{ denounced: false, handle: "alice" }],59 }60 );61 });6263 it("reads Windows line endings and surrounding spaces", () => {64 expect(parseVouchFile(" alice \r\n-bob\r\n")).toStrictEqual({65 invalid: [],66 vouches: [67 { denounced: false, handle: "alice" },68 { denounced: true, handle: "bob" },69 ],70 });71 });7273 it("reads an empty file as no vouches", () => {74 expect(parseVouchFile("")).toStrictEqual({ invalid: [], vouches: [] });75 });76});
added:packages/rules/test/world.ts+140 added
1import { NodeServices } from "@effect/platform-node";2import { Glob } from "@repo/protocol/domain/common";3import { FromCI, PolicyInput } from "@repo/protocol/domain/policy";4import { LandedSha } from "@repo/protocol/ids";5import { Effect, FileSystem, Layer, Path, Schema } from "effect";67import { defaultPolicyInput } from "../src/defaults.ts";8import { Finishers } from "../src/finish.ts";9import { EvaluationFacts } from "../src/rules-evaluator.ts";10import type { ConfigBundle } from "../src/rules-evaluator.ts";11import { rulesEvaluatorBun } from "../src/rules-evaluator/bun.ts";12import type { BunOptions } from "../src/rules-evaluator/bun.ts";1314/**15 * The config folder these bundles hold. A bundle names its own folder (its16 * `entry` is the folder's `project.ts`), so any name serves; the real one17 * lives in `packages/brand`, which `rules` and its tests don't import.18 */19export const configFolder = ".cfg";2021/** The vouch file a policy that names none gets: `PolicyInput`'s default. */22export const defaultVouchFile = Schema.decodeSync(PolicyInput)({23 asks: [],24 deciders: [],25 functions: { admit: false, opensAlone: false },26 kinds: [],27 ratchets: [],28 run: FromCI.make({}),29 source: "defaults",30 weakening: { markers: [] },31}).vouch.file;3233/** The landed commit every test evaluates at. */34export const at = LandedSha.make("a".repeat(40));3536/** The frozen clock the facts carry, as text and in epoch milliseconds. */37export const now = "2026-10-07T12:00:00.000Z";3839export const nowMs = "1791374400000";4041/**42 * What the platform knows about datekit: two workspace packages, one CI43 * file, a vouch file with a vouch, a denouncement and a handle on another44 * platform, and its initializer.45 */46export const factsEncoded = {47 ci: [{ content: "steps: [bun test]", path: ".github/workflows/ci.yml" }],48 initializer: "olivia",49 now,50 project: "datekit",51 seed: 7,52 vouchFile: "# vouched\npriya\n-mallory Spam\ngitlab:eve\n",53 workspaces: [54 {55 dir: "packages/parse",56 exports: ["packages/parse/src/index.ts"],57 name: "@datekit/parse",58 },59 { dir: "./packages/format/", exports: [], name: "@datekit/format" },60 ],61} satisfies typeof EvaluationFacts.Encoded;6263export const facts = Schema.decodeSync(EvaluationFacts)(factsEncoded);6465/**66 * Fakes for `checks`' finder and judge closure: the finder finds one lane in67 * any CI, and the closure names the config folder, every CI file, and the68 * run block's test command it was handed.69 */70export const finishers = Finishers.of({71 findRunBlock: (files) => ({72 run: { checks: { unit: "bun test" }, test: "bun test {path}" },73 sources: files.map(({ path }) => path),74 }),75 judgeClosure: (run, files) => ({76 paths: [77 Glob.make(`${configFolder}/**`),78 ...files.map(({ path }) => Glob.make(path)),79 ],80 pointers: ["package.json#/scripts", `test:${run.test}`],81 }),82});8384/** The `/bun` adapter over Node, with the fake finishers. */85export const bunEvaluator = (86 options: BunOptions = {},87 finish: Finishers["Service"] = finishers88) =>89 rulesEvaluatorBun(options).pipe(90 Layer.provide(Layer.succeed(Finishers, finish)),91 Layer.provideMerge(NodeServices.layer)92 );9394/** A bundle of config-folder files, keyed by their path inside the folder. */95export const bundleOf = (files: Readonly<Record<string, string>>) =>96 ({97 entry: `${configFolder}/project.ts`,98 modules: Object.fromEntries(99 Object.entries(files).map(([file, source]) => [100 `${configFolder}/${file}`,101 source,102 ])103 ),104 sdkVersion: "0.0.0",105 }) satisfies ConfigBundle;106107/**108 * A fixture folder under `test/fixtures/`, read into the bundle the Lander109 * makes of a config folder. The folder has no config-folder segment on110 * disk; the bundle's keys get it.111 */112export const folder = (name: string) =>113 Effect.gen(function* () {114 const fs = yield* FileSystem.FileSystem;115 const path = yield* Path.Path;116117 const root = yield* path.fromFileUrl(118 new URL(`fixtures/${name}`, import.meta.url)119 );120121 const files: Record<string, string> = {};122123 for (const file of (yield* fs.readDirectory(root, {124 recursive: true,125 })).toSorted()) {126 const full = path.join(root, file);127128 if ((yield* fs.stat(full)).type === "File") {129 files[file] = yield* fs.readFileString(full);130 }131 }132133 return bundleOf(files);134 });135136/** A project module that exports the defaults as config: a base to vary. */137export const baseProject = Effect.map(138 Schema.encodeEffect(PolicyInput)({ ...defaultPolicyInput, source: "config" }),139 (encoded) => `export default ${JSON.stringify(encoded)};\n`140);