Skip to content
Myr

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

71 files+168 added−1432 removed

modified:packages/rules/src/rules-evaluator/bun-main.ts+2 added-6 removed
modified:packages/rules/src/rules-evaluator/bun-prelude.ts+1 added-13 removed
modified:packages/rules/src/rules-evaluator/bun.ts+1 added-28 removed
25 unmodified lines
26import type { ConfigBundle } from "../rules-evaluator.ts";27import { bunMain } from "./bun-main.ts";28import { bunPrelude, clockVariable } from "./bun-prelude.ts";2930/** How the `/bun` adapter runs config code. */30export 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}4142// An import or export of the sdk by either of its names: the workspace one,
2 unmodified lines
45// can import nothing else by a bare name anyway.46const SDK_IMPORT =47 /(?<lead>\bfrom\s*|\bimport\s*\(?\s*)(?<quote>["'])(?:@repo\/sdk|@[a-z0-9][\w.-]*\/cli\/rules)\k<quote>/gu;4857/** Points every import of the sdk, by either name, at the module `sdk`. */49const pointSdkAt = (source: string, sdk: string) =>50 source.replaceAll(SDK_IMPORT, `$<lead>${JSON.stringify(sdk)}`);5161/** What the subprocess prints as its last line. */52const Output = Schema.TaggedUnion({53 Called: { result: Schema.Json },54 Collected: Collected.fields,55 Failed: {
5 unmodified lines
61type Output = typeof Output.Type;6263const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));6475/** A module the main imports: where it was written, and its path in the bundle. */65interface Written {66 readonly file: string;67 readonly path: string;68}6981/** What the main is asked to do: collect the folder's exports, or call a rule. */70interface Job {71 readonly asks: readonly Written[];72 readonly entry: string;73 readonly facts?: Schema.Json;
1 unmodified line
75 readonly rule?: string;76 readonly visibility?: Written;77}7891/** The frozen clock and seed the prelude installs. */79interface Clock {80 readonly now: string;81 readonly seed: number;82}
20 unmodified lines
103const resultLimit = 16 * 1024 * 1024;104105const logLimit = 64 * 1024;106120/** The last `limit` characters a stream prints; the rest is read and dropped. */107const 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 lines
117 ),118 Effect.map((kept) => kept.slice(-limit))119 );120135/** The project module, the visibility module and the ask files, as the main imports them. */121const modulesOf = (122 written: ReadonlyMap<string, string>,123 project: string | undefined,124 asks: readonly string[],
13 unmodified lines
138 ? withProject139 : { ...withProject, visibility: at(visibility) };140};141157/**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. */143export const rulesEvaluatorBun = (options: BunOptions = {}) =>144 Layer.effect(145 RulesEvaluator,146 Effect.gen(function* () {
18 unmodified lines
165166 const sdk =167 options.sdk ?? (yield* fromUrl(import.meta.resolve("@repo/sdk")));168192 /** 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 lines
188 )189 );190 };191216 /** 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 lines
278 ? { ...output, detail: clean(output.detail) }279 : output;280 });281307 /** 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 lines
381 });382 })383 );384411/** The `/bun` adapter with its defaults: `bun` on the `PATH`, a 5-second limit. */385export const RulesEvaluatorBun = rulesEvaluatorBun();
modified:packages/rules/src/rules-evaluator/json.ts+1 added-5 removed
modified:packages/rules/src/rules-evaluator/worker.ts+8 added-57 removed
18 unmodified lines
19import type { FrozenFacts } from "../prelude.ts";20import { factsOf, RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";21import type { ConfigBundle, RuleName } from "../rules-evaluator.ts";2223/**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 */23export type LoaderModule =24 | { readonly js: string }25 | { readonly json: Schema.Json }26 | { readonly text: string };2733/**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. */29export 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}3646/** A loaded worker's default entrypoint, as `Fetcher#fetch` serves it. */37export interface LoaderEntrypoint {38 readonly fetch: (39 url: string,40 init: { readonly body: string; readonly method: "POST" }41 ) => Promise<{ readonly text: () => Promise<string> }>;42}4354/** A loaded worker, as `WorkerStub#getEntrypoint` opens it. */44export interface LoadedWorker {45 readonly getEntrypoint: () => LoaderEntrypoint;46}4748/**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 */53export interface LoaderBinding {54 readonly get: (id: string, getCode: () => LoaderCode) => LoadedWorker;55}5669/** How the `/worker` adapter loads config code. */57export 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}6279/** What the loaded worker answers: the same results `/bun`'s main prints. */63const Output = Schema.TaggedUnion({64 Called: { result: Schema.Json },65 Collected: Collected.fields,66 Failed: {
5 unmodified lines
72type Output = typeof Output.Type;7374const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(Output));7593/** A request to the loaded worker: collect the folder's exports, or call a rule. */76type Job =77 | Readonly<Record<string, never>>78 | { readonly facts: Schema.Json; readonly rule: RuleName };79
21 unmodified lines
101// before the worker starts, so a syntax error anywhere in the folder102// rejects the request instead of reaching the main.103const WONT_START = /^Failed to start Worker\b/u;104123// A module the Loader imports as code.105const SCRIPT = /\.[cm]?[jt]s$/u;106107const loadFailed = (detail: string) =>108 new RulesFailed({ detail, reason: "load" });
9 unmodified lines
118119const messageOf = (cause: unknown) =>120 Predicate.isError(cause) ? cause.message : String(cause);121141/**142 * A rejection from the loaded worker: a module that won't compile, its CPU143 * limit spent, or its code threw.144 */122const thrownBy = (cause: unknown) => {123 const message = messageOf(cause);124 const detail = `the loaded worker: ${message}`;125
6 unmodified lines
132 reason: RAN_OUT.test(message) ? "timeout" : "threw",133 });134};135159/** Releases a stub the runtime handed out; one with no way to be released is left. */136const released = (stub: LoadedWorker | LoaderEntrypoint) =>137 Effect.try(() => {138 const dispose =139 Predicate.isSymbol(disposeKey) && Predicate.hasProperty(stub, disposeKey)
4 unmodified lines
144 dispose.call(stub);145 }146 }).pipe(Effect.ignore);147172/** Sends one job to a loaded worker's entrypoint, and decodes its answer. */148const requested = (entrypoint: LoaderEntrypoint, job: Job) =>149 Effect.tryPromise({150 catch: thrownBy,151 try: () =>
17 unmodified lines
169 )170 )171 );172198/**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 */173const isModulePath = (path: string) =>174 path !== mainName &&175 path !== preludeName &&176 path177 .split("/")178 .every((segment) => segment !== "" && segment !== "." && segment !== "..");179209/** Refuses a bundle with a path outside the folder, before any worker loads. */180const insideTheFolder = (bundle: ConfigBundle) => {181 const outside = Object.keys(bundle.modules).filter(182 (path) => !isModulePath(path)183 );
8 unmodified lines
192};193194const parsedJson = Schema.decodeOption(Schema.fromJsonString(Schema.Json));195226/**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. */197const moduleOf = (path: string, source: string): LoaderModule => {198 if (SCRIPT.test(path)) {199 return { js: source };200 }
14 unmodified lines
215 */216const workerIdOf = (bundle: ConfigBundle, at: string, clock: FrozenFacts) =>217 `rules:${at}:${bundle.sdkVersion}:${clock.now}:${clock.seed}`;218253/**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. */220export const RulesEvaluatorWorker = (221 loader: LoaderBinding,222 options: WorkerOptions = {}223) =>
5 unmodified lines
229 const cpuMs = options.cpuMs ?? 200;230 const timeoutMs = options.timeoutMs ?? 5000;231232 /**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 lines
258 modules,259 };260 };261307 /**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 lines
modified:packages/rules/src/config-folder.ts+3 added-57 removed
5 unmodified lines
6import { defaultPolicyInput } from "./defaults.ts";7import { RulesFailed } from "./rules-evaluator.ts";8import type { ConfigBundle } from "./rules-evaluator.ts";910// An ask file: `<id>.ask.ts`, or the `.js` a bundler writes for it.10const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;1113// A module that runs: TypeScript or JavaScript, not JSON or a vouch file.12const SCRIPT = /\.[cm]?[jt]s$/u;1316/**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. */15const folderOf = (bundle: ConfigBundle) =>16 bundle.entry.slice(0, bundle.entry.lastIndexOf("/") + 1);1724/** Where a committed policy stands in for the TypeScript (the fallback). */18export const policyJsonOf = (bundle: ConfigBundle) =>19 `${folderOf(bundle)}policy.json`;2028/** The bundle's project module, when it has one. */21export const projectModule = (bundle: ConfigBundle): string | undefined =>22 SCRIPT.test(bundle.entry) && Object.hasOwn(bundle.modules, bundle.entry)23 ? bundle.entry24 : undefined;2534// The visibility module: `visibility.ts`, or the `.js` a bundler writes for it.26const VISIBILITY_FILE = /^visibility\.[cm]?[jt]s$/u;2737/**38 * The bundle's visibility module (`<folder>/visibility.ts`), when it has39 * one: the project's layers and held-back checks.40 */28export const visibilityModule = (bundle: ConfigBundle): string | undefined => {29 const folder = folderOf(bundle);3031 return Object.keys(bundle.modules)
4 unmodified lines
36 VISIBILITY_FILE.test(path.slice(folder.length))37 );38};3953/** The bundle's ask files, in path order so evaluation is the same every time. */40export const askModules = (bundle: ConfigBundle): readonly string[] => {41 const asks = `${folderOf(bundle)}asks/`;4243 return Object.keys(bundle.modules)44 .filter((path) => path.startsWith(asks) && ASK_FILE.test(path))45 .toSorted();46};4762/** A decode failure, named by the file it came from. */48export const failedAt =49 (where: string) =>50 (failure: Schema.SchemaError): RulesFailed =>51 new RulesFailed({52 detail: `${where}: ${failure.message}`,53 reason: "decode",54 });5571/** A module whose default export is missing (or `null`) states nothing. */56const noDefault = (path: string, what: string) =>57 new RulesFailed({58 detail: `${path}: its default export is not ${what}`,59 reason: "decode",60 });6178/**79 * The policy a committed `policy.json` states, when the bundle has one. It80 * carries its asks inline.81 */62const fromPolicyJson = (63 bundle: ConfigBundle64): Effect.Effect<Option.Option<PolicyInput>, RulesFailed> => {65 const path = policyJsonOf(bundle);
8 unmodified lines
74 Effect.mapError(failedAt(path))75 );76};7798/**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. */79export const statedWithoutCode = (80 bundle: ConfigBundle81): Effect.Effect<PolicyInput, RulesFailed> =>82 Effect.map(
4 unmodified lines
87 : { ...defaultPolicyInput, source: "config" }88 )89 );90116/** What the config folder's modules exported, as data, read back from the sandbox. */91export 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});9697export type Collected = typeof Collected.Type;98127/**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 */99const 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});104137/**138 * A project module's data: its asks are the ask files, its source the139 * folder, and its visibility the visibility module's.140 */105const ProjectFile = PolicyInput.mapFields(106 Struct.omit(["asks", "source", "visibility"])107);108145/** An ask's id: its file's name less `.ask.ts`. */109const idOf = (path: string) =>110 path.slice(path.lastIndexOf("/") + 1).replace(ASK_FILE, "");111149/**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. */113const 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 lines
132 id,133 } satisfies AskInput;134 });135177/**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 */136const visibilityOf = (137 data: Schema.Json | undefined,138 path: string | undefined139): Effect.Effect<Option.Option<VisibilityPolicy>, RulesFailed> => {
10 unmodified lines
150 Effect.mapError(failedAt(where))151 );152};153200/**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 */154export 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 lines
modified:packages/rules/src/defaults.ts+1 added-12 removed
1import { PolicyInput } from "@repo/protocol/domain/policy";2import { defaults, toPolicyInput } from "@repo/sdk";3import { Schema } from "effect";45/**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. */6export 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.3import { Functions } from "@repo/sdk/functions";4import { Predicate } from "effect";5import type { Schema } from "effect";614/**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. */8export type Definition = Schema.Json;923/** A function-valued rule: called with the facts its caller passes. */10export type Rule = (facts: Schema.Json) => boolean | Promise<boolean>;1126/** One module's default export, by the module's path in the bundle. */12export interface Exported {13 readonly definition: Definition | undefined;14 readonly path: string;15}1632/** The modules' data, as the host reads it back (`Collected` there). */17export interface CollectedData {18 readonly asks: readonly {19 readonly ask: Schema.Json;20 readonly path: string;
1 unmodified line
22 readonly project?: Schema.Json;23 readonly visibility?: Schema.Json;24}2542/** A module with no default export gives `null`, which the host refuses. */26const dataOf = (definition: Definition | undefined): Schema.Json =>27 definition ?? null;2846/**47 * Collects the project module's data and the visibility module's (each when48 * the folder has one), and every ask's.49 */29export const collect = (30 project: Exported | undefined,31 asks: readonly Exported[],32 visibility?: Exported
14 unmodified lines
47};4849const isRule = (value: unknown): value is Rule => Predicate.isFunction(value);5072/**73 * The project definition's function-valued rule, when it has one: read74 * where the sdk keeps it (`functionsOf`), under its `Functions` symbol.75 */51export const ruleOf = (52 definition: Definition | undefined,53 rule: string54): Rule | undefined => {
12 unmodified lines
modified:packages/rules/src/finish.ts+8 added-35 removed
10 unmodified lines
11import { RulesFailed } from "./rules-evaluator.ts";12import type { EvaluationFacts } from "./rules-evaluator.ts";13import { parseVouchFile } from "./vouch.ts";1415/** A file the finishers read: a CI workflow, a hook config, a manifest. */15export interface FactFile {16 readonly content: string;17 readonly path: string;18}1921/**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. */21export class Finishers extends Context.Service<22 Finishers,23 {24 readonly findRunBlock: (files: readonly FactFile[]) => {
16 unmodified lines
41 * platform names someone else, so it vouches for no one here.42 */43const isSignInPlatform = (platform: string) => platform === "github";4450/** The run block: the config folder's own, or the one the finder finds in CI. */45const runBlockOf = (46 run: PolicyInput["run"],47 facts: EvaluationFacts,48 finishers: Finishers["Service"]
14 unmodified lines
63 ...found.run,64 }).pipe(Effect.mapError(failedAt(`the run block found in ${where}`)));65};6673/**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. */68const vouchesOf = (text: string, file: RepoPath) => {69 const { invalid, vouches } = parseVouchFile(text);7071 if (invalid.length > 0) {
21 unmodified lines
93 })94 );95};96106/** A workspace folder as a glob prefix: `./packages/x/` is `packages/x`. */97const folderOf = (dir: string) =>98 dir99 .replace(/^(?:\.\/)+/u, "")100 .replace(/\/+$/u, "")101 .replace(/^\.$/u, "");102113/**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 */103const territoriesOf = (104 workspaces: EvaluationFacts["workspaces"]105): (typeof Policy.Encoded)["modules"] =>106 workspaces.length === 0
9 unmodified lines
116 ? { module: name, paths }117 : { module: name, paths, publicFiles: exports };118 });119134/** A glob with the package's folder written over the sdk's `{dir}`. */120const placed = (glob: string, folder: string) => {121 const written = glob.replaceAll(packageDir, folder).replace(/^\/+/u, "");122123 return written === "" ? "**" : written;124};125126/**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 */131const placedIn = (132 workspaces: EvaluationFacts["workspaces"],133 territory: PolicyInput["asks"][number]["territory"]
14 unmodified lines
148 ? { ...territory, paths }149 : { ...territory, paths, publicFiles: workspace.exports };150};151171/** Fails when two asks share an id: an id names one ask, and one fork per claim. */152const distinctAsks = (asks: PolicyInput["asks"]) => {153 const seen = new Map<string, string>();154155 for (const { file, id } of asks) {
14 unmodified lines
170 return Effect.void;171};172173/**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 */178export const finishPolicy = (input: {179 readonly at: LandedSha;180 readonly facts: EvaluationFacts;
39 unmodified lines
220 vouches,221 weakening: policy.weakening,222 } satisfies typeof Policy.Encoded;223249 // 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 lines
modified: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.3import { Functions } from "@repo/sdk/functions";45/**6 * The clock and seed config code sees, injected by the caller: an
1 unmodified line
8 * call's are the Unix epoch and 0, so a rule gets time only through its9 * facts (as `/bun` does).10 */11export interface FrozenFacts {17 /** The time, in epoch milliseconds. */12 readonly now: number;13 readonly seed: number;14}1522/**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 */16export interface DateClass {17 new (...args: readonly (Date | number | string)[]): Date;18 now: () => number;19 readonly prototype: Date;20}2132/**33 * The globals the prelude replaces: `globalThis` in the loaded worker, a34 * plain object in tests.35 */22export interface FreezableScope {23 Date: DateClass;24 readonly Math: { random: () => number };25 readonly crypto: {
2 unmodified lines
28 };29 readonly performance: { now: () => number };30}3146/** What the prelude hands the main. */32export 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 own
2 unmodified lines
38 readonly settle: () => void;39}4041/**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 */49export const installFrozenGlobals = (50 scope: FreezableScope,51 facts: FrozenFacts
102 unmodified lines
154 },155 };156};157182/**183 * The prelude module: `installFrozenGlobals` applied to the loaded worker's184 * `globalThis` with `facts` as JSON, exporting what it returns as `frozen`.185 */158export const preludeModule = (facts: FrozenFacts): string =>159 `export const frozen = (${String(installFrozenGlobals)})(globalThis, ${JSON.stringify({ now: facts.now, seed: facts.seed })});\n`;160189/** The prelude's module name, beside the main at the root. */161export const preludeName = "prelude.js";162192/** The main's module name. */163export const mainName = "main.js";164195/** The modules a main imports: the config folder's, by their bundle paths. */165export 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}170205/** A module the main imports on first use, by a literal specifier. */171const importer = (path: string) =>172 `{ load: () => import(${JSON.stringify(`./${path}`)}), path: ${JSON.stringify(path)} }`;173174/**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 */182export const mainModule = (modules: MainModules): string => `183import { frozen } from "./${preludeName}";184
120 unmodified lines
modified:packages/rules/src/rules-evaluator.ts+4 added-52 removed
2 unmodified lines
3import { Handle, ProjectName, RepoPath } from "@repo/protocol/ids";4import { ClaimantFacts, ProposalFacts } from "@repo/sdk/functions";5import { Context, Effect, Schema } from "effect";67/**8 * The config folder as it stood at one landed commit, ready to evaluate.9 * `modules` maps each file's repo path (`<folder>/project.ts`,10 * `<folder>/asks/<id>.ask.ts`, `<folder>/policy.json`) to its source. An11 * empty `modules` means the project has no config folder, so it runs on the12 * defaults.13 */7/** An empty `modules` means the project has no config folder, so it runs on the defaults. */8export 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});1718export type ConfigBundle = typeof ConfigBundle.Type;1927/**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. */21export { sdkVersion } from "@repo/sdk";2234/** One workspace package, as the repo's manifests declare it. */23const 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});2843/**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. */30export 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});3940export type EvaluationFacts = typeof EvaluationFacts.Type;4172/**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. */43export class RulesFailed extends Schema.TaggedError<RulesFailed>()(44 "RulesFailed",45 {46 detail: Schema.String,47 reason: Schema.Literals(["load", "timeout", "decode", "threw"]),48 }49) {}5085/** The function-valued rules, called on demand rather than read as data. */51export const RuleName = Schema.Literals(["opensAlone", "admit"]);5253export type RuleName = typeof RuleName.Type;5490/**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 */55export type RuleCall =56 | { readonly rule: "opensAlone"; readonly facts: ProposalFacts }57 | { readonly rule: "admit"; readonly facts: ClaimantFacts };58100/** A call's facts as JSON carries them into the sandbox. */59export 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 lines
65 // The facts were typed by the same schemas, so encoding them can't fail.66 return Effect.orDie(encoded);67};68111/**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 */69export class RulesEvaluator extends Context.Service<70 RulesEvaluator,71 {72 readonly call: (
12 unmodified lines
modified:packages/rules/src/vouch.ts+1 added-12 removed
1import { Handle } from "@repo/protocol/ids";2import { Schema } from "effect";34/** One line of a vouch file: a person vouched for, or denounced. */4export 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}1013/** A line that names no valid handle, kept so it is reported, not dropped. */11export interface InvalidVouchLine {12 readonly line: number;13 readonly text: string;14}1519/** A vouch file, read: its vouches and denouncements, and its bad lines. */16export interface VouchFile {17 readonly invalid: readonly InvalidVouchLine[];18 readonly vouches: readonly Vouch[];19}
5 unmodified lines
25 /^(?<sign>[+-]?)\s*(?:(?<platform>[a-z][a-z0-9-]*):)?(?<handle>\S+)(?:\s+(?<note>\S.*))?$/u;2627const isHandle = Schema.is(Handle);2833/** One non-blank, non-comment line, read; `undefined` when it names no handle. */29const vouchOf = (text: string): Vouch | undefined => {30 const groups = LINE.exec(text)?.groups;31 const handle = groups?.handle;32
10 unmodified lines
43 ? withNote44 : { ...withNote, platform: groups.platform };45};4652/**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`. */48export const parseVouchFile = (text: string): VouchFile => {49 const vouches: Vouch[] = [];50 const invalid: InvalidVouchLine[] = [];51
18 unmodified lines
modified: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 */1export { 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. */2export { default } from "./leap-year.json" with { type: "json" };
modified:packages/rules/test/fixtures/cm/project.ts-12 removed
1import { Functions } from "@repo/sdk";23import data from "./project.json" with { type: "json" };45/**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 */5const project = Object.defineProperty({ ...data }, Functions, {6 enumerable: false,7 value: {8 admit: undefined,
5 unmodified lines
modified: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 */1export const marker = "the sdk";
modified:packages/rules/test/evaluate.test.ts-20 removed
26 unmodified lines
27const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);2829const decodeClaimant = Schema.decodeUnknownSync(ClaimantFacts);3031/** A proposal for an ask of the example's `fixBug` kind, but its record. */31const fixBugProposal = {32 kind: "fixBug",33 proposer: "carol",34 territory: "@datekit/parse",35};3638/** A red-then-green check on one file, as `CheckSpec` encodes it. */37const redThenGreen = (path: string) =>38 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });3942/** What the platform fills in on every ask: when, where and whose. */40const opened = {41 openedAt: now,42 openedIn: at,43 project: "oscabriel/datekit",44 state: "open",45};4650/** What every policy in these tests derives from the shared facts. */47const fromFacts = {48 at,49 modules: [50 {
8 unmodified lines
59 { denounced: true, handle: "mallory", note: "Spam" },60 ],61};6267/** The judge closure the fake finishers give for a run block's test command. */63const judgeFor = (test: string) => ({64 paths: [`${configFolder}/**`, ".github/workflows/ci.yml"],65 pointers: ["package.json#/scripts", `test:${test}`],66});6773/** The run block the fake finder finds in CI. */68const foundRun = { checks: { unit: "bun test" }, test: "bun test {path}" };6970const fixBug = {71 checkKind: "redThenGreen",
5 unmodified lines
77 requires: ["want", "check"],78 strength: "assertion",79};8087/** The convex-merged example's policy, as `Policy` encodes it. */81const exampleEncoded = {82 ...fromFacts,83 agents: "trailer",84 asks: [
42 unmodified lines
127 vouch: { file: defaultVouchFile, mode: "forCode" },128 weakening: { markers: [".skip(", ".only("] },129};130138/** The policy a folder holding only `policy.json` states. */131const jsonEncoded = {132 ...fromFacts,133 agents: "none",134 asks: [
38 unmodified lines
173 vouch: { file: defaultVouchFile, mode: "forCode" },174 weakening: { markers: [".skip("] },175};176185/**186 * The defaults (no folder means defaults), as187 * `Policy` encodes them: the sdk's `defaults`, finished with the facts.188 */177const defaultsEncoded = {178 ...fromFacts,179 agents: "trailer",180 asks: [],
23 unmodified lines
204 // The gate scans its own default markers plus these, a project's own.205 weakening: { markers: [] },206};207220/** Evaluates a bundle at `at` with the shared facts, and encodes the policy. */208const evaluated = (modules: ConfigBundle) =>209 Effect.gen(function* () {210 const evaluator = yield* RulesEvaluator;211 const policy = yield* evaluator.evaluate({ at, facts, modules });212213 return yield* Schema.encodeEffect(Policy)(policy);214 });215229/** Evaluates a bundle that must fail, and hands back its `RulesFailed`. */216const failed = (modules: ConfigBundle) =>217 Effect.gen(function* () {218 const evaluator = yield* RulesEvaluator;219
7 unmodified lines
227228 return result.failure;229 });230245/**246 * A `visibility.ts`'s default export, as the sdk writes it: one layer of247 * held-back checks for one area.248 */231const visibilityEncoded = {232 checks: {233 admit: { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 },234 areas: { parse: "packages/parse/**" },
19 unmodified lines
254 ],255 notice: { narrowingDays: 7 },256} satisfies typeof VisibilityPolicy.Encoded;257276/** A module whose default export is `data`. */258const exporting = (data: Schema.Json) =>259 `export default ${JSON.stringify(data)};\n`;260280/** An ask file whose brief says what happens today, but not what is wanted. */261const 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 lines
modified: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.3import { describe, expect, it } from "@effect/vitest";4import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";5import { Command, SymbolName } from "@repo/protocol/domain/common";6import { Policy } from "@repo/protocol/domain/policy";
1 unmodified line
89import { EvaluationFacts, RulesEvaluator } from "../src/rules-evaluator.ts";10import { at, bundleOf, bunEvaluator, configFolder, now } from "./world.ts";1121/** A text file under burrow's root, by its path there. */12interface File {13 readonly content: string;14 readonly path: string;15}
5 unmodified lines
21});2223const decodeManifest = Schema.decodeEffect(Schema.fromJsonString(Manifest));2435/** The folders at `root` that hold a `project.ts`, and the files beside them. */25const rootEntries = (root: string) =>26 Effect.gen(function* () {27 const fs = yield* FileSystem.FileSystem;28 const path = yield* Path.Path;
15 unmodified lines
4445 return { files, folders };46 });4759/** Every `.ts` file under a folder, keyed by its path inside it. */48const sourcesIn = (folder: string) =>49 Effect.gen(function* () {50 const fs = yield* FileSystem.FileSystem;51 const path = yield* Path.Path;
11 unmodified lines
6364 return sources;65 });6679/**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 */67const workspacesAt = (root: string, globs: readonly string[]) =>68 Effect.gen(function* () {69 const fs = yield* FileSystem.FileSystem;70 const path = yield* Path.Path;
22 unmodified lines
93 )94 );95 });96114/** burrow's config folder as a bundle, and the facts the platform reads around it. */97const readBurrow = () =>98 Effect.gen(function* () {99 const fs = yield* FileSystem.FileSystem;100 const path = yield* Path.Path;
29 unmodified lines
130 modules: bundleOf(yield* sourcesIn(path.join(root, folder))),131 };132 });133152/** burrow's policy at `at`, as `Policy` encodes it. */134const evaluated = () =>135 Effect.gen(function* () {136 const { facts, modules } = yield* readBurrow();137 const evaluator = yield* RulesEvaluator;
2 unmodified lines
140 yield* evaluator.evaluate({ at, facts, modules })141 );142 });143163/** Every workspace package as its own module: its folder, and its `exports`. */144const modules = [145 {146 module: "@burrow/auth",147 paths: ["packages/auth/**"],
25 unmodified lines
173 publicFiles: ["packages/search/src/index.ts"],174 },175];176197/** The migrate ask, as `Policy` encodes it. */177const dropLegacyFetch = {178 askedBy: "okafor",179 blockedBy: [],180 brief: {
17 unmodified lines
198 state: "open",199 territory: { module: ".", paths: ["packages/**"] },200};201223/** The sdk's `migrate` kind, as `Policy` encodes it. */202const migrateKind = {203 checkKind: "migrate",204 claimers: "vouched",205 finish: "never",
58 unmodified lines
264 },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 lines
284 Effect.gen(function* () {285 const policy = yield* evaluated();286 const globs = policy.asks.flatMap(({ territory }) => territory.paths);287312 // 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 lines
modified: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 */1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { CheckSpec } from "@repo/protocol/domain/check";4import { Policy } from "@repo/protocol/domain/policy";
3 unmodified lines
8import { EvaluationFacts, RulesEvaluator } from "../src/rules-evaluator.ts";9import type { ConfigBundle } from "../src/rules-evaluator.ts";10import { at, bunEvaluator, now } from "./world.ts";1120/** Where the example lives, from this test's folder. */12const exampleUrl = new URL("../../../examples/datekit/", import.meta.url);1323/**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. */15const 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 lines
2930 return { folders, root };31});3246/** Every file in the example's config folder, as the bundle the Lander makes of it. */33const exampleBundle = Effect.gen(function* () {34 const fs = yield* FileSystem.FileSystem;35 const path = yield* Path.Path;36 const { folders, root } = yield* configFolders;
24 unmodified lines
61 folder,62 };63});6479/** The policy the example's config folder evaluates to, encoded. */65const evaluated = Effect.gen(function* () {66 const { bundle, folder } = yield* exampleBundle;67 const evaluator = yield* RulesEvaluator;68
11 unmodified lines
8081 return { folder, policy: yield* Schema.encodeEffect(Policy)(policy) };82});8399/** What one of the example's asks is, beside its brief. */84const askOf = (85 folder: string,86 id: string,87 territory: readonly [string, ...string[]]
89 unmodified lines
177 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 lines
modified:packages/rules/test/fake-loader.ts+2 added-25 removed
8 unmodified lines
9 LoaderEntrypoint,10 LoaderModule,11} from "../src/rules-evaluator/worker.ts";1213/** How a loaded worker's entrypoint answers every request. */13export 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 };1722/** One cold start: the id the adapter asked for, and the code it handed over. */18export interface Load {19 readonly code: LoaderCode;20 readonly id: string;21}2228/** A fake Worker Loader, and what it saw. */23export 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}2930// `Symbol.dispose`, which the runtime calls a stub's release by; the lib the
2 unmodified lines
33 Symbol,34 "dispose"35)?.value;3646/**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`. */38export 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 };4357 /** A handle that counts itself out, and in again when disposed. */44 const handle = <A extends object>(value: A): A => {45 counts.out += 1;4647 if (Predicate.isSymbol(disposeKey)) {
40 unmodified lines
88 requests,89 };90};91106/** A module's source, as the Loader would read it. */92const sourceOf = (module: LoaderModule) => {93 if ("js" in module) {94 return module.js;95 }9697 return "json" in module ? JSON.stringify(module.json) : module.text;98};99115/** Runs the main's default `fetch` once, and prints what it answered. */100const harness = `101import worker from "./main.js";102const body = await Bun.file(new URL("./request.json", import.meta.url)).text();103const response = await worker.fetch(new Request("https://rules.invalid/", { body, method: "POST" }));104process.stdout.write(await response.text());105process.exit(0);106`;107124/** Writes the code's modules under a temp directory, and runs one request. */108const runInBun = (code: LoaderCode, body: string, sdk: string) =>109 Effect.scoped(110 Effect.gen(function* () {111 const fs = yield* FileSystem.FileSystem;
3 unmodified lines
115 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 lines
145 return stdout === "" ? `bun printed nothing: ${stderr}` : stdout;146 })147 ).pipe(Effect.orDie);148167/**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. */150export const bunLoader = (151 services: Context.Context<152 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path153 >,
17 unmodified lines
modified:packages/rules/test/finish.test.ts-2 removed
6 unmodified lines
7import { defaultPolicyInput } from "../src/defaults.ts";8import { finishPolicy } from "../src/finish.ts";9import { at, facts, finishers } from "./world.ts";1011/** The whole repo, as one module. */11const wholeRepo: (typeof AskInput.Encoded)["territory"] = {12 module: ".",13 paths: ["**"],14};1517/** An ask with the given id, declared in `file`, in `territory`. */16const askIn = (17 id: string,18 file: string,19 territory: (typeof AskInput.Encoded)["territory"] = wholeRepo
99 unmodified lines
modified:packages/rules/test/prelude.test.ts-2 removed
5 unmodified lines
6 preludeModule,7} from "../src/prelude.ts";8import type { FreezableScope, FrozenFacts } from "../src/prelude.ts";910/** 2026-10-07T12:00:00.000Z, the landed commit's time, and its seed. */10const facts: FrozenFacts = { now: 1_791_374_400_000, seed: 7 };1112/**13 * mulberry32 seeded with 7, worked out from the published algorithm apart
18 unmodified lines
32 },33 performance: { now: () => 1 },34});3537/** Two words and a UUID from a scope frozen with `seed`. */36const draws = (seed: number) => {37 const scope = scopeOf();3839 installFrozenGlobals(scope, { ...facts, seed });
130 unmodified lines
modified:packages/rules/test/replay.test.ts-11 removed
13 unmodified lines
14 now,15 nowMs,16} from "./world.ts";1718/** Evaluates a bundle with the given facts, and encodes the policy. */18const 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 });2223 return yield* Schema.encodeEffect(Policy)(policy);24 });2527/**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 */26const readsTheClock = Effect.map(baseProject, (base) =>27 bundleOf({28 "asks/stamp.ask.ts": [29 'import { stamp } from "../project.ts";',
19 unmodified lines
49 ].join("\n"),50 })51);5261/** What the clock-reading config put into its ask's context. */53const stampOf = (policy: typeof Policy.Encoded) =>54 policy.asks[0]?.brief.context;5556describe("evaluating a config folder twice", () => {
32 unmodified lines
89 "2027-01-01T00:00:00.000Z",90 "1798761600000",91 ]);92102 // 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 );9697 it.live("gives config code randomness from the facts' seed", () =>98 Effect.gen(function* () {99 const modules = yield* readsTheClock;100111 // 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 lines
modified:packages/rules/test/vouch.test.ts-2 removed
1import { describe, expect, it } from "@effect/vitest";23import { parseVouchFile } from "../src/vouch.ts";45// A vouch file in Ghostty's VOUCHED.td format: its header comment, then one6// handle per line.5const vouchedFile = [6 "# The list of vouched (or actively denounced) users for this repository.",7 "#",8 "# Syntax:",
66 unmodified lines
modified:packages/rules/test/worker.test.ts-39 removed
30 unmodified lines
31 now,32 nowMs,33} from "./world.ts";3435/** The `/worker` adapter over a loader, with the fake finishers. */35const workerEvaluator = (loader: LoaderBinding, options?: WorkerOptions) =>36 RulesEvaluatorWorker(loader, options).pipe(37 Layer.provide(Layer.succeed(Finishers, finishers))38 );3941/** A policy as JSON carries it: one the evaluator gave always encodes. */40const encoded = (policy: Policy) =>41 Effect.orDie(Schema.encodeEffect(Policy)(policy));4245/** Evaluates a bundle at a landed commit: the encoded policy, or the failure. */43const evaluated = (modules: ConfigBundle, landed = at) =>44 Effect.gen(function* () {45 const evaluator = yield* RulesEvaluator;46
3 unmodified lines
50 .pipe(Effect.flatMap(encoded))51 );52 });5357/** Calls a function-valued rule: its answer, or the failure. */54const called = (modules: ConfigBundle, call: RuleCall) =>55 Effect.gen(function* () {56 const evaluator = yield* RulesEvaluator;5758 return yield* Effect.result(evaluator.call({ ...call, at, modules }));59 });6065/** The reason a result failed for; a policy or an answer fails the test. */61const reasonOf = <A>(62 result: Result.Result<A, { readonly reason: string }>63): string => {64 assert(Result.isFailure(result), "expected the evaluation to fail");
2 unmodified lines
67};6869const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);7076/** A proposal for an ask of the example's `fixBug` kind, with a record. */71const proposal = (record: number): RuleCall => ({72 facts: decodeProposal({73 kind: "fixBug",74 proposer: "carol",
2 unmodified lines
77 }),78 rule: "opensAlone",79});8087/** The defaults, written as a project module's data. */81const baseEncoded = Schema.encodeSync(PolicyInput)({82 ...defaultPolicyInput,83 source: "config",84});8593/** A folder with a project module and one ask file. */86const bundle = bundleOf({87 "asks/a.ask.ts": "export default {};\n",88 "project.ts": "export default {};\n",89});9099/** What the main answers for a folder whose project module is the defaults. */91const collectedBase = `{"_tag":"Collected","asks":[],"project":${JSON.stringify(baseEncoded)}}`;92102/** The specifiers a module imports, in the order it names them. */93const importsOf = (source: string) =>94 [95 ...source.matchAll(96 /\bimport\s*(?:\(\s*|[^"'()]*?from\s*)(?<quote>["'])(?<specifier>[^"']+)\k<quote>/gu97 ),98 ].map((match) => match.groups?.specifier);99110/** A script module's source, from the modules a load handed over. */100const scriptOf = (modules: LoaderCode["modules"], name: string): string => {101 const module = modules[name];102103 assert(module !== undefined && "js" in module, `${name} is no script`);104105 return module.js;106};107119/** The modules the first load handed over. */108const firstLoaded = (loads: readonly { readonly code: LoaderCode }[]) => {109 const [load] = loads;110111 assert(load !== undefined, "the adapter loaded no worker");112113 return load.code;114};115128/**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 */116const outcome = (answer: Answer) =>117 Effect.gen(function* () {118 const loader = fakeLoader(answer);119
6 unmodified lines
126 reason: Result.isFailure(result) ? result.failure.reason : "ok",127 };128 });129146/** Why evaluating `bundle` fails over a fake whose worker answers so. */130const reasonFor = (answer: Answer) =>131 evaluated(bundle).pipe(132 Effect.provide(workerEvaluator(fakeLoader(answer).binding)),133 Effect.map(reasonOf)
117 unmodified lines
251 yield* evaluated(bundle, other);252 yield* evaluated({ ...bundle, sdkVersion: "0.0.1" });253 }).pipe(Effect.provide(workerEvaluator(loader.binding)));254272 // 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 lines
295 const viaWorker = yield* evaluated(bundle).pipe(296 Effect.provide(workerEvaluator(loader.binding))297 );298317 // 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 lines
352 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 lines
432 })433 );434});435457/**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 */436const running = Effect.gen(function* () {437 const services = yield* Effect.context<438 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path439 >();
6 unmodified lines
446447 return workerEvaluator(bunLoader(services, sdk));448});449476/**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 */450const readsTheClock = bundleOf({451 "asks/stamp.ask.ts": [452 'import { stamp } from "../project.ts";',453 "export default {",
19 unmodified lines
473 `export default ${JSON.stringify(baseEncoded)};`,474 ].join("\n"),475});476512/**513 * A folder with a `visibility.ts` beside its project module: one layer of514 * held-back checks, as the sdk writes it.515 */477const withVisibility = bundleOf({478 "project.ts": `export default ${JSON.stringify(baseEncoded)};\n`,479 "visibility.ts": `export default ${JSON.stringify({480 env: { setters: "deciders" },
117 unmodified lines
modified:packages/rules/test/world.ts+1 added-21 removed
16 unmodified lines
17 * lives in `packages/brand`, which `rules` and its tests don't import.18 */19export const configFolder = ".cfg";2021/** The vouch file a policy that names none gets: `PolicyInput`'s default. */21export const defaultVouchFile = Schema.decodeSync(PolicyInput)({22 asks: [],23 deciders: [],24 functions: { admit: false, opensAlone: false },
3 unmodified lines
28 source: "defaults",29 weakening: { markers: [] },30}).vouch.file;3133/** The landed commit every test evaluates at. */32export const at = LandedSha.make("a".repeat(40));3336/** The frozen clock the facts carry, as text and in epoch milliseconds. */34export const now = "2026-10-07T12:00:00.000Z";3536export const nowMs = "1791374400000";3741/**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 */38export const factsEncoded = {39 ci: [{ content: "steps: [bun test]", path: ".github/workflows/ci.yml" }],40 initializer: "olivia",41 now,
11 unmodified lines
53} satisfies typeof EvaluationFacts.Encoded;5455export const facts = Schema.decodeSync(EvaluationFacts)(factsEncoded);5665/**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 */57export 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 lines
67 pointers: ["package.json#/scripts", `test:${run.test}`],68 }),69});7084/** The `/bun` adapter over Node, with the fake finishers. */71export const bunEvaluator = (72 options: BunOptions = {},73 finish: Finishers["Service"] = finishers74) =>
1 unmodified line
76 Layer.provide(Layer.succeed(Finishers, finish)),77 Layer.provideMerge(NodeServices.layer)78 );7994/** A bundle of config-folder files, keyed by their path inside the folder. */80export const bundleOf = (files: Readonly<Record<string, string>>) =>81 ({82 entry: `${configFolder}/project.ts`,83 modules: Object.fromEntries(
4 unmodified lines
88 ),89 sdkVersion: "0.0.0",90 }) satisfies ConfigBundle;91107/**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. */93export const folder = (name: string) =>94 Effect.gen(function* () {95 const fs = yield* FileSystem.FileSystem;96 const path = yield* Path.Path;
16 unmodified lines
113114 return bundleOf(files);115 });116136/** A project module that exports the defaults as config: a base to vary. */117export 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 */1import {2 CheckSpec,3 RatchetMeasure as Measure,4} from "@repo/protocol/domain/check";5import { Schema, Struct } from "effect";67type CheckSpecEncoded = typeof CheckSpec.Encoded;813/**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. */10export type CheckSpecInput<11 Tag extends CheckSpecEncoded["_tag"] = CheckSpecEncoded["_tag"],12> = Extract<CheckSpecEncoded, { readonly _tag: Tag }>;1321/** How a ratchet measures its number, as plain data: a lint count, or a number in a command's JSON. */14export type RatchetMeasure = typeof Measure.Encoded;1516const { LintToZero, Migrate, Ratchet, RedThenGreen } = CheckSpec.cases;1718const { Count, Metric } = Measure.cases;1928// 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.20const lintToZeroFields = Schema.Struct(21 Struct.omit(LintToZero.fields, ["_tag"])22);23
8 unmodified lines
32const countFields = Schema.Struct(Struct.omit(Count.fields, ["_tag"]));3334const metricFields = Schema.Struct(Struct.omit(Metric.fields, ["_tag"]));3546/** The builders for an ask's check, one per check kind, and for a ratchet's measure. */36export 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 lines
49 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 lines
72 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 line
modified:packages/sdk/src/checked.ts-5 removed
1import { Schema } from "effect";23/**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 */3export const checked = <T, E>(schema: Schema.Codec<T, E>) => {4 const decode = Schema.decodeSync(schema);5 const encode = Schema.encodeSync(schema);6
2 unmodified lines
modified: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 */1import { Ask } from "@repo/protocol/domain/ask";2import { AskKind } from "@repo/protocol/domain/kind";3import { Territory } from "@repo/protocol/domain/territory";4import { Schema } from "effect";
6 unmodified lines
11const KindName = AskKind.fields.name;1213const Module = Territory.fields.module;1421/** A count of landings on a person's record: never negative. */15const LandingCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));1624/**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. */18export 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});2526export type ProposalFacts = typeof ProposalFacts.Type;
3 unmodified lines
30 * only when the kind's data can't say it: `(p) => p.record >= 3`.31 */32export type OpensAlone = (proposal: ProposalFacts) => boolean;3348/**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 */34export 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});4243export type ClaimantFacts = typeof ClaimantFacts.Type;
3 unmodified lines
47 * say it: `(c) => c.vouched || c.record > 0`.48 */49export type Admit = (claimant: ClaimantFacts) => boolean;5074/** A project's function-valued rules: absent ones are `undefined`. */51export interface ProjectFunctions {52 readonly admit: Admit | undefined;53 readonly opensAlone: OpensAlone | undefined;54}5580/** An ask kind's function-valued rule, which its asks carry too. */56export interface KindFunctions {57 readonly opensAlone: OpensAlone | undefined;58}59
2 unmodified lines
62 * enumerable, so encoding, spreading or printing the data never meets them.63 */64export const Functions: unique symbol = Symbol.for("@repo/sdk/Functions");6591/** Something that carries function-valued rules beside its data. */66export interface WithFunctions<F> {67 readonly [Functions]: F;68}6996/**97 * Puts function-valued rules beside a copy of `data`, where encoding never98 * meets them.99 */70export const withFunctions = <A extends Readonly<Record<string, unknown>>, F>(71 data: A,72 functions: F73): A & WithFunctions<F> => {
3 unmodified lines
7778 return carried;79};80111/**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)`. */82export 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.2export { check, type CheckSpecInput, type RatchetMeasure } from "./check.ts";34export {5 type Admit,
83 unmodified lines
modified: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 */1import type { Brief } from "@repo/protocol/domain/ask";2import { AskKind } from "@repo/protocol/domain/kind";3import type {4 BriefField,
10 unmodified lines
15import { withFunctions } from "./functions.ts";16import type { KindFunctions, OpensAlone, WithFunctions } from "./functions.ts";17import type { TerritoryInput } from "./territory.ts";1823/** An ask kind as data: what a project's policy lists. */19export type AskKindInput = typeof AskKind.Encoded;2021type AskInputEncoded = typeof AskInput.Encoded;2228/**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 */23export type AskStated = Omit<AskInputEncoded, "askedBy" | "file" | "id">;2434/**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 */25export type AskDefinition = AskStated & WithFunctions<KindFunctions>;2640/**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 */27export type AskFields = typeof Brief.Encoded &28 Partial<Pick<AskInputEncoded, "blockedBy">> &29 Pick<AskInputEncoded, "mentor" | "parent" | "reserve">;3050/** Whether an ask states its territory, or its kind derives it from the args. */31export type TerritoryMode = "derived" | "stated";3233type TerritoryField<Mode extends TerritoryMode> = Mode extends "derived"34 ? { readonly territory?: TerritoryInput }35 : { readonly territory: TerritoryInput };3657/**58 * A kind's args: config fields as Effect schemas that decode with no59 * services, `{ path: Schema.NonEmptyString }`.60 */37export type ArgFields = Readonly<38 Record<PropertyKey, Schema.Constraint & { readonly DecodingServices: never }>39>;4065/**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 */41export type AskArgs<42 Args extends ArgFields,43 Mode extends TerritoryMode = "stated",44> = Schema.Struct.Encoded<Args> & AskFields & TerritoryField<Mode>;4574/** Derives an ask's territory from its kind's args. */46export type DeriveTerritory<Args extends ArgFields> = (47 args: Schema.Struct.Type<Args>48) => TerritoryInput;4979/**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 */50export 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}75118/**119 * An ask kind as the project lists it: its data, and its function-valued120 * rule beside it.121 */76export interface DeclaredKind extends WithFunctions<KindFunctions> {123 /** The ask kind as data. */77 readonly askKind: AskKindInput;78}79127/**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 */80export 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}8788const askKindOf = checked(AskKind);
1 unmodified line
90const territoryOf = Schema.decodeUnknownSync(Territory);9192const encodeTerritory = Schema.encodeSync(Territory);93148/**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 */94export 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}104105/**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 */110export const kind: KindBuilder = <111 const Args extends ArgFields,112 const K extends CheckKind,
46 unmodified lines
159 functions160 );161};162226/** Where an ask file sits, and who asked: what the platform knows and the file doesn't. */163export 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}167168const askSuffix = ".ask.ts";169236/** An ask's id, from its file's name: `parse-iso-week.ask.ts` is `parse-iso-week`. */170const askIdOf = (file: string): string => {171 const name = file.slice(file.lastIndexOf("/") + 1);172173 return name.endsWith(askSuffix) ? name.slice(0, -askSuffix.length) : name;174};175243/**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 */176export const toAskInput = (177 definition: AskDefinition,178 origin: AskOrigin179): AskInputEncoded => ({
4 unmodified lines
184});185186const path = { path: Schema.NonEmptyString };187259/**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 })`. */189export 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 lines
modified: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 */1import { Brand } from "@repo/brand";2import type { PolicyInput } from "@repo/protocol/domain/policy";3import { Duration, Predicate } from "effect";4import type { Types } from "effect";
27 unmodified lines
32 | "seconds"33 | "week"34 | "weeks"}`;3540/** A span in whole days or weeks, as config writes it: `"30 days"`, `"2 weeks"`. */36export type Days = `${number} ${"day" | "days" | "week" | "weeks"}`;3738/**39 * What a vouch gates: claims and sealed answers (`forCode`), proposals too
4 unmodified lines
44 | undefined45 ? M46 : never;4753/** A ratchet by name: its measure, and the territory it counts, if only one. */48export interface RatchetEntry {49 readonly measure: RatchetMeasure;56 /** The territory's module the ratchet counts. */50 readonly territory?: string;51}5260/**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`). */54export 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 lines
70 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 lines
94 /** Markers this project counts as weakening a check, beyond the platform's own list. */95 readonly weakening?: { readonly markers: readonly string[] };96}97112/**113 * A project file's default export: its process as policy data, with its114 * function-valued rules carried beside the data.115 */98export type ProjectDefinition = PolicyInputEncoded &99 WithFunctions<ProjectFunctions>;100101type Settings = Pick<
100 unmodified lines
202 functions203 );204};205224/**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`. */207export const project = (config: ProjectConfig): ProjectDefinition =>208 define(config, "config");209233/**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 */210export const defaults: ProjectDefinition = define({}, "defaults");211242/**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 */212export 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 */1import { FromCI } from "@repo/protocol/domain/policy";2import type { RunBlock } from "@repo/protocol/domain/run";34/** A test command, which names the one check file it runs with `{path}`: `bun test {path}`. */
6 unmodified lines
11export type RunBlockInput = Omit<typeof RunBlock.Encoded, "test"> & {12 readonly test: TestCommand;13};1418/** A project's run block: written out, or `run.fromCI`. */15export type RunInput = RunBlockInput | typeof FromCI.Encoded;1621/** Where a project's run block comes from. */17export 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 */1import { Territory } from "@repo/protocol/domain/territory";2import { Schema } from "effect";34import { checked } from "./checked.ts";510/** An ask's territory as the config folder states it: a module and its paths, as plain data. */6export type TerritoryInput = typeof Territory.Encoded;78/**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 */12export const packageDir = "{dir}";1321/** Where a project's modules come from: its workspace packages, one module each. */14export const FromWorkspaces = Schema.TaggedStruct("FromWorkspaces", {});1524/** Where a project's modules come from, as plain data. */16export type ModulesInput = typeof FromWorkspaces.Encoded;1718const territoryOf = checked(Territory);1929/** The builders for a territory, and for a project's modules. */20export 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 lines
modified: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.3import {4 Layer,5 LayerManifest,6 SealedChecks,
14 unmodified lines
21type VisibilityPolicyEncoded = typeof VisibilityPolicy.Encoded;2223type SealedChecksEncoded = typeof SealedChecks.Encoded;2434/** Who a rule names, as config writes it: `deciders`, or handles without `@`. */25export type MembersInput = typeof Members.Encoded;2637/** The project's deciders, whoever they are at the landed commit. */27export const deciders = "deciders" satisfies MembersInput;2840/**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 */29export type LayerDefinition = Omit<typeof Layer.Encoded, "name" | "repo">;3046/** What a layer holds: one kind or more. */31export type LayerHolds = readonly [LayerKind, ...LayerKind[]];3249/** A layer, as `layer()` takes it. */33export 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}4849const LayerFields = Schema.Struct(Struct.omit(Layer.fields, ["name", "repo"]));
8 unmodified lines
5859 return days.length === 0 ? {} : { sunsetDays: Math.min(...days) };60};6182/**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. */63export const layer = <const Holds extends LayerHolds>(64 config: LayerConfig<Holds>65): LayerDefinition =>66 layerOf({
39 unmodified lines
106 "Each person's own agent and tool configuration, for them and their agents only",107 writers: deciders,108 });109133/**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 */110export type SealedChecksDefinition<Area extends string = string> = Omit<111 SealedChecksEncoded,112 "areas"113> & { readonly areas: Readonly<Record<Area, string>> };114115const sealedChecksOf = checked(SealedChecks);116117/**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 */122export const sealedChecks = <123 const Areas extends Readonly<Record<string, string>>,124>(config: {
28 unmodified lines
153 }),154 areas: config.areas,155});156187/** How content moves between audiences, as data. */157export type FlowsDefinition = VisibilityPolicyEncoded["flows"];158159const flowsOf = checked(VisibilityPolicy.fields.flows);160192/** The flow rules. */161export 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 lines
168 }): FlowsDefinition =>169 flowsOf({ noWriteDown: true, release: options?.release ?? deciders }),170};171204/** A project's `visibility.ts`, as `visibility()` takes it. */172export 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}182218/** A visibility file's default export: the policy it states, as data. */183export type VisibilityDefinition<Area extends string = string> = Omit<184 VisibilityPolicyEncoded,185 "checks"186> & { readonly checks?: SealedChecksDefinition<Area> };
15 unmodified lines
202 )203 )204);205242/**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. */207export const visibility = <Area extends string = never>(208 config: VisibilityConfig<Area>209): VisibilityDefinition<Area> => {210 const { checks } = config;
33 unmodified lines
244 : Definition extends VisibilityDefinition<infer Area>245 ? Area246 : never;247287/** One held-back check as its layer's manifest lists it. */248export type SealedCheckInput<Area extends string = string> = Omit<249 typeof SealedCheck.Encoded,250 "area"251> & { readonly area: Area };252293/** A layer manifest's default export, as data. */253export type LayerManifestDefinition = typeof LayerManifest.Encoded;254255const manifestOf = checked(LayerManifest);256298/**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. */258export const layerManifest = <Area extends string>(config: {259 readonly checks: readonly SealedCheckInput<Area>[];260 readonly knownBad?: readonly string[];261 readonly layer: string;
6 unmodified lines
modified:packages/sdk/test/sdk.test.ts-1 removed
24 unmodified lines
2526const redThenGreen = (path: string) =>27 RedThenGreen.make({ path: RedThenGreen.fields.path.make(path) });2829// A name a migrate moves from or to: `from` and `to` share one schema.29const symbol = (name: string) => Migrate.fields.from.make(name);3031const askFile = (id: string) => `${Brand.configDir}/asks/${id}.ask.ts`;32
482 unmodified lines
modified:packages/sdk/test/visibility.test.ts-3 removed
20 unmodified lines
21const decodePolicy = Schema.decodeUnknownSync(VisibilityPolicy);2223const decodeManifest = Schema.decodeUnknownSync(LayerManifest);2425// One held-back check as a layer's manifest lists it.25const exportCheck = {26 area: "export",27 author: "alice",28 clause: {
3 unmodified lines
32 },33 path: "checks/export/escapes-titles.test.ts",34} as const;3537// A `visibility.ts` as the platform reads it: every default the38// example leaves unsaid is filled, and nothing names a path or a check.36const osrPolicy = {37 checks: {38 admit: { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 },39 areas: { export: "src/export/**", parser: "src/parser/**" },
361 unmodified lines
modified: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 */1import { DateTime, Duration } from "effect";2import type { Effect } from "effect";3import { TestClock } from "effect/testing";410/** An ISO 8601 instant, such as `2026-10-07T12:00:00Z`, as a UTC date-time. */5export const at = (iso: string): DateTime.Utc =>6 DateTime.toUtc(DateTime.makeUnsafe(iso));714/** The instant every scenario starts at unless it is given another. */8export const defaultNow: DateTime.Utc = at("2026-10-07T12:00:00Z");910/**11 * Moves the TestClock to an instant, waking everything that sleeps until then:
1 unmodified line
13 */14export const advanceTo = (iso: string): Effect.Effect<void> =>15 TestClock.setTime(DateTime.toEpochMillis(at(iso)));1624/** `n` hours, the unit claims are warned and lapsed in. */17export 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 */11import { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";12import {13 Data,
8 unmodified lines
22import { constVoid } from "effect/Function";2324import { defaultNow } from "./clock.ts";2541/** A git object id, branded as `@repo/artifacts`' `ObjectId` is. */26export const ObjectId = Schema.String.pipe(27 Schema.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),28 Schema.brand("ObjectId")29);3031export type ObjectId = typeof ObjectId.Type;3249/** A short branch name, branded as `@repo/artifacts`' `BranchName` is. */33export const BranchName = Schema.String.pipe(34 Schema.check(35 Schema.isPattern(36 /^(?!refs\/)(?!.*\.\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u
3 unmodified lines
40);4142export type BranchName = typeof BranchName.Type;4361/** Where a read starts, as `@repo/artifacts`' `Revision` has it. */44export type Revision = Data.TaggedEnum<{45 Branch: { readonly name: BranchName };46 Commit: { readonly sha: CommitSha };47}>;4849export const Revision = Data.taggedEnum<Revision>();5069/** What a host fails with: `RepoHost`'s errors, by shape. */51export 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 lines
86 readonly name: string;87 readonly remote: string;88}89109/**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 */90export interface HostLike {91 readonly create: (name: RepoName) => Effect.Effect<HostCreated, HostError>;92 readonly importFrom: (93 name: RepoName,
46 unmodified lines
140 ) => Effect.Effect<readonly HostCommit[], HostError>;141}142143export 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}156189/** A refusal the binding throws, before it becomes the thrown error. */157class Refused extends Data.TaggedError("Refused")<{158 readonly code: ArtifactsError["code"];159 readonly reason: string;160}> {}
14 unmodified lines
175 Match.when("INTERNAL_ERROR", () => numericCodes.INTERNAL_ERROR),176 Match.orElse(() => 0)177 );178212/** A host's error as the binding words it; a refusal stays as it is. */179const refusalOf = (error: HostError | Refused) =>180 Match.valueTags(error, {181 ForkInProgress: ({ name }) =>182 new Refused({
18 unmodified lines
201 reason: `Repository not found: ${name}`,202 }),203 });204239/** The repos the fake made, with what `info()` and `list()` report. */205interface Kept {206 readonly id: string;207 readonly name: RepoName;208 readonly description: string | null;
17 unmodified lines
226const decodeBranch = Schema.decodeUnknownOption(BranchName);227228const decodePath = Schema.decodeUnknownOption(RepoPath);229265/**266 * `main` → that branch; 40 hex digits → that commit; anything else, such as267 * `refs/heads/main` or a tag, resolves to nothing.268 */230const 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 lines
248 name: entry.name,249 type: typeOf(entry),250});251291// The times the host read from the commit itself, in Unix seconds.252const metadataOf = (commit: HostCommit): ArtifactsCommitMetadata => ({253 author: { email: commit.author.email, name: commit.author.name },254 authoredAt: commit.authoredAt,255 committedAt: commit.committedAt,
20 unmodified lines
276277const blobOf = (bytes: Uint8Array) =>278 new Blob([bytes], { type: "application/octet-stream" });279320/** An Artifacts binding over `host`, with the real one's surprises (see the module's doc). */280export 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>();289332 /** 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 line
295 name: "ArtifactsError" as const,296 numericCode: numericOf(code),297 });298342 /** 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 );303348 /** 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 line
309 name: "ArtifactsError" as const,310 numericCode: 0,311 });312358 /** 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 lines
347348 return repo;349 };350397 /**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, {})));353354 const mint = (name: RepoName, scope: "read" | "write", seconds: number) =>
19 unmodified lines
374375 return { expiresAt, id: token.id, plaintext, scope: token.scope };376 });377429 /** 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 lines
389 token: token.plaintext,390 };391 });392445 /** 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 lines
475 const ref = logOptions?.ref ?? "HEAD";476 const limit = Math.min(logOptions?.limit ?? 50, 1000);477 const offset = logOptions?.offset ?? 0;478532 // `HEAD` is the repo's default branch.479 const at = revisionOf(480 ref === "HEAD" ? (yield* keptOf(name)).defaultBranch : ref481 );482
181 unmodified lines
modified:packages/testkit/src/git-client.ts-5 removed
1 unmodified line
2import { Effect } from "effect";3import { init, writeBlob, writeCommit, writeTree } from "isomorphic-git";4import type { FsClient, TreeEntry } from "isomorphic-git";56/** Paths and their text, such as `[["src/a.ts", "v1"]]`. */6export type Files = readonly (readonly [path: string, content: string])[];78// Fixed, so the same files and parents always make the same commit id.9const signature = {
2 unmodified lines
12 timestamp: 1_791_300_000,13 timezoneOffset: 0,14};1517/**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 */16export const gitClient = (fs: FsClient) =>17 Effect.gen(function* () {18 const source = { fs, gitdir: "/client.git" };19
63 unmodified lines
modified:packages/testkit/src/git.ts-3 removed
23 unmodified lines
2425const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>26 bytes.pipe(Stream.decodeText(), Stream.mkString);2728/** Spawns a process and hands back its handle, for callers that feed stdin. */28export const spawn = (29 command: string,30 args: readonly string[],31 options: ChildProcess.CommandOptions
11 unmodified lines
43 })44 )45 ).pipe(Effect.orDie);4648/** Runs git in `cwd` to the end; a failing git is a result, not an error. */47export const git = (cwd: string, ...args: string[]) =>48 Effect.scoped(49 Effect.gen(function* () {50 const child = yield* spawn("git", args, { cwd });
6 unmodified lines
57 return { exitCode, stderr, stdout } satisfies Ran;58 })59 );6063/** Runs git and returns its trimmed output; a failing git fails the test. */61export const gitOk = (cwd: string, ...args: string[]) =>62 Effect.flatMap(git(cwd, ...args), (ran) =>63 ran.exitCode === 064 ? Effect.succeed(ran.stdout.trim())
4 unmodified lines
modified: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 */1import { Brand } from "@repo/brand";2import { Config, Context, Effect, FileSystem } from "effect";311/**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 */4export const GoldenDir = Context.Reference<string>("testkit/GoldenDir", {5 defaultValue: () => "test/golden",6});7
17 unmodified lines
25const lastRewrite = (line: string) =>26 line.split("\r").findLast((version) => version !== "") ?? "";2728/**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 */33export const normaliseGitOutput = (text: string): string =>34 text35 .split(/\r?\n/u)
9 unmodified lines
45// Letters on either side make it another word, not the product's name:46// the rule `brand:check` applies.47const NAME = new RegExp(`(?<![a-z])${Brand.slug}(?![a-z])`, "giu");4863/**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`). */50const unbranded = (text: string) =>51 text.replaceAll(Brand.configDir, "<configDir>").replaceAll(NAME, "<brand>");5272/** The lines that differ, as `- golden` and `+ actual`, in order. */53const difference = (golden: string, actual: string) => {54 const was = golden.split("\n");55 const now = actual.split("\n");56
8 unmodified lines
65 .flat()66 .join("\n");67};6889/**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. */70export const expectGolden = (71 name: string,72 text: string73): Effect.Effect<void, never, FileSystem.FileSystem> =>
36 unmodified lines
modified:packages/testkit/src/http-backend.ts+2 added-14 removed
29 unmodified lines
3031 return -1;32};3334/** A CGI reply (`Status:` and headers, a blank line, the body) as a Response. */34const 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 lines
5051 return new Response(output.slice(cut + 4), { headers, status });52};5355/** `…/<repo>.git/info/refs` and the two service calls: what smart HTTP asks for. */54const SMART_HTTP =55 /\/(?<repo>[^/]+)\.git\/(?<path>info\/refs|git-upload-pack|git-receive-pack)$/u;5657const notFound = () =>58 new Response("not a smart-HTTP git URL", { status: 404 });5962/**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. */61const bytes = () =>62 new TransformStream<unknown, Uint8Array>({63 transform: (chunk, controller) => {64 if (chunk instanceof Uint8Array) {
5 unmodified lines
70 }71 },72 });7379/** A request's body as the CGI's stdin; a request without one gives none. */74const stdinOf = (request: Request) => {75 const { body } = request;7677 return body === null
3 unmodified lines
81 onError: (cause) => cause,82 }).pipe(Stream.orDie);83};8491/**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. */86export const httpBackend =87 (root: string) =>88 (89 request: Request
36 unmodified lines
modified: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.3import { Brand } from "@repo/brand";4import { Ask } from "@repo/protocol/domain/ask";5import { CheckSpec } from "@repo/protocol/domain/check";6import { Command, SymbolName } from "@repo/protocol/domain/common";
14 unmodified lines
21import type { Types } from "effect";2223import { defaultNow } from "./clock.ts";2437/** An ask kind as a test writes it, before decoding. */25export type AskKindEncoded = typeof AskKind.Encoded;2640/** A project at one landed commit, with the people a test acts as. */27export 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}3536type ScenarioFields = Omit<Scenario, "pipe">;
41 unmodified lines
7879 return word - low + mixed;80};8199/** FNV-1a (32-bit) over the UTF-8 bytes of `text`, as eight hex digits. */82const fnv1a = (text: string) => {83 let hash = 0x81_1c_9d_c5;8485 for (const byte of new TextEncoder().encode(text)) {
12 unmodified lines
98 CommitSha.make(99 [0, 1, 2, 3, 4].map((round) => fnv1a(`${round}:${seed}`)).join("")100 );101120/** `prefix-000001`, `prefix-000002`, …: one counter per call of `ids()`. */102const counter = (prefix: string) => {103 let next = 0;104105 return () => {
2 unmodified lines
108 return `${prefix}-${String(next).padStart(6, "0")}`;109 };110};111131/**132 * Fresh counters for the ids a project mints: `req-000001`, `prop-000001`,133 * `dec-000001`. Each call starts again at 1.134 */112export const ids = () => {113 const request = counter("req");114 const proposal = counter("prop");115 const decision = counter("dec");
38 unmodified lines
154const encodeTerritory = Schema.encodeSync(Territory);155156const encodeCheck = Schema.encodeSync(CheckSpec);157181/**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 */158export const aProject = (159 options: {160 readonly name?: string;161 readonly now?: DateTime.Utc;
47 unmodified lines
209 project: ProjectName.make(name),210 });211};212241/** `packages/parser` → its module `parser` and its paths `packages/parser/**`; `.` → the whole repo. */213const territoryOf = (folder: string) =>214 decodeTerritory(215 folder === "."216 ? { module: ".", paths: ["**"] }
2 unmodified lines
219 paths: [`${folder}/**`],220 }221 );222252/** An ask as `withAsk` takes it. */223interface 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}233266/**267 * Opens `ask` over `territory` in the scenario, and records the territory as268 * a module when `module` says it is one.269 */234const openAsk = (235 scenario: Scenario,236 ask: AskOptions,237 territory: Territory,
40 unmodified lines
278 modules: module && !known ? [...modules, territory] : modules,279 });280};281318/**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 */282export const withAsk =283 (ask: AskOptions) =>284 (scenario: Scenario): Scenario =>285 openAsk(scenario, ask, territoryOf(ask.territory), ask.territory !== ".");286330/** Adds an ask kind, in place of one with the same name. */287export const withKind =288 (kind: AskKindEncoded) =>289 (scenario: Scenario): Scenario => {290 const added = decodeKind(kind);
6 unmodified lines
297 : [...kinds, added],298 });299 };300345/** Adds the vouch file's lines: `handles` vouched for, then `denounced`. */301export const withVouches =302 (handles: readonly string[], denounced: readonly string[] = []) =>303 (scenario: Scenario): Scenario =>304 withPolicy(scenario, {
10 unmodified lines
315 })),316 ],317 });318364/** `legacyFetch` → `legacy-fetch`, `http.get` → `http-get`: a name an ask id can carry. */319const words = (symbol: string) =>320 symbol321 .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower>-$<upper>")322 .toLowerCase()
1 unmodified line
324 .replaceAll(/^-|-$/gu, "");325326const packages = Arr.makeBy(6, (n) => `packages/p${n + 1}`);327374/** The six packages together: where a family's parent and delete child reach. */328const allSix = decodeTerritory({329 module: ".",330 paths: Arr.map(packages, (folder) => `${folder}/**`),331});332380/**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 */333export const sixChildren = (334 options: { readonly symbol?: string; readonly to?: string } = {}335): Scenario => {336 const symbol = options.symbol ?? "legacyFetch";
56 unmodified lines
modified: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 */6import { Predicate } from "effect";713/** What reading `name.member` hit: a member the test did not give. */8export class TouchedError extends Error {9 constructor(name: string, member: string) {10 super(`a test touched ${name}.${member}`);11 this.name = "TouchedError";
25 unmodified lines
modified:packages/testkit/test/fake-artifacts-binding.test.ts-10 removed
20 unmodified lines
21 readonly name: RepoName;22 readonly reason: string;23}> {}2425/** What a promise of the binding threw. */25class Thrown extends Data.TaggedError("Thrown")<{ readonly error: Error }> {}2627const commit = CommitSha.make("c".repeat(40));28
6 unmodified lines
35const hello = new TextEncoder().encode("hello\n");3637const answerer = { email: "answerer@example.com", name: "Answerer" };3840/** The one commit every repo holds on `main`. */39const firstCommit = {40 author: answerer,41 authoredAt: 1_791_300_000,42 committedAt: 1_791_300_060,
3 unmodified lines
46 sha: commit,47 tree,48};4952/**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 */50const tinyHost = (): HostLike => {51 const repos = new Set<RepoName>();52 let minted = 0;53
88 unmodified lines
142 revokeToken: (name) => known(name).pipe(Effect.as(true)),143 };144};145152/** Awaits one of the binding's promises. */146const call = <A>(run: () => Promise<A>) =>147 Effect.tryPromise({148 catch: (error) =>149 new Thrown({
1 unmodified line
151 }),152 try: run,153 });154162/** What one of the binding's promises threw, or an error saying it resolved. */155const thrown = <A>(run: () => Promise<A>) =>156 call(run).pipe(157 Effect.match({158 onFailure: ({ error }) => error,
3 unmodified lines
162163const text = (bytes: Blob | null) =>164 bytes === null ? Effect.succeed(null) : call(() => bytes.text());165174/** An error as a plain record: its name and message, and its code and number if it has them. */166const 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});173183/** A binding over a fresh tiny host, with `datekit` made, and the repo `get` hands back. */174const withDatekit = (175 options: Parameters<typeof fakeArtifactsBinding>[1] = {}176) =>177 Effect.gen(function* () {
284 unmodified lines
modified:packages/testkit/test/golden.test.ts-6 removed
6 unmodified lines
7import { expectGolden, GoldenDir, normaliseGitOutput } from "../src/golden.ts";89const id = "0123456789abcdef0123456789abcdef01234567";1011/**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 */11const 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 lines
3738 return yield* git(work, "push", remote, "HEAD:refs/heads/main");39}).pipe(Effect.scoped);4045/** What a failed expectation says, or nothing when it passed. */41const complaint = (exit: Exit.Exit<void>) =>42 Exit.isFailure(exit) ? String(Cause.squash(exit.cause)) : "";4349/** Runs with golden files in a fresh folder, and `UPDATE_GOLDEN` as given. */44const inTempGoldens = <A, E, R>(45 update: string,46 run: (dir: string) => Effect.Effect<A, E, R>47) =>
215 unmodified lines
modified: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 */11import {12 ParsedEnvSpecFunctionArgs,13 ParsedEnvSpecFunctionCall,
23 unmodified lines
37 ParsedNamedArg,38 ParsedValue,39} from "../env-schema.ts";4043/** A value node of the parser's tree. */41type ValueNode =42 | ParsedEnvSpecArrayLiteral43 | ParsedEnvSpecFunctionArgs44 | ParsedEnvSpecFunctionCall45 | ParsedEnvSpecObjectLiteral46 | ParsedEnvSpecStaticValue;4751/** A static value: text, a number, a flag, or none for `undefined`. */48const staticOf = (49 node: ParsedEnvSpecStaticValue50): Option.Option<ParsedValue> => {51 const value: unknown = node.value;
4 unmodified lines
56 ? Option.some(value)57 : Option.none();58};5964/** A node as plain data, never evaluated; none for a static `undefined`. */60const 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 | ParsedEnvSpecKeyValuePair
40 unmodified lines
105106 return Option.some(Array.getSomes(node.values.map(valueOf)));107};108115/** The decorators as written, but those set to `undefined`. */109const decoratorsOf = (110 decorators: readonly ParsedEnvSpecDecorator[]111): readonly ParsedDecorator[] =>112 Array.getSomes(
4 unmodified lines
117 )118 )119 );120128/** The text of an item's value, if it has one: `KEY=` and `KEY=undefined` have none. */121const valueTextOf = (item: ParsedEnvSpecConfigItem): Option.Option<string> => {122 const { value } = item;123124 if (value === undefined) {
4 unmodified lines
129 ? Option.map(staticOf(value), String)130 : Option.some(value.toString());131};132141/** One item: its key, its description comment, its decorators, its value's text. */133const itemOf = (item: ParsedEnvSpecConfigItem): ParsedItem => {134 const parsed: Types.Mutable<ParsedItem> = {135 decorators: decoratorsOf(item.decoratorsArray),136 key: item.key,
11 unmodified lines
148149 return parsed;150};151161/** Where the parser stopped, as its syntax errors carry it. */152const Stopped = Schema.Struct({153 location: Schema.Struct({154 start: Schema.Struct({ column: Schema.Int, line: Schema.Int }),155 }),156});157168/** Why a text is not a schema: where it stops parsing, never the text itself. */158const unreadable = (file: RepoPath, cause: unknown) =>159 new EnvSchemaUnreadable({160 file,161 reason: Option.match(Schema.decodeUnknownOption(Stopped)(cause), {
21 unmodified lines
modified: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 */1import type { RepoPath } from "@repo/protocol/ids";2import { Effect, Layer } from "effect";34import {
20 unmodified lines
modified: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).3import { Effect, Layer, Option, Redacted, Schema } from "effect";45import {6 admitLength,
8 unmodified lines
15 * be found and sealed again.16 */17const KEY_VERSION = 1;1827/** AES-GCM's recommended IV size. */19const IV_BYTES = 12;2030/** AES-256: the data key and the master key are 32 bytes each. */21const KEY_BYTES = 32;2223/**24 * Values are padded to a multiple of this many bytes before sealing, so a
1 unmodified line
26 * falls in, not the length itself.27 */28const PAD_TO = 64;2940/** The padding's first byte (ISO/IEC 7816-4): `0x80`, then zeros. */30const PAD_MARK = 0x80;3143/** `MASTER_KEY` is not 32 bytes as 64 hex characters. Never names the key. */32class MasterKeyUnusable extends Schema.TaggedError<MasterKeyUnusable>()(33 "MasterKeyUnusable",34 {}35) {}
9 unmodified lines
4546const decodeBase64 = (text: string) =>47 Effect.map(Schema.decodeEffect(Schema.Uint8ArrayFromBase64)(text), owned);4861/** The value's UTF-8 bytes, then `0x80`, then zeros to the next step. */49const 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 lines
5556 return out;57};5872/** The bytes before the padding; none when the padding is not there. */59const unpadded = (bytes: Uint8Array) => {60 const end = bytes.findLastIndex((byte) => byte !== 0);6162 return end !== -1 && bytes[end] === PAD_MARK63 ? Option.some(bytes.subarray(0, end))64 : Option.none();65};6681/** The master key's 32 bytes, decoded from its hex; a defect for any other form. */67const masterKeyBytes = (masterKey: Redacted.Redacted) =>68 Schema.decodeEffect(Schema.Uint8ArrayFromHex)(Redacted.value(masterKey)).pipe(69 Effect.mapError(() => new MasterKeyUnusable()),70 Effect.filterOrFail(
4 unmodified lines
75 Effect.orDie76 );7778/**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 */82const importMasterKey = (bytes: Uint8Array<ArrayBuffer>) =>83 Effect.promise(() =>84 crypto.subtle.importKey("raw", bytes, "AES-KW", false, [
1 unmodified line
86 "unwrapKey",87 ])88 );89106/** A fresh data key, from WebCrypto's random bytes, extractable only to be wrapped. */90const freshDataKey = Effect.sync(() =>91 crypto.getRandomValues(new Uint8Array(KEY_BYTES))92).pipe(93 Effect.flatMap((raw) =>
2 unmodified lines
96 ).pipe(Effect.ensuring(Effect.sync(() => raw.fill(0))))97 )98);99117/** Seals `value` under a fresh data key, wrapped by `master`. */100const seal = (master: CryptoKey, input: ValueToSeal) =>101 Effect.gen(function* () {102 yield* admitLength(input);103
28 unmodified lines
132 wrappedKey: wrappedKeyText,133 } satisfies SealedValue;134 });135154/** Opens a sealed value; a defect naming the step that failed when it does not open. */136const unseal = (master: CryptoKey, sealed: SealedValue) =>137 Effect.gen(function* () {138 if (sealed.keyVersion !== KEY_VERSION) {139 return yield* new SealedValueUnopenable({ step: "keyVersion" });
46 unmodified lines
186 ),187 });188 }).pipe(Effect.orDie);189209/**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. */191export const WriteOnlyValuesWebCrypto = (192 masterKey: Redacted.Redacted193): Layer.Layer<WriteOnlyValues> =>194 Layer.effect(
16 unmodified lines
modified:packages/visibility/src/commitment.ts+2 added-29 removed
1 unmodified line
2import type { AreaName, BlobSha, RepoPath } from "@repo/protocol/ids";3import { SuiteRoot } from "@repo/protocol/ids";4import { Array, Effect, Option, Order } from "effect";56/** One held-back check file: where it sits in its layer, its area, and its blob. */6export interface SuiteFile {7 readonly path: RepoPath;8 readonly area: AreaName;9 readonly blob: BlobSha;
6 unmodified lines
16const AREA = Uint8Array.of(0x02);1718const utf8 = (text: string) => new TextEncoder().encode(text);1921/**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 */20const sha256 = (...parts: readonly Uint8Array[]) =>21 Effect.promise(() =>22 crypto.subtle.digest(23 "SHA-256",
38 unmodified lines
62 LEAF_SEPARATOR,63 utf8(file.blob)64 );6572/** Each area's root as bytes, the areas sorted by name. */66const 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 lines
78 Effect.map((root) => [area, root] as const)79 )80 );8189/**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. */83export const areaRoots = (84 salt: Uint8Array,85 files: readonly SuiteFile[]86): Effect.Effect<ReadonlyMap<AreaName, SuiteRoot>> =>
2 unmodified lines
89 (areas) => new Map(areas.map(([area, root]) => [area, rootOf(root)]))90 )91 );92105/**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. */94export const suiteRoot = (95 salt: Uint8Array,96 files: readonly SuiteFile[]97): Effect.Effect<SuiteRoot> =>
17 unmodified lines
115 )116 )117);118136/**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 */119export const heldBackValue = (input: {120 readonly results: readonly HeldBackResult[];121 readonly areas: readonly AreaName[];122}): Option.Option<string> => {
24 unmodified lines
147 ).join("; ")148 );149};150174/**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 */151export const heldBackTrailer = (input: {152 readonly results: readonly HeldBackResult[];153 readonly areas: readonly AreaName[];154}): Option.Option<string> =>
1 unmodified line
modified: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.3import { RepoPath } from "@repo/protocol/ids";4import { Array, Context, Effect, Predicate, Result, Schema } from "effect";512/**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)`. */7export type ParsedValue =8 | string9 | number10 | boolean11 | readonly ParsedValue[]12 | ParsedCall13 | ParsedArgs;1427/** One `key=value` argument. */15export interface ParsedNamedArg {16 readonly key: string;17 readonly value: ParsedValue;18}1933/** Arguments as written: the positional ones, then the `key=value` ones. */20export interface ParsedArgs {21 readonly positional: readonly ParsedValue[];22 readonly named: readonly ParsedNamedArg[];23}2439/** A function call, never run, and its text as written: `enum(development, test)`. */25export interface ParsedCall extends ParsedArgs {26 readonly fn: string;27 readonly text: string;28}2945/** One decorator: `@sensitive`, `@type=string(minLength=32)`, `@import(../shared/)`. */30export interface ParsedDecorator {31 readonly name: string;32 readonly value: ParsedValue;33}3451/** One item: its key, its description comment, its decorators, and its value text if it has one. */35export interface ParsedItem {36 readonly key: string;37 readonly description?: string;38 readonly decorators: readonly ParsedDecorator[];39 readonly value?: string;40}4159/**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 */42export interface ParsedEnvSchema {43 readonly header: readonly ParsedDecorator[];44 readonly items: readonly ParsedItem[];45 readonly imports: readonly string[];46}4770/**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. */49export class EnvSchemaUnreadable extends Schema.TaggedError<EnvSchemaUnreadable>()(50 "EnvSchemaUnreadable",51 { file: RepoPath, reason: Schema.String }52) {}5379/** Parses a `.env.schema`'s text; reads nothing else. */54export class EnvSchemaParser extends Context.Service<55 EnvSchemaParser,56 {57 readonly parse: (
2 unmodified lines
60 ) => Effect.Effect<ParsedEnvSchema, EnvSchemaUnreadable>;61 }62>()("visibility/EnvSchemaParser") {}6390/** Whether a value is a function call as written (`forEnv(production)`). */64export const isCall = (value: ParsedValue): value is ParsedCall =>65 Predicate.hasProperty(value, "fn");6694/** Whether a value is arguments alone: a bare call's or an object's. */67export const isArgs = (value: ParsedValue): value is ParsedArgs =>68 Predicate.hasProperty(value, "named") && !isCall(value);6998/** Whether a value is a list as written (`[GET, POST]`). */70export const isList = (value: ParsedValue): value is readonly ParsedValue[] =>71 Array.isArray(value);72102/** A path that starts outside any repo: the home folder, the root, a drive or a scheme (`C:`, `https:`). */73const OUTSIDE = /^(?:~|[/\\]|[A-Za-z][\w+.-]*:)/u;74105/**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 */75const repoImport = (76 file: RepoPath,77 written: string78): Result.Result<RepoPath, string> => {
24 unmodified lines
103 );104};105106/**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 */111export const withImports = (112 file: RepoPath,113 parsed: Pick<ParsedEnvSchema, "header" | "items">
21 unmodified lines
modified: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.3import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";4import { EnvKey } from "@repo/protocol/ids";5import type { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";6import { Array, Option, Predicate, Schema } from "effect";
7 unmodified lines
14 ParsedItem,15 ParsedValue,16} from "./env-schema.ts";1722/** The header's decorators, above its `# ---`. */18type Header = ParsedEnvSchema["header"];1925/** The value of the named argument `key`, if the arguments carry one. */20const namedArg = (args: ParsedArgs, key: string): Option.Option<ParsedValue> =>21 Option.map(22 Array.findFirst(args.named, (arg) => arg.key === key),23 ({ value }) => value24 );2532/**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. */27const firstNamed = (28 decorators: readonly ParsedDecorator[],29 ...names: readonly string[]30): Option.Option<ParsedDecorator> =>31 Array.findFirst(decorators, ({ name }) => names.includes(name));3242/**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. */34const flagOf = (35 decorators: readonly ParsedDecorator[],36 flag: string,37 opposite: string
5 unmodified lines
4344 return name === flag ? value : !value;45 });4661/** The proxy rule the env shape holds: hosts, and what narrows them. */47type Proxy = NonNullable<EnvItem["proxy"]>;4864/** Text, or a list of texts (`[GET, POST]`), as a list; none when it is anything else. */49const textsOf = (value: ParsedValue): Option.Option<readonly string[]> => {50 const each = Predicate.isString(value) ? [value] : value;5152 return isList(each) && each.every(Predicate.isString)
15 unmodified lines
68 Option.exists(textsOf(targets), (each) => each.includes("header")),69 });7071/**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 lines
112113 return Option.some(rule);114 });115134/** Whether the item is routed through `@proxy(…)`: any `@proxy` but `=passthrough` and `=omit`. */116const isProxied = (item: ParsedItem): boolean =>117 item.decorators.some(118 ({ name, value }) =>119 name === "proxy" && value !== "passthrough" && value !== "omit"120 );121122/**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 */126export const proxyOf = (item: ParsedItem): Option.Option<Proxy> => {127 const rules = Array.getSomes(128 Array.map(item.decorators, ({ name, value }): Option.Option<Proxy> =>
21 unmodified lines
150 };151 });152};153175/** The data types varlock builds in; none of them makes an item sensitive. */154const builtInTypes = [155 "array",156 "boolean",157 "domain",
24 unmodified lines
182183 return !builtInTypes.some((builtIn) => builtIn === type);184 });185208/**209 * `@sensitive` with options (`{enabled=forEnv(production), preventLeaks=false}`)210 * as the flag its `enabled` says, which is `true` when it says nothing.211 */186const enabledOf = (decorator: ParsedDecorator): ParsedDecorator =>187 decorator.name === "sensitive" && isArgs(decorator.value)188 ? {189 name: decorator.name,
3 unmodified lines
193 ),194 }195 : decorator;196223/**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 */197const defaultSensitive = (key: string, value: ParsedValue): boolean => {198 if (Predicate.isBoolean(value)) {199 return value;200 }
6 unmodified lines
207 return !Predicate.isString(prefix) || !key.startsWith(prefix);208};209210/**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 */215export const isSensitive = (item: ParsedItem, header: Header): boolean =>216 isProxied(item) ||217 Option.match(flagOf(item.decorators.map(enabledOf), "sensitive", "public"), {
5 unmodified lines
223 }),224 onSome: (flag) => flag !== false,225 });226261/**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 */227export const requiredOf = (228 item: ParsedItem,229 header: Header230): boolean | "depends" =>
9 unmodified lines
240 },241 })242 );243284/** A value as the schema writes it: `enum(development, test)`, `[GET, POST]`, `url`. */244const textOf = (value: ParsedValue): string => {245 if (isCall(value)) {246 return value.text;247 }
12 unmodified lines
260261 return String(value);262};263305/** Every tag the item's `@tag(…)`s attach, in order, each once. */264const tagsOf = (item: ParsedItem): readonly string[] =>265 Array.dedupe(266 item.decorators.flatMap(({ name, value }) =>267 name === "tag" && isArgs(value)
4 unmodified lines
272 : []273 )274 );275318/** The link of the item's first `@docs(url)` or `@docs(label, url)`. */276const 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 );282326/** One item as the public sees it: its declaration, never a value. */283const itemOf = (284 item: ParsedItem & { readonly key: EnvKey },285 header: Header286): EnvItem => {
51 unmodified lines
338339 return shown;340};341386/** An item the shape can name: its key is an env key (`PAYMENTS_KEY`). */342const isNamed = (343 item: ParsedItem344): item is ParsedItem & { readonly key: EnvKey } => Schema.is(EnvKey)(item.key);345391/** The item `@currentEnv` names (`@currentEnv=$APP_ENV`), if it names one. */346const 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;350351 return Schema.is(EnvKey)(key) ? Option.some(key) : Option.none();352 });353400/** The env shape of one parsed `.env.schema` at a landed SHA. */354export const envSchemaViewOf = (input: {355 readonly at: LandedSha;356 readonly file: RepoPath;357 readonly parsed: ParsedEnvSchema;
22 unmodified lines
modified:packages/visibility/src/guards.ts+9 added-24 removed
3 unmodified lines
4import { LayerContentInPublicTree } from "@repo/protocol/refusal";5import type { PrivatePathInPublicTree } from "@repo/protocol/refusal";6import { Array, Option, Order } from "effect";78/** The paths, once each and sorted, or none when there are none. */8const named = (paths: readonly RepoPath[]) =>9 Array.match(Array.dedupe(Array.sort(paths, Order.String)), {10 onEmpty: Option.none,11 onNonEmpty: Option.some,12 });1315/** Files the answer puts into the public tree: added, or modified to a new blob. */14const written = (changes: readonly Change[]) =>15 changes.filter((change) => change.status !== "deleted");1617/**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 */24export const privatePaths: (input: {25 readonly changes: readonly Change[];26 readonly layerPaths: ReadonlySet<RepoPath>;27 readonly pusherCanRead: boolean;28}) => Option.Option<PrivatePathInPublicTree> = layerPathRefusal;2930/**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 */36export const writeDown = (input: {37 readonly changes: readonly Change[];38 readonly layerBlobs: ReadonlySet<BlobSha>;
14 unmodified lines
modified: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 */1export { EnvSchemaParser, EnvSchemaUnreadable } from "./env-schema.ts";23export type {4 ParsedArgs,
11 unmodified lines
modified: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.3import type { RepoHost } from "@repo/artifacts/repo-host";4import { Context } from "effect";56export class LayerRepos extends Context.Service<
3 unmodified lines
modified:packages/visibility/src/leak-scan.ts+4 added-23 removed
30 unmodified lines
31// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE32// SOFTWARE.3334/**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 */40import type { EnvKey } from "@repo/protocol/ids";41import { Option, Redacted, Schema, Stream } from "effect";42import type { Effect } from "effect";4344import { charactersIn, HARD_MIN_LENGTH } from "./vault.ts";4547/** A stored value to look for, and the item it belongs to. */46export interface Watched {47 readonly key: EnvKey;48 readonly value: Redacted.Redacted;49}5053/** One watched item and every form of its value the scan looks for. */51interface Needle {52 readonly forms: readonly string[];53 readonly key: EnvKey;54}5559/** Every value's forms, in the order the items were given, and the longest form. */56interface Needles {57 readonly longest: number;58 readonly needles: readonly Needle[];59}
30 unmodified lines
90 : [run, run.replaceAll("+", "-").replaceAll("/", "_")];91 });92};9398/**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 */94const formsOf = (value: string) => [95 ...new Set([96 value,97 JSON.stringify(value).slice(1, -1),
2 unmodified lines
100 ...base64Forms(value),101 ]),102];103113/** The forms of every value long enough to look for. */104const needlesOf = (values: readonly Watched[]): Needles => {105 const needles = values.flatMap(({ key, value }) => {106 const text = Redacted.value(value);107
10 unmodified lines
118 needles,119 };120};121132/** The first watched item any form of whose value `text` contains. */122const 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 lines
148149 return 0;150};151163/** The item whose stored value `text` holds, in any of its forms; none when it holds none. */152export const scanText = (153 text: string,154 values: readonly Watched[]155): Option.Option<EnvKey> => firstLeak(text, needlesOf(values));156169/** As `scanText`, over bytes read as UTF-8 (bytes that are not text match nothing). */157export const scanBytes = (158 bytes: Uint8Array,159 values: readonly Watched[]160): Option.Option<EnvKey> => scanText(new TextDecoder().decode(bytes), values);161175/**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 */162export 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 lines
modified:packages/visibility/src/ledger.ts+2 added-14 removed
16 unmodified lines
17 onNone: (): readonly Layer[] => [],18 onSome: (policy) => policy.layers,19 });2021/**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. */22export const ledgerOf = (input: {23 readonly project: ProjectName;24 readonly visibility: Option.Option<VisibilityPolicy>;25 readonly licence: Option.Option<string>;
9 unmodified lines
35 project: input.project,36 };37};3844/** What the ledger records of a layer's declaration: what it holds and discloses. */39const declared = (layer: Layer) =>40 `${layer.disclose}:${Array.sort(layer.holds, Order.String).join(",")}`;4148/**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. */43export const entriesForPolicy = (44 before: Option.Option<VisibilityPolicy>,45 after: Option.Option<VisibilityPolicy>,46 seq: number,
19 unmodified lines
modified:packages/visibility/src/posture.ts+2 added-20 removed
141 unmodified lines
142143// Kinds whose files would ship: a layer holding one keeps shipped code closed.144const SHIPPED: ReadonlySet<LayerKind> = new Set(["fix", "source"]);145146/**147 * A layer that narrows what the public sees: neither a personal layer, which148 * gates nothing, nor a public one, which everyone reads.149 */146const narrowing = (layer: Layer) =>147 layer.audience !== "personal" && layer.audience !== "public";148149const ships = (layer: Layer) => layer.holds.some((kind) => SHIPPED.has(kind));
4 unmodified lines
154const days = (count: number) => (count === 1 ? "1 day" : `${count} days`);155156const labelled = (posture: Posture, label: string) => ({ label, posture });157162/** The posture from the layers alone (the table's first four rows). */158const fromLayers = (visibility: VisibilityPolicy) => {159 const layers = visibility.layers.filter(narrowing);160 const shipping = layers.filter(ships);161
28 unmodified lines
190 : `Open with sealed evidence · sealed checks in ${sorted(areas)}`191 );192};193199/**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. */195export const postureOf = (input: {196 readonly visibility: Option.Option<VisibilityPolicy>;197 readonly licence: Option.Option<string>;198}): { readonly posture: Posture; readonly label: string } =>
3 unmodified lines
202 onNone: () => labelled("open", "Open"),203 onSome: fromLayers,204 });205219// The postures, from Open down.206const FURTHER_FROM_OPEN: readonly Posture[] = [207 "open",208 "openWithSealedEvidence",209 "openOnSchedule",210 "openCore",211 "sourceAvailable",212];213228/**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. */215export 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.2import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";3import type { EnvKey } from "@repo/protocol/ids";4import { Option, String } from "effect";513/** One host whose requests the platform intercepts for one item. */6export 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}1415/**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 */19export const placeholderFor = (item: EnvItem): string =>20 Option.fromUndefinedOr(item.placeholder).pipe(21 Option.filter(String.isNonEmpty),22 Option.getOrElse(() => `__${item.key}_PLACEHOLDER__`)23 );2442/** The rules for every `@sensitive` item's `@proxy`, one per domain, in the schema's order. */25export const proxyMap = (26 schema: Pick<EnvSchemaView, "items">27): readonly ProxyRule[] =>28 schema.items.flatMap((item) => {
17 unmodified lines
modified: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.3import type { EnvKey } from "@repo/protocol/ids";4import { ValueTooShort } from "@repo/protocol/refusal";5import { Context, Effect, Redacted, Schema } from "effect";6
9 unmodified lines
16 * for: below it a value matches ordinary text everywhere.17 */18export const HARD_MIN_LENGTH = 3;1924/** Bytes as base64 text. */20const Base64 = Schema.String.check(Schema.isBase64());2127/**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 */22export const SealedValue = Schema.Struct({23 ciphertext: Base64,24 iv: Base64,25 keyVersion: Schema.Int,
1 unmodified line
27});2829export type SealedValue = typeof SealedValue.Type;3041/**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. */32export class SealedValueUnopenable extends Schema.TaggedError<SealedValueUnopenable>()(33 "SealedValueUnopenable",34 { step: Schema.Literals(["keyVersion", "unwrap", "decrypt"]) }35) {}3652/** A value a decider sets for one item, and whether they accept a short one. */37export interface ValueToSeal {38 readonly acknowledgeShort: boolean;39 readonly key: EnvKey;40 readonly value: Redacted.Redacted;
8 unmodified lines
49 */50export const charactersIn = (value: string) =>51 [...graphemes.segment(value)].length;5269/**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. */54export const admitLength = ({55 acknowledgeShort,56 key,57 value,
8 unmodified lines
66 ? Effect.fail(ValueTooShort.of(key, MIN_LENGTH))67 : Effect.void;68};6991/** Seals values, and opens one only for a landed run. */70export 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 lines
modified: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/`.3import type { EnvSchemaView } from "@repo/protocol/domain/env";4import { RepoPath } from "@repo/protocol/ids";56import type { ParsedEnvSchema } from "../../../src/env-schema.ts";
7 unmodified lines
14import prefix from "./prefix.env.schema?raw";15import proxy from "./proxy.env.schema?raw";16import silentHeader from "./silent-header.env.schema?raw";1728/** The env shape a fixture gives, as the wire carries it, but for where and whose. */18export type ExpectedView = Omit<19 typeof EnvSchemaView.Encoded,20 "at" | "file" | "project"21>;2234/** `forEnv(production)`, as the parser reads it. */23const forProduction = {24 fn: "forEnv",25 named: [],26 positional: ["production"],27 text: "forEnv(production)",28};2942/** `$APP_ENV`, which the parser reads as the call `ref(APP_ENV)`. */30const appEnv = {31 fn: "ref",32 named: [],33 positional: ["APP_ENV"],34 text: "ref(APP_ENV)",35};3650/** `@proxy(domain="…", path="…")`, as the parser reads it. */37const proxyTo = (domain: string, path: string) => ({38 name: "proxy",39 value: {40 named: [
3 unmodified lines
44 positional: [],45 },46});4762/** One `.env.schema`: where it sits, its text, its parsed structure, and its env shape. */48export interface EnvFixture {49 readonly title: string;50 readonly file: RepoPath;51 readonly text: string;
260 unmodified lines
312 "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 lines
740 },741 },742];743760/** A `.env.schema` the platform refuses to read, and why. */744export interface RefusedFixture {745 readonly title: string;746 readonly file: RepoPath;747 readonly text: string;748 readonly parsed: ParsedEnvSchema;749 readonly reason: string;750}751769/** `API_KEY=` under a header that imports `path`, as the parser reads it. */752const importing = (path: string): ParsedEnvSchema => ({753 header: [{ name: "import", value: { named: [], positional: [path] } }],754 imports: [],755 items: [{ decorators: [], key: "API_KEY" }],
22 unmodified lines
778 title: "an import from above the repo's root",779 },780];781800/** What the `/memory` fake holds: every fixture's parsed structure, by its file. */782export 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 */1declare module "*?raw" {2 const text: string;3 export default text;4}
13 unmodified lines
modified:packages/visibility/test/env-shape.test.ts-3 removed
16 unmodified lines
17const project = ProjectName.make("oscabriel/datekit");1819const at = LandedSha.make("a1".repeat(20));2021// 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.21const parsers = [22 ["the /memory fake", EnvSchemaParserMemory(parsedByFile)],23 ["the /env-spec adapter", EnvSchemaParserEnvSpec],24] as const;
86 unmodified lines
modified:packages/visibility/test/env-spec-adapter.test.ts+3 added-8 removed
19 unmodified lines
2021 return yield* parser.parse(file, text);22 }).pipe(Effect.provide(EnvSchemaParserEnvSpec));2324/** The modules a source file imports, in order: static, side-effect, `import()` and re-exports alike. */24const importsOf = (source: string | undefined) =>25 [26 ...(source ?? "").matchAll(27 /(?:\bfrom\s+|\bimport\s*\(\s*|^import\s+)["'](?<specifier>[^"']+)["']/gmu28 ),29 ].map((match) => match.groups?.specifier);3032/** The seam's own modules, as text. */31const seam = import.meta.glob(32 ["../src/env-schema.ts", "../src/env-schema/env-spec.ts"],33 { eager: true, import: "default", query: "?raw" }34);3538/** Where the parser's pinned 0.6.1 build lives, and its ES modules, as text. */36const dist = "../node_modules/@env-spec/parser/dist/";3738const parserModules = import.meta.glob(39 ["../node_modules/@env-spec/parser/dist/*.mjs"],40 { eager: true, exhaustive: true, import: "default", query: "?raw" }41);4246// The adapter over @env-spec/parser 0.6.1.43describe("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 lines
50 expect(yield* parse(file, text)).toStrictEqual(parsed);51 })52 );5358 // 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 lines
122 })123 );124});125131// ADR 0009: the platform parses, never resolves.126// The platform parses, never resolves.127describe("the /env-spec adapter never evaluates", () => {128 it.effect(129 "reads $(…) and exec(…) as text, and the shape carries no value",130 () =>
67 unmodified lines
modified:packages/visibility/test/guards.test.ts-1 removed
107 unmodified lines
108 privatePaths({ changes, layerPaths, pusherCanRead: false })109 ).toStrictEqual(Option.none());110 });111112 // 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"))];114115 expect(
139 unmodified lines
modified:packages/visibility/test/leak-scan.test.ts-4 removed
10 unmodified lines
11});1213const found = (key: string) => Option.some(EnvKey.make(key));1415/** A token-shaped value. */15const sentry = "sntrys_eyJpYXQiOjE3MjA";1618/** A value every serialized form changes: a quote, a slash, a plus, a space. */17const stripe = 'sk_live_51H"q/7+x Zr';1819const values = [20 watched("SENTRY_AUTH_TOKEN", sentry),
5 unmodified lines
26const base64 = Schema.encodeSync(Schema.StringFromBase64);2728const base64Url = Schema.encodeSync(Schema.StringFromBase64Url);2932/** `text` as a stream of byte chunks, cut at the given byte offsets. */30const chunked = (text: string, cuts: readonly number[]) => {31 const bytes = utf8(text);32 const bounds = [0, ...cuts, bytes.length];33
81 unmodified lines
115 });116117 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;120121 const draw = () => {122 state = (state * 48_271) % 2_147_483_647;
121 unmodified lines
modified:packages/visibility/test/posture.test.ts-4 removed
68 unmodified lines
69const decode = Schema.decodeUnknownSync(VisibilityPolicy);7071const policy = (layers: readonly unknown[]) => decode({ ...config, layers });7273/** A policy whose maintainers layer holds the held-back checks. */73const sealed = (layers: readonly unknown[]) =>74 decode({ ...config, checks: sealedChecks, layers });7576const mit = Option.some("MIT");
3 unmodified lines
8081const postureUnder = (licence: string) =>82 of(policy([]), Option.some(licence)).posture;8385// The posture table, one row at a time.84describe("a project's posture", () => {85 it("is Open with no visibility config", () => {86 expect(87 postureOf({ licence: mit, visibility: Option.none() })
7 unmodified lines
95 posture: "open",96 });97 });98101 // 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 lines
141 posture: "openCore",142 });143 });144148 // 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 lines
modified:packages/visibility/test/proxy.test.ts-6 removed
9 unmodified lines
10import { placeholderFor, proxyMap } from "../src/proxy.ts";1112const item = Schema.decodeUnknownSync(EnvItem);1314/** datekit's one `@sensitive` item, behind `@proxy(domain="sentry.io", path="/api/**")`. */14const sentryAuthToken = item({15 description:16 "Source-map upload token. Release step only; never enters a check.",17 key: "SENTRY_AUTH_TOKEN",
2 unmodified lines
20 sensitive: true,21 tags: ["release"],22});2325/**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 */24const datekit = {25 items: [26 item({27 key: "APP_ENV",
153 unmodified lines
modified:packages/visibility/test/smoke.test.ts-2 removed
5 unmodified lines
6import { EnvSchemaParser } from "../src/env-schema.ts";7import { LayerRepos } from "../src/layer-repos.ts";8import { SealedValue, WriteOnlyValues } from "../src/vault.ts";910// The skeleton's test: the ports the visibility package builds against.11// The modules that fill them have their own tests beside this one.10describe("the package", () => {11 it("is @repo/visibility", () => {12 expect(manifest.name).toBe("@repo/visibility");13 });
45 unmodified lines
modified:packages/visibility/test/vault.test.ts-6 removed
19 unmodified lines
20 WriteOnlyValues,21} from "../src/vault.ts";22import { WriteOnlyValuesWebCrypto } from "../src/vault/webcrypto.ts";2324// A fixed test master key and a second one, 32 bytes each as 64 hex25// characters (the form the platform decodes `MASTER_KEY` in).24const masterKey = WriteOnlyValuesWebCrypto(25 Redacted.make(26 "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF"27 )
6 unmodified lines
34);3536const key = EnvKey.make("SENTRY_AUTH_TOKEN");3740/** A token-shaped value of 22 characters. */38const token = "sntrys_eyJpYXQiOjE3MjA";3940const put = (value: string, acknowledgeShort = false) =>41 WriteOnlyValues.use((values) =>
4 unmodified lines
46 WriteOnlyValues.use((values) => values.open(sealed)).pipe(47 Effect.map((value) => Redacted.value(value))48 );4953/** The sealed value with one byte of `field` changed. */50const tampered = (51 sealed: SealedValue,52 field: "ciphertext" | "iv" | "wrappedKey"53): SealedValue => {
8 unmodified lines
62};6364const base64 = Schema.encodeSync(Schema.StringFromBase64);6570/** What an effect failed with: none when it succeeded. */66const refusalOf = <A, E, R>(effect: Effect.Effect<A, E, R>) =>67 Effect.result(effect).pipe(Effect.map(Result.getFailure));6874/** The defect an effect died with. */69const defectOf = <A, E>(exit: Exit.Exit<A, E>) =>70 Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;7172describe("write-only values over WebCrypto", () => {
238 unmodified lines