Skip to content
Myr

drafting.model.test.ts

This file

Path

packages/project/test/drafting.model.test.ts

414 lines · 11.4 KiB · TypeScript

Last changed by

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

History of this file

Take it

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 1–7why, one step back
1import { assert, describe, it } from "@effect/vitest";
2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { CheckSpec } from "@repo/protocol/domain/check";4import { DecisionSubject } from "@repo/protocol/domain/decision";5import type { Decision } from "@repo/protocol/domain/decision";6import { DraftState } from "@repo/protocol/domain/proposal";7import type { Proposal } from "@repo/protocol/domain/proposal";

Merge build/1008oscabrielbefore adoption7de721c

line 8why, one step back
8import type { ProposalId } from "@repo/protocol/ids";

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 9–15why, one step back
9import {
10 keyOf,11 LandedSha,12 LaneName,13 RepoName,14 RepoPath,15} from "@repo/protocol/ids";

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 16–37why, one step back
16import { Person } from "@repo/protocol/principal";
17import { NotRedFirst } from "@repo/protocol/refusal";18import { advanceTo } from "@repo/testkit/clock";19import type { Files } from "@repo/testkit/git-client";20import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";21import { Arbitrary, Array, Duration, Effect, Option, Schema } from "effect";22import { TestClock } from "effect/testing";2324import { DraftResult } from "../src/draft-runs.ts";25import type { ProjectSnapshot } from "../src/project-store.ts";26import { ProjectStore } from "../src/project-store.ts";27import type { ProjectApi } from "../src/project.ts";28import { projectService } from "../src/project.ts";29import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";3031const scenario = aProject({ people: ["carol", "dave"] }).pipe(32 withVouches(["carol", "dave"]),33 withAsk({ id: "parse-week", territory: "packages/parser" })34);3536const { project } = scenario;37

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 38why, one step back
38const repo = RepoName.make(keyOf(project));

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 39–55why, one step back
39
40const People = Schema.Literals(["alice", "carol", "dave"]);4142type People = typeof People.Type;4344const person = (name: People) =>45 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });4647const redThenGreen = LaneName.make("redThenGreen");4849const mainRef = RefName.make("refs/heads/main");5051const ask = Option.getOrThrow(52 Array.findFirst(scenario.policy.asks, ({ id }) => id === "parse-week")53);5455const start: Files = [

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 56–59why, one step back
56 [
57 "package.json",58 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',59 ],

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 60–154why, one step back
60 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],
61];6263const files = Array.make(64 { content: `export default "parse-week";\n`, path: ask.file },65 {66 content: `import { parseWeek } from "../src/parse.ts";\n`,67 path: CheckSpec.guards.RedThenGreen(ask.check)68 ? ask.check.path69 : RepoPath.make("packages/parser/test/week.test.ts"),70 }71);7273const model = "@cf/openai/gpt-oss-120b";7475const red = DraftResult.cases.Red.make({76 attempts: 1,77 files,78 lane: redThenGreen,79 model,80 rationale: "parseWeek is missing",81 signature: "redThenGreen: scripted failure",82});8384const failed = DraftResult.cases.Failed.make({85 attempts: 3,86 model,87 refusal: new NotRedFirst({}),88});8990const Which = Schema.Literals([0, 1]);9192const Round = Schema.Literals(["current", "before", "after"]);9394type Round = typeof Round.Type;9596const Move = Schema.TaggedUnion({97 Accept: { which: Which },98 Expire: {},99 Propose: {},100 Redraft: { which: Which, who: People },101 Settle: { red: Schema.Boolean, round: Round, which: Which },102});103104type Move = typeof Move.Type;105106const roll = (maximum: number) =>107 Arbitrary.schema(Schema.Int.check(Schema.isBetween({ maximum, minimum: 0 })));108109const anyWhich = roll(3).pipe(Arbitrary.map((n) => (n === 3 ? 1 : 0)));110111const rounds: readonly Round[] = [112 "current",113 "current",114 "current",115 "current",116 "before",117 "after",118];119120const anyRound = roll(rounds.length - 1).pipe(121 Arbitrary.map((n) => rounds[n] ?? "current")122);123124const drafters: readonly People[] = [125 "carol",126 "alice",127 "carol",128 "alice",129 "dave",130];131132const anyWho = roll(drafters.length - 1).pipe(133 Arbitrary.map((n) => drafters[n] ?? "carol")134);135136const settles = Arbitrary.all({137 red: Arbitrary.schema(Schema.Boolean),138 round: anyRound,139 which: anyWhich,140}).pipe(Arbitrary.map((made) => Move.cases.Settle.make(made)));141142const redrafts = Arbitrary.all({ which: anyWhich, who: anyWho }).pipe(143 Arbitrary.map((made) => Move.cases.Redraft.make(made))144);145146const accepts = anyWhich.pipe(147 Arbitrary.map((chosen) => Move.cases.Accept.make({ which: chosen }))148);149150const proposes = Arbitrary.Constant(Move.cases.Propose.make({}));151152const expires = Arbitrary.Constant(Move.cases.Expire.make({}));153154/**

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

lines 155–156why, one step back
155 * A roll leans and shrinks towards 0, so a settle, the move that runs into most
156 * rules, comes first.

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 157–210why, one step back
157 */
158const weighted = [159 settles,160 redrafts,161 settles,162 proposes,163 redrafts,164 settles,165 accepts,166 proposes,167 expires,168];169170const moves = roll(weighted.length - 1).pipe(171 Arbitrary.flatMap((n): Arbitrary.Arbitrary<Move> => weighted[n] ?? settles)172);173174const histories = Arbitrary.array(moves, { maxLength: 16 });175176const offset = (round: Round) => ({ after: 1, before: -1, current: 0 })[round];177178const notFiles = new Set([179 "want",180 "territory",181 "red first",182 "drafted by",183 "why this test",184 "draft failed",185 "sealed answer",186]);187188const decisionsFor = (snapshot: ProjectSnapshot, proposal: Proposal) =>189 snapshot.decisions.filter(190 ({ subject }) =>191 DecisionSubject.guards.OpenProposal(subject) &&192 subject.proposal === proposal.id193 );194195const roundOf = (proposal: Proposal) => proposal.draft?.round ?? 1;196197const settledRound = (proposal: Proposal, round: Round) =>198 Math.max(1, roundOf(proposal) + offset(round));199200const isCurrent = (proposal: Proposal, round: number) =>201 proposal.state === "open" &&202 proposal.draft !== undefined &&203 DraftState.guards.Drafting(proposal.draft) &&204 proposal.draft.round === round;205206const fileLabels = (decision: Decision) =>207 decision.evidence.flatMap(({ label }) =>208 notFiles.has(label) ? [] : [label]209 );210

