Skip to content
Myr

scenarios.ts

This file

Path

packages/testkit/src/scenarios.ts

392 lines · 10.5 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

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

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 1–2why, one step back
1// Each value is decoded with the domain's own schema as it is built, so a
2// scenario the domain would refuse throws 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 3–166why, one step back
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";7import { AskKind } from "@repo/protocol/domain/kind";8import { Policy } from "@repo/protocol/domain/policy";9import { Territory } from "@repo/protocol/domain/territory";10import {11 CommitSha,12 DecisionId,13 Handle,14 LandedSha,15 ProjectName,16 ProposalId,17 RepoPath,18 RequestId,19} from "@repo/protocol/ids";20import { Array as Arr, DateTime, Pipeable, Schema } from "effect";21import type { Types } from "effect";2223import { defaultNow } from "./clock.ts";2425export type AskKindEncoded = typeof AskKind.Encoded;2627export interface Scenario extends Pipeable.Pipeable {28 readonly project: ProjectName;29 readonly initializer: Handle;30 readonly policy: Policy;31 readonly landed: LandedSha;32 readonly people: ReadonlyMap<string, Handle>;33 readonly now: DateTime.Utc;34}3536type ScenarioFields = Omit<Scenario, "pipe">;3738// A class only for `pipe`: its fields are its own, so `Equal.equals` compares39// two scenarios by what they hold.40class Built extends Pipeable.Class implements Scenario {41 readonly project: ProjectName;42 readonly initializer: Handle;43 readonly policy: Policy;44 readonly landed: LandedSha;45 readonly people: ReadonlyMap<string, Handle>;46 readonly now: DateTime.Utc;4748 constructor(fields: ScenarioFields) {49 super();50 this.project = fields.project;51 this.initializer = fields.initializer;52 this.policy = fields.policy;53 this.landed = fields.landed;54 this.people = fields.people;55 this.now = fields.now;56 }57}5859const withPolicy = (scenario: Scenario, policy: Policy): Scenario =>60 new Built({ ...scenario, policy });6162const WORD = 2 ** 32;6364/**65 * `word` with its low byte exclusive-ored with `byte`, in arithmetic: lint66 * keeps bitwise operators out of the codebase, and FNV needs only this one.67 */68const xorLowByte = (word: number, byte: number) => {69 const low = word % 256;70 let mixed = 0;7172 for (let place = 1; place < 256; place *= 2) {73 const ours = Math.floor(low / place) % 2;74 const theirs = Math.floor(byte / place) % 2;7576 mixed += ours === theirs ? 0 : place;77 }7879 return word - low + mixed;80};8182const fnv1a = (text: string) => {83 let hash = 0x81_1c_9d_c5;8485 for (const byte of new TextEncoder().encode(text)) {86 // `Math.imul` multiplies modulo 2^32, signed; the remainder makes it unsigned.87 hash = (Math.imul(xorLowByte(hash, byte), 0x01_00_01_93) + WORD) % WORD;88 }8990 return hash.toString(16).padStart(8, "0");91};9293/**94 * A commit id made from a seed: FNV-1a over `0:<seed>` … `4:<seed>`, so the95 * same seed always gives the same 40 hex digits (FNV, not crypto).96 */97export const sha = (seed: string): CommitSha =>98 CommitSha.make(99 [0, 1, 2, 3, 4].map((round) => fnv1a(`${round}:${seed}`)).join("")100 );101102const counter = (prefix: string) => {103 let next = 0;104105 return () => {106 next += 1;107108 return `${prefix}-${String(next).padStart(6, "0")}`;109 };110};111112export const ids = () => {113 const request = counter("req");114 const proposal = counter("prop");115 const decision = counter("dec");116117 return {118 decision: () => DecisionId.make(decision()),119 proposal: () => ProposalId.make(proposal()),120 request: () => RequestId.make(request()),121 };122};123124const fix: AskKindEncoded = {125 checkKind: "redThenGreen",126 claimers: "vouched",127 finish: "optional",128 name: "fix",129 oneWay: false,130 race: 1,131 requires: ["want", "check", "territory"],132 strength: "assertion",133};134135const migrate: AskKindEncoded = {136 checkKind: "migrate",137 claimers: "vouched",138 finish: "never",139 name: "migrate",140 oneWay: false,141 race: 1,142 requires: ["want", "check", "territory"],143 strength: "assertion",144};145146const decodePolicy = Schema.decodeSync(Policy);147148const decodeAsk = Schema.decodeSync(Ask);149150const decodeKind = Schema.decodeSync(AskKind);151152const decodeTerritory = Schema.decodeSync(Territory);153154const encodeTerritory = Schema.encodeSync(Territory);155156const encodeCheck = Schema.encodeSync(CheckSpec);157158export const aProject = (159 options: {160 readonly name?: string;161 readonly now?: DateTime.Utc;162 readonly deciders?: readonly string[];163 readonly people?: readonly string[];164 } = {}165): Scenario => {166 const [first = "alice", ...more] = options.deciders ?? [];

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

