Skip to content
Myr

evaluate.test.ts

This file

Path

packages/rules/test/evaluate.test.ts

674 lines · 19.6 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–4why, one step back
1import { NodeServices } from "@effect/platform-node";
2import { assert, describe, expect, it } from "@effect/vitest";3import { CheckSpec } from "@repo/protocol/domain/check";4import { Policy } from "@repo/protocol/domain/policy";

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

line 5why, one step back
5import type { VisibilityPolicy } from "@repo/protocol/domain/visibility";

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 6–42why, one step back
6import { RepoPath } from "@repo/protocol/ids";
7import { ClaimantFacts, ProposalFacts } from "@repo/sdk";8import { Duration, Effect, Layer, Result, Schema } from "effect";910import { Finishers } from "../src/finish.ts";11import { RulesEvaluator } from "../src/rules-evaluator.ts";12import type { ConfigBundle } from "../src/rules-evaluator.ts";13import { RulesEvaluatorJson } from "../src/rules-evaluator/json.ts";14import {15 at,16 baseProject,17 bundleOf,18 bunEvaluator,19 configFolder,20 defaultVouchFile,21 facts,22 finishers,23 folder,24 now,25} from "./world.ts";2627const decodeProposal = Schema.decodeUnknownSync(ProposalFacts);2829const decodeClaimant = Schema.decodeUnknownSync(ClaimantFacts);3031const fixBugProposal = {32 kind: "fixBug",33 proposer: "carol",34 territory: "@datekit/parse",35};3637const redThenGreen = (path: string) =>38 CheckSpec.cases.RedThenGreen.make({ path: RepoPath.make(path) });3940const opened = {41 openedAt: now,42 openedIn: at,

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 43why, one step back
43 project: "oscabriel/datekit",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 44–230why, one step back
44 state: "open",
45};4647const fromFacts = {48 at,49 modules: [50 {51 module: "@datekit/parse",52 paths: ["packages/parse/**"],53 publicFiles: ["packages/parse/src/index.ts"],54 },55 { module: "@datekit/format", paths: ["packages/format/**"] },56 ],57 vouches: [58 { denounced: false, handle: "priya" },59 { denounced: true, handle: "mallory", note: "Spam" },60 ],61};6263const judgeFor = (test: string) => ({64 paths: [`${configFolder}/**`, ".github/workflows/ci.yml"],65 pointers: ["package.json#/scripts", `test:${test}`],66});6768const foundRun = { checks: { unit: "bun test" }, test: "bun test {path}" };6970const fixBug = {71 checkKind: "redThenGreen",72 claimers: { record: { area: "packages/parse", atLeast: 1 } },73 finish: "optional",74 name: "fixBug",75 oneWay: false,76 race: 1,77 requires: ["want", "check"],78 strength: "assertion",79};8081const exampleEncoded = {82 ...fromFacts,83 agents: "trailer",84 asks: [85 {86 ...opened,87 askedBy: "priya",88 blockedBy: [],89 brief: { want: "Parse ISO week dates such as 2026-W40-6" },90 check: redThenGreen("packages/parse/test/iso-week.repro.test.ts"),91 file: `${configFolder}/asks/iso-week.ask.ts`,92 id: "iso-week",93 kind: "fixBug",94 mentor: "priya",95 reserve: "newcomers",96 territory: { module: "@datekit/parse", paths: ["packages/parse/**"] },97 },98 {99 ...opened,100 askedBy: "olivia",101 blockedBy: [],102 brief: {103 context: ["February 29 exists only in leap years"],104 want: "Reject February 29 in a year that is not a leap year",105 },106 check: redThenGreen("packages/parse/test/leap-year.repro.test.ts"),107 file: `${configFolder}/asks/leap-year.ask.ts`,108 id: "leap-year",109 kind: "fixBug",110 territory: { module: "@datekit/parse", paths: ["packages/parse/**"] },111 },112 ],113 budget: { decisionsPerDay: 5, expireDays: 14 },114 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },115 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },116 deciders: [117 { handles: ["priya"], paths: "packages/parse/src/public/**" },118 { handles: ["olivia"], paths: "**" },119 ],120 functions: { admit: false, opensAlone: true },121 judge: judgeFor("bun test {path}"),122 kinds: [fixBug],123 ratchets: [],124 record: { countsAfterDays: 30, windowDays: 365 },125 run: foundRun,126 source: "config",127 vouch: { file: defaultVouchFile, mode: "forCode" },128 weakening: { markers: [".skip(", ".only("] },129};130131const jsonEncoded = {132 ...fromFacts,133 agents: "none",134 asks: [135 {136 ...opened,137 askedBy: "olivia",138 blockedBy: [],139 brief: { want: "Format durations as ISO 8601" },140 check: redThenGreen("test/duration.repro.test.ts"),141 file: "policy.json",142 id: "iso-duration",143 kind: "fix",144 territory: { module: ".", paths: ["**"] },145 },146 ],147 budget: { decisionsPerDay: 3, expireDays: 7 },148 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },149 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },150 deciders: [{ handles: ["olivia"], paths: "**" }],151 functions: { admit: false, opensAlone: false },152 judge: judgeFor("npx vitest run {path}"),153 kinds: [154 {155 checkKind: "redThenGreen",156 claimers: "anyone",157 finish: "never",158 name: "fix",159 oneWay: false,160 race: 1,161 requires: ["want", "check"],162 strength: "assertion",163 },164 ],165 ratchets: [],166 record: { countsAfterDays: 30, windowDays: 365 },167 run: {168 checks: { lint: "npm run lint" },169 setup: "npm ci --ignore-scripts",170 test: "npx vitest run {path}",171 },172 source: "config",173 vouch: { file: defaultVouchFile, mode: "forCode" },174 weakening: { markers: [".skip("] },175};176177const defaultsEncoded = {178 ...fromFacts,179 agents: "trailer",180 asks: [],181 budget: { decisionsPerDay: 5, expireDays: 14 },182 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },183 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },184 deciders: [{ handles: ["olivia"], paths: "**" }],185 functions: { admit: false, opensAlone: false },186 judge: judgeFor("bun test {path}"),187 kinds: [188 {189 checkKind: "redThenGreen",190 claimers: "vouched",191 finish: "optional",192 name: "fix",193 oneWay: false,194 race: 1,195 requires: ["want", "check", "territory"],196 strength: "assertion",197 },198 ],199 ratchets: [],200 record: { countsAfterDays: 30, windowDays: 365 },201 run: foundRun,202 source: "defaults",203 vouch: { file: defaultVouchFile, mode: "forCode" },204 // The gate scans its own default markers plus these, a project's own.205 weakening: { markers: [] },206};207208const 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 });215216const failed = (modules: ConfigBundle) =>217 Effect.gen(function* () {218 const evaluator = yield* RulesEvaluator;219220 const result = yield* Effect.result(221 evaluator.evaluate({ at, facts, modules })222 );223224 if (Result.isSuccess(result)) {225 return assert.fail("the config evaluated to a policy");226 }227228 return result.failure;229 });230

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