Merge build/1008oscabrielbefore adoption7de721c

lines 211–222why, one step back
211type ReadyFiles = ReadonlyMap<ProposalId, readonly RepoPath[]>;
212213const readyIn = (ready: ReadyFiles, snapshot: ProjectSnapshot): ReadyFiles =>214 new Map([215 ...ready,216 ...snapshot.proposals.flatMap((proposal) =>217 proposal.draft !== undefined && DraftState.guards.Ready(proposal.draft)218 ? [[proposal.id, proposal.files] as const]219 : []220 ),221 ]);222

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 223–225why, one step back
223const brokenBy = (
224 move: Move,225 before: ProjectSnapshot,

Merge build/1008oscabrielbefore adoption7de721c

lines 226–227why, one step back
226 after: ProjectSnapshot,
227 ready: ReadyFiles

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 228–279why, one step back
228): readonly string[] => [
229 ...after.proposals.flatMap((proposal) =>230 proposal.draft !== undefined &&231 DraftState.guards.Drafting(proposal.draft) &&232 proposal.draft.round === 1 &&233 decisionsFor(after, proposal).length > 0234 ? [`${proposal.id} has a decision while its first draft is drafting`]235 : []236 ),237 ...Option.match(238 Option.flatMap(239 Option.liftPredicate(move, Move.guards.Settle),240 ({ round, which }) =>241 Option.map(242 Option.fromUndefinedOr(before.proposals[which]),243 (proposal) => ({ proposal, round: settledRound(proposal, round) })244 )245 ),246 {247 onNone: (): readonly string[] => [],248 onSome: ({ proposal, round }) =>249 isCurrent(proposal, round) ||250 JSON.stringify([after.decisions, after.proposals, after.lastSeq]) ===251 JSON.stringify([before.decisions, before.proposals, before.lastSeq])252 ? []253 : [`a stale settle of ${proposal.id} round ${round} changed it`],254 }255 ),256 ...after.proposals.flatMap((proposal) => {257 if (258 proposal.state !== "open" ||259 proposal.draft === undefined ||260 DraftState.guards.Drafting(proposal.draft)261 ) {262 return [];263 }264265 const decision = decisionsFor(after, proposal).at(-1);266267 const says = (label: string) =>268 decision?.evidence.some((each) => each.label === label) === true;269270 const held =271 decision !== undefined &&272 JSON.stringify(fileLabels(decision)) === JSON.stringify(proposal.files);273274 if (DraftState.guards.Ready(proposal.draft)) {275 return held && says("red first")276 ? []277 : [`${proposal.id} is ready, and its decision holds other files`];278 }279

Merge build/1008oscabrielbefore adoption7de721c

lines 280–290why, one step back
280 const earlier = ready.get(proposal.id) ?? [];
281282 if (JSON.stringify(proposal.files) !== JSON.stringify(earlier)) {283 return [284 `${proposal.id}'s draft failed, and it lost its ready round's files`,285 ];286 }287288 return held &&289 says("draft failed") &&290 says("red first") === earlier.length > 0

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 291–381why, one step back
291 ? []
292 : [`${proposal.id}'s draft failed, and its decision says otherwise`];293 }),294];295296const stored = ProjectStore.use((store) => store.load());297298const redOnMain = Effect.gen(function* () {299 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);300301 const tip = LandedSha.make(302 Option.getOrThrow(Option.fromUndefinedOr(refs.get(mainRef)))303 );304305 const composed = yield* composedAt(repo, tip, files);306307 yield* CheckScript.use((checker) =>308 checker.script(composed, redThenGreen, ["failed", "failed"])309 );310});311312const step = (api: ProjectApi, before: ProjectSnapshot, move: Move) => {313 const proposalAt = (which: number) =>314 Option.fromUndefinedOr(before.proposals[which]);315316 return Move.match(move, {317 Accept: ({ which }) =>318 Option.match(319 Option.flatMap(proposalAt(which), (proposal) =>320 Array.findLast(321 decisionsFor(before, proposal),322 ({ decided }) => decided === undefined323 )324 ),325 {326 onNone: () => Effect.void,327 onSome: (decision) =>328 redOnMain.pipe(329 Effect.andThen(330 api.decide(person("alice"), {331 choice: "accept",332 decision: decision.id,333 })334 ),335 Effect.ignore336 ),337 }338 ),339 Expire: () =>340 TestClock.adjust(Duration.days(15)).pipe(Effect.andThen(api.onAlarm())),341 Propose: () =>342 Effect.ignore(343 api.proposeAsk(person("carol"), {344 draft: true,345 territory: "packages/parser",346 want: "Parse an ISO week date",347 })348 ),349 Redraft: ({ which, who }) =>350 Option.match(proposalAt(which), {351 onNone: () => Effect.void,352 onSome: (proposal) =>353 Effect.ignore(api.draftAsk(person(who), { proposal: proposal.id })),354 }),355 Settle: ({ red: isRed, round, which }) =>356 Option.match(proposalAt(which), {357 onNone: () => Effect.void,358 onSome: (proposal) =>359 api.draftSettled(360 proposal.id,361 settledRound(proposal, round),362 isRed ? red : failed363 ),364 }),365 });366};367368const firstBreak = (history: readonly Move[]) =>369 Effect.gen(function* () {370 yield* advanceTo("2026-10-08T12:00:00Z");371372 const api = yield* projectService(project);373374 yield* api.initProject(person("alice"), {});375376 const first = yield* Pusher.use((pusher) =>377 pusher.push(repo, Option.none(), start, "Start")378 );379380 yield* api.recordFirstPush(person("alice"), first);381

Merge build/1008oscabrielbefore adoption7de721c

lines 382–383why, one step back
382 let ready: ReadyFiles = new Map();
383

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 384–386why, one step back
384 for (const [index, move] of history.entries()) {
385 const before = yield* stored;386

Merge build/1008oscabrielbefore adoption7de721c

lines 387–388why, one step back
387 ready = readyIn(ready, before);
388

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 389–390why, one step back
389 yield* step(api, before, move);
390

Merge build/1008oscabrielbefore adoption7de721c

line 391why, one step back
391 const broken = brokenBy(move, before, yield* stored, ready);

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 392–400why, one step back
392
393 if (broken.length > 0) {394 return [`step ${index} (${move._tag})`, ...broken];395 }396 }397398 return [];399 }).pipe(Effect.provide(worldOf(scenario, "memory")));400

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

line 401why, one step back
401/** Catches a hang, not a busy machine. */

Merge branch 'build/909-draft-rehearsal-and-settling'oscabrielbefore adoption9e6b61c

lines 402–414why, one step back
402const generated = { timeout: 120_000 };
403404describe("drafting, over generated histories", generated, () => {405 it.effect.prop(406 "keeps every invariant after every step",407 { history: histories },408 ({ history }) =>409 Effect.map(firstBreak(history), (broken) => {410 assert.deepStrictEqual(broken, [], broken.join("; "));411 }),412 { arbitrary: { runs: 200, size: 40 }, timeout: 120_000 }413 );414});