Skip to content
Myr

answer.test.ts

This file

Path

apps/platform/test/workflows/answer.test.ts

999 lines · 29.2 KiB · TypeScript

Last changed by

Merge observability into mainoscabrielbefore adoption1985111

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { RepoHost } from "@repo/artifacts/repo-host";3import { CheckAt, shaOf } from "@repo/checks/check-runner";4import type { CheckRunner } from "@repo/checks/check-runner";5import { logRefOf } from "@repo/checks/evidence-store";6import type { EvidenceStore } from "@repo/checks/evidence-store";7import { EvidenceKept } from "@repo/checks/evidence-store/memory";8import {9  AnswerReport,10  ReportedCommand,11  Steps,12} from "@repo/project/answer-runs";13import { drive } from "@repo/project/answer-runs/steps";14import type { Lander } from "@repo/project/lander";15import { LanderJob } from "@repo/project/lander/memory";16import { Projects } from "@repo/project/projects";17import { Verdict } from "@repo/protocol/domain/answer";18import { ProjectEvent } from "@repo/protocol/domain/event";19import { Outcome } from "@repo/protocol/domain/outcome";20import { keyOf, LaneName, RequestId } from "@repo/protocol/ids";21import type { CommitSha, LandedSha } from "@repo/protocol/ids";22import {23  ChecksFailed,24  Flake,25  StaleBase,26  VerifierBlocked,27} from "@repo/protocol/refusal";28import { untouchable } from "@repo/testkit/untouchable";29import { DateTime, Effect, Exit, Layer, Option, Schema, Struct } from "effect";30import type { Context } from "effect";3132import type { AnswerParams } from "../../src/answer-runs.ts";33import {34  Answer,35  OutcomeJson,36  runWorkflow,37} from "../../src/workflows/answer.ts";38import { failingPathsOf } from "../../src/workflows/answer/lanes.ts";39import { runAnswer } from "../../src/workflows/answer/program.ts";40import { memoSteps } from "../../src/workflows/step.ts";41import type { StepRunner, WorkflowSteps } from "../../src/workflows/step.ts";42import { fakeEnv } from "../fake-env.ts";43import {44  admitted,45  alice,46  askLane,47  bob,48  bobFork,49  changed,50  checkedStages,51  Checker,52  DoCalls,53  finishRequired,54  LanderCalls,55  lexPath,56  logged,57  mainMoved,58  mainTip,59  openedFiles,60  parseIso,61  parsePath,62  policy,63  project,64  repo,65  scriptProjectLanes,66  Started,67  StepLog,68  verdictOf,69  world,70  worldWith,71} from "./answer.fixtures.ts";72import type { Admitted } from "./answer.fixtures.ts";7374const unit = LaneName.make("unit");7576const lint = LaneName.make("lint");7778const Advance = Schema.toCodecJson(79  Schema.Struct({80    command: ReportedCommand,81    report: Schema.UndefinedOr(AnswerReport),82  })83);8485const run = (answer: Admitted, steps: Context.Context<StepRunner>) =>86  runAnswer({ project, requestId: answer.requestId }).pipe(87    Effect.provide(steps)88  );8990const freshSteps = (options: { readonly twice?: boolean } = {}) =>91  Effect.flatMap(memoSteps(), (memo) => Layer.build(logged(memo, options)));9293const namesOf = (steps: Context.Context<StepLog>) =>94  StepLog.use(({ names }) => names).pipe(Effect.provide(steps));9596const pass = (attempt: number) => [97  `merge#${attempt}`,98  `record:merge#${attempt}`,99  `cheap#${attempt}`,100  `checks#${attempt}`,101  `record:checks#${attempt}`,102  `land#${attempt}`,103  `record:land#${attempt}`,104];105106const allGreen = (at: CheckAt) =>107  Effect.andThen(108    scriptProjectLanes(at, { result: "passed" }),109    Checker.use((script) => script.script(at, askLane, [{ result: "passed" }]))110  );111112const failsOnMerged = (113  answer: Admitted,114  lane: LaneName,115  signature: string,116  onMain: "passed" | "failed"117) =>118  Effect.gen(function* () {119    yield* allGreen(answer.merged);120    yield* Checker.use((script) =>121      Effect.andThen(122        script.script(answer.merged, lane, [{ result: "failed", signature }]),123        script.script(124          CheckAt.cases.Commit.make({ commit: answer.opened }),125          lane,126          [{ result: onMain }]127        )128      )129    );130  });131132const jobsOn = (at: CheckAt) =>133  Checker.use(({ jobs }) =>134    Effect.map(jobs, (all) =>135      all136        .filter((job) => shaOf(job.at) === shaOf(at))137        .map(({ lanes, repo: on }) => ({ lanes, on }))138    )139  );140141const landsOf = (answer: Admitted) =>142  LanderCalls.use(({ jobs }) =>143    Effect.map(jobs, (all) =>144      all.filter(145        (each) =>146          LanderJob.$is("Land")(each) && each.job.requestId === answer.requestId147      )148    )149  );150151const reportedTags = DoCalls.use(({ advances }) =>152  Effect.map(advances, (all) => all.map(({ command }) => command._tag))153);154155const parentsOf = (sha: CommitSha) =>156  Effect.gen(function* () {157    const host = yield* RepoHost;158    const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);159160    return Option.getOrThrow(read).parents;161  });162163const landedAt = (sha: LandedSha) => Outcome.cases.Landed.make({ sha });164165const cleanAnswer = Effect.tap(admitted(), (answer) => allGreen(answer.merged));166167const withoutMessage = Layer.effect(168  Projects,169  Effect.map(Projects, (inner) =>170    Projects.of({171      create: inner.create,172      get: (name) =>173        Effect.map(inner.get(name), (api) => ({174          ...api,175          answer: (requestId) =>176            Effect.map(177              api.answer(requestId),178              Option.map((found) => Struct.omit(found, ["message"]))179            ),180        })),181    })182  )183);184185describe(runAnswer, () => {186  it.effect(187    "1. a clean answer is merged, checked and landed, one named step at a time",188    () =>189      Effect.gen(function* () {190        const answer = yield* cleanAnswer;191        const steps = yield* freshSteps();192        const outcome = yield* run(answer, steps);193        const tip = yield* mainTip;194195        expect(outcome).toStrictEqual(landedAt(tip));196        expect(yield* parentsOf(tip)).toStrictEqual([answer.opened]);197        expect(yield* namesOf(steps)).toStrictEqual([198          "load",199          ...pass(1),200          "notes:Landed",201        ]);202        expect(yield* landsOf(answer)).toHaveLength(1);203      }).pipe(Effect.provide(world))204  );205206  it.effect(207    "1. the project records each step's report and the landing, through its queue",208    () =>209      Effect.gen(function* () {210        const answer = yield* cleanAnswer;211        const outcome = yield* run(answer, yield* freshSteps());212        const { answers } = yield* answer.api.status(bob);213214        expect(yield* reportedTags).toStrictEqual([215          "Merged",216          "Checked",217          "LandedOk",218        ]);219        expect(answers.map((each) => each.outcome)).toStrictEqual([outcome]);220        expect(221          Option.map(yield* verdictOf(answer.api), (v) => v.tree)222        ).toStrictEqual(Option.some(shaOf(answer.merged)));223      }).pipe(Effect.provide(world))224  );225226  it.effect(227    "1. the checks run on the exact merged tree, in the fork that holds it, the cheap lanes first",228    () =>229      Effect.gen(function* () {230        const answer = yield* cleanAnswer;231232        yield* run(answer, yield* freshSteps());233234        const jobs = yield* Checker.use((script) => script.jobs);235236        expect(237          jobs238            .filter(({ at }) => CheckAt.guards.Tree(at))239            .map(({ at, lanes, repo: on, run: block }) => ({240              at,241              lanes: lanes.map(({ lane }) => lane),242              on,243              run: block,244            }))245        ).toStrictEqual([246          {247            at: answer.merged,248            lanes: ["lint", "types"],249            on: bobFork,250            run: policy.run,251          },252          {253            at: answer.merged,254            lanes: [askLane, "unit"],255            on: bobFork,256            run: policy.run,257          },258        ]);259      }).pipe(Effect.provide(world))260  );261262  it.effect(263    "2. the whole program run twice over one step record lands once, with one outcome",264    () =>265      Effect.gen(function* () {266        const answer = yield* cleanAnswer;267        const steps = yield* freshSteps();268        const first = yield* run(answer, steps);269        const second = yield* run(answer, steps);270271        expect(second).toStrictEqual(first);272        expect(yield* landsOf(answer)).toHaveLength(1);273        expect(yield* reportedTags).toStrictEqual([274          "Merged",275          "Checked",276          "LandedOk",277        ]);278      }).pipe(Effect.provide(world))279  );280281  it.effect(282    "2. every step's effect run twice still lands once, with the same outcome",283    () =>284      Effect.gen(function* () {285        const answer = yield* cleanAnswer;286        const outcome = yield* run(answer, yield* freshSteps({ twice: true }));287        const tip = yield* mainTip;288        const events = yield* answer.api.events(0, 1000);289290        expect(outcome).toStrictEqual(landedAt(tip));291        expect(yield* parentsOf(tip)).toStrictEqual([answer.opened]);292        expect(293          events.filter(294            ({ event }) =>295              ProjectEvent.guards.Landed(event) &&296              event.landing.requestId === answer.requestId297          )298        ).toHaveLength(1);299      }).pipe(Effect.provide(world))300  );301302  it.effect(303    "3. a lane red on the merged tree and green on main, in a file the answer changed, is the answer's failure",304    () =>305      Effect.gen(function* () {306        const answer = yield* admitted();307308        yield* failsOnMerged(309          answer,310          unit,311          `parses ISO weeks: AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,312          "passed"313        );314315        const steps = yield* freshSteps();316        const outcome = yield* run(answer, steps);317318        expect(outcome).toStrictEqual(319          Outcome.cases.Refused.make({320            refusals: [321              new ChecksFailed({322                lane: unit,323                logRef: `${keyOf(project)}/${answer.requestId}/unit#1`,324                next: "bun run test",325              }),326            ],327          })328        );329        expect(yield* namesOf(steps)).toContain(`main:${answer.opened}:unit`);330        expect(331          yield* jobsOn(CheckAt.cases.Commit.make({ commit: answer.opened }))332        ).toStrictEqual([333          { lanes: [{ command: "bun run test", lane: unit }], on: repo },334        ]);335        expect(yield* landsOf(answer)).toHaveLength(0);336      }).pipe(Effect.provide(world))337  );338339  it.effect(340    "3. a lane red on the merged tree and on main is the verifier's trouble",341    () =>342      Effect.gen(function* () {343        const answer = yield* admitted();344345        yield* failsOnMerged(answer, unit, "AssertionError: red", "failed");346347        expect(yield* run(answer, yield* freshSteps())).toStrictEqual(348          Outcome.cases.Refused.make({ refusals: [new VerifierBlocked({})] })349        );350      }).pipe(Effect.provide(world))351  );352353  it.effect(354    "3. a lane red only in a file outside the answer's diff, and green on main, means a stale base",355    () =>356      Effect.gen(function* () {357        const answer = yield* admitted();358359        yield* failsOnMerged(360          answer,361          unit,362          `lexes words: AssertionError: expected 2 to be 3 at ${lexPath}:1:30`,363          "passed"364        );365366        expect(yield* run(answer, yield* freshSteps())).toStrictEqual(367          Outcome.cases.Refused.make({368            refusals: [369              new StaleBase({370                base: answer.opened,371                conflicts: [],372                main: answer.opened,373              }),374            ],375          })376        );377      }).pipe(Effect.provide(world))378  );379380  it.effect(381    "3. a lane that never got going runs once more on the merged tree, and green then is a flake",382    () =>383      Effect.gen(function* () {384        const answer = yield* admitted();385386        yield* allGreen(answer.merged);387        yield* Checker.use((script) =>388          script.script(answer.merged, unit, [389            { result: "flaked" },390            { result: "passed" },391          ])392        );393394        expect(yield* run(answer, yield* freshSteps())).toStrictEqual(395          Outcome.cases.Refused.make({ refusals: [new Flake({ lane: unit })] })396        );397        expect(398          (yield* jobsOn(answer.merged)).map(({ lanes, on }) => ({399            lanes: lanes.map(({ lane }) => lane),400            on,401          }))402        ).toStrictEqual([403          { lanes: [lint, "types"], on: bobFork },404          { lanes: [askLane, unit], on: bobFork },405          { lanes: [unit], on: bobFork },406        ]);407      }).pipe(Effect.provide(world))408  );409410  it.effect(411    "3. a lane that never got going and then fails on its fresh run is the answer's failure",412    () =>413      Effect.gen(function* () {414        const answer = yield* admitted();415416        yield* failsOnMerged(answer, unit, "AssertionError: red", "passed");417        yield* Checker.use((script) =>418          script.script(answer.merged, unit, [419            { result: "blocked" },420            {421              result: "failed",422              signature: `AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,423            },424          ])425        );426427        expect(yield* run(answer, yield* freshSteps())).toStrictEqual(428          Outcome.cases.Refused.make({429            refusals: [430              new ChecksFailed({431                lane: unit,432                logRef: `${keyOf(project)}/${answer.requestId}/unit#1`,433                next: "bun run test",434              }),435            ],436          })437        );438      }).pipe(Effect.provide(world))439  );440441  it.effect("3. a red cheap lane refuses before the costlier checks run", () =>442    Effect.gen(function* () {443      const answer = yield* admitted();444445      yield* failsOnMerged(answer, lint, "lint: no-unused-vars", "passed");446447      const steps = yield* freshSteps();448449      expect(yield* run(answer, steps)).toStrictEqual(450        Outcome.cases.Refused.make({451          refusals: [452            new ChecksFailed({453              lane: lint,454              logRef: `${keyOf(project)}/${answer.requestId}/lint#1`,455              next: "bun run lint",456            }),457          ],458        })459      );460      expect(yield* namesOf(steps)).not.toContain("checks#1");461    }).pipe(Effect.provide(world))462  );463464  it.effect("3. names cheap, in its report, when a cheap lane refuses", () =>465    Effect.gen(function* () {466      const answer = yield* admitted();467468      yield* failsOnMerged(answer, lint, "lint: no-unused-vars", "passed");469      yield* run(answer, yield* freshSteps());470471      expect(yield* checkedStages).toStrictEqual(["cheap"]);472    }).pipe(Effect.provide(world))473  );474475  it.effect(476    "3. names checks, in its report, when a lane after the cheap ones refuses",477    () =>478      Effect.gen(function* () {479        const answer = yield* admitted();480481        yield* failsOnMerged(answer, unit, "unit: expected 2", "passed");482        yield* run(answer, yield* freshSteps());483484        expect(yield* checkedStages).toStrictEqual(["checks"]);485      }).pipe(Effect.provide(world))486  );487488  it.effect("3. names no stage, in its report, when nothing refused", () =>489    Effect.gen(function* () {490      yield* run(yield* cleanAnswer, yield* freshSteps());491492      expect(yield* checkedStages).toStrictEqual([undefined]);493    }).pipe(Effect.provide(world))494  );495496  it.effect(497    "4. a land that finds main moved is merged again, checked again on the new tree, and lands",498    () =>499      Effect.gen(function* () {500        const answer = yield* cleanAnswer;501502        const moved = yield* mainMoved(503          answer.opened,504          changed(505            openedFiles,506            lexPath,507            "export const lex = (s) => s.split(/ +/);\n"508          )509        );510511        const remerged = yield* LanderCalls.use(({ preview }) =>512          preview({513            base: answer.opened,514            fork: bobFork,515            head: answer.head,516            main: moved,517            repo,518          })519        );520521        yield* allGreen(remerged);522523        const steps = yield* freshSteps();524        const outcome = yield* run(answer, steps);525        const tip = yield* mainTip;526527        expect(outcome).toStrictEqual(landedAt(tip));528        expect(yield* parentsOf(tip)).toStrictEqual([moved]);529        expect(yield* namesOf(steps)).toStrictEqual([530          "load",531          ...pass(1),532          ...pass(2),533          "notes:Landed",534        ]);535        expect(536          Option.map(yield* verdictOf(answer.api), ({ tree }) => tree)537        ).toStrictEqual(Option.some(shaOf(remerged)));538      }).pipe(Effect.provide(world))539  );540541  it.effect(542    "4. a land that finds main moved, whose re-merge conflicts, is refused as stale",543    () =>544      Effect.gen(function* () {545        const answer = yield* cleanAnswer;546547        const moved = yield* mainMoved(548          answer.opened,549          changed(openedFiles, parsePath, "export const parse = (s) => null;\n")550        );551552        expect(yield* run(answer, yield* freshSteps())).toStrictEqual(553          Outcome.cases.Refused.make({554            refusals: [555              new StaleBase({556                base: answer.opened,557                conflicts: [parsePath],558                main: moved,559              }),560            ],561          })562        );563        expect(yield* mainTip).toBe(moved);564      }).pipe(Effect.provide(world))565  );566567  it.effect(568    "5. a busy repo is retried by the land step's own retries, not refused",569    () =>570      Effect.gen(function* () {571        const answer = yield* cleanAnswer;572573        yield* LanderCalls.use(({ busyFor }) => busyFor(1));574575        const steps = yield* freshSteps();576        const outcome = yield* run(answer, steps);577578        const retries = yield* StepLog.use((log) => log.retries).pipe(579          Effect.provide(steps)580        );581582        expect(outcome).toStrictEqual(landedAt(yield* mainTip));583        expect(yield* landsOf(answer)).toHaveLength(2);584        expect(yield* reportedTags).toStrictEqual([585          "Merged",586          "Checked",587          "LandedOk",588        ]);589        expect(Option.fromUndefinedOr(retries.get("land#1"))).toStrictEqual(590          Option.some({ backoff: "exponential", delayMs: 1000, limit: 3 })591        );592      }).pipe(Effect.provide(world))593  );594595  it.effect(596    "5. a repo still busy once the retries are spent waits on the project's own retry",597    () =>598      Effect.gen(function* () {599        const answer = yield* cleanAnswer;600601        yield* LanderCalls.use(({ busyFor }) => busyFor(100));602603        expect(yield* run(answer, yield* freshSteps())).toStrictEqual(604          Outcome.cases.Checking.make({ stage: "human" })605        );606        expect(yield* reportedTags).toStrictEqual([607          "Merged",608          "Checked",609          "Busy",610        ]);611        expect(yield* mainTip).toBe(answer.opened);612      }).pipe(Effect.provide(world))613  );614615  it.effect(616    "a land step that finds nothing to do ends the run there, as the in-process run does",617    () =>618      Effect.gen(function* () {619        const answer = yield* cleanAnswer;620        const steps = yield* freshSteps();621622        const exit = yield* Effect.exit(623          run(answer, steps).pipe(Effect.provide(withoutMessage))624        );625626        expect(Exit.getSuccess(exit)).toStrictEqual(627          Option.some(Outcome.cases.Checking.make({ stage: "human" }))628        );629        expect(yield* namesOf(steps)).toStrictEqual([630          "load",631          ...pass(1),632          "notes:Checking",633        ]);634        expect(yield* landsOf(answer)).toHaveLength(0);635      }).pipe(Effect.provide(world))636  );637638  it.effect(639    "an answer a maintainer must finish stops once checked, and lands nothing",640    () =>641      Effect.gen(function* () {642        const answer = yield* cleanAnswer;643        const steps = yield* freshSteps();644645        expect(yield* run(answer, steps)).toStrictEqual(646          Outcome.cases.AwaitingFinish.make({})647        );648        expect(yield* namesOf(steps)).toStrictEqual([649          "load",650          "merge#1",651          "record:merge#1",652          "cheap#1",653          "checks#1",654          "record:checks#1",655          "notes:AwaitingFinish",656        ]);657        expect(yield* landsOf(answer)).toHaveLength(0);658      }).pipe(Effect.provide(worldWith(finishRequired)))659  );660661  it.effect(662    "a maintainer's finish starts the answer's run again, and a fresh run lands it, finished",663    () =>664      Effect.gen(function* () {665        const answer = yield* cleanAnswer;666667        yield* run(answer, yield* freshSteps());668669        yield* answer.api.finish(alice, {670          ask: parseIso,671          base: answer.opened,672          head: answer.head,673          requestId: RequestId.make(`finish-${answer.head}`),674        });675676        const outcome = yield* run(answer, yield* freshSteps());677        const tip = yield* mainTip;678        const events = yield* answer.api.events(0, 1000);679680        expect(yield* Started.use(({ ids }) => ids)).toStrictEqual([681          answer.requestId,682          answer.requestId,683        ]);684        expect(outcome).toStrictEqual(landedAt(tip));685        expect(686          events.flatMap(({ event: each }) =>687            ProjectEvent.guards.Landed(each)688              ? each.landing.credits.filter(689                  ({ role }) => role === "Finished-by"690                )691              : []692          )693        ).toStrictEqual([{ handle: alice.handle, role: "Finished-by" }]);694      }).pipe(Effect.provide(worldWith(finishRequired)))695  );696697  it.effect(698    "6. a failing lane's log is kept once, and the verdict names it",699    () =>700      Effect.gen(function* () {701        const answer = yield* admitted();702        const said = "AssertionError: expected {} to equal { year: 2026 }";703704        yield* failsOnMerged(705          answer,706          unit,707          `parses ISO weeks: ${said}`,708          "passed"709        );710711        const outcome = yield* run(answer, yield* freshSteps());712        const puts = yield* EvidenceKept.use((kept) => kept.puts);713        const verdict = yield* verdictOf(answer.api);714715        const ref = logRefOf({716          attempt: 1,717          lane: unit,718          project,719          requestId: answer.requestId,720        });721722        expect(723          puts.map((log) => ({724            ref: logRefOf(log),725            told: log.text.includes(said),726          }))727        ).toStrictEqual([{ ref, told: true }]);728        expect(outcome).toStrictEqual(729          Outcome.cases.Refused.make({730            refusals: [731              new ChecksFailed({732                lane: unit,733                logRef: ref,734                next: "bun run test",735              }),736            ],737          })738        );739        expect(740          Option.map(verdict, ({ lanes, outcome: judged }) => ({741            judged,742            refs: lanes.map(({ logRef }) => logRef),743          }))744        ).toStrictEqual(745          Option.some({746            judged: outcome,747            refs: [undefined, undefined, undefined, ref],748          })749        );750      }).pipe(Effect.provide(world))751  );752753  it.effect(754    "6. a lane's log travels nowhere: not in the outcome, the verdict or the calls to the project",755    () =>756      Effect.gen(function* () {757        const answer = yield* admitted();758        const said = "AssertionError: expected {} to equal { year: 2026 }";759760        yield* failsOnMerged(761          answer,762          unit,763          `parses ISO weeks: ${said}`,764          "passed"765        );766767        const outcome = yield* run(answer, yield* freshSteps());768        const verdict = Option.getOrThrow(yield* verdictOf(answer.api));769        const advances = yield* DoCalls.use((calls) => calls.advances);770771        const travelled = JSON.stringify([772          yield* Schema.encodeEffect(OutcomeJson)(outcome),773          yield* Schema.encodeEffect(Schema.toCodecJson(Verdict))(verdict),774          yield* Effect.forEach(advances, (each) =>775            Schema.encodeEffect(Advance)(each)776          ),777        ]);778779        expect(travelled).not.toContain(said);780        expect(travelled).toContain(781          logRefOf({782            attempt: 1,783            lane: unit,784            project,785            requestId: answer.requestId,786          })787        );788      }).pipe(Effect.provide(world))789  );790791  it.effect("6. a check step run twice keeps its log under the same name", () =>792    Effect.gen(function* () {793      const answer = yield* admitted();794795      yield* failsOnMerged(answer, unit, "AssertionError: red", "passed");796      yield* run(answer, yield* freshSteps({ twice: true }));797798      const puts = yield* EvidenceKept.use((kept) => kept.puts);799800      expect(puts.length).toBeGreaterThan(1);801      expect(new Set(puts.map(logRefOf))).toStrictEqual(802        new Set([803          logRefOf({804            attempt: 1,805            lane: unit,806            project,807            requestId: answer.requestId,808          }),809        ])810      );811    }).pipe(Effect.provide(world))812  );813814  it.effect(815    "the in-process run reaches the same outcome as the Workflow's program",816    () =>817      Effect.gen(function* () {818        const viaProgram = yield* Effect.flatMap(cleanAnswer, (answer) =>819          Effect.flatMap(freshSteps(), (steps) => run(answer, steps))820        ).pipe(Effect.provide(world));821822        const inProcess = yield* Effect.gen(function* () {823          const answer = yield* cleanAnswer;824825          yield* drive(answer.api, answer.requestId);826827          return (yield* answer.api.status(bob)).answers.map(828            ({ outcome }) => outcome829          );830        }).pipe(Effect.provide(world));831832        expect(inProcess).toStrictEqual([viaProgram]);833      })834  );835});836837describe(failingPathsOf, () => {838  it("names the repo files a failure points at, tests and absolute paths left out", () => {839    expect(840      failingPathsOf(841        [842          `lexes words: AssertionError: expected 2 to be 3 at ${lexPath}:1:30`,843          `    at packages/parser/test/parse-iso.test.ts:5:7`,844          "    at /home/ci/node_modules/vitest/dist/index.js:10:3",845          `    at (${parsePath}:3)`,846          `    at ${lexPath}:2:1`,847        ].join("\n")848      )849    ).toStrictEqual([lexPath, parsePath]);850  });851852  it("reads no network address as a file", () => {853    expect(854      failingPathsOf(855        "serves: AssertionError: expected 'listening on 127.0.0.1:8080' to be 'up'"856      )857    ).toStrictEqual([]);858  });859});860861const fakeEngine = () => {862  const recorded = new Map<string, Promise<Schema.Json>>();863  const ran: string[] = [];864865  const steps: WorkflowSteps = {866    do: (name, _config, body) => {867      const kept = recorded.get(name);868869      if (kept !== undefined) {870        return kept;871      }872873      ran.push(name);874875      const running = body();876877      recorded.set(name, running);878879      return running;880    },881  };882883  const record = (name: string) =>884    Effect.promise(() => recorded.get(name) ?? Promise.resolve(null));885886  return { ran, record, steps };887};888889const isJson = Schema.is(Schema.Json);890891const event = (payload: typeof AnswerParams.Encoded) => ({892  instanceId: payload.requestId,893  payload,894  timestamp: DateTime.toDateUtc(DateTime.makeUnsafe("2026-10-07T12:00:00Z")),895  workflowName: "answer-local",896});897898const portsOfWorld = Effect.map(899  Effect.context<CheckRunner | EvidenceStore | Lander | Projects | RepoHost>(),900  Layer.succeedContext901);902903describe(runWorkflow, () => {904  it.effect(905    "hands the engine each step's value as JSON, and returns the outcome as JSON",906    () =>907      Effect.gen(function* () {908        const answer = yield* cleanAnswer;909        const engine = fakeEngine();910        const ports = yield* portsOfWorld;911        const payload = { project, requestId: answer.requestId };912913        const outcome = yield* Effect.promise(() =>914          runWorkflow(ports, payload, engine.steps)915        );916917        const tip = yield* mainTip;918919        const recorded = yield* engine.record("record:land#1");920921        expect(engine.ran).toStrictEqual(["load", ...pass(1), "notes:Landed"]);922        expect(isJson(outcome)).toBeTruthy();923        expect(yield* Schema.decodeEffect(OutcomeJson)(outcome)).toStrictEqual(924          landedAt(tip)925        );926        expect(isJson(recorded)).toBeTruthy();927        expect(928          yield* Schema.decodeUnknownEffect(Schema.toCodecJson(Steps))(recorded)929        ).toStrictEqual({ effects: [], outcome: landedAt(tip) });930      }).pipe(Effect.provide(world))931  );932933  it.effect(934    "replays a run from the engine's records: nothing runs again, and the outcome is the same",935    () =>936      Effect.gen(function* () {937        const answer = yield* cleanAnswer;938        const engine = fakeEngine();939        const ports = yield* portsOfWorld;940        const payload = { project, requestId: answer.requestId };941942        const first = yield* Effect.promise(() =>943          runWorkflow(ports, payload, engine.steps)944        );945946        const ranOnce = [...engine.ran];947948        const second = yield* Effect.promise(() =>949          runWorkflow(ports, payload, engine.steps)950        );951952        expect(second).toStrictEqual(first);953        expect(engine.ran).toStrictEqual(ranOnce);954        expect(yield* landsOf(answer)).toHaveLength(1);955      }).pipe(Effect.provide(world))956  );957});958959describe(Answer, () => {960  it.effect("refuses params that don't decode before any step runs", () =>961    Effect.gen(function* () {962      const engine = fakeEngine();963      const workflow = new Answer(untouchable("ctx"), fakeEnv());964965      const exit = yield* Effect.exit(966        Effect.tryPromise(() =>967          workflow.run(968            event({ project: "Not A Project", requestId: "push-0001" }),969            engine.steps970          )971        )972      );973974      expect(Exit.isFailure(exit)).toBeTruthy();975      expect(engine.ran).toStrictEqual([]);976    })977  );978979  it.effect(980    "runs its first step over the engine's, on the ports its env builds",981    () =>982      Effect.gen(function* () {983        const engine = fakeEngine();984        const workflow = new Answer(untouchable("ctx"), fakeEnv());985986        const exit = yield* Effect.exit(987          Effect.tryPromise(() =>988            workflow.run(989              event({ project, requestId: "push-0001" }),990              engine.steps991            )992          )993        );994995        expect(Exit.isFailure(exit)).toBeTruthy();996        expect(engine.ran).toStrictEqual(["load"]);997      })998  );999});