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
Provenance
- Commit
84a8001- Tree
c17e22d- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
6f594b9- Parent 2
8abb792
24 files changed+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+ */13+export const bunMain = `14+import job from "./job.json" with { type: "json" };15+16+// Taken before any config code runs; the prelude sends its logging to stderr.17+const out = process.stdout;18+19+const loadErrors = new Set(["BuildError", "BuildMessage", "ResolveError", "ResolveMessage", "SyntaxError"]);20+21+const isLoadError = (error) =>22+ error instanceof AggregateError23+ ? error.errors.length > 0 && error.errors.every(isLoadError)24+ : loadErrors.has(error?.constructor?.name) || error instanceof SyntaxError;25+26+const describe = (error) =>27+ error instanceof AggregateError28+ ? error.errors.map(describe).join("; ")29+ : error instanceof Error30+ ? error.name + ": " + error.message31+ : String(error);32+33+const failed = (where, error, reason) => ({34+ _tag: "Failed",35+ detail: where + ": " + describe(error),36+ reason: reason ?? (isLoadError(error) ? "load" : "threw"),37+});38+39+const 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+};47+48+const run = async () => {49+ const entry = await import(job.entry);50+ const project = job.project === undefined ? undefined : await load(job.project);51+52+ if (project?.failure !== undefined) {53+ return project.failure;54+ }55+56+ 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+ }64+65+ const asks = [];66+67+ for (const ask of job.asks) {68+ const loaded = await load(ask);69+70+ if (loaded.failure !== undefined) {71+ return loaded.failure;72+ }73+74+ asks.push(loaded.exported);75+ }76+77+ 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+};83+84+const result = JSON.stringify(await run()) + "\\n";85+86+await new Promise((resolve) => out.write(result, resolve));87+88+// Config code may leave a timer running; the one result is out.89+process.exit(0);90+`;added:packages/rules/src/rules-evaluator/bun-prelude.ts+75 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475/** * The env var through which the `/bun` adapter hands the prelude the frozen * clock and seed, as JSON `{"now": "<ISO time>", "seed": <int>}`. */export const clockVariable = "RULES_CLOCK";
/** * The preload the `/bun` adapter runs before any config code (principle 8): * `Date.now()`, `new Date()` with no argument, `Math.random()`, * `crypto.getRandomValues()`, `crypto.randomUUID()` and `performance.now()` * give values derived from the injected clock and seed, `fetch` is gone, and * config code's own logging goes to stderr so stdout carries only the * evaluator's one result. It is plain JavaScript written beside the modules: * source text here, not host code. W3's Worker prelude is its own module. */export const bunPrelude = `const clock = JSON.parse(process.env.${clockVariable} ?? "{}");delete process.env.${clockVariable};
const RealDate = Date;const frozen = RealDate.parse(clock.now ?? "1970-01-01T00:00:00.000Z");
// mulberry32: a small seeded generator, the same numbers for the same seed.let state = (clock.seed ?? 0) >>> 0;const next = () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296;};
function FrozenDate(...args) { if (new.target === undefined) { return new RealDate(frozen).toString(); } return Reflect.construct(RealDate, args.length === 0 ? [frozen] : args, new.target);}FrozenDate.prototype = RealDate.prototype;// A date's own constructor must not lead back to the wall clock.Object.defineProperty(RealDate.prototype, "constructor", { configurable: true, value: FrozenDate, writable: true,});FrozenDate.now = () => frozen;FrozenDate.parse = RealDate.parse;FrozenDate.UTC = RealDate.UTC;globalThis.Date = FrozenDate;
Math.random = next;
const fill = (array) => { const bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength); for (let index = 0; index < bytes.length; index += 1) { bytes[index] = Math.floor(next() * 256); } return array;};crypto.getRandomValues = fill;crypto.randomUUID = () => { const bytes = fill(new Uint8Array(16)); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join("-");};performance.now = () => 0;
delete globalThis.fetch;
for (const level of ["debug", "info", "log"]) { console[level] = (...values) => console.error(...values);}`;added:packages/rules/src/rules-evaluator/bun.ts+383 added
1+import {2+ Config,3+ DateTime,4+ Duration,5+ Effect,6+ FileSystem,7+ Layer,8+ Path,9+ Schema,10+ Stream,11+} from "effect";12+import type { Scope } from "effect";13+import { ChildProcess, ChildProcessSpawner } from "effect/process";14+15+import {16+ Collected,17+ askModules,18+ fromCollected,19+ projectModule,20+ statedWithoutCode,21+} from "../config-folder.ts";22+import { defaultPolicyInput } from "../defaults.ts";23+import { Finishers, finishPolicy } from "../finish.ts";24+import { RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";25+import type { ConfigBundle } from "../rules-evaluator.ts";26+import { bunMain } from "./bun-main.ts";27+import { bunPrelude, clockVariable } from "./bun-prelude.ts";28+29+/** How the `/bun` adapter runs config code. */30+export 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+}38+39+// 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.43+const SDK_IMPORT =44+ /(?<lead>\bfrom\s*|\bimport\s*\(?\s*)(?<quote>["'])(?:@repo\/sdk|@[a-z0-9][\w.-]*\/cli\/rules)\k<quote>/gu;45+46+/** Points every import of the sdk, by either name, at the module `sdk`. */47+const pointSdkAt = (source: string, sdk: string) =>48+ source.replaceAll(SDK_IMPORT, `$<lead>${JSON.stringify(sdk)}`);49+50+/** What the subprocess prints as its last line. */51+const 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+});59+60+type Output = typeof Output.Type;61+62+const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));63+64+/** A module the main imports: where it was written, and its path in the bundle. */65+interface Written {66+ readonly file: string;67+ readonly path: string;68+}69+70+/** What the main is asked to do: collect the folder's exports, or call a rule. */71+interface Job {72+ readonly asks: readonly Written[];73+ readonly entry: string;74+ readonly facts?: Schema.Json;75+ readonly project?: Written;76+ readonly rule?: string;77+}78+79+/** The frozen clock and seed the prelude installs. */80+interface Clock {81+ readonly now: string;82+ readonly seed: number;83+}84+85+// Where the clock stands for a call: rule functions get time only through86+// the facts they are called with.87+const epoch: Clock = { now: "1970-01-01T00:00:00.000Z", seed: 0 };88+89+const loadFailed = (detail: string) =>90+ new RulesFailed({ detail, reason: "load" });91+92+const surprised = (output: Output) =>93+ new RulesFailed({94+ detail: `the evaluator answered ${output._tag} to a job it was not given`,95+ reason: "decode",96+ });97+98+const fromFailed = ({ detail, reason }: Extract<Output, { _tag: "Failed" }>) =>99+ new RulesFailed({ detail, reason });100+101+// 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.104+const resultLimit = 16 * 1024 * 1024;105+106+const logLimit = 64 * 1024;107+108+/** The last `limit` characters a stream prints; the rest is read and dropped. */109+const 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+ );122+123+/** The project module and ask files, as the main imports them. */124+const 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+ });133+134+ const asksWritten = asks.map(at);135+136+ return project === undefined137+ ? { asks: asksWritten }138+ : { asks: asksWritten, project: at(project) };139+};140+141+/**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+ */150+export 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");160+161+ const searchPath = yield* Effect.orDie(162+ Config.String("PATH").pipe(163+ Config.withDefault("/usr/local/bin:/usr/bin:/bin")164+ )165+ );166+167+ const fromUrl = (url: string) =>168+ Effect.orDie(path.fromFileUrl(new URL(url)));169+170+ const entry = yield* fromUrl(import.meta.resolve("../entry.ts"));171+172+ const sdk =173+ options.sdk ?? (yield* fromUrl(import.meta.resolve("@repo/sdk")));174+175+ /** 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);179+180+ 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+ }189+190+ 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+ };198+199+ /** 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)));209+210+ const root = path.join(dir, "config");211+ const written = new Map<string, string>();212+213+ for (const [file, source] of Object.entries(bundle.modules)) {214+ written.set(215+ file,216+ yield* writeUnder(root, file, pointSdkAt(source, sdk))217+ );218+ }219+220+ const request: Job = { ...job(written), entry };221+222+ yield* writeUnder(dir, "job.json", JSON.stringify(request));223+ yield* writeUnder(dir, "main.mjs", bunMain);224+ yield* writeUnder(dir, "prelude.mjs", bunPrelude);225+226+ // Details name the bundle's paths, not where they were written.227+ const clean = (detail: string) =>228+ detail.replaceAll(`${root}/`, "").trim();229+230+ 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+ );244+245+ const child = yield* spawner246+ .spawn(command)247+ .pipe(248+ Effect.mapError((failure) =>249+ loadFailed(`could not start ${bun}: ${failure.message}`)250+ )251+ );252+253+ 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)));261+262+ const last = stdout.trimEnd().split("\n").at(-1) ?? "";263+264+ if (exitCode !== 0 || last === "") {265+ return yield* loadFailed(266+ clean(stderr) ||267+ `${bun} exited with ${exitCode} and printed no result`268+ );269+ }270+271+ 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+ );280+281+ return Schema.is(Output.cases.Failed)(output)282+ ? { ...output, detail: clean(output.detail) }283+ : output;284+ });285+286+ /** 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+ );302+303+ return RulesEvaluator.of({304+ call: ({ facts, modules, rule }) => {305+ const project = projectModule(modules);306+307+ if (project === undefined) {308+ return Effect.succeed(false);309+ }310+311+ 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);340+341+ const clock: Clock = {342+ now: DateTime.formatIso(facts.now),343+ seed: facts.seed,344+ };345+346+ // 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;352+353+ 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+ );375+376+ return yield* finishPolicy({ at, facts, finishers, policy });377+ }),378+ });379+ })380+ );381+382+/** The `/bun` adapter with its defaults: `bun` on the `PATH`, a 5-second limit. */383+export const RulesEvaluatorBun = rulesEvaluatorBun();added:packages/rules/src/rules-evaluator/json.ts+27 added
123456789101112131415161718192021222324252627import { Effect, Layer } from "effect";
import { statedWithoutCode } from "../config-folder.ts";import { Finishers, finishPolicy } from "../finish.ts";import { RulesEvaluator } from "../rules-evaluator.ts";
/** * `RulesEvaluator` over a committed `policy.json` (the fallback): the policy * it states, or the defaults when the folder has none. It runs no code, so * it has no function-valued rules: `call` is always `false`. */export const RulesEvaluatorJson = Layer.effect( RulesEvaluator, Effect.gen(function* () { const finishers = yield* Finishers;
return RulesEvaluator.of({ call: () => Effect.succeed(false), evaluate: ({ at, facts, modules }) => Effect.gen(function* () { const policy = yield* statedWithoutCode(modules);
return yield* finishPolicy({ at, facts, finishers, policy }); }), }); }));added:packages/rules/src/config-folder.ts+187 added
1+import { AskInput, PolicyInput } from "@repo/protocol/domain/policy";2+import { AskId, Handle, RepoPath } from "@repo/protocol/ids";3+import { Effect, Option, Schema, Struct } from "effect";4+5+import { defaultPolicyInput } from "./defaults.ts";6+import { RulesFailed } from "./rules-evaluator.ts";7+import type { ConfigBundle } from "./rules-evaluator.ts";8+9+// An ask file: `<id>.ask.ts`, or the `.js` a bundler writes for it.10+const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;11+12+// A module that runs: TypeScript or JavaScript, not JSON or a vouch file.13+const SCRIPT = /\.[cm]?[jt]s$/u;14+15+/**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+ */20+const folderOf = (bundle: ConfigBundle) =>21+ bundle.entry.slice(0, bundle.entry.lastIndexOf("/") + 1);22+23+/** Where a committed policy stands in for the TypeScript (the fallback). */24+export const policyJsonOf = (bundle: ConfigBundle) =>25+ `${folderOf(bundle)}policy.json`;26+27+/** The bundle's project module, when it has one. */28+export const projectModule = (bundle: ConfigBundle): string | undefined =>29+ SCRIPT.test(bundle.entry) && Object.hasOwn(bundle.modules, bundle.entry)30+ ? bundle.entry31+ : undefined;32+33+/** The bundle's ask files, in path order so evaluation is the same every time. */34+export const askModules = (bundle: ConfigBundle): readonly string[] => {35+ const asks = `${folderOf(bundle)}asks/`;36+37+ return Object.keys(bundle.modules)38+ .filter((path) => path.startsWith(asks) && ASK_FILE.test(path))39+ .toSorted();40+};41+42+/** A decode failure, named by the file it came from. */43+export const failedAt =44+ (where: string) =>45+ (failure: Schema.SchemaError): RulesFailed =>46+ new RulesFailed({47+ detail: `${where}: ${failure.message}`,48+ reason: "decode",49+ });50+51+/** A module whose default export is missing (or `null`) states nothing. */52+const noDefault = (path: string, what: string) =>53+ new RulesFailed({54+ detail: `${path}: its default export is not ${what}`,55+ reason: "decode",56+ });57+58+/**59+ * The policy a committed `policy.json` states, when the bundle has one. It60+ * carries its asks inline.61+ */62+const fromPolicyJson = (63+ bundle: ConfigBundle64+): Effect.Effect<Option.Option<PolicyInput>, RulesFailed> => {65+ const path = policyJsonOf(bundle);66+ const source = bundle.modules[path];67+68+ 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+};77+78+/**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+ */84+export 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+ );95+96+/** What the config folder's modules exported, as data, read back from the sandbox. */97+export 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+});102+103+export type Collected = typeof Collected.Type;104+105+/**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+ */109+const 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+});114+115+/** A project module's data: its asks are the ask files, its source the folder. */116+const ProjectFile = PolicyInput.mapFields(Struct.omit(["asks", "source"]));117+118+/** An ask's id: its file's name less `.ask.ts`. */119+const idOf = (path: string) =>120+ path.slice(path.lastIndexOf("/") + 1).replace(ASK_FILE, "");121+122+/**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+ */127+const askInputOf = (path: string, data: Schema.Json, initializer: Handle) =>128+ Effect.gen(function* () {129+ if (data === null) {130+ return yield* noDefault(path, "an ask");131+ }132+133+ const ask = yield* Schema.decodeUnknownEffect(AskFile)(data).pipe(134+ Effect.mapError(failedAt(path))135+ );136+137+ const id = yield* Schema.decodeEffect(AskId)(idOf(path)).pipe(138+ Effect.mapError(failedAt(`${path}'s file name`))139+ );140+141+ return {142+ ...ask,143+ askedBy: ask.askedBy ?? initializer,144+ blockedBy: ask.blockedBy ?? [],145+ file: RepoPath.make(path),146+ id,147+ } satisfies AskInput;148+ });149+150+/**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+ */156+export 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;165+166+ if (project === null) {167+ return yield* noDefault(entry, "a project");168+ }169+170+ const base =171+ project === undefined172+ ? fallback173+ : {174+ ...(yield* Schema.decodeUnknownEffect(ProjectFile)(project).pipe(175+ Effect.mapError(failedAt(entry))176+ )),177+ asks: [],178+ };179+180+ const asks: AskInput[] = [...base.asks];181+182+ for (const { ask, path } of collected.asks) {183+ asks.push(yield* askInputOf(path, ask, initializer));184+ }185+186+ return { ...base, asks, source: "config" };187+ });added:packages/rules/src/defaults.ts+61 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061import { FromCI, PolicyInput } from "@repo/protocol/domain/policy";import { Schema } from "effect";
// The Effect language service reads its directive's name anywhere in a// source, string literals included, so the marker is joined at run time.const effectDirective = ["@effect", "diagnostics"].join("-");
/** * The markers that disable a check when an answer adds them (spec §4.2 * `packages/gate`); a project may add its own. */const weakeningMarkers = [ ".skip(", ".only(", ".todo(", "eslint-disable", "oxlint-disable", "biome-ignore", "@ts-ignore", "@ts-expect-error", "@ts-nocheck", effectDirective, "# noqa", "# type: ignore", "#[allow(", "//nolint", "istanbul ignore", "c8 ignore",];
/** * The policy a project with no config folder runs on (convex-merged design * §3, "no folder means defaults"): one `fix` kind whose asks a vouched person * claims, the run block found in the project's CI, the initializer deciding * everything (spec D20), and the default weakening markers. The rest is * `PolicyInput`'s own defaults: five decisions a day that wait 14 days, two * proposals and three claims per person, a claim warned after 2 hours and * lapsed after 24, a vouch for code in the config folder's `vouched.td`, * `Assisted-by` trailers, and a record that counts after 30 days for a year. */export const defaultPolicyInput: PolicyInput = Schema.decodeSync(PolicyInput)({ asks: [], deciders: [{ handles: "owners", paths: "**" }], functions: { admit: false, opensAlone: false }, kinds: [ { checkKind: "redThenGreen", claimers: "vouched", finish: "optional", name: "fix", oneWay: false, race: 1, requires: ["want", "check"], strength: "assertion", }, ], ratchets: [], run: FromCI.make({}), source: "defaults", weakening: { markers: weakeningMarkers },});added:packages/rules/src/entry.ts+75 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475/** * The evaluator's side inside the sandbox (a `bun` subprocess here, a Dynamic * Worker in W3): it hands what the config folder's modules exported back as * data, which the sandbox's main sends as JSON, so functions and * non-enumerable properties drop out and the host decodes the rest; and it * finds a function-valued rule to call. It imports only `effect`, which the * sdk brings anyway, so a bundler can inline it beside the sdk. */import { Predicate } from "effect";import type { Schema } from "effect";
/** * What a config module's default export is: the sdk's definition, plain * data shaped as `PolicyInput` or `AskInput` once encoded. A function-valued * rule rides on the project's definition as an own property named after the * rule (`opensAlone`, `admit`) that JSON leaves out: the sdk makes it * non-enumerable, and `functions` in the data says it exists. */export type Definition = Schema.Json;
/** A function-valued rule: called with the facts its caller passes. */export type Rule = (facts: Schema.Json) => boolean | Promise<boolean>;
/** One module's default export, by the module's path in the bundle. */export interface Exported { readonly definition: Definition | undefined; readonly path: string;}
/** The modules' data, as the host reads it back (`Collected` there). */export interface CollectedData { readonly asks: readonly { readonly ask: Schema.Json; readonly path: string; }[]; readonly project?: Schema.Json;}
/** A module with no default export gives `null`, which the host refuses. */const dataOf = (definition: Definition | undefined): Schema.Json => definition ?? null;
/** Collects the project module's data (when the folder has one) and every ask's. */export const collect = ( project: Exported | undefined, asks: readonly Exported[]): CollectedData => { const collected = asks.map(({ definition, path }) => ({ ask: dataOf(definition), path, }));
return project === undefined ? { asks: collected } : { asks: collected, project: dataOf(project.definition) };};
const isRule = (value: unknown): value is Rule => Predicate.isFunction(value);
/** The project definition's function-valued rule, when it has one. */export const ruleOf = ( definition: Definition | undefined, rule: string): Rule | undefined => { if (definition === undefined || definition === null) { return undefined; }
const found: unknown = Object.getOwnPropertyDescriptor( definition, rule )?.value;
return isRule(found) ? found : undefined;};added:packages/rules/src/finish.ts+212 added
1+import type { Glob } from "@repo/protocol/domain/common";2+import { FromCI, Policy } from "@repo/protocol/domain/policy";3+import type { PolicyInput } from "@repo/protocol/domain/policy";4+import { RunBlock } from "@repo/protocol/domain/run";5+import type { LandedSha, RepoPath } from "@repo/protocol/ids";6+import { Context, DateTime, Effect, Schema } from "effect";7+8+import { failedAt } from "./config-folder.ts";9+import { RulesFailed } from "./rules-evaluator.ts";10+import type { EvaluationFacts } from "./rules-evaluator.ts";11+import { parseVouchFile } from "./vouch.ts";12+13+/** A file the finishers read: a CI workflow, a hook config, a manifest. */14+export interface FactFile {15+ readonly content: string;16+ readonly path: string;17+}18+19+/**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+ */24+export 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") {}40+41+/**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+ */46+const isSignInPlatform = (platform: string) => platform === "github";47+48+/** The run block: the config folder's own, or the one the finder finds in CI. */49+const 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+ }57+58+ const found = finishers.findRunBlock(facts.ci);59+60+ const where =61+ found.sources.length === 062+ ? "the project's files"63+ : found.sources.join(", ");64+65+ return Schema.decodeUnknownEffect(RunBlock)({66+ checks: {},67+ ...found.run,68+ }).pipe(Effect.mapError(failedAt(`the run block found in ${where}`)));69+};70+71+/**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+ */75+const vouchesOf = (text: string, file: RepoPath) => {76+ const { invalid, vouches } = parseVouchFile(text);77+78+ if (invalid.length > 0) {79+ const lines = invalid80+ .map(({ line, text: bad }) => `line ${line} ("${bad}")`)81+ .join(", ");82+83+ return Effect.fail(84+ new RulesFailed({85+ detail: `${file}: no handle on ${lines}`,86+ reason: "decode",87+ })88+ );89+ }90+91+ return Effect.succeed(92+ vouches.flatMap(({ denounced, handle, note, platform }) => {93+ if (platform !== undefined && !isSignInPlatform(platform)) {94+ return [];95+ }96+97+ return note === undefined98+ ? [{ denounced, handle }]99+ : [{ denounced, handle, note }];100+ })101+ );102+};103+104+/** A workspace folder as a glob prefix: `./packages/x/` is `packages/x`. */105+const folderOf = (dir: string) =>106+ dir107+ .replace(/^(?:\.\/)+/u, "")108+ .replace(/\/+$/u, "")109+ .replace(/^\.$/u, "");110+111+/**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+ */115+const 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);122+123+ const paths: readonly [string] = [124+ folder === "" ? "**" : `${folder}/**`,125+ ];126+127+ return exports.length === 0128+ ? { module: name, paths }129+ : { module: name, paths, publicFiles: exports };130+ });131+132+/** Fails when two asks share an id: an id names one ask, and one fork per claim. */133+const distinctAsks = (asks: PolicyInput["asks"]) => {134+ const seen = new Map<string, string>();135+136+ for (const { file, id } of asks) {137+ const other = seen.get(id);138+139+ 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+ }147+148+ seen.set(id, file);149+ }150+151+ return Effect.void;152+};153+154+/**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+ */164+export 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);176+177+ yield* distinctAsks(policy.asks);178+179+ 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;208+209+ 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
1+import type { Policy } from "@repo/protocol/domain/policy";2+import type { LandedSha } from "@repo/protocol/ids";3+import { Handle, ProjectName, RepoPath } from "@repo/protocol/ids";4+import { Context, Schema } from "effect";5+import type { Effect } from "effect";6+7+/**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+ */14+export 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+});24+25+export type ConfigBundle = typeof ConfigBundle.Type;26+27+/** One workspace package, as the repo's manifests declare it. */28+const 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+});35+36+/**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+ */41+export 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+});60+61+export type EvaluationFacts = typeof EvaluationFacts.Type;62+63+/**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+ */68+export class RulesFailed extends Schema.TaggedError<RulesFailed>()(69+ "RulesFailed",70+ {71+ detail: Schema.String,72+ reason: Schema.Literals(["load", "timeout", "decode", "threw"]),73+ }74+) {}75+76+/** The function-valued rules, called on demand rather than read as data. */77+export const RuleName = Schema.Literals(["opensAlone", "admit"]);78+79+export type RuleName = typeof RuleName.Type;80+81+/**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+ */87+export 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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import { Handle } from "@repo/protocol/ids";import { Schema } from "effect";
/** One line of a vouch file: a person vouched for, or denounced. */export interface Vouch { readonly denounced: boolean; readonly handle: Handle; readonly note?: string; /** The `platform:` prefix the line wrote, when it wrote one: `github`. */ readonly platform?: string;}
/** A line that names no valid handle, kept so it is reported, not dropped. */export interface InvalidVouchLine { readonly line: number; readonly text: string;}
/** A vouch file, read: its vouches and denouncements, and its bad lines. */export interface VouchFile { readonly invalid: readonly InvalidVouchLine[]; readonly vouches: readonly Vouch[];}
// `-` denounces and `+` vouches explicitly (a second sample's spelling); the// first word is the handle, with an optional `platform:` prefix; the rest of// the line is a note.const LINE = /^(?<sign>[+-]?)\s*(?:(?<platform>[a-z][a-z0-9-]*):)?(?<handle>\S+)(?:\s+(?<note>\S.*))?$/u;
const isHandle = Schema.is(Handle);
/** One non-blank, non-comment line, read; `undefined` when it names no handle. */const vouchOf = (text: string): Vouch | undefined => { const groups = LINE.exec(text)?.groups; const handle = groups?.handle;
if (groups === undefined || handle === undefined || !isHandle(handle)) { return undefined; }
const vouch: Vouch = { denounced: groups.sign === "-", handle };
const withNote: Vouch = groups.note === undefined ? vouch : { ...vouch, note: groups.note };
return groups.platform === undefined ? withNote : { ...withNote, platform: groups.platform };};
/** * Reads a vouch file in Ghostty's `VOUCHED.td` format: one handle per line * (without `@`), an optional `platform:` prefix (`github:alice`), `-handle` * to denounce, text after a space as a note, and `#` lines as comments. * Blank lines are skipped; a line whose handle fails `Handle` is reported * in `invalid` with its line number. */export const parseVouchFile = (text: string): VouchFile => { const vouches: Vouch[] = []; const invalid: InvalidVouchLine[] = [];
for (const [index, raw] of text.split(/\r?\n/u).entries()) { const line = raw.trim();
if (line === "" || line.startsWith("#")) { continue; }
const vouch = vouchOf(line);
if (vouch === undefined) { invalid.push({ line: index + 1, text: line }); } else { vouches.push(vouch); } }
return { invalid, vouches };};added:packages/rules/test/fixtures/cm/asks/iso-week.ask.ts+5 added
12345/** * The example's open ask, held for newcomers, as the sdk encodes it. Its id * and file come from its path in the config folder. */export { default } from "./iso-week.json" with { type: "json" };added:packages/rules/test/fixtures/cm/asks/iso-week.json+13 added
12345678910111213{ "askedBy": "priya", "blockedBy": [], "brief": { "want": "Parse ISO week dates such as 2026-W40-6" }, "check": { "_tag": "RedThenGreen", "path": "packages/parse/test/iso-week.repro.test.ts" }, "kind": "fixBug", "mentor": "priya", "reserve": "newcomers", "territory": { "module": "@datekit/parse", "paths": ["packages/parse/**"] }}added:packages/rules/test/fixtures/cm/asks/leap-year.ask.ts+5 added
12345/** * A second ask that names no asker, so the initializer asked it, and no * `blockedBy`, so nothing blocks it. */export { default } from "./leap-year.json" with { type: "json" };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
1+import data from "./project.json" with { type: "json" };2+3+/**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+ */14+const project = Object.defineProperty({ ...data }, "opensAlone", {15+ enumerable: false,16+ value: (facts: { readonly held: number }) => facts.held >= 3,17+});18+19+export 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+ */5+export const marker = "the sdk";added:packages/rules/test/evaluate.test.ts+511 added
1+import { NodeServices } from "@effect/platform-node";2+import { assert, describe, expect, it } from "@effect/vitest";3+import { CheckSpec } from "@repo/protocol/domain/check";4+import { Policy } from "@repo/protocol/domain/policy";5+import { RepoPath } from "@repo/protocol/ids";6+import { Duration, Effect, Layer, Result, Schema } from "effect";7+8+import { Finishers } from "../src/finish.ts";9+import { RulesEvaluator } from "../src/rules-evaluator.ts";10+import type { ConfigBundle } from "../src/rules-evaluator.ts";11+import { RulesEvaluatorJson } from "../src/rules-evaluator/json.ts";12+import {13+ at,14+ baseProject,15+ bundleOf,16+ bunEvaluator,17+ configFolder,18+ defaultVouchFile,19+ facts,20+ finishers,21+ folder,22+ now,23+} from "./world.ts";24+25+/** A red-then-green check on one file, as `CheckSpec` encodes it. */26+const redThenGreen = (path: string) =>27+ CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });28+29+/** What the platform fills in on every ask: when, where and whose. */30+const opened = {31+ openedAt: now,32+ openedIn: at,33+ project: "datekit",34+ state: "open",35+};36+37+/** What every policy in these tests derives from the shared facts. */38+const 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+};53+54+/** The judge closure the fake finishers give for a run block's test command. */55+const judgeFor = (test: string) => ({56+ paths: [`${configFolder}/**`, ".github/workflows/ci.yml"],57+ pointers: ["package.json#/scripts", `test:${test}`],58+});59+60+/** The run block the fake finder finds in CI. */61+const foundRun = { checks: { unit: "bun test" }, test: "bun test {path}" };62+63+const 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+};73+74+/** The convex-merged example's policy, as `Policy` encodes it. */75+const 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+};124+125+/** The policy a folder holding only `policy.json` states. */126+const 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+};171+172+/**173+ * The defaults (convex-merged design §3, "no folder means defaults"; the174+ * weakening markers from spec §4.2), as `Policy` encodes them.175+ */176+const 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+};225+226+/** Evaluates a bundle at `at` with the shared facts, and encodes the policy. */227+const evaluated = (modules: ConfigBundle) =>228+ Effect.gen(function* () {229+ const evaluator = yield* RulesEvaluator;230+ const policy = yield* evaluator.evaluate({ at, facts, modules });231+232+ return yield* Schema.encodeEffect(Policy)(policy);233+ });234+235+/** Evaluates a bundle that must fail, and hands back its `RulesFailed`. */236+const failed = (modules: ConfigBundle) =>237+ Effect.gen(function* () {238+ const evaluator = yield* RulesEvaluator;239+240+ const result = yield* Effect.result(241+ evaluator.evaluate({ at, facts, modules })242+ );243+244+ if (Result.isSuccess(result)) {245+ return assert.fail("the config evaluated to a policy");246+ }247+248+ return result.failure;249+ });250+251+/** An ask file whose brief says what happens today, but not what is wanted. */252+const 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`;259+260+describe("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+ );268+269+ 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+ );276+277+ 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");283+284+ const askFiles = Object.entries(example.modules).filter(([path]) =>285+ path.startsWith(`${configFolder}/asks/`)286+ );287+288+ const policy = yield* evaluated({289+ ...json,290+ modules: { ...json.modules, ...Object.fromEntries(askFiles) },291+ });292+293+ 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+ );301+302+ 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+ );307+308+ 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+ );313+314+ expect(failure.reason).toBe("load");315+ expect(failure.detail).toContain(`${configFolder}/project.ts`);316+ }).pipe(Effect.provide(bunEvaluator()))317+ );318+319+ 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+ );327+328+ 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+ );333+334+ 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+ );339+340+ expect(failure.reason).toBe("timeout");341+ expect(Duration.toMillis(took)).toBeLessThan(5000);342+ }).pipe(Effect.provide(bunEvaluator({ timeout: "1 second" })))343+ );344+345+ 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+ );350+351+ expect(failure.reason).toBe("threw");352+ expect(failure.detail).toContain("no policy today");353+ }).pipe(Effect.provide(bunEvaluator()))354+ );355+356+ 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"));359+360+ 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+ );378+379+ it.live("points both names of the sdk at the one sdk module", () =>380+ Effect.gen(function* () {381+ const base = yield* baseProject;382+383+ 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");389+390+ const policy = yield* evaluated(bundleOf({ "project.ts": project }));391+392+ 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+ );401+402+ it.live("runs config code with no env beyond PATH, and no fetch", () =>403+ Effect.gen(function* () {404+ const base = yield* baseProject;405+406+ 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");411+412+ const policy = yield* evaluated(bundleOf({ "project.ts": project }));413+414+ expect(policy.weakening).toStrictEqual({415+ markers: ["PATH", "undefined"],416+ });417+ }).pipe(Effect.provide(bunEvaluator()))418+ );419+420+ 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+ );431+432+ expect(failure.detail.length).toBeLessThanOrEqual(64 * 1024);433+ expect(failure.detail).toMatch(/x+the end$/u);434+ }).pipe(Effect.provide(bunEvaluator()))435+ );436+437+ 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");441+442+ const call = (rule: "admit" | "opensAlone", held: number) =>443+ evaluator.call({ at, facts: { held }, modules, rule });444+445+ 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+});451+452+describe("the /json adapter", () => {453+ const jsonEvaluator = RulesEvaluatorJson.pipe(454+ Layer.provide(Layer.succeed(Finishers, finishers)),455+ Layer.provideMerge(NodeServices.layer)456+ );457+458+ 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+ );465+466+ 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+ );476+477+ 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+ );482+483+ 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);487+488+ const fromBun = yield* evaluated(modules).pipe(489+ Effect.provide(bunEvaluator())490+ );491+492+ expect(fromJson).toStrictEqual({ ...defaultsEncoded, source: "config" });493+ expect(fromBun).toStrictEqual(fromJson);494+ }).pipe(Effect.provide(jsonEvaluator))495+ );496+497+ it.live("has no function-valued rules to call", () =>498+ Effect.gen(function* () {499+ const evaluator = yield* RulesEvaluator;500+501+ const called = yield* evaluator.call({502+ at,503+ facts: { held: 3 },504+ modules: yield* folder("cm"),505+ rule: "opensAlone",506+ });507+508+ expect(called).toBeFalsy();509+ }).pipe(Effect.provide(jsonEvaluator))510+ );511+});added:packages/rules/test/finish.test.ts+64 added
1+import { describe, expect, it } from "@effect/vitest";2+import { CheckSpec } from "@repo/protocol/domain/check";3+import { AskInput } from "@repo/protocol/domain/policy";4+import { RepoPath } from "@repo/protocol/ids";5+import { Effect, Schema } from "effect";6+7+import { defaultPolicyInput } from "../src/defaults.ts";8+import { finishPolicy } from "../src/finish.ts";9+import { at, facts, finishers } from "./world.ts";10+11+/** An ask with the given id, declared in `file`. */12+const 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+ });25+26+describe(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+ );37+38+ expect(failure.reason).toBe("decode");39+ expect(failure.detail).toContain('line 2 ("@bob")');40+ })41+ );42+43+ 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+ );59+60+ 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
1+import { describe, expect, it } from "@effect/vitest";2+import { Policy } from "@repo/protocol/domain/policy";3+import { DateTime, Effect, Schema } from "effect";4+5+import { RulesEvaluator } from "../src/rules-evaluator.ts";6+import type { ConfigBundle, EvaluationFacts } from "../src/rules-evaluator.ts";7+import {8+ at,9+ baseProject,10+ bundleOf,11+ bunEvaluator,12+ facts,13+ folder,14+ now,15+ nowMs,16+} from "./world.ts";17+18+/** Evaluates a bundle with the given facts, and encodes the policy. */19+const 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 });23+24+ return yield* Schema.encodeEffect(Policy)(policy);25+ });26+27+/**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+ */34+const 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+);60+61+/** What the clock-reading config put into its ask's context. */62+const stampOf = (policy: typeof Policy.Encoded) =>63+ policy.asks[0]?.brief.context;64+65+describe("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);71+72+ expect(second).toStrictEqual(first);73+ }74+ }).pipe(Effect.provide(bunEvaluator()))75+ );76+77+ 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));81+82+ const later = stampOf(83+ yield* evaluated(modules, {84+ ...facts,85+ now: DateTime.makeUnsafe("2027-01-01T00:00:00.000Z"),86+ })87+ );88+89+ expect(first?.slice(0, 3)).toStrictEqual([nowMs, now, nowMs]);90+91+ expect(later?.slice(0, 3)).toStrictEqual([92+ "1798761600000",93+ "2027-01-01T00:00:00.000Z",94+ "1798761600000",95+ ]);96+97+ // 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+ );101+102+ it.live("gives config code randomness from the facts' seed", () =>103+ Effect.gen(function* () {104+ const modules = yield* readsTheClock;105+106+ // 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+ );112+113+ const first = yield* randomWith(7);114+ const other = yield* randomWith(8);115+116+ // 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
1-import { describe, expect, it } from "@effect/vitest";2-3-import manifest from "../package.json" with { type: "json" };4-5-// A skeleton's one test, so vitest finds a file; real tests replace it.6-describe("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
1+import { describe, expect, it } from "@effect/vitest";2+3+import { parseVouchFile } from "../src/vouch.ts";4+5+// A vouch file in Ghostty's VOUCHED.td format: its header comment, then one6+// handle per line.7+const 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");21+22+describe(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+ });41+42+ 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+ });48+49+ 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+ });62+63+ 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+ });72+73+ it("reads an empty file as no vouches", () => {74+ expect(parseVouchFile("")).toStrictEqual({ invalid: [], vouches: [] });75+ });76+});added:packages/rules/test/world.ts+140 added
1+import { NodeServices } from "@effect/platform-node";2+import { Glob } from "@repo/protocol/domain/common";3+import { FromCI, PolicyInput } from "@repo/protocol/domain/policy";4+import { LandedSha } from "@repo/protocol/ids";5+import { Effect, FileSystem, Layer, Path, Schema } from "effect";6+7+import { defaultPolicyInput } from "../src/defaults.ts";8+import { Finishers } from "../src/finish.ts";9+import { EvaluationFacts } from "../src/rules-evaluator.ts";10+import type { ConfigBundle } from "../src/rules-evaluator.ts";11+import { rulesEvaluatorBun } from "../src/rules-evaluator/bun.ts";12+import type { BunOptions } from "../src/rules-evaluator/bun.ts";13+14+/**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+ */19+export const configFolder = ".cfg";20+21+/** The vouch file a policy that names none gets: `PolicyInput`'s default. */22+export 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;32+33+/** The landed commit every test evaluates at. */34+export const at = LandedSha.make("a".repeat(40));35+36+/** The frozen clock the facts carry, as text and in epoch milliseconds. */37+export const now = "2026-10-07T12:00:00.000Z";38+39+export const nowMs = "1791374400000";40+41+/**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+ */46+export 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;62+63+export const facts = Schema.decodeSync(EvaluationFacts)(factsEncoded);64+65+/**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+ */70+export 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+});83+84+/** The `/bun` adapter over Node, with the fake finishers. */85+export 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+ );93+94+/** A bundle of config-folder files, keyed by their path inside the folder. */95+export 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;106+107+/**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+ */112+export const folder = (name: string) =>113+ Effect.gen(function* () {114+ const fs = yield* FileSystem.FileSystem;115+ const path = yield* Path.Path;116+117+ const root = yield* path.fromFileUrl(118+ new URL(`fixtures/${name}`, import.meta.url)119+ );120+121+ const files: Record<string, string> = {};122+123+ for (const file of (yield* fs.readDirectory(root, {124+ recursive: true,125+ })).toSorted()) {126+ const full = path.join(root, file);127+128+ if ((yield* fs.stat(full)).type === "File") {129+ files[file] = yield* fs.readFileString(full);130+ }131+ }132+133+ return bundleOf(files);134+ });135+136+/** A project module that exports the defaults as config: a base to vary. */137+export const baseProject = Effect.map(138+ Schema.encodeEffect(PolicyInput)({ ...defaultPolicyInput, source: "config" }),139+ (encoded) => `export default ${JSON.stringify(encoded)};\n`140+);