lines 231–260why, one step back
231const visibilityEncoded = {
232 checks: {233 admit: { greenOnMainRuns: 3, redOnKnownBadAtLeast: 1 },234 areas: { parse: "packages/parse/**" },235 attempts: { perClaim: 3, perPersonPerAreaPerWeek: 10 },236 canary: false,237 commit: "salted-sha256-merkle",238 layer: "maintainers",239 pin: "claim",240 result: "area-bit",241 },242 env: { setters: "deciders" },243 flows: { noWriteDown: true, release: "deciders" },244 layers: [245 {246 audience: "maintainers",247 disclose: "sealed",248 holds: ["checks"],249 name: "maintainers",250 readers: "deciders",251 reason: "Held-back checks for the parser",252 writers: "deciders",253 },254 ],255 notice: { narrowingDays: 7 },256} satisfies typeof VisibilityPolicy.Encoded;257258const exporting = (data: Schema.Json) =>259 `export default ${JSON.stringify(data)};\n`;260

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 261–313why, one step back
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"),265 kind: "fix",266 territory: { module: ".", paths: ["**"] },267})};\n`;268269describe("the /bun adapter", () => {270 it.live("evaluates the example's config folder to its policy", () =>271 Effect.gen(function* () {272 expect(yield* evaluated(yield* folder("cm"))).toStrictEqual(273 exampleEncoded274 );275 }).pipe(Effect.provide(bunEvaluator()))276 );277278 it.live("reads a folder that holds only policy.json", () =>279 Effect.gen(function* () {280 expect(yield* evaluated(yield* folder("json-only"))).toStrictEqual(281 jsonEncoded282 );283 }).pipe(Effect.provide(bunEvaluator()))284 );285286 it.live(287 "adds ask files to the policy.json that stands in for project.ts",288 () =>289 Effect.gen(function* () {290 const json = yield* folder("json-only");291 const example = yield* folder("cm");292293 const askFiles = Object.entries(example.modules).filter(([path]) =>294 path.startsWith(`${configFolder}/asks/`)295 );296297 const policy = yield* evaluated({298 ...json,299 modules: { ...json.modules, ...Object.fromEntries(askFiles) },300 });301302 expect(policy.asks.map(({ id }) => id)).toStrictEqual([303 "iso-duration",304 "iso-week",305 "leap-year",306 ]);307 expect(policy.run).toStrictEqual(jsonEncoded.run);308 }).pipe(Effect.provide(bunEvaluator()))309 );310311 it.live("gives the defaults to a project with no config folder", () =>312 Effect.gen(function* () {313 expect(yield* evaluated(bundleOf({}))).toStrictEqual(defaultsEncoded);

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