line 167why, one step back
167 // A bare word is the first maintainer's (`alice/<word>`), who makes the

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 168–170why, one step back
168 // project in every scenario; a full name is kept as given.
169 const given = options.name ?? "datekit";170 const name = given.includes("/") ? given : `${first.toLowerCase()}/${given}`;

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 171–392why, one step back
171 const deciders = [first, ...more] as const;
172 const landed = LandedSha.make(sha(`${name}:landed`));173174 const policy = decodePolicy({175 agents: "trailer",176 asks: [],177 at: landed,178 budget: { decisionsPerDay: 5, expireDays: 14 },179 caps: { claimsPerPerson: 3, proposalsPerPerson: 2 },180 claims: { lapseAfterMs: 86_400_000, warnAfterMs: 7_200_000 },181 deciders: [{ handles: deciders, paths: "**" }],182 functions: { admit: false, opensAlone: false },183 judge: {184 paths: [`${Brand.configDir}/**`],185 pointers: ["package.json#/scripts"],186 },187 kinds: [fix, migrate],188 modules: [],189 ratchets: [],190 record: { countsAfterDays: 30, windowDays: 365 },191 run: {192 checks: { lint: "bun run lint", types: "bun run typecheck" },193 test: "bun test {path}",194 },195 source: "config",196 vouch: { file: `${Brand.configDir}/vouched.td`, mode: "forCode" },197 vouches: [],198 weakening: { markers: [".skip(", ".only(", ".todo("] },199 });200201 const names = [...deciders, ...(options.people ?? [])];202203 return new Built({204 initializer: Handle.make(first),205 landed,206 now: options.now ?? defaultNow,207 people: new Map(names.map((person) => [person, Handle.make(person)])),208 policy,209 project: ProjectName.make(name),210 });211};212213const territoryOf = (folder: string) =>214 decodeTerritory(215 folder === "."216 ? { module: ".", paths: ["**"] }217 : {218 module: folder.split("/").at(-1) ?? folder,219 paths: [`${folder}/**`],220 }221 );222223interface AskOptions {224 readonly id: string;225 readonly territory: string;226 readonly kind?: string;227 readonly check?: CheckSpec;228 readonly blockedBy?: readonly string[];229 readonly reserve?: "newcomers" | "people";230 readonly parent?: string;231 readonly want?: string;232}233234const openAsk = (235 scenario: Scenario,236 ask: AskOptions,237 territory: Territory,238 module: boolean239): Scenario => {240 const tests = ask.territory === "." ? "test" : `${ask.territory}/test`;241242 const encoded: Types.Mutable<typeof Ask.Encoded> = {243 askedBy: scenario.initializer,244 blockedBy: ask.blockedBy ?? [],245 brief: {246 want: ask.want ?? `${ask.id}: its check passes in ${ask.territory}`,247 },248 check: encodeCheck(249 ask.check ??250 CheckSpec.cases.RedThenGreen.make({251 path: RepoPath.make(`${tests}/${ask.id}.test.ts`),252 })253 ),254 file: `${Brand.configDir}/asks/${ask.id}.ask.ts`,255 id: ask.id,256 kind: ask.kind ?? "fix",257 openedAt: DateTime.formatIso(scenario.now),258 openedIn: scenario.landed,259 project: scenario.project,260 state: "open",261 territory: encodeTerritory(territory),262 };263264 if (ask.parent !== undefined) {265 encoded.parent = ask.parent;266 }267268 if (ask.reserve !== undefined) {269 encoded.reserve = ask.reserve;270 }271272 const { modules } = scenario.policy;273 const known = modules.some((each) => each.module === territory.module);274275 return withPolicy(scenario, {276 ...scenario.policy,277 asks: [...scenario.policy.asks, decodeAsk(encoded)],278 modules: module && !known ? [...modules, territory] : modules,279 });280};281282export const withAsk =283 (ask: AskOptions) =>284 (scenario: Scenario): Scenario =>285 openAsk(scenario, ask, territoryOf(ask.territory), ask.territory !== ".");286287export const withKind =288 (kind: AskKindEncoded) =>289 (scenario: Scenario): Scenario => {290 const added = decodeKind(kind);291 const { kinds } = scenario.policy;292293 return withPolicy(scenario, {294 ...scenario.policy,295 kinds: kinds.some(({ name }) => name === added.name)296 ? kinds.map((each) => (each.name === added.name ? added : each))297 : [...kinds, added],298 });299 };300301export const withVouches =302 (handles: readonly string[], denounced: readonly string[] = []) =>303 (scenario: Scenario): Scenario =>304 withPolicy(scenario, {305 ...scenario.policy,306 vouches: [307 ...scenario.policy.vouches,308 ...handles.map((handle) => ({309 denounced: false,310 handle: Handle.make(handle),311 })),312 ...denounced.map((handle) => ({313 denounced: true,314 handle: Handle.make(handle),315 })),316 ],317 });318319const words = (symbol: string) =>320 symbol321 .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower>-$<upper>")322 .toLowerCase()323 .replaceAll(/[^a-z0-9]+/gu, "-")324 .replaceAll(/^-|-$/gu, "");325326const packages = Arr.makeBy(6, (n) => `packages/p${n + 1}`);327328const allSix = decodeTerritory({329 module: ".",330 paths: Arr.map(packages, (folder) => `${folder}/**`),331});332333export const sixChildren = (334 options: { readonly symbol?: string; readonly to?: string } = {}335): Scenario => {336 const symbol = options.symbol ?? "legacyFetch";337 const to = options.to ?? "http.get";338 const parent = `drop-${words(symbol)}`;339 const count = `node scripts/count-callers.mjs ${symbol} --json`;340341 const check = CheckSpec.cases.Migrate.make({342 count: Command.make(count),343 from: SymbolName.make(symbol),344 to: SymbolName.make(to),345 });346347 const children = packages.map((folder) => ({348 check,349 id: `${parent}-${folder.split("/").at(-1) ?? folder}`,350 kind: "migrate",351 parent,352 territory: folder,353 want: `${folder}: move every use of ${symbol} to ${to}`,354 }));355356 const opened = openAsk(357 aProject({ name: "burrow" }),358 {359 check,360 id: parent,361 kind: "migrate",362 territory: ".",363 want: `Move every use of ${symbol} to ${to}, then delete ${symbol}`,364 },365 allSix,366 false367 );368369 let split = opened;370371 for (const child of children) {372 split = withAsk(child)(split);373 }374375 return openAsk(376 split,377 {378 blockedBy: children.map(({ id }) => id),379 check: CheckSpec.cases.SymbolAbsent.make({380 count: Command.make(count),381 symbol: SymbolName.make(symbol),382 }),383 id: `${parent}-delete`,384 kind: "migrate",385 parent,386 territory: ".",387 want: `Delete ${symbol}: nothing uses it any more`,388 },389 allSix,390 false391 );392};