Skip to content
Myr

Merge build/304-answer-workflow: an accepted answer is merged, checked and landed by a durable Answer Workflow

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 1046efe, 798d6e6 · Browse files · 5 files+2548 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+2548 added−5 removed

  • tests:+1620 added−0 removed
  • other:+928 added−5 removed

5 files+2548 added−5 removed

added:apps/platform/src/workflows/answer/lanes.ts+429 added
1/**2 * The answer's lanes on its merged tree (spec §5 step 7 (b), (c)): the3 * cheap stage (the static lanes) and then the checks (the ask's own check4 * and every other project lane), always on the exact tree the merge made.5 * A lane whose checker never got going gets one fresh run; every lane that6 * did not pass keeps its log through `EvidenceStore`, and only the name it7 * is kept under travels on. The gate classifies each failure against the8 * same lane on main (`gate.classifyFailure`).9 *10 * The merged tree is checked in the answer's fork, where `Lander.merge`11 * keeps it (under `${Brand.refsPrefix}merge/<tree>`), so a merge needs no12 * write token on the canonical repo; main is checked in the canonical repo.13 */14import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";15import type { CheckRun, LaneEvidence } from "@repo/checks/check-runner";16import { EvidenceStore } from "@repo/checks/evidence-store";17import { classifyFailure } from "@repo/gate/classify";18import type { AnswerRun } from "@repo/project/answer-runs";19import { LandingState } from "@repo/project/landing";20import {21 HeldBackResult,22 LaneOutcome,23 LaneResult,24} from "@repo/protocol/domain/answer";25import { AskKind } from "@repo/protocol/domain/kind";26import {27 CommitSha,28 LandedSha,29 LaneName,30 ProjectName,31 RepoName,32 RepoPath,33 RequestId,34 TreeSha,35} from "@repo/protocol/ids";36import type {37 ChecksFailed,38 Flake,39 StaleBase,40 VerifierBlocked,41} from "@repo/protocol/refusal";42import { Array, Effect, Option, Order, Schema } from "effect";4344/**45 * The lanes the cheap stage runs before the costlier checks: the static46 * ones, under the names the run block finder gives them (`checks/finder`).47 * Ratchet counts join them in W4 (417).48 */49export const cheapLanes = ["format", "lint", "types"] as const;5051/** Which of the answer's lanes a stage runs. */52export type Stage = "cheap" | "checks";5354const isCheap = (lane: LaneName) =>55 cheapLanes.some((name): boolean => name === lane);5657/** The lanes of `run` that `stage` runs; the ask's own check is never cheap. */58export const lanesFor = (run: AnswerRun, stage: Stage): readonly CheckLane[] =>59 run.lanes.filter(60 ({ lane }) =>61 (stage === "cheap") === (isCheap(lane) && lane !== run.askLane)62 );6364/** What the lanes are judged against: the answer's request, its merge and its main. */65export const Checked = Schema.Struct({66 /** The lane the ask's own check reports as: red on main by design. */67 askLane: Schema.optionalKey(LaneName),68 attempt: Schema.Int,69 base: CommitSha,70 /** Every path the answer changed against its base. */71 changed: Schema.Array(RepoPath),72 finish: AskKind.fields.finish,73 /**74 * The answer's fork, which holds the merged tree: the Lander keeps it there75 * under `${Brand.refsPrefix}merge/<tree>` for the Checker to fetch.76 */77 fork: RepoName,78 main: LandedSha,79 project: ProjectName,80 /** The canonical repo, which holds main. */81 repo: RepoName,82 requestId: RequestId,83 tree: TreeSha,84});8586export type Checked = typeof Checked.Type;8788/** One lane on the merged tree, as the gate classifies it. */89export const LaneRun = Schema.Struct({90 /** The lane as the project runs it: what runs again on main. */91 check: CheckLane,92 /** The repo files outside tests its failure points at, when its log names any. */93 failingPaths: Schema.Array(RepoPath),94 /** How its first run on the merged tree ended. */95 first: LaneOutcome,96 /** How its fresh run ended, when the first never got going. */97 rerun: Schema.optionalKey(LaneOutcome),98 /** The result that stands, with where its log is kept when it did not pass at first. */99 result: LaneResult,100});101102export type LaneRun = typeof LaneRun.Type;103104/** What one stage's run on the merged tree came to. */105export const StageRun = Schema.TaggedUnion({106 /** The checker could not run at all: the project tries again later. */107 Blocked: { attempt: Schema.Int },108 /** The answer no longer waits on these checks: another run moved it on. */109 Moved: {},110 Ran: {111 checked: Checked,112 heldBack: Schema.Array(HeldBackResult),113 lanes: Schema.Array(LaneRun),114 },115});116117export type StageRun = typeof StageRun.Type;118119type Ran = Extract<StageRun, { readonly _tag: "Ran" }>;120121/**122 * A path with a line, as a stack frame or a compiler prints one:123 * `src/lex.ts:3:7`. Its extension starts with a letter, so an address and124 * its port (`127.0.0.1:8080`) is no file.125 */126const LOCATION =127 /(?<![\w./@+-])(?<path>(?:[\w@+-][\w.@+-]*\/)*[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]*):\d+/gu;128129/** A file whose failure says nothing about where the code broke: a test itself. */130const TEST_FILE =131 /(?:^|\/)(?:tests?|__tests__)\/|\.(?:test|spec)\.[A-Za-z0-9]+$/u;132133/**134 * The repo files a lane's failure points at: every relative `path:line` its135 * output names, tests left out (a test failing in its own file says136 * nothing about which code broke). Absolute paths are not the repo's.137 */138export const failingPathsOf = (output: string): readonly RepoPath[] =>139 Array.sort(140 Array.dedupe(141 [...output.matchAll(LOCATION)].flatMap(({ groups }) =>142 groups?.path === undefined || TEST_FILE.test(groups.path)143 ? []144 : [groups.path]145 )146 ),147 Order.String148 ).map((path) => RepoPath.make(path));149150/**151 * A lane's log, as the platform keeps it. The Checker's `CheckRun` carries152 * no raw output yet, so the log is what the run said of the lane: its end,153 * its command, and its failure's signature.154 */155export const laneLog = (156 result: LaneResult,157 evidence: Option.Option<LaneEvidence>158): string =>159 [160 `${result.lane}: ${result.result} in ${result.durationMs} ms`,161 `$ ${result.command}`,162 ...Option.toArray(163 Option.flatMap(evidence, ({ signature }) =>164 Option.fromUndefinedOr(signature)165 )166 ),167 ...Option.toArray(168 Option.flatMap(evidence, ({ weakness }) =>169 Option.fromUndefinedOr(weakness)170 )171 ),172 ].join("\n");173174const isTrouble = (result: LaneOutcome) =>175 result === "flaked" || result === "blocked";176177/** Each lane's result and evidence in a run, by lane. */178interface ByLane {179 readonly evidence: ReadonlyMap<LaneName, LaneEvidence>;180 readonly results: ReadonlyMap<LaneName, LaneResult>;181}182183const byLane = (run: CheckRun): ByLane => ({184 evidence: new Map(run.evidence.map((each) => [each.lane, each])),185 results: new Map(run.lanes.map((each) => [each.lane, each])),186});187188const noRun: ByLane = { evidence: new Map(), results: new Map() };189190/** One lane as a stage's runs left it. */191interface Standing {192 readonly check: CheckLane;193 /** Its first run on the merged tree; `blocked` when that run left it out. */194 readonly first: LaneResult;195 /** Its fresh run, when it had one. */196 readonly again: Option.Option<LaneResult>;197 /** The result that stands: the fresh run's, else the first. */198 readonly stands: LaneResult;199 /** What the run that stands said of it, when it did not pass. */200 readonly said: Option.Option<LaneEvidence>;201}202203const standingOf = (204 lane: CheckLane,205 first: ByLane,206 fresh: ByLane207): Standing => {208 const began = first.results.get(lane.lane) ?? {209 command: lane.command,210 durationMs: 0,211 lane: lane.lane,212 result: "blocked",213 };214215 const again = Option.fromUndefinedOr(fresh.results.get(lane.lane));216217 return {218 again,219 check: lane,220 first: began,221 said: Option.fromUndefinedOr(222 (Option.isSome(again) ? fresh : first).evidence.get(lane.lane)223 ),224 stands: Option.getOrElse(again, () => began),225 };226};227228/** A lane as the gate classifies it, before its log is kept. */229const laneRunOf = (checked: Checked, standing: Standing): LaneRun => {230 const signature = Option.getOrElse(231 Option.flatMap(standing.said, ({ signature: said }) =>232 Option.fromUndefinedOr(said)233 ),234 () => ""235 );236237 const judged: LaneRun = {238 check: standing.check,239 failingPaths:240 standing.first.lane === checked.askLane ? [] : failingPathsOf(signature),241 first: standing.first.result,242 result: standing.stands,243 };244245 return Option.match(standing.again, {246 onNone: () => judged,247 onSome: ({ result }) => ({ ...judged, rerun: result }),248 });249};250251/** What the answer's state says the lanes are judged against, when it waits on checks of `tree`. */252const checkedOf = (run: AnswerRun, tree: TreeSha): Option.Option<Checked> => {253 const { state } = run;254255 if (!LandingState.guards.Checking(state) || state.tree !== tree) {256 return Option.none();257 }258259 const { request } = state;260261 const checked = {262 attempt: state.attempt,263 base: request.base,264 changed: state.changes.map(({ path }) => path),265 finish: run.finish,266 fork: request.fork,267 main: state.main,268 project: request.project,269 repo: run.repo,270 requestId: request.requestId,271 tree: state.tree,272 };273274 return Option.some(275 run.askLane === undefined ? checked : { ...checked, askLane: run.askLane }276 );277};278279/**280 * One stage's lanes on the merged tree `tree`: run, a troubled lane run281 * once more, and each lane that did not pass at first logged. The log's282 * name counts the answer's merges (`#1` on its first main), so a replayed283 * step keeps its log under the same name and a re-merge gets a new one.284 */285export const runStage = (286 run: AnswerRun,287 tree: TreeSha,288 stage: Stage289): Effect.Effect<StageRun, never, CheckRunner | EvidenceStore> =>290 Option.match(checkedOf(run, tree), {291 onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),292 onSome: (checked) =>293 Effect.gen(function* () {294 const runner = yield* CheckRunner;295 const evidence = yield* EvidenceStore;296 const lanes = lanesFor(run, stage);297298 const remerges = LandingState.guards.Checking(run.state)299 ? run.state.remerges300 : 0;301302 const job = (each: readonly CheckLane[]) =>303 runner.run({304 at: CheckAt.cases.Tree.make({ tree }),305 lanes: each,306 placeholders: [],307 project: checked.project,308 proxies: [],309 repo: checked.fork,310 });311312 if (!Array.isReadonlyArrayNonEmpty(lanes)) {313 return StageRun.cases.Ran.make({ checked, heldBack: [], lanes: [] });314 }315316 const firstRun = yield* job(lanes);317 const first = byLane(firstRun);318319 const troubled = lanes.filter(({ lane }) =>320 isTrouble(first.results.get(lane)?.result ?? "blocked")321 );322323 const fresh = Array.isReadonlyArrayNonEmpty(troubled)324 ? byLane(yield* job(troubled))325 : noRun;326327 const laneRuns = yield* Effect.forEach(lanes, (lane) => {328 const standing = standingOf(lane, first, fresh);329 const judged = laneRunOf(checked, standing);330331 if (standing.first.result === "passed") {332 return Effect.succeed(judged);333 }334335 return Effect.map(336 evidence.put({337 attempt: remerges + 1,338 lane: lane.lane,339 project: checked.project,340 requestId: checked.requestId,341 text: laneLog(standing.stands, standing.said),342 }),343 (logRef) => ({ ...judged, result: { ...judged.result, logRef } })344 );345 });346347 return StageRun.cases.Ran.make({348 checked,349 heldBack: firstRun.heldBack,350 lanes: laneRuns,351 });352 }).pipe(353 Effect.catchTag("VerifierBlocked", () =>354 Effect.succeed(355 StageRun.cases.Blocked.make({ attempt: checked.attempt })356 )357 )358 ),359 });360361/** The lanes of a stage's run whose failure the gate classifies against main. */362export const toCompareOnMain = (ran: Ran): readonly CheckLane[] =>363 ran.lanes364 .filter(365 ({ check, first }) =>366 first !== "passed" && check.lane !== ran.checked.askLane367 )368 .map(({ check }) => check);369370/**371 * Each failing lane, classified by the gate: against the same lane on main372 * (`onMain`; the ask's own check counts as green there, since it is red on373 * main by design), the fresh run, and the paths the answer changed.374 */375export const refusalsOf = (376 ran: Ran,377 onMain: ReadonlyMap<LaneName, LaneOutcome>378): readonly (ChecksFailed | Flake | StaleBase | VerifierBlocked)[] => {379 const { checked } = ran;380 const changed = new Set(checked.changed);381382 return Array.getSomes(383 ran.lanes.map(({ failingPaths, first, rerun, result }) =>384 Option.flatMap(Option.fromUndefinedOr(result.logRef), (logRef) =>385 classifyFailure(386 {387 command: result.command,388 failingPaths,389 isDoctor: false,390 lane: result.lane,391 logRef,392 onMain:393 result.lane === checked.askLane394 ? "passed"395 : (onMain.get(result.lane) ?? "blocked"),396 onMerged: first,397 rerun: Option.fromUndefinedOr(rerun),398 },399 changed,400 { base: checked.base, main: checked.main }401 )402 )403 )404 );405};406407/** A lane's end on main: what the gate compares a failure on the merged tree with. */408export const laneOnMain = (409 checked: Checked,410 lane: CheckLane411): Effect.Effect<LaneOutcome, never, CheckRunner> =>412 CheckRunner.use((runner) =>413 runner.run({414 at: CheckAt.cases.Commit.make({ commit: checked.main }),415 lanes: [lane],416 placeholders: [],417 project: checked.project,418 proxies: [],419 repo: checked.repo,420 })421 ).pipe(422 Effect.map(423 ({ lanes }): LaneOutcome =>424 lanes.find((each) => each.lane === lane.lane)?.result ?? "blocked"425 ),426 Effect.catchTag("VerifierBlocked", () =>427 Effect.succeed<LaneOutcome>("blocked")428 )429 );
added:apps/platform/src/workflows/answer/program.ts+437 added
1/**2 * The Answer Workflow's program (spec §5 steps 7–8): one admitted answer3 * carried to its verdict and onto main through its project's answer queue,4 * each port call a named durable step.5 *6 * The project decides; the program only runs what it asks for. It loads7 * the answer's run (`answer`), then runs each port call the run waits on8 * (`merge`, the `cheap` lanes and the `checks` on the merged tree, `land`)9 * as a step whose value is the `LandingCommand` that reports it, and10 * reports it in a `record` step (`advanceAnswer`), which returns the calls11 * to run next. Every call to the project happens inside a step, so a replay12 * of the whole run follows the same path and runs nothing twice; a step13 * whose effect ran twice reports twice, and the landing lifecycle takes the14 * second report as the replay it is. Step names carry their attempt15 * (`merge#2`), so a merge onto a main that moved is a new step, not a replay.16 *17 * The run stops when the answer lands, is refused, waits on a person or on18 * the landing slot, or must wait for a retry: the project starts it again19 * then. A busy repo during a land is retried by the land step's own20 * retries first. It also stops when a port step finds nothing to do (the21 * answer no longer waits on that call), as W2's in-process run does:22 * whatever moved the answer on carries it, and a run that went on from the23 * state it found could ask for the same call forever.24 */25import type { CheckRunner } from "@repo/checks/check-runner";26import type { EvidenceStore } from "@repo/checks/evidence-store";27import {28 AnswerReport,29 AnswerRun,30 NextStep,31 ReportedCommand,32 Steps,33} from "@repo/project/answer-runs";34import { nextSteps, runStep } from "@repo/project/answer-runs/steps";35import type { Lander } from "@repo/project/lander";36import {37 LandingCommand,38 LandingEffect,39 outcomeOf,40} from "@repo/project/landing";41import { Projects } from "@repo/project/projects";42import { LaneOutcome } from "@repo/protocol/domain/answer";43import type { Outcome } from "@repo/protocol/domain/outcome";44import type { LaneName, ProjectName, RequestId } from "@repo/protocol/ids";45import { Array, Data, Effect, Match, Option, Schema } from "effect";4647import type { AnswerParams } from "../../answer-runs.ts";48import { StepRunner } from "../step.ts";49import type { StepRetry } from "../step.ts";50import {51 laneOnMain,52 refusalsOf,53 runStage,54 StageRun,55 toCompareOnMain,56} from "./lanes.ts";57import type { Stage } from "./lanes.ts";5859/** Every port the program runs on. */60export type AnswerPorts =61 | CheckRunner62 | EvidenceStore63 | Lander64 | Projects65 | StepRunner;6667/** A run was started for a request its project does not hold: the project never does that. */68export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{69 readonly project: ProjectName;70 readonly requestId: RequestId;71}> {}7273/** A land found the repo busy, at the landing's attempt: the land step's retries take it. */74class LandBusy extends Data.TaggedError("LandBusy")<{75 readonly attempt: number;76}> {}7778/** How a land step retries a busy repo before the project's own retry takes over. */79export const landRetry: StepRetry = {80 backoff: "exponential",81 delayMs: 1000,82 limit: 3,83};8485/** What a port step came to: the command that reports it, and what it saw beside it. */86export const Reported = Schema.Struct({87 command: ReportedCommand,88 report: Schema.optionalKey(AnswerReport),89});9091export type Reported = typeof Reported.Type;9293/** A port step's value: `None` when the answer no longer waits on that call. */94const Reporting = Schema.Option(Reported);9596type NextStep = typeof NextStep.Type;9798type Steps = typeof Steps.Type;99100type Call<Tag extends NextStep["_tag"]> = Extract<101 NextStep,102 { readonly _tag: Tag }103>;104105/** How many times each port call has run in this run: the attempt in a step's name. */106interface Attempts {107 readonly Land: number;108 readonly Merge: number;109 readonly RunChecks: number;110}111112const reported = (113 command: LandingCommand,114 report?: AnswerReport115): Option.Option<Reported> =>116 Option.some(report === undefined ? { command } : { command, report });117118/** The port calls among a landing's effects, as a run hands them on. */119const callsOf = (effects: readonly LandingEffect[]): readonly NextStep[] =>120 effects.flatMap((effect) =>121 LandingEffect.$match(effect, {122 Emit: (): readonly NextStep[] => [],123 Land: ({ main, tree }) => [NextStep.cases.Land.make({ main, tree })],124 Merge: ({ base, fork, head, main }) => [125 NextStep.cases.Merge.make({ base, fork, head, main }),126 ],127 Record: () => [],128 Retry: ({ at }) => [NextStep.cases.Retry.make({ at })],129 RunChecks: ({ tree }) => [NextStep.cases.RunChecks.make({ tree })],130 })131 );132133/** What a call is about, to tell whether the run still waits on it. */134const keyOf = (call: NextStep): string =>135 NextStep.match(call, {136 Land: ({ main, tree }) => `land ${main} ${tree}`,137 Merge: ({ head, main }) => `merge ${head} onto ${main}`,138 Retry: () => "retry",139 RunChecks: ({ tree }) => `checks ${tree}`,140 });141142/** Whether the answer's run waits on `call` now. */143const waitsOn = (run: AnswerRun, call: NextStep) =>144 callsOf(nextSteps(run)).some((each) => keyOf(each) === keyOf(call));145146/** The answer's project, as the platform reaches it. */147const projectOf = (project: ProjectName) =>148 Projects.use((projects) => projects.get(project)).pipe(Effect.orDie);149150/** The answer's run as its project holds it now. */151const load = ({ project, requestId }: AnswerParams) =>152 Effect.flatMap(projectOf(project), (api) => api.answer(requestId));153154/**155 * The port call `effect` names, run as W2's in-process run runs it156 * (`runStep`), on the answer's run as its project holds it now; `None`157 * when the run no longer waits on `call`.158 */159const portCall = (160 params: AnswerParams,161 call: Call<"Land" | "Merge">,162 effect: LandingEffect163) =>164 Effect.flatMap(load(params), (run) =>165 Option.isSome(run) && waitsOn(run.value, call)166 ? runStep(run.value, effect)167 : Effect.succeedNone168 );169170/** The answer's head merged onto the main the call names. */171const merge = (params: AnswerParams, call: Call<"Merge">) =>172 portCall(173 params,174 call,175 LandingEffect.Merge({176 base: call.base,177 fork: call.fork,178 head: call.head,179 main: call.main,180 })181 );182183/**184 * The checked tree landed on main as the platform's commit, through the185 * project's landing slot (the run waits on a land only while it holds the186 * slot). A main that moved sends the answer back to merge; a busy repo187 * fails the step, for its retries.188 */189const land = (params: AnswerParams, call: Call<"Land">) =>190 Effect.flatMap(191 portCall(192 params,193 call,194 LandingEffect.Land({ main: call.main, tree: call.tree })195 ),196 (given) =>197 Option.isSome(given) && LandingCommand.$is("Busy")(given.value.command)198 ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))199 : Effect.succeed(given)200 );201202/**203 * One stage's lanes on the merged tree, then each failing lane on main, one204 * step per (main, lane), and the gate's classification of each failure.205 */206const stage = (207 params: AnswerParams,208 tree: Call<"RunChecks">["tree"],209 name: Stage,210 attempt: number211) =>212 Effect.gen(function* () {213 const { step } = yield* StepRunner;214215 const ran = yield* step(216 `${name}#${attempt}`,217 StageRun,218 Effect.flatMap(load(params), (run) =>219 Option.match(run, {220 onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),221 onSome: (found) => runStage(found, tree, name),222 })223 )224 );225226 if (!StageRun.guards.Ran(ran)) {227 return { ran, refusals: [] };228 }229230 const onMain = yield* Effect.forEach(toCompareOnMain(ran), (lane) =>231 Effect.map(232 step(233 `main:${ran.checked.main}:${lane.lane}`,234 LaneOutcome,235 laneOnMain(ran.checked, lane)236 ),237 (outcome) => [lane.lane, outcome] as const238 )239 );240241 return {242 ran,243 refusals: refusalsOf(ran, new Map<LaneName, LaneOutcome>(onMain)),244 };245 });246247/**248 * The checks on the exact merged tree: the cheap stage, then, if it passed,249 * the ask's own check and every other project lane. The first stage that250 * refuses ends them, with its refusals and its lanes.251 */252const checks = (253 params: AnswerParams,254 call: Call<"RunChecks">,255 attempt: number256): Effect.Effect<Option.Option<Reported>, never, AnswerPorts> =>257 Effect.gen(function* () {258 const cheap = yield* stage(params, call.tree, "cheap", attempt);259260 // W4 417: the cheap stage's ratchet counts, and the decisions a reasoned261 // escape asks for, join here.262 const judged =263 StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0264 ? yield* stage(params, call.tree, "checks", attempt)265 : undefined;266267 const last = judged ?? cheap;268269 return StageRun.match(last.ran, {270 Blocked: ({ attempt: at }) =>271 reported(LandingCommand.Blocked({ attempt: at })),272 Moved: () => Option.none(),273 Ran: ({ checked, heldBack, lanes }) =>274 reported(275 LandingCommand.Checked({276 decisions: [],277 finish: checked.finish,278 refusals: last.refusals,279 tree: call.tree,280 }),281 {282 heldBack,283 lanes: [284 ...(judged !== undefined && StageRun.guards.Ran(cheap.ran)285 ? cheap.ran.lanes286 : []),287 ...lanes,288 ].map(({ result }) => result),289 }290 ),291 });292 });293294/**295 * A port step's report given to the project, and the calls to run next.296 * When nothing comes next, or the step had nothing to report, the run's own297 * state says what it waits on: a person, the landing slot, a retry, or298 * nothing (the report was given already, by a step whose effect ran twice).299 */300const record = (params: AnswerParams, given: Option.Option<Reported>) =>301 Effect.gen(function* () {302 const api = yield* projectOf(params.project);303304 if (Option.isSome(given)) {305 const advanced = yield* api.advanceAnswer(306 params.requestId,307 given.value.command,308 given.value.report309 );310311 const calls = callsOf(advanced.effects);312313 if (Array.isReadonlyArrayNonEmpty(calls)) {314 return { effects: calls, outcome: advanced.outcome } satisfies Steps;315 }316 }317318 const run = yield* api.answer(params.requestId);319320 if (Option.isNone(run)) {321 return yield* Effect.die(new UnknownRequest(params));322 }323324 return {325 effects: callsOf(nextSteps(run.value)),326 outcome: outcomeOf(run.value.state),327 } satisfies Steps;328 });329330/**331 * Where the verdict note on the answer's head, in its fork, is written after332 * a step that judged it (W4 407: `writeVerdictNote` in its own step). Empty333 * until then; the canonical note is written by `Lander.land` with the334 * verdict.335 */336const notes = (_params: AnswerParams, _judged: Steps): Effect.Effect<void> =>337 Effect.void;338339/** The port call a step runs, under its name. */340const portStep = (341 params: AnswerParams,342 call: Call<"Land" | "Merge" | "RunChecks">,343 attempt: number344): Effect.Effect<Option.Option<Reported>, never, AnswerPorts> =>345 Effect.flatMap(StepRunner, ({ step }) =>346 Match.valueTags(call, {347 Land: (landing) =>348 step(349 `land#${attempt}`,350 Reporting,351 land(params, landing),352 landRetry353 ).pipe(354 Effect.catchTag("LandBusy", ({ attempt: at }) =>355 Effect.succeed(reported(LandingCommand.Busy({ attempt: at })))356 )357 ),358 Merge: (merging) =>359 step(`merge#${attempt}`, Reporting, merge(params, merging)),360 RunChecks: (checking) => checks(params, checking, attempt),361 })362 );363364const nameOf = {365 Land: "land",366 Merge: "merge",367 RunChecks: "checks",368} as const satisfies Record<keyof Attempts, string>;369370/** Runs the calls `at` names, one after another, until none is left. */371const carry = (372 params: AnswerParams,373 at: Steps,374 attempts: Attempts375): Effect.Effect<Outcome, never, AnswerPorts> =>376 Effect.gen(function* () {377 // A retry is the project's to start, at its alarm.378 if (at.effects.some(NextStep.guards.Retry)) {379 return at.outcome;380 }381382 const call = at.effects.find(383 (each): each is Call<"Land" | "Merge" | "RunChecks"> =>384 !NextStep.guards.Retry(each)385 );386387 if (call === undefined) {388 return at.outcome;389 }390391 const attempt = attempts[call._tag] + 1;392 const given = yield* portStep(params, call, attempt);393 const { step } = yield* StepRunner;394395 const next = yield* step(396 `record:${nameOf[call._tag]}#${attempt}`,397 Steps,398 record(params, given)399 );400401 if (Option.isNone(given)) {402 return next.outcome;403 }404405 if (NextStep.guards.RunChecks(call)) {406 yield* notes(params, next);407 }408409 return yield* carry(params, next, { ...attempts, [call._tag]: attempt });410 });411412/**413 * Carries one admitted answer as far as it goes now: merged onto main,414 * checked on the merged tree, and landed through its project's serial415 * queue, or refused, or waiting. The same request run again converges on416 * one outcome and one landing (principle 8).417 */418export const runAnswer = (419 params: AnswerParams420): Effect.Effect<Outcome, never, AnswerPorts> =>421 Effect.gen(function* () {422 const { step } = yield* StepRunner;423 const run = yield* step("load", Schema.Option(AnswerRun), load(params));424425 if (Option.isNone(run)) {426 return yield* Effect.die(new UnknownRequest(params));427 }428429 return yield* carry(430 params,431 {432 effects: callsOf(nextSteps(run.value)),433 outcome: outcomeOf(run.value.state),434 },435 { Land: 0, Merge: 0, RunChecks: 0 }436 );437 });
modified:apps/platform/src/workflows/answer.ts+62 added-5 removed
added:apps/platform/test/workflows/answer.fixtures.ts+649 added
1/**2 * One project with one answer admitted and waiting for its Answer Workflow,3 * over in-process adapters: `RepoHostMemory`, W2's isomorphic-git `Lander`4 * over it (recorded, and able to answer `RepoBusy`), a `CheckRunner`5 * scripted per (tree or commit, lane), a `RulesEvaluator` that returns the6 * scenario's policy, `ProjectsMemory`, `EvidenceStoreMemory`, and an7 * `AnswerRuns` that only records which runs the project started: the test8 * runs the Workflow's program itself.9 *10 * The Lander is the isomorphic-git one, not the scripted `/memory` one,11 * because the project reads real commits on the way to an admitted answer12 * (the ask's files composed onto main, the answer's diff for the gate), and13 * a re-merge after main moved must produce a real tree.14 */15import { RefName, RepoHost } from "@repo/artifacts/repo-host";16import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";17import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";18import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";19import type { CheckJob, LaneEvidence } from "@repo/checks/check-runner";20import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";21import { AlarmsMemory } from "@repo/project/alarms/memory";22import { AnswerRuns } from "@repo/project/answer-runs";23import type { AnswerReport } from "@repo/project/answer-runs";24import { Lander } from "@repo/project/lander";25import type { MergeJob } from "@repo/project/lander";26import { LanderIsogit } from "@repo/project/lander/isogit";27import { LanderJob } from "@repo/project/lander/memory";28import type { LandingCommand } from "@repo/project/landing";29import { FinishersFromChecks } from "@repo/project/project";30import type { ProjectApi } from "@repo/project/project";31import { ProjectionMemory } from "@repo/project/projection/memory";32import { Projects } from "@repo/project/projects";33import { ProjectsMemory } from "@repo/project/projects/memory";34import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";35import type { Ask } from "@repo/protocol/domain/ask";36import { CheckSpec } from "@repo/protocol/domain/check";37import { Policy } from "@repo/protocol/domain/policy";38import {39 AskId,40 LandedSha,41 LaneName,42 RepoName,43 RepoPath,44 RequestId,45} from "@repo/protocol/ids";46import type { CommitSha } from "@repo/protocol/ids";47import { Person } from "@repo/protocol/principal";48import { RepoBusy, VerifierBlocked } from "@repo/protocol/refusal";49import { Finishers } from "@repo/rules/finish";50import { RulesEvaluator } from "@repo/rules/rules-evaluator";51import { advanceTo } from "@repo/testkit/clock";52import { gitClient } from "@repo/testkit/git-client";53import type { Files } from "@repo/testkit/git-client";54import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";55import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";5657import { StepRunner } from "../../src/workflows/step.ts";58import type { StepRetry } from "../../src/workflows/step.ts";5960const mainRef = RefName.make("refs/heads/main");6162const scenario = aProject({ people: ["bob"] }).pipe(63 withVouches(["bob"]),64 withAsk({ id: "parse-iso", territory: "packages/parser" })65);6667/**68 * The scenario's policy, with a `unit` lane beside its cheap `lint` and69 * `types` lanes: the checks stage runs the ask's own check and `unit`.70 */71export const policy: Policy = Schema.decodeSync(Policy)({72 ...Schema.encodeSync(Policy)(scenario.policy),73 run: {74 checks: {75 lint: "bun run lint",76 types: "bun run typecheck",77 unit: "bun run test",78 },79 test: "bun test {path}",80 },81});8283export const { project } = scenario;8485export const repo = RepoName.make(project);8687export const alice = Person.make({ handle: scenario.initializer });8889export const bob = Person.make({90 handle: scenario.people.get("bob") ?? scenario.initializer,91});9293export const parseIso = AskId.make("parse-iso");9495export const bobFork = RepoName.make(`${project}--${parseIso}--${bob.handle}`);9697const ask: Ask = Option.getOrThrow(98 Array.findFirst(policy.asks, ({ id }) => id === parseIso)99);100101/** The lane the ask's own check reports as. */102export const askLane = LaneName.make("redThenGreen");103104/** Where the ask's check lives: red on main, green once answered. */105export const checkPath = CheckSpec.guards.RedThenGreen(ask.check)106 ? ask.check.path107 : RepoPath.make("packages/parser/test/parse-iso.test.ts");108109/** The file the answer changes. */110export const parsePath = RepoPath.make("packages/parser/src/parse.ts");111112/** A file the answer leaves alone. */113export const lexPath = RepoPath.make("packages/lexer/src/lex.ts");114115/** The project as alice first pushes it. */116const start: Files = [117 ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],118 [lexPath, "export const lex = (s) => s.split(' ');\n"],119 [parsePath, "export const parse = (s) => ({});\n"],120];121122/** The ask's own files: its file in the config folder, and its check. */123const askFiles = Array.make(124 { content: `export default "${parseIso}";\n`, path: ask.file },125 {126 content: [127 `import { expect, it } from "vitest";`,128 `import { parse } from "../src/parse.ts";`,129 ``,130 `it("${parseIso}", () => {`,131 ` expect(parse("2026-10-07")).toStrictEqual({ year: 2026 });`,132 `});`,133 ``,134 ].join("\n"),135 path: checkPath,136 }137);138139/** Main once the ask opened: alice's files and the ask's. */140export const openedFiles: Files = [141 ...start,142 ...askFiles.map(({ content, path }) => [path, content] as const),143];144145/** `files` with `path` holding `content`, added or replaced. */146export const changed = (files: Files, path: string, content: string): Files => [147 ...files.filter(([each]) => each !== path),148 [path, content],149];150151/** Bob's answer: main once the ask opened, with `parse` fixed. */152export const fixed = changed(153 openedFiles,154 parsePath,155 "export const parse = (s) => ({ year: 2026 });\n"156);157158// ------------------------------------------------------------------ checker159160/** One scripted run of a lane: how it ends, and its failure's signature. */161export interface ScriptedRun {162 readonly result: LaneOutcome;163 /** What the failing test said, as `checks.classify` writes a signature. */164 readonly signature?: string;165}166167/** The scripted Checker's script, and every job it was given. */168export class Checker extends Context.Service<169 Checker,170 {171 readonly script: (172 at: CheckAt,173 lane: LaneName,174 runs: readonly ScriptedRun[]175 ) => Effect.Effect<void>;176 readonly jobs: Effect.Effect<readonly CheckJob[]>;177 }178>()("test/Checker") {}179180/** Where a lane's script lives: `<tree or commit sha>:<lane>`. */181const keyOf = (at: CheckAt, lane: LaneName) => `${shaOf(at)}:${lane}`;182183/**184 * `CheckRunner` scripted per (tree or commit, lane), as `CheckRunnerMemory`185 * is, with each failure's signature too: each key serves its runs in order,186 * then the last again. A job with a lane nobody scripted is187 * `VerifierBlocked`, as a Checker that cannot run is.188 */189const checker = Layer.effectContext(190 Effect.gen(function* () {191 const scripts = yield* Ref.make<192 ReadonlyMap<string, readonly ScriptedRun[]>193 >(new Map());194195 const served = yield* Ref.make<ReadonlyMap<string, number>>(new Map());196 const jobs = yield* Ref.make<readonly CheckJob[]>([]);197198 const next = (199 key: string,200 runs: Array.NonEmptyReadonlyArray<ScriptedRun>201 ) =>202 Ref.modify(served, (counts) => {203 const count = counts.get(key) ?? 0;204205 return [206 runs[Math.min(count, runs.length - 1)] ?? runs[0],207 new Map(counts).set(key, count + 1),208 ] as const;209 });210211 const run = (job: CheckJob) =>212 Effect.gen(function* () {213 yield* Ref.update(jobs, (given) => [...given, job]);214215 const known = yield* Ref.get(scripts);216217 const scripted = yield* Effect.forEach(job.lanes, (lane) =>218 Option.match(219 Option.filter(220 Option.fromUndefinedOr(known.get(keyOf(job.at, lane.lane))),221 Array.isReadonlyArrayNonEmpty222 ),223 {224 onNone: () => Effect.fail(new VerifierBlocked({})),225 onSome: (runs) => Effect.succeed({ lane, runs }),226 }227 )228 );229230 const ran = yield* Effect.forEach(scripted, ({ lane, runs }) =>231 Effect.map(next(keyOf(job.at, lane.lane), runs), (one) => ({232 lane,233 one,234 }))235 );236237 const lanes = ran.map(({ lane, one }): LaneResult => ({238 command: lane.command,239 durationMs: 1,240 lane: lane.lane,241 result: one.result,242 }));243244 const evidence = ran.flatMap(({ lane, one }): LaneEvidence[] => {245 if (one.result === "passed") {246 return [];247 }248249 return one.signature === undefined250 ? [{ lane: lane.lane }]251 : [{ lane: lane.lane, signature: one.signature }];252 });253254 return { durationMs: lanes.length, evidence, heldBack: [], lanes };255 });256257 return Context.make(CheckRunner, { run }).pipe(258 Context.add(Checker, {259 jobs: Ref.get(jobs),260 script: (at, lane, runs) =>261 Ref.update(scripts, (known) =>262 new Map(known).set(keyOf(at, lane), runs)263 ),264 })265 );266 })267);268269// ------------------------------------------------------------------- lander270271/** What the Lander was asked, and a way to make its next lands busy. */272export class LanderCalls extends Context.Service<273 LanderCalls,274 {275 /** Every job the project and the program gave the Lander, in order. */276 readonly jobs: Effect.Effect<readonly LanderJob[]>;277 /** The next `count` lands find the repo busy, and push nothing. */278 readonly busyFor: (count: number) => Effect.Effect<void>;279 /** The merge a test scripts the checks for, unrecorded. */280 readonly preview: (job: MergeJob) => Effect.Effect<CheckAt>;281 }282>()("test/LanderCalls") {}283284/** The isomorphic-git Lander, recorded, whose lands a test can make busy. */285const lander = Layer.effectContext(286 Effect.gen(function* () {287 const inner = yield* Lander;288 const jobs = yield* Ref.make<readonly LanderJob[]>([]);289 const busy = yield* Ref.make(0);290 const keep = (job: LanderJob) => Ref.update(jobs, (all) => [...all, job]);291292 const land: Lander["Service"]["land"] = (job) =>293 Effect.gen(function* () {294 yield* keep(LanderJob.Land({ job }));295296 const left = yield* Ref.getAndUpdate(busy, (n) => Math.max(n - 1, 0));297298 return left > 0 ? yield* new RepoBusy({}) : yield* inner.land(job);299 });300301 return Context.make(Lander, {302 bundleRules: (job) =>303 Effect.andThen(304 keep(LanderJob.BundleRules({ job })),305 inner.bundleRules(job)306 ),307 compose: (job) =>308 Effect.andThen(keep(LanderJob.Compose({ job })), inner.compose(job)),309 land,310 merge: (job) =>311 Effect.andThen(keep(LanderJob.Merge({ job })), inner.merge(job)),312 }).pipe(313 Context.add(LanderCalls, {314 busyFor: (count) => Ref.set(busy, count),315 jobs: Ref.get(jobs),316 preview: (job) =>317 Effect.map(inner.merge(job), ({ tree }) =>318 CheckAt.cases.Tree.make({ tree })319 ).pipe(Effect.orDie),320 })321 );322 })323).pipe(Layer.provide(LanderIsogit));324325// ------------------------------------------------------------- the project326327/**328 * A `RulesEvaluator` that evaluates nothing: at any commit it returns329 * `given`, holding the asks whose files the commit's config folder has, and330 * the judge closure `checks` derives.331 */332const rulesOf = (given: Policy) =>333 Layer.effect(334 RulesEvaluator,335 Effect.gen(function* () {336 const finishers = yield* Finishers;337338 return RulesEvaluator.of({339 call: () => Effect.succeed(false),340 evaluate: ({ at, facts, modules }) =>341 Effect.succeed({342 ...given,343 asks: given.asks.filter(({ file }) => file in modules.modules),344 at,345 judge: finishers.judgeClosure(given.run, facts.ci),346 } satisfies Policy),347 });348 })349 ).pipe(Layer.provide(FinishersFromChecks));350351/** Which answer runs the project started: the program runs them in the test. */352export class Started extends Context.Service<353 Started,354 { readonly ids: Effect.Effect<readonly RequestId[]> }355>()("test/Started") {}356357const started = Layer.effectContext(358 Effect.map(Ref.make<readonly RequestId[]>([]), (ids) =>359 Context.make(AnswerRuns, {360 start: (requestId) => Ref.update(ids, (all) => [...all, requestId]),361 }).pipe(Context.add(Started, { ids: Ref.get(ids) }))362 )363);364365/** One `advanceAnswer` call the project took, as the program made it. */366export interface Advance {367 readonly command: LandingCommand;368 readonly report: AnswerReport | undefined;369}370371/** Every `advanceAnswer` call made through `Projects`, in order. */372export class DoCalls extends Context.Service<373 DoCalls,374 { readonly advances: Effect.Effect<readonly Advance[]> }375>()("test/DoCalls") {}376377/** `ProjectsMemory`, with every `advanceAnswer` through it recorded. */378const projects = Layer.effectContext(379 Effect.gen(function* () {380 const inner = yield* Projects;381 const advances = yield* Ref.make<readonly Advance[]>([]);382383 const recorded = (api: ProjectApi): ProjectApi => ({384 ...api,385 advanceAnswer: (requestId, command, report) =>386 Effect.andThen(387 Ref.update(advances, (all) => [...all, { command, report }]),388 api.advanceAnswer(requestId, command, report)389 ),390 });391392 return Context.make(Projects, {393 create: (name) => Effect.map(inner.create(name), recorded),394 get: (name) => Effect.map(inner.get(name), recorded),395 }).pipe(Context.add(DoCalls, { advances: Ref.get(advances) }));396 })397).pipe(Layer.provide(ProjectsMemory));398399/** Commits made the way git would make them, pushed to a repo's `main`. */400export class Pusher extends Context.Service<401 Pusher,402 {403 readonly push: (404 repo: RepoName,405 parent: Option.Option<CommitSha>,406 files: Files407 ) => Effect.Effect<CommitSha>;408 }409>()("test/Pusher") {}410411const pusher = Layer.effect(412 Pusher,413 Effect.gen(function* () {414 const host = yield* RepoHost;415 const client = yield* gitClient(memoryFs());416417 return Pusher.of({418 push: (to, parent, files) =>419 Effect.gen(function* () {420 const sha = yield* client.commit(421 "Work",422 files,423 Option.toArray(parent)424 );425426 yield* host427 .push(to, client.source, [{ from: parent, ref: mainRef, to: sha }])428 .pipe(Effect.orDie);429430 return sha;431 }),432 });433 })434);435436/**437 * Every port the program runs on, and what the test reads back, with the438 * project's rules evaluating to `given`; fresh per build.439 */440export const worldWith = (given: Policy) =>441 Layer.mergeAll(projects, pusher).pipe(442 Layer.provideMerge(443 Layer.mergeAll(444 started,445 AlarmsMemory,446 ProjectionMemory,447 rulesOf(given),448 checker,449 EvidenceStoreMemory450 )451 ),452 Layer.provideMerge(lander),453 Layer.provideMerge(RepoHostMemory)454 );455456/** The world over the scenario's policy. */457export const world = worldWith(policy);458459/** The scenario's policy, with answers to a `fix` ask landing only once a decider finishes them. */460export const finishRequired: Policy = {461 ...policy,462 kinds: policy.kinds.map((kind) =>463 kind.name === "fix" ? { ...kind, finish: "required" } : kind464 ),465};466467/** Where canonical `main` stands now. */468export const mainTip = Effect.gen(function* () {469 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);470471 return LandedSha.make(472 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))473 );474});475476/** Every lane but the ask's, scripted the same on `at`. */477export const scriptProjectLanes = (at: CheckAt, run: ScriptedRun) =>478 Checker.use((script) =>479 Effect.forEach(480 Object.keys(policy.run.checks),481 (lane) => script.script(at, LaneName.make(lane), [run]),482 { discard: true }483 )484 );485486/** One answer admitted: its project, its request, where it was made and checked. */487export interface Admitted {488 readonly api: ProjectApi;489 readonly requestId: RequestId;490 /** The main the answer was made on: the ask's opening landing. */491 readonly opened: LandedSha;492 readonly head: CommitSha;493 /** The tree the answer merges onto `opened` as. */494 readonly merged: CheckAt;495}496497/**498 * The project made, its ask opened red first, bob's claim, his push of499 * `files` to his fork and his answer admitted: its run started, and no step500 * of it run yet. The checks on the merged tree are left to the test.501 */502export const admitted = (files: Files = fixed) =>503 Effect.gen(function* () {504 yield* advanceTo("2026-10-07T12:00:00Z");505506 const api = yield* Projects.use((each) => each.create(project)).pipe(507 Effect.orDie508 );509510 yield* api.initProject(alice, {}).pipe(Effect.orDie);511512 const first = yield* Pusher.use((each) =>513 each.push(repo, Option.none(), start)514 );515516 yield* api.recordFirstPush(alice, first).pipe(Effect.orDie);517518 const composed = yield* Lander.use((each) =>519 each.compose({ files: askFiles, main: LandedSha.make(first), repo })520 ).pipe(Effect.orDie);521522 yield* Checker.use((script) =>523 script.script(524 CheckAt.cases.Commit.make({ commit: composed.commit }),525 askLane,526 [{ result: "failed", signature: `${parseIso}: red` }]527 )528 );529530 const open = yield* api531 .openAsk(alice, { ask: parseIso, files: askFiles })532 .pipe(Effect.orDie);533534 yield* api.claim(bob, parseIso).pipe(Effect.orDie);535536 const head = yield* Pusher.use((each) =>537 each.push(bobFork, Option.some(open.landed), files)538 );539540 const merged = yield* LanderCalls.use((calls) =>541 calls.preview({542 base: open.landed,543 fork: bobFork,544 head,545 main: open.landed,546 repo,547 })548 );549550 const receipt = yield* api551 .submitAnswer(bob, {552 ask: parseIso,553 base: open.landed,554 head,555 requestId: RequestId.make(`push-${head}`),556 })557 .pipe(Effect.orDie);558559 return {560 api,561 head,562 merged,563 opened: open.landed,564 requestId: receipt.requestId,565 } satisfies Admitted;566 });567568/** Main moved by a push the platform did not make: `files` on top of `from`. */569export const mainMoved = (from: LandedSha, files: Files) =>570 Effect.map(571 Pusher.use((each) => each.push(repo, Option.some(from), files)),572 (sha) => LandedSha.make(sha)573 );574575/** The verdict the project keeps on bob's answer. */576export const verdictOf = (api: ProjectApi) =>577 Effect.map(api.verdict(bob, { ask: parseIso }), ({ verdict }) =>578 Option.fromUndefinedOr(verdict)579 ).pipe(Effect.orDie);580581// -------------------------------------------------------------------- steps582583/** Every step the program asked for, by name, in order, and each one's retries. */584export class StepLog extends Context.Service<585 StepLog,586 {587 readonly names: Effect.Effect<readonly string[]>;588 readonly retries: Effect.Effect<ReadonlyMap<string, StepRetry>>;589 }590>()("test/StepLog") {}591592/** More steps than any run of the scenario asks for: past it, the program ran away. */593const runaway = 64;594595/**596 * `inner`'s steps, each name the program asks for recorded, replays597 * included. With `twice`, a step that runs runs its effect twice and keeps598 * the second value, as an engine does when it retries a step whose first599 * run took effect before its record was written. A program that asks for600 * more than `runaway` steps dies there, so a test fails rather than hangs.601 */602export const logged = (603 inner: Layer.Layer<StepRunner>,604 options: { readonly twice?: boolean } = {}605) =>606 Layer.effectContext(607 Effect.gen(function* () {608 const runner = yield* StepRunner;609 const names = yield* Ref.make<readonly string[]>([]);610611 const retries = yield* Ref.make<ReadonlyMap<string, StepRetry>>(612 new Map()613 );614615 return Context.make(StepRunner, {616 step: (name, schema, effect, retry) =>617 Effect.gen(function* () {618 const asked = yield* Ref.updateAndGet(names, (all) => [619 ...all,620 name,621 ]);622623 if (asked.length > runaway) {624 return yield* Effect.die(625 `ran away: ${runaway} steps, then ${name}`626 );627 }628629 if (retry !== undefined) {630 yield* Ref.update(retries, (all) =>631 new Map(all).set(name, retry)632 );633 }634635 return yield* runner.step(636 name,637 schema,638 options.twice === true ? Effect.andThen(effect, effect) : effect,639 retry640 );641 }),642 }).pipe(643 Context.add(StepLog, {644 names: Ref.get(names),645 retries: Ref.get(retries),646 })647 );648 })649 ).pipe(Layer.provide(inner));
added:apps/platform/test/workflows/answer.test.ts+971 added
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 { 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 Checker,51 DoCalls,52 finishRequired,53 LanderCalls,54 lexPath,55 logged,56 mainMoved,57 mainTip,58 openedFiles,59 parseIso,60 parsePath,61 project,62 repo,63 scriptProjectLanes,64 Started,65 StepLog,66 verdictOf,67 world,68 worldWith,69} from "./answer.fixtures.ts";70import type { Admitted } from "./answer.fixtures.ts";7172const unit = LaneName.make("unit");7374const lint = LaneName.make("lint");7576/** One `advanceAnswer` call as it crosses the Durable Object's boundary. */77const Advance = Schema.toCodecJson(78 Schema.Struct({79 command: ReportedCommand,80 report: Schema.UndefinedOr(AnswerReport),81 })82);8384/** The program run for `answer`, over `steps`. */85const run = (answer: Admitted, steps: Context.Context<StepRunner>) =>86 runAnswer({ project, requestId: answer.requestId }).pipe(87 Effect.provide(steps)88 );8990/** Steps over a fresh in-memory record, each name asked for logged. */91const freshSteps = (options: { readonly twice?: boolean } = {}) =>92 Effect.flatMap(memoSteps(), (memo) => Layer.build(logged(memo, options)));9394/** Every step name `steps` was asked for, in order. */95const namesOf = (steps: Context.Context<StepLog>) =>96 StepLog.use(({ names }) => names).pipe(Effect.provide(steps));9798/** The steps of one pass from merge to land, after the run's `load`. */99const pass = (attempt: number) => [100 `merge#${attempt}`,101 `record:merge#${attempt}`,102 `cheap#${attempt}`,103 `checks#${attempt}`,104 `record:checks#${attempt}`,105 `land#${attempt}`,106 `record:land#${attempt}`,107];108109/** Every lane on `at` passes: the ask's check and every project lane. */110const allGreen = (at: CheckAt) =>111 Effect.andThen(112 scriptProjectLanes(at, { result: "passed" }),113 Checker.use((script) => script.script(at, askLane, [{ result: "passed" }]))114 );115116/** `lane` fails on the merged tree, saying `signature`, and ends `onMain` on main. */117const failsOnMerged = (118 answer: Admitted,119 lane: LaneName,120 signature: string,121 onMain: "passed" | "failed"122) =>123 Effect.gen(function* () {124 yield* allGreen(answer.merged);125 yield* Checker.use((script) =>126 Effect.andThen(127 script.script(answer.merged, lane, [{ result: "failed", signature }]),128 script.script(129 CheckAt.cases.Commit.make({ commit: answer.opened }),130 lane,131 [{ result: onMain }]132 )133 )134 );135 });136137/** The Checker's jobs on `at`: their lanes, and the repo each ran in. */138const jobsOn = (at: CheckAt) =>139 Checker.use(({ jobs }) =>140 Effect.map(jobs, (all) =>141 all142 .filter((job) => shaOf(job.at) === shaOf(at))143 .map(({ lanes, repo: on }) => ({ lanes, on }))144 )145 );146147/** The lands of `answer` the Lander was asked for. */148const landsOf = (answer: Admitted) =>149 LanderCalls.use(({ jobs }) =>150 Effect.map(jobs, (all) =>151 all.filter(152 (each) =>153 LanderJob.$is("Land")(each) && each.job.requestId === answer.requestId154 )155 )156 );157158/** What each `advanceAnswer` call reported, by tag. */159const reportedTags = DoCalls.use(({ advances }) =>160 Effect.map(advances, (all) => all.map(({ command }) => command._tag))161);162163const parentsOf = (sha: CommitSha) =>164 Effect.gen(function* () {165 const host = yield* RepoHost;166 const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);167168 return Option.getOrThrow(read).parents;169 });170171const landedAt = (sha: LandedSha) => Outcome.cases.Landed.make({ sha });172173/** A clean answer, admitted, its lanes all green on the merged tree. */174const cleanAnswer = Effect.tap(admitted(), (answer) => allGreen(answer.merged));175176/**177 * The world's projects, each answer's run handed on without its landing178 * message: a run that holds the landing slot, but whose land no step can179 * make.180 */181const withoutMessage = Layer.effect(182 Projects,183 Effect.map(Projects, (inner) =>184 Projects.of({185 create: inner.create,186 get: (name) =>187 Effect.map(inner.get(name), (api) => ({188 ...api,189 answer: (requestId) =>190 Effect.map(191 api.answer(requestId),192 Option.map((found) => Struct.omit(found, ["message"]))193 ),194 })),195 })196 )197);198199describe(runAnswer, () => {200 it.effect(201 "1. a clean answer is merged, checked and landed, one named step at a time",202 () =>203 Effect.gen(function* () {204 const answer = yield* cleanAnswer;205 const steps = yield* freshSteps();206 const outcome = yield* run(answer, steps);207 const tip = yield* mainTip;208209 expect(outcome).toStrictEqual(landedAt(tip));210 expect(yield* parentsOf(tip)).toStrictEqual([answer.opened]);211 expect(yield* namesOf(steps)).toStrictEqual(["load", ...pass(1)]);212 expect(yield* landsOf(answer)).toHaveLength(1);213 }).pipe(Effect.provide(world))214 );215216 it.effect(217 "1. the project records each step's report and the landing, through its queue",218 () =>219 Effect.gen(function* () {220 const answer = yield* cleanAnswer;221 const outcome = yield* run(answer, yield* freshSteps());222 const { answers } = yield* answer.api.status(bob);223224 expect(yield* reportedTags).toStrictEqual([225 "Merged",226 "Checked",227 "LandedOk",228 ]);229 expect(answers.map((each) => each.outcome)).toStrictEqual([outcome]);230 expect(231 Option.map(yield* verdictOf(answer.api), (v) => v.tree)232 ).toStrictEqual(Option.some(shaOf(answer.merged)));233 }).pipe(Effect.provide(world))234 );235236 it.effect(237 "1. the checks run on the exact merged tree, in the fork that holds it, the cheap lanes first",238 () =>239 Effect.gen(function* () {240 const answer = yield* cleanAnswer;241242 yield* run(answer, yield* freshSteps());243244 const jobs = yield* Checker.use((script) => script.jobs);245246 expect(247 jobs248 .filter(({ at }) => CheckAt.guards.Tree(at))249 .map(({ at, lanes, repo: on }) => ({250 at,251 lanes: lanes.map(({ lane }) => lane),252 on,253 }))254 ).toStrictEqual([255 { at: answer.merged, lanes: ["lint", "types"], on: bobFork },256 { at: answer.merged, lanes: [askLane, "unit"], on: bobFork },257 ]);258 }).pipe(Effect.provide(world))259 );260261 it.effect(262 "2. the whole program run twice over one step record lands once, with one outcome",263 () =>264 Effect.gen(function* () {265 const answer = yield* cleanAnswer;266 const steps = yield* freshSteps();267 const first = yield* run(answer, steps);268 const second = yield* run(answer, steps);269270 expect(second).toStrictEqual(first);271 expect(yield* landsOf(answer)).toHaveLength(1);272 expect(yield* reportedTags).toStrictEqual([273 "Merged",274 "Checked",275 "LandedOk",276 ]);277 }).pipe(Effect.provide(world))278 );279280 it.effect(281 "2. every step's effect run twice still lands once, with the same outcome",282 () =>283 Effect.gen(function* () {284 const answer = yield* cleanAnswer;285 const outcome = yield* run(answer, yield* freshSteps({ twice: true }));286 const tip = yield* mainTip;287 const events = yield* answer.api.events(0, 1000);288289 expect(outcome).toStrictEqual(landedAt(tip));290 expect(yield* parentsOf(tip)).toStrictEqual([answer.opened]);291 expect(292 events.filter(293 ({ event }) =>294 ProjectEvent.guards.Landed(event) &&295 event.landing.requestId === answer.requestId296 )297 ).toHaveLength(1);298 }).pipe(Effect.provide(world))299 );300301 it.effect(302 "3. a lane red on the merged tree and green on main, in a file the answer changed, is the answer's failure",303 () =>304 Effect.gen(function* () {305 const answer = yield* admitted();306307 yield* failsOnMerged(308 answer,309 unit,310 `parses ISO weeks: AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,311 "passed"312 );313314 const steps = yield* freshSteps();315 const outcome = yield* run(answer, steps);316317 expect(outcome).toStrictEqual(318 Outcome.cases.Refused.make({319 refusals: [320 new ChecksFailed({321 lane: unit,322 logRef: `${project}/${answer.requestId}/unit#1`,323 next: "bun run test",324 }),325 ],326 })327 );328 expect(yield* namesOf(steps)).toContain(`main:${answer.opened}:unit`);329 expect(330 yield* jobsOn(CheckAt.cases.Commit.make({ commit: answer.opened }))331 ).toStrictEqual([332 { lanes: [{ command: "bun run test", lane: unit }], on: repo },333 ]);334 expect(yield* landsOf(answer)).toHaveLength(0);335 }).pipe(Effect.provide(world))336 );337338 it.effect(339 "3. a lane red on the merged tree and on main is the verifier's trouble",340 () =>341 Effect.gen(function* () {342 const answer = yield* admitted();343344 yield* failsOnMerged(answer, unit, "AssertionError: red", "failed");345346 expect(yield* run(answer, yield* freshSteps())).toStrictEqual(347 Outcome.cases.Refused.make({ refusals: [new VerifierBlocked({})] })348 );349 }).pipe(Effect.provide(world))350 );351352 it.effect(353 "3. a lane red only in a file outside the answer's diff, and green on main, means a stale base",354 () =>355 Effect.gen(function* () {356 const answer = yield* admitted();357358 yield* failsOnMerged(359 answer,360 unit,361 `lexes words: AssertionError: expected 2 to be 3 at ${lexPath}:1:30`,362 "passed"363 );364365 expect(yield* run(answer, yield* freshSteps())).toStrictEqual(366 Outcome.cases.Refused.make({367 refusals: [368 new StaleBase({369 base: answer.opened,370 conflicts: [],371 main: answer.opened,372 }),373 ],374 })375 );376 }).pipe(Effect.provide(world))377 );378379 it.effect(380 "3. a lane that never got going runs once more on the merged tree, and green then is a flake",381 () =>382 Effect.gen(function* () {383 const answer = yield* admitted();384385 yield* allGreen(answer.merged);386 yield* Checker.use((script) =>387 script.script(answer.merged, unit, [388 { result: "flaked" },389 { result: "passed" },390 ])391 );392393 expect(yield* run(answer, yield* freshSteps())).toStrictEqual(394 Outcome.cases.Refused.make({ refusals: [new Flake({ lane: unit })] })395 );396 expect(397 (yield* jobsOn(answer.merged)).map(({ lanes, on }) => ({398 lanes: lanes.map(({ lane }) => lane),399 on,400 }))401 ).toStrictEqual([402 { lanes: [lint, "types"], on: bobFork },403 { lanes: [askLane, unit], on: bobFork },404 { lanes: [unit], on: bobFork },405 ]);406 }).pipe(Effect.provide(world))407 );408409 it.effect(410 "3. a lane that never got going and then fails on its fresh run is the answer's failure",411 () =>412 Effect.gen(function* () {413 const answer = yield* admitted();414415 yield* failsOnMerged(answer, unit, "AssertionError: red", "passed");416 yield* Checker.use((script) =>417 script.script(answer.merged, unit, [418 { result: "blocked" },419 {420 result: "failed",421 signature: `AssertionError: expected {} to equal { year: 2026 } at ${parsePath}:1:22`,422 },423 ])424 );425426 expect(yield* run(answer, yield* freshSteps())).toStrictEqual(427 Outcome.cases.Refused.make({428 refusals: [429 new ChecksFailed({430 lane: unit,431 logRef: `${project}/${answer.requestId}/unit#1`,432 next: "bun run test",433 }),434 ],435 })436 );437 }).pipe(Effect.provide(world))438 );439440 it.effect("3. a red cheap lane refuses before the costlier checks run", () =>441 Effect.gen(function* () {442 const answer = yield* admitted();443444 yield* failsOnMerged(answer, lint, "lint: no-unused-vars", "passed");445446 const steps = yield* freshSteps();447448 expect(yield* run(answer, steps)).toStrictEqual(449 Outcome.cases.Refused.make({450 refusals: [451 new ChecksFailed({452 lane: lint,453 logRef: `${project}/${answer.requestId}/lint#1`,454 next: "bun run lint",455 }),456 ],457 })458 );459 expect(yield* namesOf(steps)).not.toContain("checks#1");460 }).pipe(Effect.provide(world))461 );462463 it.effect(464 "4. a land that finds main moved is merged again, checked again on the new tree, and lands",465 () =>466 Effect.gen(function* () {467 const answer = yield* cleanAnswer;468469 const moved = yield* mainMoved(470 answer.opened,471 changed(472 openedFiles,473 lexPath,474 "export const lex = (s) => s.split(/ +/);\n"475 )476 );477478 const remerged = yield* LanderCalls.use(({ preview }) =>479 preview({480 base: answer.opened,481 fork: bobFork,482 head: answer.head,483 main: moved,484 repo,485 })486 );487488 yield* allGreen(remerged);489490 const steps = yield* freshSteps();491 const outcome = yield* run(answer, steps);492 const tip = yield* mainTip;493494 expect(outcome).toStrictEqual(landedAt(tip));495 expect(yield* parentsOf(tip)).toStrictEqual([moved]);496 expect(yield* namesOf(steps)).toStrictEqual([497 "load",498 ...pass(1),499 ...pass(2),500 ]);501 expect(502 Option.map(yield* verdictOf(answer.api), ({ tree }) => tree)503 ).toStrictEqual(Option.some(shaOf(remerged)));504 }).pipe(Effect.provide(world))505 );506507 it.effect(508 "4. a land that finds main moved, whose re-merge conflicts, is refused as stale",509 () =>510 Effect.gen(function* () {511 const answer = yield* cleanAnswer;512513 const moved = yield* mainMoved(514 answer.opened,515 changed(openedFiles, parsePath, "export const parse = (s) => null;\n")516 );517518 expect(yield* run(answer, yield* freshSteps())).toStrictEqual(519 Outcome.cases.Refused.make({520 refusals: [521 new StaleBase({522 base: answer.opened,523 conflicts: [parsePath],524 main: moved,525 }),526 ],527 })528 );529 expect(yield* mainTip).toBe(moved);530 }).pipe(Effect.provide(world))531 );532533 it.effect(534 "5. a busy repo is retried by the land step's own retries, not refused",535 () =>536 Effect.gen(function* () {537 const answer = yield* cleanAnswer;538539 yield* LanderCalls.use(({ busyFor }) => busyFor(1));540541 const steps = yield* freshSteps();542 const outcome = yield* run(answer, steps);543544 const retries = yield* StepLog.use((log) => log.retries).pipe(545 Effect.provide(steps)546 );547548 expect(outcome).toStrictEqual(landedAt(yield* mainTip));549 expect(yield* landsOf(answer)).toHaveLength(2);550 expect(yield* reportedTags).toStrictEqual([551 "Merged",552 "Checked",553 "LandedOk",554 ]);555 expect(Option.fromUndefinedOr(retries.get("land#1"))).toStrictEqual(556 Option.some({ backoff: "exponential", delayMs: 1000, limit: 3 })557 );558 }).pipe(Effect.provide(world))559 );560561 it.effect(562 "5. a repo still busy once the retries are spent waits on the project's own retry",563 () =>564 Effect.gen(function* () {565 const answer = yield* cleanAnswer;566567 yield* LanderCalls.use(({ busyFor }) => busyFor(100));568569 expect(yield* run(answer, yield* freshSteps())).toStrictEqual(570 Outcome.cases.Checking.make({ stage: "human" })571 );572 expect(yield* reportedTags).toStrictEqual([573 "Merged",574 "Checked",575 "Busy",576 ]);577 expect(yield* mainTip).toBe(answer.opened);578 }).pipe(Effect.provide(world))579 );580581 it.effect(582 "a land step that finds nothing to do ends the run there, as the in-process run does",583 () =>584 Effect.gen(function* () {585 const answer = yield* cleanAnswer;586 const steps = yield* freshSteps();587588 const exit = yield* Effect.exit(589 run(answer, steps).pipe(Effect.provide(withoutMessage))590 );591592 expect(Exit.getSuccess(exit)).toStrictEqual(593 Option.some(Outcome.cases.Checking.make({ stage: "human" }))594 );595 expect(yield* namesOf(steps)).toStrictEqual(["load", ...pass(1)]);596 expect(yield* landsOf(answer)).toHaveLength(0);597 }).pipe(Effect.provide(world))598 );599600 it.effect(601 "an answer a decider must finish stops once checked, and lands nothing",602 () =>603 Effect.gen(function* () {604 const answer = yield* cleanAnswer;605 const steps = yield* freshSteps();606607 expect(yield* run(answer, steps)).toStrictEqual(608 Outcome.cases.AwaitingFinish.make({})609 );610 expect(yield* namesOf(steps)).toStrictEqual([611 "load",612 "merge#1",613 "record:merge#1",614 "cheap#1",615 "checks#1",616 "record:checks#1",617 ]);618 expect(yield* landsOf(answer)).toHaveLength(0);619 }).pipe(Effect.provide(worldWith(finishRequired)))620 );621622 it.effect(623 "a decider's finish starts the answer's run again, and a fresh run lands it, finished",624 () =>625 Effect.gen(function* () {626 const answer = yield* cleanAnswer;627628 yield* run(answer, yield* freshSteps());629630 yield* answer.api.finish(alice, {631 ask: parseIso,632 base: answer.opened,633 head: answer.head,634 requestId: RequestId.make(`finish-${answer.head}`),635 });636637 const outcome = yield* run(answer, yield* freshSteps());638 const tip = yield* mainTip;639 const events = yield* answer.api.events(0, 1000);640641 expect(yield* Started.use(({ ids }) => ids)).toStrictEqual([642 answer.requestId,643 answer.requestId,644 ]);645 expect(outcome).toStrictEqual(landedAt(tip));646 expect(647 events.flatMap(({ event: each }) =>648 ProjectEvent.guards.Landed(each)649 ? each.landing.credits.filter(650 ({ role }) => role === "Finished-by"651 )652 : []653 )654 ).toStrictEqual([{ handle: alice.handle, role: "Finished-by" }]);655 }).pipe(Effect.provide(worldWith(finishRequired)))656 );657658 it.effect(659 "6. a failing lane's log is kept once, and the verdict names it",660 () =>661 Effect.gen(function* () {662 const answer = yield* admitted();663 const said = "AssertionError: expected {} to equal { year: 2026 }";664665 yield* failsOnMerged(666 answer,667 unit,668 `parses ISO weeks: ${said}`,669 "passed"670 );671672 const outcome = yield* run(answer, yield* freshSteps());673 const puts = yield* EvidenceKept.use((kept) => kept.puts);674 const verdict = yield* verdictOf(answer.api);675676 const ref = logRefOf({677 attempt: 1,678 lane: unit,679 project,680 requestId: answer.requestId,681 });682683 expect(684 puts.map((log) => ({685 ref: logRefOf(log),686 told: log.text.includes(said),687 }))688 ).toStrictEqual([{ ref, told: true }]);689 expect(outcome).toStrictEqual(690 Outcome.cases.Refused.make({691 refusals: [692 new ChecksFailed({693 lane: unit,694 logRef: ref,695 next: "bun run test",696 }),697 ],698 })699 );700 expect(701 Option.map(verdict, ({ lanes, outcome: judged }) => ({702 judged,703 refs: lanes.map(({ logRef }) => logRef),704 }))705 ).toStrictEqual(706 Option.some({707 judged: outcome,708 refs: [undefined, undefined, undefined, ref],709 })710 );711 }).pipe(Effect.provide(world))712 );713714 it.effect(715 "6. a lane's log travels nowhere: not in the outcome, the verdict or the calls to the project",716 () =>717 Effect.gen(function* () {718 const answer = yield* admitted();719 const said = "AssertionError: expected {} to equal { year: 2026 }";720721 yield* failsOnMerged(722 answer,723 unit,724 `parses ISO weeks: ${said}`,725 "passed"726 );727728 const outcome = yield* run(answer, yield* freshSteps());729 const verdict = Option.getOrThrow(yield* verdictOf(answer.api));730 const advances = yield* DoCalls.use((calls) => calls.advances);731732 const travelled = JSON.stringify([733 yield* Schema.encodeEffect(OutcomeJson)(outcome),734 yield* Schema.encodeEffect(Schema.toCodecJson(Verdict))(verdict),735 yield* Effect.forEach(advances, (each) =>736 Schema.encodeEffect(Advance)(each)737 ),738 ]);739740 expect(travelled).not.toContain(said);741 expect(travelled).toContain(742 logRefOf({743 attempt: 1,744 lane: unit,745 project,746 requestId: answer.requestId,747 })748 );749 }).pipe(Effect.provide(world))750 );751752 it.effect("6. a check step run twice keeps its log under the same name", () =>753 Effect.gen(function* () {754 const answer = yield* admitted();755756 yield* failsOnMerged(answer, unit, "AssertionError: red", "passed");757 yield* run(answer, yield* freshSteps({ twice: true }));758759 const puts = yield* EvidenceKept.use((kept) => kept.puts);760761 expect(puts.length).toBeGreaterThan(1);762 expect(new Set(puts.map(logRefOf))).toStrictEqual(763 new Set([764 logRefOf({765 attempt: 1,766 lane: unit,767 project,768 requestId: answer.requestId,769 }),770 ])771 );772 }).pipe(Effect.provide(world))773 );774775 it.effect(776 "the in-process run reaches the same outcome as the Workflow's program",777 () =>778 Effect.gen(function* () {779 const viaProgram = yield* Effect.flatMap(cleanAnswer, (answer) =>780 Effect.flatMap(freshSteps(), (steps) => run(answer, steps))781 ).pipe(Effect.provide(world));782783 const inProcess = yield* Effect.gen(function* () {784 const answer = yield* cleanAnswer;785786 yield* drive(answer.api, answer.requestId);787788 return (yield* answer.api.status(bob)).answers.map(789 ({ outcome }) => outcome790 );791 }).pipe(Effect.provide(world));792793 expect(inProcess).toStrictEqual([viaProgram]);794 })795 );796});797798describe(failingPathsOf, () => {799 it("names the repo files a failure points at, tests and absolute paths left out", () => {800 expect(801 failingPathsOf(802 [803 `lexes words: AssertionError: expected 2 to be 3 at ${lexPath}:1:30`,804 ` at packages/parser/test/parse-iso.test.ts:5:7`,805 " at /home/ci/node_modules/vitest/dist/index.js:10:3",806 ` at (${parsePath}:3)`,807 ` at ${lexPath}:2:1`,808 ].join("\n")809 )810 ).toStrictEqual([lexPath, parsePath]);811 });812813 it("reads no network address as a file", () => {814 expect(815 failingPathsOf(816 "serves: AssertionError: expected 'listening on 127.0.0.1:8080' to be 'up'"817 )818 ).toStrictEqual([]);819 });820});821822/**823 * A Workflow engine in memory, as `step.test.ts` fakes one: a step's first824 * run records what its body returns under its name, and a replay returns825 * the record without running the body. It keeps the name of every step826 * whose body ran.827 */828const fakeEngine = () => {829 const recorded = new Map<string, Promise<Schema.Json>>();830 const ran: string[] = [];831832 const steps: WorkflowSteps = {833 do: (name, _config, body) => {834 const kept = recorded.get(name);835836 if (kept !== undefined) {837 return kept;838 }839840 ran.push(name);841842 const running = body();843844 recorded.set(name, running);845846 return running;847 },848 };849850 /** What the engine recorded for `name`; `null` if no step of that name ran. */851 const record = (name: string) =>852 Effect.promise(() => recorded.get(name) ?? Promise.resolve(null));853854 return { ran, record, steps };855};856857/** Whether a value is plain JSON: no class instance, no `undefined`, no cycle. */858const isJson = Schema.is(Schema.Json);859860/** The engine's event for one run of the Workflow. */861const event = (payload: typeof AnswerParams.Encoded) => ({862 instanceId: payload.requestId,863 payload,864 timestamp: DateTime.toDateUtc(DateTime.makeUnsafe("2026-10-07T12:00:00Z")),865 workflowName: "answer-local",866});867868/** The world's ports, as the Workflow's run takes them. */869const portsOfWorld = Effect.map(870 Effect.context<CheckRunner | EvidenceStore | Lander | Projects>(),871 Layer.succeedContext872);873874describe(runWorkflow, () => {875 it.effect(876 "hands the engine each step's value as JSON, and returns the outcome as JSON",877 () =>878 Effect.gen(function* () {879 const answer = yield* cleanAnswer;880 const engine = fakeEngine();881 const ports = yield* portsOfWorld;882 const payload = { project, requestId: answer.requestId };883884 const outcome = yield* Effect.promise(() =>885 runWorkflow(ports, payload, engine.steps)886 );887888 const tip = yield* mainTip;889890 const recorded = yield* engine.record("record:land#1");891892 expect(engine.ran).toStrictEqual(["load", ...pass(1)]);893 expect(isJson(outcome)).toBeTruthy();894 expect(yield* Schema.decodeEffect(OutcomeJson)(outcome)).toStrictEqual(895 landedAt(tip)896 );897 expect(isJson(recorded)).toBeTruthy();898 expect(899 yield* Schema.decodeUnknownEffect(Schema.toCodecJson(Steps))(recorded)900 ).toStrictEqual({ effects: [], outcome: landedAt(tip) });901 }).pipe(Effect.provide(world))902 );903904 it.effect(905 "replays a run from the engine's records: nothing runs again, and the outcome is the same",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 first = yield* Effect.promise(() =>914 runWorkflow(ports, payload, engine.steps)915 );916917 const ranOnce = [...engine.ran];918919 const second = yield* Effect.promise(() =>920 runWorkflow(ports, payload, engine.steps)921 );922923 expect(second).toStrictEqual(first);924 expect(engine.ran).toStrictEqual(ranOnce);925 expect(yield* landsOf(answer)).toHaveLength(1);926 }).pipe(Effect.provide(world))927 );928});929930describe(Answer, () => {931 it.effect("refuses params that don't decode before any step runs", () =>932 Effect.gen(function* () {933 const engine = fakeEngine();934 const workflow = new Answer(untouchable("ctx"), fakeEnv());935936 const exit = yield* Effect.exit(937 Effect.tryPromise(() =>938 workflow.run(939 event({ project: "Not A Project", requestId: "push-0001" }),940 engine.steps941 )942 )943 );944945 expect(Exit.isFailure(exit)).toBeTruthy();946 expect(engine.ran).toStrictEqual([]);947 })948 );949950 it.effect(951 "runs its first step over the engine's, on the ports its env builds",952 () =>953 Effect.gen(function* () {954 const engine = fakeEngine();955 const workflow = new Answer(untouchable("ctx"), fakeEnv());956957 // Until W3 317 wires the ports, the first port call dies `NotWired`.958 const exit = yield* Effect.exit(959 Effect.tryPromise(() =>960 workflow.run(961 event({ project, requestId: "push-0001" }),962 engine.steps963 )964 )965 );966967 expect(Exit.isFailure(exit)).toBeTruthy();968 expect(engine.ran).toStrictEqual(["load"]);969 })970 );971});