Trim comments in rules, sdk, testkit and visibility to the essential ones
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parent 022043d · Browse files · 71 files·+168 added−1432 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
71 files+168 added−1432 removed
- tests:+16 added−274 removed
- other:+152 added−1158 removed
Provenance
- Commit
f314385- Tree
85c67bc- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
022043d
71 files changed+168 added−1432 removed
modified:packages/rules/src/rules-evaluator/bun-main.ts+2 added-6 removed
123456723456785 unmodified lines/** * The `/bun` adapter's main module, written beside the config modules with a * `job.json` that names them. It imports each module in turn, so it can tell * a module that would not load (a syntax error, an import that resolves to * nothing) from one whose code threw, hands their exports to `entry.ts`, and * prints one JSON document as its last line of stdout: `Collected`, `Called` * or `Failed`. Plain JavaScript as source text, like the prelude. * It imports each module in turn, so it can tell a module that would not load * from one whose code threw. Plain JavaScript as source text, like the prelude. * * `job.json`: `{entry, project?: {file, path}, visibility?: {file, path}, * asks: [{file, path}]}` for an evaluation, plus `{rule, facts}` for a call; * `file` is where a module was written, `path` its path in the bundle.85 unmodified linesmodified:packages/rules/src/rules-evaluator/bun-prelude.ts+1 added-13 removed
1234127891011121314153456756 unmodified lines/** * 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. The Worker's prelude is its own module. *//** Config code's own logging goes to stderr, so stdout carries only the evaluator's one result. */export const bunPrelude = `const clock = JSON.parse(process.env.${clockVariable} ?? "{}");delete process.env.${clockVariable};
56 unmodified linesmodified:packages/rules/src/rules-evaluator/bun.ts+1 added-28 removed
25 unmodified lines26 import type { ConfigBundle } from "../rules-evaluator.ts";27 import { bunMain } from "./bun-main.ts";28 import { bunPrelude, clockVariable } from "./bun-prelude.ts";29 30-/** How the `/bun` adapter runs config code. */30 export interface BunOptions {32- /** The bun binary; `bun` on the `PATH` by default. */31 readonly bun?: string;32 /**33 * What the bun binary needs in its env beside `PATH` and the clock: a34 * compiled CLI runs itself as bun with `BUN_BE_BUN=1`. None by default.35 */36 readonly env?: Readonly<Record<string, string>>;39- /**40- * The module the main hands the exports to (`../entry.ts` here, or a41- * bundled copy of it on disk); this package's own by default.42- */37 readonly entry?: string;44- /** The module the sdk's imports point at; `@repo/sdk`'s entry by default. */38 readonly sdk?: string;46- /** How long config code may run; 5 seconds by default. */39 readonly timeout?: Duration.Input;40 }41 42 // An import or export of the sdk by either of its names: the workspace one,2 unmodified lines45 // can import nothing else by a bare name anyway.46 const SDK_IMPORT =47 /(?<lead>\bfrom\s*|\bimport\s*\(?\s*)(?<quote>["'])(?:@repo\/sdk|@[a-z0-9][\w.-]*\/cli\/rules)\k<quote>/gu;48 57-/** Points every import of the sdk, by either name, at the module `sdk`. */49 const pointSdkAt = (source: string, sdk: string) =>50 source.replaceAll(SDK_IMPORT, `$<lead>${JSON.stringify(sdk)}`);51 61-/** What the subprocess prints as its last line. */52 const Output = Schema.TaggedUnion({53 Called: { result: Schema.Json },54 Collected: Collected.fields,55 Failed: {5 unmodified lines61 type Output = typeof Output.Type;62 63 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));64 75-/** 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 81-/** What the main is asked to do: collect the folder's exports, or call a rule. */70 interface Job {71 readonly asks: readonly Written[];72 readonly entry: string;73 readonly facts?: Schema.Json;1 unmodified line75 readonly rule?: string;76 readonly visibility?: Written;77 }78 91-/** The frozen clock and seed the prelude installs. */79 interface Clock {80 readonly now: string;81 readonly seed: number;82 }20 unmodified lines103 const resultLimit = 16 * 1024 * 1024;104 105 const logLimit = 64 * 1024;106 120-/** The last `limit` characters a stream prints; the rest is read and dropped. */107 const tailOf = <E>(bytes: Stream.Stream<Uint8Array, E>, limit: number) =>108 bytes.pipe(109 Stream.decodeText(),110 // Cut at twice the limit, so each character is copied only a few times.6 unmodified lines117 ),118 Effect.map((kept) => kept.slice(-limit))119 );120 135-/** The project module, the visibility module and the ask files, as the main imports them. */121 const modulesOf = (122 written: ReadonlyMap<string, string>,123 project: string | undefined,124 asks: readonly string[],13 unmodified lines138 ? withProject139 : { ...withProject, visibility: at(visibility) };140 };141 157-/**158- * `RulesEvaluator` over a `bun` subprocess. Each evaluation writes the159- * bundle's modules into a scoped temp directory (every import of the sdk160- * pointed at the sdk's own entry), runs `bun --preload <prelude> <main>`161- * with no inherited env beyond `PATH`, frozen time and randomness, and a162- * time limit, and reads one JSON document from its stdout. A bundle with no163- * project module, no asks and no visibility module reads `policy.json`, or164- * gets the defaults, without a subprocess. Then `finishPolicy`, with the caller's `Finishers`.165- */142+/** The subprocess inherits no env beyond `PATH`, with frozen time and randomness and a time limit. */143 export const rulesEvaluatorBun = (options: BunOptions = {}) =>144 Layer.effect(145 RulesEvaluator,146 Effect.gen(function* () {18 unmodified lines165 166 const sdk =167 options.sdk ?? (yield* fromUrl(import.meta.resolve("@repo/sdk")));168 192- /** Writes `source` at `file` under `root`, refusing a path that leaves it. */169 const writeUnder = (root: string, file: string, source: string) => {170 const target = path.join(root, file);171 const relative = path.relative(root, target);172 15 unmodified lines188 )189 );190 };191 216- /** Runs the main over the bundle for one job, and reads its result. */192 const run = (193 bundle: ConfigBundle,194 clock: Clock,195 job: (written: ReadonlyMap<string, string>) => Omit<Job, "entry">82 unmodified lines278 ? { ...output, detail: clean(output.detail) }279 : output;280 });281 307- /** Runs a job in its own scope, within the time limit. */282 const limited = (283 effect: Effect.Effect<Output, RulesFailed, Scope.Scope>284 ) =>285 Effect.scoped(effect).pipe(95 unmodified lines381 });382 })383 );384 411-/** The `/bun` adapter with its defaults: `bun` on the `PATH`, a 5-second limit. */385 export const RulesEvaluatorBun = rulesEvaluatorBun();modified:packages/rules/src/rules-evaluator/json.ts+1 added-5 removed
2 unmodified lines34567891011789101112 unmodified lines2 unmodified linesimport { 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`. *//** 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;12 unmodified linesmodified:packages/rules/src/rules-evaluator/worker.ts+8 added-57 removed
18 unmodified lines19 import type { FrozenFacts } from "../prelude.ts";20 import { factsOf, RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";21 import type { ConfigBundle, RuleName } from "../rules-evaluator.ts";22 23-/**24- * One module as the Worker Loader takes it: ES module source, JSON data, or25- * text. (`@cloudflare/workers-types`' `WorkerLoaderModule`, for the kinds26- * used.)27- */23 export type LoaderModule =24 | { readonly js: string }25 | { readonly json: Schema.Json }26 | { readonly text: string };27 33-/**34- * The code the adapter hands the Loader: `WorkerLoaderWorkerCode`'s fields35- * it uses. There is no `env` (no binding reaches config code), no outbound36- * (`fetch` and `connect` throw), and no subrequests.37- */28+/** No `env` (no binding reaches config code), no outbound and no subrequests. */29 export interface LoaderCode {30 readonly compatibilityDate: string;31 readonly globalOutbound: null;32 readonly limits: { readonly cpuMs: number; readonly subRequests: number };33 readonly mainModule: string;34 readonly modules: Readonly<Record<string, LoaderModule>>;35 }36 46-/** A loaded worker's default entrypoint, as `Fetcher#fetch` serves it. */37 export interface LoaderEntrypoint {38 readonly fetch: (39 url: string,40 init: { readonly body: string; readonly method: "POST" }41 ) => Promise<{ readonly text: () => Promise<string> }>;42 }43 54-/** A loaded worker, as `WorkerStub#getEntrypoint` opens it. */44 export interface LoadedWorker {45 readonly getEntrypoint: () => LoaderEntrypoint;46 }47 48 /**60- * The Worker Loader binding, typed by the fields the adapter uses, so61- * `rules` needs no Workers types: the platform's `env.LOADER` (a62- * `WorkerLoader`) is one. `get` keeps a worker warm under its id and calls63- * `getCode` only for an id it doesn't hold.49+ * Typed by the fields the adapter uses, so `rules` needs no Workers types.50+ * `get` keeps a worker warm under its id and calls `getCode` only for an id it51+ * doesn't hold.52 */53 export interface LoaderBinding {54 readonly get: (id: string, getCode: () => LoaderCode) => LoadedWorker;55 }56 69-/** How the `/worker` adapter loads config code. */57 export interface WorkerOptions {71- /** The loaded worker's compatibility date; the platform's by default. */58 readonly compatibilityDate?: string;73- /** The CPU time one request may spend; 200 ms by default. */59 readonly cpuMs?: number;75- /** How long one request may take, waiting included; 5 s by default. */60 readonly timeoutMs?: number;61 }62 79-/** What the loaded worker answers: the same results `/bun`'s main prints. */63 const Output = Schema.TaggedUnion({64 Called: { result: Schema.Json },65 Collected: Collected.fields,66 Failed: {5 unmodified lines72 type Output = typeof Output.Type;73 74 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));75 93-/** A request to the loaded worker: collect the folder's exports, or call a rule. */76 type Job =77 | Readonly<Record<string, never>>78 | { readonly facts: Schema.Json; readonly rule: RuleName };79 21 unmodified lines101 // before the worker starts, so a syntax error anywhere in the folder102 // rejects the request instead of reaching the main.103 const WONT_START = /^Failed to start Worker\b/u;104 123-// A module the Loader imports as code.105 const SCRIPT = /\.[cm]?[jt]s$/u;106 107 const loadFailed = (detail: string) =>108 new RulesFailed({ detail, reason: "load" });9 unmodified lines118 119 const messageOf = (cause: unknown) =>120 Predicate.isError(cause) ? cause.message : String(cause);121 141-/**142- * A rejection from the loaded worker: a module that won't compile, its CPU143- * limit spent, or its code threw.144- */122 const thrownBy = (cause: unknown) => {123 const message = messageOf(cause);124 const detail = `the loaded worker: ${message}`;125 6 unmodified lines132 reason: RAN_OUT.test(message) ? "timeout" : "threw",133 });134 };135 159-/** Releases a stub the runtime handed out; one with no way to be released is left. */136 const released = (stub: LoadedWorker | LoaderEntrypoint) =>137 Effect.try(() => {138 const dispose =139 Predicate.isSymbol(disposeKey) && Predicate.hasProperty(stub, disposeKey)4 unmodified lines144 dispose.call(stub);145 }146 }).pipe(Effect.ignore);147 172-/** Sends one job to a loaded worker's entrypoint, and decodes its answer. */148 const requested = (entrypoint: LoaderEntrypoint, job: Job) =>149 Effect.tryPromise({150 catch: thrownBy,151 try: () =>17 unmodified lines169 )170 )171 );172 198-/**199- * Whether a bundle path names a module inside the folder: relative, with200- * no empty, `.` or `..` segment, and not the main's or the prelude's name.201- */173 const isModulePath = (path: string) =>174 path !== mainName &&175 path !== preludeName &&176 path177 .split("/")178 .every((segment) => segment !== "" && segment !== "." && segment !== "..");179 209-/** Refuses a bundle with a path outside the folder, before any worker loads. */180 const insideTheFolder = (bundle: ConfigBundle) => {181 const outside = Object.keys(bundle.modules).filter(182 (path) => !isModulePath(path)183 );8 unmodified lines192 };193 194 const parsedJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));195 226-/**227- * A bundle file as a Loader module: a script as ES module source, JSON as228- * data (or as text when it won't parse, which fails only if config code229- * imports it), anything else as text.230- */196+/** JSON that won't parse goes as text, which fails only if config code imports it. */197 const moduleOf = (path: string, source: string): LoaderModule => {198 if (SCRIPT.test(path)) {199 return { js: source };200 }14 unmodified lines215 */216 const workerIdOf = (bundle: ConfigBundle, at: string, clock: FrozenFacts) =>217 `rules:${at}:${bundle.sdkVersion}:${clock.now}:${clock.seed}`;218 253-/**254- * `RulesEvaluator` over the Worker Loader. Each request loads255- * the bundle's modules, a prelude that freezes the clock and randomness to256- * the injected facts, and a main that answers one JSON document, as a257- * Dynamic Worker with no bindings, no outbound and a CPU limit, kept warm258- * per landed commit; asks it to collect the folder's exports or call a259- * rule; and disposes it after, whatever it answered. A bundle with no260- * project module, no asks and no visibility module reads `policy.json`, or261- * gets the defaults, without a worker. Then `finishPolicy`, with the caller's `Finishers`. The262- * adapter reads no clock: an evaluation's clock is `facts.now`, the landed263- * commit's time.264- */219+/** The adapter reads no clock: an evaluation's clock is `facts.now`, the landed commit's time. */220 export const RulesEvaluatorWorker = (221 loader: LoaderBinding,222 options: WorkerOptions = {}223 ) =>5 unmodified lines229 const cpuMs = options.cpuMs ?? 200;230 const timeoutMs = options.timeoutMs ?? 5000;231 232 /**278- * The code the Loader gets for a bundle under a clock. The Loader asks279- * for it only for an id it doesn't hold, so a warm request builds none.233+ * The Loader asks for it only for an id it doesn't hold, so a warm234+ * request builds none.235 */236 const codeOf = (bundle: ConfigBundle, clock: FrozenFacts): LoaderCode => {237 const modules: Record<string, LoaderModule> = {};238 19 unmodified lines258 modules,259 };260 };261 307- /**308- * Loads the bundle under a clock, runs one job, and disposes the309- * worker and its entrypoint, within the time limit.310- */262 const run = (263 bundle: ConfigBundle,264 at: string,265 clock: FrozenFacts,112 unmodified linesmodified:packages/rules/src/config-folder.ts+3 added-57 removed
5 unmodified lines6 import { defaultPolicyInput } from "./defaults.ts";7 import { RulesFailed } from "./rules-evaluator.ts";8 import type { ConfigBundle } from "./rules-evaluator.ts";9 10-// An ask file: `<id>.ask.ts`, or the `.js` a bundler writes for it.10 const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;11 13-// A module that runs: TypeScript or JavaScript, not JSON or a vouch file.12 const SCRIPT = /\.[cm]?[jt]s$/u;13 16-/**17- * The config folder a bundle holds: its project module's folder. The bundle18- * names it, so `rules` never spells it (the brand lives in `packages/brand`,19- * which `rules` does not import).20- */14+/** The bundle names the folder, so `rules` never spells the brand. */15 const folderOf = (bundle: ConfigBundle) =>16 bundle.entry.slice(0, bundle.entry.lastIndexOf("/") + 1);17 24-/** Where a committed policy stands in for the TypeScript (the fallback). */18 export const policyJsonOf = (bundle: ConfigBundle) =>19 `${folderOf(bundle)}policy.json`;20 28-/** The bundle's project module, when it has one. */21 export const projectModule = (bundle: ConfigBundle): string | undefined =>22 SCRIPT.test(bundle.entry) && Object.hasOwn(bundle.modules, bundle.entry)23 ? bundle.entry24 : undefined;25 34-// The visibility module: `visibility.ts`, or the `.js` a bundler writes for it.26 const VISIBILITY_FILE = /^visibility\.[cm]?[jt]s$/u;27 37-/**38- * The bundle's visibility module (`<folder>/visibility.ts`), when it has39- * one: the project's layers and held-back checks.40- */28 export const visibilityModule = (bundle: ConfigBundle): string | undefined => {29 const folder = folderOf(bundle);30 31 return Object.keys(bundle.modules)4 unmodified lines36 VISIBILITY_FILE.test(path.slice(folder.length))37 );38 };39 53-/** The bundle's ask files, in path order so evaluation is the same every time. */40 export const askModules = (bundle: ConfigBundle): readonly string[] => {41 const asks = `${folderOf(bundle)}asks/`;42 43 return Object.keys(bundle.modules)44 .filter((path) => path.startsWith(asks) && ASK_FILE.test(path))45 .toSorted();46 };47 62-/** A decode failure, named by the file it came from. */48 export const failedAt =49 (where: string) =>50 (failure: Schema.SchemaError): RulesFailed =>51 new RulesFailed({52 detail: `${where}: ${failure.message}`,53 reason: "decode",54 });55 71-/** A module whose default export is missing (or `null`) states nothing. */56 const noDefault = (path: string, what: string) =>57 new RulesFailed({58 detail: `${path}: its default export is not ${what}`,59 reason: "decode",60 });61 78-/**79- * The policy a committed `policy.json` states, when the bundle has one. It80- * carries its asks inline.81- */62 const fromPolicyJson = (63 bundle: ConfigBundle64 ): Effect.Effect<Option.Option<PolicyInput>, RulesFailed> => {65 const path = policyJsonOf(bundle);8 unmodified lines74 Effect.mapError(failedAt(path))75 );76 };77 98-/**99- * The policy input a bundle states without running code: its `policy.json`,100- * or else the defaults. Its source is the config folder whenever there is101- * one, and the defaults only when there is none, so every102- * adapter gives one bundle the same source.103- */78+/** Its source is the config folder whenever there is one, so every adapter gives one bundle the same source. */79 export const statedWithoutCode = (80 bundle: ConfigBundle81 ): Effect.Effect<PolicyInput, RulesFailed> =>82 Effect.map(4 unmodified lines87 : { ...defaultPolicyInput, source: "config" }88 )89 );90 116-/** What the config folder's modules exported, as data, read back from the sandbox. */91 export const Collected = Schema.Struct({92 asks: Schema.Array(Schema.Struct({ ask: Schema.Json, path: Schema.String })),119- /** Absent when the bundle has no project module; `null` when it exports nothing. */93 project: Schema.optionalKey(Schema.Json),121- /** Absent when the bundle has no visibility module; `null` when it exports nothing. */94 visibility: Schema.optionalKey(Schema.Json),95 });96 97 export type Collected = typeof Collected.Type;98 127-/**128- * An ask as its file states it: the path names it (its id and file), and129- * the asker and what blocks it may go unsaid.130- */99 const AskFile = Schema.Struct({100 ...Struct.omit(AskInput.fields, ["askedBy", "blockedBy", "file", "id"]),101 askedBy: Schema.optionalKey(Handle),102 blockedBy: Schema.optionalKey(Schema.Array(AskId)),103 });104 137-/**138- * A project module's data: its asks are the ask files, its source the139- * folder, and its visibility the visibility module's.140- */105 const ProjectFile = PolicyInput.mapFields(106 Struct.omit(["asks", "source", "visibility"])107 );108 145-/** An ask's id: its file's name less `.ask.ts`. */109 const idOf = (path: string) =>110 path.slice(path.lastIndexOf("/") + 1).replace(ASK_FILE, "");111 149-/**150- * An ask file's data as an `AskInput`. The id and file come from the path,151- * whatever the data says; an ask that names no asker was asked by the152- * initializer, and one that names nothing blocking it is blocked by nothing.153- */112+/** The id and file come from the path, whatever the data says. */113 const askInputOf = (path: string, data: Schema.Json, initializer: Handle) =>114 Effect.gen(function* () {115 if (data === null) {116 return yield* noDefault(path, "an ask");15 unmodified lines132 id,133 } satisfies AskInput;134 });135 177-/**178- * The visibility module's data as the project's `VisibilityPolicy`, when179- * the folder has one; a module that exports nothing, or no policy, fails180- * naming it.181- */136 const visibilityOf = (137 data: Schema.Json | undefined,138 path: string | undefined139 ): Effect.Effect<Option.Option<VisibilityPolicy>, RulesFailed> => {10 unmodified lines150 Effect.mapError(failedAt(where))151 );152 };153 200-/**201- * The policy input the config folder's modules give: the project module's202- * data, or `fallback` when the folder has no project module (its203- * `policy.json`, or the defaults), with every ask file's ask after the204- * fallback's own, and the visibility module's policy when the folder has205- * one (else the fallback's). Its source is the config folder.206- */154 export const fromCollected = (input: {155 readonly collected: Collected;156 readonly entry: string;157 readonly fallback: PolicyInput;158 readonly initializer: Handle;212- /** The visibility module's path, which a failure names. */159 readonly visibility?: string | undefined;160 }): Effect.Effect<PolicyInput, RulesFailed> =>161 Effect.gen(function* () {162 const { collected, entry, fallback, initializer } = input;37 unmodified linesmodified:packages/rules/src/defaults.ts+1 added-12 removed
1 import { PolicyInput } from "@repo/protocol/domain/policy";2 import { defaults, toPolicyInput } from "@repo/sdk";3 import { Schema } from "effect";4 5-/**6- * The policy a project with no config folder runs on (no folder means7- * defaults): the sdk's own `defaults`, decoded, so the8- * default kinds and numbers have one home each. One `fix` kind whose asks a9- * vouched person claims, the run block found in the project's CI, and the10- * initializer deciding everything; the rest is `PolicyInput`'s11- * own defaults: five decisions a day that wait 14 days, two proposals and12- * three claims per person, a claim warned after 2 hours and lapsed after 24,13- * a vouch for code in the config folder's `vouched.td`, `Assisted-by`14- * trailers, and a record that counts after 30 days for a year. It adds no15- * weakening markers: the gate scans its own defaults plus a project's.16- */5+/** It adds no weakening markers: the gate scans its own defaults plus a project's. */6 export const defaultPolicyInput: PolicyInput = Schema.decodeSync(PolicyInput)(7 toPolicyInput(defaults)8 );modified:packages/rules/src/entry.ts+3 added-28 removed
1-/**2- * The evaluator's side inside the sandbox (a `bun` subprocess here, a Dynamic3- * Worker on a stage): it hands what the config folder's modules exported back as4- * data, which the sandbox's main sends as JSON, so functions and5- * non-enumerable properties drop out and the host decodes the rest; and it6- * finds a function-valued rule to call. It imports only `effect` and the7- * sdk's `Functions` key, which config code brings anyway, so a bundler can8- * inline it beside the sdk.9- */1+// Imports only `effect` and the sdk's `Functions` key, which config code2+// brings anyway, so a bundler can inline it beside the sdk.3 import { Functions } from "@repo/sdk/functions";4 import { Predicate } from "effect";5 import type { Schema } from "effect";6 14-/**15- * What a config module's default export is: the sdk's definition, plain16- * data shaped as `PolicyInput` or `AskInput` once encoded. Its17- * function-valued rules (`opensAlone`, `admit`) ride under the sdk's18- * `Functions` symbol, which JSON never meets, and `functions` in the data19- * says which exist.20- */7+/** Function-valued rules ride under the sdk's `Functions` symbol, which JSON never meets. */8 export type Definition = Schema.Json;9 23-/** A function-valued rule: called with the facts its caller passes. */10 export type Rule = (facts: Schema.Json) => boolean | Promise<boolean>;11 26-/** One module's default export, by the module's path in the bundle. */12 export interface Exported {13 readonly definition: Definition | undefined;14 readonly path: string;15 }16 32-/** The modules' data, as the host reads it back (`Collected` there). */17 export interface CollectedData {18 readonly asks: readonly {19 readonly ask: Schema.Json;20 readonly path: string;1 unmodified line22 readonly project?: Schema.Json;23 readonly visibility?: Schema.Json;24 }25 42-/** A module with no default export gives `null`, which the host refuses. */26 const dataOf = (definition: Definition | undefined): Schema.Json =>27 definition ?? null;28 46-/**47- * Collects the project module's data and the visibility module's (each when48- * the folder has one), and every ask's.49- */29 export const collect = (30 project: Exported | undefined,31 asks: readonly Exported[],32 visibility?: Exported14 unmodified lines47 };48 49 const isRule = (value: unknown): value is Rule => Predicate.isFunction(value);50 72-/**73- * The project definition's function-valued rule, when it has one: read74- * where the sdk keeps it (`functionsOf`), under its `Functions` symbol.75- */51 export const ruleOf = (52 definition: Definition | undefined,53 rule: string54 ): Rule | undefined => {12 unmodified linesmodified:packages/rules/src/finish.ts+8 added-35 removed
10 unmodified lines11 import { RulesFailed } from "./rules-evaluator.ts";12 import type { EvaluationFacts } from "./rules-evaluator.ts";13 import { parseVouchFile } from "./vouch.ts";14 15-/** A file the finishers read: a CI workflow, a hook config, a manifest. */15 export interface FactFile {16 readonly content: string;17 readonly path: string;18 }19 21-/**22- * What `rules` needs from `checks` without importing it: the judge closure23- * and the run-block finder. The caller passes `checks`' own functions; tests24- * pass fakes.25- */20+/** What `rules` needs from `checks` without importing it. */21 export class Finishers extends Context.Service<22 Finishers,23 {24 readonly findRunBlock: (files: readonly FactFile[]) => {16 unmodified lines41 * platform names someone else, so it vouches for no one here.42 */43 const isSignInPlatform = (platform: string) => platform === "github";44 50-/** The run block: the config folder's own, or the one the finder finds in CI. */45 const runBlockOf = (46 run: PolicyInput["run"],47 facts: EvaluationFacts,48 finishers: Finishers["Service"]14 unmodified lines63 ...found.run,64 }).pipe(Effect.mapError(failedAt(`the run block found in ${where}`)));65 };66 73-/**74- * The vouch file's lines as the policy holds them. A line that names no75- * handle fails the policy, so a typo is reported rather than dropped.76- */67+/** A line that names no handle fails the policy, so a typo is reported rather than dropped. */68 const vouchesOf = (text: string, file: RepoPath) => {69 const { invalid, vouches } = parseVouchFile(text);70 71 if (invalid.length > 0) {21 unmodified lines93 })94 );95 };96 106-/** A workspace folder as a glob prefix: `./packages/x/` is `packages/x`. */97 const folderOf = (dir: string) =>98 dir99 .replace(/^(?:\.\/)+/u, "")100 .replace(/\/+$/u, "")101 .replace(/^\.$/u, "");102 113-/**114- * The territories answers may change: one per workspace package, its paths115- * its folder, its public files its `exports`; `.` for a single-package repo.116- */103 const territoriesOf = (104 workspaces: EvaluationFacts["workspaces"]105 ): (typeof Policy.Encoded)["modules"] =>106 workspaces.length === 09 unmodified lines116 ? { module: name, paths }117 : { module: name, paths, publicFiles: exports };118 });119 134-/** A glob with the package's folder written over the sdk's `{dir}`. */120 const placed = (glob: string, folder: string) => {121 const written = glob.replaceAll(packageDir, folder).replace(/^\/+/u, "");122 123 return written === "" ? "**" : written;124 };125 126 /**142- * An ask's territory with its package's folder written in. The sdk's143- * `territory.package(name)` can't know where the package lives, so it names144- * the workspace by `module` and writes `{dir}` in its paths; here the145- * workspace's folder replaces it, and its `exports` become the public files146- * unless the ask states its own. A module no workspace names keeps the147- * placeholder, which matches no real path, so the gate refuses every change148- * (it fails closed).127+ * The sdk's `territory.package(name)` can't know where the package lives, so128+ * it writes `{dir}`. A module no workspace names keeps the placeholder, which129+ * matches no real path, so the gate refuses every change (it fails closed).130 */131 const placedIn = (132 workspaces: EvaluationFacts["workspaces"],133 territory: PolicyInput["asks"][number]["territory"]14 unmodified lines148 ? { ...territory, paths }149 : { ...territory, paths, publicFiles: workspace.exports };150 };151 171-/** Fails when two asks share an id: an id names one ask, and one fork per claim. */152 const distinctAsks = (asks: PolicyInput["asks"]) => {153 const seen = new Map<string, string>();154 155 for (const { file, id } of asks) {14 unmodified lines170 return Effect.void;171 };172 173 /**194- * Turns what the config folder evaluated to into the project's `Policy` at195- * `at`, filling in what the platform knows from the facts: the run block196- * (`fromCI` resolved by the finder), the modules from the workspaces, each197- * package territory's folder (the sdk's `{dir}`), the judge closure, `owners` as the initializer, and the vouch198- * file's lines. Each ask counts as open, opened at `facts.now` in `at`: the199- * Project DO overwrites `openedAt`, `openedIn` and `state` from its own rows.200- * The whole is decoded with `Policy`, so a value the finishers or facts got201- * wrong fails here as `RulesFailed`, not later.174+ * Each ask counts as open, opened at `facts.now`: the Project DO overwrites175+ * `openedAt`, `openedIn` and `state` from its own rows. The whole is decoded176+ * with `Policy`, so a value the finishers or facts got wrong fails here.177 */178 export const finishPolicy = (input: {179 readonly at: LandedSha;180 readonly facts: EvaluationFacts;39 unmodified lines220 vouches,221 weakening: policy.weakening,222 } satisfies typeof Policy.Encoded;223 249- // The project's layers and held-back checks, as `visibility.ts` states250- // them; a project without one is Open.224 const stated =225 policy.visibility === undefined226 ? candidate227 : {11 unmodified linesmodified:packages/rules/src/prelude.ts+12 added-55 removed
1-/**2- * The source the `/worker` adapter hands the Worker Loader beside the config3- * folder's modules: a prelude that freezes the clock and randomness before4- * any config code runs (principle 8), and a main that imports the folder's5- * modules and answers one JSON document per request. Both are module text;6- * nothing here runs in the platform's own isolate except to write it.7- */1+// Module text for the Worker Loader: nothing here runs in the platform's own2+// isolate except to write it.3 import { Functions } from "@repo/sdk/functions";4 5 /**6 * The clock and seed config code sees, injected by the caller: an1 unmodified line8 * call's are the Unix epoch and 0, so a rule gets time only through its9 * facts (as `/bun` does).10 */11 export interface FrozenFacts {17- /** The time, in epoch milliseconds. */12 readonly now: number;13 readonly seed: number;14 }15 22-/**23- * A scope's `Date`: constructed with or without a time, and asked for one.24- * Its `now` is replaced too, so the frozen `Date` leads to no other clock.25- */16 export interface DateClass {17 new (...args: readonly (Date | number | string)[]): Date;18 now: () => number;19 readonly prototype: Date;20 }21 32-/**33- * The globals the prelude replaces: `globalThis` in the loaded worker, a34- * plain object in tests.35- */22 export interface FreezableScope {23 Date: DateClass;24 readonly Math: { random: () => number };25 readonly crypto: {2 unmodified lines28 };29 readonly performance: { now: () => number };30 }31 46-/** What the prelude hands the main. */32 export interface Frozen {33 /**34 * Puts the randomness back where it stood the first time this was called:35 * the main calls it once its modules are loaded, before each job's own2 unmodified lines38 readonly settle: () => void;39 }40 41 /**57- * Replaces the scope's clock and randomness with values from `facts`:58- * `Date.now()`, `new Date()` with no argument, `Date()`, a date's own59- * `constructor`, `performance.now()` (always 0), and `Math.random()`,60- * `crypto.getRandomValues()` and `crypto.randomUUID()` from a generator61- * seeded with `facts.seed`. The frozen `Date` is the scope's own behind a62- * proxy, whose `now` and whose dates' `constructor` it replaces as well, so63- * no path from it (a date the runtime made, what sits above it) leads to64- * the real clock: the same as `/bun`'s prelude.65- *66- * It is serialised into the prelude module with `Function#toString`, so its67- * body names nothing outside itself and defines no function or class a68- * bundler would name (only methods, and functions assigned to a member; an69- * arrow bound to a name or written as an object literal's property value70- * is named): a `keepNames` build, wrangler's default, would otherwise call71- * a naming helper the prelude module doesn't have.42+ * Serialised into the prelude module with `Function#toString`, so its body43+ * names nothing outside itself and defines no function or class a bundler44+ * would name (only methods, and functions assigned to a member; an arrow45+ * bound to a name or written as an object literal's property value is46+ * named): a `keepNames` build, wrangler's default, would otherwise call a47+ * naming helper the prelude module doesn't have.48 */49 export const installFrozenGlobals = (50 scope: FreezableScope,51 facts: FrozenFacts102 unmodified lines154 },155 };156 };157 182-/**183- * The prelude module: `installFrozenGlobals` applied to the loaded worker's184- * `globalThis` with `facts` as JSON, exporting what it returns as `frozen`.185- */158 export const preludeModule = (facts: FrozenFacts): string =>159 `export const frozen = (${String(installFrozenGlobals)})(globalThis, ${JSON.stringify({ now: facts.now, seed: facts.seed })});\n`;160 189-/** The prelude's module name, beside the main at the root. */161 export const preludeName = "prelude.js";162 192-/** The main's module name. */163 export const mainName = "main.js";164 195-/** The modules a main imports: the config folder's, by their bundle paths. */165 export interface MainModules {197- /** The ask files, in path order. */166 readonly asks: readonly string[];199- /** The project module, when the folder has one. */167 readonly project?: string | undefined;201- /** The visibility module, when the folder has one. */168 readonly visibility?: string | undefined;169 }170 205-/** A module the main imports on first use, by a literal specifier. */171 const importer = (path: string) =>172 `{ load: () => import(${JSON.stringify(`./${path}`)}), path: ${JSON.stringify(path)} }`;173 174 /**210- * The main module. It imports the prelude first, so the clock is frozen211- * before any config code exists; then, per request, it imports the config212- * folder's modules (once, while the worker stays warm) and answers the213- * request's job with one JSON document, as `/bun`'s main prints one:175+ * It imports the prelude first, so the clock is frozen before any config code176+ * exists, and answers each request with one JSON document:177 *215- * - `{}` → `Collected {asks: [{ask, path}], project?, visibility?}`, each216- * module's default export as data (functions and the sdk's symbol drop217- * out);218- * - `{rule, facts}` → `Called {result}`, the project module's rule called219- * with the facts (`false` when it has none);178+ * - `{}` → `Collected {asks: [{ask, path}], project?, visibility?}`;179+ * - `{rule, facts}` → `Called {result}` (`false` when there is no rule);180 * - either → `Failed {reason: "load" | "threw", detail}`.221- *222- * Function-valued rules are read where the sdk keeps them, under its223- * `Functions` symbol, which the main finds by its registry key.181 */182 export const mainModule = (modules: MainModules): string => `183 import { frozen } from "./${preludeName}";184 120 unmodified linesmodified:packages/rules/src/rules-evaluator.ts+4 added-52 removed
2 unmodified lines3 import { Handle, ProjectName, RepoPath } from "@repo/protocol/ids";4 import { ClaimantFacts, ProposalFacts } from "@repo/sdk/functions";5 import { Context, Effect, Schema } 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- */7+/** An empty `modules` means the project has no config folder, so it runs on the defaults. */8 export const ConfigBundle = Schema.Struct({9 /**10 * The project module's path, `<folder>/project.ts`, whether or not the11 * folder has one: it names the folder the asks and `policy.json` sit in.12 */13 entry: Schema.NonEmptyString,14 modules: Schema.Record(Schema.String, Schema.String),21- /** The rules package version the folder was written against. */15 sdkVersion: Schema.NonEmptyString,16 });17 18 export type ConfigBundle = typeof ConfigBundle.Type;19 27-/**28- * The version of the rules the platform runs, the sdk's own: what a bundle29- * the platform makes reports, and part of every check version. Callers that30- * may not import the sdk (`@repo/project`) read it here.31- */20+/** Callers that may not import the sdk (`@repo/project`) read it here. */21 export { sdkVersion } from "@repo/sdk";22 34-/** One workspace package, as the repo's manifests declare it. */23 const Workspace = Schema.Struct({36- /** Its folder, from the repo's root: `packages/parse`. */24 dir: Schema.String,38- /** The files its `exports` name, from the repo's root. */25 exports: Schema.Array(RepoPath),26 name: Schema.NonEmptyString,27 });28 43-/**44- * Everything rule code may know about the project, injected by the platform:45- * rule code never reads the repo, the network or the clock. The same facts46- * always give the same policy (principle 8).47- */29+/** Rule code never reads the repo, the network or the clock: the same facts always give the same policy. */30 export const EvaluationFacts = Schema.Struct({49- /**50- * Every file of the commit, as `checks`' `judgeInputs` gathers them: the51- * text of each one its finder (where a `run: fromCI` block is found) or52- * judge closure reads (CI workflows, hook configs and the scripts they53- * run, `package.json`s, tsconfig chains, lint plugins and their tests,54- * the config folder), and empty text for the rest.55- */31 ci: Schema.Array(Schema.Struct({ content: Schema.String, path: RepoPath })),57- /** The person who made the project; `owners` resolves to them. */32 initializer: Handle,59- /** The frozen clock rule code sees, and when its asks count as opened. */33 now: Schema.DateTimeUtcFromString,61- /** The project the asks belong to. */34 project: ProjectName,63- /** The frozen randomness rule code sees. */35 seed: Schema.Int,65- /** The vouch file's text, when the project has one. */36 vouchFile: Schema.optionalKey(Schema.String),37 workspaces: Schema.Array(Workspace),38 });39 40 export type EvaluationFacts = typeof EvaluationFacts.Type;41 72-/**73- * Why the config folder gave no policy: it would not load, it ran past its74- * time limit, what it exported is not a policy, or its code threw. The75- * policy then stays on the previous landed commit.76- */42+/** The policy then stays on the previous landed commit. */43 export class RulesFailed extends Schema.TaggedError<RulesFailed>()(44 "RulesFailed",45 {46 detail: Schema.String,47 reason: Schema.Literals(["load", "timeout", "decode", "threw"]),48 }49 ) {}50 85-/** The function-valued rules, called on demand rather than read as data. */51 export const RuleName = Schema.Literals(["opensAlone", "admit"]);52 53 export type RuleName = typeof RuleName.Type;54 90-/**91- * One function-valued rule and the facts it is told, typed by the sdk's own92- * fact schemas (principle 2): `opensAlone` hears about a proposal, `admit`93- * about a person who wants to claim. The facts are encoded as JSON before94- * they cross into the sandbox.95- */55 export type RuleCall =56 | { readonly rule: "opensAlone"; readonly facts: ProposalFacts }57 | { readonly rule: "admit"; readonly facts: ClaimantFacts };58 100-/** A call's facts as JSON carries them into the sandbox. */59 export const factsOf = (call: RuleCall): Effect.Effect<Schema.Json> => {60 const encoded: Effect.Effect<Schema.Json, Schema.SchemaError> =61 call.rule === "opensAlone"62 ? Schema.encodeEffect(ProposalFacts)(call.facts)2 unmodified lines65 // The facts were typed by the same schemas, so encoding them can't fail.66 return Effect.orDie(encoded);67 };68 111-/**112- * Turns the config folder at a landed commit into its `Policy`, the same113- * one every time for the same facts, and calls its function-valued rules on114- * demand. Adapters: `/bun` (a subprocess with frozen time), `/json` (a115- * committed `policy.json`, or the defaults) and, on a stage, `/worker`.116- */69 export class RulesEvaluator extends Context.Service<70 RulesEvaluator,71 {72 readonly call: (12 unmodified linesmodified:packages/rules/src/vouch.ts+1 added-12 removed
1 import { Handle } from "@repo/protocol/ids";2 import { Schema } from "effect";3 4-/** One line of a vouch file: a person vouched for, or denounced. */4 export interface Vouch {5 readonly denounced: boolean;6 readonly handle: Handle;7 readonly note?: string;9- /** The `platform:` prefix the line wrote, when it wrote one: `github`. */8 readonly platform?: string;9 }10 13-/** A line that names no valid handle, kept so it is reported, not dropped. */11 export interface InvalidVouchLine {12 readonly line: number;13 readonly text: string;14 }15 19-/** A vouch file, read: its vouches and denouncements, and its bad lines. */16 export interface VouchFile {17 readonly invalid: readonly InvalidVouchLine[];18 readonly vouches: readonly Vouch[];19 }5 unmodified lines25 /^(?<sign>[+-]?)\s*(?:(?<platform>[a-z][a-z0-9-]*):)?(?<handle>\S+)(?:\s+(?<note>\S.*))?$/u;26 27 const isHandle = Schema.is(Handle);28 33-/** One non-blank, non-comment line, read; `undefined` when it names no handle. */29 const vouchOf = (text: string): Vouch | undefined => {30 const groups = LINE.exec(text)?.groups;31 const handle = groups?.handle;32 10 unmodified lines43 ? withNote44 : { ...withNote, platform: groups.platform };45 };46 52-/**53- * Reads a vouch file in Ghostty's `VOUCHED.td` format: one handle per line54- * (without `@`), an optional `platform:` prefix (`github:alice`), `-handle`55- * to denounce, text after a space as a note, and `#` lines as comments.56- * Blank lines are skipped; a line whose handle fails `Handle` is reported57- * in `invalid` with its line number.58- */47+/** Ghostty's `VOUCHED.td` format; a line whose handle fails `Handle` is reported in `invalid`. */48 export const parseVouchFile = (text: string): VouchFile => {49 const vouches: Vouch[] = [];50 const invalid: InvalidVouchLine[] = [];51 18 unmodified linesmodified:packages/rules/test/fixtures/cm/asks/iso-week.ask.ts-4 removed
1-/**2- * The example's open ask, held for newcomers, as the sdk encodes it. Its id3- * and file come from its path in the config folder.4- */1 export { default } from "./iso-week.json" with { type: "json" };modified:packages/rules/test/fixtures/cm/asks/leap-year.ask.ts+1 added-4 removed
1-/**2- * A second ask that names no asker, so the initializer asked it, and no3- * `blockedBy`, so nothing blocks it.4- */1+/** Names no asker and no `blockedBy`, so the defaults apply. */2 export { default } from "./leap-year.json" with { type: "json" };modified:packages/rules/test/fixtures/cm/project.ts-12 removed
1 import { Functions } from "@repo/sdk";2 3 import data from "./project.json" with { type: "json" };4 5-/**6- * The convex-merged design's example project, as the data the sdk's7- * builders encode it to (`project.json`): a `fixBug` kind with a8- * red-then-green check, deciders by glob with the owners for the rest, the9- * budget and caps, `Assisted-by` trailers, and the record window. The run10- * block is the one found in CI; claims and the vouch file keep their11- * defaults.12- *13- * The example's one function-valued rule rides where the sdk keeps it,14- * under its `Functions` symbol, which JSON never meets: a proposal opens15- * alone for someone with three unreverted landings in the territory.16- */5 const project = Object.defineProperty({ ...data }, Functions, {6 enumerable: false,7 value: {8 admit: undefined,5 unmodified linesmodified:packages/rules/test/fixtures/sdk-stub.ts-4 removed
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- */1 export const marker = "the sdk";modified:packages/rules/test/evaluate.test.ts-20 removed
26 unmodified lines27 const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);28 29 const decodeClaimant = Schema.decodeUnknownSync(ClaimantFacts);30 31-/** A proposal for an ask of the example's `fixBug` kind, but its record. */31 const fixBugProposal = {32 kind: "fixBug",33 proposer: "carol",34 territory: "@datekit/parse",35 };36 38-/** A red-then-green check on one file, as `CheckSpec` encodes it. */37 const redThenGreen = (path: string) =>38 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });39 42-/** What the platform fills in on every ask: when, where and whose. */40 const opened = {41 openedAt: now,42 openedIn: at,43 project: "oscabriel/datekit",44 state: "open",45 };46 50-/** What every policy in these tests derives from the shared facts. */47 const fromFacts = {48 at,49 modules: [50 {8 unmodified lines59 { denounced: true, handle: "mallory", note: "Spam" },60 ],61 };62 67-/** The judge closure the fake finishers give for a run block's test command. */63 const judgeFor = (test: string) => ({64 paths: [`${configFolder}/**`, ".github/workflows/ci.yml"],65 pointers: ["package.json#/scripts", `test:${test}`],66 });67 73-/** The run block the fake finder finds in CI. */68 const foundRun = { checks: { unit: "bun test" }, test: "bun test {path}" };69 70 const fixBug = {71 checkKind: "redThenGreen",5 unmodified lines77 requires: ["want", "check"],78 strength: "assertion",79 };80 87-/** The convex-merged example's policy, as `Policy` encodes it. */81 const exampleEncoded = {82 ...fromFacts,83 agents: "trailer",84 asks: [42 unmodified lines127 vouch: { file: defaultVouchFile, mode: "forCode" },128 weakening: { markers: [".skip(", ".only("] },129 };130 138-/** The policy a folder holding only `policy.json` states. */131 const jsonEncoded = {132 ...fromFacts,133 agents: "none",134 asks: [38 unmodified lines173 vouch: { file: defaultVouchFile, mode: "forCode" },174 weakening: { markers: [".skip("] },175 };176 185-/**186- * The defaults (no folder means defaults), as187- * `Policy` encodes them: the sdk's `defaults`, finished with the facts.188- */177 const defaultsEncoded = {178 ...fromFacts,179 agents: "trailer",180 asks: [],23 unmodified lines204 // The gate scans its own default markers plus these, a project's own.205 weakening: { markers: [] },206 };207 220-/** Evaluates a bundle at `at` with the shared facts, and encodes the policy. */208 const evaluated = (modules: ConfigBundle) =>209 Effect.gen(function* () {210 const evaluator = yield* RulesEvaluator;211 const policy = yield* evaluator.evaluate({ at, facts, modules });212 213 return yield* Schema.encodeEffect(Policy)(policy);214 });215 229-/** Evaluates a bundle that must fail, and hands back its `RulesFailed`. */216 const failed = (modules: ConfigBundle) =>217 Effect.gen(function* () {218 const evaluator = yield* RulesEvaluator;219 7 unmodified lines227 228 return result.failure;229 });230 245-/**246- * A `visibility.ts`'s default export, as the sdk writes it: one layer of247- * held-back checks for one area.248- */231 const visibilityEncoded = {232 checks: {233 admit: { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 },234 areas: { parse: "packages/parse/**" },19 unmodified lines254 ],255 notice: { narrowingDays: 7 },256 } satisfies typeof VisibilityPolicy.Encoded;257 276-/** A module whose default export is `data`. */258 const exporting = (data: Schema.Json) =>259 `export default ${JSON.stringify(data)};\n`;260 280-/** An ask file whose brief says what happens today, but not what is wanted. */261 const noWant = `export default ${JSON.stringify({262 blockedBy: [],263 brief: { current: "Dates parse only in one format" },264 check: redThenGreen("test/formats.repro.test.ts"),410 unmodified linesmodified:packages/rules/test/example-burrow.test.ts+2 added-27 removed
1-/**2- * The fence-shaped example's config folder: the `/bun` adapter3- * evaluates `examples/burrow`'s config folder, with the facts the platform4- * reads from burrow's tree (its root files, its six workspace packages and5- * its vouch file), into the policy the ratchet and the six-way migrate demo6- * run on.7- *8- * The folder is found as the one at burrow's root that holds a `project.ts`:9- * its name is the brand's, which `rules` never spells. Its presence is10- * asserted before it is read, so a missing folder is a failed assertion.11- */1+// The config folder is found as the one at burrow's root holding a2+// `project.ts`: its name is the brand's, which `rules` never spells.3 import { describe, expect, it } from "@effect/vitest";4 import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";5 import { Command, SymbolName } from "@repo/protocol/domain/common";6 import { Policy } from "@repo/protocol/domain/policy";1 unmodified line8 9 import { EvaluationFacts, RulesEvaluator } from "../src/rules-evaluator.ts";10 import { at, bundleOf, bunEvaluator, configFolder, now } from "./world.ts";11 21-/** A text file under burrow's root, by its path there. */12 interface File {13 readonly content: string;14 readonly path: string;15 }5 unmodified lines21 });22 23 const decodeManifest = Schema.decodeEffect(Schema.fromJsonString(Manifest));24 35-/** The folders at `root` that hold a `project.ts`, and the files beside them. */25 const rootEntries = (root: string) =>26 Effect.gen(function* () {27 const fs = yield* FileSystem.FileSystem;28 const path = yield* Path.Path;15 unmodified lines44 45 return { files, folders };46 });47 59-/** Every `.ts` file under a folder, keyed by its path inside it. */48 const sourcesIn = (folder: string) =>49 Effect.gen(function* () {50 const fs = yield* FileSystem.FileSystem;51 const path = yield* Path.Path;11 unmodified lines63 64 return sources;65 });66 79-/**80- * The workspace packages a root manifest declares, as the platform reads81- * them: each `<dir>/*` glob is every folder in `<dir>`, and each package's82- * `exports` targets are its public files.83- */67 const workspacesAt = (root: string, globs: readonly string[]) =>68 Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;22 unmodified lines93 )94 );95 });96 114-/** burrow's config folder as a bundle, and the facts the platform reads around it. */97 const readBurrow = () =>98 Effect.gen(function* () {99 const fs = yield* FileSystem.FileSystem;100 const path = yield* Path.Path;29 unmodified lines130 modules: bundleOf(yield* sourcesIn(path.join(root, folder))),131 };132 });133 152-/** burrow's policy at `at`, as `Policy` encodes it. */134 const evaluated = () =>135 Effect.gen(function* () {136 const { facts, modules } = yield* readBurrow();137 const evaluator = yield* RulesEvaluator;2 unmodified lines140 yield* evaluator.evaluate({ at, facts, modules })141 );142 });143 163-/** Every workspace package as its own module: its folder, and its `exports`. */144 const modules = [145 {146 module: "@burrow/auth",147 paths: ["packages/auth/**"],25 unmodified lines173 publicFiles: ["packages/search/src/index.ts"],174 },175 ];176 197-/** The migrate ask, as `Policy` encodes it. */177 const dropLegacyFetch = {178 askedBy: "okafor",179 blockedBy: [],180 brief: {17 unmodified lines198 state: "open",199 territory: { module: ".", paths: ["packages/**"] },200 };201 223-/** The sdk's `migrate` kind, as `Policy` encodes it. */202 const migrateKind = {203 checkKind: "migrate",204 claimers: "vouched",205 finish: "never",58 unmodified lines264 },265 setup: "bun install --frozen-lockfile",266 test: "bun test {path}",267 },290- // The two deciders, six contributors (one for each migrate child),291- // and one person denounced.268 vouches: [269 ["okafor", false],270 ["lin-h", false],271 ["wren", false],12 unmodified lines284 Effect.gen(function* () {285 const policy = yield* evaluated();286 const globs = policy.asks.flatMap(({ territory }) => territory.paths);287 312- // Each module's folder lies under one of the ask's `<dir>/**` globs.288 const covered = policy.modules.filter(({ paths: [folder] }) =>289 globs.some(290 (glob) =>291 glob.endsWith("/**") &&10 unmodified linesmodified:packages/rules/test/example-datekit.test.ts+1 added-18 removed
1-/**2- * The datekit example's config folder, evaluated by the `/bun`3- * adapter as the Lander's bundle of it would be: every file in the folder,4- * keyed by its repo path, with the facts the platform would give a5- * single-package repo (no workspaces, its vouch file, `ines-v` as the6- * initializer). Its `.ts` files import the sdk by the name users write, the7- * published one, which the adapter points at the sdk.8- */1 import { NodeServices } from "@effect/platform-node";2 import { describe, expect, it } from "@effect/vitest";3 import { CheckSpec } from "@repo/protocol/domain/check";4 import { Policy } from "@repo/protocol/domain/policy";3 unmodified lines8 import { EvaluationFacts, RulesEvaluator } from "../src/rules-evaluator.ts";9 import type { ConfigBundle } from "../src/rules-evaluator.ts";10 import { at, bunEvaluator, now } from "./world.ts";11 20-/** Where the example lives, from this test's folder. */12 const exampleUrl = new URL("../../../examples/datekit/", import.meta.url);13 23-/**24- * The example's dot-folders that hold a `project.ts`: its config folder, as25- * the repo names it. `rules` never spells that name (it lives in26- * `packages/brand`), so the test finds it.27- */14+/** `rules` never spells the config folder's name, so the test finds it. */15 const configFolders = Effect.gen(function* () {16 const fs = yield* FileSystem.FileSystem;17 const path = yield* Path.Path;18 const root = yield* path.fromFileUrl(exampleUrl);10 unmodified lines29 30 return { folders, root };31 });32 46-/** Every file in the example's config folder, as the bundle the Lander makes of it. */33 const exampleBundle = Effect.gen(function* () {34 const fs = yield* FileSystem.FileSystem;35 const path = yield* Path.Path;36 const { folders, root } = yield* configFolders;24 unmodified lines61 folder,62 };63 });64 79-/** The policy the example's config folder evaluates to, encoded. */65 const evaluated = Effect.gen(function* () {66 const { bundle, folder } = yield* exampleBundle;67 const evaluator = yield* RulesEvaluator;68 11 unmodified lines80 81 return { folder, policy: yield* Schema.encodeEffect(Policy)(policy) };82 });83 99-/** What one of the example's asks is, beside its brief. */84 const askOf = (85 folder: string,86 id: string,87 territory: readonly [string, ...string[]]89 unmodified lines177 policy.asks.map(({ brief, id }) => ({178 current: brief.current !== undefined,179 id,180 outOfScope: (brief.outOfScope ?? []).length > 0,197- // A want is behavioural: no file paths, no line numbers.181 wantNamesCode: /\.ts\b|:\d+|\bline \d/u.test(brief.want),182 }))183 ).toStrictEqual(184 ["add-months-clamp", "format-ordinal", "parse-iso-week"].map(70 unmodified linesmodified:packages/rules/test/fake-loader.ts+2 added-25 removed
8 unmodified lines9 LoaderEntrypoint,10 LoaderModule,11 } from "../src/rules-evaluator/worker.ts";12 13-/** How a loaded worker's entrypoint answers every request. */13 export type Answer =15- /** With this body. */14 | { readonly responds: string }17- /** By rejecting with this error, as the runtime does when the worker fails. */15 | { readonly rejects: Error }19- /** Never. */16 | { readonly hangs: true };17 22-/** One cold start: the id the adapter asked for, and the code it handed over. */18 export interface Load {19 readonly code: LoaderCode;20 readonly id: string;21 }22 28-/** A fake Worker Loader, and what it saw. */23 export interface FakeLoader {24 readonly binding: LoaderBinding;31- /** The stubs and entrypoints handed out, and how many were disposed. */25 readonly handles: () => { readonly disposed: number; readonly out: number };33- /** Each cold start, in order: a warm id loads nothing. */26 readonly loads: readonly Load[];35- /** Each request's body, as sent. */27 readonly requests: readonly string[];28 }29 30 // `Symbol.dispose`, which the runtime calls a stub's release by; the lib the2 unmodified lines33 Symbol,34 "dispose"35 )?.value;36 46-/**47- * A fake Worker Loader whose workers answer every request the same way. It48- * keeps workers warm by id, as the Loader does: a second `get` with an id it49- * has seen calls no `getCode`.50- */37+/** Keeps workers warm by id, as the Loader does: a second `get` with a seen id calls no `getCode`. */38 export const fakeLoader = (answer: Answer): FakeLoader => {39 const loads: Load[] = [];40 const requests: string[] = [];41 const warm = new Set<string>();42 const counts = { disposed: 0, out: 0 };43 57- /** A handle that counts itself out, and in again when disposed. */44 const handle = <A extends object>(value: A): A => {45 counts.out += 1;46 47 if (Predicate.isSymbol(disposeKey)) {40 unmodified lines88 requests,89 };90 };91 106-/** A module's source, as the Loader would read it. */92 const sourceOf = (module: LoaderModule) => {93 if ("js" in module) {94 return module.js;95 }96 97 return "json" in module ? JSON.stringify(module.json) : module.text;98 };99 115-/** Runs the main's default `fetch` once, and prints what it answered. */100 const harness = `101 import worker from "./main.js";102 const body = await Bun.file(new URL("./request.json", import.meta.url)).text();103 const response = await worker.fetch(new Request("https://rules.invalid/", { body, method: "POST" }));104 process.stdout.write(await response.text());105 process.exit(0);106 `;107 124-/** Writes the code's modules under a temp directory, and runs one request. */108 const runInBun = (code: LoaderCode, body: string, sdk: string) =>109 Effect.scoped(110 Effect.gen(function* () {111 const fs = yield* FileSystem.FileSystem;3 unmodified lines115 const files = {116 ...Object.fromEntries(117 Object.entries(code.modules).map(([name, module]) => [118 name,136- // The config modules import the sdk by its workspace name.119 sourceOf(module).replaceAll('"@repo/sdk"', JSON.stringify(sdk)),120 ])121 ),122 "request.json": body,22 unmodified lines145 return stdout === "" ? `bun printed nothing: ${stderr}` : stdout;146 })147 ).pipe(Effect.orDie);148 167-/**168- * A Loader that runs the code it is handed, in a `bun` subprocess per169- * request: Bun stands in for workerd, so the main and the prelude are run170- * as the JavaScript they are, without workerd's limits. Every import of the171- * sdk by its workspace name points at `sdk`.172- */149+/** Bun stands in for workerd, so the main and the prelude run as the JavaScript they are, without workerd's limits. */150 export const bunLoader = (151 services: Context.Context<152 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path153 >,17 unmodified linesmodified:packages/rules/test/finish.test.ts-2 removed
6 unmodified lines7 import { defaultPolicyInput } from "../src/defaults.ts";8 import { finishPolicy } from "../src/finish.ts";9 import { at, facts, finishers } from "./world.ts";10 11-/** The whole repo, as one module. */11 const wholeRepo: (typeof AskInput.Encoded)["territory"] = {12 module: ".",13 paths: ["**"],14 };15 17-/** An ask with the given id, declared in `file`, in `territory`. */16 const askIn = (17 id: string,18 file: string,19 territory: (typeof AskInput.Encoded)["territory"] = wholeRepo99 unmodified linesmodified:packages/rules/test/prelude.test.ts-2 removed
5 unmodified lines6 preludeModule,7 } from "../src/prelude.ts";8 import type { FreezableScope, FrozenFacts } from "../src/prelude.ts";9 10-/** 2026-10-07T12:00:00.000Z, the landed commit's time, and its seed. */10 const facts: FrozenFacts = { now: 1_791_374_400_000, seed: 7 };11 12 /**13 * mulberry32 seeded with 7, worked out from the published algorithm apart18 unmodified lines32 },33 performance: { now: () => 1 },34 });35 37-/** Two words and a UUID from a scope frozen with `seed`. */36 const draws = (seed: number) => {37 const scope = scopeOf();38 39 installFrozenGlobals(scope, { ...facts, seed });130 unmodified linesmodified:packages/rules/test/replay.test.ts-11 removed
13 unmodified lines14 now,15 nowMs,16 } from "./world.ts";17 18-/** Evaluates a bundle with the given facts, and encodes the policy. */18 const evaluated = (modules: ConfigBundle, with_: EvaluationFacts = facts) =>19 Effect.gen(function* () {20 const evaluator = yield* RulesEvaluator;21 const policy = yield* evaluator.evaluate({ at, facts: with_, modules });22 23 return yield* Schema.encodeEffect(Policy)(policy);24 });25 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- */26 const readsTheClock = Effect.map(baseProject, (base) =>27 bundleOf({28 "asks/stamp.ask.ts": [29 'import { stamp } from "../project.ts";',19 unmodified lines49 ].join("\n"),50 })51 );52 61-/** What the clock-reading config put into its ask's context. */53 const stampOf = (policy: typeof Policy.Encoded) =>54 policy.asks[0]?.brief.context;55 56 describe("evaluating a config folder twice", () => {32 unmodified lines89 "2027-01-01T00:00:00.000Z",90 "1798761600000",91 ]);92 102- // A date that names its own time is left alone.93 expect(first?.[3]).toBe("1970-01-01T00:00:00.000Z");94 }).pipe(Effect.provide(bunEvaluator()))95 );96 97 it.live("gives config code randomness from the facts' seed", () =>98 Effect.gen(function* () {99 const modules = yield* readsTheClock;100 111- // Math.random(), crypto.getRandomValues() and crypto.randomUUID().101 const randomWith = (seed: number) =>102 Effect.map(103 evaluated(modules, { ...facts, seed }),104 (policy) => stampOf(policy)?.slice(4) ?? []18 unmodified linesmodified:packages/rules/test/vouch.test.ts-2 removed
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.5 const vouchedFile = [6 "# The list of vouched (or actively denounced) users for this repository.",7 "#",8 "# Syntax:",66 unmodified linesmodified:packages/rules/test/worker.test.ts-39 removed
30 unmodified lines31 now,32 nowMs,33 } from "./world.ts";34 35-/** The `/worker` adapter over a loader, with the fake finishers. */35 const workerEvaluator = (loader: LoaderBinding, options?: WorkerOptions) =>36 RulesEvaluatorWorker(loader, options).pipe(37 Layer.provide(Layer.succeed(Finishers, finishers))38 );39 41-/** A policy as JSON carries it: one the evaluator gave always encodes. */40 const encoded = (policy: Policy) =>41 Effect.orDie(Schema.encodeEffect(Policy)(policy));42 45-/** Evaluates a bundle at a landed commit: the encoded policy, or the failure. */43 const evaluated = (modules: ConfigBundle, landed = at) =>44 Effect.gen(function* () {45 const evaluator = yield* RulesEvaluator;46 3 unmodified lines50 .pipe(Effect.flatMap(encoded))51 );52 });53 57-/** Calls a function-valued rule: its answer, or the failure. */54 const called = (modules: ConfigBundle, call: RuleCall) =>55 Effect.gen(function* () {56 const evaluator = yield* RulesEvaluator;57 58 return yield* Effect.result(evaluator.call({ ...call, at, modules }));59 });60 65-/** The reason a result failed for; a policy or an answer fails the test. */61 const reasonOf = <A>(62 result: Result.Result<A, { readonly reason: string }>63 ): string => {64 assert(Result.isFailure(result), "expected the evaluation to fail");2 unmodified lines67 };68 69 const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);70 76-/** A proposal for an ask of the example's `fixBug` kind, with a record. */71 const proposal = (record: number): RuleCall => ({72 facts: decodeProposal({73 kind: "fixBug",74 proposer: "carol",2 unmodified lines77 }),78 rule: "opensAlone",79 });80 87-/** The defaults, written as a project module's data. */81 const baseEncoded = Schema.encodeSync(PolicyInput)({82 ...defaultPolicyInput,83 source: "config",84 });85 93-/** A folder with a project module and one ask file. */86 const bundle = bundleOf({87 "asks/a.ask.ts": "export default {};\n",88 "project.ts": "export default {};\n",89 });90 99-/** What the main answers for a folder whose project module is the defaults. */91 const collectedBase = `{"_tag":"Collected","asks":[],"project":${JSON.stringify(baseEncoded)}}`;92 102-/** The specifiers a module imports, in the order it names them. */93 const importsOf = (source: string) =>94 [95 ...source.matchAll(96 /\bimport\s*(?:\(\s*|[^"'()]*?from\s*)(?<quote>["'])(?<specifier>[^"']+)\k<quote>/gu97 ),98 ].map((match) => match.groups?.specifier);99 110-/** A script module's source, from the modules a load handed over. */100 const scriptOf = (modules: LoaderCode["modules"], name: string): string => {101 const module = modules[name];102 103 assert(module !== undefined && "js" in module, `${name} is no script`);104 105 return module.js;106 };107 119-/** The modules the first load handed over. */108 const firstLoaded = (loads: readonly { readonly code: LoaderCode }[]) => {109 const [load] = loads;110 111 assert(load !== undefined, "the adapter loaded no worker");112 113 return load.code;114 };115 128-/**129- * Evaluates `bundle` over a fake whose worker answers so, with a 20 ms130- * limit: why it failed ("ok" when it didn't), and the handles disposed.131- */116 const outcome = (answer: Answer) =>117 Effect.gen(function* () {118 const loader = fakeLoader(answer);119 6 unmodified lines126 reason: Result.isFailure(result) ? result.failure.reason : "ok",127 };128 });129 146-/** Why evaluating `bundle` fails over a fake whose worker answers so. */130 const reasonFor = (answer: Answer) =>131 evaluated(bundle).pipe(132 Effect.provide(workerEvaluator(fakeLoader(answer).binding)),133 Effect.map(reasonOf)117 unmodified lines251 yield* evaluated(bundle, other);252 yield* evaluated({ ...bundle, sdkVersion: "0.0.1" });253 }).pipe(Effect.provide(workerEvaluator(loader.binding)));254 272- // Each cold start, by what its id names.255 const named = loader.loads.map(({ id }) => ({256 at: [at, other].find((sha) => id.includes(sha)),257 sdk: ["0.0.0", "0.0.1"].find((version) => id.includes(version)),258 }));36 unmodified lines295 const viaWorker = yield* evaluated(bundle).pipe(296 Effect.provide(workerEvaluator(loader.binding))297 );298 317- // The same data, committed as policy.json, read without running code.299 const viaJson = yield* evaluated(300 bundleOf({ "policy.json": JSON.stringify(baseEncoded) })301 ).pipe(302 Effect.provide(49 unmodified lines352 yield* reasonFor({353 responds:354 '{"_tag":"Failed","detail":".cfg/project.ts: Error: no policy today","reason":"threw"}',355 }),375- // Exports that are not a policy.356 yield* reasonFor({357 responds:358 '{"_tag":"Collected","asks":[],"project":{"budget":"plenty"}}',359 }),380- // An answer to a job it was not given.360 yield* reasonFor({ responds: '{"_tag":"Called","result":true}' }),361 ]).toStrictEqual([362 "timeout",363 "load",68 unmodified lines432 })433 );434 });435 457-/**458- * The `/worker` adapter over a Loader that runs what it is handed in Bun,459- * so the main and the prelude run as the JavaScript they are, beside the460- * `/bun` adapter over the same bundles.461- */436 const running = Effect.gen(function* () {437 const services = yield* Effect.context<438 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path439 >();6 unmodified lines446 447 return workerEvaluator(bunLoader(services, sdk));448 });449 476-/**477- * A config whose project module reads the clock and randomness while it478- * loads, and whose one ask puts what it read into its context: the wall479- * clock, a dated `new Date()`, the clock reached through a date's own480- * constructor, whether `Date()` tells the same time as `new Date()`, the481- * clock reached through a date the runtime made (`structuredClone`) and482- * through whatever sits above `Date`, then `Math.random()`,483- * `crypto.getRandomValues()` and `crypto.randomUUID()`.484- */450 const readsTheClock = bundleOf({451 "asks/stamp.ask.ts": [452 'import { stamp } from "../project.ts";',453 "export default {",19 unmodified lines473 `export default ${JSON.stringify(baseEncoded)};`,474 ].join("\n"),475 });476 512-/**513- * A folder with a `visibility.ts` beside its project module: one layer of514- * held-back checks, as the sdk writes it.515- */477 const withVisibility = bundleOf({478 "project.ts": `export default ${JSON.stringify(baseEncoded)};\n`,479 "visibility.ts": `export default ${JSON.stringify({480 env: { setters: "deciders" },117 unmodified linesmodified:packages/rules/test/world.ts+1 added-21 removed
16 unmodified lines17 * 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. */21 export const defaultVouchFile = Schema.decodeSync(PolicyInput)({22 asks: [],23 deciders: [],24 functions: { admit: false, opensAlone: false },3 unmodified lines28 source: "defaults",29 weakening: { markers: [] },30 }).vouch.file;31 33-/** The landed commit every test evaluates at. */32 export const at = LandedSha.make("a".repeat(40));33 36-/** The frozen clock the facts carry, as text and in epoch milliseconds. */34 export const now = "2026-10-07T12:00:00.000Z";35 36 export const nowMs = "1791374400000";37 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- */38 export const factsEncoded = {39 ci: [{ content: "steps: [bun test]", path: ".github/workflows/ci.yml" }],40 initializer: "olivia",41 now,11 unmodified lines53 } satisfies typeof EvaluationFacts.Encoded;54 55 export const facts = Schema.decodeSync(EvaluationFacts)(factsEncoded);56 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- */57 export const finishers = Finishers.of({58 findRunBlock: (files) => ({59 run: { checks: { unit: "bun test" }, test: "bun test {path}" },60 sources: files.map(({ path }) => path),6 unmodified lines67 pointers: ["package.json#/scripts", `test:${run.test}`],68 }),69 });70 84-/** The `/bun` adapter over Node, with the fake finishers. */71 export const bunEvaluator = (72 options: BunOptions = {},73 finish: Finishers["Service"] = finishers74 ) =>1 unmodified line76 Layer.provide(Layer.succeed(Finishers, finish)),77 Layer.provideMerge(NodeServices.layer)78 );79 94-/** A bundle of config-folder files, keyed by their path inside the folder. */80 export const bundleOf = (files: Readonly<Record<string, string>>) =>81 ({82 entry: `${configFolder}/project.ts`,83 modules: Object.fromEntries(4 unmodified lines88 ),89 sdkVersion: "0.0.0",90 }) satisfies ConfigBundle;91 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- */92+/** The folder has no config-folder segment on disk; the bundle's keys get it. */93 export const folder = (name: string) =>94 Effect.gen(function* () {95 const fs = yield* FileSystem.FileSystem;96 const path = yield* Path.Path;16 unmodified lines113 114 return bundleOf(files);115 });116 136-/** A project module that exports the defaults as config: a base to vary. */117 export const baseProject = Effect.map(118 Schema.encodeEffect(PolicyInput)({ ...defaultPolicyInput, source: "config" }),119 (encoded) => `export default ${JSON.stringify(encoded)};\n`120 );modified:packages/sdk/src/check.ts+5 added-29 removed
1-/**2- * Builders for an ask's check and for a ratchet's measure. Each checks its3- * input against protocol's schema at the call and returns plain data.4- */1 import {2 CheckSpec,3 RatchetMeasure as Measure,4 } from "@repo/protocol/domain/check";5 import { Schema, Struct } from "effect";6 7 type CheckSpecEncoded = typeof CheckSpec.Encoded;8 13-/**14- * An ask's check as the config folder states it: plain data, by check kind.15- * `CheckSpecInput<"RedThenGreen">` narrows it to one check kind.16- */9+/** `CheckSpecInput<"RedThenGreen">` narrows it to one check kind. */10 export type CheckSpecInput<11 Tag extends CheckSpecEncoded["_tag"] = CheckSpecEncoded["_tag"],12 > = Extract<CheckSpecEncoded, { readonly _tag: Tag }>;13 21-/** How a ratchet measures its number, as plain data: a lint count, or a number in a command's JSON. */14 export type RatchetMeasure = typeof Measure.Encoded;15 16 const { LintToZero, Migrate, Ratchet, RedThenGreen } = CheckSpec.cases;17 18 const { Count, Metric } = Measure.cases;19 28-// Each case's fields without its tag: what a builder checks before it makes29-// the case, so a malformed input fails with a Schema issue at the call.20 const lintToZeroFields = Schema.Struct(21 Struct.omit(LintToZero.fields, ["_tag"])22 );23 8 unmodified lines32 const countFields = Schema.Struct(Struct.omit(Count.fields, ["_tag"]));33 34 const metricFields = Schema.Struct(Struct.omit(Metric.fields, ["_tag"]));35 46-/** The builders for an ask's check, one per check kind, and for a ratchet's measure. */36 export const check = {48- /**49- * A lint rule's count goes to zero: red while `command` (the project's own50- * lint, with JSON output) reports `rule` on main.51- */37+ /** A lint rule's count goes to zero: red while `command` (the project's lint, as JSON) reports `rule` on main. */38 lintToZero: (rule: string, command: string): CheckSpecInput<"LintToZero"> =>39 Schema.encodeSync(LintToZero)(40 LintToZero.make(Schema.decodeSync(lintToZeroFields)({ command, rule }))41 ),56- /**57- * Every use of `from` moves to `to` (or is gone, without `to`). `count` is58- * the project's own command that prints `{"total": n, "byModule": {...}}`.59- */42+ /** Every use of `from` moves to `to`; `count` prints `{"total": n, "byModule": {...}}`. */43 migrate: (spec: {44 readonly count: string;45 readonly from: string;46 readonly to?: string;2 unmodified lines49 Migrate.make(Schema.decodeSync(migrateFields)(spec))50 ),51 /** Ratchets: a counted budget per territory that answers may lower and never raise. */52 ratchet: {70- /**71- * Counts lint findings in the project's own lint JSON output72- * (oxlint or ESLint), for one rule or for all.73- */53+ /** Counts findings in the project's own lint JSON output (oxlint or ESLint), for one rule or all. */54 count: (55 command: string,56 options?: { readonly rule?: string }57 ): RatchetMeasure =>58 Schema.encodeSync(Count)(59 Count.make(Schema.decodeSync(countFields)({ command, ...options }))60 ),81- /** The check of a ratchet ask: the named ratchet goes down. */61 down: (ratchet: string): CheckSpecInput<"Ratchet"> =>62 Schema.encodeSync(Ratchet)(63 Ratchet.make(Schema.decodeSync(ratchetFields)({ ratchet }))64 ),7 unmodified lines72 Schema.decodeSync(metricFields)({ command, path: options.path })73 )74 ),75 },97- /**98- * One check file fails on main by an assertion, and passes on the answer.99- * The run block's `test` command runs it, with `path` for `{path}`.100- */76+ /** One check file fails on main by an assertion and passes on the answer; `test` runs it with `path` for `{path}`. */77 redThenGreen: (path: string): CheckSpecInput<"RedThenGreen"> =>78 Schema.encodeSync(RedThenGreen)(79 RedThenGreen.make(Schema.decodeSync(redThenGreenFields)({ path }))80 ),1 unmodified linemodified:packages/sdk/src/checked.ts-5 removed
1 import { Schema } from "effect";2 3-/**4- * Checks config data against its schema at the call and gives it back5- * encoded, so a mistake in the config folder fails where it is written,6- * with a Schema issue the rules evaluator can report.7- */3 export const checked = <T, E>(schema: Schema.Codec<T, E>) => {4 const decode = Schema.decodeSync(schema);5 const encode = Schema.encodeSync(schema);6 2 unmodified linesmodified:packages/sdk/src/functions.ts+2 added-35 removed
1-/**2- * Function-valued rules: the few a project's process needs that data can't3- * say. A definition carries them beside its data, under a key that encoding4- * never meets, and says in its data which ones exist; the rules evaluator5- * calls them on demand, with facts the platform injects.6- */1 import { Ask } from "@repo/protocol/domain/ask";2 import { AskKind } from "@repo/protocol/domain/kind";3 import { Territory } from "@repo/protocol/domain/territory";4 import { Schema } from "effect";6 unmodified lines11 const KindName = AskKind.fields.name;12 13 const Module = Territory.fields.module;14 21-/** A count of landings on a person's record: never negative. */15 const LandingCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));16 24-/**25- * What an `opensAlone` rule is told about a proposal: who proposed it, for26- * which ask kind and territory, and the proposer's record there. The rule27- * sees these facts and nothing else: no clock, no network, no repo.28- */17+/** The rule sees these facts and nothing else: no clock, no network, no repo. */18 export const ProposalFacts = Schema.Struct({30- /** The ask kind the proposed ask is made from. */19 kind: KindName,32- /** The person who made the proposal. */20 proposer: Handle,21 /** The proposer's landings in the territory that stayed unreverted. */22 record: LandingCount,36- /** The proposed ask's territory, by module. */23 territory: Module,24 });25 26 export type ProposalFacts = typeof ProposalFacts.Type;3 unmodified lines30 * only when the kind's data can't say it: `(p) => p.record >= 3`.31 */32 export type OpensAlone = (proposal: ProposalFacts) => boolean;33 48-/**49- * What an `admit` rule is told about a person who wants to claim an ask:50- * who they are, the ask's kind and territory, their record there, and51- * whether the vouch file vouches for them.52- */34 export const ClaimantFacts = Schema.Struct({54- /** The person who wants to claim. */35 handle: Handle,56- /** The ask's kind. */36 kind: KindName,37 /** Their landings in the territory that stayed unreverted. */38 record: LandingCount,60- /** The ask's territory, by module. */39 territory: Module,62- /** Whether the vouch file vouches for them. */40 vouched: Schema.Boolean,41 });42 43 export type ClaimantFacts = typeof ClaimantFacts.Type;3 unmodified lines47 * say it: `(c) => c.vouched || c.record > 0`.48 */49 export type Admit = (claimant: ClaimantFacts) => boolean;50 74-/** A project's function-valued rules: absent ones are `undefined`. */51 export interface ProjectFunctions {52 readonly admit: Admit | undefined;53 readonly opensAlone: OpensAlone | undefined;54 }55 80-/** An ask kind's function-valued rule, which its asks carry too. */56 export interface KindFunctions {57 readonly opensAlone: OpensAlone | undefined;58 }59 2 unmodified lines62 * enumerable, so encoding, spreading or printing the data never meets them.63 */64 export const Functions: unique symbol = Symbol.for("@repo/sdk/Functions");65 91-/** Something that carries function-valued rules beside its data. */66 export interface WithFunctions<F> {67 readonly [Functions]: F;68 }69 96-/**97- * Puts function-valued rules beside a copy of `data`, where encoding never98- * meets them.99- */70 export const withFunctions = <A extends Readonly<Record<string, unknown>>, F>(71 data: A,72 functions: F73 ): A & WithFunctions<F> => {3 unmodified lines77 78 return carried;79 };80 111-/**112- * The function-valued rules a definition carries, for the rules evaluator113- * to call on demand: `functionsOf(definition).opensAlone?.(facts)`.114- */81+/** For the rules evaluator: `functionsOf(definition).opensAlone?.(facts)`. */82 export const functionsOf = <F>(definition: WithFunctions<F>): F =>83 definition[Functions];modified:packages/sdk/src/index.ts+1 added-7 removed
1-/**2- * What maintainers import in the config folder (its `project.ts`,3- * `asks/<id>.ask.ts` and `visibility.ts`, and a layer's `layer.ts`): object4- * literals and named helpers that evaluate to plain policy data. It runs5- * inside a network-off sandbox, so it reads no file, clock or randomness;6- * the rules evaluator does the rest.7- */1+// Runs inside a network-off sandbox, so it reads no file, clock or randomness.2 export { check, type CheckSpecInput, type RatchetMeasure } from "./check.ts";3 4 export {5 type Admit,83 unmodified linesmodified:packages/sdk/src/kind.ts+9 added-95 removed
1-/**2- * Ask kinds and the asks made from them: what the config folder's3- * `asks/<id>.ask.ts` exports by default.4- */1 import type { Brief } from "@repo/protocol/domain/ask";2 import { AskKind } from "@repo/protocol/domain/kind";3 import type {4 BriefField,10 unmodified lines15 import { withFunctions } from "./functions.ts";16 import type { KindFunctions, OpensAlone, WithFunctions } from "./functions.ts";17 import type { TerritoryInput } from "./territory.ts";18 23-/** An ask kind as data: what a project's policy lists. */19 export type AskKindInput = typeof AskKind.Encoded;20 21 type AskInputEncoded = typeof AskInput.Encoded;22 28-/**29- * An ask as its file states it: everything but its id and file, which come30- * from where the file sits, and who asked, which the platform knows.31- */23 export type AskStated = Omit<AskInputEncoded, "askedBy" | "file" | "id">;24 34-/**35- * An ask file's default export: the ask as its file states it, carrying its36- * kind's function-valued rule beside the data.37- */25 export type AskDefinition = AskStated & WithFunctions<KindFunctions>;26 40-/**41- * The fields every ask states, whatever its kind: its brief (`want` and42- * the optional `current`, `outOfScope`, `terms`, `context`), who it is held43- * for (`reserve`, `mentor`), and its place in a migrate family (`parent`,44- * `blockedBy`).45- */27 export type AskFields = typeof Brief.Encoded &28 Partial<Pick<AskInputEncoded, "blockedBy">> &29 Pick<AskInputEncoded, "mentor" | "parent" | "reserve">;30 50-/** Whether an ask states its territory, or its kind derives it from the args. */31 export type TerritoryMode = "derived" | "stated";32 33 type TerritoryField<Mode extends TerritoryMode> = Mode extends "derived"34 ? { readonly territory?: TerritoryInput }35 : { readonly territory: TerritoryInput };36 57-/**58- * A kind's args: config fields as Effect schemas that decode with no59- * services, `{ path: Schema.NonEmptyString }`.60- */37 export type ArgFields = Readonly<38 Record<PropertyKey, Schema.Constraint & { readonly DecodingServices: never }>39 >;40 65-/**66- * What an ask of a kind takes: the kind's args, the fields every ask states,67- * and its territory unless the kind derives it.68- */41 export type AskArgs<42 Args extends ArgFields,43 Mode extends TerritoryMode = "stated",44 > = Schema.Struct.Encoded<Args> & AskFields & TerritoryField<Mode>;45 74-/** Derives an ask's territory from its kind's args. */46 export type DeriveTerritory<Args extends ArgFields> = (47 args: Schema.Struct.Type<Args>48 ) => TerritoryInput;49 79-/**80- * An ask kind, as a maintainer declares it: a typed template for asks that81- * fixes the brief's args, the check kind, who may claim, and whether a82- * finish is required. Left out: claimers `"vouched"`, finish `"optional"`,83- * race 1, not one-way, strength `"assertion"`, and every ask needing its84- * want, check and territory.85- */50 export interface KindDefinition<51 Args extends ArgFields,52 K extends CheckKind = CheckKind,53 > {90- /** The args an ask of this kind takes, beyond the fields every ask states. */54 readonly args: Args;55 /** Builds an ask's check from its args; it must be of `checkKind`. */56 readonly check: (57 args: Schema.Struct.Type<Args>58 ) => CheckSpecInput<Capitalize<K>>;96- /** The check kind this kind's asks are judged by. */59 readonly checkKind: K;98- /** Who may claim an ask of this kind. */60 readonly claimers?: typeof ClaimRule.Encoded;61 /** Whether a decider's finish is never offered, optional, or required before landing. */62 readonly finish?: AskKindInput["finish"];102- /** The kind's name, as its asks and the policy name it: `fixBug`. */63 readonly name: string;64 /** Answers can't be undone by a later answer: judge changes, dependency changes. */65 readonly oneWay?: boolean;66 /** Whether a proposal for an ask of this kind opens without a decider. */67 readonly opensAlone?: OpensAlone;68 /** How many claims an ask takes at once; 1 is exclusive. */69 readonly race?: number;110- /** The brief's fields an ask of this kind must have. */70 readonly requires?: readonly BriefField[];71 /** How strong an ask's check must be: failing on main by an assertion, or also failing a null answer. */72 readonly strength?: AskKindInput["strength"];114- /** Derives an ask's territory from its args, so its asks need not state one. */73 readonly territory?: DeriveTerritory<Args>;74 }75 118-/**119- * An ask kind as the project lists it: its data, and its function-valued120- * rule beside it.121- */76 export interface DeclaredKind extends WithFunctions<KindFunctions> {123- /** The ask kind as data. */77 readonly askKind: AskKindInput;78 }79 127-/**128- * A declared ask kind. List it in `project({ kinds })`, and make an ask file129- * with `ask`: `export default fixBug.ask({ want, repro, territory })`.130- */80 export interface KindHandle<81 Args extends ArgFields,82 Mode extends TerritoryMode = "stated",83 > extends DeclaredKind {135- /**136- * An ask of this kind, as its file states it. The args are checked at the137- * call, so a malformed ask fails with a Schema issue.138- */84+ /** An ask of this kind; the args are checked at the call, so a malformed ask fails with a Schema issue. */85 readonly ask: (input: AskArgs<Args, Mode>) => AskDefinition;86 }87 88 const askKindOf = checked(AskKind);1 unmodified line90 const territoryOf = Schema.decodeUnknownSync(Territory);91 92 const encodeTerritory = Schema.encodeSync(Territory);93 148-/**149- * Declares an ask kind: a typed template for asks, which fixes the brief's150- * args, the check kind, who may claim, and whether a finish is required.151- */94 export interface KindBuilder {153- /** A kind that derives each ask's territory from its args, so its asks need not state one. */95 <const Args extends ArgFields, const K extends CheckKind>(96 definition: KindDefinition<Args, K> & {97 readonly territory: DeriveTerritory<Args>;98 }99 ): KindHandle<Args, "derived">;159- /** A kind whose asks each state their territory. */100 <const Args extends ArgFields, const K extends CheckKind>(101 definition: KindDefinition<Args, K>102 ): KindHandle<Args>;103 }104 105 /**166- * Declares an ask kind: a typed template for asks, which fixes the brief's167- * args, the check kind, who may claim, and whether a finish is required.168- * Its data is checked at the call, as an ask's args are, so a malformed169- * kind fails where it is written.170- * `kind({ name: "fixBug", args: { repro: Schema.NonEmptyString }, checkKind:171- * "redThenGreen", check: ({ repro }) => check.redThenGreen(repro) })`.106+ * Declares an ask kind, checked at the call: `kind({ name: "fixBug", args: {107+ * repro: Schema.NonEmptyString }, checkKind: "redThenGreen", check: ({ repro })108+ * => check.redThenGreen(repro) })`.109 */110 export const kind: KindBuilder = <111 const Args extends ArgFields,112 const K extends CheckKind,46 unmodified lines159 functions160 );161 };162 226-/** Where an ask file sits, and who asked: what the platform knows and the file doesn't. */163 export interface AskOrigin {228- /** The person credited with deciding the change was worth making. */164 readonly askedBy: string;230- /** The ask file's path in the repo: `<config folder>/asks/<id>.ask.ts`. */165 readonly file: string;166 }167 168 const askSuffix = ".ask.ts";169 236-/** An ask's id, from its file's name: `parse-iso-week.ask.ts` is `parse-iso-week`. */170 const askIdOf = (file: string): string => {171 const name = file.slice(file.lastIndexOf("/") + 1);172 173 return name.endsWith(askSuffix) ? name.slice(0, -askSuffix.length) : name;174 };175 243-/**244- * An ask file's data, for the rules evaluator: the ask its file states, with245- * its id and file from where the file sits, and who asked.246- */176 export const toAskInput = (177 definition: AskDefinition,178 origin: AskOrigin179 ): AskInputEncoded => ({4 unmodified lines184 });185 186 const path = { path: Schema.NonEmptyString };187 259-/**260- * The ask kinds a project gets without declaring any. Each is vouched-only261- * and exclusive; list the ones a project uses in `project({ kinds })`.262- */188+/** The ask kinds a project gets without declaring any; list the ones it uses in `project({ kinds })`. */189 export const kinds = {264- /**265- * Changes what judges answers (a check, lint or CI file), shown by a check266- * file that fails on main: one-way, and a decider finishes every answer.267- */190+ /** Changes what judges answers (a check, lint or CI file): one-way, and a decider finishes every answer. */191 changeJudge: kind({192 args: path,193 check: (args) => check.redThenGreen(args.path),194 checkKind: "redThenGreen",195 finish: "required",196 name: "changeJudge",197 oneWay: true,198 }),276- /**277- * A sentence and a check file that fails on main by an assertion; an278- * answer must pass it. A finish is optional.279- */199+ /** A sentence and a check file that fails on main by an assertion; an answer must pass it. */200 fix: kind({201 args: path,202 check: (args) => check.redThenGreen(args.path),203 checkKind: "redThenGreen",204 name: "fix",205 }),286- /**287- * A lint rule's count in the territory goes to zero, as the project's own288- * lint command reports it. Mechanical, so never finished.289- */206+ /** A lint rule's count in the territory goes to zero. Never finished. */207 lintToZero: kind({208 args: { command: Schema.NonEmptyString, rule: Schema.NonEmptyString },209 check: (args) => check.lintToZero(args.rule, args.command),210 checkKind: "lintToZero",211 finish: "never",212 name: "lintToZero",213 }),297- /**298- * Every use of one name moves to another: the parent of a migrate family,299- * whose steps answer it package by package. Never finished.300- */214+ /** Every use of one name moves to another, package by package. Never finished. */215 migrate: kind({216 args: {217 count: Schema.NonEmptyString,218 from: Schema.NonEmptyString,16 unmodified linesmodified:packages/sdk/src/project.ts+3 added-37 removed
1-/**2- * The config folder's `project.ts`: a project's process as one object3- * literal, and the defaults a project with no config folder runs on.4- */1 import { Brand } from "@repo/brand";2 import type { PolicyInput } from "@repo/protocol/domain/policy";3 import { Duration, Predicate } from "effect";4 import type { Types } from "effect";27 unmodified lines32 | "seconds"33 | "week"34 | "weeks"}`;35 40-/** A span in whole days or weeks, as config writes it: `"30 days"`, `"2 weeks"`. */36 export type Days = `${number} ${"day" | "days" | "week" | "weeks"}`;37 38 /**39 * What a vouch gates: claims and sealed answers (`forCode`), proposals too4 unmodified lines44 | undefined45 ? M46 : never;47 53-/** A ratchet by name: its measure, and the territory it counts, if only one. */48 export interface RatchetEntry {49 readonly measure: RatchetMeasure;56- /** The territory's module the ratchet counts. */50 readonly territory?: string;51 }52 60-/**61- * A project's process, as the config folder's `project.ts` writes it. Every key is62- * optional; one left out takes its default (`defaults` shows them all).63- */53+/** A project's process. Every key is optional; one left out takes its default (see `defaults`). */54 export interface ProjectConfig {55 /** A trust rule in code: whether a person may claim an ask. Called on demand. */56 readonly admit?: Admit;57 /** Whether landings carry `Assisted-by:` trailers for the agents people worked through. Default `"trailer"`. */12 unmodified lines70 readonly claims?: {71 readonly lapseAfter: Span;72 readonly warnAfter: Span;73 };84- /**85- * Who decides for which paths: a glob, and the handles of its deciders,86- * or `"owners"` for the person who made the project. Default `{ "**": "owners" }`.87- */74+ /** Who decides for which paths: a glob, and its deciders' handles or `"owners"`. Default `{ "**": "owners" }`. */75 readonly deciders?: Readonly<76 Record<string, readonly [string, ...string[]] | "owners">77 >;78 /** The ask kinds the project's asks are made from. Default `[kinds.fix]`. */79 readonly kinds?: readonly DeclaredKind[];93- /** Where the project's modules come from. Default and only: `territory.fromWorkspaces()`. */80 readonly modules?: ModulesInput;81 /** Ratchets, by name: `{ "no-explicit-any": check.ratchet.count("bun run lint --format json", { rule }) }`. */82 readonly ratchets?: Readonly<Record<string, RatchetEntry | RatchetMeasure>>;83 /** When a landing starts to count on a person's record, and for how long. Default `"30 days"`, `"365 days"`. */10 unmodified lines94 /** Markers this project counts as weakening a check, beyond the platform's own list. */95 readonly weakening?: { readonly markers: readonly string[] };96 }97 112-/**113- * A project file's default export: its process as policy data, with its114- * function-valued rules carried beside the data.115- */98 export type ProjectDefinition = PolicyInputEncoded &99 WithFunctions<ProjectFunctions>;100 101 type Settings = Pick<100 unmodified lines202 functions203 );204 };205 224-/**225- * Declares a project's process: the default export of the config folder's226- * `project.ts`.227- * Plain data, except `admit` and a kind's `opensAlone`, which are flagged228- * in the data and called on demand.229- */206+/** Declares a project's process: the default export of the config folder's `project.ts`. */207 export const project = (config: ProjectConfig): ProjectDefinition =>208 define(config, "config");209 233-/**234- * What a project with no config folder runs on: the `fix` kind, the run235- * block found from CI, the person who made the project deciding for every236- * path, 5 decisions a day that expire after 14 days, 2 open proposals and 3237- * claims a person, vouches for code, `Assisted-by:` trailers, and a record238- * that counts landings unreverted for 30 days over 365.239- */210 export const defaults: ProjectDefinition = define({}, "defaults");211 242-/**243- * A project file's data, for the rules evaluator: the policy it states,244- * without the function-valued rules, ready to encode as JSON.245- */212 export const toPolicyInput = (213 definition: ProjectDefinition214 ): PolicyInputEncoded => ({ ...definition });modified:packages/sdk/src/run.ts+1 added-9 removed
1-/**2- * The run block: the project's own commands, written out or found from CI.3- */1 import { FromCI } from "@repo/protocol/domain/policy";2 import type { RunBlock } from "@repo/protocol/domain/run";3 4 /** A test command, which names the one check file it runs with `{path}`: `bun test {path}`. */6 unmodified lines11 export type RunBlockInput = Omit<typeof RunBlock.Encoded, "test"> & {12 readonly test: TestCommand;13 };14 18-/** A project's run block: written out, or `run.fromCI`. */15 export type RunInput = RunBlockInput | typeof FromCI.Encoded;16 21-/** Where a project's run block comes from. */17 export const run = {23- /**24- * The run block the platform finds in the project's own scripts and CI25- * files, shown to the initializer to confirm. The default.26- */18+ /** The run block the platform finds in the project's scripts and CI, for the initializer to confirm. The default. */19 fromCI: FromCI.make({}),20 };modified:packages/sdk/src/territory.ts+4 added-20 removed
1-/**2- * Builders for an ask's territory, the module an answer may change, and for3- * where a project's modules come from.4- */1 import { Territory } from "@repo/protocol/domain/territory";2 import { Schema } from "effect";3 4 import { checked } from "./checked.ts";5 10-/** An ask's territory as the config folder states it: a module and its paths, as plain data. */6 export type TerritoryInput = typeof Territory.Encoded;7 8 /**14- * The placeholder a package territory's paths hold until the rules evaluator15- * writes the package's folder in from the workspaces it is told about, as a16- * run block's `{path}` waits for its file. Unfilled, it names no real17- * folder, so an answer is refused rather than let through.9+ * Filled in by the rules evaluator from the workspaces. Unfilled, it names no10+ * real folder, so an answer is refused rather than let through.11 */12 export const packageDir = "{dir}";13 21-/** Where a project's modules come from: its workspace packages, one module each. */14 export const FromWorkspaces = Schema.TaggedStruct("FromWorkspaces", {});15 24-/** Where a project's modules come from, as plain data. */16 export type ModulesInput = typeof FromWorkspaces.Encoded;17 18 const territoryOf = checked(Territory);19 29-/** The builders for a territory, and for a project's modules. */20 export const territory = {31- /**32- * Each workspace package is a module, and its `package.json` `exports` are33- * its public files. This is the only source of modules, and the default.34- */21+ /** Each workspace package is a module, its `exports` its public files. The default. */22 fromWorkspaces: (): ModulesInput => FromWorkspaces.make({}),36- /**37- * One workspace package, by its name: an answer may change any path in its38- * folder (`{dir}/**` until the evaluator fills the folder in).39- */23+ /** One workspace package, by its name: an answer may change any path in its folder. */24 package: (name: string): TerritoryInput =>25 territoryOf({ module: name, paths: [`${packageDir}/**`] }),26 /**27 * The escape hatch: exactly these globs, in a repo-wide module (`.`).5 unmodified linesmodified:packages/sdk/src/visibility.ts+8 added-54 removed
1-/**2- * The config folder's `visibility.ts`: a project's layers, its held-back3- * checks, how content flows between audiences, how long a narrowing waits,4- * and who may set write-only env values. And a layer's own manifest5- * (`layer.ts` in the layer repo's config folder), which alone names the6- * held-back checks' paths, each with the clause it enforces.7- *8- * Every builder returns plain data, checked against protocol's schema at the9- * call, so a mistake fails where it is written. The public file names areas,10- * kinds and rules only: what a `sealed` layer discloses.11- */1+// The public file names areas, kinds and rules only: what a `sealed` layer2+// discloses. Only a layer's own manifest names the held-back checks' paths.3 import {4 Layer,5 LayerManifest,6 SealedChecks,14 unmodified lines21 type VisibilityPolicyEncoded = typeof VisibilityPolicy.Encoded;22 23 type SealedChecksEncoded = typeof SealedChecks.Encoded;24 34-/** Who a rule names, as config writes it: `deciders`, or handles without `@`. */25 export type MembersInput = typeof Members.Encoded;26 37-/** The project's deciders, whoever they are at the landed commit. */27 export const deciders = "deciders" satisfies MembersInput;28 40-/**41- * A layer as a builder states it: everything but its name, which is its key42- * in `visibility({ layers })`, and its repo, which the platform makes.43- */29 export type LayerDefinition = Omit<typeof Layer.Encoded, "name" | "repo">;30 46-/** What a layer holds: one kind or more. */31 export type LayerHolds = readonly [LayerKind, ...LayerKind[]];32 49-/** A layer, as `layer()` takes it. */33 export interface LayerConfig<Holds extends LayerHolds = LayerHolds> {34 /** Who may read it. Default `"maintainers"`, the deciders' audience. */35 readonly audience?: Audience;36 /** What people outside its audience learn about what it holds. */37 readonly disclose: Disclosure;38 readonly holds: Holds;56- /** Who may clone it. */39 readonly readers?: MembersInput;58- /** Why it exists, in public. */40 readonly reason: string;41 /**42 * How long each kind it holds may stay unreleased: `{ experiment: "30 days" }`.43 * The protocol keeps one sunset a layer, so the layer takes the soonest.44 */45 readonly sunset?: Readonly<Partial<Record<Holds[number], Days>>>;65- /** Who may push to it. */46 readonly writers?: MembersInput;47 }48 49 const LayerFields = Schema.Struct(Struct.omit(Layer.fields, ["name", "repo"]));8 unmodified lines58 59 return days.length === 0 ? {} : { sunsetDays: Math.min(...days) };60 };61 82-/**83- * Declares a layer: a separate repo holding one audience's files, overlaid84- * on main only where that audience may read. Its paths stay in the layer.85- */62+/** Declares a layer: a separate repo holding one audience's files. Its paths stay in the layer. */63 export const layer = <const Holds extends LayerHolds>(64 config: LayerConfig<Holds>65 ): LayerDefinition =>66 layerOf({39 unmodified lines106 "Each person's own agent and tool configuration, for them and their agents only",107 writers: deciders,108 });109 133-/**134- * Held-back checks as the public file states them: their areas by name and135- * code glob, never a check's path or name. `Area` is the areas' names, so a136- * layer's manifest can be held to them (`AreaOf`).137- */110 export type SealedChecksDefinition<Area extends string = string> = Omit<111 SealedChecksEncoded,112 "areas"113 > & { readonly areas: Readonly<Record<Area, string>> };114 115 const sealedChecksOf = checked(SealedChecks);116 117 /**146- * Declares the held-back checks: the layer holding them, each area's name147- * and the code it guards, how often an answer may fail them, and when a new148- * check joins the suite. An answer is judged by the suite pinned at its149- * claim; a failure tells it one bit per area, and the suite is committed to150- * in public by a salted SHA-256 Merkle root.118+ * Declares the held-back checks. An answer is judged by the suite pinned at119+ * its claim; a failure tells it one bit per area, and the suite is committed120+ * to in public by a salted SHA-256 Merkle root.121 */122 export const sealedChecks = <123 const Areas extends Readonly<Record<string, string>>,124 >(config: {28 unmodified lines153 }),154 areas: config.areas,155 });156 187-/** How content moves between audiences, as data. */157 export type FlowsDefinition = VisibilityPolicyEncoded["flows"];158 159 const flowsOf = checked(VisibilityPolicy.fields.flows);160 192-/** The flow rules. */161 export const flows = {162 /**163 * Nothing moves from a layer into a wider audience but a credited164 * release, by the people named. Default release: the deciders.3 unmodified lines168 }): FlowsDefinition =>169 flowsOf({ noWriteDown: true, release: options?.release ?? deciders }),170 };171 204-/** A project's `visibility.ts`, as `visibility()` takes it. */172 export interface VisibilityConfig<Area extends string = string> {206- /** Held-back checks: `sealedChecks({ areas })`. */173 readonly checks?: SealedChecksDefinition<Area>;174 /** Who may set a write-only env value. Default the deciders. */175 readonly env?: { readonly setters: MembersInput };176 /** Default `flows.noWriteDown()`. */177 readonly flows?: FlowsDefinition;212- /** The project's layers, by name. */178 readonly layers?: Readonly<Record<string, LayerDefinition>>;179 /** How long a change that narrows visibility waits before it lands. Default `"7 days"`. */180 readonly notice?: { readonly narrowing: Days };181 }182 218-/** A visibility file's default export: the policy it states, as data. */183 export type VisibilityDefinition<Area extends string = string> = Omit<184 VisibilityPolicyEncoded,185 "checks"186 > & { readonly checks?: SealedChecksDefinition<Area> };15 unmodified lines202 )203 )204 );205 242-/**243- * Declares a project's visibility: the default export of the config244- * folder's `visibility.ts`. A project without one is Open.245- */206+/** Declares a project's visibility: the default export of `visibility.ts`. A project without one is Open. */207 export const visibility = <Area extends string = never>(208 config: VisibilityConfig<Area>209 ): VisibilityDefinition<Area> => {210 const { checks } = config;33 unmodified lines244 : Definition extends VisibilityDefinition<infer Area>245 ? Area246 : never;247 287-/** One held-back check as its layer's manifest lists it. */248 export type SealedCheckInput<Area extends string = string> = Omit<249 typeof SealedCheck.Encoded,250 "area"251 > & { readonly area: Area };252 293-/** A layer manifest's default export, as data. */253 export type LayerManifestDefinition = typeof LayerManifest.Encoded;254 255 const manifestOf = checked(LayerManifest);256 298-/**299- * Declares a layer's manifest: the default export of `layer.ts` in the300- * layer repo's config folder. Each held-back check's path, its area, the301- * clause of an ask or a doc it enforces, and its author; and the commits a302- * new check must fail on before it is admitted.303- */257+/** Declares a layer's manifest: the default export of `layer.ts` in the layer repo's config folder. */258 export const layerManifest = <Area extends string>(config: {259 readonly checks: readonly SealedCheckInput<Area>[];260 readonly knownBad?: readonly string[];261 readonly layer: string;6 unmodified linesmodified:packages/sdk/test/sdk.test.ts-1 removed
24 unmodified lines25 26 const redThenGreen = (path: string) =>27 RedThenGreen.make({ path: RedThenGreen.fields.path.make(path) });28 29-// A name a migrate moves from or to: `from` and `to` share one schema.29 const symbol = (name: string) => Migrate.fields.from.make(name);30 31 const askFile = (id: string) => `${Brand.configDir}/asks/${id}.ask.ts`;32 482 unmodified linesmodified:packages/sdk/test/visibility.test.ts-3 removed
20 unmodified lines21 const decodePolicy = Schema.decodeUnknownSync(VisibilityPolicy);22 23 const decodeManifest = Schema.decodeUnknownSync(LayerManifest);24 25-// One held-back check as a layer's manifest lists it.25 const exportCheck = {26 area: "export",27 author: "alice",28 clause: {3 unmodified lines32 },33 path: "checks/export/escapes-titles.test.ts",34 } as const;35 37-// A `visibility.ts` as the platform reads it: every default the38-// example leaves unsaid is filled, and nothing names a path or a check.36 const osrPolicy = {37 checks: {38 admit: { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 },39 areas: { export: "src/export/**", parser: "src/parser/**" },361 unmodified linesmodified:packages/testkit/src/clock.ts-8 removed
1-/**2- * Time for tests, on top of the TestClock `@effect/vitest`'s `it.effect`3- * provides. Like everything in `@repo/testkit`, this module is for `test/`4- * directories only: no `src/` imports it.5- */1 import { DateTime, Duration } from "effect";2 import type { Effect } from "effect";3 import { TestClock } from "effect/testing";4 10-/** An ISO 8601 instant, such as `2026-10-07T12:00:00Z`, as a UTC date-time. */5 export const at = (iso: string): DateTime.Utc =>6 DateTime.toUtc(DateTime.makeUnsafe(iso));7 14-/** The instant every scenario starts at unless it is given another. */8 export const defaultNow: DateTime.Utc = at("2026-10-07T12:00:00Z");9 10 /**11 * Moves the TestClock to an instant, waking everything that sleeps until then:1 unmodified line13 */14 export const advanceTo = (iso: string): Effect.Effect<void> =>15 TestClock.setTime(DateTime.toEpochMillis(at(iso)));16 24-/** `n` hours, the unit claims are warned and lapsed in. */17 export const hours = (n: number): Duration.Duration => Duration.hours(n);modified:packages/testkit/src/fake-artifacts-binding.ts+6 added-60 removed
1 /**2- * A fake of the Workers `Artifacts` binding over a repo host, for tests of3- * code that takes the binding. It keeps the surprises the spikes found in the4- * real one:2+ * Keeps the surprises found in the real binding: codeless `Error`s under3+ * `wrangler dev`, a fork's 500-then-409 under load, reads that resolve short4+ * branch names and commit ids only, `info().lastPushAt` staying `null`, and5+ * rate-limited reads (ASSUMPTION: the refusal names the limit in its message;6+ * no live one has been seen yet).7 *6- * - under `wrangler dev`, errors arrive as plain `Error`s with no `code`:7- * pass `{ codeless: true }`;8- * - under load, a fork answers HTTP 500 after making the repo, and the retry9- * answers 409: pass `{ forkFailures: n }`;10- * - reads by ref resolve short branch names and commit ids only, never11- * `refs/heads/main`;12- * - `info().lastPushAt` stays `null` after pushes;13- * - past 2,000 requests per 10 s a repo's reads are refused as rate limited:14- * pass `{ rateLimited: n }` to refuse the next `n` reads (ASSUMPTION: the15- * refusal names the limit in its message, as an HTTP 429's "Too Many16- * Requests" does; no live one has been seen yet).17- *8 * It takes its host structurally (`HostLike`), so `@repo/testkit` depends on19- * no adapter package: a `RepoHost` service value satisfies `HostLike`. Each20- * call runs the host's Effect with `Effect.runPromise`, since the binding is21- * a promise API; this is a test double, in a package only tests import.22- *23- * Like everything in `@repo/testkit`, this module is for `test/` directories24- * only: no `src/` imports it.9+ * no adapter package.10 */11 import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";12 import {13 Data,8 unmodified lines22 import { constVoid } from "effect/Function";23 24 import { defaultNow } from "./clock.ts";25 41-/** A git object id, branded as `@repo/artifacts`' `ObjectId` is. */26 export const ObjectId = Schema.String.pipe(27 Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),28 Schema.brand("ObjectId")29 );30 31 export type ObjectId = typeof ObjectId.Type;32 49-/** A short branch name, branded as `@repo/artifacts`' `BranchName` is. */33 export const BranchName = Schema.String.pipe(34 Schema.check(35 Schema.isPattern(36 /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u3 unmodified lines40 );41 42 export type BranchName = typeof BranchName.Type;43 61-/** Where a read starts, as `@repo/artifacts`' `Revision` has it. */44 export type Revision = Data.TaggedEnum<{45 Branch: { readonly name: BranchName };46 Commit: { readonly sha: CommitSha };47 }>;48 49 export const Revision = Data.taggedEnum<Revision>();50 69-/** What a host fails with: `RepoHost`'s errors, by shape. */51 export type HostError =52 | { readonly _tag: "RepoNotFound"; readonly name: RepoName }53 | { readonly _tag: "RepoExists"; readonly name: RepoName }54 | { readonly _tag: "ForkInProgress"; readonly name: RepoName }31 unmodified lines86 readonly name: string;87 readonly remote: string;88 }89 109-/**110- * The `RepoHost` methods the fake calls, by shape: the same parameters, with111- * the domain's ids, and results at least as wide. A `RepoHost` service value112- * is one.113- */90 export interface HostLike {91 readonly create: (name: RepoName) => Effect.Effect<HostCreated, HostError>;92 readonly importFrom: (93 name: RepoName,46 unmodified lines140 ) => Effect.Effect<readonly HostCommit[], HostError>;141 }142 143 export interface FakeOptions {168- /** Throw plain `Error`s with no `code`, as remote bindings under `wrangler dev` do. */144 readonly codeless?: boolean;170- /** How many forks fail with a 500 after making the repo, as under load. */145 readonly forkFailures?: number;172- /** Remotes are `<remoteBase>/<name>.git`, for a git server the test runs; else the host's. */146 readonly remoteBase?: string;174- /**175- * The default branch an import that names none reports, as the remote's176- * own: `master` for a remote like anyhow's. `main` when not given.177- */147 readonly defaultBranch?: string;148 /**149 * How many of a just-imported repo's first `get`s answer150 * `IMPORT_IN_PROGRESS`: an import Artifacts is still copying after151 * `import()` returned, as a large one is.152 */153 readonly importing?: number;185- /** How many of the next reads (a blob, a tree, a commit, a log) are refused as rate limited. */154 readonly rateLimited?: number;155 }156 189-/** A refusal the binding throws, before it becomes the thrown error. */157 class Refused extends Data.TaggedError("Refused")<{158 readonly code: ArtifactsError["code"];159 readonly reason: string;160 }> {}14 unmodified lines175 Match.when("INTERNAL_ERROR", () => numericCodes.INTERNAL_ERROR),176 Match.orElse(() => 0)177 );178 212-/** A host's error as the binding words it; a refusal stays as it is. */179 const refusalOf = (error: HostError | Refused) =>180 Match.valueTags(error, {181 ForkInProgress: ({ name }) =>182 new Refused({18 unmodified lines201 reason: `Repository not found: ${name}`,202 }),203 });204 239-/** The repos the fake made, with what `info()` and `list()` report. */205 interface Kept {206 readonly id: string;207 readonly name: RepoName;208 readonly description: string | null;17 unmodified lines226 const decodeBranch = Schema.decodeUnknownOption(BranchName);227 228 const decodePath = Schema.decodeUnknownOption(RepoPath);229 265-/**266- * `main` → that branch; 40 hex digits → that commit; anything else, such as267- * `refs/heads/main` or a tag, resolves to nothing.268- */230 const revisionOf = (ref: string): Option.Option<Revision> =>231 isObjectId(ref)232 ? Option.some(Revision.Commit({ sha: CommitSha.make(ref) }))233 : Option.map(decodeBranch(ref), (name) => Revision.Branch({ name }));14 unmodified lines248 name: entry.name,249 type: typeOf(entry),250 });251 291-// The times the host read from the commit itself, in Unix seconds.252 const metadataOf = (commit: HostCommit): ArtifactsCommitMetadata => ({253 author: { email: commit.author.email, name: commit.author.name },254 authoredAt: commit.authoredAt,255 committedAt: commit.committedAt,20 unmodified lines276 277 const blobOf = (bytes: Uint8Array) =>278 new Blob([bytes], { type: "application/octet-stream" });279 320-/** An Artifacts binding over `host`, with the real one's surprises (see the module's doc). */280 export const fakeArtifactsBinding = (281 host: HostLike,282 options: FakeOptions = {}283 ): Artifacts => {284 const kept = new Map<RepoName, Kept>();285 let forkFailures = options.forkFailures ?? 0;286 let rateLimited = options.rateLimited ?? 0;287 let made = 0;329- // Each imported repo's `get`s still to answer that the import runs on.288 const importing = new Map<RepoName, number>();289 332- /** The thrown error: an `ArtifactsError`, or a plain one when codeless. */290 const thrown = ({ code, reason }: Refused) =>291 options.codeless === true292 ? new Error(`ArtifactsError: ${reason}`)293 : Object.assign(new Error(reason), {1 unmodified line295 name: "ArtifactsError" as const,296 numericCode: numericOf(code),297 });298 342- /** Runs one call as the binding answers: a promise, rejected with its error. */299 const run = <A>(effect: Effect.Effect<A, Refused | HostError>) =>300 Effect.runPromise(301 Effect.mapError(effect, (failure) => thrown(refusalOf(failure)))302 );303 348- /** What a read past the rate limit throws (see the module's doc). */304 const limited = () =>305 options.codeless === true306 ? new Error("ArtifactsError: Too many requests: rate limit exceeded")307 : Object.assign(new Error("Too many requests: rate limit exceeded"), {1 unmodified line309 name: "ArtifactsError" as const,310 numericCode: 0,311 });312 358- /** One read, refused while the scripted rate limit lasts. */313 const read = <A>(effect: Effect.Effect<A, Refused | HostError>) => {314 if (rateLimited > 0) {315 rateLimited -= 1;316 30 unmodified lines347 348 return repo;349 };350 397- /**398- * The fake's record of a repo the host has: the one it made, or a fresh one399- * for a repo made on the host directly. A repo the host lacks fails with400- * `RepoNotFound` and leaves no record, so `list()` never shows it.401- */351 const keptOf = (name: RepoName) =>352 host.remote(name).pipe(Effect.map(() => kept.get(name) ?? keep(name, {})));353 354 const mint = (name: RepoName, scope: "read" | "write", seconds: number) =>19 unmodified lines374 375 return { expiresAt, id: token.id, plaintext, scope: token.scope };376 });377 429- /** A new repo's result: its metadata, its remote and a day-long write token. */378 const createdOf = (repo: Kept) =>379 Effect.gen(function* () {380 const remote = yield* remoteOf(repo.name);381 const token = yield* mint(repo.name, "write", 86_400);7 unmodified lines389 token: token.plaintext,390 };391 });392 445- /** What `list()` shows of a repo; `info()` adds its remote. */393 const summaryOf = (repo: Kept): Omit<ArtifactsRepoInfo, "remote"> => ({394 createdAt: stamped,395 defaultBranch: repo.defaultBranch,396 description: repo.description,78 unmodified lines475 const ref = logOptions?.ref ?? "HEAD";476 const limit = Math.min(logOptions?.limit ?? 50, 1000);477 const offset = logOptions?.offset ?? 0;478 532- // `HEAD` is the repo's default branch.479 const at = revisionOf(480 ref === "HEAD" ? (yield* keptOf(name)).defaultBranch : ref481 );482 181 unmodified linesmodified:packages/testkit/src/git-client.ts-5 removed
1 unmodified line2 import { Effect } from "effect";3 import { init, writeBlob, writeCommit, writeTree } from "isomorphic-git";4 import type { FsClient, TreeEntry } from "isomorphic-git";5 6-/** Paths and their text, such as `[["src/a.ts", "v1"]]`. */6 export type Files = readonly (readonly [path: string, content: string])[];7 8 // Fixed, so the same files and parents always make the same commit id.9 const signature = {2 unmodified lines12 timestamp: 1_791_300_000,13 timezoneOffset: 0,14 };15 17-/**18- * A bare repo at `/client.git` in `fs` that tests build commits in and push19- * from. Its `source` is what `RepoHost.push` takes objects from.20- */16 export const gitClient = (fs: FsClient) =>17 Effect.gen(function* () {18 const source = { fs, gitdir: "/client.git" };19 63 unmodified linesmodified:packages/testkit/src/git.ts-3 removed
23 unmodified lines24 25 const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>26 bytes.pipe(Stream.decodeText(), Stream.mkString);27 28-/** Spawns a process and hands back its handle, for callers that feed stdin. */28 export const spawn = (29 command: string,30 args: readonly string[],31 options: ChildProcess.CommandOptions11 unmodified lines43 })44 )45 ).pipe(Effect.orDie);46 48-/** Runs git in `cwd` to the end; a failing git is a result, not an error. */47 export const git = (cwd: string, ...args: string[]) =>48 Effect.scoped(49 Effect.gen(function* () {50 const child = yield* spawn("git", args, { cwd });6 unmodified lines57 return { exitCode, stderr, stdout } satisfies Ran;58 })59 );60 63-/** Runs git and returns its trimmed output; a failing git fails the test. */61 export const gitOk = (cwd: string, ...args: string[]) =>62 Effect.flatMap(git(cwd, ...args), (ran) =>63 ran.exitCode === 064 ? Effect.succeed(ran.stdout.trim())4 unmodified linesmodified:packages/testkit/src/golden.ts+5 added-29 removed
1-/**2- * Golden git transcripts: git's output made the same on every run and every3- * machine, compared with a file under `test/golden/`.4- *5- * Like everything in `@repo/testkit`, this module is for `test/` directories6- * only: no `src/` imports it.7- */1 import { Brand } from "@repo/brand";2 import { Config, Context, Effect, FileSystem } from "effect";3 11-/**12- * Where golden files live: `test/golden`, from the package whose tests run13- * (vitest runs in the package's folder). A test about golden files14- * themselves points it at a temporary folder.15- */4 export const GoldenDir = Context.Reference<string>("testkit/GoldenDir", {5 defaultValue: () => "test/golden",6 });7 17 unmodified lines25 const lastRewrite = (line: string) =>26 line.split("\r").findLast((version) => version !== "") ?? "";27 28 /**41- * Git's output, the same on every run of the same push: without the eight42- * spaces git pads side-band lines with when stderr is not a terminal (and any43- * other trailing space), with temporary folders as `<tmp>`, full object ids as44- * `<sha>`, a local server's address as `<host>`, and each line rewritten with45- * carriage returns as a terminal leaves it.29+ * Without the spaces git pads side-band lines with when stderr is not a30+ * terminal, with temporary folders as `<tmp>`, object ids as `<sha>`, a local31+ * server as `<host>`, and each carriage-return line as a terminal leaves it.32 */33 export const normaliseGitOutput = (text: string): string =>34 text35 .split(/\r?\n/u)9 unmodified lines45 // Letters on either side make it another word, not the product's name:46 // the rule `brand:check` applies.47 const NAME = new RegExp(`(?<![a-z])${Brand.slug}(?![a-z])`, "giu");48 63-/**64- * The text as a golden file holds it: the product's config folder as65- * `<configDir>` and every other spelling of its name as `<brand>`, so no66- * golden file names the product (`brand:check`) and a renamed brand still67- * matches.68- */49+/** The product's name as placeholders, so no golden file names it (`brand:check`). */50 const unbranded = (text: string) =>51 text.replaceAll(Brand.configDir, "<configDir>").replaceAll(NAME, "<brand>");52 72-/** The lines that differ, as `- golden` and `+ actual`, in order. */53 const difference = (golden: string, actual: string) => {54 const was = golden.split("\n");55 const now = actual.split("\n");56 8 unmodified lines65 .flat()66 .join("\n");67 };68 89-/**90- * Compares `text` with `test/golden/<name>.txt`, and fails the test where91- * they differ. With `UPDATE_GOLDEN=1` it writes the file instead, folders92- * and all: run the package's tests that way once, then read the diff.93- */69+/** With `UPDATE_GOLDEN=1` it writes the file instead: run the tests that way once, then read the diff. */70 export const expectGolden = (71 name: string,72 text: string73 ): Effect.Effect<void, never, FileSystem.FileSystem> =>36 unmodified linesmodified:packages/testkit/src/http-backend.ts+2 added-14 removed
29 unmodified lines30 31 return -1;32 };33 34-/** A CGI reply (`Status:` and headers, a blank line, the body) as a Response. */34 const fromCgi = (output: Uint8Array) => {35 const cut = blankLine(output);36 const head = new TextDecoder().decode(output.slice(0, Math.max(cut, 0)));37 const headers = new Headers();12 unmodified lines50 51 return new Response(output.slice(cut + 4), { headers, status });52 };53 55-/** `…/<repo>.git/info/refs` and the two service calls: what smart HTTP asks for. */54 const SMART_HTTP =55 /\/(?<repo>[^/]+)\.git\/(?<path>info\/refs|git-upload-pack|git-receive-pack)$/u;56 57 const notFound = () =>58 new Response("not a smart-HTTP git URL", { status: 404 });59 62-/**63- * Passes bytes and fails the stream on anything else: the Workers types leave64- * a request body's chunk type open.65- */60+/** The Workers types leave a request body's chunk type open. */61 const bytes = () =>62 new TransformStream<unknown, Uint8Array>({63 transform: (chunk, controller) => {64 if (chunk instanceof Uint8Array) {5 unmodified lines70 }71 },72 });73 79-/** A request's body as the CGI's stdin; a request without one gives none. */74 const stdinOf = (request: Request) => {75 const { body } = request;76 77 return body === null3 unmodified lines81 onError: (cause) => cause,82 }).pipe(Stream.orDie);83 };84 91-/**92- * `git http-backend` over the bare repos in `root`: a smart-HTTP server for93- * `…/<repo>.git/info/refs`, `…/git-upload-pack` and `…/git-receive-pack`,94- * whatever comes before the repo in the URL. It serves receive-pack too, and95- * reads no credentials: a test that wants a server to refuse them, or to stand96- * in for a reply, wraps this handler.97- */85+/** It reads no credentials: a test that wants a server to refuse them wraps this handler. */86 export const httpBackend =87 (root: string) =>88 (89 request: Request36 unmodified linesmodified:packages/testkit/src/scenarios.ts+2 added-56 removed
1-/**2- * Scenario builders: a project, its people and its policy as plain values,3- * built the same way every run. `aProject()` starts one; `withAsk`, `withKind`4- * and `withVouches` add to it in a pipe; `sixChildren()` is the migrate family5- * six agents claim at once.6- *7- * Values, not services: every builder is a pure function. None reads the8- * clock or randomness; time comes from `now` (default `2026-10-07T12:00:00Z`)9- * and ids from counters. Each value is decoded with the domain's own schema10- * as it is built, so a scenario the domain would refuse throws here.11- *12- * Like everything in `@repo/testkit`, this module is for `test/` directories13- * only: no `src/` imports it.14- */1+// Each value is decoded with the domain's own schema as it is built, so a2+// scenario the domain would refuse throws here.3 import { Brand } from "@repo/brand";4 import { Ask } from "@repo/protocol/domain/ask";5 import { CheckSpec } from "@repo/protocol/domain/check";6 import { Command, SymbolName } from "@repo/protocol/domain/common";14 unmodified lines21 import type { Types } from "effect";22 23 import { defaultNow } from "./clock.ts";24 37-/** An ask kind as a test writes it, before decoding. */25 export type AskKindEncoded = typeof AskKind.Encoded;26 40-/** A project at one landed commit, with the people a test acts as. */27 export interface Scenario extends Pipeable.Pipeable {28 readonly project: ProjectName;43- /** The person who made the project; the first decider. */29 readonly initializer: Handle;30 readonly policy: Policy;31 readonly landed: LandedSha;47- /** Everyone in the scenario by the name the test gave them, deciders first. */32 readonly people: ReadonlyMap<string, Handle>;49- /** When the scenario's asks opened. */33 readonly now: DateTime.Utc;34 }35 36 type ScenarioFields = Omit<Scenario, "pipe">;41 unmodified lines78 79 return word - low + mixed;80 };81 99-/** FNV-1a (32-bit) over the UTF-8 bytes of `text`, as eight hex digits. */82 const fnv1a = (text: string) => {83 let hash = 0x81_1c_9d_c5;84 85 for (const byte of new TextEncoder().encode(text)) {12 unmodified lines98 CommitSha.make(99 [0, 1, 2, 3, 4].map((round) => fnv1a(`${round}:${seed}`)).join("")100 );101 120-/** `prefix-000001`, `prefix-000002`, …: one counter per call of `ids()`. */102 const counter = (prefix: string) => {103 let next = 0;104 105 return () => {2 unmodified lines108 return `${prefix}-${String(next).padStart(6, "0")}`;109 };110 };111 131-/**132- * Fresh counters for the ids a project mints: `req-000001`, `prop-000001`,133- * `dec-000001`. Each call starts again at 1.134- */112 export const ids = () => {113 const request = counter("req");114 const proposal = counter("prop");115 const decision = counter("dec");38 unmodified lines154 const encodeTerritory = Schema.encodeSync(Territory);155 156 const encodeCheck = Schema.encodeSync(CheckSpec);157 181-/**182- * A project at its first landed commit: the defaults the config folder183- * leaves out, the kinds `fix` and `migrate`, and its deciders184- * (default `alice`) deciding everything. `people` are everyone else.185- */158 export const aProject = (159 options: {160 readonly name?: string;161 readonly now?: DateTime.Utc;47 unmodified lines209 project: ProjectName.make(name),210 });211 };212 241-/** `packages/parser` → its module `parser` and its paths `packages/parser/**`; `.` → the whole repo. */213 const territoryOf = (folder: string) =>214 decodeTerritory(215 folder === "."216 ? { module: ".", paths: ["**"] }2 unmodified lines219 paths: [`${folder}/**`],220 }221 );222 252-/** An ask as `withAsk` takes it. */223 interface AskOptions {224 readonly id: string;225 readonly territory: string;226 readonly kind?: string;257- /** Built with the domain's constructors: `CheckSpec.cases.LintToZero.make(…)`. */227 readonly check?: CheckSpec;228 readonly blockedBy?: readonly string[];229 readonly reserve?: "newcomers" | "people";261- /** The migrate ask this one is a step of. */230 readonly parent?: string;231 readonly want?: string;232 }233 266-/**267- * Opens `ask` over `territory` in the scenario, and records the territory as268- * a module when `module` says it is one.269- */234 const openAsk = (235 scenario: Scenario,236 ask: AskOptions,237 territory: Territory,40 unmodified lines278 modules: module && !known ? [...modules, territory] : modules,279 });280 };281 318-/**319- * Adds an open ask, asked by the initializer in the landed commit, and its320- * territory's module. The territory is a folder (`packages/parser`) or `.`321- * (the whole repo, which is no module: modules are workspaces); the kind322- * defaults to `fix`, the check to a `RedThenGreen` file in the territory, the323- * want to a sentence naming both.324- */282 export const withAsk =283 (ask: AskOptions) =>284 (scenario: Scenario): Scenario =>285 openAsk(scenario, ask, territoryOf(ask.territory), ask.territory !== ".");286 330-/** Adds an ask kind, in place of one with the same name. */287 export const withKind =288 (kind: AskKindEncoded) =>289 (scenario: Scenario): Scenario => {290 const added = decodeKind(kind);6 unmodified lines297 : [...kinds, added],298 });299 };300 345-/** Adds the vouch file's lines: `handles` vouched for, then `denounced`. */301 export const withVouches =302 (handles: readonly string[], denounced: readonly string[] = []) =>303 (scenario: Scenario): Scenario =>304 withPolicy(scenario, {10 unmodified lines315 })),316 ],317 });318 364-/** `legacyFetch` → `legacy-fetch`, `http.get` → `http-get`: a name an ask id can carry. */319 const words = (symbol: string) =>320 symbol321 .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower>-$<upper>")322 .toLowerCase()1 unmodified line324 .replaceAll(/^-|-$/gu, "");325 326 const packages = Arr.makeBy(6, (n) => `packages/p${n + 1}`);327 374-/** The six packages together: where a family's parent and delete child reach. */328 const allSix = decodeTerritory({329 module: ".",330 paths: Arr.map(packages, (folder) => `${folder}/**`),331 });332 380-/**381- * "Six agents claim six children": the project `burrow` with a382- * migrate ask `drop-<symbol>` over `packages/p1` … `packages/p6`, a child per383- * package (`drop-<symbol>-p1` …), each moving the symbol in its own package,384- * and a delete child (`drop-<symbol>-delete`) blocked by all six. The six385- * packages are the project's modules.386- */333 export const sixChildren = (334 options: { readonly symbol?: string; readonly to?: string } = {}335 ): Scenario => {336 const symbol = options.symbol ?? "legacyFetch";56 unmodified linesmodified:packages/testkit/src/untouchable.ts+3 added-9 removed
1 /**2- * A stand-in for a Workers binding, or any runtime object, handed to code a3- * test expects not to use it: every read throws and names the member, so the4- * test proves what a call touches (a fake env's bindings, a Worker's5- * context). The members `known` gives read as given. Symbols and `then` read6- * as absent: printing a value or resolving a promise with it is not a use.7- *8- * Like everything in `@repo/testkit`, this module is for `test/` directories9- * only: no `src/` imports it.2+ * Every read throws and names the member, so a test proves what a call3+ * touches. Symbols and `then` read as absent: printing a value or resolving a4+ * promise with it is not a use.5 */6 import { Predicate } from "effect";7 13-/** What reading `name.member` hit: a member the test did not give. */8 export class TouchedError extends Error {9 constructor(name: string, member: string) {10 super(`a test touched ${name}.${member}`);11 this.name = "TouchedError";25 unmodified linesmodified:packages/testkit/test/fake-artifacts-binding.test.ts-10 removed
20 unmodified lines21 readonly name: RepoName;22 readonly reason: string;23 }> {}24 25-/** What a promise of the binding threw. */25 class Thrown extends Data.TaggedError("Thrown")<{ readonly error: Error }> {}26 27 const commit = CommitSha.make("c".repeat(40));28 6 unmodified lines35 const hello = new TextEncoder().encode("hello\n");36 37 const answerer = { email: "answerer@example.com", name: "Answerer" };38 40-/** The one commit every repo holds on `main`. */39 const firstCommit = {40 author: answerer,41 authoredAt: 1_791_300_000,42 committedAt: 1_791_300_060,3 unmodified lines46 sha: commit,47 tree,48 };49 52-/**53- * A repo host as small as the fake needs: every repo holds one commit on54- * `main`, whose tree has `a.txt` ("hello") and a folder `src`.55- */50 const tinyHost = (): HostLike => {51 const repos = new Set<RepoName>();52 let minted = 0;53 88 unmodified lines142 revokeToken: (name) => known(name).pipe(Effect.as(true)),143 };144 };145 152-/** Awaits one of the binding's promises. */146 const call = <A>(run: () => Promise<A>) =>147 Effect.tryPromise({148 catch: (error) =>149 new Thrown({1 unmodified line151 }),152 try: run,153 });154 162-/** What one of the binding's promises threw, or an error saying it resolved. */155 const thrown = <A>(run: () => Promise<A>) =>156 call(run).pipe(157 Effect.match({158 onFailure: ({ error }) => error,3 unmodified lines162 163 const text = (bytes: Blob | null) =>164 bytes === null ? Effect.succeed(null) : call(() => bytes.text());165 174-/** An error as a plain record: its name and message, and its code and number if it has them. */166 const described = (error: Error) => ({167 code: "code" in error ? error.code : undefined,168 isError: error instanceof Error,169 message: error.message,170 name: error.name,171 numericCode: "numericCode" in error ? error.numericCode : undefined,172 });173 183-/** A binding over a fresh tiny host, with `datekit` made, and the repo `get` hands back. */174 const withDatekit = (175 options: Parameters<typeof fakeArtifactsBinding>[1] = {}176 ) =>177 Effect.gen(function* () {284 unmodified linesmodified:packages/testkit/test/golden.test.ts-6 removed
6 unmodified lines7 import { expectGolden, GoldenDir, normaliseGitOutput } from "../src/golden.ts";8 9 const id = "0123456789abcdef0123456789abcdef01234567";10 11-/**12- * One push of one fixed commit to a new bare repo, through a pre-receive hook13- * that prints what it received: git's whole stderr, as it printed it.14- */11 const pushOnce = Effect.gen(function* () {12 const fs = yield* FileSystem.FileSystem;13 const root = yield* fs.makeTempDirectoryScoped().pipe(Effect.orDie);14 const remote = `${root}/remote.git`;22 unmodified lines37 38 return yield* git(work, "push", remote, "HEAD:refs/heads/main");39 }).pipe(Effect.scoped);40 45-/** What a failed expectation says, or nothing when it passed. */41 const complaint = (exit: Exit.Exit<void>) =>42 Exit.isFailure(exit) ? String(Cause.squash(exit.cause)) : "";43 49-/** Runs with golden files in a fresh folder, and `UPDATE_GOLDEN` as given. */44 const inTempGoldens = <A, E, R>(45 update: string,46 run: (dir: string) => Effect.Effect<A, E, R>47 ) =>215 unmodified linesmodified:packages/visibility/src/env-schema/env-spec.ts+6 added-17 removed
1 /**2- * The parser seam's adapter over `@env-spec/parser` 0.6.1 (MIT; varlock's3- * format), pinned exactly: its API is 0.x. It reads the text into4- * plain data and nothing else. The parser's own expansion only rewrites5- * syntax (`$APP_ENV` becomes the call `ref(APP_ENV)`, `$(…)` the call6- * `exec(…)`); nothing here runs a call, loads a `@plugin` or follows an7- * `@import`, and this module imports nothing that could.2+ * Over `@env-spec/parser` 0.6.1, pinned exactly: its API is 0.x. The parser's3+ * own expansion only rewrites syntax (`$APP_ENV` becomes the call4+ * `ref(APP_ENV)`, `$(…)` the call `exec(…)`); nothing here runs a call, loads5+ * a `@plugin` or follows an `@import`, and this module imports nothing that6+ * could.7 *8 * A static `undefined` (`@sensitive=undefined`, `KEY=undefined`) is read as10- * absent, which is what varlock makes of it: a flag so set leaves the11- * default in place.9+ * absent, as varlock reads it: a flag so set leaves the default in place.10 */11 import {12 ParsedEnvSpecFunctionArgs,13 ParsedEnvSpecFunctionCall,23 unmodified lines37 ParsedNamedArg,38 ParsedValue,39 } from "../env-schema.ts";40 43-/** A value node of the parser's tree. */41 type ValueNode =42 | ParsedEnvSpecArrayLiteral43 | ParsedEnvSpecFunctionArgs44 | ParsedEnvSpecFunctionCall45 | ParsedEnvSpecObjectLiteral46 | ParsedEnvSpecStaticValue;47 51-/** A static value: text, a number, a flag, or none for `undefined`. */48 const staticOf = (49 node: ParsedEnvSpecStaticValue50 ): Option.Option<ParsedValue> => {51 const value: unknown = node.value;4 unmodified lines56 ? Option.some(value)57 : Option.none();58 };59 64-/** A node as plain data, never evaluated; none for a static `undefined`. */60 const valueOf = (node: ValueNode): Option.Option<ParsedValue> => {66- /** Arguments as written: the positional ones, then the `key=value` ones. */61 const argsOf = (62 values: readonly (63 | ParsedEnvSpecFunctionCall64 | ParsedEnvSpecKeyValuePair40 unmodified lines105 106 return Option.some(Array.getSomes(node.values.map(valueOf)));107 };108 115-/** The decorators as written, but those set to `undefined`. */109 const decoratorsOf = (110 decorators: readonly ParsedEnvSpecDecorator[]111 ): readonly ParsedDecorator[] =>112 Array.getSomes(4 unmodified lines117 )118 )119 );120 128-/** The text of an item's value, if it has one: `KEY=` and `KEY=undefined` have none. */121 const valueTextOf = (item: ParsedEnvSpecConfigItem): Option.Option<string> => {122 const { value } = item;123 124 if (value === undefined) {4 unmodified lines129 ? Option.map(staticOf(value), String)130 : Option.some(value.toString());131 };132 141-/** One item: its key, its description comment, its decorators, its value's text. */133 const itemOf = (item: ParsedEnvSpecConfigItem): ParsedItem => {134 const parsed: Types.Mutable<ParsedItem> = {135 decorators: decoratorsOf(item.decoratorsArray),136 key: item.key,11 unmodified lines148 149 return parsed;150 };151 161-/** Where the parser stopped, as its syntax errors carry it. */152 const Stopped = Schema.Struct({153 location: Schema.Struct({154 start: Schema.Struct({ column: Schema.Int, line: Schema.Int }),155 }),156 });157 168-/** Why a text is not a schema: where it stops parsing, never the text itself. */158 const unreadable = (file: RepoPath, cause: unknown) =>159 new EnvSchemaUnreadable({160 file,161 reason: Option.match(Schema.decodeUnknownOption(Stopped)(cause), {21 unmodified linesmodified:packages/visibility/src/env-schema/memory.ts-5 removed
1-/**2- * The parser seam's fake: `.env.schema` files already parsed, by path. It3- * reads no text; the imports each header names are checked and recorded4- * by the same rule the real parser follows (`withImports`).5- */1 import type { RepoPath } from "@repo/protocol/ids";2 import { Effect, Layer } from "effect";3 4 import {20 unmodified linesmodified:packages/visibility/src/vault/webcrypto.ts+5 added-28 removed
1-/**2- * Write-only values sealed through WebCrypto, so the same code runs in3- * workerd and in Node (envelope-encrypted in the DO).4- *5- * `put` makes a fresh AES-GCM-256 data key and a fresh 12-byte IV for each6- * value, seals the value under them, and wraps the data key with the7- * master key by AES-KW (RFC 3394, which checks the key's integrity on8- * unwrap). `open` unwraps and decrypts; nothing else here returns a value.9- * A sealed value is useless without `MASTER_KEY`.10- */1+// A fresh AES-GCM-256 data key and IV per value, the data key wrapped with the2+// master key by AES-KW (RFC 3394, which checks the key's integrity on unwrap).3 import { Effect, Layer, Option, Redacted, Schema } from "effect";4 5 import {6 admitLength,8 unmodified lines15 * be found and sealed again.16 */17 const KEY_VERSION = 1;18 27-/** AES-GCM's recommended IV size. */19 const IV_BYTES = 12;20 30-/** AES-256: the data key and the master key are 32 bytes each. */21 const KEY_BYTES = 32;22 23 /**24 * Values are padded to a multiple of this many bytes before sealing, so a1 unmodified line26 * falls in, not the length itself.27 */28 const PAD_TO = 64;29 40-/** The padding's first byte (ISO/IEC 7816-4): `0x80`, then zeros. */30 const PAD_MARK = 0x80;31 43-/** `MASTER_KEY` is not 32 bytes as 64 hex characters. Never names the key. */32 class MasterKeyUnusable extends Schema.TaggedError<MasterKeyUnusable>()(33 "MasterKeyUnusable",34 {}35 ) {}9 unmodified lines45 46 const decodeBase64 = (text: string) =>47 Effect.map(Schema.decodeEffect(Schema.Uint8ArrayFromBase64)(text), owned);48 61-/** The value's UTF-8 bytes, then `0x80`, then zeros to the next step. */49 const padded = (value: string) => {50 const bytes = new TextEncoder().encode(value);51 const out = new Uint8Array((Math.floor(bytes.length / PAD_TO) + 1) * PAD_TO);52 2 unmodified lines55 56 return out;57 };58 72-/** The bytes before the padding; none when the padding is not there. */59 const unpadded = (bytes: Uint8Array) => {60 const end = bytes.findLastIndex((byte) => byte !== 0);61 62 return end !== -1 && bytes[end] === PAD_MARK63 ? Option.some(bytes.subarray(0, end))64 : Option.none();65 };66 81-/** The master key's 32 bytes, decoded from its hex; a defect for any other form. */67 const masterKeyBytes = (masterKey: Redacted.Redacted) =>68 Schema.decodeEffect(Schema.Uint8ArrayFromHex)(Redacted.value(masterKey)).pipe(69 Effect.mapError(() => new MasterKeyUnusable()),70 Effect.filterOrFail(4 unmodified lines75 Effect.orDie76 );77 78 /**94- * The master key as an AES-KW key that can only wrap and unwrap, imported95- * for each call: WebCrypto's import is a promise, and the layer is built96- * where nothing may be awaited (the platform's router, at module load).79+ * Imported for each call: WebCrypto's import is a promise, and the layer is80+ * built where nothing may be awaited (the platform's router, at module load).81 */82 const importMasterKey = (bytes: Uint8Array<ArrayBuffer>) =>83 Effect.promise(() =>84 crypto.subtle.importKey("raw", bytes, "AES-KW", false, [1 unmodified line86 "unwrapKey",87 ])88 );89 106-/** A fresh data key, from WebCrypto's random bytes, extractable only to be wrapped. */90 const freshDataKey = Effect.sync(() =>91 crypto.getRandomValues(new Uint8Array(KEY_BYTES))92 ).pipe(93 Effect.flatMap((raw) =>2 unmodified lines96 ).pipe(Effect.ensuring(Effect.sync(() => raw.fill(0))))97 )98 );99 117-/** Seals `value` under a fresh data key, wrapped by `master`. */100 const seal = (master: CryptoKey, input: ValueToSeal) =>101 Effect.gen(function* () {102 yield* admitLength(input);103 28 unmodified lines132 wrappedKey: wrappedKeyText,133 } satisfies SealedValue;134 });135 154-/** Opens a sealed value; a defect naming the step that failed when it does not open. */136 const unseal = (master: CryptoKey, sealed: SealedValue) =>137 Effect.gen(function* () {138 if (sealed.keyVersion !== KEY_VERSION) {139 return yield* new SealedValueUnopenable({ step: "keyVersion" });46 unmodified lines186 ),187 });188 }).pipe(Effect.orDie);189 209-/**210- * Write-only values sealed under `masterKey` (the platform's `MASTER_KEY`:211- * 32 bytes as 64 hex characters, either case). A key of any other form is212- * a defect when the layer is built, and the defect never holds the key.213- */190+/** A key of any other form is a defect when the layer is built, and the defect never holds the key. */191 export const WriteOnlyValuesWebCrypto = (192 masterKey: Redacted.Redacted193 ): Layer.Layer<WriteOnlyValues> =>194 Layer.effect(16 unmodified linesmodified:packages/visibility/src/commitment.ts+2 added-29 removed
1 unmodified line2 import type { AreaName, BlobSha, RepoPath } from "@repo/protocol/ids";3 import { SuiteRoot } from "@repo/protocol/ids";4 import { Array, Effect, Option, Order } from "effect";5 6-/** One held-back check file: where it sits in its layer, its area, and its blob. */6 export interface SuiteFile {7 readonly path: RepoPath;8 readonly area: AreaName;9 readonly blob: BlobSha;6 unmodified lines16 const AREA = Uint8Array.of(0x02);17 18 const utf8 = (text: string) => new TextEncoder().encode(text);19 21-/**22- * SHA-256 of the parts joined, through WebCrypto, which the Workers and Bun23- * both have. Hashing bytes in memory cannot fail for a reason a caller could24- * handle, so a failure is a defect.25- */20 const sha256 = (...parts: readonly Uint8Array[]) =>21 Effect.promise(() =>22 crypto.subtle.digest(23 "SHA-256",38 unmodified lines62 LEAF_SEPARATOR,63 utf8(file.blob)64 );65 72-/** Each area's root as bytes, the areas sorted by name. */66 const roots = (salt: Uint8Array, files: readonly SuiteFile[]) =>67 Effect.forEach(68 Array.sort(new Set(files.map((file) => file.area)), Order.String),69 (area) =>8 unmodified lines78 Effect.map((root) => [area, root] as const)79 )80 );81 89-/**90- * Each area's commitment: the salted SHA-256 Merkle root of its files'91- * leaves, sorted by path. Without the salt, nobody can test a92- * guess at a check against it; with the same salt and files it is the same93- * root, in any order.94- */82+/** Without the salt, nobody can test a guess at a check against it. */83 export const areaRoots = (84 salt: Uint8Array,85 files: readonly SuiteFile[]86 ): Effect.Effect<ReadonlyMap<AreaName, SuiteRoot>> =>2 unmodified lines89 (areas) => new Map(areas.map(([area, root]) => [area, rootOf(root)]))90 )91 );92 105-/**106- * The whole suite's commitment: a Merkle root over each area's root under107- * its name, `H(0x02 ‖ area ‖ 0x00 ‖ area root)`, the areas sorted. It moves108- * when any file's content, path or area moves, or the salt does, so the109- * public sees that the suite changed and learns nothing of what it holds.110- */93+/** `H(0x02 ‖ area ‖ 0x00 ‖ area root)` per area, sorted: the public sees the suite changed and learns nothing of what it holds. */94 export const suiteRoot = (95 salt: Uint8Array,96 files: readonly SuiteFile[]97 ): Effect.Effect<SuiteRoot> =>17 unmodified lines115 )116 )117 );118 136-/**137- * The `Held-back:` trailer's value, without its key, as the trailer138- * machinery takes it: each area sorted by name, as `passed/total @ root`139- * when its checks ran in this run, or `n/a` when none did. None when no140- * area ran.141- */119 export const heldBackValue = (input: {120 readonly results: readonly HeldBackResult[];121 readonly areas: readonly AreaName[];122 }): Option.Option<string> => {24 unmodified lines147 ).join("; ")148 );149 };150 174-/**175- * The landing's `Held-back:` trailer, key and value:176- * `Held-back: export 7/7 @ sha256:…; parser n/a`. None when no area ran.177- */151 export const heldBackTrailer = (input: {152 readonly results: readonly HeldBackResult[];153 readonly areas: readonly AreaName[];154 }): Option.Option<string> =>1 unmodified linemodified:packages/visibility/src/env-schema.ts+7 added-44 removed
1-/**2- * The parser seam: the one place a project's `.env.schema` is3- * parsed, at a landed SHA. `@env-spec/parser` is reached only through an4- * adapter of this port (`./env-schema/env-spec`), with a fake5- * beside it (`./env-schema/memory`). Parsing reads text and nothing else: no6- * value expression is evaluated, no plugin is loaded, and no import outside7- * the repo is followed.8- */1+// Parsing reads text and nothing else: no value expression is evaluated, no2+// plugin is loaded, and no import outside the repo is followed.3 import { RepoPath } from "@repo/protocol/ids";4 import { Array, Context, Effect, Predicate, Result, Schema } from "effect";5 12-/**13- * A decorator's value as the schema writes it, never evaluated: text or a14- * number (`infer`, `sentry.io`), a flag (a bare `@required` is `true`), a15- * list (`[APP_ENV]`), a function call (`forEnv(production)`; a `$APP_ENV`16- * reference arrives as the call `ref(APP_ENV)`), or arguments alone (a bare17- * call's, `@proxy(domain="sentry.io")`, or an object's, `{preventLeaks=false}`).18- */6+/** Never evaluated; a `$APP_ENV` reference arrives as the call `ref(APP_ENV)`. */7 export type ParsedValue =8 | string9 | number10 | boolean11 | readonly ParsedValue[]12 | ParsedCall13 | ParsedArgs;14 27-/** One `key=value` argument. */15 export interface ParsedNamedArg {16 readonly key: string;17 readonly value: ParsedValue;18 }19 33-/** Arguments as written: the positional ones, then the `key=value` ones. */20 export interface ParsedArgs {21 readonly positional: readonly ParsedValue[];22 readonly named: readonly ParsedNamedArg[];23 }24 39-/** A function call, never run, and its text as written: `enum(development, test)`. */25 export interface ParsedCall extends ParsedArgs {26 readonly fn: string;27 readonly text: string;28 }29 45-/** One decorator: `@sensitive`, `@type=string(minLength=32)`, `@import(../shared/)`. */30 export interface ParsedDecorator {31 readonly name: string;32 readonly value: ParsedValue;33 }34 51-/** One item: its key, its description comment, its decorators, and its value text if it has one. */35 export interface ParsedItem {36 readonly key: string;37 readonly description?: string;38 readonly decorators: readonly ParsedDecorator[];39 readonly value?: string;40 }41 59-/**60- * A `.env.schema`, parsed: the header's decorators (above its `# ---`),61- * every item in order, and the files its `@import`s name, recorded and62- * never merged.63- */42 export interface ParsedEnvSchema {43 readonly header: readonly ParsedDecorator[];44 readonly items: readonly ParsedItem[];45 readonly imports: readonly string[];46 }47 70-/**71- * A `.env.schema` that cannot be read as one: it does not parse, or it72- * imports from outside the repo. Names the file and why, never a value.73- */48+/** Names the file and why, never a value. */49 export class EnvSchemaUnreadable extends Schema.TaggedError<EnvSchemaUnreadable>()(50 "EnvSchemaUnreadable",51 { file: RepoPath, reason: Schema.String }52 ) {}53 79-/** Parses a `.env.schema`'s text; reads nothing else. */54 export class EnvSchemaParser extends Context.Service<55 EnvSchemaParser,56 {57 readonly parse: (2 unmodified lines60 ) => Effect.Effect<ParsedEnvSchema, EnvSchemaUnreadable>;61 }62 >()("visibility/EnvSchemaParser") {}63 90-/** Whether a value is a function call as written (`forEnv(production)`). */64 export const isCall = (value: ParsedValue): value is ParsedCall =>65 Predicate.hasProperty(value, "fn");66 94-/** Whether a value is arguments alone: a bare call's or an object's. */67 export const isArgs = (value: ParsedValue): value is ParsedArgs =>68 Predicate.hasProperty(value, "named") && !isCall(value);69 98-/** Whether a value is a list as written (`[GET, POST]`). */70 export const isList = (value: ParsedValue): value is readonly ParsedValue[] =>71 Array.isArray(value);72 102-/** A path that starts outside any repo: the home folder, the root, a drive or a scheme (`C:`, `https:`). */73 const OUTSIDE = /^(?:~|[/\\]|[A-Za-z][\w+.-]*:)/u;74 105-/**106- * The repo path an `@import` names, resolved from the folder of the schema107- * that imports it; a reason when it names a place outside the repo. A108- * folder import (`../shared/`) keeps its trailing `/`.109- */75 const repoImport = (76 file: RepoPath,77 written: string78 ): Result.Result<RepoPath, string> => {24 unmodified lines103 );104 };105 106 /**142- * A parsed schema with the files its header's `@import`s name, as repo143- * paths, recorded and never merged. An import from outside the repo144- * (`~/…`, an absolute path, above the repo's root) makes the schema145- * unreadable: the platform never follows one. Both parsers end here, so146- * the rule is the same whichever reads the text.107+ * An import from outside the repo makes the schema unreadable: the platform108+ * never follows one. Both parsers end here, so the rule is the same whichever109+ * reads the text.110 */111 export const withImports = (112 file: RepoPath,113 parsed: Pick<ParsedEnvSchema, "header" | "items">21 unmodified linesmodified:packages/visibility/src/env-shape.ts+10 added-57 removed
1-/**2- * The env shape (ADR 0009): a project's `.env.schema`, parsed3- * through the parser seam, read the way varlock reads it, and never4- * resolved. Where the header is silent, items are required and sensitive,5- * as in varlock.6- */1+// Read the way varlock reads it, and never resolved. Where the header is2+// silent, items are required and sensitive, as in varlock.3 import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";4 import { EnvKey } from "@repo/protocol/ids";5 import type { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";6 import { Array, Option, Predicate, Schema } from "effect";7 unmodified lines14 ParsedItem,15 ParsedValue,16 } from "./env-schema.ts";17 22-/** The header's decorators, above its `# ---`. */18 type Header = ParsedEnvSchema["header"];19 25-/** The value of the named argument `key`, if the arguments carry one. */20 const namedArg = (args: ParsedArgs, key: string): Option.Option<ParsedValue> =>21 Option.map(22 Array.findFirst(args.named, (arg) => arg.key === key),23 ({ value }) => value24 );25 32-/**33- * The first of `decorators` named one of `names`: as in varlock, the first34- * flag written decides.35- */26+/** As in varlock, the first flag written decides. */27 const firstNamed = (28 decorators: readonly ParsedDecorator[],29 ...names: readonly string[]30 ): Option.Option<ParsedDecorator> =>31 Array.findFirst(decorators, ({ name }) => names.includes(name));32 42-/**43- * A flag and its opposite (`@required`/`@optional`): what the first one44- * written says, or `depends` when its value is anything but `true` or45- * `false` (`forEnv(production)`, `eq($A, b)`), which only the environment46- * decides.47- */33+/** `depends` when the flag's value is anything but `true` or `false`, which only the environment decides. */34 const flagOf = (35 decorators: readonly ParsedDecorator[],36 flag: string,37 opposite: string5 unmodified lines43 44 return name === flag ? value : !value;45 });46 61-/** The proxy rule the env shape holds: hosts, and what narrows them. */47 type Proxy = NonNullable<EnvItem["proxy"]>;48 64-/** Text, or a list of texts (`[GET, POST]`), as a list; none when it is anything else. */49 const textsOf = (value: ParsedValue): Option.Option<readonly string[]> => {50 const each = Predicate.isString(value) ? [value] : value;51 52 return isList(each) && each.every(Predicate.isString)15 unmodified lines68 Option.exists(textsOf(targets), (each) => each.includes("header")),69 });70 71 /**88- * One `@proxy(…)` rule: its hosts in order, and the path, method and89- * `block` that narrow it. None when it names no host as text (a host only90- * the environment decides gets no value). A rule the platform cannot honour72+ * None when it names no host as text. A rule the platform cannot honour73 * exactly is blocked rather than widened: one that waits on an `approval`,74 * carries `rules` for other paths, computes its credential with a75 * `transform`, keeps the value out of some headers (`substituteIn`), or has76 * a path or method that is not text.35 unmodified lines112 113 return Option.some(rule);114 });115 134-/** Whether the item is routed through `@proxy(…)`: any `@proxy` but `=passthrough` and `=omit`. */116 const isProxied = (item: ParsedItem): boolean =>117 item.decorators.some(118 ({ name, value }) =>119 name === "proxy" && value !== "passthrough" && value !== "omit"120 );121 122 /**142- * The item's `@proxy` rule: the outbound requests on which the platform143- * swaps its placeholder for its value. Rules that differ only in hosts144- * share one; a later rule that differs otherwise is left out, so the value145- * goes nowhere the shape doesn't show.123+ * Rules that differ only in hosts share one; a later rule that differs124+ * otherwise is left out, so the value goes nowhere the shape doesn't show.125 */126 export const proxyOf = (item: ParsedItem): Option.Option<Proxy> => {127 const rules = Array.getSomes(128 Array.map(item.decorators, ({ name, value }): Option.Option<Proxy> =>21 unmodified lines150 };151 });152 };153 175-/** The data types varlock builds in; none of them makes an item sensitive. */154 const builtInTypes = [155 "array",156 "boolean",157 "domain",24 unmodified lines182 183 return !builtInTypes.some((builtIn) => builtIn === type);184 });185 208-/**209- * `@sensitive` with options (`{enabled=forEnv(production), preventLeaks=false}`)210- * as the flag its `enabled` says, which is `true` when it says nothing.211- */186 const enabledOf = (decorator: ParsedDecorator): ParsedDecorator =>187 decorator.name === "sensitive" && isArgs(decorator.value)188 ? {189 name: decorator.name,3 unmodified lines193 ),194 }195 : decorator;196 223-/**224- * What the header's `@defaultSensitive` says of an item with no flag of its225- * own: `true` or `false`, or, under `inferFromPrefix(P)`, sensitive unless226- * its key starts with `P`. Anything else counts as sensitive.227- */197 const defaultSensitive = (key: string, value: ParsedValue): boolean => {198 if (Predicate.isBoolean(value)) {199 return value;200 }6 unmodified lines207 return !Predicate.isString(prefix) || !key.startsWith(prefix);208 };209 210 /**242- * Whether the item is sensitive: whether its value may be stored,243- * write-only, and never shown. Its own `@sensitive` or `@public` decides;244- * otherwise the header's `@defaultSensitive`, and a silent header means245- * sensitive. A flag only the environment decides counts as sensitive, and246- * so does an item whose `@type` only a plugin knows; an item routed through247- * `@proxy(…)` is sensitive whatever it says, as in varlock.211+ * A flag only the environment decides counts as sensitive, and so does an212+ * item whose `@type` only a plugin knows; an item routed through `@proxy(…)`213+ * is sensitive whatever it says, as in varlock.214 */215 export const isSensitive = (item: ParsedItem, header: Header): boolean =>216 isProxied(item) ||217 Option.match(flagOf(item.decorators.map(enabledOf), "sensitive", "public"), {5 unmodified lines223 }),224 onSome: (flag) => flag !== false,225 });226 261-/**262- * Whether the item must have a value. Its own `@required` or `@optional`263- * decides; otherwise the header's `@defaultRequired` (`infer`: required264- * when the schema gives it a value), and a silent header means required.265- * `depends` when the schema decides it with a function.266- */227 export const requiredOf = (228 item: ParsedItem,229 header: Header230 ): boolean | "depends" =>9 unmodified lines240 },241 })242 );243 284-/** A value as the schema writes it: `enum(development, test)`, `[GET, POST]`, `url`. */244 const textOf = (value: ParsedValue): string => {245 if (isCall(value)) {246 return value.text;247 }12 unmodified lines260 261 return String(value);262 };263 305-/** Every tag the item's `@tag(…)`s attach, in order, each once. */264 const tagsOf = (item: ParsedItem): readonly string[] =>265 Array.dedupe(266 item.decorators.flatMap(({ name, value }) =>267 name === "tag" && isArgs(value)4 unmodified lines272 : []273 )274 );275 318-/** The link of the item's first `@docs(url)` or `@docs(label, url)`. */276 const docsOf = (item: ParsedItem): Option.Option<string> =>277 Option.flatMap(firstNamed(item.decorators, "docs"), ({ value }) =>278 isArgs(value)279 ? Option.filter(Array.last(value.positional), Predicate.isString)280 : Option.none()281 );282 326-/** One item as the public sees it: its declaration, never a value. */283 const itemOf = (284 item: ParsedItem & { readonly key: EnvKey },285 header: Header286 ): EnvItem => {51 unmodified lines338 339 return shown;340 };341 386-/** An item the shape can name: its key is an env key (`PAYMENTS_KEY`). */342 const isNamed = (343 item: ParsedItem344 ): item is ParsedItem & { readonly key: EnvKey } => Schema.is(EnvKey)(item.key);345 391-/** The item `@currentEnv` names (`@currentEnv=$APP_ENV`), if it names one. */346 const currentEnvOf = (header: Header): Option.Option<EnvKey> =>347 Option.flatMap(firstNamed(header, "currentEnv"), ({ value }) => {348 const key =349 isCall(value) && value.fn === "ref" ? value.positional[0] : undefined;350 351 return Schema.is(EnvKey)(key) ? Option.some(key) : Option.none();352 });353 400-/** The env shape of one parsed `.env.schema` at a landed SHA. */354 export const envSchemaViewOf = (input: {355 readonly at: LandedSha;356 readonly file: RepoPath;357 readonly parsed: ParsedEnvSchema;22 unmodified linesmodified:packages/visibility/src/guards.ts+9 added-24 removed
3 unmodified lines4 import { LayerContentInPublicTree } from "@repo/protocol/refusal";5 import type { PrivatePathInPublicTree } from "@repo/protocol/refusal";6 import { Array, Option, Order } from "effect";7 8-/** The paths, once each and sorted, or none when there are none. */8 const named = (paths: readonly RepoPath[]) =>9 Array.match(Array.dedupe(Array.sort(paths, Order.String)), {10 onEmpty: Option.none,11 onNonEmpty: Option.some,12 });13 15-/** Files the answer puts into the public tree: added, or modified to a new blob. */14 const written = (changes: readonly Change[]) =>15 changes.filter((change) => change.status !== "deleted");16 17 /**20- * Stage 1's no-write-down guard by path, as the gate owns21- * it (`@repo/gate/stages/shape`'s `layerPathRefusal`), so the landing guard22- * and stage 1 hold one rule: the answer's public tree may hold no path from23- * any layer's path set, a path or a folder above it. A deletion never24- * triggers. The refusal is no oracle on which paths are layer paths: to a25- * pusher who cannot read the layer it names every path they added or26- * modified, all of them their own; only a reader hears exactly which ones27- * collide.28- *29- * `pusherCanRead` vouches for every layer whose paths are in `layerPaths`.30- * Paired with the paths of several layers, it is true only when the pusher31- * reads all of them: reading one layer must not name another's paths. Call32- * it once per layer, or with the union and `false`, when they read some.18+ * The same rule as stage 1 (`@repo/gate/stages/shape`'s `layerPathRefusal`).19+ * The refusal is no oracle: to a pusher who cannot read the layer it names20+ * every path they added or modified; only a reader hears which collide.21+ * `pusherCanRead` must hold for every layer in `layerPaths`: call it once per22+ * layer, or with the union and `false`, when they read some.23 */24 export const privatePaths: (input: {25 readonly changes: readonly Change[];26 readonly layerPaths: ReadonlySet<RepoPath>;27 readonly pusherCanRead: boolean;28 }) => Option.Option<PrivatePathInPublicTree> = layerPathRefusal;29 30 /**41- * The write-down guard by content (exact match only): a file the42- * answer adds, or modifies to a new blob, whose git blob id is a blob of the43- * layer. It runs only for someone who can read the layer, the only people44- * who could have copied from it; on anyone else it would be an oracle for45- * the layer's content, so it says nothing.46- *47- * `layerBlobs` holds the blobs of layers the answerer reads, and only48- * those: a blob of a layer they cannot read would make this the oracle it49- * refuses to be.31+ * It runs only for someone who can read the layer, the only people who could32+ * have copied from it; on anyone else it would be an oracle for the layer's33+ * content. `layerBlobs` holds the blobs of layers the answerer reads, and only34+ * those.35 */36 export const writeDown = (input: {37 readonly changes: readonly Change[];38 readonly layerBlobs: ReadonlySet<BlobSha>;14 unmodified linesmodified:packages/visibility/src/index.ts-5 removed
1-/**2- * Typed visibility: layers, sealed checks, the ledger, the env shape3- * and write-only values, as a cartridge the platform plugs in. Each module4- * is its own subpath too (`@repo/visibility/env-schema`).5- */1 export { EnvSchemaParser, EnvSchemaUnreadable } from "./env-schema.ts";2 3 export type {4 ParsedArgs,11 unmodified linesmodified:packages/visibility/src/layer-repos.ts+2 added-6 removed
1-/**2- * The private namespace's repos: every project's layer repos,3- * `<project>--<layer>`, behind a `RepoHost` of their own. The platform binds4- * it over `ARTIFACTS_PRIVATE`; code that asks for the public `RepoHost` is5- * never handed it, and no Worker that serves public pages binds it.6- */1+// Code that asks for the public `RepoHost` is never handed this one, and no2+// Worker that serves public pages binds it.3 import type { RepoHost } from "@repo/artifacts/repo-host";4 import { Context } from "effect";5 6 export class LayerRepos extends Context.Service<3 unmodified linesmodified:packages/visibility/src/leak-scan.ts+4 added-23 removed
30 unmodified lines31 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE32 // SOFTWARE.33 34 /**35- * The leak scan: whether a text, some bytes or36- * a stream holds a stored value, by exact match. It answers with the item's37- * key alone, never where the value was or what it was, so its answer cannot38- * help anyone guess a value. Values under `HARD_MIN_LENGTH` characters are39- * never looked for: they would match ordinary text everywhere.35+ * It answers with the item's key alone, never where the value was or what it36+ * was, so its answer cannot help anyone guess a value. Values under37+ * `HARD_MIN_LENGTH` characters are never looked for: they would match38+ * ordinary text everywhere.39 */40 import type { EnvKey } from "@repo/protocol/ids";41 import { Option, Redacted, Schema, Stream } from "effect";42 import type { Effect } from "effect";43 44 import { charactersIn, HARD_MIN_LENGTH } from "./vault.ts";45 47-/** A stored value to look for, and the item it belongs to. */46 export interface Watched {47 readonly key: EnvKey;48 readonly value: Redacted.Redacted;49 }50 53-/** One watched item and every form of its value the scan looks for. */51 interface Needle {52 readonly forms: readonly string[];53 readonly key: EnvKey;54 }55 59-/** Every value's forms, in the order the items were given, and the longest form. */56 interface Needles {57 readonly longest: number;58 readonly needles: readonly Needle[];59 }30 unmodified lines90 : [run, run.replaceAll("+", "-").replaceAll("/", "_")];91 });92 };93 98-/**99- * Every form a value takes where it commonly leaks: as itself, inside a100- * JSON string, URL-encoded as a URI component or a form field, and inside101- * base64 text. Each form once.102- */94 const formsOf = (value: string) => [95 ...new Set([96 value,97 JSON.stringify(value).slice(1, -1),2 unmodified lines100 ...base64Forms(value),101 ]),102 ];103 113-/** The forms of every value long enough to look for. */104 const needlesOf = (values: readonly Watched[]): Needles => {105 const needles = values.flatMap(({ key, value }) => {106 const text = Redacted.value(value);107 10 unmodified lines118 needles,119 };120 };121 132-/** The first watched item any form of whose value `text` contains. */122 const firstLeak = (text: string, { needles }: Needles) =>123 Option.fromUndefinedOr(124 needles.find(({ forms }) => forms.some((form) => text.includes(form)))125 ).pipe(Option.map(({ key }) => key));22 unmodified lines148 149 return 0;150 };151 163-/** The item whose stored value `text` holds, in any of its forms; none when it holds none. */152 export const scanText = (153 text: string,154 values: readonly Watched[]155 ): Option.Option<EnvKey> => firstLeak(text, needlesOf(values));156 169-/** As `scanText`, over bytes read as UTF-8 (bytes that are not text match nothing). */157 export const scanBytes = (158 bytes: Uint8Array,159 values: readonly Watched[]160 ): Option.Option<EnvKey> => scanText(new TextDecoder().decode(bytes), values);161 175-/**176- * As `scanText`, over a stream of byte chunks, read as UTF-8 in order. Each177- * chunk is scanned with the end of the text before it that could begin a178- * value, so a value split across any number of chunks is found. Stops at179- * the first leak.180- */162 export const scanStream = <E, R>(163 stream: Stream.Stream<Uint8Array, E, R>,164 values: readonly Watched[]165 ): Effect.Effect<Option.Option<EnvKey>, E, R> => {18 unmodified linesmodified:packages/visibility/src/ledger.ts+2 added-14 removed
16 unmodified lines17 onNone: (): readonly Layer[] => [],18 onSome: (policy) => policy.layers,19 });20 21-/**22- * A project's public ledger: every row the Project DO keeps, in23- * sequence order (the sort is stable, so nothing is dropped or reordered24- * under one number), the layers its config declares, and the posture25- * computed from that config and its licence.26- */21+/** The sort is stable, so nothing is dropped or reordered under one number. */22 export const ledgerOf = (input: {23 readonly project: ProjectName;24 readonly visibility: Option.Option<VisibilityPolicy>;25 readonly licence: Option.Option<string>;9 unmodified lines35 project: input.project,36 };37 };38 44-/** What the ledger records of a layer's declaration: what it holds and discloses. */39 const declared = (layer: Layer) =>40 `${layer.disclose}:${Array.sort(layer.holds, Order.String).join(",")}`;41 48-/**49- * The ledger entries a change to the visibility config writes, numbered50- * from `seq`: `LayerDeclared` for each layer the change adds, and again for51- * a layer whose kinds or disclosure it changes, sorted by layer name. A52- * layer that leaves writes nothing here; posture changes are decisions,53- * recorded where they are decided.54- */42+/** A layer that leaves writes nothing here; posture changes are decisions, recorded where they are decided. */43 export const entriesForPolicy = (44 before: Option.Option<VisibilityPolicy>,45 after: Option.Option<VisibilityPolicy>,46 seq: number,19 unmodified linesmodified:packages/visibility/src/posture.ts+2 added-20 removed
141 unmodified lines142 143 // Kinds whose files would ship: a layer holding one keeps shipped code closed.144 const SHIPPED: ReadonlySet<LayerKind> = new Set(["fix", "source"]);145 146-/**147- * A layer that narrows what the public sees: neither a personal layer, which148- * gates nothing, nor a public one, which everyone reads.149- */146 const narrowing = (layer: Layer) =>147 layer.audience !== "personal" && layer.audience !== "public";148 149 const ships = (layer: Layer) => layer.holds.some((kind) => SHIPPED.has(kind));4 unmodified lines154 const days = (count: number) => (count === 1 ? "1 day" : `${count} days`);155 156 const labelled = (posture: Posture, label: string) => ({ label, posture });157 162-/** The posture from the layers alone (the table's first four rows). */158 const fromLayers = (visibility: VisibilityPolicy) => {159 const layers = visibility.layers.filter(narrowing);160 const shipping = layers.filter(ships);161 28 unmodified lines190 : `Open with sealed evidence · sealed checks in ${sorted(areas)}`191 );192 };193 199-/**200- * A project's posture and the label it is shown as, computed from its201- * visibility config and its licence: Open; Open with sealed202- * evidence, naming the sealed areas; Open on schedule, naming the longest203- * embargo; Open core, naming the closed layers; Source available, under a204- * licence that is not OSI-approved, whatever the layers. `licence` is the205- * SPDX id or expression from the landed `LICENSE` or `package.json`; none206- * found leaves the layers to decide.207- */194+/** `licence` is the SPDX id or expression from the landed `LICENSE` or `package.json`; none found leaves the layers to decide. */195 export const postureOf = (input: {196 readonly visibility: Option.Option<VisibilityPolicy>;197 readonly licence: Option.Option<string>;198 }): { readonly posture: Posture; readonly label: string } =>3 unmodified lines202 onNone: () => labelled("open", "Open"),203 onSome: fromLayers,204 });205 219-// The postures, from Open down.206 const FURTHER_FROM_OPEN: readonly Posture[] = [207 "open",208 "openWithSealedEvidence",209 "openOnSchedule",210 "openCore",211 "sourceAvailable",212 ];213 228-/**229- * Whether moving from one posture to another narrows what the public sees.230- * Narrowing is a `PostureChange` decision with a notice period; widening is231- * a release (the posture's ratchet).232- */214+/** Narrowing is a `PostureChange` decision with a notice period; widening is a release. */215 export const narrows = (from: Posture, to: Posture): boolean =>216 FURTHER_FROM_OPEN.indexOf(to) > FURTHER_FROM_OPEN.indexOf(from);modified:packages/visibility/src/proxy.ts+3 added-21 removed
1-/**2- * The outbound map: what the Checker intercepts for each `@proxy`3- * item (the Checker hands each host to `interceptOutboundHttps`). A rule names a4- * host, the path and method a request must match, whether every request5- * is denied, the placeholder the process sees, and the item whose value6- * replaces it on the way out. Only `@sensitive` items hold values, so7- * `@proxy` on any other item maps to nothing.8- */1+// Only `@sensitive` items hold values, so `@proxy` on any other item maps to nothing.2 import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";3 import type { EnvKey } from "@repo/protocol/ids";4 import { Option, String } from "effect";5 13-/** One host whose requests the platform intercepts for one item. */6 export interface ProxyRule {15- /** Every request to the host is denied (`@proxy(block=true)`). */7 readonly block: boolean;17- /** A host as the schema writes it; a glob (`*.example.com`) stays one. */8 readonly host: string;19- /** The item whose value replaces the placeholder. */9 readonly key: EnvKey;21- /** The one method allowed; none allows any. */10 readonly method: Option.Option<string>;23- /** The path pattern allowed (`/api/**`); none allows any. */11 readonly path: Option.Option<string>;25- /** What the process sees in place of the value. */12 readonly placeholder: string;13 }14 15 /**30- * What unlanded code sees in place of an item's value: the item's own31- * `@placeholder`, or one made from its key alone (`__SENTRY_AUTH_TOKEN_PLACEHOLDER__`),32- * the same on every run and plainly not a real value. An empty33- * `@placeholder` counts as none, as in varlock's proxy: the gateway swaps34- * the placeholder for the value, and an empty one marks no place to swap.16+ * An empty `@placeholder` counts as none, as in varlock's proxy: the gateway17+ * swaps the placeholder for the value, and an empty one marks no place to swap.18 */19 export const placeholderFor = (item: EnvItem): string =>20 Option.fromUndefinedOr(item.placeholder).pipe(21 Option.filter(String.isNonEmpty),22 Option.getOrElse(() => `__${item.key}_PLACEHOLDER__`)23 );24 42-/** The rules for every `@sensitive` item's `@proxy`, one per domain, in the schema's order. */25 export const proxyMap = (26 schema: Pick<EnvSchemaView, "items">27 ): readonly ProxyRule[] =>28 schema.items.flatMap((item) => {17 unmodified linesmodified:packages/visibility/src/vault.ts+4 added-30 removed
1-/**2- * Write-only values (`writeOnly`): a decider sets a3- * value for a `@sensitive` item, and nobody reads it back, the decider and4- * the platform's contracts included. Each value is sealed under a random5- * data key, wrapped by the platform's `MASTER_KEY` (`./vault/webcrypto`).6- */1+// Nobody reads a write-only value back, the decider and the platform's2+// contracts included.3 import type { EnvKey } from "@repo/protocol/ids";4 import { ValueTooShort } from "@repo/protocol/refusal";5 import { Context, Effect, Redacted, Schema } from "effect";6 9 unmodified lines16 * for: below it a value matches ordinary text everywhere.17 */18 export const HARD_MIN_LENGTH = 3;19 24-/** Bytes as base64 text. */20 const Base64 = Schema.String.check(Schema.isBase64());21 27-/**28- * A value as the Project DO stores it: its ciphertext, the IV it was sealed29- * with, its data key wrapped by the master key, and which master key that30- * was. Nothing in it is the value.31- */22 export const SealedValue = Schema.Struct({23 ciphertext: Base64,24 iv: Base64,25 keyVersion: Schema.Int,1 unmodified line27 });28 29 export type SealedValue = typeof SealedValue.Type;30 41-/**42- * A sealed value that does not open: its master key is not this one, a43- * byte of it changed, or it names a key version this platform does not44- * hold. A defect, never a refusal: a stored row that will not open is the45- * platform's fault, and nothing about the value is in it.46- */31+/** A defect, never a refusal: a stored row that will not open is the platform's fault. */32 export class SealedValueUnopenable extends Schema.TaggedError<SealedValueUnopenable>()(33 "SealedValueUnopenable",34 { step: Schema.Literals(["keyVersion", "unwrap", "decrypt"]) }35 ) {}36 52-/** A value a decider sets for one item, and whether they accept a short one. */37 export interface ValueToSeal {38 readonly acknowledgeShort: boolean;39 readonly key: EnvKey;40 readonly value: Redacted.Redacted;8 unmodified lines49 */50 export const charactersIn = (value: string) =>51 [...graphemes.segment(value)].length;52 69-/**70- * Whether a value is long enough to seal. Under `MIN_LENGTH` it is refused71- * unless acknowledged; under `HARD_MIN_LENGTH` it is refused even then, and72- * the refusal says to set a longer one. A refusal names the minimum, never73- * the value or its length.74- */53+/** A refusal names the minimum, never the value or its length. */54 export const admitLength = ({55 acknowledgeShort,56 key,57 value,8 unmodified lines66 ? Effect.fail(ValueTooShort.of(key, MIN_LENGTH))67 : Effect.void;68 };69 91-/** Seals values, and opens one only for a landed run. */70 export class WriteOnlyValues extends Context.Service<71 WriteOnlyValues,72 {95- /**96- * Seals `value` for `key`. A short value is `ValueTooShort` unless the97- * decider acknowledged it; a very short one is refused even then.98- */73 readonly put: (74 input: ValueToSeal75 ) => Effect.Effect<SealedValue, ValueTooShort>;76 /** Opens a sealed value, for a landed run only; never behind a contract. */3 unmodified linesmodified:packages/visibility/test/fixtures/env/cases.ts+6 added-25 removed
1-/**2- * The env shape's fixtures: each `.env.schema` beside it as3- * committed, the structure the parser reads it as (what the `/memory` fake4- * holds), and the env shape it gives. The same fixtures run through both5- * parsers (`env-shape.test.ts`), and the adapter's reading of each text is6- * held to its structure (`env-spec-adapter.test.ts`), so the fake says what7- * the real parser says.8- *9- * Where varlock's own tests show its behaviour, an expectation cites the10- * test it mirrors (defaults must match), from the varlock clone at11- * `928e8e4b`, under `packages/varlock/src/env-graph/test/`.12- */1+// Where varlock's own tests show its behaviour, an expectation cites the test2+// it mirrors, from varlock@928e8e4b's `packages/varlock/src/env-graph/test/`.3 import type { EnvSchemaView } from "@repo/protocol/domain/env";4 import { RepoPath } from "@repo/protocol/ids";5 6 import type { ParsedEnvSchema } from "../../../src/env-schema.ts";7 unmodified lines14 import prefix from "./prefix.env.schema?raw";15 import proxy from "./proxy.env.schema?raw";16 import silentHeader from "./silent-header.env.schema?raw";17 28-/** The env shape a fixture gives, as the wire carries it, but for where and whose. */18 export type ExpectedView = Omit<19 typeof EnvSchemaView.Encoded,20 "at" | "file" | "project"21 >;22 34-/** `forEnv(production)`, as the parser reads it. */23 const forProduction = {24 fn: "forEnv",25 named: [],26 positional: ["production"],27 text: "forEnv(production)",28 };29 42-/** `$APP_ENV`, which the parser reads as the call `ref(APP_ENV)`. */30 const appEnv = {31 fn: "ref",32 named: [],33 positional: ["APP_ENV"],34 text: "ref(APP_ENV)",35 };36 50-/** `@proxy(domain="…", path="…")`, as the parser reads it. */37 const proxyTo = (domain: string, path: string) => ({38 name: "proxy",39 value: {40 named: [3 unmodified lines44 positional: [],45 },46 });47 62-/** One `.env.schema`: where it sits, its text, its parsed structure, and its env shape. */48 export interface EnvFixture {49 readonly title: string;50 readonly file: RepoPath;51 readonly text: string;260 unmodified lines312 "a flag only the environment decides counts as sensitive, and as depends for required",313 view: {314 currentEnvKey: "APP_ENV",315 imports: [],331- // ADR 0009: a function-valued flag fails safe. Where the332- // flag is static, varlock decides: sensitive-decorator.test.ts,333- // "enabled=false toggles the item to not sensitive" (OFF public, ON334- // sensitive) and "opts an item out of leak detection while keeping it335- // sensitive".316+ // A function-valued flag fails safe. Where the flag is static, varlock317+ // decides: sensitive-decorator.test.ts, "enabled=false toggles the item318+ // to not sensitive" (OFF public, ON sensitive) and "opts an item out of319+ // leak detection while keeping it sensitive".320 items: [321 { key: "APP_ENV", required: false, sensitive: false, tags: [] },322 {323 key: "SENTRY_AUTH_TOKEN",416 unmodified lines740 },741 },742 ];743 760-/** A `.env.schema` the platform refuses to read, and why. */744 export interface RefusedFixture {745 readonly title: string;746 readonly file: RepoPath;747 readonly text: string;748 readonly parsed: ParsedEnvSchema;749 readonly reason: string;750 }751 769-/** `API_KEY=` under a header that imports `path`, as the parser reads it. */752 const importing = (path: string): ParsedEnvSchema => ({753 header: [{ name: "import", value: { named: [], positional: [path] } }],754 imports: [],755 items: [{ decorators: [], key: "API_KEY" }],22 unmodified lines778 title: "an import from above the repo's root",779 },780 ];781 800-/** What the `/memory` fake holds: every fixture's parsed structure, by its file. */782 export const parsedByFile: ReadonlyMap<RepoPath, ParsedEnvSchema> = new Map(783 [...fixtures, ...refused].map(({ file, parsed }) => [file, parsed])784 );modified:packages/visibility/test/fixtures/env/raw.d.ts-4 removed
1-/**2- * What Vite gives these tests to read files as text: a `.env.schema`3- * fixture by `?raw` import, and source files by `import.meta.glob`.4- */1 declare module "*?raw" {2 const text: string;3 export default text;4 }13 unmodified linesmodified:packages/visibility/test/env-shape.test.ts-3 removed
16 unmodified lines17 const project = ProjectName.make("oscabriel/datekit");18 19 const at = LandedSha.make("a1".repeat(20));20 21-// The env shape (ADR 0009): a project's `.env.schema`,22-// parsed at a landed SHA through the parser seam and never resolved, as the23-// public sees it.21 const parsers = [22 ["the /memory fake", EnvSchemaParserMemory(parsedByFile)],23 ["the /env-spec adapter", EnvSchemaParserEnvSpec],24 ] as const;86 unmodified linesmodified:packages/visibility/test/env-spec-adapter.test.ts+3 added-8 removed
19 unmodified lines20 21 return yield* parser.parse(file, text);22 }).pipe(Effect.provide(EnvSchemaParserEnvSpec));23 24-/** The modules a source file imports, in order: static, side-effect, `import()` and re-exports alike. */24 const importsOf = (source: string | undefined) =>25 [26 ...(source ?? "").matchAll(27 /(?:\bfrom\s+|\bimport\s*\(\s*|^import\s+)["'](?<specifier>[^"']+)["']/gmu28 ),29 ].map((match) => match.groups?.specifier);30 32-/** The seam's own modules, as text. */31 const seam = import.meta.glob(32 ["../src/env-schema.ts", "../src/env-schema/env-spec.ts"],33 { eager: true, import: "default", query: "?raw" }34 );35 38-/** Where the parser's pinned 0.6.1 build lives, and its ES modules, as text. */36 const dist = "../node_modules/@env-spec/parser/dist/";37 38 const parserModules = import.meta.glob(39 ["../node_modules/@env-spec/parser/dist/*.mjs"],40 { eager: true, exhaustive: true, import: "default", query: "?raw" }41 );42 46-// The adapter over @env-spec/parser 0.6.1.43 describe("the /env-spec adapter", () => {44 // The /memory fake holds what this parser reads, so a test over the fake45 // says what the real parser says.46 it.effect.each(fixtures)(3 unmodified lines50 expect(yield* parse(file, text)).toStrictEqual(parsed);51 })52 );53 58- // datekit, as the env shape beat shows it: the Sentry token is59- // sensitive, required only in production, and sent only to sentry.io's60- // API; everything else is public.54+ // datekit: the Sentry token is sensitive, required only in production, and55+ // sent only to sentry.io's API; everything else is public.56 it.effect(57 "gives datekit's committed .env.schema the shape the demo shows",58 () =>59 Effect.gen(function* () {62 unmodified lines122 })123 );124 });125 131-// ADR 0009: the platform parses, never resolves.126+// The platform parses, never resolves.127 describe("the /env-spec adapter never evaluates", () => {128 it.effect(129 "reads $(…) and exec(…) as text, and the shape carries no value",130 () =>67 unmodified linesmodified:packages/visibility/test/guards.test.ts-1 removed
107 unmodified lines108 privatePaths({ changes, layerPaths, pusherCanRead: false })109 ).toStrictEqual(Option.none());110 });111 112- // A layer may name a folder in its path set: whatever sits under it is its.112 it("refuses a path under a folder in a layer's path set", () => {113 const changes: readonly Change[] = [added(sealed, blob("2"))];114 115 expect(139 unmodified linesmodified:packages/visibility/test/leak-scan.test.ts-4 removed
10 unmodified lines11 });12 13 const found = (key: string) => Option.some(EnvKey.make(key));14 15-/** A token-shaped value. */15 const sentry = "sntrys_eyJpYXQiOjE3MjA";16 18-/** A value every serialized form changes: a quote, a slash, a plus, a space. */17 const stripe = 'sk_live_51H"q/7+x Zr';18 19 const values = [20 watched("SENTRY_AUTH_TOKEN", sentry),5 unmodified lines26 const base64 = Schema.encodeSync(Schema.StringFromBase64);27 28 const base64Url = Schema.encodeSync(Schema.StringFromBase64Url);29 32-/** `text` as a stream of byte chunks, cut at the given byte offsets. */30 const chunked = (text: string, cuts: readonly number[]) => {31 const bytes = utf8(text);32 const bounds = [0, ...cuts, bytes.length];33 81 unmodified lines115 });116 117 it.live("scans 5 MB of text for 20 values in under a second", () =>118 Effect.gen(function* () {122- // A fixed Park–Miller generator, so the text is the same on every run.119 let state = 20_261_008;120 121 const draw = () => {122 state = (state * 48_271) % 2_147_483_647;121 unmodified linesmodified:packages/visibility/test/posture.test.ts-4 removed
68 unmodified lines69 const decode = Schema.decodeUnknownSync(VisibilityPolicy);70 71 const policy = (layers: readonly unknown[]) => decode({ ...config, layers });72 73-/** A policy whose maintainers layer holds the held-back checks. */73 const sealed = (layers: readonly unknown[]) =>74 decode({ ...config, checks: sealedChecks, layers });75 76 const mit = Option.some("MIT");3 unmodified lines80 81 const postureUnder = (licence: string) =>82 of(policy([]), Option.some(licence)).posture;83 85-// The posture table, one row at a time.84 describe("a project's posture", () => {85 it("is Open with no visibility config", () => {86 expect(87 postureOf({ licence: mit, visibility: Option.none() })7 unmodified lines95 posture: "open",96 });97 });98 101- // A public layer hides nothing from anyone, so it narrows nothing.99 it("is Open with a layer everyone may read", () => {100 expect(101 of(policy([{ ...enterprise, audience: "public", disclose: "public" }]))102 ).toStrictEqual({ label: "Open", posture: "open" });38 unmodified lines141 posture: "openCore",142 });143 });144 148- // Sponsorware is source that opens after a declared delay.145 it("is Open on schedule when the source layer opens within a declared delay", () => {146 expect(of(policy([{ ...enterprise, maxDays: 90 }]))).toStrictEqual({147 label: "Open on schedule · embargo ≤ 90 days",148 posture: "openOnSchedule",128 unmodified linesmodified:packages/visibility/test/proxy.test.ts-6 removed
9 unmodified lines10 import { placeholderFor, proxyMap } from "../src/proxy.ts";11 12 const item = Schema.decodeUnknownSync(EnvItem);13 14-/** datekit's one `@sensitive` item, behind `@proxy(domain="sentry.io", path="/api/**")`. */14 const sentryAuthToken = item({15 description:16 "Source-map upload token. Release step only; never enters a check.",17 key: "SENTRY_AUTH_TOKEN",2 unmodified lines20 sensitive: true,21 tags: ["release"],22 });23 25-/**26- * datekit's `.env.schema` as its env shape reads: `@defaultSensitive=false`27- * in the header, and one `@sensitive` item behind28- * `@proxy(domain="sentry.io", path="/api/**")`.29- */24 const datekit = {25 items: [26 item({27 key: "APP_ENV",153 unmodified linesmodified:packages/visibility/test/smoke.test.ts-2 removed
5 unmodified lines6 import { EnvSchemaParser } from "../src/env-schema.ts";7 import { LayerRepos } from "../src/layer-repos.ts";8 import { SealedValue, WriteOnlyValues } from "../src/vault.ts";9 10-// The skeleton's test: the ports the visibility package builds against.11-// The modules that fill them have their own tests beside this one.10 describe("the package", () => {11 it("is @repo/visibility", () => {12 expect(manifest.name).toBe("@repo/visibility");13 });45 unmodified linesmodified:packages/visibility/test/vault.test.ts-6 removed
19 unmodified lines20 WriteOnlyValues,21 } from "../src/vault.ts";22 import { WriteOnlyValuesWebCrypto } from "../src/vault/webcrypto.ts";23 24-// A fixed test master key and a second one, 32 bytes each as 64 hex25-// characters (the form the platform decodes `MASTER_KEY` in).24 const masterKey = WriteOnlyValuesWebCrypto(25 Redacted.make(26 "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF"27 )6 unmodified lines34 );35 36 const key = EnvKey.make("SENTRY_AUTH_TOKEN");37 40-/** A token-shaped value of 22 characters. */38 const token = "sntrys_eyJpYXQiOjE3MjA";39 40 const put = (value: string, acknowledgeShort = false) =>41 WriteOnlyValues.use((values) =>4 unmodified lines46 WriteOnlyValues.use((values) => values.open(sealed)).pipe(47 Effect.map((value) => Redacted.value(value))48 );49 53-/** The sealed value with one byte of `field` changed. */50 const tampered = (51 sealed: SealedValue,52 field: "ciphertext" | "iv" | "wrappedKey"53 ): SealedValue => {8 unmodified lines62 };63 64 const base64 = Schema.encodeSync(Schema.StringFromBase64);65 70-/** What an effect failed with: none when it succeeded. */66 const refusalOf = <A, E, R>(effect: Effect.Effect<A, E, R>) =>67 Effect.result(effect).pipe(Effect.map(Result.getFailure));68 74-/** The defect an effect died with. */69 const defectOf = <A, E>(exit: Exit.Exit<A, E>) =>70 Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;71 72 describe("write-only values over WebCrypto", () => {238 unmodified lines