migrate.test.ts
This file
Path
packages/project/test/migrate.test.ts
1,585 lines · 43.7 KiB · TypeScript
Last changed by
Merge build/comments-project into mainoscabrielbefore adoption49efd2a
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–24why, one step back1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it, layer } from "@effect/vitest";3import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";4import type { ObjectId } from "@repo/artifacts/repo-host";5import { Brand } from "@repo/brand";6import { CheckAt, CheckRunner } from "@repo/checks/check-runner";7import type { CheckJob, CheckLane, CheckRun } from "@repo/checks/check-runner";8import { measure } from "@repo/checks/kinds/ratchet";9import { authorLine, parseTrailers } from "@repo/git/trailers";10import type { LaneResult } from "@repo/protocol/domain/answer";11import type { Ask } from "@repo/protocol/domain/ask";12import { CheckSpec } from "@repo/protocol/domain/check";13import { Command, Glob, SymbolName } from "@repo/protocol/domain/common";14import type { ProjectEvent } from "@repo/protocol/domain/event";15import { Outcome } from "@repo/protocol/domain/outcome";16import type { Territory } from "@repo/protocol/domain/territory";17import {18 AskId,19 Handle,20 KindName,21 LandedSha,22 LaneName,23 RepoName,24 RepoPath,Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 25why, one step back25 keyOf,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 26–122why, one step back26 RequestId,27} from "@repo/protocol/ids";28import type { CommitSha } from "@repo/protocol/ids";29import { Anonymous, Person } from "@repo/protocol/principal";30import {31 AskBlocked,32 NotRedFirst,33 TouchedJudge,34 Weakened,35} from "@repo/protocol/refusal";36import {37 EvaluationFacts,38 RulesEvaluator,39 sdkVersion,40} from "@repo/rules/rules-evaluator";41import { RulesEvaluatorBun } from "@repo/rules/rules-evaluator/bun";42import { advanceTo } from "@repo/testkit/clock";43import type { Files } from "@repo/testkit/git-client";44import { sixChildren, withAsk, withVouches } from "@repo/testkit/scenarios";45import {46 Array,47 Context,48 Effect,49 Exit,50 Layer,51 Option,52 Ref,53 Result,54 Schema,55 Struct,56} from "effect";5758import { AnswerRuns } from "../src/answer-runs.ts";59import type { AnswerQueue, AnswerRun } from "../src/answer-runs.ts";60import { drive } from "../src/answer-runs/steps.ts";61import { Lander } from "../src/lander.ts";62import { LandingCommand } from "../src/landing.ts";63import type { Change } from "../src/landing.ts";64import {65 callersIn,66 childId,67 deleteChildId,68 familyClosed,69 remainingBlockers,70 splitFamily,71} from "../src/migrate.ts";72import type { MigrateFamily, CallerCount } from "../src/migrate.ts";73import { ProjectStore } from "../src/project-store.ts";74import type { ProjectApi } from "../src/project.ts";75import { FinishersFromChecks, projectService } from "../src/project.ts";76import { Pusher, worldOf } from "./world.ts";7778const symbol = "legacyFetch";7980const countOf = (name: string) =>81 Command.make(`node scripts/count-callers.mjs ${name} --json`);8283const packages = ["p1", "p2", "p3", "p4", "p5", "p6"] as const;8485type Package = (typeof packages)[number];8687const callers = { p1: 5, p2: 7, p3: 6, p4: 8, p5: 4, p6: 7 } as const;8889const total = 37;9091const answerers = ["bob", "carol", "dave", "eve", "frank", "grace"] as const;9293const others = ["heidi", "ivan"] as const;9495const family = sixChildren({ symbol, to: "http.get" });9697const scenario = family.pipe(98 withVouches([...answerers, ...others]),99 withAsk({ id: "tidy-p6", territory: "packages/p6" }),100 withAsk({101 check: CheckSpec.cases.Migrate.make({102 count: countOf(symbol),103 from: SymbolName.make(symbol),104 to: SymbolName.make("http.get"),105 }),106 id: "move-p2-fetch",107 kind: "migrate",108 territory: "packages/p2",109 }),110 withAsk({111 check: CheckSpec.cases.Migrate.make({112 count: countOf("oldThing"),113 from: SymbolName.make("oldThing"),114 }),115 id: "drop-old-thing",116 kind: "migrate",117 territory: ".",118 })119);120121const { project } = scenario;122Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 123why, one step back123const repo = RepoName.make(keyOf(project));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 124–159why, one step back124125const mainRef = RefName.make("refs/heads/main");126127const parentId = AskId.make("drop-legacy-fetch");128129const childIdOf = (name: Package) => AskId.make(`${parentId}-${name}`);130131const childIds = Array.map(packages, childIdOf);132133const deleteId = AskId.make(`${parentId}-delete`);134135const tidyId = AskId.make("tidy-p6");136137const ratchetName = "callers-legacyfetch";138139const person = (handle: string) => Person.make({ handle: Handle.make(handle) });140141const alice = person("alice");142143const anyone = Anonymous.make({});144145const askOf = (id: string) =>146 Option.getOrThrow(147 Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)148 );149150const calls = (name: string, count: number) =>151 Array.makeBy(count, (n) => ` ${name}("/item/${n}");\n`).join("");152153const indexOf = (name: string) => `packages/${name}/src/index.ts`;154155const extraOf = (name: string) => `packages/${name}/src/extra.ts`;156157const legacyFile = "packages/p1/src/legacy.ts";158159const start: Files = [Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 160–163why, one step back160 [161 "package.json",162 '{ "name": "alice/burrow", "workspaces": ["packages/*"] }\n',163 ],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 164–402why, one step back164 ["scripts/count-callers.mjs", "// prints {total, byModule} for a name\n"],165 [legacyFile, "export const legacyFetch = (url) => fetch(url);\n"],166 ...packages.map((name): readonly [string, string] => [167 indexOf(name),168 `export const run = () => {\n${calls(symbol, callers[name])}};\n`,169 ]),170];171172const changed = (files: Files, path: string, content?: string): Files => [173 ...files.filter(([each]) => each !== path),174 ...(content === undefined ? [] : [[path, content] as const]),175];176177const askFile = (id: string) => {178 const { file } = askOf(id);179180 return { content: `export default "${id}";\n`, path: file };181};182183const plainFiles = (id: string) => {184 const { check } = askOf(id);185186 return Array.make(askFile(id), {187 content: [188 `import { expect, it } from "vitest";`,189 `import { run } from "../src/index.ts";`,190 ``,191 `it("${id}", () => {`,192 ` expect(run()).toStrictEqual(undefined);`,193 `});`,194 ``,195 ].join("\n"),196 path: CheckSpec.guards.RedThenGreen(check)197 ? check.path198 : RepoPath.make(`test/${id}.test.ts`),199 });200};201202interface Merged {203 readonly changes: readonly Change[];204 readonly fork: RepoName;205 readonly head: CommitSha;206 readonly main: LandedSha;207}208209const countedName = (command: string) => command.split(" ")[2] ?? "";210211const occurrences = (text: string, name: string) =>212 text.split(`${name}(`).length - 1;213214interface CheckerOptions {215 readonly drifting?: boolean;216}217218const ratchetsOn = (run: AnswerRun, tree: CheckAt) =>219 Effect.gen(function* () {220 const runner = yield* CheckRunner;221 const specs = run.counts?.ratchets ?? [];222 const block = Option.fromUndefinedOr(run.run);223224 if (specs.length === 0 || Option.isNone(block)) {225 return [];226 }227228 const lanes = specs.map(({ measure: { command }, name }): CheckLane => ({229 command,230 lane: LaneName.make(name),231 output: "stdout",232 }));233234 const ran = yield* runner235 .run({236 at: tree,237 lanes,238 placeholders: [],239 project,240 proxies: [],241 repo,242 run: block.value,243 })244 .pipe(Effect.orDie);245246 const printed = (command: string) =>247 ran.outputs?.find(248 ({ lane }) =>249 lanes.find((each) => each.lane === lane)?.command === command250 )?.stdout ?? "";251252 const counts = yield* Effect.forEach(specs, (spec) =>253 measure(254 spec,255 (command) => Effect.succeed({ code: 0, stdout: printed(command) }),256 run.counts?.modules ?? []257 )258 ).pipe(Effect.orDie);259260 return counts.flat();261 });262263const standIns = (options: CheckerOptions) =>264 Layer.effectContext(265 Effect.gen(function* () {266 const host = yield* RepoHost;267 const inner = yield* Lander;268 const merges = new Map<string, Merged>();269 const counted = yield* Ref.make(0);270 const running = yield* Ref.make<ReadonlySet<RequestId>>(new Set());271272 const lander = Lander.of({273 ...inner,274 merge: (job) =>275 Effect.tap(inner.merge(job), ({ changes, tree }) =>276 Effect.sync(() =>277 merges.set(tree, {278 changes,279 fork: job.fork,280 head: job.head,281 main: job.main,282 })283 )284 ),285 });286287 const read = (from: RepoName, sha: CommitSha, path: string) =>288 host.readFile(from, Revision.Commit({ sha }), RepoPath.make(path)).pipe(289 Effect.orDie,290 Effect.map((bytes) =>291 Option.match(bytes, {292 onNone: () => "",293 onSome: (found) => new TextDecoder().decode(found),294 })295 )296 );297298 const textAt = (at: CheckAt, path: string) =>299 CheckAt.match(at, {300 Commit: ({ commit }) => read(repo, commit, path),301 Tree: ({ tree }) => {302 const merged = merges.get(tree);303304 if (merged === undefined) {305 return Effect.die(`no merge made the tree ${tree}`);306 }307308 const change = merged.changes.find((each) => each.path === path);309310 if (change === undefined) {311 return read(repo, merged.main, path);312 }313314 return change.status === "deleted"315 ? Effect.succeed("")316 : read(merged.fork, merged.head, path);317 },318 });319320 const countAt = (at: CheckAt, name: string) =>321 Effect.gen(function* () {322 const found = yield* Effect.forEach(packages, (each) =>323 Effect.gen(function* () {324 const index = yield* textAt(at, indexOf(each));325 const extra = yield* textAt(at, extraOf(each));326327 return [328 each,329 occurrences(index, name) + occurrences(extra, name),330 ] as const;331 })332 );333334 const skew =335 options.drifting === true336 ? yield* Ref.getAndUpdate(counted, (n) => n + 1)337 : 0;338339 const byModule = Object.fromEntries(340 found.map(([each, count]) => [341 each,342 each === "p1" ? count + skew : count,343 ])344 );345346 return JSON.stringify({347 byModule,348 total: Object.values(byModule).reduce((sum, n) => sum + n, 0),349 });350 });351352 const laneRun = (job: CheckJob, lane: CheckLane) =>353 Effect.gen(function* () {354 const fails =355 CheckAt.guards.Commit(job.at) && lane.lane === "redThenGreen";356357 const result: LaneResult = {358 command: lane.command,359 durationMs: 1,360 lane: lane.lane,361 result: fails ? "failed" : "passed",362 };363364 const output =365 lane.output === "stdout"366 ? Option.some({367 lane: lane.lane,368 stdout: yield* countAt(job.at, countedName(lane.command)),369 })370 : Option.none();371372 return { output, result };373 });374375 const runner = CheckRunner.of({376 run: (job) =>377 Effect.gen(function* () {378 const lanes = yield* Effect.forEach(job.lanes, (lane) =>379 laneRun(job, lane)380 );381382 const outputs = Array.getSomes(lanes.map(({ output }) => output));383384 const ran: CheckRun = {385 durationMs: lanes.length,386 evidence: lanes387 .filter(({ result }) => result.result === "failed")388 .map(({ result }) => ({389 lane: result.lane,390 signature: `${result.lane}: expected undefined`,391 })),392 heldBack: [],393 lanes: lanes.map(({ result }) => result),394 };395396 return Array.isReadonlyArrayEmpty(outputs)397 ? ran398 : { ...ran, outputs };399 }),400 });401402 const ports = Context.make(CheckRunner, runner).pipe(Merge refusal/stale-base-movers into mainoscabrielbefore adoptiona23e097
lines 403–404why, one step back403 Context.add(Lander, lander),404 Context.add(RepoHost, host)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 405–428why, one step back405 );406407 const counting = (queue: AnswerQueue): AnswerQueue => ({408 advanceAnswer: (requestId, command, report) =>409 LandingCommand.$is("Checked")(command)410 ? Effect.gen(function* () {411 const run = yield* queue.answer(requestId);412413 const ratchets = yield* Option.match(run, {414 onNone: () => Effect.succeed([]),415 onSome: (found) =>416 ratchetsOn(417 found,418 CheckAt.cases.Tree.make({ tree: command.tree })419 ).pipe(Effect.provideContext(ports)),420 });421422 return yield* queue.advanceAnswer(requestId, command, {423 ...report,424 ratchets,425 });426 })427 : queue.advanceAnswer(requestId, command, report),428 answer: queue.answer,Merge refusal/stale-base-movers into mainoscabrielbefore adoptiona23e097
line 429why, one step back429 landings: queue.landings,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 430–561why, one step back430 });431432 const leave = (requestId: RequestId) =>433 Ref.update(434 running,435 (under) => new Set([...under].filter((each) => each !== requestId))436 );437438 const runs = AnswerRuns.of({439 start: (requestId, queue) =>440 Effect.gen(function* () {441 const free = yield* Ref.modify(running, (under) =>442 under.has(requestId)443 ? [false, under]444 : [true, new Set(under).add(requestId)]445 );446447 if (free) {448 yield* drive(counting(queue), requestId).pipe(449 Effect.provideContext(ports),450 Effect.ensuring(leave(requestId))451 );452 }453 }),454 });455456 return ports.pipe(Context.add(AnswerRuns, runs));457 })458 );459460const worldWith = (options: CheckerOptions = {}) =>461 standIns(options).pipe(Layer.provideMerge(worldOf(scenario, "memory")));462463const mainTip = Effect.gen(function* () {464 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);465466 return LandedSha.make(467 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))468 );469});470471const commitOf = (sha: CommitSha) =>472 Effect.gen(function* () {473 const host = yield* RepoHost;474 const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);475 const { author, message, parents } = Option.getOrThrow(read);476477 return { author, parents, trailers: parseTrailers(message) };478 });479480const holds = (sha: CommitSha, path: string) =>481 RepoHost.use((host) =>482 host.readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))483 ).pipe(Effect.orDie, Effect.map(Option.isSome));484485const filesAt = (sha: CommitSha) =>486 Effect.gen(function* () {487 const host = yield* RepoHost;488489 const under = (tree: ObjectId, prefix: string): Effect.Effect<Files> =>490 Effect.gen(function* () {491 const entries = yield* host.readTree(repo, tree).pipe(Effect.orDie);492493 const nested = yield* Effect.forEach(494 Option.getOrElse(entries, () => []),495 ({ name, sha: id, type }) =>496 type === "tree"497 ? under(id, `${prefix}${name}/`)498 : Effect.map(499 host.readBlob(repo, id).pipe(Effect.orDie),500 (bytes): Files => [501 [502 `${prefix}${name}`,503 new TextDecoder().decode(504 Option.getOrElse(bytes, () => new Uint8Array())505 ),506 ],507 ]508 )509 );510511 return nested.flat();512 });513514 const commit = yield* host.readCommit(repo, sha).pipe(Effect.orDie);515516 return yield* under(Option.getOrThrow(commit).tree, "");517 });518519const ratchetRows = ProjectStore.use((store) => store.load()).pipe(520 Effect.map(({ ratchets }) =>521 ratchets.map(({ count, ratchet, territory }) => ({522 count,523 ratchet,524 territory,525 }))526 )527);528529const landingCount = ProjectStore.use((store) => store.load()).pipe(530 Effect.map(({ landings }) => landings.length)531);532533const listed = (api: ProjectApi) =>534 Effect.map(api.listAsks(anyone), ({ asks }) =>535 asks.map(({ ask }) => ask).toSorted()536 );537538const shown = (api: ProjectApi, id: AskId) =>539 Effect.map(api.showAsk(anyone, id), ({ ask }) => ask);540541const fromFirstPush = (api: ProjectApi) =>542 Effect.gen(function* () {543 yield* api.initProject(alice, {});544545 const first = yield* Pusher.use((pusher) =>546 pusher.push(repo, Option.none(), start, "Start")547 );548549 yield* api.recordFirstPush(alice, first);550 });551552const answer = (553 api: ProjectApi,554 input: {555 readonly ask: AskId;556 readonly base: LandedSha;557 readonly change: (files: Files) => Files;558 readonly who: Person;559 }560) =>561 Effect.gen(function* () {Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 562–565why, one step back562 const fork = RepoName.make(563 `${keyOf(project)}--${input.ask}--${input.who.handle}`564 );565Merge 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 566–741why, one step back566 const files = yield* filesAt(input.base);567568 const head = yield* Pusher.use((pusher) =>569 pusher.push(fork, Option.some(input.base), input.change(files))570 );571572 return yield* api.submitAnswer(input.who, {573 ask: input.ask,574 base: input.base,575 head,576 requestId: RequestId.make(`req-${input.ask}`),577 });578 });579580const migrated = (name: Package) => (files: Files) =>581 changed(582 files,583 indexOf(name),584 `export const run = () => {\n${calls("http.get", callers[name])}};\n`585 );586587const outcomesOf = (api: ProjectApi, who: string) =>588 Effect.map(api.status(person(who)), ({ answers }) =>589 answers.map(({ outcome }) => outcome)590 );591592const story = Effect.gen(function* () {593 yield* advanceTo("2026-10-07T12:00:00Z");594595 const api = yield* projectService(project);596 const host = yield* RepoHost;597598 yield* fromFirstPush(api);599600 yield* api.openAsk(alice, { ask: tidyId, files: plainFiles(tidyId) });601602 const parentFiles = Array.make(askFile(parentId));603 const beforeFamily = yield* mainTip;604605 const opened = yield* api.openAsk(alice, {606 ask: parentId,607 files: parentFiles,608 });609610 const atOpen = {611 children: yield* Effect.forEach(childIds, (id) => shown(api, id)),612 commit: yield* commitOf(opened.landed),613 deleteChild: yield* shown(api, deleteId),614 files: yield* Effect.forEach([parentId, ...childIds, deleteId], (id) =>615 holds(opened.landed, `${Brand.configDir}/asks/${id}.ask.ts`)616 ),617 listed: yield* listed(api),618 ratchets: yield* ratchetRows,619 };620621 const landingsBefore = yield* landingCount;622623 const replay = yield* api.openAsk(alice, {624 ask: parentId,625 files: parentFiles,626 });627628 const afterReplay = {629 landings: (yield* landingCount) - landingsBefore,630 listed: yield* listed(api),631 main: yield* mainTip,632 ratchets: yield* ratchetRows,633 };634635 const refusedEarly = {636 deleteChild: yield* api.claim(person("heidi"), deleteId).pipe(Effect.flip),637 parent: yield* api.claim(person("heidi"), parentId).pipe(Effect.flip),638 };639640 const claims = yield* Effect.forEach(641 Array.zip(answerers, childIds),642 ([who, id]) => api.claim(person(who), id),643 { concurrency: "unbounded" }644 );645646 const forks = yield* Effect.forEach(claims, ({ claim }) =>647 Effect.map(Effect.exit(host.refs(claim.fork)), Exit.isSuccess)648 );649650 const tidyClaim = yield* api.claim(person("ivan"), tidyId);651652 const landChild = (n: number) =>653 Effect.gen(function* () {654 const name = packages[n] ?? "p1";655656 yield* answer(api, {657 ask: childIdOf(name),658 base: opened.landed,659 change: migrated(name),660 who: person(answerers[n] ?? "bob"),661 });662663 return yield* mainTip;664 });665666 const firstThree = yield* Effect.forEach([0, 1, 2], landChild);667668 const midFamily = {669 deleteClaim: yield* api.claim(person("heidi"), deleteId).pipe(Effect.flip),670 main: yield* mainTip,671 ratchets: yield* ratchetRows,672 };673674 yield* answer(api, {675 ask: tidyId,676 base: LandedSha.make(tidyClaim.claim.base),677 change: (files) =>678 changed(679 files,680 extraOf("p6"),681 `export const extra = () => {\n${calls(symbol, 1)}};\n`682 ),683 who: person("ivan"),684 });685686 const tidyAfter = {687 main: yield* mainTip,688 outcomes: yield* outcomesOf(api, "ivan"),689 };690691 const lastThree = yield* Effect.forEach([3, 4, 5], landChild);692693 const afterSix = {694 deleteChild: yield* shown(api, deleteId),695 parent: yield* shown(api, parentId),696 };697698 const deleteClaim = yield* api.claim(person("heidi"), deleteId);699700 yield* answer(api, {701 ask: deleteId,702 base: LandedSha.make(deleteClaim.claim.base),703 change: (files) => changed(files, legacyFile),704 who: person("heidi"),705 });706707 const deleteLanded = yield* mainTip;708 const childrenLanded = [...firstThree, ...lastThree];709710 return {711 afterReplay,712 afterSix,713 atOpen,714 beforeFamily,715 childrenLanded,716 claims,717 deleteLanded,718 events: (yield* api.events(0, 1000)).map(({ event }) => event),719 forks,720 landings: yield* Effect.forEach(721 [...childrenLanded, deleteLanded],722 commitOf723 ),724 listedAtEnd: yield* listed(api),725 midFamily,726 opened,727 outcomes: yield* Effect.forEach([...answerers, "heidi"], (who) =>728 outcomesOf(api, who)729 ),730 parentAtEnd: yield* shown(api, parentId),731 ratchetsAtEnd: yield* ratchetRows,732 refusedEarly,733 replay,734 tidyAfter,735 };736});737738class Seen extends Context.Service<Seen, Effect.Success<typeof story>>()(739 "test/Seen"740) {}741Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 742why, one step back742// About three seconds alone, more under turbo: the limit catches a hang, not a busy machine.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 743–1585why, one step back743const wholeStory = { timeout: 60_000 };744745const seen = Seen.useSync((told) => told);746747const eventsOf = <T extends ProjectEvent["_tag"]>(748 events: readonly ProjectEvent[],749 tag: T750) =>751 events.filter(752 (event): event is Extract<ProjectEvent, { readonly _tag: T }> =>753 event._tag === tag754 );755756const askedByAlice = {757 key: "Asked-by",758 value: `alice <alice@users.${Brand.domain}>`,759};760761layer(Layer.effect(Seen, story).pipe(Layer.provide(worldWith())), wholeStory)(762 "a migrate ask over six packages",763 (cases) => {764 cases.effect(765 "1. opens as one platform commit adding the parent, the six children and the delete child",766 () =>767 Effect.map(seen, ({ atOpen, beforeFamily, opened }) => {768 expect({769 asked: atOpen.commit.trailers.filter(770 ({ key }) => key === "Asked-by"771 ),772 author: atOpen.commit.author,773 files: atOpen.files,774 opened: opened.ask.id,775 parents: atOpen.commit.parents,776 }).toStrictEqual({777 asked: [askedByAlice],778 author: authorLine(alice.handle),779 files: Array.makeBy(8, () => true),780 opened: parentId,781 parents: [beforeFamily],782 });783 expect(atOpen.listed).toStrictEqual(784 [tidyId, parentId, ...childIds, deleteId].toSorted()785 );786 })787 );788789 cases.effect("1. gives each child its own package as its territory", () =>790 Effect.map(seen, ({ atOpen }) => {791 expect(792 atOpen.children.map(({ brief, check, parent, territory }) => ({793 check: check._tag,794 parent,795 territory: territory.paths,796 want: brief.want,797 }))798 ).toStrictEqual(799 packages.map((name) => ({800 check: "Migrate",801 parent: parentId,802 territory: [Glob.make(`packages/${name}/**`)],803 want: `${name}: ${callers[name]} callers of legacyFetch → http.get`,804 }))805 );806 })807 );808809 cases.effect(810 "1. blocks the delete child on the six, and the parent on all seven",811 () =>812 Effect.map(seen, ({ atOpen, opened }) => {813 expect({814 blockedBy: atOpen.deleteChild.blockedBy,815 check: atOpen.deleteChild.check,816 parent: atOpen.deleteChild.parent,817 state: atOpen.deleteChild.state,818 }).toStrictEqual({819 blockedBy: childIds,820 check: CheckSpec.cases.SymbolAbsent.make({821 count: countOf(symbol),822 symbol: SymbolName.make(symbol),823 }),824 parent: parentId,825 state: "waitingOnParent",826 });827 expect(opened.ask.blockedBy).toStrictEqual([...childIds, deleteId]);828 })829 );830831 cases.effect("1. records the callers ratchet at the counted total", () =>832 Effect.map(seen, ({ atOpen }) => {833 expect(atOpen.ratchets).toStrictEqual([834 { count: total, ratchet: ratchetName, territory: "." },835 ]);836 })837 );838839 cases.effect("opening it again converges on the same family", () =>840 Effect.map(seen, ({ afterReplay, atOpen, opened, replay }) => {841 expect(replay).toStrictEqual(opened);842 expect(afterReplay).toStrictEqual({843 landings: 0,844 listed: atOpen.listed,845 main: opened.landed,846 ratchets: atOpen.ratchets,847 });848 })849 );850851 cases.effect(852 "2. refuses a claim on the delete child, or on the parent, as blocked",853 () =>854 Effect.map(seen, ({ refusedEarly }) => {855 expect(refusedEarly).toStrictEqual({856 deleteChild: AskBlocked.of(deleteId, childIds),857 parent: AskBlocked.of(parentId, Array.append(childIds, deleteId)),858 });859 })860 );861862 cases.effect(863 "3. lets six people claim the six children at once, each in a fork",864 () =>865 Effect.map(seen, ({ claims, forks }) => {866 expect(867 claims.map(({ claim }) => [claim.ask, claim.claimant])868 ).toStrictEqual(Array.zip(childIds, answerers));869 expect(forks).toStrictEqual(Array.makeBy(6, () => true));870 })871 );872873 cases.effect(874 "4. lands the six answers in turn, none stale, each authored by its claimant and asked by alice",875 () =>876 Effect.map(seen, ({ landings, outcomes, childrenLanded }) => {877 expect(outcomes.slice(0, 6)).toStrictEqual(878 childrenLanded.map((sha) => [Outcome.cases.Landed.make({ sha })])879 );880 expect(881 landings.slice(0, 6).map(({ author, trailers }) => ({882 asked: trailers.filter(({ key }) => key === "Asked-by"),883 author,884 }))885 ).toStrictEqual(886 answerers.map((who) => ({887 asked: [askedByAlice],888 author: authorLine(Handle.make(who)),889 }))890 );891 })892 );893894 cases.effect(895 "5. still refuses the delete child after three land, naming the three still open",896 () =>897 Effect.map(seen, ({ midFamily }) => {898 expect(midFamily.deleteClaim).toStrictEqual(899 AskBlocked.of(900 deleteId,901 Array.map(["p4", "p5", "p6"] as const, childIdOf)902 )903 );904 })905 );906907 cases.effect("lowers the callers ratchet as each child lands", () =>908 Effect.map(seen, ({ midFamily, ratchetsAtEnd }) => {909 expect([midFamily.ratchets, ratchetsAtEnd]).toStrictEqual([910 [911 {912 count: total - callers.p1 - callers.p2 - callers.p3,913 ratchet: ratchetName,914 territory: ".",915 },916 ],917 [{ count: 0, ratchet: ratchetName, territory: "." }],918 ]);919 })920 );921922 cases.effect(923 "7. refuses a plain answer that adds a caller mid-family as a weakened ratchet, and lands nothing",924 () =>925 Effect.map(seen, ({ midFamily, tidyAfter }) => {926 const before = total - callers.p1 - callers.p2 - callers.p3;927928 expect(tidyAfter).toStrictEqual({929 main: midFamily.main,930 outcomes: [931 Outcome.cases.Refused.make({932 refusals: [933 new Weakened({934 weakening: {935 after: before + 1,936 before,937 ratchet: ratchetName,938 territory: ".",939 },940 }),941 ],942 }),943 ],944 });945 })946 );947948 cases.effect(949 "6. opens the delete child once the six land, while the parent waits on it",950 () =>951 Effect.map(seen, ({ afterSix, events }) => {952 expect([953 afterSix.deleteChild.state,954 afterSix.parent.state,955 ]).toStrictEqual(["open", "open"]);956 expect(957 eventsOf(events, "AskOpened")958 .map(({ ask }) => ask.ask)959 .filter((id) => id === deleteId)960 ).toStrictEqual([deleteId]);961 })962 );963964 cases.effect(965 "6. lands the delete child by heidi, and closes the parent on that landing",966 () =>967 Effect.map(968 seen,969 ({970 deleteLanded,971 events,972 landings,973 listedAtEnd,974 outcomes,975 parentAtEnd,976 }) => {977 expect({978 author: landings[6]?.author,979 outcome: outcomes[6],980 parent: parentAtEnd.state,981 }).toStrictEqual({982 author: authorLine(Handle.make("heidi")),983 outcome: [Outcome.cases.Landed.make({ sha: deleteLanded })],984 parent: "closed",985 });986 expect(listedAtEnd).toStrictEqual([tidyId]);987 expect(988 eventsOf(events, "AskClosed").filter(989 ({ ask }) => ask === parentId990 )991 ).toStrictEqual([992 expect.objectContaining({ ask: parentId, landing: deleteLanded }),993 ]);994 }995 )996 );997 }998);9991000const allAtOnce = Effect.gen(function* () {1001 yield* advanceTo("2026-10-07T12:00:00Z");10021003 const api = yield* projectService(project);10041005 yield* fromFirstPush(api);10061007 const opened = yield* api.openAsk(alice, {1008 ask: parentId,1009 files: Array.make(askFile(parentId)),1010 });10111012 const children = Array.zip(packages, answerers);10131014 yield* Effect.forEach(1015 children,1016 ([name, who]) => api.claim(person(who), childIdOf(name)),1017 { concurrency: "unbounded" }1018 );10191020 yield* Effect.forEach(1021 children,1022 ([name, who]) =>1023 answer(api, {1024 ask: childIdOf(name),1025 base: opened.landed,1026 change: migrated(name),1027 who: person(who),1028 }),1029 { concurrency: "unbounded" }1030 );10311032 // Whatever waits on a retry runs at the project's next alarms.1033 yield* api.onAlarm();1034 yield* advanceTo("2026-10-07T12:10:00Z");1035 yield* api.onAlarm();10361037 return {1038 deleteChild: (yield* shown(api, deleteId)).state,1039 outcomes: yield* Effect.forEach(answerers, (who) =>1040 Effect.map(outcomesOf(api, who), (all) => all.map(({ _tag }) => _tag))1041 ),1042 ratchets: yield* ratchetRows,1043 };1044}).pipe(Effect.provide(worldWith()));10451046describe("six answers to the six children at once", () => {1047 it.effect(1048 "all land, none stale and none refused by the callers ratchet",1049 () =>1050 Effect.map(allAtOnce, (seenThen) => {1051 expect(seenThen).toStrictEqual({1052 deleteChild: "open",1053 outcomes: Array.makeBy(6, () => ["Landed"]),1054 ratchets: [{ count: 0, ratchet: ratchetName, territory: "." }],1055 });1056 }),1057 wholeStory1058 );1059});10601061const openingOf = (id: string, options: CheckerOptions = {}) =>1062 Effect.gen(function* () {1063 yield* advanceTo("2026-10-07T12:00:00Z");10641065 const api = yield* projectService(project);10661067 yield* fromFirstPush(api);10681069 const opened = yield* Effect.result(1070 api.openAsk(alice, {1071 ask: AskId.make(id),1072 files: Array.make(askFile(id)),1073 })1074 );10751076 return {1077 landings: yield* landingCount,1078 listed: yield* listed(api),1079 opened,1080 ratchets: yield* ratchetRows,1081 };1082 }).pipe(Effect.provide(worldWith(options)));10831084const reopening = Effect.gen(function* () {1085 yield* advanceTo("2026-10-07T12:00:00Z");10861087 const api = yield* projectService(project);1088 const onePackage = AskId.make("move-p2-fetch");10891090 yield* fromFirstPush(api);1091 yield* api.openAsk(alice, {1092 ask: onePackage,1093 files: Array.make(askFile(onePackage)),1094 });10951096 const moving = yield* api.claim(person("bob"), onePackage);10971098 yield* answer(api, {1099 ask: onePackage,1100 base: LandedSha.make(moving.claim.base),1101 change: migrated("p2"),1102 who: person("bob"),1103 });11041105 yield* api.openAsk(alice, { ask: tidyId, files: plainFiles(tidyId) });11061107 const tidying = yield* api.claim(person("ivan"), tidyId);11081109 yield* answer(api, {1110 ask: tidyId,1111 base: LandedSha.make(tidying.claim.base),1112 change: (files) =>1113 changed(1114 files,1115 extraOf("p6"),1116 `export const extra = () => {\n${calls(symbol, 1)}};\n`1117 ),1118 who: person("ivan"),1119 });11201121 const left = yield* ratchetRows;11221123 yield* api.openAsk(alice, {1124 ask: parentId,1125 files: Array.make(askFile(parentId)),1126 });11271128 return { left, opened: yield* ratchetRows };1129}).pipe(Effect.provide(worldWith()));11301131const overwriting = Effect.gen(function* () {1132 yield* advanceTo("2026-10-07T12:00:00Z");11331134 const api = yield* projectService(project);1135 const p1 = childIdOf("p1");11361137 yield* fromFirstPush(api);1138 yield* api.openAsk(alice, { ask: p1, files: Array.make(askFile(p1)) });11391140 const main = yield* mainTip;11411142 const opened = yield* Effect.result(1143 api.openAsk(alice, {1144 ask: parentId,1145 files: Array.make(askFile(parentId)),1146 })1147 );11481149 return {1150 listed: yield* listed(api),1151 main,1152 mainAfter: yield* mainTip,1153 opened,1154 };1155}).pipe(Effect.provide(worldWith()));11561157describe("opening a migrate ask", () => {1158 it.effect(1159 "is refused TouchedJudge when a child's file would replace an ask the project holds",1160 () =>1161 Effect.map(overwriting, ({ listed: open, main, mainAfter, opened }) => {1162 expect({ listed: open, mainAfter, opened }).toStrictEqual({1163 listed: [childIdOf("p1")],1164 mainAfter: main,1165 opened: Result.fail(1166 new TouchedJudge({1167 paths: [1168 RepoPath.make(1169 `${Brand.configDir}/asks/${childIdOf("p1")}.ask.ts`1170 ),1171 ],1172 })1173 ),1174 });1175 }),1176 wholeStory1177 );11781179 it.effect(1180 "is refused NotRedFirst when the two counts on main differ",1181 () =>1182 Effect.map(openingOf(parentId, { drifting: true }), (seenThen) => {1183 expect(seenThen).toStrictEqual({1184 landings: 1,1185 listed: [],1186 opened: Result.fail(new NotRedFirst({})),1187 ratchets: [],1188 });1189 }),1190 wholeStory1191 );11921193 it.effect(1194 "is refused NotRedFirst when nothing calls the name: nothing to migrate",1195 () =>1196 Effect.map(openingOf("drop-old-thing"), ({ listed: open, opened }) => {1197 expect([open, opened]).toStrictEqual([1198 [],1199 Result.fail(new NotRedFirst({})),1200 ]);1201 }),1202 wholeStory1203 );12041205 it.effect(1206 "records the callers ratchet at the counted total, over a lower one a closed migrate ask left",1207 () =>1208 Effect.map(reopening, (seenThen) => {1209 expect(seenThen).toStrictEqual({1210 left: [1211 { count: total - callers.p2, ratchet: ratchetName, territory: "." },1212 ],1213 opened: [1214 {1215 count: total - callers.p2 + 1,1216 ratchet: ratchetName,1217 territory: ".",1218 },1219 ],1220 });1221 }),1222 wholeStory1223 );12241225 it.effect(1226 "opens as one plain ask, with no family, when its territory is one package",1227 () =>1228 Effect.map(1229 openingOf("move-p2-fetch"),1230 ({ listed: open, opened, ratchets }) => {1231 expect({1232 blockedBy: Result.map(opened, ({ ask }) => ask.blockedBy),1233 listed: open,1234 ratchets,1235 }).toStrictEqual({1236 blockedBy: Result.succeed([]),1237 listed: [AskId.make("move-p2-fetch")],1238 ratchets: [{ count: total, ratchet: ratchetName, territory: "." }],1239 });1240 }1241 ),1242 wholeStory1243 );1244});12451246const parent: Ask = askOf(parentId);12471248const { modules } = scenario.policy;12491250const counted = (byModule: Readonly<Record<string, number>>): CallerCount => ({1251 byModule,1252 total: Object.values(byModule).reduce((sum, n) => sum + n, 0),1253});12541255const split = (1256 byModule: Readonly<Record<string, number>>,1257 of: Ask = parent1258): Option.Option<MigrateFamily> =>1259 splitFamily({1260 configDir: Brand.configDir,1261 counts: counted(byModule),1262 modules,1263 parent: of,1264 });12651266const comparable = (ask: Ask) =>1267 Struct.pick(ask, [1268 "blockedBy",1269 "check",1270 "file",1271 "id",1272 "kind",1273 "parent",1274 "state",1275 "territory",1276 ]);12771278describe(splitFamily, () => {1279 it("splits as testkit's sixChildren() is written by hand: six children and a delete child", () => {1280 const made = Option.getOrThrow(split(callers));1281 const byHand = new Map(family.policy.asks.map((ask) => [ask.id, ask]));12821283 const expected = (id: AskId, state: Ask["state"]) => {1284 const {1285 blockedBy,1286 check,1287 file,1288 kind,1289 parent: of,1290 territory,1291 } = byHand.get(id) ?? parent;12921293 return { blockedBy, check, file, id, kind, parent: of, state, territory };1294 };12951296 expect([...made.children, made.deleteChild].map(comparable)).toStrictEqual([1297 ...childIds.map((id) => expected(id, "open")),1298 expected(deleteId, "waitingOnParent"),1299 ]);1300 expect({1301 blockedBy: made.parent.blockedBy,1302 files: made.files.map(({ path }) => path),1303 ratchet: made.ratchet,1304 }).toStrictEqual({1305 blockedBy: [...childIds, deleteId],1306 files: [...childIds, deleteId].map((id) =>1307 RepoPath.make(`${Brand.configDir}/asks/${id}.ask.ts`)1308 ),1309 ratchet: { baseline: total, name: ratchetName },1310 });1311 });13121313 it("gives no child to a module with no callers", () => {1314 expect(1315 Option.map(split({ ...callers, p3: 0 }), ({ children }) =>1316 children.map(({ id }) => id)1317 )1318 ).toStrictEqual(1319 Option.some(Array.map(["p1", "p2", "p4", "p5", "p6"] as const, childIdOf))1320 );1321 });13221323 it("gives no child to a module outside the parent's territory", () => {1324 const narrower: Ask = {1325 ...parent,1326 territory: {1327 module: ".",1328 paths: [Glob.make("packages/p1/**"), Glob.make("packages/p2/**")],1329 },1330 };13311332 expect(1333 Option.map(split(callers, narrower), ({ children }) =>1334 children.map(({ id }) => id)1335 )1336 ).toStrictEqual(Option.some(Array.map(["p1", "p2"] as const, childIdOf)));1337 });13381339 it.each([1340 ["only one module has callers", { p2: 7 }, parent],1341 [1342 "the territory names one package",1343 callers,1344 { ...parent, territory: modules[1] ?? parent.territory },1345 ],1346 [1347 "the ask is no migrate ask",1348 callers,1349 {1350 ...parent,1351 check: CheckSpec.cases.SymbolAbsent.make({1352 count: countOf(symbol),1353 symbol: SymbolName.make(symbol),1354 }),1355 },1356 ],1357 ] as const)("does not split when %s", (_, byModule, of) => {1358 expect(split(byModule, of)).toStrictEqual(Option.none());1359 });13601361 it("holds every child to the parent's asker, kind and reserve", () => {1362 const reserved: Ask = {1363 ...parent,1364 mentor: Handle.make("alice"),1365 reserve: "newcomers",1366 };13671368 const made = Option.getOrThrow(split(callers, reserved));13691370 expect(1371 [...made.children, made.deleteChild].map((ask) =>1372 Struct.pick(ask, ["askedBy", "kind", "mentor", "reserve"])1373 )1374 ).toStrictEqual(1375 Array.makeBy(7, () => ({1376 askedBy: parent.askedBy,1377 kind: KindName.make("migrate"),1378 mentor: Handle.make("alice"),1379 reserve: "newcomers",1380 }))1381 );1382 });1383});13841385describe(callersIn, () => {1386 const twoPackages: Territory = {1387 module: ".",1388 paths: [Glob.make("packages/p1/**"), Glob.make("packages/p2/**")],1389 };13901391 it.each([1392 ["the one package it names", modules[1] ?? parent.territory, 7],1393 ["every package", parent.territory, total],1394 ["two of the six packages", twoPackages, callers.p1 + callers.p2],1395 ] as const)("counts the callers in %s", (_, territory, count) => {1396 expect(callersIn(territory, counted(callers), modules)).toStrictEqual(1397 count1398 );1399 });1400});14011402describe(childId, () => {1403 it.each([1404 ["p1", "drop-legacy-fetch-p1"],1405 ["@burrow/http-kit", "drop-legacy-fetch-burrow-http-kit"],1406 ["--Odd__Name--", "drop-legacy-fetch-odd-name"],1407 ])("names %s's child %s, an ask id with no --", (module, id) => {1408 const named = childId(parentId, module);14091410 expect([1411 named,1412 named.includes("--"),1413 Schema.is(AskId)(named),1414 ]).toStrictEqual([id, false, true]);1415 });14161417 it("names the delete child apart from every child", () => {1418 expect(deleteChildId(parentId)).toStrictEqual(deleteId);1419 });1420});14211422const standing = (closed: readonly Package[]) => {1423 const made = Option.getOrThrow(split(callers));14241425 return new Map(1426 [made.parent, ...made.children, made.deleteChild].map((ask) => [1427 ask.id,1428 packages.some(1429 (name) => closed.includes(name) && childIdOf(name) === ask.id1430 )1431 ? { ...ask, state: "closed" as const }1432 : ask,1433 ])1434 );1435};14361437describe(remainingBlockers, () => {1438 it("names the children still open, in order", () => {1439 const asks = standing(["p1", "p3", "p5"]);14401441 expect(1442 remainingBlockers(1443 Option.getOrThrow(Option.fromUndefinedOr(asks.get(deleteId))),1444 asks1445 )1446 ).toStrictEqual(Array.map(["p2", "p4", "p6"] as const, childIdOf));1447 });14481449 it("names none once every child has closed", () => {1450 const asks = standing(packages);14511452 expect(1453 remainingBlockers(1454 Option.getOrThrow(Option.fromUndefinedOr(asks.get(deleteId))),1455 asks1456 )1457 ).toStrictEqual([]);1458 });14591460 it("keeps an ask it does not know as blocking", () => {1461 const ghost = AskId.make("never-opened");14621463 expect(1464 remainingBlockers({ ...parent, blockedBy: [ghost] }, new Map())1465 ).toStrictEqual([ghost]);1466 });1467});14681469describe(familyClosed, () => {1470 it("is false while the delete child is open, and true once it closes", () => {1471 const asks = standing(packages);14721473 const deleteChild = Option.getOrThrow(1474 Option.fromUndefinedOr(asks.get(deleteId))1475 );14761477 expect([1478 familyClosed(parentId, asks),1479 familyClosed(1480 parentId,1481 new Map(asks).set(deleteId, { ...deleteChild, state: "closed" })1482 ),1483 ]).toStrictEqual([false, true]);1484 });14851486 it("is false for an ask with no children", () => {1487 expect([familyClosed(tidyId, standing([]))]).toStrictEqual([false]);1488 });1489});14901491const facts = Schema.decodeSync(EvaluationFacts)({1492 ci: [],1493 initializer: "alice",1494 now: "2026-10-07T12:00:00.000Z",1495 project,1496 seed: 7,1497 workspaces: packages.map((name) => ({1498 dir: `packages/${name}`,1499 exports: [],1500 name,1501 })),1502});15031504const projectFile = [1505 `import { kinds, project } from "${Brand.cliPackage}/rules";`,1506 "",1507 "export default project({",1508 " kinds: [kinds.migrate],",1509 ' run: { checks: {}, test: "bun test {path}" },',1510 "});",1511 "",1512].join("\n");15131514const stated = (ask: Ask) =>1515 Struct.pick(ask, [1516 "blockedBy",1517 "brief",1518 "check",1519 "file",1520 "id",1521 "kind",1522 "parent",1523 "territory",1524 ]);15251526const byId = (asks: readonly Ask[]) =>1527 asks.map(stated).toSorted((a, b) => a.id.localeCompare(b.id));15281529const evaluatedFamily = (of: Ask) =>1530 Effect.gen(function* () {1531 const made = Option.getOrThrow(split(callers, of));1532 const evaluator = yield* RulesEvaluator;15331534 const policy = yield* evaluator.evaluate({1535 at: LandedSha.make("a".repeat(40)),1536 facts,1537 modules: {1538 entry: `${Brand.configDir}/project.ts`,1539 modules: {1540 [`${Brand.configDir}/project.ts`]: projectFile,1541 ...Object.fromEntries(1542 made.files.map(({ content, path }) => [path, content])1543 ),1544 },1545 sdkVersion,1546 },1547 });15481549 return {1550 evaluated: byId(policy.asks),1551 family: byId([...made.children, made.deleteChild]),1552 };1553 }).pipe(1554 Effect.provide(1555 RulesEvaluatorBun.pipe(1556 Layer.provide(Layer.mergeAll(FinishersFromChecks, NodeServices.layer))1557 )1558 )1559 );15601561describe("the family's ask files", () => {1562 it.live(1563 "evaluate, through the sdk, to the family's children and its delete child",1564 () =>1565 Effect.map(evaluatedFamily(parent), ({ evaluated, family: written }) => {1566 expect(evaluated).toStrictEqual(written);1567 }),1568 wholeStory1569 );15701571 it.live(1572 "keep the parent's kind when it is a migrate kind of another name",1573 () =>1574 Effect.map(1575 evaluatedFamily({ ...parent, kind: KindName.make("dropApi") }),1576 ({ evaluated, family: written }) => {1577 expect([1578 evaluated,1579 Array.dedupe(evaluated.map(({ kind }) => kind)),1580 ]).toStrictEqual([written, [KindName.make("dropApi")]]);1581 }1582 ),1583 wholeStory1584 );1585});