Skip to content
Myr

Merge build/219-landing-lifecycle: an answer's way to main moves only by a pure transition, and a model test proves it

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

authored by oscabriel · committed by oscabriel · parents 7723381, e546fce · Browse files · 3 files+2156 added−0 removed
This commit

State

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

Diff stats

3 files+2156 added−0 removed

  • tests:+1571 added−0 removed
  • other:+585 added−0 removed

3 files+2156 added−0 removed

added:packages/project/src/landing.ts+585 added
1/**2 * The landing lifecycle: one answer request's way from the queue to main3 * (ADR 0012). A pure `transition(state, command, now)` returns the next state4 * and the effects the project service settles; it reads no clock and calls no5 * port. A command that does not apply to a state changes nothing, so a replay6 * converges (principle 8).7 */8import { AgentTrailer, Credit } from "@repo/protocol/domain/credit";9import type { CreditRole } from "@repo/protocol/domain/credit";10import type { Choice } from "@repo/protocol/domain/decision";11import { DecisionSubject } from "@repo/protocol/domain/decision";12import type { ProjectEvent } from "@repo/protocol/domain/event";13import { AskKind } from "@repo/protocol/domain/kind";14import { LandingView } from "@repo/protocol/domain/landing";15import { Outcome } from "@repo/protocol/domain/outcome";16import {17 AskId,18 BlobSha,19 CommitSha,20 DecisionId,21 Handle,22 LandedSha,23 ProjectName,24 RepoName,25 RepoPath,26 RequestId,27 TreeSha,28} from "@repo/protocol/ids";29import {30 PostureChange,31 Refusal,32 StaleBase,33 Weakened,34} from "@repo/protocol/refusal";35import { Array, Data, DateTime, Duration, Match, Option, Schema } from "effect";3637/** How many times a moved main may send an answer back to merge before it is refused as stale. */38export const maxRemerges = 3;3940/**41 * One path an answer's merge changed. Structurally the gate's and git's42 * `Change`, so the service passes one where the other is expected.43 */44export const Change = Schema.Struct({45 after: Schema.optionalKey(BlobSha),46 before: Schema.optionalKey(BlobSha),47 path: RepoPath,48 status: Schema.Literals(["added", "modified", "deleted"]),49});5051export type Change = typeof Change.Type;5253/**54 * An admitted answer, as the gate let it through: who answers which ask from55 * which fork, and the credit its landing will carry.56 */57export const Request = Schema.Struct({58 answerer: Handle,59 /** Absent for a decider's own landing. */60 ask: Schema.OptionFromOptionalKey(AskId),61 assisted: Schema.Array(AgentTrailer),62 base: CommitSha,63 /**64 * The credit trailers the landing carries; a finish adds `Finished-by`, and65 * an accepted decision `Decided-by`.66 */67 credits: Schema.Array(Credit),68 fork: RepoName,69 head: CommitSha,70 project: ProjectName,71 requestId: RequestId,72});7374export type Request = typeof Request.Type;7576/**77 * A decision an answer can wait on. Declining one refuses the answer with the78 * refusal it stands for.79 */80export const AnswerDecision = Schema.Union([81 DecisionSubject.cases.PostureChange,82 DecisionSubject.cases.RaiseRatchet,83 DecisionSubject.cases.Waiver,84]).pipe(Schema.toTaggedUnion("_tag"));8586export type AnswerDecision = typeof AnswerDecision.Type;8788/** A decision the answer waits on, with the id the service minted for it. */89export const PendingDecision = Schema.Struct({90 id: DecisionId,91 subject: AnswerDecision,92});9394export type PendingDecision = typeof PendingDecision.Type;9596const Count = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));9798// What every state between the queue and main carries: the main it works99// against, how often a moved main sent it back, and how often a port retried.100const underway = {101 attempt: Count,102 main: LandedSha,103 remerges: Count,104 request: Request,105};106107const checkedFields = { ...underway, tree: TreeSha };108109/** Where one answer request stands on its way to main. */110export const LandingState = Schema.TaggedUnion({111 /** Passed its checks, and waits on decisions; a finish may follow. */112 AwaitingDecision: {113 ...checkedFields,114 decisions: Schema.NonEmptyArray(PendingDecision),115 finish: AskKind.fields.finish,116 },117 /** Passed its checks, and waits for a decider's finish. */118 AwaitingFinish: checkedFields,119 /** The merged tree is being checked. */120 Checking: { ...checkedFields, changes: Schema.Array(Change) },121 Landed: { request: Request, sha: LandedSha },122 /** Passed every stage; the platform is landing the tree on main. */123 Landing: checkedFields,124 /** Being merged onto `main`. */125 Merging: underway,126 Queued: { request: Request },127 Refused: { refusals: Schema.NonEmptyArray(Refusal), request: Request },128 /** Passed the gate, and waits for its parent ask to land first. */129 WaitingOnParent: { parent: AskId, request: Request },130});131132export type LandingState = typeof LandingState.Type;133134/** What the service tells a landing: a port's answer, a person's decision, or the queue's go. */135export type LandingCommand = Data.TaggedEnum<{136 /** The queue started the request against the landed main. */137 Start: { readonly main: LandedSha };138 /** The request's ask waits on its parent; `Start` resumes it. */139 Wait: { readonly parent: AskId };140 /** The merge onto `main` came out clean. */141 Merged: {142 readonly changes: readonly Change[];143 readonly main: LandedSha;144 readonly tree: TreeSha;145 };146 /** The merge onto `main` conflicted in these paths. */147 MergeConflict: {148 readonly conflicts: readonly RepoPath[];149 readonly main: LandedSha;150 };151 /** The checks judged `tree`. */152 Checked: {153 readonly decisions: readonly PendingDecision[];154 readonly finish: AskKind["finish"];155 readonly refusals: readonly Refusal[];156 readonly tree: TreeSha;157 };158 /** A decider finished the answer. */159 Finished: { readonly by: Handle };160 /** Decider `by` decided one of the decisions the answer waits on. */161 Decided: {162 readonly by: Handle;163 readonly choice: Choice;164 readonly decision: DecisionId;165 };166 /** Landing found main moved from `from`, the main it landed against, to `main`. */167 MainMoved: { readonly from: LandedSha; readonly main: LandedSha };168 /** The landing is on main at `sha`. */169 LandedOk: { readonly sha: LandedSha };170 /** The repo was busy with another push during landing attempt `attempt`. */171 Busy: { readonly attempt: number };172 /**173 * A port answered `VerifierBlocked` during attempt `attempt`: retried with174 * backoff, never counted against the answerer.175 */176 Blocked: { readonly attempt: number };177}>;178179export const LandingCommand = Data.taggedEnum<LandingCommand>();180181type WithoutSeq<E> = E extends ProjectEvent ? Omit<E, "seq"> : never;182183/** A project event before the store gives it its place in the sequence. */184export type ProjectEventInput = WithoutSeq<ProjectEvent>;185186export const ProjectEventInput = Data.taggedEnum<ProjectEventInput>();187188/** What the service runs for a landing: the transition only describes it. */189export type LandingEffect = Data.TaggedEnum<{190 Merge: {191 readonly base: CommitSha;192 readonly fork: RepoName;193 readonly head: CommitSha;194 readonly main: LandedSha;195 };196 RunChecks: { readonly tree: TreeSha };197 Land: { readonly main: LandedSha; readonly tree: TreeSha };198 /** Run the state's `pendingEffects` again at `at`. */199 Retry: { readonly at: DateTime.Utc };200 Emit: { readonly event: ProjectEventInput };201 /** Record the landing: close the ask, answer the claim, move the landed SHA. */202 Record: { readonly sha: LandedSha };203}>;204205export const LandingEffect = Data.taggedEnum<LandingEffect>();206207/** One step of a landing: the state it reached and the effects to settle. */208export interface Step {209 readonly effects: readonly LandingEffect[];210 readonly state: LandingState;211}212213const {214 AwaitingDecision,215 AwaitingFinish,216 Checking,217 Landed,218 Landing,219 Merging,220 Refused,221 WaitingOnParent,222} = LandingState.cases;223224type Underway = Pick<225 typeof Merging.Type,226 "attempt" | "main" | "remerges" | "request"227>;228229type Passed = Underway & { readonly tree: TreeSha };230231const passedOf = ({ attempt, main, remerges, request, tree }: Passed) => ({232 attempt,233 main,234 remerges,235 request,236 tree,237});238239/** How long a retry waits after attempt `attempt`: a second, doubling, up to five minutes. */240export const backoff = (attempt: number): Duration.Duration =>241 Duration.millis(Math.min(1000 * 2 ** attempt, 5 * 60 * 1000));242243/**244 * The port call a state waits on: the service runs it when the state is245 * entered, and again at a `Retry`.246 */247export const pendingEffects = (state: LandingState): readonly LandingEffect[] =>248 LandingState.matchOrElse<readonly LandingEffect[]>(249 state,250 {251 Checking: ({ tree }) => [LandingEffect.RunChecks({ tree })],252 Landing: ({ main, tree }) => [LandingEffect.Land({ main, tree })],253 Merging: ({ main, request }) => [254 LandingEffect.Merge({255 base: request.base,256 fork: request.fork,257 head: request.head,258 main,259 }),260 ],261 },262 () => []263 );264265const stay = (state: LandingState): Step => ({ effects: [], state });266267const enter = (state: LandingState): Step => ({268 effects: pendingEffects(state),269 state,270});271272const refuse = (273 request: Request,274 refusals: Array.NonEmptyReadonlyArray<Refusal>275): Step => stay(Refused.make({ refusals, request }));276277const start = (request: Request, main: LandedSha): Step =>278 enter(Merging.make({ attempt: 0, main, remerges: 0, request }));279280// A port answered `Busy` or `VerifierBlocked` for this attempt: the same281// state waits, then runs its port call again. A report for another attempt282// is a replay, and changes nothing.283const retry = (284 state: typeof Checking.Type | typeof Landing.Type | typeof Merging.Type,285 attempt: number,286 now: DateTime.Utc287): Step =>288 attempt === state.attempt289 ? {290 effects: [291 LandingEffect.Retry({292 at: DateTime.addDuration(now, backoff(attempt)),293 }),294 ],295 state: { ...state, attempt: attempt + 1 },296 }297 : stay(state);298299const isFinished = (request: Request) =>300 request.credits.some(({ role }) => role === "Finished-by");301302// The landing credits a person once in each role, however often they act in it.303const credit = (request: Request, role: CreditRole, handle: Handle): Request =>304 request.credits.some(305 (given) => given.role === role && given.handle === handle306 )307 ? request308 : { ...request, credits: [...request.credits, { handle, role }] };309310// Every stage passed but the human one: wait on each decision first, then on311// a finish the kind requires and nobody gave yet, then land.312const human = (313 passed: Passed,314 decisions: readonly PendingDecision[],315 finish: AskKind["finish"]316): Step =>317 Array.match(decisions, {318 onEmpty: () =>319 finish === "required" && !isFinished(passed.request)320 ? stay(AwaitingFinish.make(passedOf(passed)))321 : enter(Landing.make(passedOf(passed))),322 onNonEmpty: (waiting) =>323 stay(324 AwaitingDecision.make({325 ...passedOf(passed),326 decisions: waiting,327 finish,328 })329 ),330 });331332/** The refusal a declined decision stands for. */333const declined = (subject: AnswerDecision): Refusal =>334 AnswerDecision.match(subject, {335 PostureChange: ({ from, to }) => new PostureChange({ from, to }),336 RaiseRatchet: ({ after, before, ratchet, territory }) =>337 new Weakened({ weakening: { after, before, ratchet, territory } }),338 Waiver: ({ at, marker, reason }) =>339 new Weakened({ at, weakening: { marker, reason } }),340 });341342const approves = {343 accept: true,344 adopt: true,345 decline: false,346 revert: false,347} as const satisfies Record<Choice, boolean>;348349const decide = (350 state: typeof AwaitingDecision.Type,351 { by, choice, decision }: Data.TaggedEnum.Value<LandingCommand, "Decided">352): Step =>353 Option.match(354 Array.findFirst(state.decisions, ({ id }) => id === decision),355 {356 onNone: () => stay(state),357 onSome: ({ subject }) =>358 approves[choice]359 ? human(360 { ...state, request: credit(state.request, "Decided-by", by) },361 state.decisions.filter(({ id }) => id !== decision),362 state.finish363 )364 : refuse(state.request, [declined(subject)]),365 }366 );367368const finished = (state: typeof AwaitingFinish.Type, by: Handle): Step =>369 enter(370 Landing.make({371 ...passedOf(state),372 request: credit(state.request, "Finished-by", by),373 })374 );375376const landed = (377 state: typeof Landing.Type,378 sha: LandedSha,379 now: DateTime.Utc380): Step => {381 const { request } = state;382383 const view = {384 assisted: request.assisted,385 author: request.answerer,386 credits: request.credits,387 landedAt: now,388 parent: state.main,389 project: request.project,390 requestId: request.requestId,391 sha,392 };393394 const landing = LandingView.make(395 Option.match(request.ask, {396 onNone: () => view,397 onSome: (ask) => ({ ...view, ask }),398 })399 );400401 return {402 effects: [403 LandingEffect.Emit({404 event: ProjectEventInput.Landed({ at: now, landing }),405 }),406 LandingEffect.Record({ sha }),407 ],408 state: Landed.make({ request, sha }),409 };410};411412// Main moved under the landing. A report about another main is a replay. A413// clean re-merge goes back through the checks; past the limit it is stale.414const moved = (415 state: typeof Landing.Type,416 { from, main }: { readonly from: LandedSha; readonly main: LandedSha }417): Step => {418 if (from !== state.main || main === state.main) {419 return stay(state);420 }421422 return state.remerges >= maxRemerges423 ? refuse(state.request, [424 new StaleBase({ base: state.request.base, conflicts: [], main }),425 ])426 : enter(427 Merging.make({428 attempt: state.attempt,429 main,430 remerges: state.remerges + 1,431 request: state.request,432 })433 );434};435436/**437 * One step of a landing. A command that does not apply to the state, or438 * reports on another main, tree, attempt or decision than the state is at,439 * returns the state as it was with no effects: replays and late duplicates440 * converge. Landed and Refused never move.441 */442export const transition = (443 state: LandingState,444 command: LandingCommand,445 now: DateTime.Utc446): Step =>447 LandingState.match(state, {448 AwaitingDecision: (waiting) =>449 Match.value(command).pipe(450 Match.tag("Decided", (decided) => decide(waiting, decided)),451 Match.orElse(() => stay(waiting))452 ),453 AwaitingFinish: (waiting) =>454 Match.value(command).pipe(455 Match.tag("Finished", ({ by }) => finished(waiting, by)),456 Match.orElse(() => stay(waiting))457 ),458 Checking: (checking) =>459 Match.value(command).pipe(460 Match.tag("Checked", ({ decisions, finish, refusals, tree }) =>461 tree === checking.tree462 ? Array.match(refusals, {463 onEmpty: () => human(checking, decisions, finish),464 onNonEmpty: (all) => refuse(checking.request, all),465 })466 : stay(checking)467 ),468 Match.tag("Blocked", ({ attempt }) => retry(checking, attempt, now)),469 Match.orElse(() => stay(checking))470 ),471 Landed: stay,472 Landing: (landing) =>473 Match.value(command).pipe(474 Match.tag("LandedOk", ({ sha }) => landed(landing, sha, now)),475 Match.tag("MainMoved", (report) => moved(landing, report)),476 Match.tag("Busy", "Blocked", ({ attempt }) =>477 retry(landing, attempt, now)478 ),479 Match.orElse(() => stay(landing))480 ),481 Merging: (merging) =>482 Match.value(command).pipe(483 Match.tag("Merged", ({ changes, main, tree }) =>484 main === merging.main485 ? enter(486 Checking.make({487 attempt: merging.attempt,488 changes,489 main,490 remerges: merging.remerges,491 request: merging.request,492 tree,493 })494 )495 : stay(merging)496 ),497 Match.tag("MergeConflict", ({ conflicts, main }) =>498 main === merging.main499 ? refuse(merging.request, [500 new StaleBase({ base: merging.request.base, conflicts, main }),501 ])502 : stay(merging)503 ),504 Match.tag("Blocked", ({ attempt }) => retry(merging, attempt, now)),505 Match.orElse(() => stay(merging))506 ),507 Queued: (queued) =>508 Match.value(command).pipe(509 Match.tag("Start", ({ main }) => start(queued.request, main)),510 Match.tag("Wait", ({ parent }) =>511 stay(WaitingOnParent.make({ parent, request: queued.request }))512 ),513 Match.orElse(() => stay(queued))514 ),515 Refused: stay,516 WaitingOnParent: (waiting) =>517 Match.value(command).pipe(518 Match.tag("Start", ({ main }) => start(waiting.request, main)),519 Match.orElse(() => stay(waiting))520 ),521 });522523/** Where the answer stands, as `status`, `verdict` and MCP report it. */524export const outcomeOf = (state: LandingState): Outcome =>525 LandingState.match<Outcome>(state, {526 AwaitingDecision: ({ decisions }) =>527 Outcome.cases.AwaitingDecision.make({ decision: decisions[0].id }),528 AwaitingFinish: () => Outcome.cases.AwaitingFinish.make({}),529 Checking: () => Outcome.cases.Checking.make({ stage: "checks" }),530 Landed: ({ sha }) => Outcome.cases.Landed.make({ sha }),531 // Past every stage: the landing closes the last one.532 Landing: () => Outcome.cases.Checking.make({ stage: "human" }),533 Merging: () => Outcome.cases.Checking.make({ stage: "merge" }),534 Queued: () => Outcome.cases.Checking.make({ stage: "merge" }),535 Refused: ({ refusals }) => Outcome.cases.Refused.make({ refusals }),536 WaitingOnParent: ({ parent }) =>537 Outcome.cases.WaitingOnParent.make({ ask: parent }),538 });539540/**541 * The project's landing queue, as a value the store persists: requests land542 * one at a time, in the order their checks passed.543 */544export const LandingQueue = Schema.Struct({545 /** The request whose landing is underway. */546 active: Schema.OptionFromOptionalKey(RequestId),547 order: Schema.Array(RequestId),548});549550export type LandingQueue = typeof LandingQueue.Type;551552const isActive = (queue: LandingQueue, id: RequestId) =>553 Option.contains(queue.active, id);554555/** Adds a request to the back of the queue; a request already in it stays where it is. */556export const enqueue = (queue: LandingQueue, id: RequestId): LandingQueue =>557 isActive(queue, id) || queue.order.includes(id)558 ? queue559 : { ...queue, order: [...queue.order, id] };560561/** Admits the request at the front, unless one is already landing. */562export const next = (563 queue: LandingQueue564): {565 readonly admit: Option.Option<RequestId>;566 readonly queue: LandingQueue;567} =>568 Option.isSome(queue.active)569 ? { admit: Option.none(), queue }570 : Array.match(queue.order, {571 onEmpty: () => ({ admit: Option.none(), queue }),572 onNonEmpty: ([front, ...rest]) => ({573 admit: Option.some(front),574 queue: { active: Option.some(front), order: rest },575 }),576 });577578/**579 * Frees the slot once a request's landing is over (landed, refused or sent580 * back to merge), or drops a request that leaves before its turn.581 */582export const settle = (queue: LandingQueue, id: RequestId): LandingQueue =>583 isActive(queue, id)584 ? { ...queue, active: Option.none() }585 : { ...queue, order: queue.order.filter((waiting) => waiting !== id) };
added:packages/project/test/landing.model.test.ts+808 added
1import { describe, expect, it } from "@effect/vitest";2import type { Credit } from "@repo/protocol/domain/credit";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import type { Choice } from "@repo/protocol/domain/decision";5import {6 AskId,7 CommitSha,8 DecisionId,9 Handle,10 LandedSha,11 ProjectName,12 RatchetName,13 RepoName,14 RepoPath,15 RequestId,16 TreeSha,17} from "@repo/protocol/ids";18import { ChecksFailed } from "@repo/protocol/refusal";19import {20 Arbitrary,21 Array,22 DateTime,23 Duration,24 Effect,25 Equal,26 Option,27 Result,28 Schema,29} from "effect";3031import {32 enqueue,33 LandingCommand,34 LandingEffect,35 LandingQueue,36 LandingState,37 maxRemerges,38 next as admitNext,39 ProjectEventInput,40 Request,41 settle,42 transition,43} from "../src/landing.ts";44import type { PendingDecision, Step } from "../src/landing.ts";4546// The model drives one answer request through generated histories of what47// the service could tell it: port answers, decisions, the queue's go, and48// commands delivered again, right away or long after. It keeps its own record49// of what happened, and after every step checks the lifecycle against it.5051const hex = (n: number) => n.toString(16).padStart(40, "0");5253const opened = DateTime.makeUnsafe("2026-10-07T12:00:00Z");5455const alice = Handle.make("alice");5657const carol = Handle.make("carol");5859const ask = AskId.make("parse-dates");6061const request = Request.make({62 answerer: Handle.make("bob"),63 ask: Option.some(ask),64 assisted: [],65 base: CommitSha.make(hex(0xba_5e)),66 credits: [{ handle: alice, role: "Asked-by" }],67 fork: RepoName.make("datekit--parse-dates--bob"),68 head: CommitSha.make(hex(0x4e_ad)),69 project: ProjectName.make("datekit"),70 requestId: RequestId.make("push-4ead"),71});7273// Every value a step makes is new, keyed by the step's index: a main, a tree74// or a decision id recurs only when a command is delivered again.75const mainAt = (step: number) => LandedSha.make(hex(0x1_00_00 + step));7677const strangerAt = (step: number) => LandedSha.make(hex(0x2_00_00 + step));7879const treeAt = (step: number) => TreeSha.make(hex(0x3_00_00 + step));8081const decisionAt = (step: number, k: number) =>82 DecisionId.make(`dec-${String(2 * step + k).padStart(6, "0")}`);8384const failed = new ChecksFailed({85 lane: "unit",86 logRef: "datekit/push-4ead/unit#1",87 next: "bun test src/parse.test.ts",88});8990const raise = DecisionSubject.cases.RaiseRatchet.make({91 after: 4,92 ask,93 before: 3,94 ratchet: RatchetName.make("escapes"),95 territory: "packages/parse",96});9798const waiver = DecisionSubject.cases.Waiver.make({99 ask,100 at: { line: 3, path: RepoPath.make("src/parse.test.ts") },101 marker: ".skip(",102 reason: "flaky until the clock fix lands",103});104105const fresh = [106 "Start",107 "Wait",108 "Merged",109 "MergeConflict",110 "Checked",111 "Finished",112 "Decided",113 "MainMoved",114 "LandedOk",115 "Busy",116 "Blocked",117] as const;118119/** The longest history the model runs. */120const longest = 60;121122/**123 * One move of a history. Half drive the request the way a service would (the124 * answer its state waits for); the rest say any command, repeat the last one,125 * or replay an earlier one. `pick` chooses among variants, and `back` which126 * earlier command a replay delivers again, from anywhere in the history.127 */128const Move = Schema.Struct({129 back: Schema.Int.check(130 Schema.isBetween({ maximum: longest - 1, minimum: 0 })131 ),132 drive: Schema.Boolean,133 kind: Schema.Literals([...fresh, "Again", "Replay"]),134 pick: Schema.Int.check(Schema.isBetween({ maximum: 7, minimum: 0 })),135});136137type Move = typeof Move.Type;138139const histories = Arbitrary.array(Arbitrary.schema(Move), {140 maxLength: longest,141});142143// Arbitrary grows arrays with `size` (10 by default): histories long enough144// to land, wait, re-merge and replay need a larger one.145const size = longest;146147interface Underway {148 readonly attempt: number;149 readonly main: LandedSha;150}151152const underway = (state: LandingState) =>153 LandingState.matchOrElse<Option.Option<Underway>>(154 state,155 {156 AwaitingDecision: Option.some,157 AwaitingFinish: Option.some,158 Checking: Option.some,159 Landing: Option.some,160 Merging: Option.some,161 },162 () => Option.none()163 );164165const remergesOf = (state: LandingState) =>166 LandingState.matchOrElse<Option.Option<number>>(167 state,168 {169 AwaitingDecision: ({ remerges }) => Option.some(remerges),170 AwaitingFinish: ({ remerges }) => Option.some(remerges),171 Checking: ({ remerges }) => Option.some(remerges),172 Landing: ({ remerges }) => Option.some(remerges),173 Merging: ({ remerges }) => Option.some(remerges),174 },175 () => Option.none()176 );177178const checkingTree = (state: LandingState) =>179 LandingState.matchOrElse<Option.Option<TreeSha>>(180 state,181 { Checking: ({ tree }) => Option.some(tree) },182 () => Option.none()183 );184185const waitingOn = (state: LandingState) =>186 LandingState.matchOrElse<readonly PendingDecision[]>(187 state,188 { AwaitingDecision: ({ decisions }) => decisions },189 () => []190 );191192interface Context {193 readonly pick: number;194 readonly state: LandingState;195 readonly step: number;196}197198const mainOf = ({ state, step }: Context) =>199 Option.match(underway(state), {200 onNone: () => mainAt(step),201 onSome: ({ main }) => main,202 });203204// `pick` 7 makes a report about something the request is not at.205const reportedMain = (context: Context) =>206 context.pick === 7 ? strangerAt(context.step) : mainOf(context);207208const attemptOf = ({ pick, state }: Context) =>209 Option.match(underway(state), {210 onNone: () => 0,211 onSome: ({ attempt }) => attempt,212 }) + (pick === 7 ? 1 : 0);213214// What the checks report, by `pick`: clean under each finish rule, refused,215// waiting on decisions, or about a tree the request is not at.216const checked = ({ pick, state, step }: Context) => {217 const tree = Option.getOrElse(checkingTree(state), () => treeAt(step));218 const clean = { decisions: [], finish: "never" as const, refusals: [], tree };219220 const reports = [221 clean,222 clean,223 { ...clean, finish: "optional" as const },224 { ...clean, finish: "required" as const },225 { ...clean, refusals: [failed] },226 { ...clean, decisions: [{ id: decisionAt(step, 0), subject: raise }] },227 {228 ...clean,229 decisions: [230 { id: decisionAt(step, 0), subject: raise },231 { id: decisionAt(step, 1), subject: waiver },232 ],233 finish: "required" as const,234 },235 { ...clean, tree: treeAt(step) },236 ];237238 return LandingCommand.Checked(reports[pick] ?? clean);239};240241const choices = [242 "accept",243 "accept",244 "accept",245 "adopt",246 "decline",247 "revert",248 "accept",249 "accept",250] as const;251252const commands = {253 Blocked: (context) => LandingCommand.Blocked({ attempt: attemptOf(context) }),254 Busy: (context) => LandingCommand.Busy({ attempt: attemptOf(context) }),255 Checked: checked,256 Decided: ({ pick, state, step }) =>257 LandingCommand.Decided({258 by: pick < 4 ? alice : carol,259 choice: choices[pick] ?? "accept",260 decision: Option.match(Array.get(waitingOn(state), pick % 2), {261 onNone: () => decisionAt(step, 0),262 onSome: ({ id }) => id,263 }),264 }),265 Finished: () => LandingCommand.Finished({ by: alice }),266 LandedOk: ({ step }) => LandingCommand.LandedOk({ sha: mainAt(step) }),267 MainMoved: (context) =>268 LandingCommand.MainMoved({269 from: reportedMain(context),270 main: context.pick === 6 ? mainOf(context) : mainAt(context.step),271 }),272 MergeConflict: (context) =>273 LandingCommand.MergeConflict({274 conflicts: [RepoPath.make("src/parse.ts")],275 main: reportedMain(context),276 }),277 Merged: (context) =>278 LandingCommand.Merged({279 changes: [],280 main: reportedMain(context),281 tree: treeAt(context.step),282 }),283 Start: ({ step }) => LandingCommand.Start({ main: mainAt(step) }),284 Wait: () => LandingCommand.Wait({ parent: AskId.make("move-to-temporal") }),285} as const satisfies Record<286 (typeof fresh)[number],287 (context: Context) => LandingCommand288>;289290// While landing, main moves under it for `pick` 0 to 2, the repo is busy291// for 7, and otherwise the landing is on main.292const landingReport = (context: Context) => {293 if (context.pick < 3) {294 return commands.MainMoved({ ...context, pick: 0 });295 }296297 return context.pick === 7298 ? commands.Busy({ ...context, pick: 0 })299 : commands.LandedOk(context);300};301302/** The answer a service would give the state next. */303const drive = (context: Context): LandingCommand => {304 const { pick } = context;305306 return LandingState.match<LandingCommand>(context.state, {307 AwaitingDecision: () => commands.Decided(context),308 AwaitingFinish: () => commands.Finished(),309 Checking: () => checked(context),310 Landed: () => commands.Start(context),311 Landing: () => landingReport(context),312 Merging: () =>313 pick === 7314 ? commands.MergeConflict({ ...context, pick: 0 })315 : commands.Merged({ ...context, pick: 0 }),316 Queued: () => (pick === 7 ? commands.Wait() : commands.Start(context)),317 Refused: () => commands.Start(context),318 WaitingOnParent: () => commands.Start(context),319 });320};321322/** What the model remembers of a history so far. */323interface Model {324 /** Commands that changed the state or asked for an effect. */325 readonly applied: readonly LandingCommand[];326 /** The tree the checks passed since the latest merge. */327 readonly cleared: Option.Option<TreeSha>;328 /** Who the landing must credit: the request's credits, then each finish and accepted decision. */329 readonly credits: readonly Credit[];330 readonly delivered: readonly LandingCommand[];331 /** A finish was given. */332 readonly finished: boolean;333 /** The latest checks asked for a finish. */334 readonly finishOwed: boolean;335 /** The main the latest `Land` effect lands on. */336 readonly landingOn: Option.Option<LandedSha>;337 /** What the latest merge made. */338 readonly merged: Option.Option<{339 readonly main: LandedSha;340 readonly tree: TreeSha;341 }>;342 /** The main the latest `Merge` effect merges onto. */343 readonly merging: Option.Option<LandedSha>;344 /** Main moved during landing, and no `Merge` followed yet. */345 readonly moved: boolean;346 /** How often main moved under a landing. */347 readonly remerges: number;348 /** How many retries the ports asked for. */349 readonly retries: number;350 readonly state: LandingState;351 /** The decisions the latest checks asked for, less those accepted since. */352 readonly waiting: readonly DecisionId[];353}354355const begin: Model = {356 applied: [],357 cleared: Option.none(),358 credits: request.credits,359 delivered: [],360 finishOwed: false,361 finished: false,362 landingOn: Option.none(),363 merged: Option.none(),364 merging: Option.none(),365 moved: false,366 remerges: 0,367 retries: 0,368 state: LandingState.cases.Queued.make({ request }),369 waiting: [],370};371372const commandFor = (move: Move, model: Model, step: number) => {373 const context = { pick: move.pick, state: model.state, step };374375 if (move.drive) {376 return Option.some(drive(context));377 }378379 if (move.kind === "Again") {380 return Array.last(model.delivered);381 }382383 if (move.kind === "Replay") {384 return Array.get(385 model.delivered,386 move.back % Math.max(model.delivered.length, 1)387 );388 }389390 return Option.some(commands[move.kind](context));391};392393const isTerminal = LandingState.isAnyOf(["Landed", "Refused"]);394395const tookEffect = (before: LandingState, { effects, state }: Step) =>396 effects.length > 0 || !Equal.equals(before, state);397398const approves = (choice: Choice) => choice === "accept" || choice === "adopt";399400const credited = (401 credits: readonly Credit[],402 role: Credit["role"],403 handle: Handle404): readonly Credit[] =>405 credits.some((given) => given.role === role && given.handle === handle)406 ? credits407 : [...credits, { handle, role }];408409/**410 * Whether the request's state waits for this command, as the model sees it:411 * the main it merges onto or lands on, the tree it checks, the attempt it is412 * at, a decision it waits on. Exactly these commands may take effect.413 */414const awaited = (model: Model, command: LandingCommand) => {415 const is = (tags: readonly LandingState["_tag"][]) =>416 LandingState.isAnyOf(tags)(model.state);417418 return LandingCommand.$match(command, {419 Blocked: ({ attempt }) =>420 is(["Merging", "Checking", "Landing"]) && attempt === model.retries,421 Busy: ({ attempt }) => is(["Landing"]) && attempt === model.retries,422 Checked: ({ tree }) =>423 is(["Checking"]) &&424 Option.exists(model.merged, (merged) => merged.tree === tree),425 Decided: ({ decision }) =>426 is(["AwaitingDecision"]) && model.waiting.includes(decision),427 Finished: () => is(["AwaitingFinish"]),428 LandedOk: () => is(["Landing"]),429 MainMoved: ({ from, main }) =>430 is(["Landing"]) &&431 Option.contains(model.landingOn, from) &&432 from !== main,433 MergeConflict: ({ main }) =>434 is(["Merging"]) && Option.contains(model.merging, main),435 Merged: ({ main }) =>436 is(["Merging"]) && Option.contains(model.merging, main),437 Start: () => is(["Queued", "WaitingOnParent"]),438 Wait: () => is(["Queued"]),439 });440};441442/** Whether an awaited command must refuse the answer. */443const refuses = LandingCommand.$match({444 Blocked: () => false,445 Busy: () => false,446 Checked: ({ refusals }) => refusals.length > 0,447 Decided: ({ choice }) => !approves(choice),448 Finished: () => false,449 LandedOk: () => false,450 MainMoved: () => false,451 MergeConflict: () => true,452 Merged: () => false,453 Start: () => false,454 Wait: () => false,455});456457/** The model after a step: what it learned from the command and the effects. */458const advance = (model: Model, command: LandingCommand, step: Step): Model => {459 const merge = Array.findLast(step.effects, LandingEffect.$is("Merge"));460 const land = Array.findLast(step.effects, LandingEffect.$is("Land"));461 const retries = step.effects.filter(LandingEffect.$is("Retry")).length;462463 const learned: Partial<Model> = awaited(model, command)464 ? LandingCommand.$match(command, {465 Blocked: () => ({}),466 Busy: () => ({}),467 Checked: ({ decisions, finish, refusals, tree }) =>468 refusals.length > 0469 ? {}470 : {471 cleared: Option.some(tree),472 finishOwed: finish === "required",473 waiting: decisions.map(({ id }) => id),474 },475 Decided: ({ by, choice, decision }) =>476 approves(choice)477 ? {478 credits: credited(model.credits, "Decided-by", by),479 waiting: model.waiting.filter((id) => id !== decision),480 }481 : {},482 Finished: ({ by }) => ({483 credits: credited(model.credits, "Finished-by", by),484 finished: true,485 }),486 LandedOk: () => ({}),487 MainMoved: () => ({ moved: true, remerges: model.remerges + 1 }),488 MergeConflict: () => ({}),489 Merged: ({ main, tree }) => ({ merged: Option.some({ main, tree }) }),490 Start: () => ({}),491 Wait: () => ({}),492 })493 : {};494495 const known = { ...model, ...learned };496 const merged = Option.isSome(merge);497498 return {499 ...known,500 applied: tookEffect(model.state, step)501 ? [...model.applied, command]502 : model.applied,503 cleared: merged ? Option.none() : known.cleared,504 delivered: [...model.delivered, command],505 finishOwed: merged ? false : known.finishOwed,506 landingOn: Option.isSome(land)507 ? Option.some(land.value.main)508 : model.landingOn,509 merged: merged ? Option.none() : known.merged,510 merging: Option.isSome(merge)511 ? Option.some(merge.value.main)512 : model.merging,513 moved: merged ? false : known.moved,514 retries: model.retries + retries,515 state: step.state,516 waiting: merged ? [] : known.waiting,517 };518};519520/** Every invariant one step must keep; the first one broken, if any. */521const broken = (522 model: Model,523 command: LandingCommand,524 step: Step,525 now: DateTime.Utc526): Option.Option<string> => {527 const after = advance(model, command, step);528 const changed = tookEffect(model.state, step);529 const due = awaited(model, command);530531 const placed = step.effects.every((effect) =>532 LandingEffect.$match(effect, {533 Emit: () => LandingState.guards.Landed(step.state),534 Land: ({ main, tree }) =>535 !after.moved &&536 !LandingState.guards.Merging(model.state) &&537 Equal.equals(after.merged, Option.some({ main, tree })) &&538 Option.contains(after.cleared, tree) &&539 after.waiting.length === 0 &&540 (!after.finishOwed || after.finished),541 Merge: ({ main }) =>542 LandingState.guards.Merging(step.state) && step.state.main === main,543 Record: ({ sha }) =>544 LandingState.guards.Landed(step.state) && step.state.sha === sha,545 Retry: ({ at }) =>546 DateTime.isGreaterThan(at, now) &&547 (LandingCommand.$is("Busy")(command) ||548 LandingCommand.$is("Blocked")(command)),549 RunChecks: ({ tree }) =>550 LandingCommand.$is("Merged")(command) && command.tree === tree,551 })552 );553554 const rules: readonly (readonly [string, boolean])[] = [555 ["a landed or refused answer moved", !isTerminal(model.state) || !changed],556 [557 "a command delivered again had an effect",558 !Array.contains(model.applied, command) || !changed,559 ],560 [561 "a report about another main, tree, attempt or decision, or one its state does not wait for, had an effect",562 !changed || due,563 ],564 ["a report its state waited for had no effect", !due || changed],565 [566 "main moved during landing, and no merge against the new main followed",567 !(due && LandingCommand.$is("MainMoved")(command)) ||568 step.effects.some(569 (effect) =>570 LandingEffect.$is("Merge")(effect) && effect.main === command.main571 ) ||572 (LandingState.guards.Refused(step.state) &&573 after.remerges === maxRemerges + 1),574 ],575 [576 `still underway after more than ${maxRemerges} re-merges`,577 after.remerges <= maxRemerges || isTerminal(step.state),578 ],579 [580 "the re-merges counted differ from the times main moved",581 Option.match(remergesOf(step.state), {582 onNone: () => true,583 onSome: (remerges) => remerges === after.remerges,584 }),585 ],586 [587 "a conflict, a failed check or a declined decision did not refuse the answer",588 !(due && refuses(command)) || LandingState.guards.Refused(step.state),589 ],590 [591 "it waits on other decisions than the checks asked for",592 !LandingState.guards.AwaitingDecision(step.state) ||593 Equal.equals(594 waitingOn(step.state).map(({ id }) => id),595 after.waiting596 ),597 ],598 [599 "it waits for a finish nobody owes, or one already given",600 !LandingState.guards.AwaitingFinish(step.state) ||601 (after.finishOwed && !after.finished),602 ],603 [604 "the landing does not credit, once each, everyone who finished it or accepted a decision it waited on",605 step.effects.every(606 (effect) =>607 !LandingEffect.$is("Emit")(effect) ||608 !ProjectEventInput.$is("Landed")(effect.event) ||609 Equal.equals(effect.event.landing.credits, after.credits)610 ),611 ],612 [613 "landed without landing",614 !LandingState.guards.Landed(step.state) ||615 LandingState.guards.Landed(model.state) ||616 LandingState.guards.Landing(model.state),617 ],618 [619 "an effect out of place (Land only on the latest merge's tree, checked clean, with every decision and finish given)",620 placed,621 ],622 ];623624 return Option.map(625 Array.findFirst(rules, ([, holds]) => !holds),626 ([rule]) => rule627 );628};629630const describeCommand = (command: LandingCommand) => JSON.stringify(command);631632/** A history's end, and every state it passed through. */633interface Run {634 readonly model: Model;635 readonly visited: ReadonlySet<LandingState["_tag"]>;636}637638/** Runs a history; fails with the first broken invariant and where it broke. */639const run = (moves: readonly Move[]): Result.Result<Run, string> => {640 const visited = new Set<LandingState["_tag"]>(["Queued"]);641 let model = begin;642643 for (const [step, move] of moves.entries()) {644 const command = commandFor(move, model, step);645646 if (Option.isSome(command)) {647 const now = DateTime.addDuration(opened, Duration.seconds(step));648 const result = transition(model.state, command.value, now);649 const violation = broken(model, command.value, result, now);650651 if (Option.isSome(violation)) {652 return Result.fail(653 `step ${step}: ${violation.value}, at ${model.state._tag} on ${describeCommand(command.value)}`654 );655 }656657 model = advance(model, command.value, result);658 visited.add(model.state._tag);659 }660 }661662 return Result.succeed({ model, visited });663};664665const holds = (moves: readonly Move[]) =>666 Result.match(run(moves), {667 onFailure: (violation) => Effect.fail(violation),668 onSuccess: () => Effect.succeed(true),669 });670671describe("the landing lifecycle over generated histories", () => {672 it.effect("keeps every invariant after every step", () =>673 Effect.gen(function* () {674 const result = yield* Arbitrary.checkEffect(histories, holds, {675 runs: 3000,676 seed: 219,677 size,678 });679680 expect(Arbitrary.formatCheckFailure(result)).toBeUndefined();681 })682 );683684 // A model test whose histories never land proves nothing: they must reach685 // every state, land after main moved under a landing, and run out of686 // re-merges.687 it.effect("reaches every state, re-merges and runs out of re-merges", () =>688 Effect.gen(function* () {689 const sample = yield* Arbitrary.sampleEffect(histories, {690 count: 1000,691 seed: 219,692 size,693 });694695 const runs = sample.flatMap((moves) =>696 Result.match(run(moves), {697 onFailure: () => [],698 onSuccess: (ran) => [ran],699 })700 );701702 const seen = new Set(runs.flatMap(({ visited }) => [...visited]));703704 expect(runs).toHaveLength(sample.length);705 expect([...seen].toSorted()).toStrictEqual(706 Object.keys(LandingState.cases).toSorted()707 );708 expect(709 runs.some(710 ({ model }) =>711 LandingState.guards.Landed(model.state) && model.remerges > 0712 )713 ).toBeTruthy();714 expect(715 runs.some(({ model }) => model.remerges > maxRemerges)716 ).toBeTruthy();717 })718 );719});720721const QueueMove = Schema.Struct({722 id: Schema.Int.check(Schema.isBetween({ maximum: 2, minimum: 0 })),723 op: Schema.Literals(["Enqueue", "Next", "Settle"]),724});725726type QueueMove = typeof QueueMove.Type;727728const requestIds = [729 RequestId.make("push-0001"),730 RequestId.make("push-0002"),731 RequestId.make("push-0003"),732] as const;733734/** The queue as the model keeps it: who is landing, and who waits, in order. */735interface Line {736 readonly landing: Option.Option<RequestId>;737 readonly waiting: readonly RequestId[];738}739740const serial = (moves: readonly QueueMove[]) => {741 let queue = LandingQueue.make({ active: Option.none(), order: [] });742 let line: Line = { landing: Option.none(), waiting: [] };743744 for (const [step, { id, op }] of moves.entries()) {745 const requestId = requestIds[id] ?? requestIds[0];746747 if (op === "Next") {748 const { admit, queue: after } = admitNext(queue);749750 if (Option.isSome(line.landing) && Option.isSome(admit)) {751 return Effect.fail(752 `step ${step}: admitted ${admit.value} while ${line.landing.value} is landing`753 );754 }755756 if (!Option.isSome(line.landing)) {757 if (!Equal.equals(admit, Array.head(line.waiting))) {758 return Effect.fail(`step ${step}: admitted out of order`);759 }760761 line = { landing: admit, waiting: line.waiting.slice(1) };762 }763764 queue = after;765 } else if (op === "Enqueue") {766 queue = enqueue(queue, requestId);767 line =768 Option.contains(line.landing, requestId) ||769 line.waiting.includes(requestId)770 ? line771 : { ...line, waiting: [...line.waiting, requestId] };772 } else {773 queue = settle(queue, requestId);774 line = {775 landing: Option.filter(776 line.landing,777 (landing) => landing !== requestId778 ),779 waiting: line.waiting.filter((waiting) => waiting !== requestId),780 };781 }782783 if (784 !Equal.equals(785 queue,786 LandingQueue.make({ active: line.landing, order: line.waiting })787 )788 ) {789 return Effect.fail(`step ${step}: the queue lost or reordered a request`);790 }791 }792793 return Effect.succeed(true);794};795796describe("the landing queue over generated histories", () => {797 it.effect("never admits a second request while one is landing", () =>798 Effect.gen(function* () {799 const result = yield* Arbitrary.checkEffect(800 Arbitrary.array(Arbitrary.schema(QueueMove), { maxLength: 30 }),801 serial,802 { runs: 2000, seed: 219, size: 30 }803 );804805 expect(Arbitrary.formatCheckFailure(result)).toBeUndefined();806 })807 );808});
added:packages/project/test/landing.test.ts+763 added
1import { describe, expect, it } from "@effect/vitest";2import { DecisionSubject } from "@repo/protocol/domain/decision";3import { Outcome } from "@repo/protocol/domain/outcome";4import {5 AskId,6 BlobSha,7 CommitSha,8 DecisionId,9 Handle,10 LandedSha,11 ProjectName,12 RatchetName,13 RepoName,14 RepoPath,15 RequestId,16 TreeSha,17} from "@repo/protocol/ids";18import {19 ChecksFailed,20 PostureChange,21 StaleBase,22 Weakened,23} from "@repo/protocol/refusal";24import { DateTime, Duration, Option, Schema } from "effect";2526import {27 backoff,28 enqueue,29 LandingCommand,30 LandingEffect,31 LandingQueue,32 LandingState,33 maxRemerges,34 next as admitNext,35 outcomeOf,36 pendingEffects,37 ProjectEventInput,38 Request,39 settle,40 transition,41} from "../src/landing.ts";4243const hex = (n: number) => n.toString(16).padStart(40, "0");4445const now = DateTime.makeUnsafe("2026-10-07T12:00:00Z");4647const alice = Handle.make("alice");4849const bob = Handle.make("bob");5051const base = CommitSha.make(hex(0xba_5e));5253const head = CommitSha.make(hex(0x4e_ad));5455const main = LandedSha.make(hex(0xa1));5657const movedMain = LandedSha.make(hex(0xa2));5859const landed = LandedSha.make(hex(0xa3));6061const tree = TreeSha.make(hex(0x7_e1));6263const fork = RepoName.make("datekit--parse-dates--bob");6465const ask = AskId.make("parse-dates");6667const project = ProjectName.make("datekit");6869const requestId = RequestId.make("push-4ead");7071const changed = RepoPath.make("src/parse.ts");7273const changes = [74 {75 after: BlobSha.make(hex(0xb2)),76 before: BlobSha.make(hex(0xb1)),77 path: changed,78 status: "modified" as const,79 },80];8182const request = Request.make({83 answerer: bob,84 ask: Option.some(ask),85 assisted: [],86 base,87 credits: [88 { handle: alice, role: "Asked-by" },89 { handle: bob, role: "Signed-off-by" },90 ],91 fork,92 head,93 project,94 requestId,95});9697const raise = DecisionSubject.cases.RaiseRatchet.make({98 after: 4,99 ask,100 before: 3,101 ratchet: RatchetName.make("escapes"),102 territory: "packages/parse",103});104105const decisionId = DecisionId.make("dec-000001");106107const {108 AwaitingDecision,109 AwaitingFinish,110 Checking,111 Landed,112 Landing,113 Merging,114 Queued,115 Refused,116 WaitingOnParent,117} = LandingState.cases;118119const underway = { attempt: 0, main, remerges: 0, request };120121const merging = Merging.make(underway);122123const checking = Checking.make({ ...underway, changes, tree });124125const landing = Landing.make({ ...underway, tree });126127const clean = {128 decisions: [],129 finish: "never" as const,130 refusals: [],131 tree,132};133134const failed = new ChecksFailed({135 lane: "unit",136 logRef: "datekit/push-4ead/unit#1",137 next: "bun test src/parse.test.ts",138});139140const terminal = [141 Landed.make({ request, sha: landed }),142 Refused.make({ refusals: [failed], request }),143];144145const everyCommand = [146 LandingCommand.Start({ main }),147 LandingCommand.Wait({ parent: ask }),148 LandingCommand.Merged({ changes, main, tree }),149 LandingCommand.MergeConflict({ conflicts: [changed], main }),150 LandingCommand.Checked(clean),151 LandingCommand.Finished({ by: alice }),152 LandingCommand.Decided({ by: alice, choice: "accept", decision: decisionId }),153 LandingCommand.MainMoved({ from: main, main: movedMain }),154 LandingCommand.LandedOk({ sha: landed }),155 LandingCommand.Busy({ attempt: 0 }),156 LandingCommand.Blocked({ attempt: 0 }),157];158159describe("an answer on its way to main", () => {160 it("is merged onto the landed main when the queue starts it", () => {161 const step = transition(162 Queued.make({ request }),163 LandingCommand.Start({ main }),164 now165 );166167 expect(step).toStrictEqual({168 effects: [LandingEffect.Merge({ base, fork, head, main })],169 state: merging,170 });171 });172173 it("is checked on the exact tree a clean merge made", () => {174 const step = transition(175 merging,176 LandingCommand.Merged({ changes, main, tree }),177 now178 );179180 expect(step).toStrictEqual({181 effects: [LandingEffect.RunChecks({ tree })],182 state: checking,183 });184 });185186 it("is refused as stale when its merge onto main conflicts", () => {187 const step = transition(188 merging,189 LandingCommand.MergeConflict({ conflicts: [changed], main }),190 now191 );192193 expect(step).toStrictEqual({194 effects: [],195 state: Refused.make({196 refusals: [new StaleBase({ base, conflicts: [changed], main })],197 request,198 }),199 });200 });201202 it("lands the checked tree when its checks pass and nobody has to act", () => {203 const step = transition(checking, LandingCommand.Checked(clean), now);204205 expect(step).toStrictEqual({206 effects: [LandingEffect.Land({ main, tree })],207 state: landing,208 });209 });210211 it("is refused with every refusal its checks gave", () => {212 const step = transition(213 checking,214 LandingCommand.Checked({ ...clean, refusals: [failed] }),215 now216 );217218 expect(step).toStrictEqual({219 effects: [],220 state: Refused.make({ refusals: [failed], request }),221 });222 });223224 it("waits for a decider's finish when its kind requires one", () => {225 const step = transition(226 checking,227 LandingCommand.Checked({ ...clean, finish: "required" }),228 now229 );230231 expect(step).toStrictEqual({232 effects: [],233 state: AwaitingFinish.make({ ...underway, tree }),234 });235 });236237 it("waits on a decision when it raises a ratchet with a reason", () => {238 const step = transition(239 checking,240 LandingCommand.Checked({241 ...clean,242 decisions: [{ id: decisionId, subject: raise }],243 }),244 now245 );246247 expect(step).toStrictEqual({248 effects: [],249 state: AwaitingDecision.make({250 ...underway,251 decisions: [{ id: decisionId, subject: raise }],252 finish: "never",253 tree,254 }),255 });256 });257258 it("goes back to merge, against the new main, when main moved while landing", () => {259 const step = transition(260 landing,261 LandingCommand.MainMoved({ from: main, main: movedMain }),262 now263 );264265 expect(step).toStrictEqual({266 effects: [LandingEffect.Merge({ base, fork, head, main: movedMain })],267 state: Merging.make({ ...underway, main: movedMain, remerges: 1 }),268 });269 });270271 it(`is refused as stale when main moves after ${maxRemerges} re-merges`, () => {272 const step = transition(273 Landing.make({ ...underway, remerges: maxRemerges, tree }),274 LandingCommand.MainMoved({ from: main, main: movedMain }),275 now276 );277278 expect(maxRemerges).toBe(3);279 expect(step).toStrictEqual({280 effects: [],281 state: Refused.make({282 refusals: [new StaleBase({ base, conflicts: [], main: movedMain })],283 request,284 }),285 });286 });287288 it("is landed, announced and recorded when its landing is on main", () => {289 const step = transition(290 landing,291 LandingCommand.LandedOk({ sha: landed }),292 now293 );294295 expect(step).toStrictEqual({296 effects: [297 LandingEffect.Emit({298 event: ProjectEventInput.Landed({299 at: now,300 landing: {301 ask,302 assisted: [],303 author: bob,304 credits: request.credits,305 landedAt: now,306 parent: main,307 project,308 requestId,309 sha: landed,310 },311 }),312 }),313 LandingEffect.Record({ sha: landed }),314 ],315 state: Landed.make({ request, sha: landed }),316 });317 });318319 it("retries with backoff when the repo is busy", () => {320 const step = transition(landing, LandingCommand.Busy({ attempt: 0 }), now);321322 expect(step).toStrictEqual({323 effects: [324 LandingEffect.Retry({325 at: DateTime.makeUnsafe("2026-10-07T12:00:01Z"),326 }),327 ],328 state: Landing.make({ ...underway, attempt: 1, tree }),329 });330 });331332 it("never moves once landed or refused, whatever it hears", () => {333 for (const state of terminal) {334 for (const command of everyCommand) {335 expect(transition(state, command, now)).toStrictEqual({336 effects: [],337 state,338 });339 }340 }341 });342});343344describe("a report about another main, tree, attempt or decision", () => {345 const otherMain = LandedSha.make(hex(0xa9));346 const otherTree = TreeSha.make(hex(0x7_e9));347348 const replays = [349 [merging, LandingCommand.Merged({ changes, main: otherMain, tree })],350 [merging, LandingCommand.MergeConflict({ conflicts: [], main: otherMain })],351 [merging, LandingCommand.Blocked({ attempt: 1 })],352 [checking, LandingCommand.Checked({ ...clean, tree: otherTree })],353 [landing, LandingCommand.MainMoved({ from: otherMain, main: movedMain })],354 [landing, LandingCommand.MainMoved({ from: main, main })],355 [landing, LandingCommand.Busy({ attempt: 1 })],356 [checking, LandingCommand.LandedOk({ sha: landed })],357 ] as const;358359 it("changes nothing, so a late or replayed report converges", () => {360 for (const [state, command] of replays) {361 expect(transition(state, command, now)).toStrictEqual({362 effects: [],363 state,364 });365 }366 });367});368369describe("a port that cannot run", () => {370 it("is retried with a backoff that doubles, up to five minutes", () => {371 expect([0, 1, 2, 12].map(backoff)).toStrictEqual([372 Duration.seconds(1),373 Duration.seconds(2),374 Duration.seconds(4),375 Duration.minutes(5),376 ]);377 });378379 it("leaves the answer where it was, never refused for it", () => {380 for (const state of [merging, checking, landing]) {381 const step = transition(382 state,383 LandingCommand.Blocked({ attempt: 0 }),384 now385 );386387 expect(step).toStrictEqual({388 effects: [389 LandingEffect.Retry({ at: DateTime.addDuration(now, backoff(0)) }),390 ],391 state: { ...state, attempt: 1 },392 });393 expect(pendingEffects(step.state)).toStrictEqual(pendingEffects(state));394 }395 });396});397398describe("a finish", () => {399 const waiting = AwaitingFinish.make({ ...underway, tree });400401 const finished = Request.make({402 ...request,403 credits: [...request.credits, { handle: alice, role: "Finished-by" }],404 });405406 it("lands the answer and credits the decider who gave it", () => {407 expect(408 transition(waiting, LandingCommand.Finished({ by: alice }), now)409 ).toStrictEqual({410 effects: [LandingEffect.Land({ main, tree })],411 state: Landing.make({ ...underway, request: finished, tree }),412 });413 });414415 it("is not asked for again after a moved main sends the answer back through its checks", () => {416 const rechecked = Checking.make({417 ...underway,418 changes,419 request: finished,420 tree,421 });422423 expect(424 transition(425 rechecked,426 LandingCommand.Checked({ ...clean, finish: "required" }),427 now428 ).state429 ).toStrictEqual(Landing.make({ ...underway, request: finished, tree }));430 });431});432433describe("a decision the answer waits on", () => {434 const posture = DecisionSubject.cases.PostureChange.make({435 from: "open",436 to: "openCore",437 });438439 const waiver = DecisionSubject.cases.Waiver.make({440 ask,441 at: { line: 12, path: changed },442 marker: ".skip(",443 reason: "flaky on CI until the clock fix lands",444 });445446 const secondId = DecisionId.make("dec-000002");447448 const waiting = (subject: typeof raise | typeof posture | typeof waiver) =>449 AwaitingDecision.make({450 ...underway,451 decisions: [{ id: decisionId, subject }],452 finish: "never",453 tree,454 });455456 it("lands the answer once accepted, and credits the decider who accepted it", () => {457 expect(458 transition(459 waiting(raise),460 LandingCommand.Decided({461 by: alice,462 choice: "accept",463 decision: decisionId,464 }),465 now466 )467 ).toStrictEqual({468 effects: [LandingEffect.Land({ main, tree })],469 state: Landing.make({470 ...underway,471 request: Request.make({472 ...request,473 credits: [474 { handle: alice, role: "Asked-by" },475 { handle: bob, role: "Signed-off-by" },476 { handle: alice, role: "Decided-by" },477 ],478 }),479 tree,480 }),481 });482 });483484 it("waits on the next decision, then on a required finish, crediting its decider once", () => {485 const both = AwaitingDecision.make({486 ...underway,487 decisions: [488 { id: decisionId, subject: raise },489 { id: secondId, subject: waiver },490 ],491 finish: "required",492 tree,493 });494495 const decided = Request.make({496 ...request,497 credits: [...request.credits, { handle: alice, role: "Decided-by" }],498 });499500 const first = transition(501 both,502 LandingCommand.Decided({503 by: alice,504 choice: "accept",505 decision: decisionId,506 }),507 now508 );509510 expect(first.state).toStrictEqual(511 AwaitingDecision.make({512 ...underway,513 decisions: [{ id: secondId, subject: waiver }],514 finish: "required",515 request: decided,516 tree,517 })518 );519 expect(520 transition(521 first.state,522 LandingCommand.Decided({523 by: alice,524 choice: "accept",525 decision: secondId,526 }),527 now528 ).state529 ).toStrictEqual(530 AwaitingFinish.make({ ...underway, request: decided, tree })531 );532 });533534 it("refuses the answer with the refusal it stands for when declined", () => {535 const cases = [536 [537 raise,538 new Weakened({539 weakening: {540 after: 4,541 before: 3,542 ratchet: "escapes",543 territory: "packages/parse",544 },545 }),546 ],547 [548 waiver,549 new Weakened({550 at: { line: 12, path: changed },551 weakening: {552 marker: ".skip(",553 reason: "flaky on CI until the clock fix lands",554 },555 }),556 ],557 [posture, new PostureChange({ from: "open", to: "openCore" })],558 ] as const;559560 for (const [subject, refusal] of cases) {561 expect(562 transition(563 waiting(subject),564 LandingCommand.Decided({565 by: alice,566 choice: "decline",567 decision: decisionId,568 }),569 now570 )571 ).toStrictEqual({572 effects: [],573 state: Refused.make({ refusals: [refusal], request }),574 });575 }576 });577578 it("ignores a choice on a decision it does not wait on", () => {579 const state = waiting(raise);580581 expect(582 transition(583 state,584 LandingCommand.Decided({585 by: alice,586 choice: "decline",587 decision: secondId,588 }),589 now590 )591 ).toStrictEqual({ effects: [], state });592 });593});594595describe("an answer to a blocked ask", () => {596 it("waits on its parent, then merges when the queue starts it", () => {597 const parent = AskId.make("move-to-temporal");598599 const waits = transition(600 Queued.make({ request }),601 LandingCommand.Wait({ parent }),602 now603 );604605 expect(waits).toStrictEqual({606 effects: [],607 state: WaitingOnParent.make({ parent, request }),608 });609 expect(610 transition(waits.state, LandingCommand.Start({ main }), now)611 ).toStrictEqual({612 effects: [LandingEffect.Merge({ base, fork, head, main })],613 state: merging,614 });615 });616});617618describe("the outcome a person reads", () => {619 it("names the stage while checking, and the wait or the result after", () => {620 expect(621 [622 Queued.make({ request }),623 merging,624 checking,625 landing,626 AwaitingFinish.make({ ...underway, tree }),627 AwaitingDecision.make({628 ...underway,629 decisions: [{ id: decisionId, subject: raise }],630 finish: "never",631 tree,632 }),633 WaitingOnParent.make({ parent: ask, request }),634 Landed.make({ request, sha: landed }),635 Refused.make({ refusals: [failed], request }),636 ].map(outcomeOf)637 ).toStrictEqual([638 Outcome.cases.Checking.make({ stage: "merge" }),639 Outcome.cases.Checking.make({ stage: "merge" }),640 Outcome.cases.Checking.make({ stage: "checks" }),641 Outcome.cases.Checking.make({ stage: "human" }),642 Outcome.cases.AwaitingFinish.make({}),643 Outcome.cases.AwaitingDecision.make({ decision: decisionId }),644 Outcome.cases.WaitingOnParent.make({ ask }),645 Outcome.cases.Landed.make({ sha: landed }),646 Outcome.cases.Refused.make({ refusals: [failed] }),647 ]);648 });649});650651describe("a landing the store keeps", () => {652 const states = [653 Queued.make({ request }),654 WaitingOnParent.make({ parent: ask, request }),655 merging,656 checking,657 AwaitingDecision.make({658 ...underway,659 decisions: [{ id: decisionId, subject: raise }],660 finish: "required",661 tree,662 }),663 AwaitingFinish.make({ ...underway, tree }),664 landing,665 // A decider's own landing answers no ask.666 Landed.make({667 request: Request.make({ ...request, ask: Option.none() }),668 sha: landed,669 }),670 Refused.make({ refusals: [failed], request }),671 ];672673 it("comes back from its stored JSON as it was, in every state", () => {674 const Stored = Schema.fromJsonString(LandingState);675676 expect(677 states.map((state) =>678 Schema.decodeSync(Stored)(Schema.encodeSync(Stored)(state))679 )680 ).toStrictEqual(states);681 });682683 it("names, after a hydrate, the port call it waits on", () => {684 expect(states.map(pendingEffects)).toStrictEqual([685 [],686 [],687 [LandingEffect.Merge({ base, fork, head, main })],688 [LandingEffect.RunChecks({ tree })],689 [],690 [],691 [LandingEffect.Land({ main, tree })],692 [],693 [],694 ]);695 });696697 it("keeps its queue as JSON too", () => {698 const Stored = Schema.fromJsonString(LandingQueue);699700 const queues = [701 LandingQueue.make({ active: Option.none(), order: [] }),702 LandingQueue.make({703 active: Option.some(requestId),704 order: [RequestId.make("push-0002")],705 }),706 ];707708 expect(709 queues.map((queue) =>710 Schema.decodeSync(Stored)(Schema.encodeSync(Stored)(queue))711 )712 ).toStrictEqual(queues);713 });714});715716describe("the landing queue", () => {717 const first = RequestId.make("push-0001");718 const second = RequestId.make("push-0002");719 const empty = LandingQueue.make({ active: Option.none(), order: [] });720721 it("takes a request once, however often it is enqueued", () => {722 const queue = enqueue(enqueue(enqueue(empty, first), second), first);723724 expect(queue).toStrictEqual(725 LandingQueue.make({ active: Option.none(), order: [first, second] })726 );727 expect(enqueue(admitNext(queue).queue, first)).toStrictEqual(728 admitNext(queue).queue729 );730 });731732 it("admits one request at a time, in the order they came", () => {733 const queue = enqueue(enqueue(empty, first), second);734 const admitted = admitNext(queue);735736 expect(admitted).toStrictEqual({737 admit: Option.some(first),738 queue: LandingQueue.make({ active: Option.some(first), order: [second] }),739 });740 expect(admitNext(admitted.queue)).toStrictEqual({741 admit: Option.none(),742 queue: admitted.queue,743 });744 expect(admitNext(settle(admitted.queue, first)).admit).toStrictEqual(745 Option.some(second)746 );747 });748749 it("admits nothing when nothing waits", () => {750 expect(admitNext(empty)).toStrictEqual({751 admit: Option.none(),752 queue: empty,753 });754 });755756 it("drops a request settled before its turn", () => {757 const queue = settle(enqueue(enqueue(empty, first), second), second);758759 expect(queue).toStrictEqual(760 LandingQueue.make({ active: Option.none(), order: [first] })761 );762 });763});