Skip to content
Myr

draft-settle.test.ts

This file

Path

packages/project/test/draft-settle.test.ts

694 lines · 20.9 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

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

line 1why, one step back
1import { describe, expect, it } from "@effect/vitest";

Merge build/1008oscabrielbefore adoption7de721c

line 2why, one step back
2import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";

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

lines 3–17why, one step back
3import { Brand } from "@repo/brand";
4import type { CheckAt } from "@repo/checks/check-runner";5import { parseTrailers } from "@repo/git/trailers";6import { CheckSpec } from "@repo/protocol/domain/check";7import { Glob } from "@repo/protocol/domain/common";8import { DecisionSubject } from "@repo/protocol/domain/decision";9import { ProjectEvent } from "@repo/protocol/domain/event";10import { DraftState } from "@repo/protocol/domain/proposal";11import {12 AskId,13 DecisionId,14 LandedSha,15 LaneName,16 ProposalId,17 RepoName,

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 18why, one step back
18 keyOf,

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

lines 19–48why, one step back
19 RepoPath,
20} from "@repo/protocol/ids";21import { Anonymous, Person } from "@repo/protocol/principal";22import {23 CapReached,24 DraftInProgress,25 NotDecider,26 NotRedFirst,27 ProposalClosed,28 UnknownProposal,29} from "@repo/protocol/refusal";30import { advanceTo, at as instant } from "@repo/testkit/clock";31import type { Files } from "@repo/testkit/git-client";32import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";33import { Array, Context, Effect, Layer, Option, Ref } from "effect";3435import { DraftResult, DraftRuns } from "../src/draft-runs.ts";36import type { DraftParams } from "../src/draft-runs.ts";37import { ProjectStore } from "../src/project-store.ts";38import type { ProjectApi } from "../src/project.ts";39import { projectService } from "../src/project.ts";40import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";4142const scenario = aProject({ people: ["carol", "dave"] }).pipe(43 withVouches(["carol", "dave"]),44 withAsk({ id: "parse-week", territory: "packages/parser" })45);4647const { project } = scenario;48

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

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

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

