finish.ts
This file
Path
packages/rules/src/finish.ts
238 lines · 7.0 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake 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 back1import type { Glob } from "@repo/protocol/domain/common";2import { FromCI, Policy } from "@repo/protocol/domain/policy";3import type { PolicyInput } from "@repo/protocol/domain/policy";4import { RunBlock } from "@repo/protocol/domain/run";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 back5import { 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–19why, one step back6import type { LandedSha, RepoPath } from "@repo/protocol/ids";7import { packageDir } from "@repo/sdk";8import { Array as Arr, Context, DateTime, Effect, Schema } from "effect";910import { failedAt } from "./config-folder.ts";11import { RulesFailed } from "./rules-evaluator.ts";12import type { EvaluationFacts } from "./rules-evaluator.ts";13import { parseVouchFile } from "./vouch.ts";1415export interface FactFile {16 readonly content: string;17 readonly path: string;18}19Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 20why, one step back20/** What `rules` needs from `checks` without importing 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 21–66why, one step back21export class Finishers extends Context.Service<22 Finishers,23 {24 readonly findRunBlock: (files: readonly FactFile[]) => {25 readonly run: Partial<typeof RunBlock.Encoded>;26 readonly sources: readonly string[];27 };28 readonly judgeClosure: (29 run: RunBlock,30 files: readonly FactFile[]31 ) => {32 readonly paths: readonly Glob[];33 readonly pointers: readonly string[];34 };35 }36>()("rules/Finishers") {}3738/**39 * Whether a vouch's platform prefix names the platform's own handles. People40 * sign in with GitHub, so `github:alice` is `alice`; a handle on another41 * platform names someone else, so it vouches for no one here.42 */43const isSignInPlatform = (platform: string) => platform === "github";4445const runBlockOf = (46 run: PolicyInput["run"],47 facts: EvaluationFacts,48 finishers: Finishers["Service"]49): Effect.Effect<RunBlock, RulesFailed> => {50 if (!Schema.is(FromCI)(run)) {51 return Effect.succeed(run);52 }5354 const found = finishers.findRunBlock(facts.ci);5556 const where =57 found.sources.length === 058 ? "the project's files"59 : found.sources.join(", ");6061 return Schema.decodeUnknownEffect(RunBlock)({62 checks: {},63 ...found.run,64 }).pipe(Effect.mapError(failedAt(`the run block found in ${where}`)));65};66Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 67why, one step back67/** A line that names no handle fails the policy, so a typo is reported rather than dropped. */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 68–126why, one step back68const vouchesOf = (text: string, file: RepoPath) => {69 const { invalid, vouches } = parseVouchFile(text);7071 if (invalid.length > 0) {72 const lines = invalid73 .map(({ line, text: bad }) => `line ${line} ("${bad}")`)74 .join(", ");7576 return Effect.fail(77 new RulesFailed({78 detail: `${file}: no handle on ${lines}`,79 reason: "decode",80 })81 );82 }8384 return Effect.succeed(85 vouches.flatMap(({ denounced, handle, note, platform }) => {86 if (platform !== undefined && !isSignInPlatform(platform)) {87 return [];88 }8990 return note === undefined91 ? [{ denounced, handle }]92 : [{ denounced, handle, note }];93 })94 );95};9697const folderOf = (dir: string) =>98 dir99 .replace(/^(?:\.\/)+/u, "")100 .replace(/\/+$/u, "")101 .replace(/^\.$/u, "");102103const territoriesOf = (104 workspaces: EvaluationFacts["workspaces"]105): (typeof Policy.Encoded)["modules"] =>106 workspaces.length === 0107 ? [{ module: ".", paths: ["**"] }]108 : workspaces.map(({ dir, exports, name }) => {109 const folder = folderOf(dir);110111 const paths: readonly [string] = [112 folder === "" ? "**" : `${folder}/**`,113 ];114115 return exports.length === 0116 ? { module: name, paths }117 : { module: name, paths, publicFiles: exports };118 });119120const placed = (glob: string, folder: string) => {121 const written = glob.replaceAll(packageDir, folder).replace(/^\/+/u, "");122123 return written === "" ? "**" : written;124};125126/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 127–129why, one step back127 * 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).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 130–173why, one step back130 */131const placedIn = (132 workspaces: EvaluationFacts["workspaces"],133 territory: PolicyInput["asks"][number]["territory"]134) => {135 const workspace = workspaces.find(({ name }) => name === territory.module);136137 if (138 workspace === undefined ||139 !territory.paths.some((glob) => glob.includes(packageDir))140 ) {141 return territory;142 }143144 const folder = folderOf(workspace.dir);145 const paths = Arr.map(territory.paths, (glob) => placed(glob, folder));146147 return territory.publicFiles !== undefined || workspace.exports.length === 0148 ? { ...territory, paths }149 : { ...territory, paths, publicFiles: workspace.exports };150};151152const distinctAsks = (asks: PolicyInput["asks"]) => {153 const seen = new Map<string, string>();154155 for (const { file, id } of asks) {156 const other = seen.get(id);157158 if (other !== undefined) {159 return Effect.fail(160 new RulesFailed({161 detail: `${file}: the ask ${id} is also declared in ${other}`,162 reason: "decode",163 })164 );165 }166167 seen.set(id, file);168 }169170 return Effect.void;171};172173/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 174–176why, one step back174 * 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.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 177–223why, one step back177 */178export const finishPolicy = (input: {179 readonly at: LandedSha;180 readonly facts: EvaluationFacts;181 readonly finishers: Finishers["Service"];182 readonly policy: PolicyInput;183}): Effect.Effect<Policy, RulesFailed> =>184 Effect.gen(function* () {185 const { at, facts, finishers, policy } = input;186 const run = yield* runBlockOf(policy.run, facts, finishers);187 const vouches = yield* vouchesOf(facts.vouchFile ?? "", policy.vouch.file);188 const judge = finishers.judgeClosure(run, facts.ci);189 const openedAt = DateTime.formatIso(facts.now);190191 yield* distinctAsks(policy.asks);192193 const candidate = {194 agents: policy.agents,195 asks: policy.asks.map((ask) => ({196 ...ask,197 openedAt,198 openedIn: at,199 project: facts.project,200 state: "open" as const,201 territory: placedIn(facts.workspaces, ask.territory),202 })),203 at,204 budget: policy.budget,205 caps: policy.caps,206 claims: policy.claims,207 deciders: policy.deciders.map(({ handles, paths }) => ({208 handles: handles === "owners" ? [facts.initializer] : handles,209 paths,210 })),211 functions: policy.functions,212 judge,213 kinds: policy.kinds,214 modules: territoriesOf(facts.workspaces),215 ratchets: policy.ratchets,216 record: policy.record,217 run,218 source: policy.source,219 vouch: policy.vouch,220 vouches,221 weakening: policy.weakening,222 } satisfies typeof Policy.Encoded;223Merge 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 224–235why, one step back224 const stated =225 policy.visibility === undefined226 ? candidate227 : {228 ...candidate,229 // A decoded policy always encodes.230 visibility: yield* Effect.orDie(231 Schema.encodeEffect(VisibilityPolicy)(policy.visibility)232 ),233 };234235 return yield* Schema.decodeEffect(Policy)(stated).pipe(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 236–238why, one step back236 Effect.mapError(failedAt(`the policy at ${at}`))237 );238 });