project.test.ts
This file
Path
packages/project/test/project.test.ts
1,403 lines · 40.0 KiB · TypeScript
Last changed by
Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
History of this fileTake it
1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { CheckAt, CheckRunner } from "@repo/checks/check-runner";5import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";6import { Verdict } from "@repo/protocol/domain/answer";7import type { Ask } from "@repo/protocol/domain/ask";8import { CheckSpec } from "@repo/protocol/domain/check";9import { ClaimView } from "@repo/protocol/domain/claim";10import { Command, Glob } from "@repo/protocol/domain/common";11import { Outcome } from "@repo/protocol/domain/outcome";12import {13 AskId,14 LandedSha,15 LaneName,16 ProjectName,17 RepoName,18 RepoPath,19 keyOf,20 RequestId,21} from "@repo/protocol/ids";22import type { CommitSha } from "@repo/protocol/ids";23import { Anonymous, Person } from "@repo/protocol/principal";24import {25 AskFull,26 ClaimLapsed,27 DirectPush,28 ImportFailed,29 NotClaimed,30 NotDecider,31 NotRedFirst,32 OutOfScope,33 ProjectExists,34 StaleBase,35 TouchedJudge,36 UnknownProject,37} from "@repo/protocol/refusal";38import { advanceTo, at as instant } from "@repo/testkit/clock";39import type { Files } from "@repo/testkit/git-client";40import {41 aProject,42 withAsk,43 withKind,44 withVouches,45} from "@repo/testkit/scenarios";46import {47 Array,48 DateTime,49 Effect,50 Exit,51 Layer,52 Option,53 Ref,54 Result,55 Schema,56} from "effect";5758import { ScheduledAlarm } from "../src/alarms/memory.ts";59import { ProjectStore } from "../src/project-store.ts";60import type { ProjectApi } from "../src/project.ts";61import { projectService } from "../src/project.ts";62import { ProjectedRows } from "../src/projection/memory.ts";63import { Projects } from "../src/projects.ts";64import { ProjectsMemory } from "../src/projects/memory.ts";65import {66 CheckScript,67 cleanMergeAt,68 composedAt,69 Evaluated,70 mergedAt,71 Pusher,72 worldOf,73} from "./world.ts";74import type { StoreKind, WorldScenario } from "./world.ts";7576const people = ["bob", "carol", "dave", "eve", "frank"];7778const scenario = aProject({ people }).pipe(79 withVouches(people),80 withAsk({ id: "parse-iso", territory: "packages/parser" }),81 withAsk({ id: "parse-green", territory: "packages/parser" }),82 withAsk({ id: "format-date", territory: "packages/format" }),83 withAsk({ id: "lex-tokens", territory: "packages/lexer" }),84 withAsk({ id: "trim-input", territory: "packages/trim" }),85 withAsk({ id: "tidy-all", territory: "." })86);8788const { project } = scenario;8990const repo = RepoName.make(keyOf(project));9192const mainRef = RefName.make("refs/heads/main");9394const person = (name: string) =>95 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });9697const alice = person("alice");9899const bob = person("bob");100101const carol = person("carol");102103const dave = person("dave");104105const eve = person("eve");106107const frank = person("frank");108109const anyone = Anonymous.make({});110111const remoteOf = (name: string) => `https://${Brand.domain}/${name}.git`;112113const forkOf = (ask: string, who: Person) =>114 RepoName.make(`${keyOf(project)}--${ask}--${who.handle}`);115116const userOf = (handle: string) =>117 `${handle} <${handle}@users.${Brand.domain}>`;118119const askOf = (id: string): Ask =>120 Option.getOrThrow(121 Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)122 );123124const redThenGreen = LaneName.make("redThenGreen");125126const lanes = [redThenGreen, LaneName.make("lint"), LaneName.make("types")];127128const noon = instant("2026-10-07T12:00:00Z");129130const hoursAfter = (from: DateTime.Utc, count: number) =>131 DateTime.add(from, { hours: count });132133const start: Files = [134 [135 "package.json",136 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',137 ],138 [139 "packages/format/src/format.ts",140 "export const format = (d) => String(d);\n",141 ],142 ["packages/lexer/src/lex.ts", "export const lex = (s) => s.split(' ');\n"],143 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],144 ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],145];146147const fixedParse = "export const parse = (s) => ({ year: 2026 });\n";148149const askFiles = (id: string) => {150 const { check, file, territory } = askOf(id);151 const subject = territory.module === "." ? "tidy" : territory.module;152153 return Array.make(154 { content: `export default "${id}";\n`, path: file },155 {156 content: [157 `import { expect, it } from "vitest";`,158 `import { ${subject} } from "../src/${subject}.ts";`,159 ``,160 `it("${id}", () => {`,161 ` expect(${subject}("2026-10-07")).toStrictEqual({ year: 2026 });`,162 `});`,163 ``,164 ].join("\n"),165 path: CheckSpec.guards.RedThenGreen(check)166 ? check.path167 : RepoPath.make(`test/${id}.test.ts`),168 }169 );170};171172const withAskFiles = (files: Files, ...ids: readonly string[]): Files => [173 ...files,174 ...ids.flatMap((id) =>175 askFiles(id).map(({ content, path }) => [path, content] as const)176 ),177];178179const changed = (files: Files, path: string, content: string): Files => [180 ...files.filter(([each]) => each !== path),181 [path, content],182];183184const mainTip = Effect.gen(function* () {185 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);186187 return LandedSha.make(188 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))189 );190});191192const commitOf = (sha: CommitSha) =>193 Effect.gen(function* () {194 const host = yield* RepoHost;195 const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);196 const { author, committer, message, parents } = Option.getOrThrow(read);197198 return { author, committer, parents, trailers: parseTrailers(message) };199 });200201const scriptAll = (202 on: Parameters<CheckScript["Service"]["script"]>[0],203 result: "passed" | "failed"204) =>205 CheckScript.use((checker) =>206 Effect.forEach(lanes, (lane) => checker.script(on, lane, [result]), {207 discard: true,208 })209 );210211const openRed = (api: ProjectApi, id: string, decider: Person = alice) =>212 Effect.gen(function* () {213 const files = askFiles(id);214 const composed = yield* composedAt(repo, yield* mainTip, files);215216 yield* CheckScript.use((checker) =>217 checker.script(composed, redThenGreen, ["failed", "failed"])218 );219220 return yield* api.openAsk(decider, { ask: AskId.make(id), files });221 });222223const eventTags = (api: ProjectApi) =>224 Effect.map(api.events(0, 1000), (events) =>225 events.map(({ event }) => event._tag)226 );227228const scheduled = ScheduledAlarm.use(({ at }) => at);229230const projectState = ProjectStore.use((store) => store.load()).pipe(231 Effect.map(({ project: row }) => Option.map(row, ({ state }) => state))232);233234const states = (api: ProjectApi, who: Person) =>235 Effect.map(api.status(who), ({ claims }) => claims.map(({ state }) => state));236237const outcomes = (api: ProjectApi, who: Person) =>238 Effect.map(api.status(who), ({ answers }) =>239 answers.map(({ outcome }) => outcome)240 );241242const parseIso = AskId.make("parse-iso");243244const opening = (api: ProjectApi) =>245 Effect.gen(function* () {246 const unmade = yield* api.firstPusher();247 const made = yield* Effect.exit(api.initProject(alice, {}));248 const awaiting = yield* projectState;249 const awaitedFrom = yield* api.firstPusher();250251 const first = yield* Pusher.use((pusher) =>252 pusher.push(repo, Option.none(), start, "Start")253 );254255 const notHers = yield* api.recordFirstPush(bob, first).pipe(Effect.flip);256 const recorded = yield* api.recordFirstPush(alice, first);257 const firstPushers = [unmade, awaitedFrom, yield* api.firstPusher()];258 const evaluated = yield* Evaluated.use(({ shas }) => shas);259 const opened = yield* openRed(api, "parse-iso");260 const redFirstJobs = yield* CheckScript.use(({ jobs }) => jobs);261 const greenFiles = askFiles("parse-green");262263 yield* scriptAll(264 yield* composedAt(repo, opened.landed, greenFiles),265 "passed"266 );267268 const green = { ask: AskId.make("parse-green"), files: greenFiles };269 const greenRefused = yield* api.openAsk(alice, green).pipe(Effect.flip);270 const bobRefused = yield* api.openAsk(bob, green).pipe(Effect.flip);271272 return {273 asked: yield* commitOf(opened.landed),274 awaiting,275 bobRefused,276 evaluated,277 first,278 firstPushers,279 greenRefused,280 listed: yield* api.listAsks(anyone),281 made,282 mainAfterRefusals: yield* mainTip,283 notHers,284 opened,285 recorded,286 redFirstJobs,287 shown: yield* api.showAsk(anyone, parseIso),288 };289 });290291const claiming = (api: ProjectApi, opened: LandedSha) =>292 Effect.gen(function* () {293 const host = yield* RepoHost;294 const bobFork = forkOf("parse-iso", bob);295 const { claim } = yield* api.claim(bob, parseIso);296 const forkRefs = yield* host.refs(bobFork).pipe(Effect.orDie);297 const alarmAfterClaim = yield* scheduled;298 const carolRefused = yield* api.claim(carol, parseIso).pipe(Effect.flip);299300 const carolFork = yield* Effect.exit(host.refs(forkOf("parse-iso", carol)));301302 const wideFiles = changed(303 changed(304 changed(305 withAskFiles(start, "parse-iso"),306 "packages/parser/src/parse.ts",307 fixedParse308 ),309 "packages/format/src/format.ts",310 "export const format = (d) => d.toString();\n"311 ),312 ".github/workflows/ci.yml",313 "on: push\n"314 );315316 const wide = yield* Pusher.use((pusher) =>317 pusher.push(bobFork, Option.some(opened), wideFiles)318 );319320 const wideRefusals = yield* api.recordPush({321 after: wide,322 before: Option.some(opened),323 eventId: "push-wide",324 pusher: bob,325 ref: "refs/heads/main",326 repo: bobFork,327 });328329 const wideSubmitted = yield* api330 .submitAnswer(bob, {331 ask: parseIso,332 base: opened,333 head: wide,334 requestId: RequestId.make("req-wide-0001"),335 })336 .pipe(Effect.flip);337338 return {339 alarmAfterClaim,340 carolFork,341 carolRefused,342 claim,343 forkMain: forkRefs.get(mainRef),344 wide,345 wideRefusals,346 wideSubmitted,347 };348 });349350const landing = (api: ProjectApi, opened: LandedSha, wide: CommitSha) =>351 Effect.gen(function* () {352 const bobFork = forkOf("parse-iso", bob);353354 const fixedFiles = changed(355 withAskFiles(start, "parse-iso"),356 "packages/parser/src/parse.ts",357 fixedParse358 );359360 const fix = yield* Pusher.use((pusher) =>361 pusher.push(bobFork, Option.some(wide), fixedFiles)362 );363364 const fixRefusals = yield* api.recordPush({365 after: fix,366 before: Option.some(wide),367 eventId: "push-fix",368 pusher: bob,369 ref: "refs/heads/main",370 repo: bobFork,371 });372373 yield* scriptAll(374 yield* mergedAt({375 base: opened,376 fork: bobFork,377 head: fix,378 main: opened,379 repo,380 }),381 "passed"382 );383384 const requestId = RequestId.make("req-fix-0001");385 const submission = { ask: parseIso, base: opened, head: fix, requestId };386 const receipt = yield* api.submitAnswer(bob, submission);387 const landed = yield* mainTip;388 const { verdict } = yield* api.verdict(anyone, { ask: parseIso });389390 const roundTrip = yield* Option.match(Option.fromUndefinedOr(verdict), {391 onNone: () => Effect.succeedNone,392 onSome: (made) =>393 Schema.encodeEffect(Verdict)(made).pipe(394 Effect.flatMap(Schema.decodeEffect(Verdict)),395 Effect.asSome,396 Effect.orDie397 ),398 });399400 return {401 events: yield* eventTags(api),402 fix,403 fixRefusals,404 fixedFiles,405 landed,406 landing: yield* commitOf(landed),407 listedAfter: yield* api.listAsks(anyone),408 projected: yield* ProjectedRows.use(({ events }) =>409 Effect.map(events, (rows) => rows.map(({ event }) => event._tag))410 ),411 receipt,412 replay: yield* api.submitAnswer(bob, submission),413 replayByCarol: yield* Effect.result(api.submitAnswer(carol, submission)),414 requestId,415 roundTrip,416 status: yield* api.status(bob),417 tipAfterReplay: yield* mainTip,418 verdict,419 view: (yield* api.landing(anyone, landed)).landing,420 };421 });422423const lapsing = (api: ProjectApi, files: Files) =>424 Effect.gen(function* () {425 const formatDate = AskId.make("format-date");426427 yield* openRed(api, "format-date");428 yield* api.claim(dave, formatDate);429430 const alarmAfterClaim = yield* scheduled;431432 yield* advanceTo("2026-10-07T14:00:00Z");433 yield* api.onAlarm();434435 const warned = {436 alarm: yield* scheduled,437 last: (yield* eventTags(api)).at(-1),438 states: yield* states(api, dave),439 };440441 yield* advanceTo("2026-10-08T12:00:00Z");442 yield* api.onAlarm();443444 const lapsed = {445 last: (yield* eventTags(api)).at(-1),446 states: yield* states(api, dave),447 };448449 const base = yield* mainTip;450451 const late = yield* Pusher.use((pusher) =>452 pusher.push(453 forkOf("format-date", dave),454 Option.some(base),455 changed(456 withAskFiles(files, "format-date"),457 "packages/format/src/format.ts",458 "export const format = (d) => ({ year: 2026 });\n"459 )460 )461 );462463 const lateRefused = yield* api464 .submitAnswer(dave, {465 ask: formatDate,466 base,467 head: late,468 requestId: RequestId.make("req-late-0001"),469 })470 .pipe(Effect.flip);471472 return { alarmAfterClaim, lapsed, lateRefused, warned };473 });474475interface Racer {476 readonly ask: string;477 readonly change: readonly [path: string, content: string];478 readonly who: Person;479}480481const racing = (482 api: ProjectApi,483 files: Files,484 [first, second]: readonly [Racer, Racer]485) =>486 Effect.gen(function* () {487 yield* openRed(api, first.ask);488 yield* openRed(api, second.ask);489490 const base = yield* mainTip;491 const onBase = withAskFiles(files, "format-date", first.ask, second.ask);492493 const answer = (racer: Racer) =>494 Effect.gen(function* () {495 const fork = forkOf(racer.ask, racer.who);496497 yield* api.claim(racer.who, AskId.make(racer.ask));498499 const head = yield* Pusher.use((pusher) =>500 pusher.push(fork, Option.some(base), changed(onBase, ...racer.change))501 );502503 return { fork, head };504 });505506 const submit = (racer: Racer, head: CommitSha) =>507 api.submitAnswer(racer.who, {508 ask: AskId.make(racer.ask),509 base,510 head,511 requestId: RequestId.make(`req-${racer.ask}`),512 });513514 const one = yield* answer(first);515 const other = yield* answer(second);516517 yield* submit(first, one.head);518519 const waiting = yield* outcomes(api, first.who);520521 yield* scriptAll(522 yield* mergedAt({ ...other, base, main: base, repo }),523 "passed"524 );525 yield* submit(second, other.head);526527 const between = yield* mainTip;528529 yield* scriptAll(530 yield* mergedAt({ ...one, base, main: base, repo }),531 "passed"532 );533534 const remerged = yield* cleanMergeAt({ ...one, base, main: between, repo });535536 if (Option.isSome(remerged)) {537 yield* scriptAll(remerged.value, "passed");538 }539540 yield* advanceTo(DateTime.formatIso(Option.getOrThrow(yield* scheduled)));541 yield* api.onAlarm();542543 const tip = yield* mainTip;544545 return {546 base,547 between,548 betweenParents: (yield* commitOf(between)).parents,549 outcomes: yield* outcomes(api, first.who),550 tip,551 tipParents: (yield* commitOf(tip)).parents,552 waiting,553 };554 });555556const core = Effect.gen(function* () {557 yield* advanceTo("2026-10-07T12:00:00Z");558559 const api = yield* projectService(project);560 const opened = yield* opening(api);561 const claimed = yield* claiming(api, opened.opened.landed);562 const answered = yield* landing(api, opened.opened.landed, claimed.wide);563 const lapsed = yield* lapsing(api, answered.fixedFiles);564565 return { answered, api, claimed, lapsed, opened };566});567568const story = Effect.gen(function* () {569 const { api, ...seen } = yield* core;570571 const raced = yield* racing(api, seen.answered.fixedFiles, [572 {573 ask: "lex-tokens",574 change: [575 "packages/lexer/src/lex.ts",576 "export const lex = (s) => s.split(/ +/);\n",577 ],578 who: eve,579 },580 {581 ask: "trim-input",582 change: [583 "packages/trim/src/trim.ts",584 "export const trim = (s) => s.trim();\n",585 ],586 who: frank,587 },588 ]);589590 return { ...seen, raced };591});592593const conflicting = Effect.gen(function* () {594 const { api, answered } = yield* core;595596 return yield* racing(api, answered.fixedFiles, [597 {598 ask: "lex-tokens",599 change: [600 "packages/lexer/src/lex.ts",601 "export const lex = (s) => s.split(/ +/);\n",602 ],603 who: eve,604 },605 {606 ask: "tidy-all",607 change: [608 "packages/lexer/src/lex.ts",609 "export const lex = (s) => s.split('\\t');\n",610 ],611 who: frank,612 },613 ]);614});615616/** Catches a hang, not a busy machine (near five seconds under turbo). */617const wholeStory = { timeout: 30_000 };618619describe.each(["memory", "sqlite"] as const)(620 "one project over memory adapters, its store in %s",621 wholeStory,622 (store: StoreKind) => {623 const seen = story.pipe(Effect.provide(worldOf(scenario, store)));624625 it.effect(626 "1. alice makes it empty, and her first push becomes its landed SHA",627 () =>628 Effect.map(seen, ({ opened }) => {629 expect(opened.made).toStrictEqual(630 Exit.succeed({ project, remote: remoteOf(project) })631 );632 expect(opened.awaiting).toStrictEqual(633 Option.some("awaitingFirstPush")634 );635 expect(opened.notHers).toStrictEqual(636 new DirectPush({ ref: mainRef })637 );638 expect(opened.recorded).toStrictEqual({ landed: opened.first });639 expect(opened.evaluated).toStrictEqual([opened.first]);640 })641 );642643 it.effect(644 "1. its first push is awaited from alice from when she makes it until she pushes it, and from no one before or after",645 () =>646 Effect.map(seen, ({ opened }) => {647 expect(opened.firstPushers).toStrictEqual([648 Option.none(),649 Option.some(alice.handle),650 Option.none(),651 ]);652 })653 );654655 it.effect(656 "2. an ask red twice on the composed tree lands as a platform commit asked by alice",657 () =>658 Effect.map(seen, ({ opened }) => {659 const { asked, first, opened: open } = opened;660661 expect({662 askedBy: open.ask.askedBy,663 openedIn: open.ask.openedIn,664 state: open.ask.state,665 }).toStrictEqual({666 askedBy: alice.handle,667 openedIn: open.landed,668 state: "open",669 });670 expect({671 author: asked.author,672 committer: asked.committer,673 parents: asked.parents,674 }).toStrictEqual({675 author: authorLine(alice.handle),676 committer: committerLine,677 parents: [first],678 });679 expect(asked.trailers).toContainEqual({680 key: "Asked-by",681 value: userOf("alice"),682 });683 expect(opened.listed).toStrictEqual({684 asks: [685 {686 ask: parseIso,687 blockedBy: [],688 claimed: false,689 kind: askOf("parse-iso").kind,690 territory: "parser",691 want: askOf("parse-iso").brief.want,692 },693 ],694 });695 expect({696 ask: opened.shown.ask,697 readsWant: opened.shown.brief.includes(open.ask.brief.want),698 }).toStrictEqual({ ask: open.ask, readsWant: true });699 })700 );701702 it.effect(703 "2. red first runs the ask's check twice on the composed commit, each run in the project's own setup",704 () =>705 Effect.map(seen, ({ opened }) => {706 expect(707 opened.redFirstJobs.map(({ at, lanes: ran, run }) => ({708 at: CheckAt.guards.Commit(at),709 lanes: ran.map(({ lane }) => lane),710 run,711 }))712 ).toStrictEqual(713 [1, 2].map(() => ({714 at: true,715 lanes: [redThenGreen],716 run: scenario.policy.run,717 }))718 );719 })720 );721722 it.effect(723 "2. an ask green on main is not red first, and only a maintainer opens one",724 () =>725 Effect.map(seen, ({ opened }) => {726 expect(opened.greenRefused).toStrictEqual(new NotRedFirst({}));727 expect(opened.bobRefused).toStrictEqual(new NotDecider({}));728 expect(opened.mainAfterRefusals).toBe(opened.opened.landed);729 })730 );731732 it.effect(733 "3. bob claims it and gets his fork; carol finds it full and gets none",734 () =>735 Effect.map(seen, ({ claimed, opened }) => {736 const bobFork = forkOf("parse-iso", bob);737738 expect(claimed.claim).toStrictEqual(739 ClaimView.make({740 ask: parseIso,741 base: opened.opened.landed,742 checkCommand: "bun test packages/parser/test/parse-iso.test.ts",743 claimant: bob.handle,744 fork: bobFork,745 lapsesAt: hoursAfter(noon, 24),746 openedAt: noon,747 project,748 remote: remoteOf(`${project}--parse-iso--bob`),749 state: "live",750 warnsAt: hoursAfter(noon, 2),751 })752 );753 expect(claimed.forkMain).toBe(opened.opened.landed);754 expect(claimed.alarmAfterClaim).toStrictEqual(755 Option.some(hoursAfter(noon, 2))756 );757 expect(claimed.carolRefused).toStrictEqual(758 new AskFull({ ask: parseIso })759 );760 expect(Exit.isFailure(claimed.carolFork)).toBeTruthy();761 })762 );763764 it.effect(765 "4. a push out of territory that edits CI hears both at once; submitting it is OutOfScope",766 () =>767 Effect.map(seen, ({ claimed }) => {768 const outside = new OutOfScope({769 paths: [RepoPath.make("packages/format/src/format.ts")],770 });771772 expect(claimed.wideRefusals).toStrictEqual([773 outside,774 new TouchedJudge({775 paths: [RepoPath.make(".github/workflows/ci.yml")],776 }),777 ]);778 expect(claimed.wideSubmitted).toStrictEqual(outside);779 })780 );781782 it.effect(783 "5. the fix is checked and lands, authored by bob, committed by the platform, credited",784 () =>785 Effect.map(seen, ({ answered, opened }) => {786 expect(answered.fixRefusals).toStrictEqual([]);787 expect(answered.receipt).toStrictEqual({788 ask: parseIso,789 base: opened.opened.landed,790 head: answered.fix,791 outcome: Outcome.cases.Checking.make({ stage: "merge" }),792 project,793 requestId: answered.requestId,794 });795 expect({796 author: answered.landing.author,797 committer: answered.landing.committer,798 parents: answered.landing.parents,799 }).toStrictEqual({800 author: authorLine(bob.handle),801 committer: committerLine,802 parents: [opened.opened.landed],803 });804 expect(805 answered.landing.trailers.filter(({ key }) =>806 ["Asked-by", "Signed-off-by"].includes(key)807 )808 ).toStrictEqual([809 { key: "Asked-by", value: userOf("alice") },810 { key: "Signed-off-by", value: userOf("bob") },811 ]);812 })813 );814815 it.effect(816 "5. status, the verdict, the landing and the asks read the landing back",817 () =>818 Effect.map(seen, ({ answered, opened }) => {819 expect({820 answers: answered.status.answers.map(({ outcome, requestId }) => ({821 outcome,822 requestId,823 })),824 claims: answered.status.claims.map(({ state }) => state),825 }).toStrictEqual({826 answers: [827 {828 outcome: Outcome.cases.Landed.make({ sha: answered.landed }),829 requestId: answered.requestId,830 },831 ],832 claims: ["answered"],833 });834 expect(answered.roundTrip).toStrictEqual(835 Option.fromUndefinedOr(answered.verdict)836 );837 expect({838 head: answered.verdict?.head,839 lanes: answered.verdict?.lanes.map(({ lane, result }) => ({840 lane,841 result,842 })),843 }).toStrictEqual({844 head: answered.fix,845 lanes: lanes.map((lane) => ({ lane, result: "passed" })),846 });847 expect(answered.view).toMatchObject({848 ask: parseIso,849 author: bob.handle,850 credits: [851 { handle: alice.handle, role: "Asked-by" },852 { handle: bob.handle, role: "Signed-off-by" },853 ],854 parent: opened.opened.landed,855 requestId: answered.requestId,856 sha: answered.landed,857 verdict: {858 outcome: Outcome.cases.Landed.make({ sha: answered.landed }),859 },860 });861 expect(answered.listedAfter).toStrictEqual({ asks: [] });862 })863 );864865 it.effect(866 "5. its events come in order, and the projection heard every one",867 () =>868 Effect.map(seen, ({ answered }) => {869 expect(answered.events).toStrictEqual([870 "Landed",871 "AskOpened",872 "Landed",873 "Claimed",874 "Pushed",875 "Pushed",876 "Judged",877 "Landed",878 "AskClosed",879 ]);880 expect(answered.projected).toStrictEqual(answered.events);881 })882 );883884 it.effect(885 "6. the same request again gets the same receipt, and nothing lands twice; nobody else's request is theirs",886 () =>887 Effect.map(seen, ({ answered }) => {888 expect(answered.replay).toStrictEqual(answered.receipt);889 expect(answered.tipAfterReplay).toBe(answered.landed);890 expect(answered.replayByCarol).toStrictEqual(891 Result.fail(NotClaimed.of(parseIso))892 );893 })894 );895896 it.effect(897 "7. a claim with no push is warned at 2 h and lapses at 24 h, and its answer is refused",898 () =>899 Effect.map(seen, ({ lapsed }) => {900 expect(lapsed.alarmAfterClaim).toStrictEqual(901 Option.some(hoursAfter(noon, 2))902 );903 expect(lapsed.warned).toStrictEqual({904 alarm: Option.some(hoursAfter(noon, 24)),905 last: "Warned",906 states: ["warned"],907 });908 expect(lapsed.lapsed).toStrictEqual({909 last: "Lapsed",910 states: ["lapsed"],911 });912 expect(lapsed.lateRefused).toStrictEqual(913 ClaimLapsed.of(AskId.make("format-date"))914 );915 })916 );917918 it.effect(919 "8. an answer whose land finds main moved re-merges cleanly and lands after the other",920 () =>921 Effect.map(seen, ({ raced }) => {922 expect(raced.waiting).toStrictEqual([923 Outcome.cases.Checking.make({ stage: "checks" }),924 ]);925 expect(raced.betweenParents).toStrictEqual([raced.base]);926 expect(raced.tipParents).toStrictEqual([raced.between]);927 expect(raced.outcomes).toStrictEqual([928 Outcome.cases.Landed.make({ sha: raced.tip }),929 ]);930 })931 );932933 it.effect(934 "8. an answer whose re-merge conflicts is refused as stale, naming the landing that moved the path, and main stays",935 () =>936 Effect.map(937 conflicting.pipe(Effect.provide(worldOf(scenario, store))),938 (raced) => {939 const lexed = RepoPath.make("packages/lexer/src/lex.ts");940941 expect(raced.tip).toBe(raced.between);942 expect(raced.outcomes).toStrictEqual([943 Outcome.cases.Refused.make({944 refusals: [945 new StaleBase({946 base: raced.base,947 conflicts: [lexed],948 main: raced.between,949 movedBy: [950 {951 ask: AskId.make("tidy-all"),952 author: frank.handle,953 landing: raced.between,954 path: lexed,955 },956 ],957 }),958 ],959 }),960 ]);961 }962 )963 );964 }965);966967const settling = Effect.gen(function* () {968 yield* advanceTo("2026-10-07T12:00:00Z");969970 const api = yield* projectService(project);971972 yield* api.initProject(alice, {});973974 const first = yield* Pusher.use((pusher) =>975 pusher.push(repo, Option.none(), start, "Start")976 );977978 yield* api.recordFirstPush(alice, first);979 yield* openRed(api, "parse-iso");980 yield* api.claim(bob, parseIso);981982 const fork = forkOf("parse-iso", bob);983 const host = yield* RepoHost;984985 const outboxOf = ProjectStore.use((store) => store.load()).pipe(986 Effect.map(({ outbox }) => outbox.map(({ kind }) => kind).toSorted())987 );988989 const before = {990 alarm: yield* scheduled,991 fork: Exit.isSuccess(yield* Effect.exit(host.refs(fork))),992 outbox: yield* outboxOf,993 };994995 yield* advanceTo(DateTime.formatIso(Option.getOrThrow(before.alarm)));996 yield* api.onAlarm();997998 return {999 after: {1000 fork: Exit.isSuccess(yield* Effect.exit(host.refs(fork))),1001 outbox: yield* outboxOf,1002 projected: yield* ProjectedRows.use(({ events }) =>1003 Effect.map(events, (rows) => rows.map(({ event }) => event._tag))1004 ),1005 },1006 before,1007 };1008});10091010const routing = Effect.gen(function* () {1011 yield* advanceTo("2026-10-07T12:00:00Z");10121013 const projects = yield* Projects;1014 const other = ProjectName.make("bob/burrow");1015 const made = yield* projects.create(project);1016 const again = yield* projects.create(project).pipe(Effect.flip);1017 const unknown = yield* projects.get(other).pipe(Effect.flip);10181019 yield* made.initProject(alice, {});1020 yield* projects.create(other);10211022 const found = yield* projects.get(project);10231024 return {1025 again,1026 initializedAgain: yield* found.initProject(alice, {}).pipe(Effect.flip),1027 otherInitialized: yield* Effect.exit(1028 Effect.flatMap(projects.get(other), (api) => api.initProject(bob, {}))1029 ),1030 unknown,1031 };1032});10331034const importing = Effect.gen(function* () {1035 yield* advanceTo("2026-10-07T12:00:00Z");10361037 const host = yield* RepoHost;1038 const upstream = RepoName.make("upstream");10391040 yield* host.create(upstream).pipe(Effect.orDie);10411042 const tip = yield* Pusher.use((pusher) =>1043 pusher.push(upstream, Option.none(), start, "Start")1044 );10451046 const api = yield* projectService(project);10471048 const refused = yield* api1049 .initProject(alice, { import: { url: "https://example.com/none.git" } })1050 .pipe(Effect.flip);10511052 const made = yield* api.initProject(alice, {1053 import: { url: "https://example.com/upstream.git" },1054 });10551056 return {1057 evaluated: yield* Evaluated.use(({ shas }) => shas),1058 firstPusher: yield* api.firstPusher(),1059 made,1060 main: yield* mainTip,1061 refused,1062 tip,1063 };1064});10651066const replaying = Effect.gen(function* () {1067 yield* advanceTo("2026-10-07T12:00:00Z");10681069 const api = yield* projectService(project);1070 const opened = yield* opening(api);1071 const claimed = yield* claiming(api, opened.opened.landed);1072 const before = yield* eventTags(api);10731074 const again = yield* api.recordPush({1075 after: claimed.wide,1076 before: Option.some(opened.opened.landed),1077 eventId: "push-wide",1078 pusher: bob,1079 ref: "refs/heads/main",1080 repo: forkOf("parse-iso", bob),1081 });10821083 return {1084 again,1085 events: [before, yield* eventTags(api)],1086 first: claimed.wideRefusals,1087 };1088});10891090const reopening = Effect.gen(function* () {1091 yield* advanceTo("2026-10-07T12:00:00Z");10921093 const api = yield* projectService(project);1094 const { opened } = yield* opening(api);10951096 yield* api.claim(bob, parseIso);10971098 const before = yield* eventTags(api);1099 const again = yield* openRed(api, "parse-iso");11001101 return {1102 again,1103 events: [before, yield* eventTags(api)],1104 listed: yield* api.listAsks(anyone),1105 main: yield* mainTip,1106 opened,1107 };1108});11091110const narrowDecider: WorldScenario = {1111 policy: {1112 ...scenario.policy,1113 deciders: [1114 ...scenario.policy.deciders,1115 {1116 handles: Array.make(dave.handle),1117 paths: Glob.make("packages/format/**"),1118 },1119 ],1120 },1121};11221123const decidingNarrowly = Effect.gen(function* () {1124 yield* advanceTo("2026-10-07T12:00:00Z");11251126 const api = yield* projectService(project);11271128 yield* api.initProject(alice, {});11291130 const first = yield* Pusher.use((pusher) =>1131 pusher.push(repo, Option.none(), start, "Start")1132 );11331134 yield* api.recordFirstPush(alice, first);11351136 const outside = yield* Effect.result(openRed(api, "parse-iso", dave));1137 const inside = yield* Effect.result(openRed(api, "format-date", dave));11381139 return {1140 inside: Result.map(inside, ({ ask }) => [ask.id, ask.askedBy]),1141 outside,1142 };1143});11441145describe("opening an ask", () => {1146 it.effect(1147 "again, once it is claimed, answers with the ask as it stands and lands nothing",1148 () =>1149 Effect.map(1150 reopening.pipe(Effect.provide(worldOf(scenario, "memory"))),1151 ({ again, events, listed, main, opened }) => {1152 expect(again).toStrictEqual({1153 ask: { ...opened.ask, state: "claimed" },1154 landed: opened.landed,1155 });1156 expect(main).toBe(opened.landed);1157 expect(events[1]).toStrictEqual(events[0]);1158 expect(listed.asks.map(({ claimed }) => claimed)).toStrictEqual([1159 true,1160 ]);1161 }1162 )1163 );11641165 it.effect("is for a maintainer whose paths hold the ask's territory", () =>1166 Effect.map(1167 decidingNarrowly.pipe(Effect.provide(worldOf(narrowDecider, "memory"))),1168 ({ inside, outside }) => {1169 expect(outside).toStrictEqual(Result.fail(new NotDecider({})));1170 expect(inside).toStrictEqual(1171 Result.succeed([AskId.make("format-date"), dave.handle])1172 );1173 }1174 )1175 );1176});11771178describe("the project's outbox", () => {1179 it.effect(1180 "keeps a fork and a projection that failed, and the next alarm runs them again",1181 () =>1182 Effect.map(1183 settling.pipe(1184 Effect.provide(worldOf(scenario, "memory", { failOnce: true }))1185 ),1186 ({ after, before }) => {1187 expect(before).toStrictEqual({1188 alarm: Option.some(DateTime.add(noon, { seconds: 1 })),1189 fork: false,1190 outbox: ["MakeFork", "Projected"],1191 });1192 // Projected again after the later events: the memory projection keeps no cursor.1193 expect(after).toStrictEqual({1194 fork: true,1195 outbox: [],1196 projected: ["AskOpened", "Landed", "Claimed", "Landed"],1197 });1198 }1199 )1200 );12011202 it.effect("acts on one push event once, however often it is reported", () =>1203 Effect.map(1204 replaying.pipe(Effect.provide(worldOf(scenario, "memory"))),1205 ({ again, events, first }) => {1206 expect(again).toStrictEqual(first);1207 expect(events[1]).toStrictEqual(events[0]);1208 }1209 )1210 );1211});12121213describe("projects", () => {1214 it.effect("are made once each, found by name, and kept apart", () =>1215 Effect.map(1216 routing.pipe(1217 Effect.provide(1218 ProjectsMemory.pipe(Layer.provideMerge(worldOf(scenario, "memory")))1219 )1220 ),1221 (seen) => {1222 expect(seen.again).toStrictEqual(new ProjectExists({ project }));1223 expect(seen.unknown).toStrictEqual(1224 new UnknownProject({ project: ProjectName.make("bob/burrow") })1225 );1226 expect(seen.initializedAgain).toStrictEqual(1227 new ProjectExists({ project })1228 );1229 expect(seen.otherInitialized).toStrictEqual(1230 Exit.succeed({1231 project: ProjectName.make("bob/burrow"),1232 remote: remoteOf("bob/burrow"),1233 })1234 );1235 }1236 )1237 );12381239 it.effect(1240 "adopt an imported repo's tip as their first landing, awaiting no first push, and refuse a repo they can't read",1241 () =>1242 Effect.map(1243 importing.pipe(Effect.provide(worldOf(scenario, "memory"))),1244 (seen) => {1245 expect(seen.made).toStrictEqual({1246 landed: seen.tip,1247 project,1248 remote: remoteOf(project),1249 });1250 expect([seen.main, seen.evaluated, seen.firstPusher]).toStrictEqual([1251 seen.tip,1252 [seen.tip],1253 Option.none(),1254 ]);1255 expect(seen.refused).toStrictEqual(1256 new ImportFailed({ reason: "no repo at memory://none.git" })1257 );1258 }1259 )1260 );1261});12621263const noAny = AskId.make("no-any");12641265const lintScenario = aProject({ people }).pipe(1266 withVouches(people),1267 withKind({1268 checkKind: "lintToZero",1269 claimers: "vouched",1270 finish: "never",1271 name: "lintToZero",1272 oneWay: false,1273 race: 1,1274 requires: ["want", "check", "territory"],1275 strength: "assertion",1276 }),1277 withAsk({1278 check: CheckSpec.cases.LintToZero.make({1279 command: Command.make("oxlint --format json"),1280 rule: "typescript/no-explicit-any",1281 }),1282 id: noAny,1283 kind: "lintToZero",1284 territory: "packages/parser",1285 })1286);12871288const lintPrinting = (count: number) =>1289 JSON.stringify({1290 // `Array.makeBy` makes at least one: none is its own case.1291 diagnostics:1292 count === 01293 ? []1294 : Array.makeBy(count, (line) => ({1295 code: "typescript(no-explicit-any)",1296 filename: "packages/parser/src/parse.ts",1297 labels: [1298 { span: { column: 1, length: 3, line: line + 1, offset: 0 } },1299 ],1300 message: "Unexpected `any`. Specify a different type.",1301 severity: "error",1302 })),1303 number_of_files: 1,1304 number_of_rules: 1,1305 });13061307/** The lint exits 1 on any finding, so only the count tells two runs apart. */1308const lintPrints = (counts: readonly number[]) =>1309 Layer.effect(1310 CheckRunner,1311 Effect.gen(function* () {1312 const left = yield* Ref.make(counts);13131314 return CheckRunner.of({1315 run: (job) =>1316 Effect.gen(function* () {1317 const count = yield* Ref.modify(left, ([next = 0, ...rest]) => [1318 next,1319 rest,1320 ]);13211322 return {1323 durationMs: 1,1324 evidence: job.lanes.map(({ lane }) => ({1325 lane,1326 signature: `${lane}: lint exited 1`,1327 })),1328 heldBack: [],1329 lanes: job.lanes.map(({ command, lane }) => ({1330 command,1331 durationMs: 1,1332 lane,1333 result: "failed" as const,1334 })),1335 outputs: job.lanes.flatMap(({ lane, output }) =>1336 output === "stdout"1337 ? [{ lane, stdout: lintPrinting(count) }]1338 : []1339 ),1340 };1341 }),1342 });1343 })1344 );13451346const openingByCount = (counts: readonly number[]) =>1347 Effect.gen(function* () {1348 yield* advanceTo("2026-10-07T12:00:00Z");13491350 const api = yield* projectService(project);13511352 yield* api.initProject(alice, {});13531354 const first = yield* Pusher.use((pusher) =>1355 pusher.push(repo, Option.none(), start, "Start")1356 );13571358 yield* api.recordFirstPush(alice, first);13591360 const { file } = Option.getOrThrow(1361 Array.findFirst(lintScenario.policy.asks, ({ id }) => id === noAny)1362 );13631364 return yield* Effect.result(1365 api.openAsk(alice, {1366 ask: noAny,1367 files: Array.make({1368 content: `export default "${noAny}";\n`,1369 path: file,1370 }),1371 })1372 );1373 }).pipe(1374 Effect.provide(1375 Layer.merge(worldOf(lintScenario, "memory"), lintPrints(counts))1376 )1377 );13781379describe("opening a lintToZero ask", () => {1380 it.effect(1381 "is red first when its rule counts the same, above zero, twice on main",1382 () =>1383 Effect.map(openingByCount([3, 3]), (opened) => {1384 expect(1385 Result.map(opened, ({ ask }) => [ask.id, ask.check._tag])1386 ).toStrictEqual(Result.succeed([noAny, "LintToZero"]));1387 })1388 );13891390 it.effect("is refused NotRedFirst when its rule counts nothing on main", () =>1391 Effect.map(openingByCount([0, 0]), (opened) => {1392 expect(opened).toStrictEqual(Result.fail(new NotRedFirst({})));1393 })1394 );13951396 it.effect(1397 "is refused NotRedFirst when the two runs on main count differently",1398 () =>1399 Effect.map(openingByCount([3, 2]), (opened) => {1400 expect(opened).toStrictEqual(Result.fail(new NotRedFirst({})));1401 })1402 );1403});