lines 50–76why, one step back
50
51const person = (name: string) =>52 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });5354const alice = person("alice");5556const carol = person("carol");5758const dave = person("dave");5960const anyone = Anonymous.make({});6162const redThenGreen = LaneName.make("redThenGreen");6364const model = "@cf/moonshotai/kimi-k2.7-code";6566const noon = instant("2026-10-08T12:00:00Z");6768const want = "Parse an ISO week date such as 2026-W41";6970const proposal = ProposalId.make("prop-000001");7172const ask = Option.getOrThrow(73 Array.findFirst(scenario.policy.asks, ({ id }) => id === "parse-week")74);7576const start: Files = [

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 77–80why, one step back
77 [
78 "package.json",79 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',80 ],

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

lines 81–330why, one step back
81 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],
82];8384const testPath = CheckSpec.guards.RedThenGreen(ask.check)85 ? ask.check.path86 : RepoPath.make("packages/parser/test/week.test.ts");8788const askSource = `export default "parse-week";\n`;8990const testSource = `import { parseWeek } from "../src/parse.ts";\n`;9192const files = Array.make(93 { content: askSource, path: ask.file },94 { content: testSource, path: testPath }95);9697const red = (attempts = 2) =>98 DraftResult.cases.Red.make({99 attempts,100 files,101 lane: redThenGreen,102 model,103 rationale: "parseWeek is missing, so the test fails by its assertion",104 signature: "redThenGreen: scripted failure",105 });106107const failed = DraftResult.cases.Failed.make({108 attempts: 3,109 model,110 refusal: new NotRedFirst({}),111});112113const mainRef = RefName.make("refs/heads/main");114115class Started extends Context.Service<116 Started,117 { readonly runs: Effect.Effect<readonly DraftParams[]> }118>()("test/Started") {}119120const recorded = Layer.effectContext(121 Effect.gen(function* () {122 const started = yield* Ref.make<readonly DraftParams[]>([]);123124 return Context.make(DraftRuns, {125 start: (params) => Ref.update(started, (all) => [...all, params]),126 }).pipe(Context.add(Started, { runs: Ref.get(started) }));127 })128);129130const world = Layer.mergeAll(worldOf(scenario, "memory"), recorded);131132const proposed = Effect.gen(function* () {133 yield* advanceTo("2026-10-08T12:00:00Z");134135 const api: ProjectApi = yield* projectService(project);136137 yield* api.initProject(alice, {});138139 const first = yield* Pusher.use((pusher) =>140 pusher.push(repo, Option.none(), start, "Start")141 );142143 yield* api.recordFirstPush(alice, first);144145 const made = yield* api.proposeAsk(carol, {146 draft: true,147 territory: "packages/parser",148 want,149 });150151 return { api, first: LandedSha.make(first), made };152});153154const stored = ProjectStore.use((store) => store.load());155156const openProposalDecisions = Effect.map(stored, ({ decisions }) =>157 decisions.filter(({ subject }) =>158 DecisionSubject.guards.OpenProposal(subject)159 )160);161162const runs = Started.use(({ runs: all }) => all);163164const redOnMain = Effect.gen(function* () {165 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);166167 const tip = LandedSha.make(168 Option.getOrThrow(Option.fromUndefinedOr(refs.get(mainRef)))169 );170171 const composed: CheckAt = yield* composedAt(repo, tip, files);172173 yield* CheckScript.use((checker) =>174 checker.script(composed, redThenGreen, ["failed", "failed"])175 );176});177178const firstDecision = DecisionId.make("dec-000001");179180const parserByDave = {181 policy: {182 ...scenario.policy,183 deciders: [184 ...scenario.policy.deciders,185 {186 handles: Array.make(dave.handle),187 paths: Glob.make("packages/parser/**"),188 },189 ],190 },191};192193describe("a proposal with a draft", () => {194 it.effect("puts up no decision, and starts one draft run", () =>195 Effect.gen(function* () {196 const { api, made } = yield* proposed;197198 expect(made.proposal).toStrictEqual({199 draft: DraftState.cases.Drafting.make({ round: 1, startedAt: noon }),200 expiresAt: instant("2026-10-22T12:00:00Z"),201 files: [],202 id: proposal,203 openedAt: noon,204 project,205 proposer: carol.handle,206 state: "open",207 territory: "packages/parser",208 want,209 });210 expect({211 decisions: yield* openProposalDecisions,212 opened: (yield* api.events(0, 100)).flatMap(({ event }) =>213 ProjectEvent.guards.ProposalOpened(event) ? [event.proposal] : []214 ),215 outbox: (yield* stored).outbox,216 runs: yield* runs,217 today: (yield* api.today(alice)).decisions,218 }).toStrictEqual({219 decisions: [],220 opened: [proposal],221 outbox: [],222 runs: [{ project, proposal, round: 1 }],223 today: [],224 });225 }).pipe(Effect.provide(world))226 );227228 it.effect(229 "settled red, puts up one decision with both files, its red first and who drafted it",230 () =>231 Effect.gen(function* () {232 const { api } = yield* proposed;233234 yield* api.draftSettled(proposal, 1, red());235236 const decisions = yield* openProposalDecisions;237 const shown = yield* api.showProposal(anyone, proposal);238239 expect(240 decisions.map(({ deciders, evidence, subject }) => ({241 deciders,242 evidence,243 subject,244 }))245 ).toStrictEqual([246 {247 deciders: [alice.handle],248 evidence: [249 { label: "want", value: want },250 { label: "territory", value: "packages/parser" },251 { label: ask.file, value: askSource },252 { label: testPath, value: testSource },253 {254 label: "red first",255 value: "redThenGreen: redThenGreen: scripted failure",256 },257 { label: "drafted by", value: `${model}, attempt 2 of 3` },258 {259 label: "why this test",260 value:261 "parseWeek is missing, so the test fails by its assertion",262 },263 ],264 subject: DecisionSubject.cases.OpenProposal.make({ proposal }),265 },266 ]);267 expect(shown).toStrictEqual({268 files,269 proposal: {270 ...shown.proposal,271 draft: DraftState.cases.Ready.make({272 attempts: 2,273 model,274 red: {275 lane: redThenGreen,276 signature: "redThenGreen: scripted failure",277 },278 round: 1,279 }),280 files: [ask.file, testPath],281 },282 });283 expect(284 (yield* api.events(0, 100)).flatMap(({ event }) =>285 ProjectEvent.guards.ProposalDrafted(event)286 ? [[event.proposal, event.ready]]287 : []288 )289 ).toStrictEqual([[proposal, true]]);290 }).pipe(Effect.provide(world))291 );292293 it.effect("settled twice, changes nothing the second time", () =>294 Effect.gen(function* () {295 const { api } = yield* proposed;296297 yield* api.draftSettled(proposal, 1, red());298299 const once = yield* stored;300301 yield* api.draftSettled(proposal, 1, red(3));302303 const twice = yield* stored;304305 expect([twice.decisions, twice.proposals, twice.lastSeq]).toStrictEqual([306 once.decisions,307 once.proposals,308 once.lastSeq,309 ]);310 }).pipe(Effect.provide(world))311 );312313 it.effect("settled for round 1 after round 2 started, changes nothing", () =>314 Effect.gen(function* () {315 const { api } = yield* proposed;316317 yield* api.draftSettled(proposal, 1, failed);318 yield* api.draftAsk(carol, { note: "use UTC", proposal });319320 const drafting = yield* stored;321322 yield* api.draftSettled(proposal, 1, red());323324 const after = yield* stored;325326 expect([after.decisions, after.proposals]).toStrictEqual([327 drafting.decisions,328 drafting.proposals,329 ]);330 expect(after.proposals.map(({ draft }) => draft)).toStrictEqual([

Merge build/1008oscabrielbefore adoption7de721c

lines 331–335why, one step back
331 DraftState.cases.Drafting.make({
332 note: "use UTC",333 round: 2,334 startedAt: noon,335 }),

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

lines 336–374why, one step back
336 ]);
337 expect(yield* runs).toStrictEqual([338 { project, proposal, round: 1 },339 { note: "use UTC", project, proposal, round: 2 },340 ]);341 }).pipe(Effect.provide(world))342 );343344 it.effect(345 "settled failed, puts up its want alone, with why the draft failed",346 () =>347 Effect.gen(function* () {348 const { api } = yield* proposed;349350 yield* api.draftSettled(proposal, 1, failed);351352 const decisions = yield* openProposalDecisions;353 const shown = yield* api.showProposal(anyone, proposal);354355 expect(decisions.map(({ evidence }) => evidence)).toStrictEqual([356 [357 { label: "want", value: want },358 { label: "territory", value: "packages/parser" },359 {360 label: "draft failed",361 value:362 "NotRedFirst: the ask's check must fail on main twice in the same way, by an assertion",363 },364 ],365 ]);366 expect([shown.files, shown.proposal.draft]).toStrictEqual([367 [],368 DraftState.cases.Failed.make({369 attempts: 3,370 model,371 refusal: "NotRedFirst",372 round: 1,373 }),374 ]);

Merge build/1008oscabrielbefore adoption7de721c

lines 375–499why, one step back
375 }).pipe(Effect.provide(world))
376 );377378 it.effect(379 "drafted again with a note, drafts with the note shown on the proposal",380 () =>381 Effect.gen(function* () {382 const { api } = yield* proposed;383384 yield* api.draftSettled(proposal, 1, failed);385386 const again = yield* api.draftAsk(carol, {387 note: "only the parser",388 proposal,389 });390391 const shown = yield* api.showProposal(anyone, proposal);392393 expect([again.proposal.draft, shown.proposal.draft]).toStrictEqual([394 DraftState.cases.Drafting.make({395 note: "only the parser",396 round: 2,397 startedAt: noon,398 }),399 DraftState.cases.Drafting.make({400 note: "only the parser",401 round: 2,402 startedAt: noon,403 }),404 ]);405 }).pipe(Effect.provide(world))406 );407408 it.effect(409 "drafted again after a ready round and failed, keeps the ready round's files and decision, and lands them on accept",410 () =>411 Effect.gen(function* () {412 const { api } = yield* proposed;413414 yield* api.draftSettled(proposal, 1, red());415 yield* api.draftAsk(carol, { note: "use UTC", proposal });416 yield* api.draftSettled(proposal, 2, failed);417418 const decisions = yield* openProposalDecisions;419 const shown = yield* api.showProposal(anyone, proposal);420421 expect(422 decisions.map(({ decided, evidence, id }) => ({423 decided,424 evidence,425 id,426 }))427 ).toStrictEqual([428 {429 decided: undefined,430 evidence: [431 { label: "want", value: want },432 { label: "territory", value: "packages/parser" },433 { label: ask.file, value: askSource },434 { label: testPath, value: testSource },435 {436 label: "red first",437 value: "redThenGreen: redThenGreen: scripted failure",438 },439 { label: "drafted by", value: `${model}, attempt 2 of 3` },440 {441 label: "why this test",442 value:443 "parseWeek is missing, so the test fails by its assertion",444 },445 {446 label: "draft failed",447 value:448 "NotRedFirst: the ask's check must fail on main twice in the same way, by an assertion",449 },450 ],451 id: firstDecision,452 },453 ]);454 expect([shown.files, shown.proposal.draft]).toStrictEqual([455 files,456 DraftState.cases.Failed.make({457 attempts: 3,458 model,459 refusal: "NotRedFirst",460 round: 2,461 }),462 ]);463464 yield* api.draftAsk(carol, { proposal });465 yield* api.draftSettled(proposal, 3, failed);466467 // A second failure keeps one line saying why, the last one.468 expect(469 (yield* openProposalDecisions).flatMap(({ evidence }) =>470 evidence.filter(({ label }) => label === "draft failed")471 )472 ).toHaveLength(1);473474 yield* redOnMain;475 yield* api.decide(alice, { choice: "accept", decision: firstDecision });476477 const host = yield* RepoHost;478 const refs = yield* host.refs(repo).pipe(Effect.orDie);479480 const tip = Option.getOrThrow(481 Option.fromUndefinedOr(refs.get(mainRef))482 );483484 const landed = yield* Effect.forEach([ask.file, testPath], (path) =>485 host486 .readFile(repo, Revision.Commit({ sha: tip }), path)487 .pipe(488 Effect.orDie,489 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes)))490 )491 );492493 expect(landed).toStrictEqual([494 Option.some(askSource),495 Option.some(testSource),496 ]);497 expect(498 (yield* api.listAsks(anyone)).asks.map((listing) => listing.ask)499 ).toStrictEqual([AskId.make("parse-week")]);

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

lines 500–503why, one step back
500 }).pipe(Effect.provide(world))
501 );502503 it.effect(

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

line 504why, one step back
504 "accepted once ready, lands its ask asked by its proposer, decided by the maintainer, and assisted by the drafter",

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

lines 505–572why, one step back
505 () =>
506 Effect.gen(function* () {507 const { api } = yield* proposed;508509 yield* api.draftSettled(proposal, 1, red());510 yield* redOnMain;511 yield* api.decide(alice, { choice: "accept", decision: firstDecision });512513 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);514515 const tip = Option.getOrThrow(516 Option.fromUndefinedOr(refs.get(mainRef))517 );518519 const read = yield* (yield* RepoHost)520 .readCommit(repo, tip)521 .pipe(Effect.orDie);522523 const trailers = parseTrailers(Option.getOrThrow(read).message);524 const { landings, proposals } = yield* stored;525526 expect(527 trailers.filter(({ key }) =>528 [529 "Asked-by",530 "Decided-by",531 "Assisted-by",532 "Signed-off-by",533 "Answered-by",534 ].includes(key)535 )536 ).toStrictEqual([537 {538 key: "Asked-by",539 value: `${carol.handle} <${carol.handle}@users.${Brand.domain}>`,540 },541 {542 key: "Decided-by",543 value: `${alice.handle} <${alice.handle}@users.${Brand.domain}>`,544 },545 {546 key: "Assisted-by",547 value: `${Brand.cli}-drafter:${model} (verified)`,548 },549 ]);550 expect(551 landings552 .filter(({ sha }) => sha === tip)553 .map(({ assisted, credits }) => ({ assisted, credits }))554 ).toStrictEqual([555 {556 assisted: [557 { harness: `${Brand.cli}-drafter`, model, verified: true },558 ],559 credits: [560 { handle: carol.handle, role: "Asked-by" },561 { handle: alice.handle, role: "Decided-by" },562 ],563 },564 ]);565 expect(proposals.map(({ state }) => state)).toStrictEqual(["accepted"]);566 expect(567 (yield* api.listAsks(anyone)).asks.map((listing) => listing.ask)568 ).toStrictEqual([AskId.make("parse-week")]);569 }).pipe(Effect.provide(world))570 );571572 it.effect(

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

line 573why, one step back
573 "drafted again is refused while drafting, for someone neither proposer nor maintainer, once closed, and past three rounds",

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

lines 574–612why, one step back
574 () =>
575 Effect.gen(function* () {576 const { api } = yield* proposed;577578 const drafting = yield* api579 .draftAsk(carol, { proposal })580 .pipe(Effect.flip);581582 yield* api.draftSettled(proposal, 1, failed);583584 const outsider = yield* api585 .draftAsk(dave, { proposal })586 .pipe(Effect.flip);587588 const unknown = yield* api589 .draftAsk(carol, { proposal: ProposalId.make("prop-000009") })590 .pipe(Effect.flip);591592 const second = yield* api.draftAsk(alice, { proposal });593594 yield* api.draftSettled(proposal, 2, failed);595 yield* api.draftAsk(carol, { proposal });596 yield* api.draftSettled(proposal, 3, red());597598 const fourth = yield* api599 .draftAsk(carol, { proposal })600 .pipe(Effect.flip);601602 yield* redOnMain;603 yield* api.decide(alice, { choice: "accept", decision: firstDecision });604605 const closed = yield* api606 .draftAsk(carol, { proposal })607 .pipe(Effect.flip);608609 expect([drafting, outsider, unknown, fourth, closed]).toStrictEqual([610 DraftInProgress.of(proposal),611 new NotDecider({}),612 new UnknownProposal({ proposal: ProposalId.make("prop-000009") }),

Say which limit a CapReached reached and when to try again, and that a fork takes branches onlyoscabrielbefore adoption42ea9b7

line 613why, one step back
613 new CapReached({ cap: 3, limit: "drafts" }),

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

lines 614–654why, one step back
614 new ProposalClosed({ proposal }),
615 ]);616 expect(second.proposal.draft).toStrictEqual(617 DraftState.cases.Drafting.make({ round: 2, startedAt: noon })618 );619 expect(yield* openProposalDecisions).toHaveLength(1);620 }).pipe(Effect.provide(world))621 );622623 it.effect(624 "gives its run what it drafts from: the landed commit, the want and the public policy",625 () =>626 Effect.gen(function* () {627 const { api, first } = yield* proposed;628 const context = yield* api.draftContext(proposal, 1);629630 const unknown = yield* api631 .draftContext(ProposalId.make("prop-000009"), 1)632 .pipe(Effect.flip);633634 expect({ ...context, policy: "policy" in context }).toStrictEqual({635 at: first,636 paths: [637 RepoPath.make("package.json"),638 RepoPath.make("packages/parser/src/parse.ts"),639 ],640 policy: true,641 project,642 proposal,643 round: 1,644 territory: "packages/parser",645 want,646 });647 expect("visibility" in context.policy).toBeFalsy();648 expect(context.policy.deciders).toStrictEqual(scenario.policy.deciders);649 expect(unknown).toStrictEqual(650 new UnknownProposal({ proposal: ProposalId.make("prop-000009") })651 );652 }).pipe(Effect.provide(world))653 );654 it.effect(

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

line 655why, one step back
655 "drafted again into files another maintainer decides, puts the open decision to them too",

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

lines 656–694why, one step back
656 () =>
657 Effect.gen(function* () {658 yield* advanceTo("2026-10-08T12:00:00Z");659660 const api = yield* projectService(project);661662 yield* api.initProject(alice, {});663664 const first = yield* Pusher.use((pusher) =>665 pusher.push(repo, Option.none(), start, "Start")666 );667668 yield* api.recordFirstPush(alice, first);669 // No territory: the files a draft holds say whose the decision is.670 yield* api.proposeAsk(carol, { draft: true, want });671 yield* api.draftSettled(proposal, 1, failed);672673 const wantOnly = yield* openProposalDecisions;674675 yield* api.draftAsk(carol, { proposal });676 yield* api.draftSettled(proposal, 2, red());677678 const drafted = yield* openProposalDecisions;679680 expect(681 [wantOnly, drafted].map((decisions) =>682 decisions.map(({ deciders, id }) => ({ deciders, id }))683 )684 ).toStrictEqual([685 [{ deciders: [alice.handle], id: firstDecision }],686 [{ deciders: [alice.handle, dave.handle], id: firstDecision }],687 ]);688 }).pipe(689 Effect.provide(690 Layer.mergeAll(worldOf(parserByDave, "memory"), recorded)691 )692 )693 );694});