Open a migrate ask as a family: one step per package with callers, a delete step that waits on them, and a callers ratchet; six answers land at once
Before adoption: this commit came in with the history the project adopted, so no landing records it.
W5 group A (issue 506), the multi-agent split demo (SYN cut line 6). - packages/project/src/migrate.ts (pure): `CallerCount` (what the count command prints: `{total, byModule}`, counts at least 0); `splitFamily` (one step per module of the parent's territory with callers, in the policy's module order, each with that module as territory and the parent's `Migrate` check; a delete step with `SymbolAbsent{symbol: from, count}`, the parent's territory, `blockedBy` the steps and state `waitingOnParent`; the parent blocked by all seven; their ask files; the callers ratchet at the total; `None` for no migrate ask or fewer than two modules with callers); `childId` (`<parent>-<module slug>`, never `--`), `deleteChildId`, `remainingBlockers`, `familyClosed`, plus `modulesWithin`, `callersIn`, `callersRatchet`, `callersSpecs`, `sameCount`. - openAsk (project.ts): a `migrate` or `symbolAbsent` ask is red first by its count. Its ask lane hands back stdout, the two runs on the composed commit must print the same count, and that count must be above zero in the ask's territory (exit status said nothing: a count command exits 0). A migrate ask whose callers sit in two or more of its modules then lands its family beside the decider's file in one platform commit (`Asked-by` the decider, the body naming the steps), and records `callers-<from>` at the total through `afterLanding`. A one-package migrate ask opens as one plain ask, with the ratchet. A family file that would overwrite a taken ask file is `TouchedJudge{paths}`. - claim: `remainingBlockers` feeds the `Claim` command, so the delete step and the parent are `AskBlocked` until their steps land. - After each landing (`recordLanding`): a step waiting on its siblings opens when the last lands (state `open`, `AskOpened`), and the parent closes on the landing that closes its last step (`AskClosed{ask: parent, landing}`). - runOf: while a migrate ask is open its callers ratchet (a `Metric` on `$.total`) joins the run's `counts.ratchets`, so the platform's cheap stage counts it on every answer: a caller added anywhere is `Weakened{ratchet: callers-…}`, and each step's landing lowers it. - ratchetJudged: a tree merged onto a main that has moved is not judged against the ratchets; its land finds main moved, and it is re-merged and re-checked first. Without this, three of six answers submitted at once were refused `Weakened{callers}`: each was judged on a stale tree against a baseline a sibling had just lowered. The same failure would hit a lintToZero split. - Decision: "waits as WaitingOnParent" is the delete step's AskState. An answer cannot reach a blocked ask (the claim is refused, so there is no fork and a push is `NotClaimed`), so the landing lifecycle's `Wait` still has no caller; recorded for the integrator. - Decision: generated step files use `kinds.migrate.ask` when the parent's kind is `migrate`, else a `kind` of the parent's name made in the file. The delete step's file makes its own `kind` with `checkKind: "symbolAbsent"`, since the sdk has no `check.symbolAbsent` (203 #13, outside this territory). - Tests (packages/project/test/migrate.test.ts, 35, about 2 s; red first by the open refused `NotRedFirst`): the story over memory adapters on `sixChildren()`, told once through `@effect/vitest`'s `layer`. It covers the one family commit with 8 asks, each step's package territory, the delete step blocked on six and the parent on seven, the ratchet at 37, `openAsk` again converging (same result, no landing), `AskBlocked` on the delete step and the parent, six concurrent claims with six forks, six landings authored by their claimants with `Asked-by: alice`, `AskBlocked` naming exactly the three open after three land, the ratchet 37 → 19 → 0, a plain answer adding a caller refused `Weakened{callers-legacyfetch, 19 → 20}` with main unmoved, the delete step opening after six and its landing closing the parent. Six answers submitted at once all land (red without the ratchetJudged fix). `NotRedFirst` on drifting counts and on a name nobody calls, and a one-package migrate ask opens alone. Pure cases for `splitFamily` (equal to testkit's hand-written family; modules without callers or outside the territory; three no-split cases; asker, kind and reserve inherited), `childId`, `remainingBlockers` and `familyClosed`. The generated files are evaluated through the real `/bun` rules evaluator and come back as the family's asks, for a `migrate` parent and a parent of another kind name. - Stand-ins in the test, for what the platform runs elsewhere: a Checker that counts callers on the files of the tree it is given, a Lander that records merges so merged trees can be read, and answer runs that count ratchets before reporting a check (the inline runs count none; noted for the integrator). - ASSUMPTION: "the same RequestId" for openAsk (which takes none) is the opening landing's `open-<tree>`. An open parent is returned as it stands, and a replay lands the same tree under the same id. - Open for the integrator (issue Comments 10-15): a `migrate` step's answer is still judged by its lane's exit status, not by 0 callers in its package (platform lanes.ts and inline steps.ts); the inline runs count no ratchets; `maxRemerges = 3` for larger concurrent families. - verify green (project 374 tests, 35 of them new; debt at baseline, platform entry 1,604,053 of 1,665,000).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+2191 added−35 removed
- tests:+1528 added−0 removed
- other:+663 added−35 removed
Provenance
- Commit
15afcac- Tree
22e5e45- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
eebd79b
3 files changed+2191 added−35 removed
added:packages/project/src/migrate.ts+358 added
1+/**2+ * A migrate ask's family (CAA §2.F): one ask that moves every use of a name3+ * to another opens, when its callers sit in two or more of the project's4+ * modules, as one step per module with callers, each with that module as5+ * its territory and "no callers in this module" as its check, and a delete6+ * step that waits on every step and checks the name is gone. The steps'7+ * territories are disjoint, so their claims never overlap and their answers8+ * re-merge cleanly through the serial landing queue; the parent closes when9+ * its last step lands.10+ *11+ * Pure: the callers are counted by the project's own command (its stdout is12+ * `CallerCount`), never by a scan here, and the service lands the family and13+ * moves it after each landing.14+ */15+import { Brand } from "@repo/brand";16+import { matchAny } from "@repo/gate/glob";17+import type { Ask } from "@repo/protocol/domain/ask";18+import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";19+import type { RatchetSpec } from "@repo/protocol/domain/check";20+import { JsonPath, NoneOrMore } from "@repo/protocol/domain/common";21+import type { Command, SymbolName } from "@repo/protocol/domain/common";22+import type { Territory } from "@repo/protocol/domain/territory";23+import { AskId, RatchetName, RepoPath } from "@repo/protocol/ids";24+import { Array, Option, Schema } from "effect";25+26+/**27+ * What a migrate ask's count command prints: every caller of the name, and28+ * the callers in each module, by the module's name.29+ */30+export const CallerCount = Schema.Struct({31+ byModule: Schema.Record(Schema.String, NoneOrMore),32+ total: NoneOrMore,33+});34+35+export type CallerCount = typeof CallerCount.Type;36+37+/** A count command's stdout, read as its `CallerCount`. */38+export const callerCountOf = Schema.decodeUnknownOption(39+ Schema.fromJsonString(CallerCount)40+);41+42+/** Whether two counts are the same: the same total, and the same callers in every module. */43+export const sameCount = (one: CallerCount, other: CallerCount): boolean =>44+ one.total === other.total &&45+ Array.dedupe([46+ ...Object.keys(one.byModule),47+ ...Object.keys(other.byModule),48+ ]).every(49+ (module) => (one.byModule[module] ?? 0) === (other.byModule[module] ?? 0)50+ );51+52+/** A migrate ask's check: the name it moves from, where to, and the command that counts callers. */53+type MigrateCheck = Extract<CheckSpec, { readonly _tag: "Migrate" }>;54+55+/** One file the family adds to the config folder. */56+export interface FamilyFile {57+ readonly content: string;58+ readonly path: RepoPath;59+}60+61+/** A migrate ask split into its family, and what its opening lands. */62+export interface MigrateFamily {63+ /** The migrate ask, blocked by every step and the delete step. */64+ readonly parent: Ask;65+ /** One step per module with callers, in the policy's module order. */66+ readonly children: Array.NonEmptyReadonlyArray<Ask>;67+ /** The last step: the name is gone. Blocked by every step until they land. */68+ readonly deleteChild: Ask;69+ /** The steps' and the delete step's ask files, in that order. */70+ readonly files: Array.NonEmptyReadonlyArray<FamilyFile>;71+ /** The callers ratchet the opening records, at the counted total. */72+ readonly ratchet: {73+ readonly name: RatchetName;74+ readonly baseline: number;75+ };76+}77+78+/** `@burrow/http-kit` → `burrow-http-kit`: a name an ask id can carry. */79+const slug = (name: string) =>80+ name81+ .toLowerCase()82+ .replaceAll(/[^a-z0-9]+/gu, "-")83+ .replaceAll(/^-+|-+$/gu, "");84+85+/**86+ * The id of a family's step in `module`: `drop-legacy-fetch-p1`. It never87+ * holds `--`, which repo names keep as their separator (spec §4.5).88+ */89+export const childId = (parent: AskId, module: string): AskId =>90+ AskId.make(`${parent}-${slug(module) || "root"}`);91+92+/** The id of a family's delete step: `drop-legacy-fetch-delete`. */93+export const deleteChildId = (parent: AskId): AskId =>94+ AskId.make(`${parent}-delete`);95+96+/** The ratchet on a name's callers: `legacyFetch` → `callers-legacyfetch`. */97+export const callersRatchet = (from: SymbolName): RatchetName =>98+ RatchetName.make(`callers-${slug(from) || "name"}`);99+100+/** What an ask still waits on: each ask it is blocked by that has not closed. */101+export const remainingBlockers = (102+ ask: Ask,103+ asks: ReadonlyMap<AskId, Ask>104+): readonly AskId[] =>105+ ask.blockedBy.filter((blocker) => asks.get(blocker)?.state !== "closed");106+107+/** Whether a family is done: it has steps, and every one has closed. */108+export const familyClosed = (109+ parent: AskId,110+ asks: ReadonlyMap<AskId, Ask>111+): boolean => {112+ const members = [...asks.values()].filter((ask) => ask.parent === parent);113+114+ return members.length > 0 && members.every(({ state }) => state === "closed");115+};116+117+/**118+ * The modules a territory spans: the one it names, or every module whose119+ * paths its globs all cover (`packages/**` covers `packages/p1/**`).120+ */121+export const modulesWithin = (122+ territory: Territory,123+ modules: readonly Territory[]124+): readonly Territory[] => {125+ const named = modules.filter(({ module }) => module === territory.module);126+127+ return named.length > 0128+ ? named129+ : modules.filter(({ paths }) =>130+ paths.every((glob) => matchAny(territory.paths, glob))131+ );132+};133+134+/**135+ * The callers an ask's own check counts: in its module, when its territory136+ * names one; everywhere, when it spans the repo.137+ */138+export const callersIn = (139+ territory: Territory,140+ counts: CallerCount,141+ modules: readonly Territory[]142+): number =>143+ modules.some(({ module }) => module === territory.module)144+ ? (counts.byModule[territory.module] ?? 0)145+ : counts.total;146+147+/**148+ * The ratchet a migrate ask's callers are counted by on every answer while149+ * it is open: its count command's `total`, over the whole project.150+ */151+export const callersSpec = (check: MigrateCheck): RatchetSpec => ({152+ measure: RatchetMeasure.cases.Metric.make({153+ command: check.count,154+ path: JsonPath.make("$.total"),155+ }),156+ name: callersRatchet(check.from),157+});158+159+/** The callers ratchets of every migrate ask still open, one per name. */160+export const callersSpecs = (asks: Iterable<Ask>): readonly RatchetSpec[] =>161+ Array.dedupeWith(162+ [...asks].flatMap(({ check, state }) =>163+ CheckSpec.guards.Migrate(check) && state !== "closed"164+ ? [callersSpec(check)]165+ : []166+ ),167+ (one, other) => one.name === other.name168+ );169+170+const quoted = (text: string) => JSON.stringify(text);171+172+const header = (parent: AskId) =>173+ `// A step of the migrate ask ${parent}, written by ${Brand.name} when it opened.`;174+175+const sdk = quoted(`${Brand.cliPackage}/rules`);176+177+/** An object literal's lines, each `key: value,`, indented by two. */178+const fields = (entries: readonly (readonly [string, string])[]) =>179+ entries.map(([key, value]) => ` ${key}: ${value},`);180+181+/**182+ * A step's file, through the sdk's `kinds.migrate` when the parent is of183+ * that kind, else through a kind of the parent's name made in the file.184+ */185+const stepFile = (step: Ask, check: MigrateCheck, parent: AskId) => {186+ const stated: (readonly [string, string])[] = [187+ ["parent", quoted(parent)],188+ ["territory", `territory.package(${quoted(step.territory.module)})`],189+ ["want", quoted(step.brief.want)],190+ ];191+192+ const args: (readonly [string, string])[] = [193+ ["count", quoted(check.count)],194+ ["from", quoted(check.from)],195+ ...(check.to === undefined ? [] : [["to", quoted(check.to)] as const]),196+ ];197+198+ if (step.kind === "migrate") {199+ return [200+ header(parent),201+ `import { kinds, territory } from ${sdk};`,202+ "",203+ "export default kinds.migrate.ask({",204+ ...fields(205+ [...args, ...stated].toSorted(([a], [b]) => a.localeCompare(b))206+ ),207+ "});",208+ "",209+ ].join("\n");210+ }211+212+ return [213+ header(parent),214+ `import { check, kind, territory } from ${sdk};`,215+ "",216+ "const step = kind({",217+ " args: {},",218+ ` check: () => check.migrate({ ${args.map(([key, value]) => `${key}: ${value}`).join(", ")} }),`,219+ ` checkKind: "migrate",`,220+ ` name: ${quoted(step.kind)},`,221+ "});",222+ "",223+ "export default step.ask({",224+ ...fields(stated),225+ "});",226+ "",227+ ].join("\n");228+};229+230+/**231+ * The delete step's file: the sdk has no `symbolAbsent` builder, so the232+ * file makes a kind of the parent's name whose check is the name gone.233+ */234+const deleteFile = (step: Ask, check: MigrateCheck, parent: AskId) =>235+ [236+ header(parent),237+ `import { kind } from ${sdk};`,238+ "",239+ "const step = kind({",240+ " args: {},",241+ ` check: () => ({ _tag: "SymbolAbsent", count: ${quoted(check.count)}, symbol: ${quoted(check.from)} }),`,242+ ` checkKind: "symbolAbsent",`,243+ ` name: ${quoted(step.kind)},`,244+ "});",245+ "",246+ "export default step.ask({",247+ ...fields([248+ ["blockedBy", JSON.stringify(step.blockedBy)],249+ ["parent", quoted(parent)],250+ ["territory", JSON.stringify(step.territory)],251+ ["want", quoted(step.brief.want)],252+ ]),253+ "});",254+ "",255+ ].join("\n");256+257+const callersOf = (count: number) =>258+ count === 1 ? "1 caller" : `${count} callers`;259+260+/** A step's want: `p1: 5 callers of legacyFetch → http.get`. */261+const stepWant = (module: string, count: number, check: MigrateCheck) =>262+ check.to === undefined263+ ? `${module}: ${callersOf(count)} of ${check.from} to remove`264+ : `${module}: ${callersOf(count)} of ${check.from} → ${check.to}`;265+266+/**267+ * Splits a migrate ask into its family: a step for each module of its268+ * territory that has callers, in the policy's module order, and a delete269+ * step blocked by all of them, each asked by the parent's asker and held270+ * as the parent is held. `None` when the ask is no migrate ask, or fewer271+ * than two of its modules have callers: a split of one is the ask itself.272+ */273+export const splitFamily = (input: {274+ readonly parent: Ask;275+ readonly counts: CallerCount;276+ readonly modules: readonly Territory[];277+ readonly configDir: string;278+}): Option.Option<MigrateFamily> => {279+ const { counts, parent } = input;280+ const { check } = parent;281+282+ if (!CheckSpec.guards.Migrate(check)) {283+ return Option.none();284+ }285+286+ const fileOf = (id: AskId) =>287+ RepoPath.make(`${input.configDir}/asks/${id}.ask.ts`);288+289+ const step = (290+ id: AskId,291+ own: Pick<Ask, "blockedBy" | "brief" | "check" | "state" | "territory">292+ ): Ask => ({293+ ...parent,294+ ...own,295+ file: fileOf(id),296+ id,297+ parent: parent.id,298+ });299+300+ const children = modulesWithin(parent.territory, input.modules).flatMap(301+ (module) => {302+ const count = counts.byModule[module.module] ?? 0;303+304+ return count > 0305+ ? [306+ step(childId(parent.id, module.module), {307+ blockedBy: [],308+ brief: { want: stepWant(module.module, count, check) },309+ check,310+ state: "open",311+ territory: module,312+ }),313+ ]314+ : [];315+ }316+ );317+318+ const [first, second, ...rest] = children;319+320+ if (first === undefined || second === undefined) {321+ return Option.none();322+ }323+324+ const steps = Array.make(first, second, ...rest);325+ const stepIds = steps.map(({ id }) => id);326+ const deleteId = deleteChildId(parent.id);327+328+ const deleteChild = step(deleteId, {329+ blockedBy: stepIds,330+ brief: { want: `Delete ${check.from}: nothing calls it any more` },331+ check: CheckSpec.cases.SymbolAbsent.make({332+ count: check.count satisfies Command,333+ symbol: check.from,334+ }),335+ state: "waitingOnParent",336+ territory: parent.territory,337+ });338+339+ return Option.some({340+ children: steps,341+ deleteChild,342+ files: Array.append(343+ Array.map(steps, (each) => ({344+ content: stepFile(each, check, parent.id),345+ path: each.file,346+ })),347+ {348+ content: deleteFile(deleteChild, check, parent.id),349+ path: deleteChild.file,350+ }351+ ),352+ parent: {353+ ...parent,354+ blockedBy: Array.dedupe([...parent.blockedBy, ...stepIds, deleteId]),355+ },356+ ratchet: { baseline: counts.total, name: callersRatchet(check.from) },357+ });358+};modified:packages/project/src/project.ts+305 added-35 removed
34 unmodified lines35 import { judgeClosure } from "@repo/checks/judge";36 import { checkVersion, commandFor } from "@repo/checks/kinds";37 import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";38 import type { LintToZeroCheck } from "@repo/checks/kinds/lint-to-zero";39-import { measure } from "@repo/checks/kinds/ratchet";39+import { measure, WHOLE_PROJECT } from "@repo/checks/kinds/ratchet";40 import type { RatchetCount } from "@repo/checks/kinds/ratchet";41 import { redFirstOfRuns } from "@repo/checks/red-first";42 import { weaknessesOf } from "@repo/checks/weak-shapes";43 import {69 unmodified lines113 DecisionId,114 LaneName,115 ProjectName,116 ProposalId,117+ TreeSha,118 } from "@repo/protocol/ids";119 import { Person, Principal } from "@repo/protocol/principal";120 import {121 AskFull,104 unmodified lines226 transition as landingTransition,227 } from "./landing.ts";228 import type { LandingQueue, PendingDecision, Request } from "./landing.ts";229 import {230+ callerCountOf,231+ callersIn,232+ callersRatchet,233+ callersSpecs,234+ familyClosed,235+ remainingBlockers,236+ sameCount,237+ splitFamily,238+} from "./migrate.ts";239+import {240 isDue,241 outboxRow,242 OutboxBody,243 projectedRows,674 unmodified lines918 /** What a check of `ask` runs, and the lane it reports as. */919 const askLaneOf = (policy: Policy, ask: Ask) =>920 commandFor(ask.check, policy.run, policy.ratchets);921 922+/** A check judged by what its command prints: a lint's count, or a migrate's callers. */923+const isCounted = CheckSpec.isAnyOf(["LintToZero", "Migrate", "SymbolAbsent"]);924+925+/** A check that counts a name's callers: a migrate, or its delete step. */926+const countsCallers = CheckSpec.isAnyOf(["Migrate", "SymbolAbsent"]);927+928 /**912- * The lane an ask's check runs as: a `lintToZero` check is a count, so its913- * lane hands back what its lint printed.929+ * The lane an ask's check runs as: a `lintToZero`, `migrate` or930+ * `symbolAbsent` check is a count, so its lane hands back what its command931+ * printed.932 */933 const askCheckLane = (policy: Policy, ask: Ask) =>934 Option.map(askLaneOf(policy, ask), ({ command, lane }) =>917- CheckSpec.guards.LintToZero(ask.check)935+ isCounted(ask.check)936 ? CheckLane.make({ command, lane, output: "stdout" })937 : CheckLane.make({ command, lane })938 );939 1161 unmodified lines2101 ...field(2102 "counts",2103 Option.map(h.policy, ({ modules, ratchets }) => ({2104 modules,2105+ // An open migrate ask's callers are counted on every answer.2087- ratchets,2106+ ratchets: [2107+ ...ratchets,2108+ ...callersSpecs(h.asks.values()).filter(2109+ (spec) =>2110+ !ratchets.some(({ name: named }) => named === spec.name)2111+ ),2112+ ],2113 }))2114 ),2115 ...field(2116 "run",88 unmodified lines2205 }2206 ),2207 });2208 2209+ /** Every ask as this call has it: as written so far, over the hydrated ones. */2210+ const asksNow = (h: Hydrated, writes: Writes): ReadonlyMap<AskId, Ask> =>2211+ new Map([...h.asks, ...writes.asks]);2212+2213 /**2214+ * A migrate family once its step `landed` closed (CAA §2.F): each step2215+ * waiting on its siblings opens when the last of them lands, and the2216+ * parent closes on the landing that closes its last step.2217+ */2218+ const familyAfter = (2219+ h: Hydrated,2220+ writes: Writes,2221+ landed: AskId,2222+ at: { readonly now: DateTime.Utc; readonly sha: LandedSha }2223+ ) => {2224+ const parent = Option.flatMap(askNow(h, writes, landed), (ask) =>2225+ Option.fromUndefinedOr(ask.parent)2226+ );2227+2228+ if (Option.isNone(parent)) {2229+ return;2230+ }2231+2232+ const before = asksNow(h, writes);2233+2234+ for (const step of before.values()) {2235+ if (2236+ step.parent === parent.value &&2237+ step.state === "waitingOnParent" &&2238+ remainingBlockers(step, before).length === 02239+ ) {2240+ const opened: Ask = { ...step, state: "open" };2241+2242+ writes.asks.set(step.id, opened);2243+ writes.events.push(askOpened(opened, at.now));2244+ }2245+ }2246+2247+ const parentOpen = Option.filter(2248+ askNow(h, writes, parent.value),2249+ ({ state }) => state !== "closed"2250+ );2251+2252+ if (2253+ Option.isSome(parentOpen) &&2254+ familyClosed(parent.value, asksNow(h, writes))2255+ ) {2256+ writes.asks.set(parent.value, { ...parentOpen.value, state: "closed" });2257+ writes.events.push(askClosed(parent.value, at.sha, at.now));2258+ }2259+ };2260+2261+ /**2262 * A landing on main recorded: the landing, its ask closed, the answering2186- * claim answered, the landed SHA moved and the policy read there.2263+ * claim answered, its migrate family moved on, the landed SHA moved and2264+ * the policy read there.2265 */2266 const recordLanding = (2267 h: Hydrated,2268 writes: Writes,37 unmodified lines2306 id,2307 { answerer: request.answerer, sha },2308 now2309 );2310+2311+ familyAfter(h, writes, id, { now, sha });2312 }2313 2314 const row = Option.orElse(2315 Option.fromUndefinedOr(writes.project.get("row")),253 unmodified lines2569 );2570 2571 const declared = input.report?.ratchets ?? [];2572 2493- const judgement = judgeRatchets({2494- ask: asked.id,2495- baselines: baselinesNow(h, writes),2496- measured: declared,2497- raises,2498- });2573+ // A tree merged onto a main that has moved on since is not judged:2574+ // its counts still hold what later landings removed (a sibling2575+ // step's callers), which against the baselines those landings2576+ // lowered would read as a raise. It cannot land as it is: its land2577+ // finds main moved, and it is merged and checked again first.2578+ const current = Option.exists(2579+ liveRow(h),2580+ ({ landed }) => landed === checking.main2581+ );2582 2583+ const judgement = current2584+ ? judgeRatchets({2585+ ask: asked.id,2586+ baselines: baselinesNow(h, writes),2587+ measured: declared,2588+ raises,2589+ })2590+ : { decisions: [], refusals: [] };2591+2592 const escapes = Array.dedupe(waivers.map(territoryIn)).map(2593 (territory): MeasuredCount => {2594 const ratchet = escapeRatchet(territory);2595 425 unmodified lines3021 }),3022 (refusals) => Array.findFirst(refusals, isTouchedJudge)3023 );3024 2933- /**2934- * Red first: the ask's check fails twice on the composed commit, the2935- * same way (a `lintToZero` check, by its count). Gives the counts of the2936- * policy's ratchets the check's own run read on the way.2937- */2938- const redTwice = (policy: Policy, ask: Ask, composed: CommitSha) =>3025+ /** An ask's own check run twice on the composed commit, and the lane it ran as. */3026+ const runTwice = (policy: Policy, ask: Ask, composed: CommitSha) =>3027 Effect.gen(function* () {3028 const lane = askCheckLane(policy, ask);3029 3030 if (Option.isNone(lane)) {11 unmodified lines3042 };3043 3044 const runs = [yield* runner.run(job), yield* runner.run(job)] as const;3045 3046+ return { lane: lane.value.lane, runs };3047+ });3048+3049+ /**3050+ * Red first: the ask's check fails twice on the composed commit, the3051+ * same way (a `lintToZero` check, by its count). Gives the counts of the3052+ * policy's ratchets the check's own run read on the way.3053+ */3054+ const redTwice = (policy: Policy, ask: Ask, composed: CommitSha) =>3055+ Effect.gen(function* () {3056+ const { lane, runs } = yield* runTwice(policy, ask, composed);3057+3058 if (CheckSpec.guards.LintToZero(ask.check)) {3059 return yield* redByCount({3060 ask,3061 check: ask.check,2962- lane: lane.value.lane,3062+ lane,3063 policy,3064 runs,3065 });3066 }3067 2968- yield* Effect.fromResult(redFirstOfRuns(runs, lane.value.lane));3068+ yield* Effect.fromResult(redFirstOfRuns(runs, lane));3069 3070 return [];3071 });3072 2973- /** The landing that opens an ask: its files on main, authored by its asker. */3073+ /**3074+ * Red first for a check that counts callers (`migrate`, `symbolAbsent`):3075+ * twice on the composed commit its count command prints the same3076+ * callers, and some in the ask's territory. Gives the count.3077+ */3078+ const callersTwice = (policy: Policy, ask: Ask, composed: CommitSha) =>3079+ Effect.gen(function* () {3080+ const { lane, runs } = yield* runTwice(policy, ask, composed);3081+3082+ const read = (run: CheckRun) =>3083+ Effect.fromOption(3084+ Option.flatMap(outputOf(run, lane), callerCountOf)3085+ ).pipe(Effect.mapError(() => new NotRedFirst({})));3086+3087+ const [first, second] = runs;3088+ const once = yield* read(first);3089+ const again = yield* read(second);3090+3091+ if (3092+ !sameCount(once, again) ||3093+ callersIn(ask.territory, once, policy.modules) === 03094+ ) {3095+ return yield* new NotRedFirst({});3096+ }3097+3098+ return once;3099+ });3100+3101+ /**3102+ * The family files of a split that would land on a path already taken:3103+ * an ask the project holds, one main's config folder states, one of the3104+ * decider's own files, or another file of the family. Overwriting any3105+ * would change the judge beyond the ask's own files (`TouchedJudge`).3106+ */3107+ const takenBy = (3108+ h: Hydrated,3109+ writes: Writes,3110+ input: {3111+ readonly added: readonly ComposedFile[];3112+ readonly files: readonly AskFile[];3113+ readonly policy: Policy;3114+ }3115+ ) => {3116+ const held = new Set<string>([3117+ ...[...h.asks.values(), ...writes.asks.values()].map(3118+ ({ file }) => file3119+ ),3120+ ...input.policy.asks.map(({ file }) => file),3121+ ...input.files.map(({ path }) => path),3122+ ]);3123+3124+ return input.added.flatMap(({ path }, at) =>3125+ held.has(path) ||3126+ input.added.findIndex((other) => other.path === path) !== at3127+ ? [path]3128+ : []3129+ );3130+ };3131+3132+ /**3133+ * What a migrate (or `symbolAbsent`) ask's opening lands: red first by3134+ * its callers, then, when its callers sit in two or more of its3135+ * modules, its family's files beside the decider's (CAA §2.F), every3136+ * ask of the family, and the callers ratchet at the counted total.3137+ */3138+ const migrateOpening = (input: {3139+ readonly ask: Ask;3140+ readonly composed: { readonly commit: CommitSha; readonly tree: TreeSha };3141+ readonly files: Array.NonEmptyReadonlyArray<AskFile>;3142+ readonly h: Hydrated;3143+ readonly main: LandedSha;3144+ readonly policy: Policy;3145+ readonly writes: Writes;3146+ }) =>3147+ Effect.gen(function* () {3148+ const { ask, composed, files, policy } = input;3149+ const counts = yield* callersTwice(policy, ask, composed.commit);3150+3151+ const counted: readonly RatchetCount[] = CheckSpec.guards.Migrate(3152+ ask.check3153+ )3154+ ? [3155+ {3156+ count: counts.total,3157+ ratchet: callersRatchet(ask.check.from),3158+ territory: WHOLE_PROJECT,3159+ },3160+ ]3161+ : [];3162+3163+ const family = splitFamily({3164+ configDir: Brand.configDir,3165+ counts,3166+ modules: policy.modules,3167+ parent: ask,3168+ });3169+3170+ if (Option.isNone(family)) {3171+ return {3172+ asks: Array.make(ask),3173+ counted,3174+ files,3175+ steps: [],3176+ tree: composed.tree,3177+ };3178+ }3179+3180+ const { children, deleteChild, parent } = family.value;3181+ const added = family.value.files;3182+ const taken = takenBy(input.h, input.writes, { added, files, policy });3183+3184+ if (Array.isReadonlyArrayNonEmpty(taken)) {3185+ return yield* new TouchedJudge({ paths: taken });3186+ }3187+3188+ const all = Array.appendAll(files, added);3189+3190+ const { tree } = yield* lander.compose({3191+ files: all,3192+ main: input.main,3193+ repo,3194+ });3195+3196+ return {3197+ asks: Array.make(parent, ...children, deleteChild),3198+ counted,3199+ files: all,3200+ steps: [...children, deleteChild].map(({ id }) => id),3201+ tree,3202+ };3203+ });3204+3205+ /**3206+ * The landing that opens an ask: its files on main, authored by its3207+ * asker. A migrate ask's landing names the steps it opened with it.3208+ */3209 const landAsk = (input: {3210 readonly ask: Ask;3211 readonly credits: readonly Credit[];3212 readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;3213 readonly main: LandedSha;3214+ readonly steps: readonly AskId[];3215 readonly tree: Checking["tree"];3216 }) => {3217 const requestId = RequestId.make(`open-${input.tree}`);2982- const { credits } = input;3218+ const { credits, steps } = input;3219 3220 const landing = lander3221 .land({3222 author: input.ask.askedBy,3223 main: input.main,3224 message: formatLanding({3225 ask: { ask: input.ask.id, project: name },3226 assisted: [],3227+ body:3228+ steps.length === 03229+ ? input.ask.brief.want3230+ : [2991- body: input.ask.brief.want,3231+ input.ask.brief.want,3232+ "",3233+ "Its steps, the last waiting on the rest:",3234+ ...steps.map((step) => `- ${step}`),3235+ ].join("\n"),3236 credits,3237 requestId,3238 subject: `Open ask ${input.ask.id}`,3239 }),102 unmodified lines3342 if (Option.isSome(weak)) {3343 return yield* new WeakCheck({ weakness: weak.value });3344 }3345 3102- const counted = yield* redTwice(policy, ask, composed.commit);3346+ const opens = countsCallers(ask.check)3347+ ? yield* migrateOpening({3348+ ask,3349+ composed,3350+ files,3351+ h,3352+ main,3353+ policy,3354+ writes,3355+ })3356+ : {3357+ asks: Array.make(ask),3358+ counted: yield* redTwice(policy, ask, composed.commit),3359+ files,3360+ steps: [],3361+ tree: composed.tree,3362+ };3363 3364 const landed = yield* landAsk({3365 ask,3366 credits: opening.credits,3107- files,3367+ files: opens.files,3368 main,3369+ steps: opens.steps,3109- tree: composed.tree,3370+ tree: opens.tree,3371 });3372 3112- const opened: Ask = { ...ask, openedIn: landed.sha };3373+ const opened = Array.map(opens.asks, (each): Ask => ({3374+ ...each,3375+ openedIn: landed.sha,3376+ }));3377 3114- writes.asks.set(opened.id, opened);3115- writes.events.push(askOpened(opened, now));3378+ for (const each of opened) {3379+ writes.asks.set(each.id, each);3380+3381+ // A step that waits on others opens when they land.3382+ if (each.state === "open") {3383+ writes.events.push(askOpened(each, now));3384+ }3385+ }3386+3387 writes.landings.push({3388 assisted: [],3389 author: opening.asker,3390 credits: landed.credits,7 unmodified lines3398 "row",3399 yield* withPolicyAt({ ...row, landed: landed.sha }, landed.sha, now)3400 );3401 3131- // The opening landing records the baselines its check's lint read.3402+ // The opening landing records the baselines its check's count read.3403 putRatchets(3404 h,3405 writes,3135- afterLanding(baselinesNow(h, writes), counted, landed.sha).baselines3406+ afterLanding(baselinesNow(h, writes), opens.counted, landed.sha)3407+ .baselines3408 );3409 3138- return { ask: opened, landed: landed.sha };3410+ return { ask: Array.headNonEmpty(opened), landed: landed.sha };3411 });3412 3413 const openBody =3414 (79 unmodified lines3494 const trust = trustOf(h, policy, ask.value, { caller, now });3495 3496 const command = ClaimCommand.cases.Claim.make({3497 base: live.value.landed,3226- blockedBy: ask.value.blockedBy.filter(3227- (blocker) => h.asks.get(blocker)?.state !== "closed"3228- ),3498+ blockedBy: remainingBlockers(ask.value, h.asks),3499 cap: policy.caps.claimsPerPerson,3500 denounced: trust.denounced,3501 heldByWho: heldBy(h, caller.handle, id),3502 liveCount: h.claims.filter(760 unmodified linesadded:packages/project/test/migrate.test.ts+1528 added
1+/**2+ * The migrate split family (CAA §2.F): one migrate ask over six packages3+ * opens as six steps, one per package, and a delete step that waits on4+ * them; six people claim the six at once, the steps land one by one through5+ * the serial queue, and the delete step's landing closes the parent.6+ *7+ * The world is `world.ts`'s over memory adapters, with three stand-ins for8+ * what the platform runs elsewhere:9+ * - a Checker that runs the project's caller count on the tree it is given10+ * (it reads the files, as `node scripts/count-callers.mjs` would), passes11+ * every other lane, and fails an ask's own test only on main;12+ * - a Lander that remembers what each merge came to, so that Checker can13+ * read a merged tree, which the isomorphic-git Lander keeps in a scratch;14+ * - answer runs that count the ratchets on the merged tree before they15+ * report its check, as the platform's Answer Workflow does in its cheap16+ * stage (the inline runs count none).17+ */18+import { NodeServices } from "@effect/platform-node";19+import { describe, expect, it, layer } from "@effect/vitest";20+import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";21+import type { ObjectId } from "@repo/artifacts/repo-host";22+import { Brand } from "@repo/brand";23+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";24+import type { CheckJob, CheckLane, CheckRun } from "@repo/checks/check-runner";25+import { measure } from "@repo/checks/kinds/ratchet";26+import { authorLine, parseTrailers } from "@repo/git/trailers";27+import type { LaneResult } from "@repo/protocol/domain/answer";28+import type { Ask } from "@repo/protocol/domain/ask";29+import { CheckSpec } from "@repo/protocol/domain/check";30+import { Command, Glob, SymbolName } from "@repo/protocol/domain/common";31+import type { ProjectEvent } from "@repo/protocol/domain/event";32+import { Outcome } from "@repo/protocol/domain/outcome";33+import {34+ AskId,35+ Handle,36+ KindName,37+ LandedSha,38+ LaneName,39+ RepoName,40+ RepoPath,41+ RequestId,42+} from "@repo/protocol/ids";43+import type { CommitSha } from "@repo/protocol/ids";44+import { Anonymous, Person } from "@repo/protocol/principal";45+import { AskBlocked, NotRedFirst, Weakened } from "@repo/protocol/refusal";46+import {47+ EvaluationFacts,48+ RulesEvaluator,49+ sdkVersion,50+} from "@repo/rules/rules-evaluator";51+import { RulesEvaluatorBun } from "@repo/rules/rules-evaluator/bun";52+import { advanceTo } from "@repo/testkit/clock";53+import type { Files } from "@repo/testkit/git-client";54+import { sixChildren, withAsk, withVouches } from "@repo/testkit/scenarios";55+import {56+ Array,57+ Context,58+ Effect,59+ Exit,60+ Layer,61+ Option,62+ Ref,63+ Result,64+ Schema,65+ Struct,66+} from "effect";67+68+import { AnswerRuns } from "../src/answer-runs.ts";69+import type { AnswerQueue, AnswerRun } from "../src/answer-runs.ts";70+import { drive } from "../src/answer-runs/steps.ts";71+import { Lander } from "../src/lander.ts";72+import { LandingCommand } from "../src/landing.ts";73+import type { Change } from "../src/landing.ts";74+import {75+ childId,76+ deleteChildId,77+ familyClosed,78+ remainingBlockers,79+ splitFamily,80+} from "../src/migrate.ts";81+import type { MigrateFamily, CallerCount } from "../src/migrate.ts";82+import { ProjectStore } from "../src/project-store.ts";83+import type { ProjectApi } from "../src/project.ts";84+import { FinishersFromChecks, projectService } from "../src/project.ts";85+import { Pusher, worldOf } from "./world.ts";86+87+// ------------------------------------------------------------- the project88+89+const symbol = "legacyFetch";90+91+const countOf = (name: string) =>92+ Command.make(`node scripts/count-callers.mjs ${name} --json`);93+94+const packages = ["p1", "p2", "p3", "p4", "p5", "p6"] as const;95+96+type Package = (typeof packages)[number];97+98+/** How many calls of `legacyFetch` each package makes on main: 37 in all. */99+const callers = { p1: 5, p2: 7, p3: 6, p4: 8, p5: 4, p6: 7 } as const;100+101+const total = 37;102+103+const answerers = ["bob", "carol", "dave", "eve", "frank", "grace"] as const;104+105+/** heidi answers the delete step; ivan the plain ask beside the family. */106+const others = ["heidi", "ivan"] as const;107+108+const family = sixChildren({ symbol, to: "http.get" });109+110+/**111+ * `burrow` as `sixChildren()` makes it, its six packages its modules, with112+ * everyone vouched for and three more asks: a plain one in `p6`, a migrate113+ * ask over one package, and a migrate ask for a name nobody calls.114+ */115+const scenario = family.pipe(116+ withVouches([...answerers, ...others]),117+ withAsk({ id: "tidy-p6", territory: "packages/p6" }),118+ withAsk({119+ check: CheckSpec.cases.Migrate.make({120+ count: countOf(symbol),121+ from: SymbolName.make(symbol),122+ to: SymbolName.make("http.get"),123+ }),124+ id: "move-p2-fetch",125+ kind: "migrate",126+ territory: "packages/p2",127+ }),128+ withAsk({129+ check: CheckSpec.cases.Migrate.make({130+ count: countOf("oldThing"),131+ from: SymbolName.make("oldThing"),132+ }),133+ id: "drop-old-thing",134+ kind: "migrate",135+ territory: ".",136+ })137+);138+139+const { project } = scenario;140+141+const repo = RepoName.make(project);142+143+const mainRef = RefName.make("refs/heads/main");144+145+const parentId = AskId.make("drop-legacy-fetch");146+147+const stepIdOf = (name: Package) => AskId.make(`${parentId}-${name}`);148+149+const childIds = Array.map(packages, stepIdOf);150+151+const deleteId = AskId.make(`${parentId}-delete`);152+153+const tidyId = AskId.make("tidy-p6");154+155+const ratchetName = "callers-legacyfetch";156+157+const person = (handle: string) => Person.make({ handle: Handle.make(handle) });158+159+const alice = person("alice");160+161+const anyone = Anonymous.make({});162+163+const askOf = (id: string) =>164+ Option.getOrThrow(165+ Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)166+ );167+168+/** `count` calls of `name`, one a line. */169+const calls = (name: string, count: number) =>170+ Array.makeBy(count, (n) => ` ${name}("/item/${n}");\n`).join("");171+172+const indexOf = (name: string) => `packages/${name}/src/index.ts`;173+174+const extraOf = (name: string) => `packages/${name}/src/extra.ts`;175+176+const legacyFile = "packages/p1/src/legacy.ts";177+178+/** The project as alice first pushes it: six packages calling `legacyFetch`. */179+const start: Files = [180+ ["package.json", '{ "name": "burrow", "workspaces": ["packages/*"] }\n'],181+ ["scripts/count-callers.mjs", "// prints {total, byModule} for a name\n"],182+ [legacyFile, "export const legacyFetch = (url) => fetch(url);\n"],183+ ...packages.map((name): readonly [string, string] => [184+ indexOf(name),185+ `export const run = () => {\n${calls(symbol, callers[name])}};\n`,186+ ]),187+];188+189+/** `files` with `path` holding `content`, added or replaced; with no `content`, deleted. */190+const changed = (files: Files, path: string, content?: string): Files => [191+ ...files.filter(([each]) => each !== path),192+ ...(content === undefined ? [] : [[path, content] as const]),193+];194+195+/** An ask's file in the config folder: what alice sends to open it. */196+const askFile = (id: string) => {197+ const { file } = askOf(id);198+199+ return { content: `export default "${id}";\n`, path: file };200+};201+202+/** A plain ask's files: its ask file, and a check file with an assertion. */203+const plainFiles = (id: string) => {204+ const { check } = askOf(id);205+206+ return Array.make(askFile(id), {207+ content: [208+ `import { expect, it } from "vitest";`,209+ `import { run } from "../src/index.ts";`,210+ ``,211+ `it("${id}", () => {`,212+ ` expect(run()).toStrictEqual(undefined);`,213+ `});`,214+ ``,215+ ].join("\n"),216+ path: CheckSpec.guards.RedThenGreen(check)217+ ? check.path218+ : RepoPath.make(`test/${id}.test.ts`),219+ });220+};221+222+// ---------------------------------------------------------- the stand-ins223+224+/** What one merge came to: the answer's head, onto which main, and the paths it changed. */225+interface Merged {226+ readonly changes: readonly Change[];227+ readonly fork: RepoName;228+ readonly head: CommitSha;229+ readonly main: LandedSha;230+}231+232+/** The name a caller count counts: `node scripts/count-callers.mjs <name> --json`. */233+const countedName = (command: string) => command.split(" ")[2] ?? "";234+235+const occurrences = (text: string, name: string) =>236+ text.split(`${name}(`).length - 1;237+238+/** How the Checker behaves, beyond counting callers on the tree it is given. */239+interface CheckerOptions {240+ /** Each count prints one more caller in `p1` than the count before it. */241+ readonly drifting?: boolean;242+}243+244+/** The ratchets a run counts on `tree`, as the platform's cheap stage reads them. */245+const ratchetsOn = (run: AnswerRun, tree: CheckAt) =>246+ Effect.gen(function* () {247+ const runner = yield* CheckRunner;248+ const specs = run.counts?.ratchets ?? [];249+ const block = Option.fromUndefinedOr(run.run);250+251+ if (specs.length === 0 || Option.isNone(block)) {252+ return [];253+ }254+255+ const lanes = specs.map(({ measure: { command }, name }): CheckLane => ({256+ command,257+ lane: LaneName.make(name),258+ output: "stdout",259+ }));260+261+ const ran = yield* runner262+ .run({263+ at: tree,264+ lanes,265+ placeholders: [],266+ project,267+ proxies: [],268+ repo,269+ run: block.value,270+ })271+ .pipe(Effect.orDie);272+273+ const printed = (command: string) =>274+ ran.outputs?.find(275+ ({ lane }) =>276+ lanes.find((each) => each.lane === lane)?.command === command277+ )?.stdout ?? "";278+279+ const counts = yield* Effect.forEach(specs, (spec) =>280+ measure(281+ spec,282+ (command) => Effect.succeed({ code: 0, stdout: printed(command) }),283+ run.counts?.modules ?? []284+ )285+ ).pipe(Effect.orDie);286+287+ return counts.flat();288+ });289+290+/**291+ * The stand-ins, over the world's own Lander and repos: a Lander that292+ * remembers its merges, a Checker that counts callers on the tree it is293+ * given, and answer runs that count ratchets before they report a check.294+ */295+const standIns = (options: CheckerOptions) =>296+ Layer.effectContext(297+ Effect.gen(function* () {298+ const host = yield* RepoHost;299+ const inner = yield* Lander;300+ const merges = new Map<string, Merged>();301+ const counted = yield* Ref.make(0);302+ const running = yield* Ref.make<ReadonlySet<RequestId>>(new Set());303+304+ const lander = Lander.of({305+ ...inner,306+ merge: (job) =>307+ Effect.tap(inner.merge(job), ({ changes, tree }) =>308+ Effect.sync(() =>309+ merges.set(tree, {310+ changes,311+ fork: job.fork,312+ head: job.head,313+ main: job.main,314+ })315+ )316+ ),317+ });318+319+ const read = (from: RepoName, sha: CommitSha, path: string) =>320+ host.readFile(from, Revision.Commit({ sha }), RepoPath.make(path)).pipe(321+ Effect.orDie,322+ Effect.map((bytes) =>323+ Option.match(bytes, {324+ onNone: () => "",325+ onSome: (found) => new TextDecoder().decode(found),326+ })327+ )328+ );329+330+ /** A file's text in the tree a job runs on: a commit of the repo, or a merge. */331+ const textAt = (at: CheckAt, path: string) =>332+ CheckAt.match(at, {333+ Commit: ({ commit }) => read(repo, commit, path),334+ Tree: ({ tree }) => {335+ const merged = merges.get(tree);336+337+ if (merged === undefined) {338+ return Effect.die(`no merge made the tree ${tree}`);339+ }340+341+ const change = merged.changes.find((each) => each.path === path);342+343+ if (change === undefined) {344+ return read(repo, merged.main, path);345+ }346+347+ return change.status === "deleted"348+ ? Effect.succeed("")349+ : read(merged.fork, merged.head, path);350+ },351+ });352+353+ /** What the caller count prints for `name` on the tree a job runs on. */354+ const countAt = (at: CheckAt, name: string) =>355+ Effect.gen(function* () {356+ const found = yield* Effect.forEach(packages, (each) =>357+ Effect.gen(function* () {358+ const index = yield* textAt(at, indexOf(each));359+ const extra = yield* textAt(at, extraOf(each));360+361+ return [362+ each,363+ occurrences(index, name) + occurrences(extra, name),364+ ] as const;365+ })366+ );367+368+ const skew =369+ options.drifting === true370+ ? yield* Ref.getAndUpdate(counted, (n) => n + 1)371+ : 0;372+373+ const byModule = Object.fromEntries(374+ found.map(([each, count]) => [375+ each,376+ each === "p1" ? count + skew : count,377+ ])378+ );379+380+ return JSON.stringify({381+ byModule,382+ total: Object.values(byModule).reduce((sum, n) => sum + n, 0),383+ });384+ });385+386+ const laneRun = (job: CheckJob, lane: CheckLane) =>387+ Effect.gen(function* () {388+ // An ask's own test fails on main by an assertion, and passes on an answer.389+ const fails =390+ CheckAt.guards.Commit(job.at) && lane.lane === "redThenGreen";391+392+ const result: LaneResult = {393+ command: lane.command,394+ durationMs: 1,395+ lane: lane.lane,396+ result: fails ? "failed" : "passed",397+ };398+399+ const output =400+ lane.output === "stdout"401+ ? Option.some({402+ lane: lane.lane,403+ stdout: yield* countAt(job.at, countedName(lane.command)),404+ })405+ : Option.none();406+407+ return { output, result };408+ });409+410+ const runner = CheckRunner.of({411+ run: (job) =>412+ Effect.gen(function* () {413+ const lanes = yield* Effect.forEach(job.lanes, (lane) =>414+ laneRun(job, lane)415+ );416+417+ const outputs = Array.getSomes(lanes.map(({ output }) => output));418+419+ const ran: CheckRun = {420+ durationMs: lanes.length,421+ evidence: lanes422+ .filter(({ result }) => result.result === "failed")423+ .map(({ result }) => ({424+ lane: result.lane,425+ signature: `${result.lane}: expected undefined`,426+ })),427+ heldBack: [],428+ lanes: lanes.map(({ result }) => result),429+ };430+431+ return Array.isReadonlyArrayEmpty(outputs)432+ ? ran433+ : { ...ran, outputs };434+ }),435+ });436+437+ const ports = Context.make(CheckRunner, runner).pipe(438+ Context.add(Lander, lander)439+ );440+441+ /** The project's queue, with the ratchets counted on a tree before its check is reported. */442+ const counting = (queue: AnswerQueue): AnswerQueue => ({443+ advanceAnswer: (requestId, command, report) =>444+ LandingCommand.$is("Checked")(command)445+ ? Effect.gen(function* () {446+ const run = yield* queue.answer(requestId);447+448+ const ratchets = yield* Option.match(run, {449+ onNone: () => Effect.succeed([]),450+ onSome: (found) =>451+ ratchetsOn(452+ found,453+ CheckAt.cases.Tree.make({ tree: command.tree })454+ ).pipe(Effect.provideContext(ports)),455+ });456+457+ return yield* queue.advanceAnswer(requestId, command, {458+ ...report,459+ ratchets,460+ });461+ })462+ : queue.advanceAnswer(requestId, command, report),463+ answer: queue.answer,464+ });465+466+ const leave = (requestId: RequestId) =>467+ Ref.update(468+ running,469+ (under) => new Set([...under].filter((each) => each !== requestId))470+ );471+472+ const runs = AnswerRuns.of({473+ // A run already under way for the request is not started twice.474+ start: (requestId, queue) =>475+ Effect.gen(function* () {476+ const free = yield* Ref.modify(running, (under) =>477+ under.has(requestId)478+ ? [false, under]479+ : [true, new Set(under).add(requestId)]480+ );481+482+ if (free) {483+ yield* drive(counting(queue), requestId).pipe(484+ Effect.provideContext(ports),485+ Effect.ensuring(leave(requestId))486+ );487+ }488+ }),489+ });490+491+ return ports.pipe(Context.add(AnswerRuns, runs));492+ })493+ );494+495+const worldWith = (options: CheckerOptions = {}) =>496+ standIns(options).pipe(Layer.provideMerge(worldOf(scenario, "memory")));497+498+// --------------------------------------------------------------- reading499+500+/** Where canonical `main` stands now. */501+const mainTip = Effect.gen(function* () {502+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);503+504+ return LandedSha.make(505+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))506+ );507+});508+509+const commitOf = (sha: CommitSha) =>510+ Effect.gen(function* () {511+ const host = yield* RepoHost;512+ const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);513+ const { author, message, parents } = Option.getOrThrow(read);514+515+ return { author, parents, trailers: parseTrailers(message) };516+ });517+518+/** Whether a commit of the canonical repo holds a file at `path`. */519+const holds = (sha: CommitSha, path: string) =>520+ RepoHost.use((host) =>521+ host.readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))522+ ).pipe(Effect.orDie, Effect.map(Option.isSome));523+524+/** Every file of a commit of the canonical repo, as the Pusher takes them. */525+const filesAt = (sha: CommitSha) =>526+ Effect.gen(function* () {527+ const host = yield* RepoHost;528+529+ const under = (tree: ObjectId, prefix: string): Effect.Effect<Files> =>530+ Effect.gen(function* () {531+ const entries = yield* host.readTree(repo, tree).pipe(Effect.orDie);532+533+ const nested = yield* Effect.forEach(534+ Option.getOrElse(entries, () => []),535+ ({ name, sha: id, type }) =>536+ type === "tree"537+ ? under(id, `${prefix}${name}/`)538+ : Effect.map(539+ host.readBlob(repo, id).pipe(Effect.orDie),540+ (bytes): Files => [541+ [542+ `${prefix}${name}`,543+ new TextDecoder().decode(544+ Option.getOrElse(bytes, () => new Uint8Array())545+ ),546+ ],547+ ]548+ )549+ );550+551+ return nested.flat();552+ });553+554+ const commit = yield* host.readCommit(repo, sha).pipe(Effect.orDie);555+556+ return yield* under(Option.getOrThrow(commit).tree, "");557+ });558+559+const ratchetRows = ProjectStore.use((store) => store.load()).pipe(560+ Effect.map(({ ratchets }) =>561+ ratchets.map(({ count, ratchet, territory }) => ({562+ count,563+ ratchet,564+ territory,565+ }))566+ )567+);568+569+const landingCount = ProjectStore.use((store) => store.load()).pipe(570+ Effect.map(({ landings }) => landings.length)571+);572+573+/** The open asks, by id, as anyone lists them. */574+const listed = (api: ProjectApi) =>575+ Effect.map(api.listAsks(anyone), ({ asks }) =>576+ asks.map(({ ask }) => ask).toSorted()577+ );578+579+const shown = (api: ProjectApi, id: AskId) =>580+ Effect.map(api.showAsk(anyone, id), ({ ask }) => ask);581+582+/** The project made from alice's first push; alice decides everything. */583+const fromFirstPush = (api: ProjectApi) =>584+ Effect.gen(function* () {585+ yield* api.initProject(alice, {});586+587+ const first = yield* Pusher.use((pusher) =>588+ pusher.push(repo, Option.none(), start, "Start")589+ );590+591+ yield* api.recordFirstPush(alice, first);592+ });593+594+/** `who` answers `ask` from their fork, with `change` made to the files at `base`. */595+const answer = (596+ api: ProjectApi,597+ input: {598+ readonly ask: AskId;599+ readonly base: LandedSha;600+ readonly change: (files: Files) => Files;601+ readonly who: Person;602+ }603+) =>604+ Effect.gen(function* () {605+ const fork = RepoName.make(`${project}--${input.ask}--${input.who.handle}`);606+ const files = yield* filesAt(input.base);607+608+ const head = yield* Pusher.use((pusher) =>609+ pusher.push(fork, Option.some(input.base), input.change(files))610+ );611+612+ return yield* api.submitAnswer(input.who, {613+ ask: input.ask,614+ base: input.base,615+ head,616+ requestId: RequestId.make(`req-${input.ask}`),617+ });618+ });619+620+/** Every call of `legacyFetch` in one package moved to `http.get`. */621+const migrated = (name: Package) => (files: Files) =>622+ changed(623+ files,624+ indexOf(name),625+ `export const run = () => {\n${calls("http.get", callers[name])}};\n`626+ );627+628+const outcomesOf = (api: ProjectApi, who: string) =>629+ Effect.map(api.status(person(who)), ({ answers }) =>630+ answers.map(({ outcome }) => outcome)631+ );632+633+// ------------------------------------------------------------- the story634+635+/**636+ * The whole family: alice opens a plain ask and the migrate ask, six637+ * people claim the six steps at once and land them one by one, a plain638+ * answer that adds a caller is refused on the way, and the delete step639+ * lands last.640+ */641+const story = Effect.gen(function* () {642+ yield* advanceTo("2026-10-07T12:00:00Z");643+644+ const api = yield* projectService(project);645+ const host = yield* RepoHost;646+647+ yield* fromFirstPush(api);648+649+ // A plain ask in p6, opened before the family: ivan answers it mid-family.650+ yield* api.openAsk(alice, { ask: tidyId, files: plainFiles(tidyId) });651+652+ const parentFiles = Array.make(askFile(parentId));653+ const beforeFamily = yield* mainTip;654+655+ const opened = yield* api.openAsk(alice, {656+ ask: parentId,657+ files: parentFiles,658+ });659+660+ const atOpen = {661+ commit: yield* commitOf(opened.landed),662+ deleteChild: yield* shown(api, deleteId),663+ files: yield* Effect.forEach([parentId, ...childIds, deleteId], (id) =>664+ holds(opened.landed, `${Brand.configDir}/asks/${id}.ask.ts`)665+ ),666+ listed: yield* listed(api),667+ ratchets: yield* ratchetRows,668+ steps: yield* Effect.forEach(childIds, (id) => shown(api, id)),669+ };670+671+ const landingsBefore = yield* landingCount;672+673+ const replay = yield* api.openAsk(alice, {674+ ask: parentId,675+ files: parentFiles,676+ });677+678+ const afterReplay = {679+ landings: (yield* landingCount) - landingsBefore,680+ listed: yield* listed(api),681+ main: yield* mainTip,682+ ratchets: yield* ratchetRows,683+ };684+685+ const refusedEarly = {686+ deleteChild: yield* api.claim(person("heidi"), deleteId).pipe(Effect.flip),687+ parent: yield* api.claim(person("heidi"), parentId).pipe(Effect.flip),688+ };689+690+ // Six people claim the six steps at once.691+ const claims = yield* Effect.forEach(692+ Array.zip(answerers, childIds),693+ ([who, id]) => api.claim(person(who), id),694+ { concurrency: "unbounded" }695+ );696+697+ const forks = yield* Effect.forEach(claims, ({ claim }) =>698+ Effect.map(Effect.exit(host.refs(claim.fork)), Exit.isSuccess)699+ );700+701+ const tidyClaim = yield* api.claim(person("ivan"), tidyId);702+703+ /** Step `n`'s claimant answers it from where they claimed, and it lands. */704+ const landStep = (n: number) =>705+ Effect.gen(function* () {706+ const name = packages[n] ?? "p1";707+708+ yield* answer(api, {709+ ask: stepIdOf(name),710+ base: opened.landed,711+ change: migrated(name),712+ who: person(answerers[n] ?? "bob"),713+ });714+715+ return yield* mainTip;716+ });717+718+ const firstThree = yield* Effect.forEach([0, 1, 2], landStep);719+720+ const midFamily = {721+ deleteClaim: yield* api.claim(person("heidi"), deleteId).pipe(Effect.flip),722+ main: yield* mainTip,723+ ratchets: yield* ratchetRows,724+ };725+726+ // ivan's answer to the plain ask adds one more caller in p6.727+ yield* answer(api, {728+ ask: tidyId,729+ base: LandedSha.make(tidyClaim.claim.base),730+ change: (files) =>731+ changed(732+ files,733+ extraOf("p6"),734+ `export const extra = () => {\n${calls(symbol, 1)}};\n`735+ ),736+ who: person("ivan"),737+ });738+739+ const tidyAfter = {740+ main: yield* mainTip,741+ outcomes: yield* outcomesOf(api, "ivan"),742+ };743+744+ const lastThree = yield* Effect.forEach([3, 4, 5], landStep);745+746+ const afterSix = {747+ deleteChild: yield* shown(api, deleteId),748+ parent: yield* shown(api, parentId),749+ };750+751+ const deleteClaim = yield* api.claim(person("heidi"), deleteId);752+753+ yield* answer(api, {754+ ask: deleteId,755+ base: LandedSha.make(deleteClaim.claim.base),756+ change: (files) => changed(files, legacyFile),757+ who: person("heidi"),758+ });759+760+ const deleteLanded = yield* mainTip;761+ const stepsLanded = [...firstThree, ...lastThree];762+763+ return {764+ afterReplay,765+ afterSix,766+ atOpen,767+ beforeFamily,768+ claims,769+ deleteLanded,770+ events: (yield* api.events(0, 1000)).map(({ event }) => event),771+ forks,772+ landings: yield* Effect.forEach([...stepsLanded, deleteLanded], commitOf),773+ listedAtEnd: yield* listed(api),774+ midFamily,775+ opened,776+ outcomes: yield* Effect.forEach([...answerers, "heidi"], (who) =>777+ outcomesOf(api, who)778+ ),779+ parentAtEnd: yield* shown(api, parentId),780+ ratchetsAtEnd: yield* ratchetRows,781+ refusedEarly,782+ replay,783+ stepsLanded,784+ tidyAfter,785+ };786+});787+788+/** What the story saw, told once and read by every case below. */789+class Seen extends Context.Service<Seen, Effect.Success<typeof story>>()(790+ "test/Seen"791+) {}792+793+/**794+ * The story runs a family of eight asks over real git objects: about three795+ * seconds alone, more while turbo runs every package's tests at once. The796+ * limit catches a hang, not a busy machine.797+ */798+const wholeStory = { timeout: 60_000 };799+800+const seen = Seen.useSync((told) => told);801+802+/** The story's events of one kind. */803+const eventsOf = <T extends ProjectEvent["_tag"]>(804+ events: readonly ProjectEvent[],805+ tag: T806+) =>807+ events.filter(808+ (event): event is Extract<ProjectEvent, { readonly _tag: T }> =>809+ event._tag === tag810+ );811+812+const askedByAlice = {813+ key: "Asked-by",814+ value: `alice <alice@users.${Brand.domain}>`,815+};816+817+layer(Layer.effect(Seen, story).pipe(Layer.provide(worldWith())), wholeStory)(818+ "a migrate ask over six packages",819+ (cases) => {820+ cases.effect(821+ "1. opens as one platform commit adding the parent, the six steps and the delete step",822+ () =>823+ Effect.map(seen, ({ atOpen, beforeFamily, opened }) => {824+ expect({825+ author: atOpen.commit.author,826+ files: atOpen.files,827+ opened: opened.ask.id,828+ parents: atOpen.commit.parents,829+ }).toStrictEqual({830+ author: authorLine(alice.handle),831+ files: Array.makeBy(8, () => true),832+ opened: parentId,833+ parents: [beforeFamily],834+ });835+ expect(atOpen.listed).toStrictEqual(836+ [tidyId, parentId, ...childIds, deleteId].toSorted()837+ );838+ })839+ );840+841+ cases.effect("1. gives each step its own package as its territory", () =>842+ Effect.map(seen, ({ atOpen }) => {843+ expect(844+ atOpen.steps.map(({ brief, check, parent, territory }) => ({845+ check: check._tag,846+ parent,847+ territory: territory.paths,848+ want: brief.want,849+ }))850+ ).toStrictEqual(851+ packages.map((name) => ({852+ check: "Migrate",853+ parent: parentId,854+ territory: [Glob.make(`packages/${name}/**`)],855+ want: `${name}: ${callers[name]} callers of legacyFetch → http.get`,856+ }))857+ );858+ })859+ );860+861+ cases.effect(862+ "1. blocks the delete step on the six, and the parent on all seven",863+ () =>864+ Effect.map(seen, ({ atOpen, opened }) => {865+ expect({866+ blockedBy: atOpen.deleteChild.blockedBy,867+ check: atOpen.deleteChild.check,868+ parent: atOpen.deleteChild.parent,869+ state: atOpen.deleteChild.state,870+ }).toStrictEqual({871+ blockedBy: childIds,872+ check: CheckSpec.cases.SymbolAbsent.make({873+ count: countOf(symbol),874+ symbol: SymbolName.make(symbol),875+ }),876+ parent: parentId,877+ state: "waitingOnParent",878+ });879+ expect(opened.ask.blockedBy).toStrictEqual([...childIds, deleteId]);880+ })881+ );882+883+ cases.effect("1. records the callers ratchet at the counted total", () =>884+ Effect.map(seen, ({ atOpen }) => {885+ expect(atOpen.ratchets).toStrictEqual([886+ { count: total, ratchet: ratchetName, territory: "." },887+ ]);888+ })889+ );890+891+ cases.effect("opening it again converges on the same family", () =>892+ Effect.map(seen, ({ afterReplay, atOpen, opened, replay }) => {893+ expect(replay).toStrictEqual(opened);894+ expect(afterReplay).toStrictEqual({895+ landings: 0,896+ listed: atOpen.listed,897+ main: opened.landed,898+ ratchets: atOpen.ratchets,899+ });900+ })901+ );902+903+ cases.effect(904+ "2. refuses a claim on the delete step, or on the parent, as blocked",905+ () =>906+ Effect.map(seen, ({ refusedEarly }) => {907+ expect(refusedEarly).toStrictEqual({908+ deleteChild: AskBlocked.of(deleteId, childIds),909+ parent: AskBlocked.of(parentId, Array.append(childIds, deleteId)),910+ });911+ })912+ );913+914+ cases.effect(915+ "3. lets six people claim the six steps at once, each in a fork",916+ () =>917+ Effect.map(seen, ({ claims, forks }) => {918+ expect(919+ claims.map(({ claim }) => [claim.ask, claim.claimant])920+ ).toStrictEqual(Array.zip(childIds, answerers));921+ expect(forks).toStrictEqual(Array.makeBy(6, () => true));922+ })923+ );924+925+ cases.effect(926+ "4. lands the six answers in turn, none stale, each authored by its claimant and asked by alice",927+ () =>928+ Effect.map(seen, ({ landings, outcomes, stepsLanded }) => {929+ expect(outcomes.slice(0, 6)).toStrictEqual(930+ stepsLanded.map((sha) => [Outcome.cases.Landed.make({ sha })])931+ );932+ expect(933+ landings.slice(0, 6).map(({ author, trailers }) => ({934+ asked: trailers.filter(({ key }) => key === "Asked-by"),935+ author,936+ }))937+ ).toStrictEqual(938+ answerers.map((who) => ({939+ asked: [askedByAlice],940+ author: authorLine(Handle.make(who)),941+ }))942+ );943+ })944+ );945+946+ cases.effect(947+ "5. still refuses the delete step after three land, naming the three still open",948+ () =>949+ Effect.map(seen, ({ midFamily }) => {950+ expect(midFamily.deleteClaim).toStrictEqual(951+ AskBlocked.of(952+ deleteId,953+ Array.map(["p4", "p5", "p6"] as const, stepIdOf)954+ )955+ );956+ })957+ );958+959+ cases.effect("lowers the callers ratchet as each step lands", () =>960+ Effect.map(seen, ({ midFamily, ratchetsAtEnd }) => {961+ expect([midFamily.ratchets, ratchetsAtEnd]).toStrictEqual([962+ [963+ {964+ count: total - callers.p1 - callers.p2 - callers.p3,965+ ratchet: ratchetName,966+ territory: ".",967+ },968+ ],969+ [{ count: 0, ratchet: ratchetName, territory: "." }],970+ ]);971+ })972+ );973+974+ cases.effect(975+ "7. refuses a plain answer that adds a caller mid-family as a weakened ratchet, and lands nothing",976+ () =>977+ Effect.map(seen, ({ midFamily, tidyAfter }) => {978+ const before = total - callers.p1 - callers.p2 - callers.p3;979+980+ expect(tidyAfter).toStrictEqual({981+ main: midFamily.main,982+ outcomes: [983+ Outcome.cases.Refused.make({984+ refusals: [985+ new Weakened({986+ weakening: {987+ after: before + 1,988+ before,989+ ratchet: ratchetName,990+ territory: ".",991+ },992+ }),993+ ],994+ }),995+ ],996+ });997+ })998+ );999+1000+ cases.effect(1001+ "6. opens the delete step once the six land, while the parent waits on it",1002+ () =>1003+ Effect.map(seen, ({ afterSix, events }) => {1004+ expect([1005+ afterSix.deleteChild.state,1006+ afterSix.parent.state,1007+ ]).toStrictEqual(["open", "open"]);1008+ expect(1009+ eventsOf(events, "AskOpened")1010+ .map(({ ask }) => ask.ask)1011+ .filter((id) => id === deleteId)1012+ ).toStrictEqual([deleteId]);1013+ })1014+ );1015+1016+ cases.effect(1017+ "6. lands the delete step by heidi, and closes the parent on that landing",1018+ () =>1019+ Effect.map(1020+ seen,1021+ ({1022+ deleteLanded,1023+ events,1024+ landings,1025+ listedAtEnd,1026+ outcomes,1027+ parentAtEnd,1028+ }) => {1029+ expect({1030+ author: landings[6]?.author,1031+ outcome: outcomes[6],1032+ parent: parentAtEnd.state,1033+ }).toStrictEqual({1034+ author: authorLine(Handle.make("heidi")),1035+ outcome: [Outcome.cases.Landed.make({ sha: deleteLanded })],1036+ parent: "closed",1037+ });1038+ expect(listedAtEnd).toStrictEqual([tidyId]);1039+ expect(1040+ eventsOf(events, "AskClosed").filter(1041+ ({ ask }) => ask === parentId1042+ )1043+ ).toStrictEqual([1044+ expect.objectContaining({ ask: parentId, landing: deleteLanded }),1045+ ]);1046+ }1047+ )1048+ );1049+ }1050+);1051+1052+/**1053+ * The six answers pushed and submitted at once, as six agents would: every1054+ * one but the first is checked on a tree merged onto a main that moved, and1055+ * still lands, through the serial queue, with the callers ratchet at zero.1056+ */1057+const allAtOnce = Effect.gen(function* () {1058+ yield* advanceTo("2026-10-07T12:00:00Z");1059+1060+ const api = yield* projectService(project);1061+1062+ yield* fromFirstPush(api);1063+1064+ const opened = yield* api.openAsk(alice, {1065+ ask: parentId,1066+ files: Array.make(askFile(parentId)),1067+ });1068+1069+ const steps = Array.zip(packages, answerers);1070+1071+ yield* Effect.forEach(1072+ steps,1073+ ([name, who]) => api.claim(person(who), stepIdOf(name)),1074+ { concurrency: "unbounded" }1075+ );1076+1077+ yield* Effect.forEach(1078+ steps,1079+ ([name, who]) =>1080+ answer(api, {1081+ ask: stepIdOf(name),1082+ base: opened.landed,1083+ change: migrated(name),1084+ who: person(who),1085+ }),1086+ { concurrency: "unbounded" }1087+ );1088+1089+ // Whatever waits on a retry runs at the project's next alarms.1090+ yield* api.onAlarm();1091+ yield* advanceTo("2026-10-07T12:10:00Z");1092+ yield* api.onAlarm();1093+1094+ return {1095+ deleteChild: (yield* shown(api, deleteId)).state,1096+ outcomes: yield* Effect.forEach(answerers, (who) =>1097+ Effect.map(outcomesOf(api, who), (all) => all.map(({ _tag }) => _tag))1098+ ),1099+ ratchets: yield* ratchetRows,1100+ };1101+}).pipe(Effect.provide(worldWith()));1102+1103+describe("six answers to the six steps at once", () => {1104+ it.effect(1105+ "all land, none stale and none refused by the callers ratchet",1106+ () =>1107+ Effect.map(allAtOnce, (seenThen) => {1108+ expect(seenThen).toStrictEqual({1109+ deleteChild: "open",1110+ outcomes: Array.makeBy(6, () => ["Landed"]),1111+ ratchets: [{ count: 0, ratchet: ratchetName, territory: "." }],1112+ });1113+ }),1114+ wholeStory1115+ );1116+});1117+1118+// ---------------------------------------------------- other openings1119+1120+/** alice opens one ask of the scenario by its file alone, on a project fresh from its first push. */1121+const openingOf = (id: string, options: CheckerOptions = {}) =>1122+ Effect.gen(function* () {1123+ yield* advanceTo("2026-10-07T12:00:00Z");1124+1125+ const api = yield* projectService(project);1126+1127+ yield* fromFirstPush(api);1128+1129+ const opened = yield* Effect.result(1130+ api.openAsk(alice, {1131+ ask: AskId.make(id),1132+ files: Array.make(askFile(id)),1133+ })1134+ );1135+1136+ return {1137+ landings: yield* landingCount,1138+ listed: yield* listed(api),1139+ opened,1140+ ratchets: yield* ratchetRows,1141+ };1142+ }).pipe(Effect.provide(worldWith(options)));1143+1144+describe("opening a migrate ask", () => {1145+ it.effect(1146+ "is refused NotRedFirst when the two counts on main differ",1147+ () =>1148+ Effect.map(openingOf(parentId, { drifting: true }), (seenThen) => {1149+ expect(seenThen).toStrictEqual({1150+ landings: 1,1151+ listed: [],1152+ opened: Result.fail(new NotRedFirst({})),1153+ ratchets: [],1154+ });1155+ }),1156+ wholeStory1157+ );1158+1159+ it.effect(1160+ "is refused NotRedFirst when nothing calls the name: nothing to migrate",1161+ () =>1162+ Effect.map(openingOf("drop-old-thing"), ({ listed: open, opened }) => {1163+ expect([open, opened]).toStrictEqual([1164+ [],1165+ Result.fail(new NotRedFirst({})),1166+ ]);1167+ }),1168+ wholeStory1169+ );1170+1171+ it.effect(1172+ "opens as one plain ask, with no family, when its territory is one package",1173+ () =>1174+ Effect.map(1175+ openingOf("move-p2-fetch"),1176+ ({ listed: open, opened, ratchets }) => {1177+ expect({1178+ blockedBy: Result.map(opened, ({ ask }) => ask.blockedBy),1179+ listed: open,1180+ ratchets,1181+ }).toStrictEqual({1182+ blockedBy: Result.succeed([]),1183+ listed: [AskId.make("move-p2-fetch")],1184+ ratchets: [{ count: total, ratchet: ratchetName, territory: "." }],1185+ });1186+ }1187+ ),1188+ wholeStory1189+ );1190+});1191+1192+// ------------------------------------------------------ the pure split1193+1194+const parent: Ask = askOf(parentId);1195+1196+const { modules } = scenario.policy;1197+1198+const counted = (byModule: Readonly<Record<string, number>>): CallerCount => ({1199+ byModule,1200+ total: Object.values(byModule).reduce((sum, n) => sum + n, 0),1201+});1202+1203+const split = (1204+ byModule: Readonly<Record<string, number>>,1205+ of: Ask = parent1206+): Option.Option<MigrateFamily> =>1207+ splitFamily({1208+ configDir: Brand.configDir,1209+ counts: counted(byModule),1210+ modules,1211+ parent: of,1212+ });1213+1214+/** The fields a family's asks are compared by. */1215+const comparable = (ask: Ask) =>1216+ Struct.pick(ask, [1217+ "blockedBy",1218+ "check",1219+ "file",1220+ "id",1221+ "kind",1222+ "parent",1223+ "state",1224+ "territory",1225+ ]);1226+1227+describe(splitFamily, () => {1228+ it("splits as testkit's sixChildren() is written by hand: six steps and a delete step", () => {1229+ const made = Option.getOrThrow(split(callers));1230+ const byHand = new Map(family.policy.asks.map((ask) => [ask.id, ask]));1231+1232+ const expected = (id: AskId, state: Ask["state"]) => {1233+ const {1234+ blockedBy,1235+ check,1236+ file,1237+ kind,1238+ parent: of,1239+ territory,1240+ } = byHand.get(id) ?? parent;1241+1242+ return { blockedBy, check, file, id, kind, parent: of, state, territory };1243+ };1244+1245+ expect([...made.children, made.deleteChild].map(comparable)).toStrictEqual([1246+ ...childIds.map((id) => expected(id, "open")),1247+ expected(deleteId, "waitingOnParent"),1248+ ]);1249+ expect({1250+ blockedBy: made.parent.blockedBy,1251+ files: made.files.map(({ path }) => path),1252+ ratchet: made.ratchet,1253+ }).toStrictEqual({1254+ blockedBy: [...childIds, deleteId],1255+ files: [...childIds, deleteId].map((id) =>1256+ RepoPath.make(`${Brand.configDir}/asks/${id}.ask.ts`)1257+ ),1258+ ratchet: { baseline: total, name: ratchetName },1259+ });1260+ });1261+1262+ it("gives no step to a module with no callers", () => {1263+ expect(1264+ Option.map(split({ ...callers, p3: 0 }), ({ children }) =>1265+ children.map(({ id }) => id)1266+ )1267+ ).toStrictEqual(1268+ Option.some(Array.map(["p1", "p2", "p4", "p5", "p6"] as const, stepIdOf))1269+ );1270+ });1271+1272+ it("gives no step to a module outside the parent's territory", () => {1273+ const narrower: Ask = {1274+ ...parent,1275+ territory: {1276+ module: ".",1277+ paths: [Glob.make("packages/p1/**"), Glob.make("packages/p2/**")],1278+ },1279+ };1280+1281+ expect(1282+ Option.map(split(callers, narrower), ({ children }) =>1283+ children.map(({ id }) => id)1284+ )1285+ ).toStrictEqual(Option.some(Array.map(["p1", "p2"] as const, stepIdOf)));1286+ });1287+1288+ it.each([1289+ ["only one module has callers", { p2: 7 }, parent],1290+ [1291+ "the territory names one package",1292+ callers,1293+ { ...parent, territory: modules[1] ?? parent.territory },1294+ ],1295+ [1296+ "the ask is no migrate ask",1297+ callers,1298+ {1299+ ...parent,1300+ check: CheckSpec.cases.SymbolAbsent.make({1301+ count: countOf(symbol),1302+ symbol: SymbolName.make(symbol),1303+ }),1304+ },1305+ ],1306+ ] as const)("does not split when %s", (_, byModule, of) => {1307+ expect(split(byModule, of)).toStrictEqual(Option.none());1308+ });1309+1310+ it("holds every step to the parent's asker, kind and reserve", () => {1311+ const reserved: Ask = {1312+ ...parent,1313+ kind: parent.kind,1314+ mentor: Handle.make("alice"),1315+ reserve: "newcomers",1316+ };1317+1318+ const made = Option.getOrThrow(split(callers, reserved));1319+1320+ expect(1321+ Array.dedupe(1322+ [...made.children, made.deleteChild].map(1323+ ({ askedBy, kind, mentor, reserve }) =>1324+ JSON.stringify({ askedBy, kind, mentor, reserve })1325+ )1326+ )1327+ ).toStrictEqual([1328+ JSON.stringify({1329+ askedBy: parent.askedBy,1330+ kind: parent.kind,1331+ mentor: "alice",1332+ reserve: "newcomers",1333+ }),1334+ ]);1335+ });1336+});1337+1338+describe(childId, () => {1339+ it.each([1340+ ["p1", "drop-legacy-fetch-p1"],1341+ ["@burrow/http-kit", "drop-legacy-fetch-burrow-http-kit"],1342+ ["--Odd__Name--", "drop-legacy-fetch-odd-name"],1343+ ])("names %s's step %s, an ask id with no --", (module, id) => {1344+ const named = childId(parentId, module);1345+1346+ expect([1347+ named,1348+ named.includes("--"),1349+ Schema.is(AskId)(named),1350+ ]).toStrictEqual([id, false, true]);1351+ });1352+1353+ it("names the delete step apart from every step", () => {1354+ expect(deleteChildId(parentId)).toStrictEqual(deleteId);1355+ });1356+});1357+1358+/** The family as it stands once the steps in `closed` have landed. */1359+const standing = (closed: readonly Package[]) => {1360+ const made = Option.getOrThrow(split(callers));1361+1362+ return new Map(1363+ [made.parent, ...made.children, made.deleteChild].map((ask) => [1364+ ask.id,1365+ packages.some(1366+ (name) => closed.includes(name) && stepIdOf(name) === ask.id1367+ )1368+ ? { ...ask, state: "closed" as const }1369+ : ask,1370+ ])1371+ );1372+};1373+1374+describe(remainingBlockers, () => {1375+ it("names the steps still open, in order", () => {1376+ const asks = standing(["p1", "p3", "p5"]);1377+1378+ expect(1379+ remainingBlockers(1380+ Option.getOrThrow(Option.fromUndefinedOr(asks.get(deleteId))),1381+ asks1382+ )1383+ ).toStrictEqual(Array.map(["p2", "p4", "p6"] as const, stepIdOf));1384+ });1385+1386+ it("names none once every step has closed", () => {1387+ const asks = standing(packages);1388+1389+ expect(1390+ remainingBlockers(1391+ Option.getOrThrow(Option.fromUndefinedOr(asks.get(deleteId))),1392+ asks1393+ )1394+ ).toStrictEqual([]);1395+ });1396+1397+ it("keeps an ask it does not know as blocking", () => {1398+ const ghost = AskId.make("never-opened");1399+1400+ expect(1401+ remainingBlockers({ ...parent, blockedBy: [ghost] }, new Map())1402+ ).toStrictEqual([ghost]);1403+ });1404+});1405+1406+describe(familyClosed, () => {1407+ it("is false while the delete step is open, and true once it closes", () => {1408+ const asks = standing(packages);1409+1410+ const deleteStep = Option.getOrThrow(1411+ Option.fromUndefinedOr(asks.get(deleteId))1412+ );1413+1414+ expect([1415+ familyClosed(parentId, asks),1416+ familyClosed(1417+ parentId,1418+ new Map(asks).set(deleteId, { ...deleteStep, state: "closed" })1419+ ),1420+ ]).toStrictEqual([false, true]);1421+ });1422+1423+ it("is false for an ask with no steps", () => {1424+ expect([familyClosed(tidyId, standing([]))]).toStrictEqual([false]);1425+ });1426+});1427+1428+// ------------------------------------------- the files the family lands1429+1430+/** The six packages as workspaces, and alice as the project's initializer. */1431+const facts = Schema.decodeSync(EvaluationFacts)({1432+ ci: [],1433+ initializer: "alice",1434+ now: "2026-10-07T12:00:00.000Z",1435+ project,1436+ seed: 7,1437+ workspaces: packages.map((name) => ({1438+ dir: `packages/${name}`,1439+ exports: [],1440+ name,1441+ })),1442+});1443+1444+const projectFile = [1445+ `import { kinds, project } from "${Brand.cliPackage}/rules";`,1446+ "",1447+ "export default project({",1448+ " kinds: [kinds.migrate],",1449+ ' run: { checks: {}, test: "bun test {path}" },',1450+ "});",1451+ "",1452+].join("\n");1453+1454+/** The fields an ask file states, as the evaluator reads them back. */1455+const stated = (ask: Ask) =>1456+ Struct.pick(ask, [1457+ "blockedBy",1458+ "brief",1459+ "check",1460+ "file",1461+ "id",1462+ "kind",1463+ "parent",1464+ "territory",1465+ ]);1466+1467+/** What asks' files state, by id: the evaluator reads ask files in path order. */1468+const byId = (asks: readonly Ask[]) =>1469+ asks.map(stated).toSorted((a, b) => a.id.localeCompare(b.id));1470+1471+/** The family of `of`'s files, as the rules evaluator reads them back from a config folder. */1472+const evaluatedFamily = (of: Ask) =>1473+ Effect.gen(function* () {1474+ const made = Option.getOrThrow(split(callers, of));1475+ const evaluator = yield* RulesEvaluator;1476+1477+ const policy = yield* evaluator.evaluate({1478+ at: LandedSha.make("a".repeat(40)),1479+ facts,1480+ modules: {1481+ entry: `${Brand.configDir}/project.ts`,1482+ modules: {1483+ [`${Brand.configDir}/project.ts`]: projectFile,1484+ ...Object.fromEntries(1485+ made.files.map(({ content, path }) => [path, content])1486+ ),1487+ },1488+ sdkVersion,1489+ },1490+ });1491+1492+ return {1493+ evaluated: byId(policy.asks),1494+ family: byId([...made.children, made.deleteChild]),1495+ };1496+ }).pipe(1497+ Effect.provide(1498+ RulesEvaluatorBun.pipe(1499+ Layer.provide(Layer.mergeAll(FinishersFromChecks, NodeServices.layer))1500+ )1501+ )1502+ );1503+1504+describe("the family's ask files", () => {1505+ it.live(1506+ "evaluate, through the sdk, to the family's steps and its delete step",1507+ () =>1508+ Effect.map(evaluatedFamily(parent), ({ evaluated, family: written }) => {1509+ expect(evaluated).toStrictEqual(written);1510+ }),1511+ wholeStory1512+ );1513+1514+ it.live(1515+ "keep the parent's kind when it is a migrate kind of another name",1516+ () =>1517+ Effect.map(1518+ evaluatedFamily({ ...parent, kind: KindName.make("dropApi") }),1519+ ({ evaluated, family: written }) => {1520+ expect([1521+ evaluated,1522+ Array.dedupe(evaluated.map(({ kind }) => kind)),1523+ ]).toStrictEqual([written, [KindName.make("dropApi")]]);1524+ }1525+ ),1526+ wholeStory1527+ );1528+});