lines 314–365why, one step back
314 }).pipe(Effect.provide(bunEvaluator()))
315 );316317 it.live(318 "reads visibility.ts into the policy's visibility, beside the project module or without one",319 () =>320 Effect.gen(function* () {321 const project = yield* baseProject;322323 const beside = yield* evaluated(324 bundleOf({325 "project.ts": project,326 "visibility.ts": exporting(visibilityEncoded),327 })328 );329330 const alone = yield* evaluated(331 bundleOf({ "visibility.ts": exporting(visibilityEncoded) })332 );333334 const without = yield* evaluated(bundleOf({ "project.ts": project }));335336 expect([337 beside.visibility,338 alone.visibility,339 without.visibility,340 ]).toStrictEqual([visibilityEncoded, visibilityEncoded, undefined]);341 expect(alone.source).toBe("config");342 }).pipe(Effect.provide(bunEvaluator()))343 );344345 it.live("names a visibility.ts that states no visibility", () =>346 Effect.gen(function* () {347 const project = yield* baseProject;348349 const failures = yield* Effect.forEach(350 ["export const nothing = 1;\n", exporting({ layers: "maintainers" })],351 (visibility) =>352 failed(353 bundleOf({ "project.ts": project, "visibility.ts": visibility })354 )355 );356357 expect(358 failures.map(({ detail, reason }) => ({359 names: detail.includes(`${configFolder}/visibility.ts`),360 reason,361 }))362 ).toStrictEqual([363 { names: true, reason: "decode" },364 { names: true, reason: "decode" },365 ]);

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 366–674why, one step back
366 }).pipe(Effect.provide(bunEvaluator()))
367 );368369 it.live("fails to load a config with a syntax error", () =>370 Effect.gen(function* () {371 const failure = yield* failed(372 bundleOf({ "project.ts": "export default {\n" })373 );374375 expect(failure.reason).toBe("load");376 expect(failure.detail).toContain(`${configFolder}/project.ts`);377 }).pipe(Effect.provide(bunEvaluator()))378 );379380 it.live("names the ask file whose ask has no want", () =>381 Effect.gen(function* () {382 const failure = yield* failed(383 bundleOf({384 "asks/formats.ask.ts": noWant,385 "project.ts": yield* baseProject,386 })387 );388389 expect(failure.reason).toBe("decode");390 expect(failure.detail).toContain(`${configFolder}/asks/formats.ask.ts`);391 expect(failure.detail).toContain("want");392 }).pipe(Effect.provide(bunEvaluator()))393 );394395 it.live("stops a config that loops forever at its time limit", () =>396 Effect.gen(function* () {397 const [took, failure] = yield* Effect.timed(398 failed(bundleOf({ "project.ts": "for (;;) {}\nexport default {};\n" }))399 );400401 expect(failure.reason).toBe("timeout");402 expect(Duration.toMillis(took)).toBeLessThan(5000);403 }).pipe(Effect.provide(bunEvaluator({ timeout: "1 second" })))404 );405406 it.live("reports a config whose code throws", () =>407 Effect.gen(function* () {408 const failure = yield* failed(409 bundleOf({ "project.ts": 'throw new Error("no policy today");\n' })410 );411412 expect(failure.reason).toBe("threw");413 expect(failure.detail).toContain("no policy today");414 }).pipe(Effect.provide(bunEvaluator()))415 );416417 it.live("refuses a run block the finder finds without a test command", () =>418 Effect.gen(function* () {419 const failure = yield* failed(yield* folder("cm"));420421 expect(failure.reason).toBe("decode");422 expect(failure.detail).toContain("run block");423 expect(failure.detail).toContain(".github/workflows/ci.yml");424 }).pipe(425 Effect.provide(426 bunEvaluator(427 {},428 Finishers.of({429 ...finishers,430 findRunBlock: (files) => ({431 run: { checks: {} },432 sources: files.map(({ path }) => path),433 }),434 })435 )436 )437 )438 );439440 it.live("points both names of the sdk at the one sdk module", () =>441 Effect.gen(function* () {442 const base = yield* baseProject;443444 const project = [445 'import { marker } from "@repo/sdk";',446 'import { marker as same } from "@some-scope/cli/rules";',447 base.replace("export default ", "const base = "),448 "export default { ...base, weakening: { markers: [marker, same] } };",449 ].join("\n");450451 const policy = yield* evaluated(bundleOf({ "project.ts": project }));452453 expect(policy.weakening).toStrictEqual({454 markers: ["the sdk", "the sdk"],455 });456 }).pipe(457 Effect.provide(458 bunEvaluator({ sdk: `${import.meta.dirname}/fixtures/sdk-stub.ts` })459 )460 )461 );462463 it.live("runs config code with no env beyond PATH, and no fetch", () =>464 Effect.gen(function* () {465 const base = yield* baseProject;466467 const project = [468 base.replace("export default ", "const base = "),469 "const seen = [...Object.keys(process.env).toSorted(), typeof fetch];",470 "export default { ...base, weakening: { markers: seen } };",471 ].join("\n");472473 const policy = yield* evaluated(bundleOf({ "project.ts": project }));474475 expect(policy.weakening).toStrictEqual({476 markers: ["PATH", "undefined"],477 });478 }).pipe(Effect.provide(bunEvaluator()))479 );480481 it.live("keeps only the end of a config's endless output", () =>482 Effect.gen(function* () {483 const failure = yield* failed(484 bundleOf({485 "project.ts": [486 'const flood = "x".repeat(8 * 1024 * 1024) + "the end";',487 "await new Promise((done) => process.stderr.write(flood, done));",488 "process.exit(3);",489 ].join("\n"),490 })491 );492493 expect(failure.detail.length).toBeLessThanOrEqual(64 * 1024);494 expect(failure.detail).toMatch(/x+the end$/u);495 }).pipe(Effect.provide(bunEvaluator()))496 );497498 // A project written with the real sdk: the rules ride under its symbol,499 // and the facts are the sdk's own fact schemas.500 const sdkProject = bundleOf({501 "project.ts": [502 'import { check, kind, kinds, project } from "@repo/sdk";',503 "",504 "const trusted = kind({",505 " args: {},",506 ' check: () => check.redThenGreen("test/trusted.test.ts"),',507 ' checkKind: "redThenGreen",',508 ' name: "trusted",',509 " opensAlone: (proposal) => proposal.record >= 3,",510 "});",511 "",512 "export default project({",513 " admit: (claimant) => claimant.vouched || claimant.record > 0,",514 " kinds: [kinds.fix, trusted],",515 "});",516 ].join("\n"),517 });518519 it.live("calls the rules a project written with the sdk carries", () =>520 Effect.gen(function* () {521 const evaluator = yield* RulesEvaluator;522 const modules = sdkProject;523524 const proposal = (kind: string, record: number) =>525 evaluator.call({526 at,527 facts: decodeProposal({528 kind,529 proposer: "carol",530 record,531 territory: ".",532 }),533 modules,534 rule: "opensAlone",535 });536537 const claimant = (vouched: boolean, record: number) =>538 evaluator.call({539 at,540 facts: decodeClaimant({541 handle: "bram",542 kind: "fix",543 record,544 territory: ".",545 vouched,546 }),547 modules,548 rule: "admit",549 });550551 expect([552 yield* proposal("trusted", 3),553 yield* proposal("trusted", 2),554 yield* proposal("fix", 9),555 yield* claimant(true, 0),556 yield* claimant(false, 1),557 yield* claimant(false, 0),558 ]).toStrictEqual([true, false, false, true, true, false]);559 }).pipe(Effect.provide(bunEvaluator()))560 );561562 it.live(563 "evaluates a project file that states nothing as no folder at all",564 () =>565 Effect.gen(function* () {566 const stated = yield* evaluated(567 bundleOf({568 "project.ts": [569 'import { project } from "@repo/sdk";',570 "",571 "export default project({});",572 ].join("\n"),573 })574 );575576 expect(stated).toStrictEqual({ ...defaultsEncoded, source: "config" });577 }).pipe(Effect.provide(bunEvaluator()))578 );579580 it.live("calls a function-valued rule with the facts it is given", () =>581 Effect.gen(function* () {582 const evaluator = yield* RulesEvaluator;583 const modules = yield* folder("cm");584585 const opensAlone = (record: number) =>586 evaluator.call({587 at,588 facts: decodeProposal({ ...fixBugProposal, record }),589 modules,590 rule: "opensAlone",591 });592593 const admit = evaluator.call({594 at,595 facts: decodeClaimant({596 handle: "bram",597 kind: "fixBug",598 record: 3,599 territory: "@datekit/parse",600 vouched: true,601 }),602 modules,603 rule: "admit",604 });605606 expect([607 yield* opensAlone(3),608 yield* opensAlone(1),609 yield* admit,610 ]).toStrictEqual([true, false, false]);611 }).pipe(Effect.provide(bunEvaluator()))612 );613});614615describe("the /json adapter", () => {616 const jsonEvaluator = RulesEvaluatorJson.pipe(617 Layer.provide(Layer.succeed(Finishers, finishers)),618 Layer.provideMerge(NodeServices.layer)619 );620621 it.live("reads the committed policy.json", () =>622 Effect.gen(function* () {623 expect(yield* evaluated(yield* folder("json-only"))).toStrictEqual(624 jsonEncoded625 );626 }).pipe(Effect.provide(jsonEvaluator))627 );628629 it.live(630 "gives the defaults, from the folder, when there is no policy.json",631 () =>632 Effect.gen(function* () {633 expect(yield* evaluated(yield* folder("cm"))).toStrictEqual({634 ...defaultsEncoded,635 source: "config",636 });637 }).pipe(Effect.provide(jsonEvaluator))638 );639640 it.live("gives the defaults to a project with no config folder", () =>641 Effect.gen(function* () {642 expect(yield* evaluated(bundleOf({}))).toStrictEqual(defaultsEncoded);643 }).pipe(Effect.provide(jsonEvaluator))644 );645646 it.live("agrees with /bun on a folder that holds no policy", () =>647 Effect.gen(function* () {648 const modules = bundleOf({ "vouched.td": "priya\n" });649 const fromJson = yield* evaluated(modules);650651 const fromBun = yield* evaluated(modules).pipe(652 Effect.provide(bunEvaluator())653 );654655 expect(fromJson).toStrictEqual({ ...defaultsEncoded, source: "config" });656 expect(fromBun).toStrictEqual(fromJson);657 }).pipe(Effect.provide(jsonEvaluator))658 );659660 it.live("has no function-valued rules to call", () =>661 Effect.gen(function* () {662 const evaluator = yield* RulesEvaluator;663664 const called = yield* evaluator.call({665 at,666 facts: decodeProposal({ ...fixBugProposal, record: 3 }),667 modules: yield* folder("cm"),668 rule: "opensAlone",669 });670671 expect(called).toBeFalsy();672 }).pipe(Effect.provide(jsonEvaluator))673 );674});