Merge build/506-migrate-split-family: one migrate ask opens as a family that lands from the bottom up
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 1a80417, e78e86c · Browse files · 3 files·+2361 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+2361 added−39 removed
- tests:+1675 added−0 removed
- other:+686 added−39 removed
Provenance
- Commit
fceb9c2- Tree
633d866- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
1a80417- Parent 2
e78e86c
3 files changed+2361 added−39 removed
added:packages/project/src/migrate.ts+365 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 child ask per module with callers, each with that module5+ * as its territory and "no callers in this module" as its check, and a6+ * delete child that waits on every child and checks the name is gone. The7+ * children's territories are disjoint, so their claims never overlap and8+ * their answers re-merge cleanly through the serial landing queue; the9+ * parent closes when its last child 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 child and the delete child. */64+ readonly parent: Ask;65+ /** One child per module with callers, in the policy's module order. */66+ readonly children: Array.NonEmptyReadonlyArray<Ask>;67+ /** The last child: the name is gone. Blocked by every child until they land. */68+ readonly deleteChild: Ask;69+ /** The children's and the delete child'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 child 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 child: `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 children, 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; in the modules it spans, when it spans some but not all;137+ * everywhere, when it spans them all or none (a repo with no modules).138+ */139+export const callersIn = (140+ territory: Territory,141+ counts: CallerCount,142+ modules: readonly Territory[]143+): number => {144+ const within = modulesWithin(territory, modules);145+146+ return within.length === 0 || within.length === modules.length147+ ? counts.total148+ : within.reduce(149+ (sum, { module }) => sum + (counts.byModule[module] ?? 0),150+ 0151+ );152+};153+154+/**155+ * The ratchet a migrate ask's callers are counted by on every answer while156+ * it is open: its count command's `total`, over the whole project.157+ */158+export const callersSpec = (check: MigrateCheck): RatchetSpec => ({159+ measure: RatchetMeasure.cases.Metric.make({160+ command: check.count,161+ path: JsonPath.make("$.total"),162+ }),163+ name: callersRatchet(check.from),164+});165+166+/** The callers ratchets of every migrate ask still open, one per name. */167+export const callersSpecs = (asks: Iterable<Ask>): readonly RatchetSpec[] =>168+ Array.dedupeWith(169+ [...asks].flatMap(({ check, state }) =>170+ CheckSpec.guards.Migrate(check) && state !== "closed"171+ ? [callersSpec(check)]172+ : []173+ ),174+ (one, other) => one.name === other.name175+ );176+177+const quoted = (text: string) => JSON.stringify(text);178+179+const header = (parent: AskId) =>180+ `// A child of the migrate ask ${parent}, written by ${Brand.name} when it opened.`;181+182+const sdk = quoted(`${Brand.cliPackage}/rules`);183+184+/** An object literal's lines, each `key: value,`, indented by two. */185+const fields = (entries: readonly (readonly [string, string])[]) =>186+ entries.map(([key, value]) => ` ${key}: ${value},`);187+188+/**189+ * A child's file, through the sdk's `kinds.migrate` when the parent is of190+ * that kind, else through a kind of the parent's name made in the file.191+ */192+const childFile = (child: Ask, check: MigrateCheck, parent: AskId) => {193+ const stated: (readonly [string, string])[] = [194+ ["parent", quoted(parent)],195+ ["territory", `territory.package(${quoted(child.territory.module)})`],196+ ["want", quoted(child.brief.want)],197+ ];198+199+ const args: (readonly [string, string])[] = [200+ ["count", quoted(check.count)],201+ ["from", quoted(check.from)],202+ ...(check.to === undefined ? [] : [["to", quoted(check.to)] as const]),203+ ];204+205+ if (child.kind === "migrate") {206+ return [207+ header(parent),208+ `import { kinds, territory } from ${sdk};`,209+ "",210+ "export default kinds.migrate.ask({",211+ ...fields(212+ [...args, ...stated].toSorted(([a], [b]) => a.localeCompare(b))213+ ),214+ "});",215+ "",216+ ].join("\n");217+ }218+219+ return [220+ header(parent),221+ `import { check, kind, territory } from ${sdk};`,222+ "",223+ "const own = kind({",224+ " args: {},",225+ ` check: () => check.migrate({ ${args.map(([key, value]) => `${key}: ${value}`).join(", ")} }),`,226+ ` checkKind: "migrate",`,227+ ` name: ${quoted(child.kind)},`,228+ "});",229+ "",230+ "export default own.ask({",231+ ...fields(stated),232+ "});",233+ "",234+ ].join("\n");235+};236+237+/**238+ * The delete child's file: the sdk has no `symbolAbsent` builder, so the239+ * file makes a kind of the parent's name whose check is the name gone.240+ */241+const deleteFile = (child: Ask, check: MigrateCheck, parent: AskId) =>242+ [243+ header(parent),244+ `import { kind } from ${sdk};`,245+ "",246+ "const own = kind({",247+ " args: {},",248+ ` check: () => ({ _tag: "SymbolAbsent", count: ${quoted(check.count)}, symbol: ${quoted(check.from)} }),`,249+ ` checkKind: "symbolAbsent",`,250+ ` name: ${quoted(child.kind)},`,251+ "});",252+ "",253+ "export default own.ask({",254+ ...fields([255+ ["blockedBy", JSON.stringify(child.blockedBy)],256+ ["parent", quoted(parent)],257+ ["territory", JSON.stringify(child.territory)],258+ ["want", quoted(child.brief.want)],259+ ]),260+ "});",261+ "",262+ ].join("\n");263+264+const callersOf = (count: number) =>265+ count === 1 ? "1 caller" : `${count} callers`;266+267+/** A child's want: `p1: 5 callers of legacyFetch → http.get`. */268+const childWant = (module: string, count: number, check: MigrateCheck) =>269+ check.to === undefined270+ ? `${module}: ${callersOf(count)} of ${check.from} to remove`271+ : `${module}: ${callersOf(count)} of ${check.from} → ${check.to}`;272+273+/**274+ * Splits a migrate ask into its family: a child for each module of its275+ * territory that has callers, in the policy's module order, and a delete276+ * child blocked by all of them, each asked by the parent's asker and held277+ * as the parent is held. `None` when the ask is no migrate ask, or fewer278+ * than two of its modules have callers: a split of one is the ask itself.279+ */280+export const splitFamily = (input: {281+ readonly parent: Ask;282+ readonly counts: CallerCount;283+ readonly modules: readonly Territory[];284+ readonly configDir: string;285+}): Option.Option<MigrateFamily> => {286+ const { counts, parent } = input;287+ const { check } = parent;288+289+ if (!CheckSpec.guards.Migrate(check)) {290+ return Option.none();291+ }292+293+ const fileOf = (id: AskId) =>294+ RepoPath.make(`${input.configDir}/asks/${id}.ask.ts`);295+296+ const member = (297+ id: AskId,298+ own: Pick<Ask, "blockedBy" | "brief" | "check" | "state" | "territory">299+ ): Ask => ({300+ ...parent,301+ ...own,302+ file: fileOf(id),303+ id,304+ parent: parent.id,305+ });306+307+ const called = modulesWithin(parent.territory, input.modules).flatMap(308+ (module) => {309+ const count = counts.byModule[module.module] ?? 0;310+311+ return count > 0312+ ? [313+ member(childId(parent.id, module.module), {314+ blockedBy: [],315+ brief: { want: childWant(module.module, count, check) },316+ check,317+ state: "open",318+ territory: module,319+ }),320+ ]321+ : [];322+ }323+ );324+325+ const [first, second, ...rest] = called;326+327+ if (first === undefined || second === undefined) {328+ return Option.none();329+ }330+331+ const children = Array.make(first, second, ...rest);332+ const childIds = children.map(({ id }) => id);333+ const deleteId = deleteChildId(parent.id);334+335+ const deleteChild = member(deleteId, {336+ blockedBy: childIds,337+ brief: { want: `Delete ${check.from}: nothing calls it any more` },338+ check: CheckSpec.cases.SymbolAbsent.make({339+ count: check.count satisfies Command,340+ symbol: check.from,341+ }),342+ state: "waitingOnParent",343+ territory: parent.territory,344+ });345+346+ return Option.some({347+ children,348+ deleteChild,349+ files: Array.append(350+ Array.map(children, (each) => ({351+ content: childFile(each, check, parent.id),352+ path: each.file,353+ })),354+ {355+ content: deleteFile(deleteChild, check, parent.id),356+ path: deleteChild.file,357+ }358+ ),359+ parent: {360+ ...parent,361+ blockedBy: Array.dedupe([...parent.blockedBy, ...childIds, deleteId]),362+ },363+ ratchet: { baseline: counts.total, name: callersRatchet(check.from) },364+ });365+};modified:packages/project/src/project.ts+321 added-39 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 child. */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 child `landed` closed (CAA §2.F): each2215+ * child waiting on its siblings opens when the last of them lands, and2216+ * the parent closes on the landing that closes its last child.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 child of before.values()) {2235+ if (2236+ child.parent === parent.value &&2237+ child.state === "waitingOnParent" &&2238+ remainingBlockers(child, before).length === 02239+ ) {2240+ const opened: Ask = { ...child, state: "open" };2241+2242+ writes.asks.set(child.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+ // child'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 callers: 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+ callers,3174+ children: [],3175+ counted: [],3176+ files,3177+ tree: composed.tree,3178+ };3179+ }3180+3181+ const { children, deleteChild, parent } = family.value;3182+ const added = family.value.files;3183+ const taken = takenBy(input.h, input.writes, { added, files, policy });3184+3185+ if (Array.isReadonlyArrayNonEmpty(taken)) {3186+ return yield* new TouchedJudge({ paths: taken });3187+ }3188+3189+ const all = Array.appendAll(files, added);3190+3191+ const { tree } = yield* lander.compose({3192+ files: all,3193+ main: input.main,3194+ repo,3195+ });3196+3197+ return {3198+ asks: Array.make(parent, ...children, deleteChild),3199+ callers,3200+ children: [...children, deleteChild].map(({ id }) => id),3201+ counted: [],3202+ files: all,3203+ tree,3204+ };3205+ });3206+3207+ /**3208+ * The landing that opens an ask: its files on main, authored by its3209+ * asker. A migrate ask's landing names the children it opened with it.3210+ */3211 const landAsk = (input: {3212 readonly ask: Ask;3213+ readonly children: readonly AskId[];3214 readonly credits: readonly Credit[];3215 readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;3216 readonly main: LandedSha;3217 readonly tree: Checking["tree"];3218 }) => {3219 const requestId = RequestId.make(`open-${input.tree}`);2982- const { credits } = input;3220+ const { children, credits } = input;3221 3222 const landing = lander3223 .land({3224 author: input.ask.askedBy,3225 main: input.main,3226 message: formatLanding({3227 ask: { ask: input.ask.id, project: name },3228 assisted: [],3229+ body:3230+ children.length === 03231+ ? input.ask.brief.want3232+ : [2991- body: input.ask.brief.want,3233+ input.ask.brief.want,3234+ "",3235+ "Its child asks, the last waiting on the rest:",3236+ ...children.map((child) => `- ${child}`),3237+ ].join("\n"),3238 credits,3239 requestId,3240 subject: `Open ask ${input.ask.id}`,3241 }),102 unmodified lines3344 if (Option.isSome(weak)) {3345 return yield* new WeakCheck({ weakness: weak.value });3346 }3347 3102- const counted = yield* redTwice(policy, ask, composed.commit);3348+ const opens = countsCallers(ask.check)3349+ ? yield* migrateOpening({3350+ ask,3351+ composed,3352+ files,3353+ h,3354+ main,3355+ policy,3356+ writes,3357+ })3358+ : {3359+ asks: Array.make(ask),3360+ callers: [],3361+ children: [],3362+ counted: yield* redTwice(policy, ask, composed.commit),3363+ files,3364+ tree: composed.tree,3365+ };3366 3367 const landed = yield* landAsk({3368 ask,3369+ children: opens.children,3370 credits: opening.credits,3107- files,3371+ files: opens.files,3372 main,3109- tree: composed.tree,3373+ tree: opens.tree,3374 });3375 3112- const opened: Ask = { ...ask, openedIn: landed.sha };3376+ const opened = Array.map(opens.asks, (each): Ask => ({3377+ ...each,3378+ openedIn: landed.sha,3379+ }));3380 3114- writes.asks.set(opened.id, opened);3115- writes.events.push(askOpened(opened, now));3381+ for (const each of opened) {3382+ writes.asks.set(each.id, each);3383+3384+ // A child that waits on others opens when they land.3385+ if (each.state === "open") {3386+ writes.events.push(askOpened(each, now));3387+ }3388+ }3389+3390 writes.landings.push({3391 assisted: [],3392 author: opening.asker,3393 credits: landed.credits,7 unmodified lines3401 "row",3402 yield* withPolicyAt({ ...row, landed: landed.sha }, landed.sha, now)3403 );3404 3131- // The opening landing records the baselines its check's lint read.3132- putRatchets(3133- h,3134- writes,3135- afterLanding(baselinesNow(h, writes), counted, landed.sha).baselines3136- );3405+ // The opening landing records the baselines its check's count read,3406+ // and sets a migrate ask's callers ratchet at its count: a lower3407+ // baseline a closed migrate ask of the same name left counted3408+ // nothing since, and while one is open no answer can raise it.3409+ putRatchets(h, writes, [3410+ ...afterLanding(baselinesNow(h, writes), opens.counted, landed.sha)3411+ .baselines,3412+ ...opens.callers.map(3413+ ({ count, ratchet, territory }): RatchetBaseline => ({3414+ count,3415+ ratchet,3416+ setAt: landed.sha,3417+ territory,3418+ })3419+ ),3420+ ]);3421 3138- return { ask: opened, landed: landed.sha };3422+ return { ask: Array.headNonEmpty(opened), landed: landed.sha };3423 });3424 3425 const openBody =3426 (79 unmodified lines3506 const trust = trustOf(h, policy, ask.value, { caller, now });3507 3508 const command = ClaimCommand.cases.Claim.make({3509 base: live.value.landed,3226- blockedBy: ask.value.blockedBy.filter(3227- (blocker) => h.asks.get(blocker)?.state !== "closed"3228- ),3510+ blockedBy: remainingBlockers(ask.value, h.asks),3511 cap: policy.caps.claimsPerPerson,3512 denounced: trust.denounced,3513 heldByWho: heldBy(h, caller.handle, id),3514 liveCount: h.claims.filter(760 unmodified linesadded:packages/project/test/migrate.test.ts+1675 added
1+/**2+ * The migrate split family (CAA §2.F): one migrate ask over six packages3+ * opens as six child asks, one per package, and a delete child that waits4+ * on them; six people claim the six at once, the children land one by one5+ * through the serial queue, and the delete child'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 type { Territory } from "@repo/protocol/domain/territory";34+import {35+ AskId,36+ Handle,37+ KindName,38+ LandedSha,39+ LaneName,40+ RepoName,41+ RepoPath,42+ RequestId,43+} from "@repo/protocol/ids";44+import type { CommitSha } from "@repo/protocol/ids";45+import { Anonymous, Person } from "@repo/protocol/principal";46+import {47+ AskBlocked,48+ NotRedFirst,49+ TouchedJudge,50+ Weakened,51+} from "@repo/protocol/refusal";52+import {53+ EvaluationFacts,54+ RulesEvaluator,55+ sdkVersion,56+} from "@repo/rules/rules-evaluator";57+import { RulesEvaluatorBun } from "@repo/rules/rules-evaluator/bun";58+import { advanceTo } from "@repo/testkit/clock";59+import type { Files } from "@repo/testkit/git-client";60+import { sixChildren, withAsk, withVouches } from "@repo/testkit/scenarios";61+import {62+ Array,63+ Context,64+ Effect,65+ Exit,66+ Layer,67+ Option,68+ Ref,69+ Result,70+ Schema,71+ Struct,72+} from "effect";73+74+import { AnswerRuns } from "../src/answer-runs.ts";75+import type { AnswerQueue, AnswerRun } from "../src/answer-runs.ts";76+import { drive } from "../src/answer-runs/steps.ts";77+import { Lander } from "../src/lander.ts";78+import { LandingCommand } from "../src/landing.ts";79+import type { Change } from "../src/landing.ts";80+import {81+ callersIn,82+ childId,83+ deleteChildId,84+ familyClosed,85+ remainingBlockers,86+ splitFamily,87+} from "../src/migrate.ts";88+import type { MigrateFamily, CallerCount } from "../src/migrate.ts";89+import { ProjectStore } from "../src/project-store.ts";90+import type { ProjectApi } from "../src/project.ts";91+import { FinishersFromChecks, projectService } from "../src/project.ts";92+import { Pusher, worldOf } from "./world.ts";93+94+// ------------------------------------------------------------- the project95+96+const symbol = "legacyFetch";97+98+const countOf = (name: string) =>99+ Command.make(`node scripts/count-callers.mjs ${name} --json`);100+101+const packages = ["p1", "p2", "p3", "p4", "p5", "p6"] as const;102+103+type Package = (typeof packages)[number];104+105+/** How many calls of `legacyFetch` each package makes on main: 37 in all. */106+const callers = { p1: 5, p2: 7, p3: 6, p4: 8, p5: 4, p6: 7 } as const;107+108+const total = 37;109+110+const answerers = ["bob", "carol", "dave", "eve", "frank", "grace"] as const;111+112+/** heidi answers the delete child; ivan the plain ask beside the family. */113+const others = ["heidi", "ivan"] as const;114+115+const family = sixChildren({ symbol, to: "http.get" });116+117+/**118+ * `burrow` as `sixChildren()` makes it, its six packages its modules, with119+ * everyone vouched for and three more asks: a plain one in `p6`, a migrate120+ * ask over one package, and a migrate ask for a name nobody calls.121+ */122+const scenario = family.pipe(123+ withVouches([...answerers, ...others]),124+ withAsk({ id: "tidy-p6", territory: "packages/p6" }),125+ withAsk({126+ check: CheckSpec.cases.Migrate.make({127+ count: countOf(symbol),128+ from: SymbolName.make(symbol),129+ to: SymbolName.make("http.get"),130+ }),131+ id: "move-p2-fetch",132+ kind: "migrate",133+ territory: "packages/p2",134+ }),135+ withAsk({136+ check: CheckSpec.cases.Migrate.make({137+ count: countOf("oldThing"),138+ from: SymbolName.make("oldThing"),139+ }),140+ id: "drop-old-thing",141+ kind: "migrate",142+ territory: ".",143+ })144+);145+146+const { project } = scenario;147+148+const repo = RepoName.make(project);149+150+const mainRef = RefName.make("refs/heads/main");151+152+const parentId = AskId.make("drop-legacy-fetch");153+154+const childIdOf = (name: Package) => AskId.make(`${parentId}-${name}`);155+156+const childIds = Array.map(packages, childIdOf);157+158+const deleteId = AskId.make(`${parentId}-delete`);159+160+const tidyId = AskId.make("tidy-p6");161+162+const ratchetName = "callers-legacyfetch";163+164+const person = (handle: string) => Person.make({ handle: Handle.make(handle) });165+166+const alice = person("alice");167+168+const anyone = Anonymous.make({});169+170+const askOf = (id: string) =>171+ Option.getOrThrow(172+ Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)173+ );174+175+/** `count` calls of `name`, one a line. */176+const calls = (name: string, count: number) =>177+ Array.makeBy(count, (n) => ` ${name}("/item/${n}");\n`).join("");178+179+const indexOf = (name: string) => `packages/${name}/src/index.ts`;180+181+const extraOf = (name: string) => `packages/${name}/src/extra.ts`;182+183+const legacyFile = "packages/p1/src/legacy.ts";184+185+/** The project as alice first pushes it: six packages calling `legacyFetch`. */186+const start: Files = [187+ ["package.json", '{ "name": "burrow", "workspaces": ["packages/*"] }\n'],188+ ["scripts/count-callers.mjs", "// prints {total, byModule} for a name\n"],189+ [legacyFile, "export const legacyFetch = (url) => fetch(url);\n"],190+ ...packages.map((name): readonly [string, string] => [191+ indexOf(name),192+ `export const run = () => {\n${calls(symbol, callers[name])}};\n`,193+ ]),194+];195+196+/** `files` with `path` holding `content`, added or replaced; with no `content`, deleted. */197+const changed = (files: Files, path: string, content?: string): Files => [198+ ...files.filter(([each]) => each !== path),199+ ...(content === undefined ? [] : [[path, content] as const]),200+];201+202+/** An ask's file in the config folder: what alice sends to open it. */203+const askFile = (id: string) => {204+ const { file } = askOf(id);205+206+ return { content: `export default "${id}";\n`, path: file };207+};208+209+/** A plain ask's files: its ask file, and a check file with an assertion. */210+const plainFiles = (id: string) => {211+ const { check } = askOf(id);212+213+ return Array.make(askFile(id), {214+ content: [215+ `import { expect, it } from "vitest";`,216+ `import { run } from "../src/index.ts";`,217+ ``,218+ `it("${id}", () => {`,219+ ` expect(run()).toStrictEqual(undefined);`,220+ `});`,221+ ``,222+ ].join("\n"),223+ path: CheckSpec.guards.RedThenGreen(check)224+ ? check.path225+ : RepoPath.make(`test/${id}.test.ts`),226+ });227+};228+229+// ---------------------------------------------------------- the stand-ins230+231+/** What one merge came to: the answer's head, onto which main, and the paths it changed. */232+interface Merged {233+ readonly changes: readonly Change[];234+ readonly fork: RepoName;235+ readonly head: CommitSha;236+ readonly main: LandedSha;237+}238+239+/** The name a caller count counts: `node scripts/count-callers.mjs <name> --json`. */240+const countedName = (command: string) => command.split(" ")[2] ?? "";241+242+const occurrences = (text: string, name: string) =>243+ text.split(`${name}(`).length - 1;244+245+/** How the Checker behaves, beyond counting callers on the tree it is given. */246+interface CheckerOptions {247+ /** Each count prints one more caller in `p1` than the count before it. */248+ readonly drifting?: boolean;249+}250+251+/** The ratchets a run counts on `tree`, as the platform's cheap stage reads them. */252+const ratchetsOn = (run: AnswerRun, tree: CheckAt) =>253+ Effect.gen(function* () {254+ const runner = yield* CheckRunner;255+ const specs = run.counts?.ratchets ?? [];256+ const block = Option.fromUndefinedOr(run.run);257+258+ if (specs.length === 0 || Option.isNone(block)) {259+ return [];260+ }261+262+ const lanes = specs.map(({ measure: { command }, name }): CheckLane => ({263+ command,264+ lane: LaneName.make(name),265+ output: "stdout",266+ }));267+268+ const ran = yield* runner269+ .run({270+ at: tree,271+ lanes,272+ placeholders: [],273+ project,274+ proxies: [],275+ repo,276+ run: block.value,277+ })278+ .pipe(Effect.orDie);279+280+ const printed = (command: string) =>281+ ran.outputs?.find(282+ ({ lane }) =>283+ lanes.find((each) => each.lane === lane)?.command === command284+ )?.stdout ?? "";285+286+ const counts = yield* Effect.forEach(specs, (spec) =>287+ measure(288+ spec,289+ (command) => Effect.succeed({ code: 0, stdout: printed(command) }),290+ run.counts?.modules ?? []291+ )292+ ).pipe(Effect.orDie);293+294+ return counts.flat();295+ });296+297+/**298+ * The stand-ins, over the world's own Lander and repos: a Lander that299+ * remembers its merges, a Checker that counts callers on the tree it is300+ * given, and answer runs that count ratchets before they report a check.301+ */302+const standIns = (options: CheckerOptions) =>303+ Layer.effectContext(304+ Effect.gen(function* () {305+ const host = yield* RepoHost;306+ const inner = yield* Lander;307+ const merges = new Map<string, Merged>();308+ const counted = yield* Ref.make(0);309+ const running = yield* Ref.make<ReadonlySet<RequestId>>(new Set());310+311+ const lander = Lander.of({312+ ...inner,313+ merge: (job) =>314+ Effect.tap(inner.merge(job), ({ changes, tree }) =>315+ Effect.sync(() =>316+ merges.set(tree, {317+ changes,318+ fork: job.fork,319+ head: job.head,320+ main: job.main,321+ })322+ )323+ ),324+ });325+326+ const read = (from: RepoName, sha: CommitSha, path: string) =>327+ host.readFile(from, Revision.Commit({ sha }), RepoPath.make(path)).pipe(328+ Effect.orDie,329+ Effect.map((bytes) =>330+ Option.match(bytes, {331+ onNone: () => "",332+ onSome: (found) => new TextDecoder().decode(found),333+ })334+ )335+ );336+337+ /** A file's text in the tree a job runs on: a commit of the repo, or a merge. */338+ const textAt = (at: CheckAt, path: string) =>339+ CheckAt.match(at, {340+ Commit: ({ commit }) => read(repo, commit, path),341+ Tree: ({ tree }) => {342+ const merged = merges.get(tree);343+344+ if (merged === undefined) {345+ return Effect.die(`no merge made the tree ${tree}`);346+ }347+348+ const change = merged.changes.find((each) => each.path === path);349+350+ if (change === undefined) {351+ return read(repo, merged.main, path);352+ }353+354+ return change.status === "deleted"355+ ? Effect.succeed("")356+ : read(merged.fork, merged.head, path);357+ },358+ });359+360+ /** What the caller count prints for `name` on the tree a job runs on. */361+ const countAt = (at: CheckAt, name: string) =>362+ Effect.gen(function* () {363+ const found = yield* Effect.forEach(packages, (each) =>364+ Effect.gen(function* () {365+ const index = yield* textAt(at, indexOf(each));366+ const extra = yield* textAt(at, extraOf(each));367+368+ return [369+ each,370+ occurrences(index, name) + occurrences(extra, name),371+ ] as const;372+ })373+ );374+375+ const skew =376+ options.drifting === true377+ ? yield* Ref.getAndUpdate(counted, (n) => n + 1)378+ : 0;379+380+ const byModule = Object.fromEntries(381+ found.map(([each, count]) => [382+ each,383+ each === "p1" ? count + skew : count,384+ ])385+ );386+387+ return JSON.stringify({388+ byModule,389+ total: Object.values(byModule).reduce((sum, n) => sum + n, 0),390+ });391+ });392+393+ const laneRun = (job: CheckJob, lane: CheckLane) =>394+ Effect.gen(function* () {395+ // An ask's own test fails on main by an assertion, and passes on an answer.396+ const fails =397+ CheckAt.guards.Commit(job.at) && lane.lane === "redThenGreen";398+399+ const result: LaneResult = {400+ command: lane.command,401+ durationMs: 1,402+ lane: lane.lane,403+ result: fails ? "failed" : "passed",404+ };405+406+ const output =407+ lane.output === "stdout"408+ ? Option.some({409+ lane: lane.lane,410+ stdout: yield* countAt(job.at, countedName(lane.command)),411+ })412+ : Option.none();413+414+ return { output, result };415+ });416+417+ const runner = CheckRunner.of({418+ run: (job) =>419+ Effect.gen(function* () {420+ const lanes = yield* Effect.forEach(job.lanes, (lane) =>421+ laneRun(job, lane)422+ );423+424+ const outputs = Array.getSomes(lanes.map(({ output }) => output));425+426+ const ran: CheckRun = {427+ durationMs: lanes.length,428+ evidence: lanes429+ .filter(({ result }) => result.result === "failed")430+ .map(({ result }) => ({431+ lane: result.lane,432+ signature: `${result.lane}: expected undefined`,433+ })),434+ heldBack: [],435+ lanes: lanes.map(({ result }) => result),436+ };437+438+ return Array.isReadonlyArrayEmpty(outputs)439+ ? ran440+ : { ...ran, outputs };441+ }),442+ });443+444+ const ports = Context.make(CheckRunner, runner).pipe(445+ Context.add(Lander, lander)446+ );447+448+ /** The project's queue, with the ratchets counted on a tree before its check is reported. */449+ const counting = (queue: AnswerQueue): AnswerQueue => ({450+ advanceAnswer: (requestId, command, report) =>451+ LandingCommand.$is("Checked")(command)452+ ? Effect.gen(function* () {453+ const run = yield* queue.answer(requestId);454+455+ const ratchets = yield* Option.match(run, {456+ onNone: () => Effect.succeed([]),457+ onSome: (found) =>458+ ratchetsOn(459+ found,460+ CheckAt.cases.Tree.make({ tree: command.tree })461+ ).pipe(Effect.provideContext(ports)),462+ });463+464+ return yield* queue.advanceAnswer(requestId, command, {465+ ...report,466+ ratchets,467+ });468+ })469+ : queue.advanceAnswer(requestId, command, report),470+ answer: queue.answer,471+ });472+473+ const leave = (requestId: RequestId) =>474+ Ref.update(475+ running,476+ (under) => new Set([...under].filter((each) => each !== requestId))477+ );478+479+ const runs = AnswerRuns.of({480+ // A run already under way for the request is not started twice.481+ start: (requestId, queue) =>482+ Effect.gen(function* () {483+ const free = yield* Ref.modify(running, (under) =>484+ under.has(requestId)485+ ? [false, under]486+ : [true, new Set(under).add(requestId)]487+ );488+489+ if (free) {490+ yield* drive(counting(queue), requestId).pipe(491+ Effect.provideContext(ports),492+ Effect.ensuring(leave(requestId))493+ );494+ }495+ }),496+ });497+498+ return ports.pipe(Context.add(AnswerRuns, runs));499+ })500+ );501+502+const worldWith = (options: CheckerOptions = {}) =>503+ standIns(options).pipe(Layer.provideMerge(worldOf(scenario, "memory")));504+505+// --------------------------------------------------------------- reading506+507+/** Where canonical `main` stands now. */508+const mainTip = Effect.gen(function* () {509+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);510+511+ return LandedSha.make(512+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))513+ );514+});515+516+const commitOf = (sha: CommitSha) =>517+ Effect.gen(function* () {518+ const host = yield* RepoHost;519+ const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);520+ const { author, message, parents } = Option.getOrThrow(read);521+522+ return { author, parents, trailers: parseTrailers(message) };523+ });524+525+/** Whether a commit of the canonical repo holds a file at `path`. */526+const holds = (sha: CommitSha, path: string) =>527+ RepoHost.use((host) =>528+ host.readFile(repo, Revision.Commit({ sha }), RepoPath.make(path))529+ ).pipe(Effect.orDie, Effect.map(Option.isSome));530+531+/** Every file of a commit of the canonical repo, as the Pusher takes them. */532+const filesAt = (sha: CommitSha) =>533+ Effect.gen(function* () {534+ const host = yield* RepoHost;535+536+ const under = (tree: ObjectId, prefix: string): Effect.Effect<Files> =>537+ Effect.gen(function* () {538+ const entries = yield* host.readTree(repo, tree).pipe(Effect.orDie);539+540+ const nested = yield* Effect.forEach(541+ Option.getOrElse(entries, () => []),542+ ({ name, sha: id, type }) =>543+ type === "tree"544+ ? under(id, `${prefix}${name}/`)545+ : Effect.map(546+ host.readBlob(repo, id).pipe(Effect.orDie),547+ (bytes): Files => [548+ [549+ `${prefix}${name}`,550+ new TextDecoder().decode(551+ Option.getOrElse(bytes, () => new Uint8Array())552+ ),553+ ],554+ ]555+ )556+ );557+558+ return nested.flat();559+ });560+561+ const commit = yield* host.readCommit(repo, sha).pipe(Effect.orDie);562+563+ return yield* under(Option.getOrThrow(commit).tree, "");564+ });565+566+const ratchetRows = ProjectStore.use((store) => store.load()).pipe(567+ Effect.map(({ ratchets }) =>568+ ratchets.map(({ count, ratchet, territory }) => ({569+ count,570+ ratchet,571+ territory,572+ }))573+ )574+);575+576+const landingCount = ProjectStore.use((store) => store.load()).pipe(577+ Effect.map(({ landings }) => landings.length)578+);579+580+/** The open asks, by id, as anyone lists them. */581+const listed = (api: ProjectApi) =>582+ Effect.map(api.listAsks(anyone), ({ asks }) =>583+ asks.map(({ ask }) => ask).toSorted()584+ );585+586+const shown = (api: ProjectApi, id: AskId) =>587+ Effect.map(api.showAsk(anyone, id), ({ ask }) => ask);588+589+/** The project made from alice's first push; alice decides everything. */590+const fromFirstPush = (api: ProjectApi) =>591+ Effect.gen(function* () {592+ yield* api.initProject(alice, {});593+594+ const first = yield* Pusher.use((pusher) =>595+ pusher.push(repo, Option.none(), start, "Start")596+ );597+598+ yield* api.recordFirstPush(alice, first);599+ });600+601+/** `who` answers `ask` from their fork, with `change` made to the files at `base`. */602+const answer = (603+ api: ProjectApi,604+ input: {605+ readonly ask: AskId;606+ readonly base: LandedSha;607+ readonly change: (files: Files) => Files;608+ readonly who: Person;609+ }610+) =>611+ Effect.gen(function* () {612+ const fork = RepoName.make(`${project}--${input.ask}--${input.who.handle}`);613+ const files = yield* filesAt(input.base);614+615+ const head = yield* Pusher.use((pusher) =>616+ pusher.push(fork, Option.some(input.base), input.change(files))617+ );618+619+ return yield* api.submitAnswer(input.who, {620+ ask: input.ask,621+ base: input.base,622+ head,623+ requestId: RequestId.make(`req-${input.ask}`),624+ });625+ });626+627+/** Every call of `legacyFetch` in one package moved to `http.get`. */628+const migrated = (name: Package) => (files: Files) =>629+ changed(630+ files,631+ indexOf(name),632+ `export const run = () => {\n${calls("http.get", callers[name])}};\n`633+ );634+635+const outcomesOf = (api: ProjectApi, who: string) =>636+ Effect.map(api.status(person(who)), ({ answers }) =>637+ answers.map(({ outcome }) => outcome)638+ );639+640+// ------------------------------------------------------------- the story641+642+/**643+ * The whole family: alice opens a plain ask and the migrate ask, six644+ * people claim the six children at once and land them one by one, a plain645+ * answer that adds a caller is refused on the way, and the delete child646+ * lands last.647+ */648+const story = Effect.gen(function* () {649+ yield* advanceTo("2026-10-07T12:00:00Z");650+651+ const api = yield* projectService(project);652+ const host = yield* RepoHost;653+654+ yield* fromFirstPush(api);655+656+ // A plain ask in p6, opened before the family: ivan answers it mid-family.657+ yield* api.openAsk(alice, { ask: tidyId, files: plainFiles(tidyId) });658+659+ const parentFiles = Array.make(askFile(parentId));660+ const beforeFamily = yield* mainTip;661+662+ const opened = yield* api.openAsk(alice, {663+ ask: parentId,664+ files: parentFiles,665+ });666+667+ const atOpen = {668+ children: yield* Effect.forEach(childIds, (id) => shown(api, id)),669+ commit: yield* commitOf(opened.landed),670+ deleteChild: yield* shown(api, deleteId),671+ files: yield* Effect.forEach([parentId, ...childIds, deleteId], (id) =>672+ holds(opened.landed, `${Brand.configDir}/asks/${id}.ask.ts`)673+ ),674+ listed: yield* listed(api),675+ ratchets: yield* ratchetRows,676+ };677+678+ const landingsBefore = yield* landingCount;679+680+ const replay = yield* api.openAsk(alice, {681+ ask: parentId,682+ files: parentFiles,683+ });684+685+ const afterReplay = {686+ landings: (yield* landingCount) - landingsBefore,687+ listed: yield* listed(api),688+ main: yield* mainTip,689+ ratchets: yield* ratchetRows,690+ };691+692+ const refusedEarly = {693+ deleteChild: yield* api.claim(person("heidi"), deleteId).pipe(Effect.flip),694+ parent: yield* api.claim(person("heidi"), parentId).pipe(Effect.flip),695+ };696+697+ // Six people claim the six children at once.698+ const claims = yield* Effect.forEach(699+ Array.zip(answerers, childIds),700+ ([who, id]) => api.claim(person(who), id),701+ { concurrency: "unbounded" }702+ );703+704+ const forks = yield* Effect.forEach(claims, ({ claim }) =>705+ Effect.map(Effect.exit(host.refs(claim.fork)), Exit.isSuccess)706+ );707+708+ const tidyClaim = yield* api.claim(person("ivan"), tidyId);709+710+ /** Child `n`'s claimant answers it from where they claimed, and it lands. */711+ const landChild = (n: number) =>712+ Effect.gen(function* () {713+ const name = packages[n] ?? "p1";714+715+ yield* answer(api, {716+ ask: childIdOf(name),717+ base: opened.landed,718+ change: migrated(name),719+ who: person(answerers[n] ?? "bob"),720+ });721+722+ return yield* mainTip;723+ });724+725+ const firstThree = yield* Effect.forEach([0, 1, 2], landChild);726+727+ const midFamily = {728+ deleteClaim: yield* api.claim(person("heidi"), deleteId).pipe(Effect.flip),729+ main: yield* mainTip,730+ ratchets: yield* ratchetRows,731+ };732+733+ // ivan's answer to the plain ask adds one more caller in p6.734+ yield* answer(api, {735+ ask: tidyId,736+ base: LandedSha.make(tidyClaim.claim.base),737+ change: (files) =>738+ changed(739+ files,740+ extraOf("p6"),741+ `export const extra = () => {\n${calls(symbol, 1)}};\n`742+ ),743+ who: person("ivan"),744+ });745+746+ const tidyAfter = {747+ main: yield* mainTip,748+ outcomes: yield* outcomesOf(api, "ivan"),749+ };750+751+ const lastThree = yield* Effect.forEach([3, 4, 5], landChild);752+753+ const afterSix = {754+ deleteChild: yield* shown(api, deleteId),755+ parent: yield* shown(api, parentId),756+ };757+758+ const deleteClaim = yield* api.claim(person("heidi"), deleteId);759+760+ yield* answer(api, {761+ ask: deleteId,762+ base: LandedSha.make(deleteClaim.claim.base),763+ change: (files) => changed(files, legacyFile),764+ who: person("heidi"),765+ });766+767+ const deleteLanded = yield* mainTip;768+ const childrenLanded = [...firstThree, ...lastThree];769+770+ return {771+ afterReplay,772+ afterSix,773+ atOpen,774+ beforeFamily,775+ childrenLanded,776+ claims,777+ deleteLanded,778+ events: (yield* api.events(0, 1000)).map(({ event }) => event),779+ forks,780+ landings: yield* Effect.forEach(781+ [...childrenLanded, deleteLanded],782+ commitOf783+ ),784+ listedAtEnd: yield* listed(api),785+ midFamily,786+ opened,787+ outcomes: yield* Effect.forEach([...answerers, "heidi"], (who) =>788+ outcomesOf(api, who)789+ ),790+ parentAtEnd: yield* shown(api, parentId),791+ ratchetsAtEnd: yield* ratchetRows,792+ refusedEarly,793+ replay,794+ tidyAfter,795+ };796+});797+798+/** What the story saw, told once and read by every case below. */799+class Seen extends Context.Service<Seen, Effect.Success<typeof story>>()(800+ "test/Seen"801+) {}802+803+/**804+ * The story runs a family of eight asks over real git objects: about three805+ * seconds alone, more while turbo runs every package's tests at once. The806+ * limit catches a hang, not a busy machine.807+ */808+const wholeStory = { timeout: 60_000 };809+810+const seen = Seen.useSync((told) => told);811+812+/** The story's events of one kind. */813+const eventsOf = <T extends ProjectEvent["_tag"]>(814+ events: readonly ProjectEvent[],815+ tag: T816+) =>817+ events.filter(818+ (event): event is Extract<ProjectEvent, { readonly _tag: T }> =>819+ event._tag === tag820+ );821+822+const askedByAlice = {823+ key: "Asked-by",824+ value: `alice <alice@users.${Brand.domain}>`,825+};826+827+layer(Layer.effect(Seen, story).pipe(Layer.provide(worldWith())), wholeStory)(828+ "a migrate ask over six packages",829+ (cases) => {830+ cases.effect(831+ "1. opens as one platform commit adding the parent, the six children and the delete child",832+ () =>833+ Effect.map(seen, ({ atOpen, beforeFamily, opened }) => {834+ expect({835+ asked: atOpen.commit.trailers.filter(836+ ({ key }) => key === "Asked-by"837+ ),838+ author: atOpen.commit.author,839+ files: atOpen.files,840+ opened: opened.ask.id,841+ parents: atOpen.commit.parents,842+ }).toStrictEqual({843+ asked: [askedByAlice],844+ author: authorLine(alice.handle),845+ files: Array.makeBy(8, () => true),846+ opened: parentId,847+ parents: [beforeFamily],848+ });849+ expect(atOpen.listed).toStrictEqual(850+ [tidyId, parentId, ...childIds, deleteId].toSorted()851+ );852+ })853+ );854+855+ cases.effect("1. gives each child its own package as its territory", () =>856+ Effect.map(seen, ({ atOpen }) => {857+ expect(858+ atOpen.children.map(({ brief, check, parent, territory }) => ({859+ check: check._tag,860+ parent,861+ territory: territory.paths,862+ want: brief.want,863+ }))864+ ).toStrictEqual(865+ packages.map((name) => ({866+ check: "Migrate",867+ parent: parentId,868+ territory: [Glob.make(`packages/${name}/**`)],869+ want: `${name}: ${callers[name]} callers of legacyFetch → http.get`,870+ }))871+ );872+ })873+ );874+875+ cases.effect(876+ "1. blocks the delete child on the six, and the parent on all seven",877+ () =>878+ Effect.map(seen, ({ atOpen, opened }) => {879+ expect({880+ blockedBy: atOpen.deleteChild.blockedBy,881+ check: atOpen.deleteChild.check,882+ parent: atOpen.deleteChild.parent,883+ state: atOpen.deleteChild.state,884+ }).toStrictEqual({885+ blockedBy: childIds,886+ check: CheckSpec.cases.SymbolAbsent.make({887+ count: countOf(symbol),888+ symbol: SymbolName.make(symbol),889+ }),890+ parent: parentId,891+ state: "waitingOnParent",892+ });893+ expect(opened.ask.blockedBy).toStrictEqual([...childIds, deleteId]);894+ })895+ );896+897+ cases.effect("1. records the callers ratchet at the counted total", () =>898+ Effect.map(seen, ({ atOpen }) => {899+ expect(atOpen.ratchets).toStrictEqual([900+ { count: total, ratchet: ratchetName, territory: "." },901+ ]);902+ })903+ );904+905+ cases.effect("opening it again converges on the same family", () =>906+ Effect.map(seen, ({ afterReplay, atOpen, opened, replay }) => {907+ expect(replay).toStrictEqual(opened);908+ expect(afterReplay).toStrictEqual({909+ landings: 0,910+ listed: atOpen.listed,911+ main: opened.landed,912+ ratchets: atOpen.ratchets,913+ });914+ })915+ );916+917+ cases.effect(918+ "2. refuses a claim on the delete child, or on the parent, as blocked",919+ () =>920+ Effect.map(seen, ({ refusedEarly }) => {921+ expect(refusedEarly).toStrictEqual({922+ deleteChild: AskBlocked.of(deleteId, childIds),923+ parent: AskBlocked.of(parentId, Array.append(childIds, deleteId)),924+ });925+ })926+ );927+928+ cases.effect(929+ "3. lets six people claim the six children at once, each in a fork",930+ () =>931+ Effect.map(seen, ({ claims, forks }) => {932+ expect(933+ claims.map(({ claim }) => [claim.ask, claim.claimant])934+ ).toStrictEqual(Array.zip(childIds, answerers));935+ expect(forks).toStrictEqual(Array.makeBy(6, () => true));936+ })937+ );938+939+ cases.effect(940+ "4. lands the six answers in turn, none stale, each authored by its claimant and asked by alice",941+ () =>942+ Effect.map(seen, ({ landings, outcomes, childrenLanded }) => {943+ expect(outcomes.slice(0, 6)).toStrictEqual(944+ childrenLanded.map((sha) => [Outcome.cases.Landed.make({ sha })])945+ );946+ expect(947+ landings.slice(0, 6).map(({ author, trailers }) => ({948+ asked: trailers.filter(({ key }) => key === "Asked-by"),949+ author,950+ }))951+ ).toStrictEqual(952+ answerers.map((who) => ({953+ asked: [askedByAlice],954+ author: authorLine(Handle.make(who)),955+ }))956+ );957+ })958+ );959+960+ cases.effect(961+ "5. still refuses the delete child after three land, naming the three still open",962+ () =>963+ Effect.map(seen, ({ midFamily }) => {964+ expect(midFamily.deleteClaim).toStrictEqual(965+ AskBlocked.of(966+ deleteId,967+ Array.map(["p4", "p5", "p6"] as const, childIdOf)968+ )969+ );970+ })971+ );972+973+ cases.effect("lowers the callers ratchet as each child lands", () =>974+ Effect.map(seen, ({ midFamily, ratchetsAtEnd }) => {975+ expect([midFamily.ratchets, ratchetsAtEnd]).toStrictEqual([976+ [977+ {978+ count: total - callers.p1 - callers.p2 - callers.p3,979+ ratchet: ratchetName,980+ territory: ".",981+ },982+ ],983+ [{ count: 0, ratchet: ratchetName, territory: "." }],984+ ]);985+ })986+ );987+988+ cases.effect(989+ "7. refuses a plain answer that adds a caller mid-family as a weakened ratchet, and lands nothing",990+ () =>991+ Effect.map(seen, ({ midFamily, tidyAfter }) => {992+ const before = total - callers.p1 - callers.p2 - callers.p3;993+994+ expect(tidyAfter).toStrictEqual({995+ main: midFamily.main,996+ outcomes: [997+ Outcome.cases.Refused.make({998+ refusals: [999+ new Weakened({1000+ weakening: {1001+ after: before + 1,1002+ before,1003+ ratchet: ratchetName,1004+ territory: ".",1005+ },1006+ }),1007+ ],1008+ }),1009+ ],1010+ });1011+ })1012+ );1013+1014+ cases.effect(1015+ "6. opens the delete child once the six land, while the parent waits on it",1016+ () =>1017+ Effect.map(seen, ({ afterSix, events }) => {1018+ expect([1019+ afterSix.deleteChild.state,1020+ afterSix.parent.state,1021+ ]).toStrictEqual(["open", "open"]);1022+ expect(1023+ eventsOf(events, "AskOpened")1024+ .map(({ ask }) => ask.ask)1025+ .filter((id) => id === deleteId)1026+ ).toStrictEqual([deleteId]);1027+ })1028+ );1029+1030+ cases.effect(1031+ "6. lands the delete child by heidi, and closes the parent on that landing",1032+ () =>1033+ Effect.map(1034+ seen,1035+ ({1036+ deleteLanded,1037+ events,1038+ landings,1039+ listedAtEnd,1040+ outcomes,1041+ parentAtEnd,1042+ }) => {1043+ expect({1044+ author: landings[6]?.author,1045+ outcome: outcomes[6],1046+ parent: parentAtEnd.state,1047+ }).toStrictEqual({1048+ author: authorLine(Handle.make("heidi")),1049+ outcome: [Outcome.cases.Landed.make({ sha: deleteLanded })],1050+ parent: "closed",1051+ });1052+ expect(listedAtEnd).toStrictEqual([tidyId]);1053+ expect(1054+ eventsOf(events, "AskClosed").filter(1055+ ({ ask }) => ask === parentId1056+ )1057+ ).toStrictEqual([1058+ expect.objectContaining({ ask: parentId, landing: deleteLanded }),1059+ ]);1060+ }1061+ )1062+ );1063+ }1064+);1065+1066+/**1067+ * The six answers pushed and submitted at once, as six agents would: every1068+ * one but the first is checked on a tree merged onto a main that moved, and1069+ * still lands, through the serial queue, with the callers ratchet at zero.1070+ */1071+const allAtOnce = Effect.gen(function* () {1072+ yield* advanceTo("2026-10-07T12:00:00Z");1073+1074+ const api = yield* projectService(project);1075+1076+ yield* fromFirstPush(api);1077+1078+ const opened = yield* api.openAsk(alice, {1079+ ask: parentId,1080+ files: Array.make(askFile(parentId)),1081+ });1082+1083+ const children = Array.zip(packages, answerers);1084+1085+ yield* Effect.forEach(1086+ children,1087+ ([name, who]) => api.claim(person(who), childIdOf(name)),1088+ { concurrency: "unbounded" }1089+ );1090+1091+ yield* Effect.forEach(1092+ children,1093+ ([name, who]) =>1094+ answer(api, {1095+ ask: childIdOf(name),1096+ base: opened.landed,1097+ change: migrated(name),1098+ who: person(who),1099+ }),1100+ { concurrency: "unbounded" }1101+ );1102+1103+ // Whatever waits on a retry runs at the project's next alarms.1104+ yield* api.onAlarm();1105+ yield* advanceTo("2026-10-07T12:10:00Z");1106+ yield* api.onAlarm();1107+1108+ return {1109+ deleteChild: (yield* shown(api, deleteId)).state,1110+ outcomes: yield* Effect.forEach(answerers, (who) =>1111+ Effect.map(outcomesOf(api, who), (all) => all.map(({ _tag }) => _tag))1112+ ),1113+ ratchets: yield* ratchetRows,1114+ };1115+}).pipe(Effect.provide(worldWith()));1116+1117+describe("six answers to the six children at once", () => {1118+ it.effect(1119+ "all land, none stale and none refused by the callers ratchet",1120+ () =>1121+ Effect.map(allAtOnce, (seenThen) => {1122+ expect(seenThen).toStrictEqual({1123+ deleteChild: "open",1124+ outcomes: Array.makeBy(6, () => ["Landed"]),1125+ ratchets: [{ count: 0, ratchet: ratchetName, territory: "." }],1126+ });1127+ }),1128+ wholeStory1129+ );1130+});1131+1132+// ---------------------------------------------------- other openings1133+1134+/** alice opens one ask of the scenario by its file alone, on a project fresh from its first push. */1135+const openingOf = (id: string, options: CheckerOptions = {}) =>1136+ Effect.gen(function* () {1137+ yield* advanceTo("2026-10-07T12:00:00Z");1138+1139+ const api = yield* projectService(project);1140+1141+ yield* fromFirstPush(api);1142+1143+ const opened = yield* Effect.result(1144+ api.openAsk(alice, {1145+ ask: AskId.make(id),1146+ files: Array.make(askFile(id)),1147+ })1148+ );1149+1150+ return {1151+ landings: yield* landingCount,1152+ listed: yield* listed(api),1153+ opened,1154+ ratchets: yield* ratchetRows,1155+ };1156+ }).pipe(Effect.provide(worldWith(options)));1157+1158+/**1159+ * A migrate ask over p2 lands and closes, leaving its callers ratchet at1160+ * 30; with no migrate ask open nothing counts callers, so ivan's answer1161+ * adds one in p6 and lands; then alice opens the family over 31 callers.1162+ */1163+const reopening = Effect.gen(function* () {1164+ yield* advanceTo("2026-10-07T12:00:00Z");1165+1166+ const api = yield* projectService(project);1167+ const onePackage = AskId.make("move-p2-fetch");1168+1169+ yield* fromFirstPush(api);1170+ yield* api.openAsk(alice, {1171+ ask: onePackage,1172+ files: Array.make(askFile(onePackage)),1173+ });1174+1175+ const moving = yield* api.claim(person("bob"), onePackage);1176+1177+ yield* answer(api, {1178+ ask: onePackage,1179+ base: LandedSha.make(moving.claim.base),1180+ change: migrated("p2"),1181+ who: person("bob"),1182+ });1183+1184+ yield* api.openAsk(alice, { ask: tidyId, files: plainFiles(tidyId) });1185+1186+ const tidying = yield* api.claim(person("ivan"), tidyId);1187+1188+ yield* answer(api, {1189+ ask: tidyId,1190+ base: LandedSha.make(tidying.claim.base),1191+ change: (files) =>1192+ changed(1193+ files,1194+ extraOf("p6"),1195+ `export const extra = () => {\n${calls(symbol, 1)}};\n`1196+ ),1197+ who: person("ivan"),1198+ });1199+1200+ const left = yield* ratchetRows;1201+1202+ yield* api.openAsk(alice, {1203+ ask: parentId,1204+ files: Array.make(askFile(parentId)),1205+ });1206+1207+ return { left, opened: yield* ratchetRows };1208+}).pipe(Effect.provide(worldWith()));1209+1210+/** alice opens p1's child ask alone first, then the migrate ask whose family would write that file again. */1211+const overwriting = Effect.gen(function* () {1212+ yield* advanceTo("2026-10-07T12:00:00Z");1213+1214+ const api = yield* projectService(project);1215+ const p1 = childIdOf("p1");1216+1217+ yield* fromFirstPush(api);1218+ yield* api.openAsk(alice, { ask: p1, files: Array.make(askFile(p1)) });1219+1220+ const main = yield* mainTip;1221+1222+ const opened = yield* Effect.result(1223+ api.openAsk(alice, {1224+ ask: parentId,1225+ files: Array.make(askFile(parentId)),1226+ })1227+ );1228+1229+ return {1230+ listed: yield* listed(api),1231+ main,1232+ mainAfter: yield* mainTip,1233+ opened,1234+ };1235+}).pipe(Effect.provide(worldWith()));1236+1237+describe("opening a migrate ask", () => {1238+ it.effect(1239+ "is refused TouchedJudge when a child's file would replace an ask the project holds",1240+ () =>1241+ Effect.map(overwriting, ({ listed: open, main, mainAfter, opened }) => {1242+ expect({ listed: open, mainAfter, opened }).toStrictEqual({1243+ listed: [childIdOf("p1")],1244+ mainAfter: main,1245+ opened: Result.fail(1246+ new TouchedJudge({1247+ paths: [1248+ RepoPath.make(1249+ `${Brand.configDir}/asks/${childIdOf("p1")}.ask.ts`1250+ ),1251+ ],1252+ })1253+ ),1254+ });1255+ }),1256+ wholeStory1257+ );1258+1259+ it.effect(1260+ "is refused NotRedFirst when the two counts on main differ",1261+ () =>1262+ Effect.map(openingOf(parentId, { drifting: true }), (seenThen) => {1263+ expect(seenThen).toStrictEqual({1264+ landings: 1,1265+ listed: [],1266+ opened: Result.fail(new NotRedFirst({})),1267+ ratchets: [],1268+ });1269+ }),1270+ wholeStory1271+ );1272+1273+ it.effect(1274+ "is refused NotRedFirst when nothing calls the name: nothing to migrate",1275+ () =>1276+ Effect.map(openingOf("drop-old-thing"), ({ listed: open, opened }) => {1277+ expect([open, opened]).toStrictEqual([1278+ [],1279+ Result.fail(new NotRedFirst({})),1280+ ]);1281+ }),1282+ wholeStory1283+ );1284+1285+ it.effect(1286+ "records the callers ratchet at the counted total, over a lower one a closed migrate ask left",1287+ () =>1288+ Effect.map(reopening, (seenThen) => {1289+ expect(seenThen).toStrictEqual({1290+ left: [1291+ { count: total - callers.p2, ratchet: ratchetName, territory: "." },1292+ ],1293+ opened: [1294+ {1295+ count: total - callers.p2 + 1,1296+ ratchet: ratchetName,1297+ territory: ".",1298+ },1299+ ],1300+ });1301+ }),1302+ wholeStory1303+ );1304+1305+ it.effect(1306+ "opens as one plain ask, with no family, when its territory is one package",1307+ () =>1308+ Effect.map(1309+ openingOf("move-p2-fetch"),1310+ ({ listed: open, opened, ratchets }) => {1311+ expect({1312+ blockedBy: Result.map(opened, ({ ask }) => ask.blockedBy),1313+ listed: open,1314+ ratchets,1315+ }).toStrictEqual({1316+ blockedBy: Result.succeed([]),1317+ listed: [AskId.make("move-p2-fetch")],1318+ ratchets: [{ count: total, ratchet: ratchetName, territory: "." }],1319+ });1320+ }1321+ ),1322+ wholeStory1323+ );1324+});1325+1326+// ------------------------------------------------------ the pure split1327+1328+const parent: Ask = askOf(parentId);1329+1330+const { modules } = scenario.policy;1331+1332+const counted = (byModule: Readonly<Record<string, number>>): CallerCount => ({1333+ byModule,1334+ total: Object.values(byModule).reduce((sum, n) => sum + n, 0),1335+});1336+1337+const split = (1338+ byModule: Readonly<Record<string, number>>,1339+ of: Ask = parent1340+): Option.Option<MigrateFamily> =>1341+ splitFamily({1342+ configDir: Brand.configDir,1343+ counts: counted(byModule),1344+ modules,1345+ parent: of,1346+ });1347+1348+/** The fields a family's asks are compared by. */1349+const comparable = (ask: Ask) =>1350+ Struct.pick(ask, [1351+ "blockedBy",1352+ "check",1353+ "file",1354+ "id",1355+ "kind",1356+ "parent",1357+ "state",1358+ "territory",1359+ ]);1360+1361+describe(splitFamily, () => {1362+ it("splits as testkit's sixChildren() is written by hand: six children and a delete child", () => {1363+ const made = Option.getOrThrow(split(callers));1364+ const byHand = new Map(family.policy.asks.map((ask) => [ask.id, ask]));1365+1366+ const expected = (id: AskId, state: Ask["state"]) => {1367+ const {1368+ blockedBy,1369+ check,1370+ file,1371+ kind,1372+ parent: of,1373+ territory,1374+ } = byHand.get(id) ?? parent;1375+1376+ return { blockedBy, check, file, id, kind, parent: of, state, territory };1377+ };1378+1379+ expect([...made.children, made.deleteChild].map(comparable)).toStrictEqual([1380+ ...childIds.map((id) => expected(id, "open")),1381+ expected(deleteId, "waitingOnParent"),1382+ ]);1383+ expect({1384+ blockedBy: made.parent.blockedBy,1385+ files: made.files.map(({ path }) => path),1386+ ratchet: made.ratchet,1387+ }).toStrictEqual({1388+ blockedBy: [...childIds, deleteId],1389+ files: [...childIds, deleteId].map((id) =>1390+ RepoPath.make(`${Brand.configDir}/asks/${id}.ask.ts`)1391+ ),1392+ ratchet: { baseline: total, name: ratchetName },1393+ });1394+ });1395+1396+ it("gives no child to a module with no callers", () => {1397+ expect(1398+ Option.map(split({ ...callers, p3: 0 }), ({ children }) =>1399+ children.map(({ id }) => id)1400+ )1401+ ).toStrictEqual(1402+ Option.some(Array.map(["p1", "p2", "p4", "p5", "p6"] as const, childIdOf))1403+ );1404+ });1405+1406+ it("gives no child to a module outside the parent's territory", () => {1407+ const narrower: Ask = {1408+ ...parent,1409+ territory: {1410+ module: ".",1411+ paths: [Glob.make("packages/p1/**"), Glob.make("packages/p2/**")],1412+ },1413+ };1414+1415+ expect(1416+ Option.map(split(callers, narrower), ({ children }) =>1417+ children.map(({ id }) => id)1418+ )1419+ ).toStrictEqual(Option.some(Array.map(["p1", "p2"] as const, childIdOf)));1420+ });1421+1422+ it.each([1423+ ["only one module has callers", { p2: 7 }, parent],1424+ [1425+ "the territory names one package",1426+ callers,1427+ { ...parent, territory: modules[1] ?? parent.territory },1428+ ],1429+ [1430+ "the ask is no migrate ask",1431+ callers,1432+ {1433+ ...parent,1434+ check: CheckSpec.cases.SymbolAbsent.make({1435+ count: countOf(symbol),1436+ symbol: SymbolName.make(symbol),1437+ }),1438+ },1439+ ],1440+ ] as const)("does not split when %s", (_, byModule, of) => {1441+ expect(split(byModule, of)).toStrictEqual(Option.none());1442+ });1443+1444+ it("holds every child to the parent's asker, kind and reserve", () => {1445+ const reserved: Ask = {1446+ ...parent,1447+ mentor: Handle.make("alice"),1448+ reserve: "newcomers",1449+ };1450+1451+ const made = Option.getOrThrow(split(callers, reserved));1452+1453+ expect(1454+ [...made.children, made.deleteChild].map((ask) =>1455+ Struct.pick(ask, ["askedBy", "kind", "mentor", "reserve"])1456+ )1457+ ).toStrictEqual(1458+ Array.makeBy(7, () => ({1459+ askedBy: parent.askedBy,1460+ kind: KindName.make("migrate"),1461+ mentor: Handle.make("alice"),1462+ reserve: "newcomers",1463+ }))1464+ );1465+ });1466+});1467+1468+describe(callersIn, () => {1469+ const twoPackages: Territory = {1470+ module: ".",1471+ paths: [Glob.make("packages/p1/**"), Glob.make("packages/p2/**")],1472+ };1473+1474+ it.each([1475+ ["the one package it names", modules[1] ?? parent.territory, 7],1476+ ["every package", parent.territory, total],1477+ ["two of the six packages", twoPackages, callers.p1 + callers.p2],1478+ ] as const)("counts the callers in %s", (_, territory, count) => {1479+ expect(callersIn(territory, counted(callers), modules)).toStrictEqual(1480+ count1481+ );1482+ });1483+});1484+1485+describe(childId, () => {1486+ it.each([1487+ ["p1", "drop-legacy-fetch-p1"],1488+ ["@burrow/http-kit", "drop-legacy-fetch-burrow-http-kit"],1489+ ["--Odd__Name--", "drop-legacy-fetch-odd-name"],1490+ ])("names %s's child %s, an ask id with no --", (module, id) => {1491+ const named = childId(parentId, module);1492+1493+ expect([1494+ named,1495+ named.includes("--"),1496+ Schema.is(AskId)(named),1497+ ]).toStrictEqual([id, false, true]);1498+ });1499+1500+ it("names the delete child apart from every child", () => {1501+ expect(deleteChildId(parentId)).toStrictEqual(deleteId);1502+ });1503+});1504+1505+/** The family as it stands once the children in `closed` have landed. */1506+const standing = (closed: readonly Package[]) => {1507+ const made = Option.getOrThrow(split(callers));1508+1509+ return new Map(1510+ [made.parent, ...made.children, made.deleteChild].map((ask) => [1511+ ask.id,1512+ packages.some(1513+ (name) => closed.includes(name) && childIdOf(name) === ask.id1514+ )1515+ ? { ...ask, state: "closed" as const }1516+ : ask,1517+ ])1518+ );1519+};1520+1521+describe(remainingBlockers, () => {1522+ it("names the children still open, in order", () => {1523+ const asks = standing(["p1", "p3", "p5"]);1524+1525+ expect(1526+ remainingBlockers(1527+ Option.getOrThrow(Option.fromUndefinedOr(asks.get(deleteId))),1528+ asks1529+ )1530+ ).toStrictEqual(Array.map(["p2", "p4", "p6"] as const, childIdOf));1531+ });1532+1533+ it("names none once every child has closed", () => {1534+ const asks = standing(packages);1535+1536+ expect(1537+ remainingBlockers(1538+ Option.getOrThrow(Option.fromUndefinedOr(asks.get(deleteId))),1539+ asks1540+ )1541+ ).toStrictEqual([]);1542+ });1543+1544+ it("keeps an ask it does not know as blocking", () => {1545+ const ghost = AskId.make("never-opened");1546+1547+ expect(1548+ remainingBlockers({ ...parent, blockedBy: [ghost] }, new Map())1549+ ).toStrictEqual([ghost]);1550+ });1551+});1552+1553+describe(familyClosed, () => {1554+ it("is false while the delete child is open, and true once it closes", () => {1555+ const asks = standing(packages);1556+1557+ const deleteChild = Option.getOrThrow(1558+ Option.fromUndefinedOr(asks.get(deleteId))1559+ );1560+1561+ expect([1562+ familyClosed(parentId, asks),1563+ familyClosed(1564+ parentId,1565+ new Map(asks).set(deleteId, { ...deleteChild, state: "closed" })1566+ ),1567+ ]).toStrictEqual([false, true]);1568+ });1569+1570+ it("is false for an ask with no children", () => {1571+ expect([familyClosed(tidyId, standing([]))]).toStrictEqual([false]);1572+ });1573+});1574+1575+// ------------------------------------------- the files the family lands1576+1577+/** The six packages as workspaces, and alice as the project's initializer. */1578+const facts = Schema.decodeSync(EvaluationFacts)({1579+ ci: [],1580+ initializer: "alice",1581+ now: "2026-10-07T12:00:00.000Z",1582+ project,1583+ seed: 7,1584+ workspaces: packages.map((name) => ({1585+ dir: `packages/${name}`,1586+ exports: [],1587+ name,1588+ })),1589+});1590+1591+const projectFile = [1592+ `import { kinds, project } from "${Brand.cliPackage}/rules";`,1593+ "",1594+ "export default project({",1595+ " kinds: [kinds.migrate],",1596+ ' run: { checks: {}, test: "bun test {path}" },',1597+ "});",1598+ "",1599+].join("\n");1600+1601+/** The fields an ask file states, as the evaluator reads them back. */1602+const stated = (ask: Ask) =>1603+ Struct.pick(ask, [1604+ "blockedBy",1605+ "brief",1606+ "check",1607+ "file",1608+ "id",1609+ "kind",1610+ "parent",1611+ "territory",1612+ ]);1613+1614+/** What asks' files state, by id: the evaluator reads ask files in path order. */1615+const byId = (asks: readonly Ask[]) =>1616+ asks.map(stated).toSorted((a, b) => a.id.localeCompare(b.id));1617+1618+/** The family of `of`'s files, as the rules evaluator reads them back from a config folder. */1619+const evaluatedFamily = (of: Ask) =>1620+ Effect.gen(function* () {1621+ const made = Option.getOrThrow(split(callers, of));1622+ const evaluator = yield* RulesEvaluator;1623+1624+ const policy = yield* evaluator.evaluate({1625+ at: LandedSha.make("a".repeat(40)),1626+ facts,1627+ modules: {1628+ entry: `${Brand.configDir}/project.ts`,1629+ modules: {1630+ [`${Brand.configDir}/project.ts`]: projectFile,1631+ ...Object.fromEntries(1632+ made.files.map(({ content, path }) => [path, content])1633+ ),1634+ },1635+ sdkVersion,1636+ },1637+ });1638+1639+ return {1640+ evaluated: byId(policy.asks),1641+ family: byId([...made.children, made.deleteChild]),1642+ };1643+ }).pipe(1644+ Effect.provide(1645+ RulesEvaluatorBun.pipe(1646+ Layer.provide(Layer.mergeAll(FinishersFromChecks, NodeServices.layer))1647+ )1648+ )1649+ );1650+1651+describe("the family's ask files", () => {1652+ it.live(1653+ "evaluate, through the sdk, to the family's children and its delete child",1654+ () =>1655+ Effect.map(evaluatedFamily(parent), ({ evaluated, family: written }) => {1656+ expect(evaluated).toStrictEqual(written);1657+ }),1658+ wholeStory1659+ );1660+1661+ it.live(1662+ "keep the parent's kind when it is a migrate kind of another name",1663+ () =>1664+ Effect.map(1665+ evaluatedFamily({ ...parent, kind: KindName.make("dropApi") }),1666+ ({ evaluated, family: written }) => {1667+ expect([1668+ evaluated,1669+ Array.dedupe(evaluated.map(({ kind }) => kind)),1670+ ]).toStrictEqual([written, [KindName.make("dropApi")]]);1671+ }1672+ ),1673+ wholeStory1674+ );1675+});