migrate.ts
This file
Path
packages/project/src/migrate.ts
301 lines · 8.8 KiB · TypeScript
Last changed by
Merge build/comments-project into mainoscabrielbefore adoption49efd2a
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–55why, one step back1import { Brand } from "@repo/brand";2import { matchAny } from "@repo/gate/glob";3import type { Ask } from "@repo/protocol/domain/ask";4import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";5import type { RatchetSpec } from "@repo/protocol/domain/check";6import { JsonPath, NoneOrMore } from "@repo/protocol/domain/common";7import type { Command, SymbolName } from "@repo/protocol/domain/common";8import type { Territory } from "@repo/protocol/domain/territory";9import { AskId, RatchetName, RepoPath } from "@repo/protocol/ids";10import { Array, Option, Schema } from "effect";1112export const CallerCount = Schema.Struct({13 byModule: Schema.Record(Schema.String, NoneOrMore),14 total: NoneOrMore,15});1617export type CallerCount = typeof CallerCount.Type;1819export const callerCountOf = Schema.decodeUnknownOption(20 Schema.fromJsonString(CallerCount)21);2223export const sameCount = (one: CallerCount, other: CallerCount): boolean =>24 one.total === other.total &&25 Array.dedupe([26 ...Object.keys(one.byModule),27 ...Object.keys(other.byModule),28 ]).every(29 (module) => (one.byModule[module] ?? 0) === (other.byModule[module] ?? 0)30 );3132type MigrateCheck = Extract<CheckSpec, { readonly _tag: "Migrate" }>;3334export interface FamilyFile {35 readonly content: string;36 readonly path: RepoPath;37}3839export interface MigrateFamily {40 readonly parent: Ask;41 readonly children: Array.NonEmptyReadonlyArray<Ask>;42 readonly deleteChild: Ask;43 readonly files: Array.NonEmptyReadonlyArray<FamilyFile>;44 readonly ratchet: {45 readonly name: RatchetName;46 readonly baseline: number;47 };48}4950const slug = (name: string) =>51 name52 .toLowerCase()53 .replaceAll(/[^a-z0-9]+/gu, "-")54 .replaceAll(/^-+|-+$/gu, "");55Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 56why, one step back56/** Never holds `--`, which repo names keep as their separator. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 57–93why, one step back57export const childId = (parent: AskId, module: string): AskId =>58 AskId.make(`${parent}-${slug(module) || "root"}`);5960export const deleteChildId = (parent: AskId): AskId =>61 AskId.make(`${parent}-delete`);6263export const callersRatchet = (from: SymbolName): RatchetName =>64 RatchetName.make(`callers-${slug(from) || "name"}`);6566export const remainingBlockers = (67 ask: Ask,68 asks: ReadonlyMap<AskId, Ask>69): readonly AskId[] =>70 ask.blockedBy.filter((blocker) => asks.get(blocker)?.state !== "closed");7172export const familyClosed = (73 parent: AskId,74 asks: ReadonlyMap<AskId, Ask>75): boolean => {76 const members = [...asks.values()].filter((ask) => ask.parent === parent);7778 return members.length > 0 && members.every(({ state }) => state === "closed");79};8081export const modulesWithin = (82 territory: Territory,83 modules: readonly Territory[]84): readonly Territory[] => {85 const named = modules.filter(({ module }) => module === territory.module);8687 return named.length > 088 ? named89 : modules.filter(({ paths }) =>90 paths.every((glob) => matchAny(territory.paths, glob))91 );92};93Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 94why, one step back94/** In its module when the territory names one; in the modules it spans when some but not all; else everywhere. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 95–182why, one step back95export const callersIn = (96 territory: Territory,97 counts: CallerCount,98 modules: readonly Territory[]99): number => {100 const within = modulesWithin(territory, modules);101102 return within.length === 0 || within.length === modules.length103 ? counts.total104 : within.reduce(105 (sum, { module }) => sum + (counts.byModule[module] ?? 0),106 0107 );108};109110export const callersSpec = (check: MigrateCheck): RatchetSpec => ({111 measure: RatchetMeasure.cases.Metric.make({112 command: check.count,113 path: JsonPath.make("$.total"),114 }),115 name: callersRatchet(check.from),116});117118export const callersSpecs = (asks: Iterable<Ask>): readonly RatchetSpec[] =>119 Array.dedupeWith(120 [...asks].flatMap(({ check, state }) =>121 CheckSpec.guards.Migrate(check) && state !== "closed"122 ? [callersSpec(check)]123 : []124 ),125 (one, other) => one.name === other.name126 );127128const quoted = (text: string) => JSON.stringify(text);129130const header = (parent: AskId) =>131 `// A child of the migrate ask ${parent}, written by ${Brand.name} when it opened.`;132133const sdk = quoted(`${Brand.cliPackage}/rules`);134135const fields = (entries: readonly (readonly [string, string])[]) =>136 entries.map(([key, value]) => ` ${key}: ${value},`);137138const childFile = (child: Ask, check: MigrateCheck, parent: AskId) => {139 const stated: (readonly [string, string])[] = [140 ["parent", quoted(parent)],141 ["territory", `territory.package(${quoted(child.territory.module)})`],142 ["want", quoted(child.brief.want)],143 ];144145 const args: (readonly [string, string])[] = [146 ["count", quoted(check.count)],147 ["from", quoted(check.from)],148 ...(check.to === undefined ? [] : [["to", quoted(check.to)] as const]),149 ];150151 if (child.kind === "migrate") {152 return [153 header(parent),154 `import { kinds, territory } from ${sdk};`,155 "",156 "export default kinds.migrate.ask({",157 ...fields(158 [...args, ...stated].toSorted(([a], [b]) => a.localeCompare(b))159 ),160 "});",161 "",162 ].join("\n");163 }164165 return [166 header(parent),167 `import { check, kind, territory } from ${sdk};`,168 "",169 "const own = kind({",170 " args: {},",171 ` check: () => check.migrate({ ${args.map(([key, value]) => `${key}: ${value}`).join(", ")} }),`,172 ` checkKind: "migrate",`,173 ` name: ${quoted(child.kind)},`,174 "});",175 "",176 "export default own.ask({",177 ...fields(stated),178 "});",179 "",180 ].join("\n");181};182Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 183why, one step back183/** The sdk has no `symbolAbsent` builder, so the file makes its own kind whose check is the name gone. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 184–214why, one step back184const deleteFile = (child: Ask, check: MigrateCheck, parent: AskId) =>185 [186 header(parent),187 `import { kind } from ${sdk};`,188 "",189 "const own = kind({",190 " args: {},",191 ` check: () => ({ _tag: "SymbolAbsent", count: ${quoted(check.count)}, symbol: ${quoted(check.from)} }),`,192 ` checkKind: "symbolAbsent",`,193 ` name: ${quoted(child.kind)},`,194 "});",195 "",196 "export default own.ask({",197 ...fields([198 ["blockedBy", JSON.stringify(child.blockedBy)],199 ["parent", quoted(parent)],200 ["territory", JSON.stringify(child.territory)],201 ["want", quoted(child.brief.want)],202 ]),203 "});",204 "",205 ].join("\n");206207const callersOf = (count: number) =>208 count === 1 ? "1 caller" : `${count} callers`;209210const childWant = (module: string, count: number, check: MigrateCheck) =>211 check.to === undefined212 ? `${module}: ${callersOf(count)} of ${check.from} to remove`213 : `${module}: ${callersOf(count)} of ${check.from} → ${check.to}`;214Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 215why, one step back215/** `None` for a non-migrate ask, or when fewer than two modules have callers: a split of one is the ask itself. */Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 216–301why, one step back216export const splitFamily = (input: {217 readonly parent: Ask;218 readonly counts: CallerCount;219 readonly modules: readonly Territory[];220 readonly configDir: string;221}): Option.Option<MigrateFamily> => {222 const { counts, parent } = input;223 const { check } = parent;224225 if (!CheckSpec.guards.Migrate(check)) {226 return Option.none();227 }228229 const fileOf = (id: AskId) =>230 RepoPath.make(`${input.configDir}/asks/${id}.ask.ts`);231232 const member = (233 id: AskId,234 own: Pick<Ask, "blockedBy" | "brief" | "check" | "state" | "territory">235 ): Ask => ({236 ...parent,237 ...own,238 file: fileOf(id),239 id,240 parent: parent.id,241 });242243 const called = modulesWithin(parent.territory, input.modules).flatMap(244 (module) => {245 const count = counts.byModule[module.module] ?? 0;246247 return count > 0248 ? [249 member(childId(parent.id, module.module), {250 blockedBy: [],251 brief: { want: childWant(module.module, count, check) },252 check,253 state: "open",254 territory: module,255 }),256 ]257 : [];258 }259 );260261 const [first, second, ...rest] = called;262263 if (first === undefined || second === undefined) {264 return Option.none();265 }266267 const children = Array.make(first, second, ...rest);268 const childIds = children.map(({ id }) => id);269 const deleteId = deleteChildId(parent.id);270271 const deleteChild = member(deleteId, {272 blockedBy: childIds,273 brief: { want: `Delete ${check.from}: nothing calls it any more` },274 check: CheckSpec.cases.SymbolAbsent.make({275 count: check.count satisfies Command,276 symbol: check.from,277 }),278 state: "waitingOnParent",279 territory: parent.territory,280 });281282 return Option.some({283 children,284 deleteChild,285 files: Array.append(286 Array.map(children, (each) => ({287 content: childFile(each, check, parent.id),288 path: each.file,289 })),290 {291 content: deleteFile(deleteChild, check, parent.id),292 path: deleteChild.file,293 }294 ),295 parent: {296 ...parent,297 blockedBy: Array.dedupe([...parent.blockedBy, ...childIds, deleteId]),298 },299 ratchet: { baseline: counts.total, name: callersRatchet(check.from) },300 });301};