program.ts
This file
Path
apps/platform/src/workflows/answer/program.ts
659 lines · 17.8 KiB · TypeScript
Last changed by
Merge observability into mainoscabrielbefore adoption1985111
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 1–3why, one step back1// Step names carry their attempt (`merge#2`), so a merge onto a main that moved is a2// new step, not a replay. The run stops when a port step finds nothing to do, or it3// could ask for the same call forever.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 4–23why, one step back4import { HostBusy } from "@repo/artifacts/repo-host";5import type { RepoHost } from "@repo/artifacts/repo-host";6import type { CheckRunner } from "@repo/checks/check-runner";7import type { EvidenceStore } from "@repo/checks/evidence-store";8import {9 AnswerReport,10 AnswerRun,11 NextStep,12 ReportedCommand,13 Steps,14} from "@repo/project/answer-runs";15import { nextSteps, runStep } from "@repo/project/answer-runs/steps";16import type { Lander } from "@repo/project/lander";17import {18 LandingCommand,19 LandingEffect,20 outcomeOf,21} from "@repo/project/landing";22import { Projects } from "@repo/project/projects";23import { LaneOutcome, Verdict } from "@repo/protocol/domain/answer";Merge observability into mainoscabrielbefore adoption1985111
line 24why, one step back24import type { Outcome, StageName } from "@repo/protocol/domain/outcome";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 25–32why, one step back25import { CommitSha } from "@repo/protocol/ids";26import type {27 EnvKey,28 LaneName,29 ProjectName,30 RequestId,31} from "@repo/protocol/ids";32import { VerifierBlocked } from "@repo/protocol/refusal";Merge observability into mainoscabrielbefore adoption1985111
line 33why, one step back33import type { Refusal } from "@repo/protocol/refusal";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 34–153why, one step back34import {35 Array,36 Cause,37 Data,38 Effect,39 Match,40 Option,41 Schedule,42 Schema,43 Struct,44} from "effect";4546import type { AnswerParams } from "../../answer-runs.ts";47import { writeVerdictNote } from "../notes.ts";48import { StepRunner } from "../step.ts";49import type { StepRetry } from "../step.ts";50import { guards, GuardRun, passes } from "./guards.ts";51import { heldBack, HeldBackRun, unsealed } from "./held-back.ts";52import type { Judged } from "./held-back.ts";53import {54 laneOnMain,55 refusalsOf,56 runStage,57 StageRun,58 toCompareOnMain,59} from "./lanes.ts";60import type { Stage } from "./lanes.ts";6162export type AnswerPorts =63 | CheckRunner64 | EvidenceStore65 | Lander66 | Projects67 | RepoHost68 | StepRunner;6970export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{71 readonly project: ProjectName;72 readonly requestId: RequestId;73}> {}7475class LandBusy extends Data.TaggedError("LandBusy")<{76 readonly attempt: number;77}> {}7879export const landRetry: StepRetry = {80 backoff: "exponential",81 delayMs: 1000,82 limit: 3,83};8485export const Reported = Schema.Struct({86 command: ReportedCommand,87 report: Schema.optionalKey(AnswerReport),88});8990export type Reported = typeof Reported.Type;9192const Reporting = Schema.Option(Reported);9394type NextStep = typeof NextStep.Type;9596type Steps = typeof Steps.Type;9798type Call<Tag extends NextStep["_tag"]> = Extract<99 NextStep,100 { readonly _tag: Tag }101>;102103interface Attempts {104 readonly Land: number;105 readonly Merge: number;106 readonly RunChecks: number;107}108109const reported = (110 command: LandingCommand,111 report?: AnswerReport112): Option.Option<Reported> =>113 Option.some(report === undefined ? { command } : { command, report });114115const callsOf = (effects: readonly LandingEffect[]): readonly NextStep[] =>116 effects.flatMap((effect) =>117 LandingEffect.$match(effect, {118 Emit: (): readonly NextStep[] => [],119 Land: ({ main, tree }) => [NextStep.cases.Land.make({ main, tree })],120 Merge: ({ base, fork, head, main }) => [121 NextStep.cases.Merge.make({ base, fork, head, main }),122 ],123 Record: () => [],124 Retry: ({ at }) => [NextStep.cases.Retry.make({ at })],125 RunChecks: ({ tree }) => [NextStep.cases.RunChecks.make({ tree })],126 })127 );128129const keyOf = (call: NextStep): string =>130 NextStep.match(call, {131 Land: ({ main, tree }) => `land ${main} ${tree}`,132 Merge: ({ head, main }) => `merge ${head} onto ${main}`,133 Retry: () => "retry",134 RunChecks: ({ tree }) => `checks ${tree}`,135 });136137const waitsOn = (run: AnswerRun, call: NextStep) =>138 callsOf(nextSteps(run)).some((each) => keyOf(each) === keyOf(call));139140const projectOf = (project: ProjectName) =>141 Projects.use((projects) => projects.get(project)).pipe(Effect.orDie);142143const load = ({ project, requestId }: AnswerParams) =>144 Effect.flatMap(projectOf(project), (api) => api.answer(requestId));145146const portCall = (147 params: AnswerParams,148 call: Call<"Land" | "Merge">,149 effect: LandingEffect,150 prepare: (run: AnswerRun) => Effect.Effect<AnswerRun, never, Projects> = (151 run152 ) => Effect.succeed(run)153) =>Merge refusal/stale-base-movers into mainoscabrielbefore adoptiona23e097
lines 154–165why, one step back154 Effect.gen(function* () {155 const api = yield* projectOf(params.project);156 const run = yield* api.answer(params.requestId);157158 if (Option.isNone(run) || !waitsOn(run.value, call)) {159 return Option.none();160 }161162 const ready = yield* prepare(run.value);163164 return yield* runStep(ready, effect, api.landings);165 });Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 166–279why, one step back166167const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));168169const leakIn = (params: AnswerParams, verdict: Verdict, where: string) =>170 Effect.gen(function* () {171 const text = yield* Effect.orDie(encodeVerdict(verdict));172 const api = yield* projectOf(params.project);173 const found = yield* api.scanForValues({ text });174175 if (Option.isSome(found)) {176 yield* Effect.logWarning(177 "an answer's verdict note held a stored write-only value; it was not written"178 ).pipe(179 Effect.annotateLogs({180 item: found.value,181 project: params.project,182 requestId: params.requestId,183 where,184 })185 );186 }187188 return found;189 });190191const withSafeNote = (params: AnswerParams) => (run: AnswerRun) =>192 run.verdict === undefined193 ? Effect.succeed(run)194 : Effect.map(leakIn(params, run.verdict, "canonical"), (leaked) =>195 Option.isSome(leaked) ? Struct.omit(run, ["verdict"]) : run196 );197198const merge = (params: AnswerParams, call: Call<"Merge">) =>199 portCall(200 params,201 call,202 LandingEffect.Merge({203 base: call.base,204 fork: call.fork,205 head: call.head,206 main: call.main,207 })208 );209210const land = (params: AnswerParams, call: Call<"Land">) =>211 Effect.flatMap(212 portCall(213 params,214 call,215 LandingEffect.Land({ main: call.main, tree: call.tree }),216 withSafeNote(params)217 ),218 (given) =>219 Option.isSome(given) && LandingCommand.$is("Busy")(given.value.command)220 ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))221 : Effect.succeed(given)222 );223224const stage = (225 params: AnswerParams,226 tree: Call<"RunChecks">["tree"],227 name: Stage,228 attempt: number229) =>230 Effect.gen(function* () {231 const { step } = yield* StepRunner;232233 const ran = yield* step(234 `${name}#${attempt}`,235 StageRun,236 Effect.flatMap(load(params), (run) =>237 Option.match(run, {238 onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),239 onSome: (found) => runStage(found, tree, name),240 })241 )242 );243244 if (!StageRun.guards.Ran(ran)) {245 return { ran, refusals: [] };246 }247248 const onMain = yield* Effect.forEach(toCompareOnMain(ran), (lane) =>249 Effect.map(250 step(251 `main:${ran.checked.main}:${lane.lane}`,252 LaneOutcome,253 laneOnMain(ran.checked, lane)254 ),255 (outcome) => [lane.lane, outcome] as const256 )257 );258259 return {260 ran,261 refusals: refusalsOf(ran, new Map<LaneName, LaneOutcome>(onMain)),262 };263 });264265const uncountedRefusals = (cheap: StageRun) =>266 StageRun.guards.Ran(cheap) && cheap.uncounted !== undefined267 ? Effect.as(268 Effect.logWarning(269 `the ratchet ${cheap.uncounted} printed no count on ${cheap.checked.tree}`270 ),271 [new VerifierBlocked({})]272 )273 : Effect.succeed([]);274275interface Ran {276 readonly given: Option.Option<Reported>;277 readonly judged: Option.Option<Judged>;278}279Merge observability into mainoscabrielbefore adoption1985111
lines 280–296why, one step back280/** The checks stage runs only when the cheap one refused nothing, and the held-back one only when neither did. */281const refusingStage = (input: {282 readonly checked: boolean;283 readonly held: readonly Refusal[];284 readonly last: readonly Refusal[];285}): Option.Option<StageName> => {286 if (input.held.length > 0) {287 return Option.some("heldBack");288 }289290 if (input.last.length > 0) {291 return Option.some(input.checked ? "checks" : "cheap");292 }293294 return Option.none();295};296Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 297–301why, one step back297const ranOnly = (given: Option.Option<Reported>): Ran => ({298 given,299 judged: Option.none(),300});301Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 302–303why, one step back302// `VerifierBlocked` names nothing, so the scan is no oracle on which item a guess303// matched; only the platform's log names the items, never a value.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 304–336why, one step back304const quarantine = (305 params: AnswerParams,306 items: readonly EnvKey[]307): Effect.Effect<readonly VerifierBlocked[]> =>308 Array.isReadonlyArrayEmpty(items)309 ? Effect.succeed([])310 : Effect.as(311 Effect.logWarning(312 "an answer adds a file holding a stored write-only value"313 ).pipe(314 Effect.annotateLogs({315 items: items.join(","),316 project: params.project,317 requestId: params.requestId,318 })319 ),320 [new VerifierBlocked({})]321 );322323const guardedOut = (324 params: AnswerParams,325 call: Call<"RunChecks">,326 run: Extract<GuardRun, { readonly _tag: "Guarded" }>327) =>328 Effect.map(quarantine(params, run.quarantined), (quarantined): Ran =>329 ranOnly(330 reported(331 LandingCommand.Checked({332 decisions: [],333 finish: run.finish,334 refusals: [...run.refusals, ...quarantined],335 tree: call.tree,336 }),Merge observability into mainoscabrielbefore adoption1985111
lines 337–338why, one step back337 // The landing guards hold the shape of the tree, as stage 1 does a push's.338 { heldBack: [], lanes: [], stage: "shape" }Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 339–398why, one step back339 )340 )341 );342343const checks = (344 params: AnswerParams,345 call: Call<"RunChecks">,346 attempt: number,347 earlier: Option.Option<Judged>348): Effect.Effect<Ran, never, AnswerPorts> =>349 Effect.gen(function* () {350 const guarded = yield* guards(params, call.tree, attempt);351352 if (Option.isSome(guarded) && !passes(guarded.value)) {353 return yield* GuardRun.match(guarded.value, {354 Blocked: ({ attempt: at }) =>355 Effect.succeed(356 ranOnly(reported(LandingCommand.Blocked({ attempt: at })))357 ),358 Guarded: (run) => guardedOut(params, call, run),359 Moved: () => Effect.succeed(ranOnly(Option.none())),360 });361 }362363 const ran = yield* stage(params, call.tree, "cheap", attempt);364365 const cheap = {366 ...ran,367 refusals: [...ran.refusals, ...(yield* uncountedRefusals(ran.ran))],368 };369370 const judged =371 StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0372 ? yield* stage(params, call.tree, "checks", attempt)373 : undefined;374375 const last = judged ?? cheap;376377 const sealed =378 judged !== undefined &&379 StageRun.guards.Ran(judged.ran) &&380 judged.refusals.length === 0 &&381 judged.ran.checked.sealed === true382 ? yield* heldBack(params, call.tree, attempt, earlier)383 : unsealed;384385 const counts = StageRun.guards.Ran(cheap.ran)386 ? Option.fromUndefinedOr(cheap.ran.counts)387 : Option.none();388389 if (HeldBackRun.guards.Blocked(sealed)) {390 return ranOnly(391 reported(LandingCommand.Blocked({ attempt: sealed.attempt }))392 );393 }394395 const held = HeldBackRun.guards.Judged(sealed)396 ? Option.some(sealed)397 : Option.none();398Merge observability into mainoscabrielbefore adoption1985111
lines 399–407why, one step back399 const refusedAt = refusingStage({400 checked: judged !== undefined,401 held: Option.match(held, {402 onNone: () => [],403 onSome: ({ refusals }) => refusals,404 }),405 last: last.refusals,406 });407Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 408–439why, one step back408 const given = StageRun.match(last.ran, {409 Blocked: ({ attempt: at }) =>410 reported(LandingCommand.Blocked({ attempt: at })),411 Moved: () => Option.none(),412 Ran: ({ checked, lanes }) =>413 reported(414 LandingCommand.Checked({415 decisions: [],416 finish: checked.finish,417 refusals: [418 ...last.refusals,419 ...Option.match(held, {420 onNone: () => [],421 onSome: ({ refusals }) => refusals,422 }),423 ],424 tree: call.tree,425 }),426 {427 heldBack: Option.match(held, {428 onNone: () => [],429 onSome: ({ results }) => results,430 }),431 lanes: [432 ...(judged !== undefined && StageRun.guards.Ran(cheap.ran)433 ? cheap.ran.lanes434 : []),435 ...lanes,436 ].map(({ result }) => result),437 ...Option.match(counts, {438 onNone: () => ({}),439 onSome: (ratchets) => ({ ratchets }),Merge observability into mainoscabrielbefore adoption1985111
lines 440–443why, one step back440 }),441 ...Option.match(refusedAt, {442 onNone: () => ({}),443 onSome: (refusing) => ({ stage: refusing }),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 444–516why, one step back444 }),445 }446 ),447 });448449 return { given, judged: held };450 });451452const record = (params: AnswerParams, given: Option.Option<Reported>) =>453 Effect.gen(function* () {454 const api = yield* projectOf(params.project);455456 if (Option.isSome(given)) {457 const advanced = yield* api.advanceAnswer(458 params.requestId,459 given.value.command,460 given.value.report461 );462463 const calls = callsOf(advanced.effects);464465 if (Array.isReadonlyArrayNonEmpty(calls)) {466 return { effects: calls, outcome: advanced.outcome } satisfies Steps;467 }468 }469470 const run = yield* api.answer(params.requestId);471472 if (Option.isNone(run)) {473 return yield* Effect.die(new UnknownRequest(params));474 }475476 return {477 effects: callsOf(nextSteps(run.value)),478 outcome: outcomeOf(run.value.state),479 } satisfies Steps;480 });481482const Noted = Schema.TaggedUnion({483 Unjudged: {},484 Unwritten: { reason: Schema.String },485 Written: { changed: Schema.Boolean, notesTip: CommitSha },486});487488const noteRetry = {489 schedule: Schedule.exponential("250 millis"),490 times: 2,491 while: Schema.is(HostBusy),492};493494const shownVerdict = (run: AnswerRun) =>495 Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({496 ...made,497 outcome: outcomeOf(run.state),498 }));499500const noteVerdict = (params: AnswerParams) =>501 Effect.gen(function* () {502 const run = yield* load(params);503504 const judged = Option.flatMap(run, (found) =>505 Option.map(shownVerdict(found), (verdict) => ({506 fork: found.state.request.fork,507 verdict,508 }))509 );510511 if (Option.isNone(judged)) {512 return Noted.cases.Unjudged.make({});513 }514515 const { fork, verdict } = judged.value;516Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 517why, one step back517 // A note that holds a stored value is not written; the verdict stands in the project.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 518–529why, one step back518 if (Option.isSome(yield* leakIn(params, verdict, "fork"))) {519 return Noted.cases.Unwritten.make({ reason: "SecretInOutput" });520 }521522 const written = yield* writeVerdictNote({523 fork,524 head: verdict.head,525 verdict,526 }).pipe(Effect.retry(noteRetry));527528 return Noted.cases.Written.make(written);529 }).pipe(Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 530–531why, one step back530 // Anything but an interruption is recorded: the note is bookkeeping, and a fork its531 // answerer filled with refs of their own may break it.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 532–659why, one step back532 Effect.catchCause((cause) =>533 Cause.hasInterruptsOnly(cause)534 ? Effect.interrupt535 : Effect.as(536 Effect.logWarning(537 "an answer's verdict note was not written",538 cause539 ),540 Noted.cases.Unwritten.make({541 reason: Option.match(Cause.findErrorOption(cause), {542 onNone: () => "defect",543 onSome: ({ _tag }) => _tag,544 }),545 })546 )547 )548 );549550const notes = (551 params: AnswerParams,552 outcome: Outcome553): Effect.Effect<void, never, AnswerPorts> =>554 Effect.flatMap(StepRunner, ({ step }) =>555 Effect.asVoid(step(`notes:${outcome._tag}`, Noted, noteVerdict(params)))556 );557558const portStep = (559 params: AnswerParams,560 call: Call<"Land" | "Merge" | "RunChecks">,561 attempt: number,562 earlier: Option.Option<Judged>563): Effect.Effect<Ran, never, AnswerPorts> =>564 Effect.flatMap(StepRunner, ({ step }) =>565 Match.valueTags(call, {566 Land: (landing) =>567 step(568 `land#${attempt}`,569 Reporting,570 land(params, landing),571 landRetry572 ).pipe(573 Effect.catchTag("LandBusy", ({ attempt: at }) =>574 Effect.succeed(reported(LandingCommand.Busy({ attempt: at })))575 ),576 Effect.map(ranOnly)577 ),578 Merge: (merging) =>579 Effect.map(580 step(`merge#${attempt}`, Reporting, merge(params, merging)),581 ranOnly582 ),583 RunChecks: (checking) => checks(params, checking, attempt, earlier),584 })585 );586587const nameOf = {588 Land: "land",589 Merge: "merge",590 RunChecks: "checks",591} as const satisfies Record<keyof Attempts, string>;592593const carry = (594 params: AnswerParams,595 at: Steps,596 attempts: Attempts,597 earlier: Option.Option<Judged>598): Effect.Effect<Outcome, never, AnswerPorts> =>599 Effect.gen(function* () {600 if (at.effects.some(NextStep.guards.Retry)) {601 return at.outcome;602 }603604 const call = at.effects.find(605 (each): each is Call<"Land" | "Merge" | "RunChecks"> =>606 !NextStep.guards.Retry(each)607 );608609 if (call === undefined) {610 return at.outcome;611 }612613 const attempt = attempts[call._tag] + 1;614 const { given, judged } = yield* portStep(params, call, attempt, earlier);615 const { step } = yield* StepRunner;616617 const next = yield* step(618 `record:${nameOf[call._tag]}#${attempt}`,619 Steps,620 record(params, given)621 );622623 if (Option.isNone(given)) {624 return next.outcome;625 }626627 return yield* carry(628 params,629 next,630 { ...attempts, [call._tag]: attempt },631 Option.orElse(judged, () => earlier)632 );633 });634635export const runAnswer = (636 params: AnswerParams637): Effect.Effect<Outcome, never, AnswerPorts> =>638 Effect.gen(function* () {639 const { step } = yield* StepRunner;640 const run = yield* step("load", Schema.Option(AnswerRun), load(params));641642 if (Option.isNone(run)) {643 return yield* Effect.die(new UnknownRequest(params));644 }645646 const outcome = yield* carry(647 params,648 {649 effects: callsOf(nextSteps(run.value)),650 outcome: outcomeOf(run.value.state),651 },652 { Land: 0, Merge: 0, RunChecks: 0 },653 Option.none()654 );655656 yield* notes(params, outcome);657658 return outcome;659 });