Skip to content
Myr

deciders.test.ts

This file

Path

packages/project/test/deciders.test.ts

1,507 lines · 41.9 KiB · TypeScript

Last changed by

Merge build/standing-caps into mainoscabrielbefore adoption8a78de8

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { shaOf } from "@repo/checks/check-runner";5import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";6import type { Ask } from "@repo/protocol/domain/ask";7import { CheckSpec } from "@repo/protocol/domain/check";8import { Glob, RefNameText } from "@repo/protocol/domain/common";9import { DecisionSubject } from "@repo/protocol/domain/decision";10import { ProjectEvent } from "@repo/protocol/domain/event";11import { Outcome } from "@repo/protocol/domain/outcome";12import {13  AskId,14  CommitSha,15  DecisionId,16  Handle,17  LandedSha,18  LaneName,19  ProjectName,20  ProposalId,21  RepoName,22  RepoPath,23  keyOf,24  RequestId,25} from "@repo/protocol/ids";26import { Anonymous, Person } from "@repo/protocol/principal";27import {28  CapReached,29  DecisionClosed,30  Denounced,31  NotDecider,32  NotVouched,33  TouchedJudge,34  UnknownAsk,35  VerifierBlocked,36} from "@repo/protocol/refusal";37import { RulesEvaluator } from "@repo/rules/rules-evaluator";38import { parseVouchFile } from "@repo/rules/vouch";39import { advanceTo, at as instant } from "@repo/testkit/clock";40import type { Files } from "@repo/testkit/git-client";41import {42  aProject,43  withAsk,44  withKind,45  withVouches,46} from "@repo/testkit/scenarios";47import { Array, DateTime, Effect, Exit, Layer, Option, Result } from "effect";4849import { ScheduledAlarm } from "../src/alarms/memory.ts";50import { platformHandle } from "../src/attention/effects.ts";51import { ProjectStore } from "../src/project-store.ts";52import type { ProjectApi } from "../src/project.ts";53import { projectService } from "../src/project.ts";54import { creditsFor, Projects } from "../src/projects.ts";55import { ProjectsMemory } from "../src/projects/memory.ts";56import { CheckScript, composedAt, mergedAt, Pusher, worldOf } from "./world.ts";5758const people = ["bob", "carol", "dave", "erin", "eve", "frank"];5960const scenario = aProject({ people }).pipe(61  withVouches(["bob", "carol", "erin", "eve", "frank"]),62  withKind({63    checkKind: "redThenGreen",64    claimers: "vouched",65    finish: "required",66    name: "polish",67    oneWay: false,68    race: 1,69    requires: ["want", "check", "territory"],70    strength: "assertion",71  }),72  withAsk({ id: "parse-iso", territory: "packages/parser" }),73  withAsk({ id: "trim-input", territory: "packages/trim" }),74  withAsk({ id: "lex-tokens", territory: "packages/lexer" }),75  withAsk({ id: "format-date", kind: "polish", territory: "packages/format" })76);7778const { project } = scenario;7980const repo = RepoName.make(keyOf(project));8182const mainRef = RefName.make("refs/heads/main");8384const person = (name: string) =>85  Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });8687const alice = person("alice");8889const aliceSignedIn = Person.make({ handle: Handle.make("Alice") });9091const bob = person("bob");9293const carol = person("carol");9495const dave = person("dave");9697const erin = person("erin");9899const eve = person("eve");100101const frank = person("frank");102103const anyone = Anonymous.make({});104105const userOf = (handle: string) =>106  `${handle} <${handle}@users.${Brand.domain}>`;107108const askOf = (id: string): Ask =>109  Option.getOrThrow(110    Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)111  );112113const redThenGreen = LaneName.make("redThenGreen");114115const noon = instant("2026-10-07T12:00:00Z");116117const daysAfter = (from: DateTime.Utc, count: number) =>118  DateTime.add(from, { days: count });119120const start: Files = [121  [122    "package.json",123    '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',124  ],125  [126    "packages/format/src/format.ts",127    "export const format = (d) => String(d);\n",128  ],129  ["packages/lexer/src/lex.ts", "export const lex = (s) => s.split(' ');\n"],130  ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],131  ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],132];133134const askFiles = (id: string) => {135  const { check, file, territory } = askOf(id);136137  const subject = territory.module;138139  return Array.make(140    { content: `export default "${id}";\n`, path: file },141    {142      content: [143        `import { expect, it } from "vitest";`,144        `import { ${subject} } from "../src/${subject}.ts";`,145        ``,146        `it("${id}", () => {`,147        `  expect(${subject}(" 2026 ")).toStrictEqual("2026");`,148        `});`,149        ``,150      ].join("\n"),151      path: CheckSpec.guards.RedThenGreen(check)152        ? check.path153        : RepoPath.make(`test/${id}.test.ts`),154    }155  );156};157158const tipOf = (name: RepoName) =>159  Effect.gen(function* () {160    const refs = yield* (yield* RepoHost).refs(name).pipe(Effect.orDie);161162    return LandedSha.make(163      Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))164    );165  });166167const mainTip = tipOf(repo);168169const commitOf = (sha: CommitSha) =>170  Effect.gen(function* () {171    const host = yield* RepoHost;172    const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);173    const { author, committer, message, parents } = Option.getOrThrow(read);174175    return { author, committer, parents, trailers: parseTrailers(message) };176  });177178const scheduled = ScheduledAlarm.use(({ at }) => at);179180const stored = ProjectStore.use((store) => store.load());181182const made = (api: ProjectApi, on: RepoName, files: Files = start) =>183  Effect.gen(function* () {184    yield* api.initProject(alice, {});185186    const first = yield* Pusher.use((pusher) =>187      pusher.push(on, Option.none(), files, "Start")188    );189190    yield* api.recordFirstPush(alice, first);191192    return api;193  });194195const begun = Effect.gen(function* () {196  yield* advanceTo("2026-10-07T12:00:00Z");197198  return yield* made(yield* projectService(project), repo);199});200201const redOnMain = (202  files: Array.NonEmptyReadonlyArray<{203    readonly content: string;204    readonly path: RepoPath;205  }>,206  on: RepoName = repo207) =>208  Effect.gen(function* () {209    const composed = yield* composedAt(on, yield* tipOf(on), files);210211    yield* CheckScript.use((checker) =>212      checker.script(composed, redThenGreen, ["failed", "failed"])213    );214  });215216const openRed = (api: ProjectApi, id: string, on: RepoName = repo) =>217  Effect.gen(function* () {218    const files = askFiles(id);219220    yield* redOnMain(files, on);221222    return yield* api.openAsk(alice, { ask: AskId.make(id), files });223  });224225const lanes = [redThenGreen, LaneName.make("lint"), LaneName.make("types")];226227const changed = (files: Files, path: string, content: string): Files => [228  ...files.filter(([each]) => each !== path),229  [path, content],230];231232const withAskFiles = (files: Files, ...ids: readonly string[]): Files => [233  ...files,234  ...ids.flatMap((id) =>235    askFiles(id).map(({ content, path }) => [path, content] as const)236  ),237];238239const answered = (240  api: ProjectApi,241  input: {242    readonly change: readonly [path: string, content: string];243    readonly files: Files;244    readonly id: string;245    readonly on?: RepoName;246    readonly who: Person;247  }248) =>249  Effect.gen(function* () {250    const ask = AskId.make(input.id);251    const on = input.on ?? repo;252    const base = yield* tipOf(on);253    const { claim } = yield* api.claim(input.who, ask);254255    const head = yield* Pusher.use((pusher) =>256      pusher.push(257        claim.fork,258        Option.some(base),259        changed(input.files, ...input.change)260      )261    );262263    const merged = yield* mergedAt({264      base,265      fork: claim.fork,266      head,267      main: base,268      repo: on,269    });270271    yield* CheckScript.use((checker) =>272      Effect.forEach(273        lanes,274        (lane) => checker.script(merged, lane, ["passed"]),275        {276          discard: true,277        }278      )279    );280281    const receipt = yield* api.submitAnswer(input.who, {282      ask,283      base,284      head,285      requestId: RequestId.make(`req-${input.id}`),286    });287288    return { base, fork: claim.fork, head, receipt };289  });290291const firstDecision = DecisionId.make("dec-000001");292293const proposing = (api: ProjectApi) =>294  Effect.gen(function* () {295    const files = askFiles("trim-input");296297    const proposed = yield* api.proposeAsk(carol, {298      files,299      territory: "packages/trim",300      want: askOf("trim-input").brief.want,301    });302303    const onToday = yield* api.today(alice);304    const alarm = yield* scheduled;305306    // The cap is for the public: dave is not vouched, carol is.307    const second = yield* api.proposeAsk(dave, { want: "Trim tabs too" });308309    yield* api.proposeAsk(dave, { want: "Trim spaces too" });310311    const third = yield* api312      .proposeAsk(dave, { want: "Trim newlines too" })313      .pipe(Effect.flip);314315    const beyondCap = yield* api316      .proposeAsk(carol, { want: "Trim carriage returns too" })317      .pipe(Effect.result, Effect.map(Result.isSuccess));318319    yield* redOnMain(files);320321    const accepted = yield* api.decide(alice, {322      choice: "accept",323      decision: firstDecision,324    });325326    const landed = yield* mainTip;327328    return {329      accepted,330      again: yield* api331        .decide(alice, { choice: "decline", decision: firstDecision })332        .pipe(Effect.flip),333      alarm,334      beyondCap,335      bobDecides: yield* api336        .decide(bob, {337          choice: "accept",338          decision: DecisionId.make("dec-000002"),339        })340        .pipe(Effect.flip),341      commit: yield* commitOf(landed),342      listed: yield* api.listAsks(anyone),343      onToday,344      proposals: (yield* stored).proposals,345      proposed,346      second,347      third,348    };349  });350351const expiring = (api: ProjectApi) =>352  Effect.gen(function* () {353    yield* api.proposeAsk(carol, { want: "Trim tabs too" });354    yield* advanceTo("2026-10-21T12:00:00Z");355    yield* api.onAlarm();356357    const { decisions, proposals } = yield* stored;358    const events = yield* api.events(0, 100);359360    return {361      decided: events.flatMap(({ event }) =>362        ProjectEvent.guards.Decided(event)363          ? [{ choice: event.choice, decision: event.decision }]364          : []365      ),366      decisions,367      proposals,368      today: yield* api.today(alice),369    };370  });371372const acceptingBlocked = (api: ProjectApi) =>373  Effect.gen(function* () {374    const files = askFiles("trim-input");375376    yield* api.proposeAsk(carol, {377      files,378      territory: "packages/trim",379      want: askOf("trim-input").brief.want,380    });381382    const blocked = yield* api383      .decide(alice, { choice: "accept", decision: firstDecision })384      .pipe(Effect.result, Effect.map(Result.getFailure));385386    const between = yield* stored;387    const { budget } = yield* api.today(alice);388389    yield* redOnMain(files);390391    const accepted = yield* api392      .decide(alice, { choice: "accept", decision: firstDecision })393      .pipe(394        Effect.result,395        Effect.map(Result.getSuccess),396        Effect.map(Option.map(({ decision }) => decision.decided?.choice))397      );398399    return {400      accepted,401      blocked,402      budget,403      decided: between.decisions.map(({ decided }) => decided),404      listed: (yield* api.listAsks(anyone)).asks.map(({ ask }) => ask),405      proposals: between.proposals.map(({ state }) => state),406    };407  });408409const splitDeciders = {410  policy: {411    ...scenario.policy,412    deciders: [413      { handles: Array.make(alice.handle), paths: Glob.make("packages/**") },414      {415        handles: Array.make(frank.handle),416        paths: Glob.make(`${Brand.configDir}/**`),417      },418    ],419  },420};421422const askedToDecide = Effect.gen(function* () {423  const api = yield* begun;424425  const { proposal } = yield* api.proposeAsk(carol, {426    files: askFiles("trim-input"),427    territory: "packages/trim",428    want: askOf("trim-input").brief.want,429  });430431  return {432    alice: (yield* api.today(alice)).decisions.map(({ deciders, subject }) => ({433      deciders,434      subject,435    })),436    frank: (yield* api.today(frank)).decisions,437    proposal: proposal.id,438  };439});440441describe("a proposal", () => {442  const world = worldOf(scenario, "memory");443  const proposal = ProposalId.make("prop-000001");444  const seen = Effect.flatMap(begun, proposing).pipe(Effect.provide(world));445446  it.effect(447    "is a decision on Today for its maintainers, with a default, expiring in fourteen days, and held to a cap",448    () =>449      Effect.map(seen, (run) => {450        expect(run.proposed.proposal).toStrictEqual({451          expiresAt: daysAfter(noon, 14),452          files: askFiles("trim-input").map(({ path }) => path),453          id: proposal,454          openedAt: noon,455          project,456          proposer: carol.handle,457          state: "open",458          territory: "packages/trim",459          want: askOf("trim-input").brief.want,460        });461        expect(462          run.onToday.decisions.map(463            ({ default: fallback, deciders, subject }) => ({464              deciders,465              fallback,466              subject,467            })468          )469        ).toStrictEqual([470          {471            deciders: [alice.handle],472            fallback: "decline",473            subject: DecisionSubject.cases.OpenProposal.make({ proposal }),474          },475        ]);476        expect(run.alarm).toStrictEqual(Option.some(daysAfter(noon, 14)));477        expect([478          run.second.proposal.state,479          run.third,480          run.beyondCap,481        ]).toStrictEqual([482          "open",483          new CapReached({ cap: 2, limit: "proposals" }),484          true,485        ]);486      })487  );488489  it.effect(490    "accepted, opens its ask red first, asked by its proposer and decided by the maintainer",491    () =>492      Effect.map(seen, (run) => {493        expect(run.accepted.decision.decided).toStrictEqual({494          at: noon,495          by: alice.handle,496          choice: "accept",497        });498        expect({499          author: run.commit.author,500          committer: run.commit.committer,501          credits: run.commit.trailers.filter(({ key }) =>502            ["Asked-by", "Decided-by"].includes(key)503          ),504        }).toStrictEqual({505          author: authorLine(carol.handle),506          committer: committerLine,507          credits: [508            { key: "Asked-by", value: userOf("carol") },509            { key: "Decided-by", value: userOf("alice") },510          ],511        });512        expect(run.listed.asks.map(({ ask }) => ask)).toStrictEqual([513          AskId.make("trim-input"),514        ]);515        expect(run.proposals.map(({ id, state }) => [id, state])).toStrictEqual(516          [517            [proposal, "accepted"],518            [ProposalId.make("prop-000002"), "open"],519            [ProposalId.make("prop-000003"), "open"],520            [ProposalId.make("prop-000004"), "open"],521          ]522        );523      })524  );525526  it.effect("decided once, is closed, and only its maintainers decide it", () =>527    Effect.map(seen, (run) => {528      expect(run.again).toStrictEqual(529        new DecisionClosed({ decision: firstDecision })530      );531      expect(run.bobDecides).toStrictEqual(new NotDecider({}));532    })533  );534535  it.effect(536    "accepted while its check cannot run, decides nothing and stays open, so it can be accepted again",537    () =>538      Effect.map(539        Effect.flatMap(begun, acceptingBlocked).pipe(Effect.provide(world)),540        (run) => {541          expect(run.blocked).toStrictEqual(542            Option.some(new VerifierBlocked({}))543          );544          expect([run.decided, run.proposals, run.budget]).toStrictEqual([545            [undefined],546            ["open"],547            { finishes: 0, total: 5, used: 0 },548          ]);549          expect([run.accepted, run.listed]).toStrictEqual([550            Option.some("accept"),551            [AskId.make("trim-input")],552          ]);553        }554      )555  );556557  it.effect(558    "is put to the maintainers of its territory, not to those of the config folder its ask file sits in",559    () =>560      Effect.map(561        askedToDecide.pipe(Effect.provide(worldOf(splitDeciders, "memory"))),562        (run) => {563          expect(run.alice).toStrictEqual([564            {565              deciders: [alice.handle],566              subject: DecisionSubject.cases.OpenProposal.make({567                proposal: run.proposal,568              }),569            },570          ]);571          expect(run.frank).toStrictEqual([]);572        }573      )574  );575576  it.effect(577    "left alone for fourteen days expires, and its decision takes its default by the platform's hand",578    () =>579      Effect.map(580        Effect.flatMap(begun, expiring).pipe(Effect.provide(world)),581        (run) => {582          const expiredAt = daysAfter(noon, 14);583584          expect(run.proposals.map(({ state }) => state)).toStrictEqual([585            "expired",586          ]);587          expect(run.decisions.map(({ decided }) => decided)).toStrictEqual([588            { at: expiredAt, by: platformHandle, choice: "decline" },589          ]);590          expect(run.decided).toStrictEqual([591            { choice: "decline", decision: firstDecision },592          ]);593          expect(run.today.decisions).toStrictEqual([]);594        }595      )596  );597});598599const finishing = (api: ProjectApi) =>600  Effect.gen(function* () {601    yield* openRed(api, "format-date");602603    const answer = yield* answered(api, {604      change: [605        "packages/format/src/format.ts",606        "export const format = (d) => d.toISOString();\n",607      ],608      files: withAskFiles(start, "format-date"),609      id: "format-date",610      who: bob,611    });612613    const waiting = (yield* api.status(bob)).answers.map(614      ({ outcome }) => outcome615    );616617    const bobFinishes = yield* api618      .finish(bob, {619        ask: AskId.make("format-date"),620        base: answer.base,621        head: answer.head,622        requestId: RequestId.make("finish-bob-01"),623      })624      .pipe(Effect.flip);625626    const finish = {627      ask: AskId.make("format-date"),628      base: answer.base,629      head: answer.head,630      requestId: RequestId.make("finish-alice-01"),631    };632633    // Her sign-in cases her handle otherwise than the policy does.634    const receipt = yield* api.finish(aliceSignedIn, finish);635    const landed = yield* mainTip;636637    return {638      again: yield* api.finish(aliceSignedIn, finish),639      answer,640      bobFinishes,641      budget: (yield* api.today(alice)).budget,642      commit: yield* commitOf(landed),643      landed,644      receipt,645      settled: (yield* api.status(bob)).answers.map(({ outcome }) => outcome),646      waiting,647    };648  });649650const finishingOnTop = (api: ProjectApi) =>651  Effect.gen(function* () {652    yield* openRed(api, "format-date");653654    const files = withAskFiles(start, "format-date");655    const formatPath = "packages/format/src/format.ts";656    const ask = AskId.make("format-date");657658    const answer = yield* answered(api, {659      change: [formatPath, "export const format = (d) => d.toISOString();\n"],660      files,661      id: "format-date",662      who: bob,663    });664665    const polishedFiles = changed(666      files,667      formatPath,668      "export const format = (d) => d.toISOString().slice(0, 10);\n"669    );670671    const polished = yield* Pusher.use((pusher) =>672      pusher.push(answer.fork, Option.some(answer.head), polishedFiles)673    );674675    const judging = yield* Pusher.use((pusher) =>676      pusher.push(677        answer.fork,678        Option.some(polished),679        changed(680          polishedFiles,681          askOf("format-date").file,682          'export default "easier";\n'683        )684      )685    );686687    const touched = yield* api688      .finish(alice, {689        ask,690        base: answer.base,691        head: judging,692        requestId: RequestId.make("finish-alice-02"),693      })694      .pipe(Effect.flip);695696    const merged = yield* mergedAt({697      base: answer.base,698      fork: answer.fork,699      head: polished,700      main: answer.base,701      repo,702    });703704    yield* CheckScript.use((checker) =>705      Effect.forEach(706        lanes,707        (lane) => checker.script(merged, lane, ["passed"]),708        {709          discard: true,710        }711      )712    );713714    const receipt = yield* api.finish(alice, {715      ask,716      base: answer.base,717      head: polished,718      requestId: RequestId.make("finish-alice-03"),719    });720721    const landed = yield* mainTip;722    const host = yield* RepoHost;723724    const format = yield* host725      .readFile(726        repo,727        Revision.Commit({ sha: landed }),728        RepoPath.make(formatPath)729      )730      .pipe(Effect.orDie);731732    return {733      commit: yield* commitOf(landed),734      format: Option.map(format, (bytes) => new TextDecoder().decode(bytes)),735      polished,736      receipt,737      touched,738    };739  });740741describe("a finish", () => {742  const seen = Effect.flatMap(begun, finishing).pipe(743    Effect.provide(worldOf(scenario, "memory"))744  );745746  it.effect("is a maintainer's, on an answer that waits on one", () =>747    Effect.map(seen, (run) => {748      expect(run.waiting).toStrictEqual([749        Outcome.cases.AwaitingFinish.make({}),750      ]);751      expect(run.bobFinishes).toStrictEqual(new NotDecider({}));752      expect(run.receipt).toStrictEqual({753        ask: AskId.make("format-date"),754        base: run.answer.base,755        head: run.answer.head,756        outcome: Outcome.cases.Checking.make({ stage: "human" }),757        project,758        requestId: RequestId.make("finish-alice-01"),759      });760    })761  );762763  it.effect(764    "with the maintainer's commits on top, checks them again from the merge and lands them, the answerer still its author",765    () =>766      Effect.map(767        Effect.flatMap(begun, finishingOnTop).pipe(768          Effect.provide(worldOf(scenario, "memory"))769        ),770        (run) => {771          expect(run.touched).toStrictEqual(772            new TouchedJudge({ paths: [askOf("format-date").file] })773          );774          expect([run.receipt.head, run.receipt.outcome]).toStrictEqual([775            run.polished,776            Outcome.cases.Checking.make({ stage: "merge" }),777          ]);778          expect(run.format).toStrictEqual(779            Option.some(780              "export const format = (d) => d.toISOString().slice(0, 10);\n"781            )782          );783          expect({784            author: run.commit.author,785            credits: run.commit.trailers.filter(({ key }) =>786              ["Signed-off-by", "Finished-by"].includes(key)787            ),788          }).toStrictEqual({789            author: authorLine(bob.handle),790            credits: [791              { key: "Signed-off-by", value: userOf("bob") },792              { key: "Finished-by", value: userOf("alice") },793            ],794          });795        }796      )797  );798799  it.effect(800    "lands the answer credited Finished-by, once however often it is sent, and counts in the maintainer's budget, however her sign-in cases her handle",801    () =>802      Effect.map(seen, (run) => {803        expect([run.settled, run.again.outcome]).toStrictEqual([804          [Outcome.cases.Landed.make({ sha: run.landed })],805          Outcome.cases.Landed.make({ sha: run.landed }),806        ]);807        expect({808          author: run.commit.author,809          credits: run.commit.trailers.filter(({ key }) =>810            ["Asked-by", "Signed-off-by", "Finished-by"].includes(key)811          ),812        }).toStrictEqual({813          author: authorLine(bob.handle),814          credits: [815            { key: "Asked-by", value: userOf("alice") },816            { key: "Signed-off-by", value: userOf("bob") },817            { key: "Finished-by", value: userOf("alice") },818          ],819        });820        expect(run.budget).toStrictEqual({ finishes: 1, total: 5, used: 0 });821      })822  );823});824825const landingOwn = (api: ProjectApi) =>826  Effect.gen(function* () {827    const host = yield* RepoHost;828    const forked = yield* api.fork(alice);829    const again = yield* api.fork(alice);830    const daveForks = yield* api.fork(dave).pipe(Effect.flip);831    const base = yield* mainTip;832    const forkRefs = yield* host.refs(forked.fork).pipe(Effect.orDie);833    const forkMain = forkRefs.get(mainRef);834835    const head = yield* Pusher.use((pusher) =>836      pusher.push(837        forked.fork,838        Option.some(base),839        changed(840          start,841          "packages/lexer/src/lex.ts",842          "export const lex = (s) => s.split(/ +/);\n"843        )844      )845    );846847    const merged = yield* mergedAt({848      base,849      fork: forked.fork,850      head,851      main: base,852      repo,853    });854855    yield* CheckScript.use((checker) =>856      Effect.forEach(857        [LaneName.make("lint"), LaneName.make("types")],858        (lane) => checker.script(merged, lane, ["passed"]),859        { discard: true }860      )861    );862863    const request = {864      base,865      head,866      message: "Split words on runs of spaces\n\nTwo spaces are one gap.",867      requestId: RequestId.make("land-alice-01"),868    };869870    const bobLands = yield* api.land(bob, request).pipe(Effect.flip);871    const receipt = yield* api.land(alice, request);872    const landed = yield* mainTip;873874    const skipping = yield* Pusher.use((pusher) =>875      pusher.push(876        forked.fork,877        Option.some(head),878        changed(879          changed(880            start,881            "packages/lexer/src/lex.ts",882            "export const lex = (s) => s.split(/ +/);\n"883          ),884          "packages/lexer/test/lex.test.ts",885          'it.skip("lexes", () => {});\n'886        )887      )888    );889890    const weakened = yield* api.land(alice, {891      base: head,892      head: skipping,893      message: "Skip the lexer's test",894      requestId: RequestId.make("land-alice-02"),895    });896897    return {898      afterWeakened: yield* mainTip,899      again,900      base,901      bobLands,902      commit: yield* commitOf(landed),903      daveForks,904      forkMain,905      forked,906      jobs: yield* CheckScript.use(({ jobs }) => jobs),907      landed,908      merged,909      receipt,910      replay: yield* api.land(alice, request),911      view: (yield* api.landing(anyone, landed)).landing,912      weakened,913    };914  });915916describe("a maintainer's own change", () => {917  const seen = Effect.flatMap(begun, landingOwn).pipe(918    Effect.provide(worldOf(scenario, "memory"))919  );920921  it.effect(922    "comes from a working fork that is made once, for vouched people only",923    () =>924      Effect.map(seen, (run) => {925        const fork = RepoName.make(`${keyOf(project)}--me--alice`);926927        expect(run.forked).toStrictEqual({928          fork,929          remote: `https://${Brand.domain}/${project}--me--alice.git`,930        });931        expect([run.again, run.forkMain]).toStrictEqual([run.forked, run.base]);932        expect(run.daveForks).toStrictEqual(new NotVouched({}));933      })934  );935936  it.effect(937    "passes the same stages and checks, and lands once as a platform commit its maintainer authors",938    () =>939      Effect.map(seen, (run) => {940        expect(run.bobLands).toStrictEqual(new NotDecider({}));941        expect([run.receipt, run.replay]).toStrictEqual([942          {943            base: run.base,944            head: run.receipt.head,945            outcome: Outcome.cases.Landed.make({ sha: run.landed }),946            project,947            requestId: RequestId.make("land-alice-01"),948          },949          run.receipt,950        ]);951        expect({952          author: run.commit.author,953          committer: run.commit.committer,954          parents: run.commit.parents,955          signed: run.commit.trailers.filter(956            ({ key }) => key === "Signed-off-by"957          ),958        }).toStrictEqual({959          author: authorLine(alice.handle),960          committer: committerLine,961          parents: [run.base],962          signed: [{ key: "Signed-off-by", value: userOf("alice") }],963        });964        expect(run.view).toMatchObject({965          author: alice.handle,966          parent: run.base,967          requestId: RequestId.make("land-alice-01"),968          sha: run.landed,969        });970      })971  );972973  it.effect(974    "checks its merged tree in the maintainer's working fork, where the Lander's merge leaves it",975    () =>976      Effect.map(seen, (run) => {977        expect(978          run.jobs979            .filter(({ at }) => shaOf(at) === shaOf(run.merged))980            .map((job) => job.repo)981        ).toStrictEqual([run.forked.fork]);982      })983  );984985  it.effect(986    "is refused by stage 1 when it weakens a check, and main stays",987    () =>988      Effect.map(seen, (run) => {989        expect(run.afterWeakened).toBe(run.landed);990        expect(991          Outcome.guards.Refused(run.weakened.outcome)992            ? run.weakened.outcome.refusals.map(({ _tag }) => _tag)993            : []994        ).toStrictEqual(["Weakened"]);995      })996  );997});998999const vouchingWorld = Layer.effect(1000  RulesEvaluator,1001  Effect.gen(function* () {1002    const evaluator = yield* RulesEvaluator;10031004    return RulesEvaluator.of({1005      ...evaluator,1006      evaluate: (input) =>1007        Effect.map(evaluator.evaluate(input), (policy) => ({1008          ...policy,1009          vouches: [1010            ...policy.vouches,1011            ...parseVouchFile(input.facts.vouchFile ?? "").vouches.map(1012              ({ denounced, handle }) => ({ denounced, handle })1013            ),1014          ],1015        })),1016    });1017  })1018).pipe(Layer.provideMerge(worldOf(scenario, "memory")));10191020const vouchFileNow = Effect.gen(function* () {1021  const host = yield* RepoHost;1022  const at = yield* mainTip;10231024  const bytes = yield* host1025    .readFile(1026      repo,1027      Revision.Commit({ sha: at }),1028      RepoPath.make(`${Brand.configDir}/vouched.td`)1029    )1030    .pipe(Effect.orDie);10311032  return Option.map(bytes, (read) => new TextDecoder().decode(read));1033});10341035const vouching = (api: ProjectApi) =>1036  Effect.gen(function* () {1037    yield* openRed(api, "lex-tokens");1038    yield* openRed(api, "parse-iso");10391040    const lexTokens = AskId.make("lex-tokens");1041    const before = yield* api.claim(dave, lexTokens).pipe(Effect.flip);10421043    const bobVouches = yield* api1044      .vouch(bob, { handle: Handle.make("dave"), verdict: "vouch" })1045      .pipe(Effect.flip);10461047    const vouched = yield* api.vouch(alice, {1048      handle: Handle.make("dave"),1049      verdict: "vouch",1050    });10511052    const fileAfterVouch = yield* vouchFileNow;1053    const commit = yield* commitOf(vouched.landed);1054    const claimed = yield* api.claim(dave, lexTokens);10551056    const again = yield* api.vouch(alice, {1057      handle: Handle.make("dave"),1058      verdict: "vouch",1059    });10601061    const denounced = yield* api.vouch(alice, {1062      handle: Handle.make("erin"),1063      note: "pushed  a secret",1064      verdict: "denounce",1065    });10661067    return {1068      again,1069      before,1070      bobVouches,1071      claimed: claimed.claim.state,1072      commit,1073      denounced,1074      erinClaims: yield* api1075        .claim(erin, AskId.make("parse-iso"))1076        .pipe(Effect.flip),1077      fileAfterVouch,1078      fileNow: yield* vouchFileNow,1079      vouched,1080    };1081  });10821083describe("a vouch", () => {1084  const seen = Effect.flatMap(begun, vouching).pipe(1085    Effect.provide(vouchingWorld)1086  );10871088  it.effect(1089    "is a maintainer's platform landing of the vouch file, with the person added",1090    () =>1091      Effect.map(seen, (run) => {1092        expect(run.bobVouches).toStrictEqual(new NotDecider({}));1093        expect(run.fileAfterVouch).toStrictEqual(Option.some("dave\n"));1094        expect({1095          author: run.commit.author,1096          committer: run.commit.committer,1097          decided: run.commit.trailers.filter(1098            ({ key }) => key === "Decided-by"1099          ),1100        }).toStrictEqual({1101          author: authorLine(alice.handle),1102          committer: committerLine,1103          decided: [{ key: "Decided-by", value: userOf("alice") }],1104        });1105        expect(run.again).toStrictEqual(run.vouched);1106      })1107  );11081109  it.effect(1110    "lets a person claim who could not before, and a denouncement bars one who could",1111    () =>1112      Effect.map(seen, (run) => {1113        expect([run.before, run.claimed]).toStrictEqual([1114          new NotVouched({}),1115          "live",1116        ]);1117        expect(run.denounced.landed).not.toBe(run.vouched.landed);1118        expect(run.fileNow).toStrictEqual(1119          Option.some("dave\n-erin pushed a secret\n")1120        );1121        expect(run.erinClaims).toStrictEqual(new Denounced({}));1122      })1123  );1124});11251126const filling = (api: ProjectApi) =>1127  Effect.gen(function* () {1128    const proposers = [carol, eve, frank, carol, eve, frank];11291130    yield* Effect.forEach(1131      proposers,1132      (who, index) =>1133        Effect.andThen(1134          advanceTo(DateTime.formatIso(DateTime.add(noon, { hours: index }))),1135          api.proposeAsk(who, { want: `Want number ${index + 1}` })1136        ),1137      { discard: true }1138    );11391140    const full = yield* api.today(alice);11411142    yield* api.decide(alice, {1143      choice: "decline",1144      decision: firstDecision,1145      note: "Not this one",1146    });11471148    const flag = yield* api.flagAsk(carol, {1149      ask: AskId.make("parse-iso"),1150      reason: "Its check reads the wall clock",1151    });11521153    return {1154      afterOne: yield* api.today(alice),1155      bobToday: yield* api.today(bob).pipe(Effect.flip),1156      flag,1157      flagUnknown: yield* api1158        .flagAsk(eve, { ask: AskId.make("no-such-ask"), reason: "Gone" })1159        .pipe(Effect.flip),1160      full,1161    };1162  });11631164const idsOf = (decisions: readonly { readonly id: DecisionId }[]) =>1165  decisions.map(({ id }) => id);11661167const decisionIds = (from: number, to: number) =>1168  Array.range(from, to).map((n) =>1169    DecisionId.make(`dec-${String(n).padStart(6, "0")}`)1170  );11711172describe("Today", () => {1173  it.effect(1174    "shows a maintainer at most the budget's decisions, soonest to expire first, and counts the rest as overflow",1175    () =>1176      Effect.map(1177        Effect.flatMap(begun, (api) =>1178          Effect.andThen(openRed(api, "parse-iso"), filling(api))1179        ).pipe(Effect.provide(worldOf(scenario, "memory"))),1180        (seen) => {1181          expect({1182            budget: seen.full.budget,1183            decider: seen.full.decider,1184            decisions: idsOf(seen.full.decisions),1185            overflow: seen.full.overflow,1186          }).toStrictEqual({1187            budget: { finishes: 0, total: 5, used: 0 },1188            decider: alice.handle,1189            decisions: decisionIds(1, 5),1190            overflow: 1,1191          });1192          expect({1193            budget: seen.afterOne.budget,1194            decisions: idsOf(seen.afterOne.decisions),1195            overflow: seen.afterOne.overflow,1196          }).toStrictEqual({1197            budget: { finishes: 0, total: 5, used: 1 },1198            decisions: decisionIds(2, 5),1199            overflow: 2,1200          });1201          expect(seen.bobToday).toStrictEqual(new NotDecider({}));1202        }1203      )1204  );12051206  it.effect(1207    "holds a flag on an open ask as a proposal for its maintainers",1208    () =>1209      Effect.map(1210        Effect.flatMap(begun, (api) =>1211          Effect.andThen(openRed(api, "parse-iso"), filling(api))1212        ).pipe(Effect.provide(worldOf(scenario, "memory"))),1213        (seen) => {1214          expect(seen.flag.proposal).toMatchObject({1215            files: [],1216            flags: AskId.make("parse-iso"),1217            proposer: carol.handle,1218            state: "open",1219            want: "Its check reads the wall clock",1220          });1221          expect(seen.flagUnknown).toStrictEqual(1222            new UnknownAsk({ ask: AskId.make("no-such-ask") })1223          );1224        }1225      )1226  );1227});12281229const burrow = ProjectName.make("alice/burrow");12301231const row = (name: ProjectName, role: "Asked-by" | "Signed-off-by") => ({1232  area: "parser",1233  count: 1,1234  project: name,1235  role,1236});12371238const crediting = Effect.gen(function* () {1239  yield* advanceTo("2026-10-07T12:00:00Z");12401241  const projects = yield* Projects;12421243  const answerIn = (name: ProjectName, who: Person) =>1244    Effect.gen(function* () {1245      const on = RepoName.make(keyOf(name));1246      const api = yield* made(yield* projects.create(name), on);12471248      yield* openRed(api, "parse-iso", on);1249      yield* answered(api, {1250        change: [1251          "packages/parser/src/parse.ts",1252          "export const parse = (s) => ({ year: 2026 });\n",1253        ],1254        files: withAskFiles(start, "parse-iso"),1255        id: "parse-iso",1256        on,1257        who,1258      });12591260      return api;1261    });12621263  const datekit = yield* answerIn(project, bob);12641265  yield* answerIn(burrow, carol);12661267  const among = [project, burrow];12681269  return {1270    alice: yield* creditsFor(alice.handle, among),1271    bob: yield* creditsFor(bob.handle, among),1272    bobInDatekit: yield* datekit.credits(anyone, bob.handle),1273    dave: yield* creditsFor(dave.handle, among),1274  };1275});12761277// Assisted-by never reaches a credit row; no answer here carries an agent trailer.1278describe("credits", () => {1279  it.effect("count a person's roles by project and area across projects", () =>1280    Effect.map(1281      crediting.pipe(1282        Effect.provide(1283          ProjectsMemory.pipe(Layer.provideMerge(worldOf(scenario, "memory")))1284        )1285      ),1286      (seen) => {1287        expect(seen.bob).toStrictEqual([row(project, "Signed-off-by")]);1288        expect(seen.bobInDatekit).toStrictEqual({ credits: seen.bob });1289        expect(seen.alice).toStrictEqual([1290          row(burrow, "Asked-by"),1291          row(project, "Asked-by"),1292        ]);1293        expect(seen.dave).toStrictEqual([]);1294      }1295    )1296  );1297});12981299const strayOnto = (first: CommitSha) =>1300  Pusher.use((pusher) =>1301    pusher.push(1302      repo,1303      Option.some(first),1304      changed(1305        start,1306        "packages/trim/src/trim.ts",1307        "export const trim = (s) => s.trimEnd();\n"1308      ),1309      "Stray"1310    )1311  );13121313const reported = (1314  api: ProjectApi,1315  eventId: string,1316  move: { readonly after: CommitSha; readonly before?: CommitSha }1317) =>1318  api.recordPush({1319    after: move.after,1320    before: Option.fromUndefinedOr(move.before),1321    eventId,1322    pusher: anyone,1323    ref: "refs/heads/main",1324    repo,1325  });13261327const strayReported = Effect.gen(function* () {1328  const api = yield* begun;1329  const first = yield* mainTip;13301331  yield* reported(api, "evt-first", { after: first });13321333  const { landed } = yield* openRed(api, "parse-iso");13341335  yield* reported(api, "evt-landed", { after: landed, before: first });13361337  const stray = yield* strayOnto(landed);13381339  yield* reported(api, "evt-stray", { after: stray, before: landed });1340  yield* reported(api, "evt-stray", { after: stray, before: landed });13411342  return {1343    decisions: (yield* api.today(alice)).decisions.map(1344      ({ deciders, default: byDefault, expiresAt, subject }) => ({1345        byDefault,1346        deciders,1347        expiresAt,1348        subject,1349      })1350    ),1351    first,1352    firstLanding: Exit.map(1353      yield* Effect.exit(api.landing(alice, first)),1354      ({ landing }) => ({ ask: landing.ask, author: landing.author })1355    ),1356    landed,1357    stray,1358  };1359});13601361const strayDecided = (choice: "accept" | "decline") =>1362  Effect.gen(function* () {1363    const api = yield* begun;1364    const host = yield* RepoHost;1365    const first = yield* mainTip;1366    const stray = yield* strayOnto(first);13671368    yield* reported(api, "evt-stray", { after: stray, before: first });13691370    const decided = yield* api.decide(alice, {1371      choice,1372      decision: firstDecision,1373    });13741375    const tip = yield* mainTip;13761377    const treeOf = (sha: CommitSha) =>1378      Effect.map(host.readCommit(repo, sha).pipe(Effect.orDie), (read) =>1379        Option.map(read, ({ tree }) => tree)1380      );13811382    return {1383      commit: yield* commitOf(tip),1384      decided: decided.decision.decided?.choice,1385      first,1386      firstTree: yield* treeOf(first),1387      landed: Option.flatMap((yield* stored).project, ({ landed }) =>1388        Option.fromUndefinedOr(landed)1389      ),1390      stray,1391      tip,1392      tipTree: yield* treeOf(tip),1393    };1394  });13951396const deletedDecided = (choice: "accept" | "decline") =>1397  Effect.gen(function* () {1398    const api = yield* begun;1399    const first = yield* mainTip;14001401    yield* reported(api, "evt-deleted", {1402      after: CommitSha.make("0".repeat(40)),1403      before: first,1404    });14051406    const decided = yield* api.decide(alice, {1407      choice,1408      decision: firstDecision,1409    });14101411    return {1412      decided: decided.decision.decided?.choice,1413      first,1414      landed: Option.flatMap((yield* stored).project, ({ landed }) =>1415        Option.fromUndefinedOr(landed)1416      ),1417      tip: yield* mainTip,1418    };1419  });14201421describe("a stray push", () => {1422  it.effect.each(["accept", "decline"] as const)(1423    "that deleted main is put to the maintainers, and decided %s moves neither main nor the landed SHA",1424    (choice) =>1425      Effect.map(1426        deletedDecided(choice).pipe(1427          Effect.provide(worldOf(scenario, "memory"))1428        ),1429        (seen) => {1430          expect([seen.decided, seen.tip, seen.landed]).toStrictEqual([1431            choice === "accept" ? "adopt" : "revert",1432            seen.first,1433            Option.some(seen.first),1434          ]);1435        }1436      )1437  );14381439  it.effect(1440    "reported by OnPush opens one StrayPush decision, default revert, however often the event comes; main moved by the platform opens none",1441    () =>1442      Effect.map(1443        strayReported.pipe(Effect.provide(worldOf(scenario, "memory"))),1444        (seen) => {1445          expect(seen.decisions).toStrictEqual([1446            {1447              byDefault: "revert",1448              deciders: [alice.handle],1449              expiresAt: daysAfter(noon, 14),1450              subject: DecisionSubject.cases.StrayPush.make({1451                after: seen.stray,1452                before: seen.landed,1453                ref: RefNameText.make("refs/heads/main"),1454              }),1455            },1456          ]);1457          expect(seen.firstLanding).toStrictEqual(1458            Exit.succeed({ ask: undefined, author: alice.handle })1459          );1460        }1461      )1462  );14631464  it.effect(1465    "decided revert lands a commit on top of it with the tree it replaced, and a Reverts trailer",1466    () =>1467      Effect.map(1468        strayDecided("decline").pipe(1469          Effect.provide(worldOf(scenario, "memory"))1470        ),1471        (seen) => {1472          expect(seen.decided).toBe("revert");1473          expect(seen.landed).toStrictEqual(Option.some(seen.tip));1474          expect(seen.tipTree).toStrictEqual(seen.firstTree);1475          expect({1476            author: seen.commit.author,1477            committer: seen.commit.committer,1478            parents: seen.commit.parents,1479            trailers: seen.commit.trailers.filter(({ key }) =>1480              ["Decided-by", "Reverts"].includes(key)1481            ),1482          }).toStrictEqual({1483            author: authorLine(alice.handle),1484            committer: committerLine,1485            parents: [seen.stray],1486            trailers: [1487              { key: "Decided-by", value: userOf("alice") },1488              { key: "Reverts", value: seen.stray },1489            ],1490          });1491        }1492      )1493  );14941495  it.effect("decided adopt becomes the landed SHA, and main stays", () =>1496    Effect.map(1497      strayDecided("accept").pipe(Effect.provide(worldOf(scenario, "memory"))),1498      (seen) => {1499        expect(seen.decided).toBe("adopt");1500        expect([seen.tip, seen.landed]).toStrictEqual([1501          seen.stray,1502          Option.some(seen.stray),1503        ]);1504      }1505    )1506  );1507});