Skip to content
Myr

deciders.ts

This file

Path

packages/project/src/deciders.ts

2,213 lines · 61.2 KiB · TypeScript

Last changed by

Merge observability into mainoscabrielbefore adoption1985111

History of this file

Take it

1import { RefName, RepoHost, Revision } from "@repo/artifacts/repo-host";2import { Brand } from "@repo/brand";3import { CheckLane } from "@repo/checks/check-runner";4import type { CheckRunner } from "@repo/checks/check-runner";5import type { PushFacts } from "@repo/gate/facts";6import { pushStages, runGate } from "@repo/gate/gate";7import { scan } from "@repo/gate/stages/shape";8import { formatLanding } from "@repo/git/trailers";9import type { AnswerReceipt, LandReceipt } from "@repo/protocol/domain/answer";10import type { Ask } from "@repo/protocol/domain/ask";11import { RefNameText } from "@repo/protocol/domain/common";12import type { ConfigFile, Evidence } from "@repo/protocol/domain/common";13import type { AgentTrailer, Credit } from "@repo/protocol/domain/credit";14import { DecisionSubject } from "@repo/protocol/domain/decision";15import type { Choice, Decision, Today } from "@repo/protocol/domain/decision";16import type { EnvSchemaView } from "@repo/protocol/domain/env";17import type { LandingView } from "@repo/protocol/domain/landing";18import { Outcome } from "@repo/protocol/domain/outcome";19import type { Policy } from "@repo/protocol/domain/policy";20import { DraftState } from "@repo/protocol/domain/proposal";21import type { Proposal } from "@repo/protocol/domain/proposal";22import type { CreditSummary } from "@repo/protocol/domain/record";23import type { RunBlock } from "@repo/protocol/domain/run";24import type { Ledger } from "@repo/protocol/domain/visibility";25import {26  AskId,27  CommitSha,28  DecisionId,29  LandedSha,30  ProposalId,31  RepoName,32  RepoPath,33  RequestId,34  TreeSha,35  keyOf,36  sameHandle,37} from "@repo/protocol/ids";38import type { ProjectName, Handle, EnvKey } from "@repo/protocol/ids";39import { Person } from "@repo/protocol/principal";40import type { Principal } from "@repo/protocol/principal";41import {42  Denounced,43  NotDecider,44  NotVouched,45  RepoBusy,46  StaleBase,47  TouchedJudge,48  UnknownAsk,49  UnknownProposal,50} from "@repo/protocol/refusal";51import type {52  CapReached,53  DecisionClosed,54  DraftInProgress,55  IncompleteBrief,56  NotRedFirst,57  NotSensitive,58  ProposalClosed,59  Refusal,60  UnknownDecision,61  UnknownEnvItem,62  UnknownProject,63  ValueTooShort,64  VerifierBlocked,65  WeakCheck,66} from "@repo/protocol/refusal";67import { parseVouchFile } from "@repo/rules/vouch";68import {69  Array,70  DateTime,71  Effect,72  Match,73  Option,74  Order,75  Record,76  Schema,77} from "effect";78import type { Redacted } from "effect";7980import type { Advanced, AnswerQueue, AnswerRun } from "./answer-runs.ts";81import { isStep, runStep } from "./answer-runs/steps.ts";82import { budgetFor, spend } from "./attention/budget.ts";83import { creditsByArea } from "./attention/credits.ts";84import {85  decide,86  decidersFor,87  expireDecisions,88  openDecision,89} from "./attention/decisions.ts";90import type { Decided } from "./attention/decisions.ts";91import { AttentionEffect, platformHandle } from "./attention/effects.ts";92import {93  draft,94  DraftCommand,95  draftFailedLabel,96  expire as expireProposals,97  propose,98  ProposalCommand,99} from "./attention/proposals.ts";100import type { Proposed } from "./attention/proposals.ts";101import { recordOf } from "./attention/record.ts";102import { today } from "./attention/today.ts";103import { capped, standing } from "./attention/vouch.ts";104import { ClaimState } from "./claim.ts";105import { DraftResult } from "./draft-runs.ts";106import type { UnlandedRunEnv } from "./env-port.ts";107import { ProjectEventInput } from "./events.ts";108import { pushFacts } from "./facts.ts";109import { Lander, Rebuild } from "./lander.ts";110import type { ComposedFile } from "./lander.ts";111import {112  AnswerDecision,113  LandingCommand,114  LandingState,115  outcomeOf,116  transition,117} from "./landing.ts";118import type { Request, Step } from "./landing.ts";119import { MetricPoint, millisBetween } from "./metrics.ts";120import {121  draftRow,122  measuredRow,123  OutboxBody,124  outboxRow,125  startRow,126} from "./outbox.ts";127import type {128  AnswerRow,129  BudgetDayRow,130  ClaimRow,131  OutboxRow,132  ProjectRow,133} from "./project-store/rows.ts";134135/** Lint keeps "shape" out of code names, so the name is spelled once, here. */136export const envSchemaMethod = "envShape";137138export interface DeciderApi {139  readonly [envSchemaMethod]: (140    caller: Principal141  ) => Effect.Effect<EnvSchemaView, UnknownProject>;142  readonly credits: (143    caller: Principal,144    handle: Handle145  ) => Effect.Effect<{ readonly credits: readonly CreditSummary[] }>;146  readonly decide: (147    caller: Person,148    input: {149      readonly choice: Choice;150      readonly decision: DecisionId;151      readonly note?: string;152    }153  ) => Effect.Effect<154    { readonly decision: Decision },155    UnknownDecision | DecisionClosed | NotDecider | WaitRefusal156  >;157  readonly finish: (158    caller: Person,159    input: {160      readonly ask: AskId;161      readonly base: CommitSha;162      readonly head: CommitSha;163      readonly requestId: RequestId;164    }165  ) => Effect.Effect<166    AnswerReceipt,167    NotDecider | StaleBase | RepoBusy | TouchedJudge168  >;169  readonly flagAsk: (170    caller: Person,171    input: { readonly ask: AskId; readonly reason: string }172  ) => Effect.Effect<173    { readonly proposal: Proposal },174    UnknownAsk | Denounced | CapReached175  >;176  readonly fork: (177    caller: Person178  ) => Effect.Effect<179    { readonly fork: RepoName; readonly remote: string },180    NotVouched | Denounced181  >;182  readonly land: (183    caller: Person,184    input: {185      readonly base: CommitSha;186      readonly head: CommitSha;187      readonly message: string;188      readonly requestId: RequestId;189    }190  ) => Effect.Effect<LandReceipt, NotDecider | StaleBase | RepoBusy>;191  readonly ledger: (caller: Principal) => Effect.Effect<Ledger>;192  readonly proposeAsk: (193    caller: Person,194    input: {195      readonly draft?: true;196      readonly files?: Array.NonEmptyReadonlyArray<ComposedFile>;197      readonly sealed?: { readonly head: CommitSha };198      readonly territory?: string;199      readonly want: string;200    }201  ) => Effect.Effect<202    { readonly proposal: Proposal },203    Denounced | CapReached | NotVouched204  >;205  readonly setEnv: (206    caller: Person,207    input: {208      readonly acknowledgeShort?: boolean;209      readonly key: EnvKey;210      readonly value: Redacted.Redacted;211    }212  ) => Effect.Effect<213    {214      readonly key: EnvKey;215      readonly setAt: DateTime.Utc;216      readonly setBy: Handle;217    },218    NotDecider | UnknownEnvItem | NotSensitive | ValueTooShort219  >;220  readonly draftAsk: (221    caller: Person,222    input: { readonly note?: string; readonly proposal: ProposalId }223  ) => Effect.Effect<224    { readonly proposal: Proposal },225    UnknownProposal | ProposalClosed | NotDecider | DraftInProgress | CapReached226  >;227  readonly showProposal: (228    caller: Principal,229    proposal: ProposalId230  ) => Effect.Effect<231    { readonly files: readonly ConfigFile[]; readonly proposal: Proposal },232    UnknownProposal233  >;234  readonly today: (caller: Person) => Effect.Effect<Today, NotDecider>;235  readonly vouch: (236    caller: Person,237    input: {238      readonly handle: Handle;239      readonly note?: string;240      readonly verdict: "vouch" | "denounce";241    }242  ) => Effect.Effect<{ readonly landed: LandedSha }, NotDecider | StaleBase>;243}244245export interface DeciderState {246  readonly answers: readonly {247    readonly record: {248      readonly landing: LandingState;249      readonly receipt: AnswerReceipt;250    };251    readonly row: AnswerRow;252  }[];253  readonly asks: ReadonlyMap<AskId, Ask>;254  readonly budgetDays: readonly BudgetDayRow[];255  readonly claims: readonly {256    readonly row: ClaimRow;257    readonly state: ClaimState;258  }[];259  readonly decisions: readonly Decision[];260  readonly landings: readonly LandingView[];261  readonly policy: Option.Option<Policy>;262  readonly project: Option.Option<ProjectRow>;263  readonly proposals: readonly Proposal[];264}265266export interface DeciderWrites {267  readonly budgetDays: Map<string, BudgetDayRow>;268  readonly decisions: Map<DecisionId, Decision>;269  readonly events: ProjectEventInput[];270  readonly landings: LandingView[];271  readonly outbox: OutboxRow[];272  readonly project: Map<"row", ProjectRow>;273  readonly proposals: Map<ProposalId, Proposal>;274}275276export interface Opening {277  readonly ask: AskId;278  readonly asker: Handle;279  readonly assisted: readonly AgentTrailer[];280  readonly credits: readonly Credit[];281  readonly decider: Person;282  readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;283}284285export type OpenRefusal =286  | NotDecider287  | NotRedFirst288  | WeakCheck289  | IncompleteBrief290  | TouchedJudge291  | VerifierBlocked292  | StaleBase;293294export type WaitRefusal = VerifierBlocked | StaleBase;295296type FinalOpenRefusal = Exclude<OpenRefusal, WaitRefusal>;297298const declines = (refusal: FinalOpenRefusal) => Effect.succeedSome(refusal);299300export type DeciderPorts = CheckRunner | Lander | RepoHost;301302export interface DeciderKernel<303  H extends DeciderState,304  W extends DeciderWrites,305> {306  readonly advance: (307    h: H,308    writes: W,309    now: DateTime.Utc,310    requestId: RequestId,311    command: LandingCommand312  ) => Effect.Effect<Advanced>;313  readonly enqueue: (314    writes: W,315    request: Request,316    input: {317      readonly ask: AskId;318      readonly main: LandedSha;319      readonly now: DateTime.Utc;320    }321  ) => Effect.Effect<AnswerReceipt>;322  readonly name: ProjectName;323  readonly open: (324    h: H,325    writes: W,326    now: DateTime.Utc,327    opening: Opening328  ) => Effect.Effect<329    { readonly ask: Ask; readonly landed: LandedSha },330    OpenRefusal331  >;332  readonly policyAt: (333    row: ProjectRow,334    at: LandedSha,335    now: DateTime.Utc336  ) => Effect.Effect<ProjectRow>;337  readonly read: Effect.Effect<H>;338  readonly runEnv: Effect.Effect<UnlandedRunEnv>;339  readonly withLayers: (facts: PushFacts) => Effect.Effect<PushFacts>;340  readonly remote: (fork: RepoName) => Effect.Effect<string>;341  readonly repo: RepoName;342  readonly withPorts: <A, E>(343    effect: Effect.Effect<A, E, DeciderPorts>344  ) => Effect.Effect<A, E>;345  readonly write: <A, E>(346    queue: AnswerQueue,347    body: (h: H, writes: W, now: DateTime.Utc) => Effect.Effect<A, E>348  ) => Effect.Effect<A, E>;349}350351const mainRef = "refs/heads/main";352353const mainRefName = RefName.make(mainRef);354355const configFolder = `${Brand.configDir}/`;356357const landTurns = 16;358359export const isDecider = (policy: Policy, handle: Handle) =>360  policy.deciders.some(({ handles }) =>361    handles.some((each) => sameHandle(each, handle))362  );363364export const decidesOn = (policy: Policy, ask: Ask, handle: Handle) =>365  decidersFor(366    policy,367    ask.territory.paths.map((glob) => RepoPath.make(glob))368  ).some((each) => sameHandle(each, handle));369370const asDecider = (policy: Policy, handle: Handle): Option.Option<Handle> =>371  Array.findFirst(372    policy.deciders.flatMap(({ handles }) => handles),373    (each) => sameHandle(each, handle)374  );375376const overlaid = <K, V extends { readonly id: K }>(377  rows: readonly V[],378  written: ReadonlyMap<K, V>379): readonly V[] => [380  ...rows.map((row) => written.get(row.id) ?? row),381  ...[...written.values()].filter(382    (row) => !rows.some(({ id }) => id === row.id)383  ),384];385386const minted = (prefix: string, taken: number) =>387  `${prefix}-${String(taken + 1).padStart(6, "0")}`;388389const workingFork = (project: ProjectName, handle: Handle) =>390  RepoName.make(`${keyOf(project)}--me--${handle.toLowerCase()}`);391392const moduleOf = (policy: Policy, territory: string) =>393  Array.findFirst(394    policy.modules,395    (module) =>396      module.module === territory ||397      module.paths.some((glob) => glob === `${territory}/**`)398  );399400export const pathsOf = (401  policy: Policy,402  files: readonly RepoPath[],403  territory: Option.Option<string>404): readonly RepoPath[] =>405  Option.match(territory, {406    onNone: () => files.filter((path) => !path.startsWith(configFolder)),407    onSome: (named) =>408      Option.match(moduleOf(policy, named), {409        onNone: () => [RepoPath.make(named)],410        onSome: ({ paths }) => paths.map((glob) => RepoPath.make(glob)),411      }),412  });413414export const decidersOn = (415  policy: Policy,416  paths: readonly RepoPath[],417  initializer: Handle418): Array.NonEmptyReadonlyArray<Handle> => {419  const named = decidersFor(policy, paths);420421  const any = Array.isReadonlyArrayNonEmpty(named)422    ? named423    : decidersFor(policy, []);424425  return Array.isReadonlyArrayNonEmpty(any) ? any : Array.of(initializer);426};427428const proposedLabel = "want";429430const draftedByLabel = "drafted by";431432export const drafterOf = (model: string): AgentTrailer => ({433  harness: `${Brand.cli}-drafter`,434  model,435  verified: true,436});437438/** A round from its start to its settle: the proposal names its start while it drafts. */439const draftedPoints = (440  proposal: Proposal,441  result: DraftResult,442  now: DateTime.Utc443): readonly MetricPoint[] =>444  proposal.draft !== undefined && DraftState.guards.Drafting(proposal.draft)445    ? [446        MetricPoint.cases.Drafted.make({447          attempts: result.attempts,448          latencyMs: millisBetween(proposal.draft.startedAt, now),449          project: proposal.project,450          ready: DraftResult.guards.Red(result),451        }),452      ]453    : [];454455const assistedBy = (evidence: readonly Evidence[]): readonly AgentTrailer[] =>456  Option.toArray(457    Option.map(458      Array.findFirst(evidence, ({ label }) => label === draftedByLabel),459      ({ value }) => drafterOf(value.split(", attempt ")[0] ?? value)460    )461  );462463const evidenceOf = (input: {464  readonly files: readonly ComposedFile[];465  readonly sealed: boolean;466  readonly territory: Option.Option<string>;467  readonly want: string;468}): readonly Evidence[] => [469  { label: proposedLabel, value: input.want },470  ...Option.toArray(471    Option.map(input.territory, (value): Evidence => ({472      label: "territory",473      value,474    }))475  ),476  ...input.files.map(({ content, path }) => ({ label: path, value: content })),477  ...(input.sealed478    ? [479        {480          label: "sealed answer",481          value:482            "a commit in the proposer's working fork, judged first once the ask opens",483        },484      ]485    : []),486];487488const filesOf = (489  proposal: Proposal,490  evidence: readonly Evidence[]491): readonly ComposedFile[] =>492  proposal.files.flatMap((path) =>493    Option.toArray(494      Option.map(495        Array.findFirst(evidence, ({ label }) => label === path),496        ({ value }): ComposedFile => ({ content: value, path })497      )498    )499  );500501const askFolder = `${configFolder}asks/`;502503const askSuffix = ".ask.ts";504505export const askIdOf = (files: readonly ComposedFile[]): Option.Option<AskId> =>506  Array.findFirst(files, ({ path }) =>507    path.startsWith(askFolder) && path.endsWith(askSuffix)508      ? Schema.decodeOption(AskId)(509          path.slice(askFolder.length, -askSuffix.length)510        )511      : Option.none()512  );513514interface FirstClaim {515  readonly at: DateTime.Utc;516  readonly handle: Handle;517}518519const firstClaimsOf = (claims: DeciderState["claims"]): readonly FirstClaim[] =>520  Array.dedupeWith(521    Array.sort(522      claims.flatMap(({ row, state }): FirstClaim[] =>523        ClaimState.guards.Open(state)524          ? []525          : [{ at: state.openedAt, handle: row.claimant }]526      ),527      Order.mapInput(DateTime.Order, ({ at }: FirstClaim) => at)528    ),529    (one: FirstClaim, other: FirstClaim) => sameHandle(one.handle, other.handle)530  );531532const isTouchedJudge = (refusal: Refusal) =>533  Match.value(refusal).pipe(534    Match.tag("TouchedJudge", () => true),535    Match.orElse(() => false)536  );537538const staleOf = (refusal: Refusal): Option.Option<StaleBase> =>539  Match.value(refusal).pipe(540    Match.tag("StaleBase", (stale) => Option.some(stale)),541    Match.orElse(() => Option.none())542  );543544const answerDecisionOf = (subject: DecisionSubject) =>545  Schema.decodeUnknownOption(Schema.toType(AnswerDecision))(subject);546547const messageParts = (message: string) => {548  const [subject = "", ...rest] = message.trim().split("\n");549550  return { body: rest.join("\n").trim(), subject: subject.trim() };551};552553const withTrailer = (message: string, key: string, value: string) =>554  `${message}${key}: ${value}\n`;555556const vouchedText = (557  text: string,558  input: {559    readonly handle: Handle;560    readonly note: Option.Option<string>;561    readonly verdict: "vouch" | "denounce";562  }563) => {564  const kept = text.split("\n").filter((line) =>565    Array.match(parseVouchFile(line).vouches, {566      onEmpty: () => true,567      onNonEmpty: ([vouch]) => !sameHandle(vouch.handle, input.handle),568    })569  );570571  const last = kept.findLastIndex((line) => line.trim() !== "");572  const lines = kept.slice(0, last + 1);573  const sign = input.verdict === "denounce" ? "-" : "";574575  const note = Option.match(576    Option.filter(577      Option.map(input.note, (said) => said.replaceAll(/\s+/gu, " ").trim()),578      (said) => said !== ""579    ),580    { onNone: () => "", onSome: (said) => ` ${said}` }581  );582583  return `${[...lines, `${sign}${input.handle}${note}`].join("\n")}\n`;584};585586const zeroId = CommitSha.make("0".repeat(40));587588export const strayDecision = (input: {589  readonly after: CommitSha;590  readonly before: Option.Option<CommitSha>;591  readonly id: DecisionId;592  readonly initializer: Handle;593  readonly now: DateTime.Utc;594  readonly policy: Policy;595  readonly project: ProjectName;596}): Decision =>597  openDecision({598    deciders: decidersOn(input.policy, [], input.initializer),599    evidence: [],600    expireDays: input.policy.budget.expireDays,601    id: input.id,602    now: input.now,603    project: input.project,604    subject: DecisionSubject.cases.StrayPush.make({605      after: input.after,606      before: Option.getOrElse(input.before, () => zeroId),607      ref: RefNameText.make("refs/heads/main"),608    }),609  });610611export const nextDecisionId = (612  decisions: readonly Decision[],613  written: ReadonlyMap<DecisionId, Decision>614) => DecisionId.make(minted("dec", overlaid(decisions, written).length));615616export const deciderDeadlines = (h: DeciderState): readonly DateTime.Utc[] => [617  ...h.proposals.flatMap(({ expiresAt, state }) =>618    state === "open" ? [expiresAt] : []619  ),620  ...h.decisions.flatMap(({ decided, expiresAt }) =>621    decided === undefined ? [expiresAt] : []622  ),623];624625const unlanded = (handle: Handle, refused: NotDecider | StaleBase) =>626  Effect.logWarning(`the vouch for ${handle} did not land`, refused);627628const mayDraft = (629  policy: Policy,630  row: ProjectRow,631  proposal: Proposal,632  handle: Handle633) =>634  sameHandle(proposal.proposer, handle) ||635  decidersOn(636    policy,637    pathsOf(policy, proposal.files, Option.fromUndefinedOr(proposal.territory)),638    row.initializer639  ).some((each) => sameHandle(each, handle));640641const emitted = (642  writes: DeciderWrites,643  effects: readonly AttentionEffect[]644) => {645  for (const effect of effects) {646    if (AttentionEffect.$is("Emit")(effect)) {647      writes.events.push(effect.event);648    }649  }650};651652export const deciders = <H extends DeciderState, W extends DeciderWrites>(653  kernel: DeciderKernel<H, W>654) => {655  const { name, repo } = kernel;656657  const liveOf = (h: H) =>658    Option.flatMap(659      Option.all({ policy: h.policy, row: h.project }),660      ({ policy, row }) =>661        row.state === "live" && row.landed !== undefined662          ? Option.some({ landed: row.landed, policy, row })663          : Option.none()664    );665666  const rowNow = (h: H, writes: W) =>667    Option.orElse(668      Option.fromUndefinedOr(writes.project.get("row")),669      () => h.project670    );671672  const proposalsNow = (h: H, writes: W) =>673    overlaid(h.proposals, writes.proposals);674675  const decisionsNow = (h: H, writes: W) =>676    overlaid(h.decisions, writes.decisions);677678  const spent = (679    h: H,680    writes: W,681    input: {682      readonly decider: Handle;683      readonly now: DateTime.Utc;684      readonly on: "decision" | "finish";685    }686  ) => {687    const row = spend([...writes.budgetDays.values(), ...h.budgetDays], input);688689    writes.budgetDays.set(`${row.day}|${row.decider}`, row);690  };691692  const recordLanding = (693    h: H,694    writes: W,695    landing: LandingView,696    now: DateTime.Utc697  ) =>698    Effect.gen(function* () {699      writes.landings.push(landing);700      writes.events.push(ProjectEventInput.Landed({ at: now, landing }));701702      const row = rowNow(h, writes);703704      if (Option.isSome(row)) {705        writes.project.set(706          "row",707          yield* kernel.policyAt(708            { ...row.value, landed: landing.sha },709            landing.sha,710            now711          )712        );713      }714    });715716  const textAt = (at: CommitSha, path: RepoPath) =>717    kernel718      .withPorts(719        RepoHost.use((host) =>720          host.readFile(repo, Revision.Commit({ sha: at }), path)721        )722      )723      .pipe(724        Effect.map((bytes) =>725          Option.match(bytes, {726            onNone: () => "",727            onSome: (read) => new TextDecoder().decode(read),728          })729        ),730        Effect.orElseSucceed(() => "")731      );732733  const putUp = (734    h: H,735    writes: W,736    input: {737      readonly evidence: readonly Evidence[];738      readonly now: DateTime.Utc;739      readonly paths: readonly RepoPath[];740      readonly policy: Policy;741      readonly proposed: Proposed;742      readonly row: ProjectRow;743    }744  ) => {745    const { now, policy, proposed } = input;746747    const decision = openDecision({748      deciders: decidersOn(policy, input.paths, input.row.initializer),749      evidence: input.evidence,750      expireDays: policy.budget.expireDays,751      id: DecisionId.make(minted("dec", decisionsNow(h, writes).length)),752      now,753      project: name,754      subject: DecisionSubject.cases.OpenProposal.make({755        proposal: proposed.proposal.id,756      }),757    });758759    writes.proposals.set(proposed.proposal.id, proposed.proposal);760    writes.decisions.set(decision.id, decision);761    emitted(writes, proposed.effects);762763    return { proposal: proposed.proposal };764  };765766  const startDraft = (767    h: H,768    writes: W,769    now: DateTime.Utc,770    input: {771      readonly by: Handle;772      readonly effects: readonly AttentionEffect[];773      readonly note: Option.Option<string>;774      readonly proposal: Proposal;775    }776  ) =>777    Effect.gen(function* () {778      const started = yield* Effect.fromResult(779        draft(780          input.proposal,781          DraftCommand.DraftStarted({782            by: input.by,783            ...Option.match(input.note, {784              onNone: () => ({}),785              onSome: (note) => ({ note }),786            }),787          }),788          now789        )790      );791792      const proposal = Option.getOrElse(793        Option.map(started, (moved) => moved.proposal),794        () => input.proposal795      );796797      writes.proposals.set(proposal.id, proposal);798      emitted(writes, input.effects);799800      if (801        proposal.draft !== undefined &&802        DraftState.guards.Drafting(proposal.draft)803      ) {804        writes.outbox.push(805          yield* draftRow(806            {807              ...Option.match(input.note, {808                onNone: () => ({}),809                onSome: (note) => ({ note }),810              }),811              project: name,812              proposal: proposal.id,813              round: proposal.draft.round,814            },815            now816          )817        );818      }819820      return { proposal };821    });822823  const proposalNow = (h: H, writes: W, id: ProposalId) =>824    Array.findFirst(proposalsNow(h, writes), (each) => each.id === id);825826  const decisionOf = (h: H, writes: W, proposal: ProposalId) =>827    Array.findLast(828      decisionsNow(h, writes),829      ({ subject }) =>830        DecisionSubject.guards.OpenProposal(subject) &&831        subject.proposal === proposal832    );833834  const draftBody =835    (caller: Person, input: Parameters<DeciderApi["draftAsk"]>[1]) =>836    (h: H, writes: W, now: DateTime.Utc) =>837      Effect.gen(function* () {838        const found = Option.all({839          live: liveOf(h),840          proposal: proposalNow(h, writes, input.proposal),841        });842843        if (Option.isNone(found)) {844          return yield* new UnknownProposal({ proposal: input.proposal });845        }846847        const { live, proposal } = found.value;848849        if (!mayDraft(live.policy, live.row, proposal, caller.handle)) {850          return yield* new NotDecider({});851        }852853        return yield* startDraft(h, writes, now, {854          by: caller.handle,855          effects: [],856          note: Option.fromUndefinedOr(input.note),857          proposal,858        });859      });860861  const settledBody =862    (input: {863      readonly proposal: ProposalId;864      readonly result: DraftResult;865      readonly round: number;866    }) =>867    (h: H, writes: W, now: DateTime.Utc) =>868      Effect.gen(function* () {869        const found = Option.all({870          live: liveOf(h),871          proposal: proposalNow(h, writes, input.proposal),872        });873874        if (Option.isNone(found)) {875          return;876        }877878        const { live, proposal } = found.value;879880        const moved = yield* Effect.fromResult(881          draft(882            proposal,883            DraftCommand.DraftSettled({884              result: input.result,885              round: input.round,886            }),887            now888          )889        ).pipe(Effect.orDie);890891        if (Option.isNone(moved)) {892          return;893        }894895        const settled = moved.value.proposal;896        const territory = Option.fromUndefinedOr(settled.territory);897898        const files = DraftResult.match(input.result, {899          Failed: (): readonly ComposedFile[] => [],900          Red: ({ files: drafted }) => drafted,901        });902903        const open = Option.filter(904          decisionOf(h, writes, settled.id),905          ({ decided }) => decided === undefined906        );907908        // A failed round that kept files keeps the decision that holds them.909        const kept = Option.filter(910          Option.map(open, ({ evidence: earlier }) =>911            earlier.filter(({ label }) => label !== draftFailedLabel)912          ),913          () =>914            DraftResult.guards.Failed(input.result) && settled.files.length > 0915        );916917        const evidence = [918          ...Option.getOrElse(kept, () =>919            evidenceOf({920              files,921              sealed: false,922              territory,923              want: settled.want,924            })925          ),926          ...moved.value.lines,927        ];928929        writes.proposals.set(settled.id, settled);930        emitted(writes, moved.value.effects);931932        // A settle moves only the round still drafting, so a replayed one counts nothing.933        writes.outbox.push(934          ...(yield* measuredRow(935            `drafted:${settled.id}:r${input.round}`,936            draftedPoints(proposal, input.result, now),937            now938          ))939        );940941        // The drafted files may lie under other maintainers than the want did.942        const decidedBy = decidersOn(943          live.policy,944          pathsOf(live.policy, settled.files, territory),945          live.row.initializer946        );947948        if (Option.isSome(open)) {949          writes.decisions.set(open.value.id, {950            ...open.value,951            deciders: decidedBy,952            evidence,953          });954955          return;956        }957958        const decision = openDecision({959          deciders: decidedBy,960          evidence,961          expireDays: live.policy.budget.expireDays,962          id: DecisionId.make(minted("dec", decisionsNow(h, writes).length)),963          now,964          project: name,965          subject: DecisionSubject.cases.OpenProposal.make({966            proposal: settled.id,967          }),968        });969970        writes.decisions.set(decision.id, decision);971      });972973  const proposalOf = (proposal: ProposalId) =>974    Effect.gen(function* () {975      const h = yield* kernel.read;976977      const found = Array.findFirst(h.proposals, ({ id }) => id === proposal);978979      if (Option.isNone(found)) {980        return yield* new UnknownProposal({ proposal });981      }982983      const evidence = Option.match(984        Array.findLast(985          h.decisions,986          ({ subject }) =>987            DecisionSubject.guards.OpenProposal(subject) &&988            subject.proposal === proposal989        ),990        { onNone: () => [], onSome: (decision) => decision.evidence }991      );992993      return {994        files: filesOf(found.value, evidence),995        proposal: found.value,996      };997    });998999  const openCountOf = (h: H, writes: W, handle: Handle) =>1000    proposalsNow(h, writes).filter(1001      ({ proposer, state }) => state === "open" && sameHandle(proposer, handle)1002    ).length;10031004  const proposeBody =1005    (caller: Person, input: Parameters<DeciderApi["proposeAsk"]>[1]) =>1006    (h: H, writes: W, now: DateTime.Utc) =>1007      Effect.gen(function* () {1008        const live = liveOf(h);10091010        // Nobody stands vouched before the project has a policy.1011        if (Option.isNone(live)) {1012          return yield* new NotVouched({});1013        }10141015        const { policy, row } = live.value;1016        const who = standing(policy, [], caller.handle);1017        const files = input.files ?? [];1018        const territory = Option.fromUndefinedOr(input.territory);10191020        const area = Option.map(territory, (named) =>1021          Option.getOrElse(1022            Option.map(moduleOf(policy, named), ({ module }) => module),1023            () => named1024          )1025        );10261027        const recordInArea = Option.match(area, {1028          onNone: () => 0,1029          onSome: (named) =>1030            recordOf({1031              asks: h.asks,1032              landings: h.landings,1033              now,1034              policy: policy.record,1035              reverted: new Set(),1036            })(caller.handle).filter((entry) => entry.area === named).length,1037        });10381039        const proposed = yield* Effect.fromResult(1040          propose(1041            policy,1042            ProposalCommand.Propose({1043              capped: capped(who),1044              denounced: who === "denounced",1045              files: files.map(({ path }) => path),1046              id: ProposalId.make(1047                minted("prop", proposalsNow(h, writes).length)1048              ),1049              openCount: openCountOf(h, writes, caller.handle),1050              project: name,1051              recordInArea,1052              sealed: Option.map(1053                Option.fromUndefinedOr(input.sealed),1054                ({ head }) => ({1055                  fork: workingFork(name, caller.handle),1056                  head,1057                })1058              ),1059              territory,1060              vouched: who === "vouched",1061              want: input.want,1062              who: caller,1063            }),1064            now1065          )1066        );10671068        if (input.draft === true) {1069          // A proposal just opened drafts its first round: nothing refuses it.1070          return yield* Effect.orDie(1071            startDraft(h, writes, now, {1072              by: caller.handle,1073              effects: proposed.effects,1074              note: Option.none(),1075              proposal: proposed.proposal,1076            })1077          );1078        }10791080        return putUp(h, writes, {1081          evidence: evidenceOf({1082            files,1083            sealed: input.sealed !== undefined,1084            territory,1085            want: input.want,1086          }),1087          now,1088          paths: pathsOf(1089            policy,1090            files.map(({ path }) => path),1091            territory1092          ),1093          policy,1094          proposed,1095          row,1096        });1097      });10981099  const flagBody =1100    (caller: Person, input: Parameters<DeciderApi["flagAsk"]>[1]) =>1101    (h: H, writes: W, now: DateTime.Utc) =>1102      Effect.gen(function* () {1103        const live = liveOf(h);1104        const ask = Option.fromUndefinedOr(h.asks.get(input.ask));11051106        if (Option.isNone(live) || Option.isNone(ask)) {1107          return yield* new UnknownAsk({ ask: input.ask });1108        }11091110        const { policy, row } = live.value;11111112        const proposed = yield* Effect.fromResult(1113          propose(1114            policy,1115            ProposalCommand.Flag({1116              ask: input.ask,1117              capped: capped(standing(policy, [], caller.handle)),1118              denounced: standing(policy, [], caller.handle) === "denounced",1119              id: ProposalId.make(1120                minted("prop", proposalsNow(h, writes).length)1121              ),1122              openCount: openCountOf(h, writes, caller.handle),1123              project: name,1124              reason: input.reason,1125              who: caller,1126            }),1127            now1128          )1129        ).pipe(1130          Effect.catchTag("NotVouched", () =>1131            Effect.die("a flag needs no vouch")1132          )1133        );11341135        return putUp(h, writes, {1136          evidence: [1137            { label: "ask", value: input.ask },1138            { label: "reason", value: input.reason },1139          ],1140          now,1141          paths: ask.value.territory.paths.map((glob) => RepoPath.make(glob)),1142          policy,1143          proposed,1144          row,1145        });1146      });11471148  const landFiles = (1149    h: H,1150    writes: W,1151    input: {1152      readonly author: Handle;1153      readonly credits: readonly Credit[];1154      readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;1155      readonly main: LandedSha;1156      readonly message: { readonly body: string; readonly subject: string };1157      readonly now: DateTime.Utc;1158      readonly prefix: string;1159    }1160  ) =>1161    Effect.gen(function* () {1162      const { files, main } = input;1163      const stale = new StaleBase({ base: main, conflicts: [], main });11641165      const composed = yield* kernel1166        .withPorts(1167          Lander.use((lander) => lander.compose({ files, main, repo }))1168        )1169        .pipe(Effect.mapError(() => stale));11701171      const requestId = RequestId.make(`${input.prefix}-${composed.tree}`);11721173      const landed = yield* kernel1174        .withPorts(1175          Lander.use((lander) =>1176            lander.land({1177              author: input.author,1178              main,1179              message: formatLanding({1180                assisted: [],1181                credits: input.credits,1182                requestId,1183                ...input.message,1184              }),1185              rebuild: Rebuild.Compose({ files }),1186              repo,1187              requestId,1188              tree: composed.tree,1189              verdict: Option.none(),1190            })1191          )1192        )1193        .pipe(1194          Effect.catchTags({1195            RepoBusy: () => Effect.fail(stale),1196            VerifierBlocked: () => Effect.fail(stale),1197          })1198        );11991200      yield* recordLanding(1201        h,1202        writes,1203        {1204          assisted: [],1205          author: input.author,1206          credits: input.credits,1207          landedAt: input.now,1208          parent: main,1209          project: name,1210          requestId,1211          sha: landed.sha,1212        },1213        input.now1214      );12151216      return landed.sha;1217    });12181219  const landVouch = (1220    h: H,1221    writes: W,1222    now: DateTime.Utc,1223    input: {1224      readonly by: Handle;1225      readonly handle: Handle;1226      readonly note: Option.Option<string>;1227      readonly verdict: "vouch" | "denounce";1228    }1229  ) =>1230    Effect.gen(function* () {1231      const live = liveOf(h);12321233      if (Option.isNone(live)) {1234        return yield* new NotDecider({});1235      }12361237      const { landed: main, policy } = live.value;1238      const { file } = policy.vouch;1239      const before = yield* textAt(main, file);1240      const after = vouchedText(before, input);12411242      if (after === before) {1243        return main;1244      }12451246      const said =1247        input.verdict === "vouch"1248          ? `Vouch for ${input.handle}`1249          : `Denounce ${input.handle}`;12501251      return yield* landFiles(h, writes, {1252        author: input.by,1253        credits: sameHandle(input.by, platformHandle)1254          ? []1255          : [{ handle: input.by, role: "Decided-by" }],1256        files: Array.of({ content: after, path: file }),1257        main,1258        message: {1259          body: Option.getOrElse(input.note, () => ""),1260          subject: said,1261        },1262        now,1263        prefix: "vouch",1264      });1265    });12661267  const revert = (1268    h: H,1269    writes: W,1270    now: DateTime.Utc,1271    input: {1272      readonly by: Handle;1273      readonly stray: Extract<DecisionSubject, { readonly _tag: "StrayPush" }>;1274    }1275  ) =>1276    Effect.gen(function* () {1277      const { after, before, ref } = input.stray;12781279      if (ref !== mainRef) {1280        yield* Effect.logWarning(1281          `a push to ${ref} was decided revert; only main is reverted`1282        );12831284        return;1285      }12861287      // Putting a deleted main back is a ref update the Lander can't make1288      // yet; the landed SHA still names it.1289      if (after === zeroId) {1290        yield* Effect.logError(1291          `canonical ${ref} was deleted; put it back at ${before} by hand`1292        );12931294        return;1295      }12961297      const commit = yield* kernel1298        .withPorts(RepoHost.use((host) => host.readCommit(repo, before)))1299        .pipe(Effect.orElseSucceed(() => Option.none()));13001301      if (Option.isNone(commit)) {1302        yield* Effect.logWarning(`no commit ${before} to revert to`);13031304        return;1305      }13061307      const credits: readonly Credit[] = sameHandle(input.by, platformHandle)1308        ? []1309        : [{ handle: input.by, role: "Decided-by" }];13101311      const requestId = RequestId.make(`revert-${after}`);13121313      const main = LandedSha.make(after);13141315      const message = withTrailer(1316        formatLanding({1317          assisted: [],1318          body: `A push the platform did not make moved ${ref} from ${before} to ${after}; this landing puts back the tree it replaced.`,1319          credits,1320          requestId,1321          subject: `Revert a push to ${ref}`,1322        }),1323        "Reverts",1324        after1325      );13261327      const landed = yield* kernel1328        .withPorts(1329          Lander.use((lander) =>1330            lander.land({1331              author: input.by,1332              main,1333              message,1334              rebuild: Rebuild.Existing({ commit: before }),1335              repo,1336              requestId,1337              tree: TreeSha.make(commit.value.tree),1338              verdict: Option.none(),1339            })1340          )1341        )1342        .pipe(Effect.option);13431344      if (Option.isNone(landed)) {1345        yield* Effect.logWarning(`the revert of ${after} did not land`);13461347        return;1348      }13491350      yield* recordLanding(1351        h,1352        writes,1353        {1354          assisted: [],1355          author: input.by,1356          credits,1357          landedAt: now,1358          parent: main,1359          project: name,1360          requestId,1361          sha: landed.value.sha,1362        },1363        now1364      );1365    });13661367  const adopt = (1368    h: H,1369    writes: W,1370    now: DateTime.Utc,1371    input: {1372      readonly by: Handle;1373      readonly stray: Extract<DecisionSubject, { readonly _tag: "StrayPush" }>;1374    }1375  ) => {1376    const { after, before, ref } = input.stray;13771378    if (after === zeroId) {1379      return Effect.logError(1380        `canonical ${ref} was deleted; a deleted ${ref} cannot be adopted, so the landed SHA stays`1381      );1382    }13831384    return ref === mainRef1385      ? recordLanding(1386          h,1387          writes,1388          {1389            assisted: [],1390            author: input.by,1391            credits: [{ handle: input.by, role: "Decided-by" }],1392            landedAt: now,1393            parent: LandedSha.make(before),1394            project: name,1395            sha: LandedSha.make(after),1396          },1397          now1398        )1399      : Effect.void;1400  };14011402  const advanceAndRun = (1403    h: H,1404    writes: W,1405    now: DateTime.Utc,1406    requestId: RequestId,1407    command: LandingCommand1408  ) =>1409    Effect.gen(function* () {1410      const advanced = yield* kernel.advance(1411        h,1412        writes,1413        now,1414        requestId,1415        command1416      );14171418      if (Array.isReadonlyArrayNonEmpty(advanced.effects)) {1419        writes.outbox.push(yield* startRow(requestId, now));1420      }14211422      return advanced;1423    });14241425  const awaitingFinish = (h: H, ask: AskId) =>1426    Array.findFirst(1427      h.answers,1428      ({ record, row }) =>1429        row.ask === ask && LandingState.guards.AwaitingFinish(record.landing)1430    );14311432  const answerWaits = (1433    h: H,1434    writes: W,1435    now: DateTime.Utc,1436    input: {1437      readonly by: Handle;1438      readonly choice: Choice;1439      readonly decision: Decision;1440    }1441  ) =>1442    Option.isNone(answerDecisionOf(input.decision.subject))1443      ? Effect.void1444      : Effect.forEach(1445          h.answers.filter(1446            ({ record }) =>1447              LandingState.guards.AwaitingDecision(record.landing) &&1448              record.landing.decisions.some(1449                ({ id }) => id === input.decision.id1450              )1451          ),1452          ({ row }) =>1453            advanceAndRun(1454              h,1455              writes,1456              now,1457              row.requestId,1458              LandingCommand.Decided({1459                by: input.by,1460                choice: input.choice,1461                decision: input.decision.id,1462              })1463            ),1464          { discard: true }1465        );14661467  const finishAt = (1468    h: H,1469    writes: W,1470    now: DateTime.Utc,1471    input: {1472      readonly ask: AskId;1473      readonly by: Handle;1474      readonly head: CommitSha;1475    }1476  ) =>1477    Option.match(1478      Option.filter(1479        awaitingFinish(h, input.ask),1480        ({ row }) => row.head === input.head1481      ),1482      {1483        onNone: () => Effect.void,1484        onSome: ({ row }) =>1485          Effect.asVoid(1486            advanceAndRun(1487              h,1488              writes,1489              now,1490              row.requestId,1491              LandingCommand.Finished({ by: input.by })1492            )1493          ),1494      }1495    );14961497  const accept = (1498    h: H,1499    writes: W,1500    now: DateTime.Utc,1501    input: {1502      readonly by: Handle;1503      readonly decision: Decision;1504      readonly proposal: ProposalId;1505    }1506  ) =>1507    Effect.gen(function* () {1508      const found = Array.findFirst(1509        proposalsNow(h, writes),1510        ({ id }) => id === input.proposal1511      );15121513      if (Option.isNone(found) || found.value.state !== "open") {1514        return;1515      }15161517      const proposal = found.value;1518      const files = filesOf(proposal, input.decision.evidence);15191520      const held: Option.Option<Array.NonEmptyReadonlyArray<ComposedFile>> =1521        Array.isReadonlyArrayNonEmpty(files)1522          ? Option.some(files)1523          : Option.none();15241525      const opening = Option.all({ ask: askIdOf(files), files: held });15261527      const toOpen = Option.filter(opening, () => proposal.flags === undefined);15281529      const refused: Option.Option<FinalOpenRefusal> = yield* Option.match(1530        toOpen,1531        {1532          onNone: () => Effect.succeedNone,1533          onSome: ({ ask, files: proposed }) =>1534            kernel1535              .open(h, writes, now, {1536                ask,1537                asker: proposal.proposer,1538                assisted: assistedBy(input.decision.evidence),1539                credits: [1540                  { handle: proposal.proposer, role: "Asked-by" },1541                  { handle: input.by, role: "Decided-by" },1542                ],1543                decider: Person.make({ handle: input.by }),1544                files: proposed,1545              })1546              .pipe(1547                Effect.as(Option.none<FinalOpenRefusal>()),1548                Effect.catchTags({1549                  IncompleteBrief: declines,1550                  NotDecider: declines,1551                  NotRedFirst: declines,1552                  TouchedJudge: declines,1553                  WeakCheck: declines,1554                })1555              ),1556        }1557      );15581559      if (Option.isSome(refused)) {1560        yield* Effect.logWarning(1561          `proposal ${proposal.id} was accepted, and its ask could not open`,1562          refused.value1563        );1564      }15651566      writes.proposals.set(proposal.id, {1567        ...proposal,1568        state: Option.isSome(refused) ? "declined" : "accepted",1569      });1570    });15711572  const goAhead = (1573    h: H,1574    writes: W,1575    now: DateTime.Utc,1576    input: { readonly by: Handle; readonly subject: DecisionSubject }1577  ): Effect.Effect<void> =>1578    DecisionSubject.match(input.subject, {1579      Finish: ({ ask, head }) =>1580        finishAt(h, writes, now, { ask, by: input.by, head }),1581      // The proposal's `OpenAsk` effect opens it.1582      OpenProposal: () => Effect.void,1583      // The answer waiting on it is told (`answerWaits`).1584      PostureChange: () => Effect.void,1585      // The env proxy and the value store are the visibility cartridge's.1586      ProxyWidened: () => Effect.void,1587      RaiseRatchet: () => Effect.void,1588      SecretInTree: () => Effect.void,1589      StrayPush: (stray) => adopt(h, writes, now, { by: input.by, stray }),1590      Vouch: ({ handle }) =>1591        landVouch(h, writes, now, {1592          by: input.by,1593          handle,1594          note: Option.none(),1595          verdict: "vouch",1596        }).pipe(1597          Effect.asVoid,1598          Effect.catchTags({1599            NotDecider: (refused) => unlanded(handle, refused),1600            StaleBase: (refused) => unlanded(handle, refused),1601          })1602        ),1603      Waiver: () => Effect.void,1604    });16051606  const settleDecided = (h: H, writes: W, now: DateTime.Utc, taken: Decided) =>1607    Effect.gen(function* () {1608      const { decision } = taken;1609      const { decided } = decision;16101611      if (decided === undefined) {1612        return;1613      }16141615      const { by, choice } = decided;16161617      yield* Effect.forEach(1618        taken.effects,1619        (effect) =>1620          AttentionEffect.$match(effect, {1621            Emit: ({ event }) => Effect.sync(() => writes.events.push(event)),1622            Land: ({ subject }) => goAhead(h, writes, now, { by, subject }),1623            OpenAsk: ({ proposal }) =>1624              accept(h, writes, now, { by, decision, proposal }),1625            Revert: () =>1626              DecisionSubject.guards.StrayPush(decision.subject)1627                ? revert(h, writes, now, { by, stray: decision.subject })1628                : Effect.void,1629            // The alarm is set once settled, to the earliest deadline of all.1630            SetAlarm: () => Effect.void,1631          }),1632        { discard: true }1633      );16341635      // A proposal a person declined closes; one that expired already has.1636      if (DecisionSubject.guards.OpenProposal(decision.subject)) {1637        const { proposal } = decision.subject;16381639        const open = Array.findFirst(1640          proposalsNow(h, writes),1641          ({ id, state }) => id === proposal && state === "open"1642        );16431644        if (1645          Option.isSome(open) &&1646          (choice === "decline" || choice === "revert")1647        ) {1648          writes.proposals.set(proposal, { ...open.value, state: "declined" });1649        }1650      }16511652      yield* answerWaits(h, writes, now, { by, choice, decision });1653    });16541655  const decideBody =1656    (caller: Person, input: Parameters<DeciderApi["decide"]>[1]) =>1657    (h: H, writes: W, now: DateTime.Utc) =>1658      Effect.gen(function* () {1659        const by = Option.getOrElse(1660          Option.flatMap(h.policy, (policy) =>1661            asDecider(policy, caller.handle)1662          ),1663          () => caller.handle1664        );16651666        const taken = yield* Effect.fromResult(1667          decide(decisionsNow(h, writes), {1668            by,1669            choice: input.choice,1670            id: input.decision,1671            note: Option.fromUndefinedOr(input.note),1672            now,1673          })1674        );16751676        writes.decisions.set(taken.decision.id, taken.decision);1677        spent(h, writes, { decider: by, now, on: "decision" });16781679        yield* settleDecided(h, writes, now, taken);16801681        return { decision: taken.decision };1682      });16831684  const expire = (h: H, writes: W, now: DateTime.Utc) =>1685    Effect.gen(function* () {1686      const proposals = proposalsNow(h, writes);1687      const expired = expireProposals(proposals, now).proposals;16881689      for (const [index, proposal] of expired.entries()) {1690        if (proposal !== proposals[index]) {1691          writes.proposals.set(proposal.id, proposal);1692        }1693      }16941695      yield* Effect.forEach(1696        decisionsNow(h, writes),1697        (decision) => {1698          const { decisions, effects } = expireDecisions([decision], now);1699          const [defaulted] = decisions;17001701          if (defaulted === undefined || defaulted === decision) {1702            return Effect.void;1703          }17041705          writes.decisions.set(defaulted.id, defaulted);17061707          // A default is its subject's no (`defaultChoice`), so an1708          // expiry never opens an ask, and opening's refusals never arise.1709          return settleDecided(h, writes, now, {1710            decision: defaulted,1711            effects,1712          }).pipe(Effect.orDie);1713        },1714        { discard: true }1715      );1716    });17171718  const finishBody =1719    (caller: Person, input: Parameters<DeciderApi["finish"]>[1]) =>1720    (h: H, writes: W, now: DateTime.Utc) =>1721      Effect.gen(function* () {1722        const live = liveOf(h);1723        const ask = Option.fromUndefinedOr(h.asks.get(input.ask));17241725        const decides = Option.exists(1726          Option.all({ ask, live }),1727          ({ ask: asked, live: { policy } }) =>1728            decidesOn(policy, asked, caller.handle)1729        );17301731        if (Option.isNone(live) || !decides) {1732          return yield* new NotDecider({});1733        }17341735        const { landed: main, policy } = live.value;17361737        // The maintainer as the policy spells them, as `decide` and Today do:1738        // the budget row and the credit name one person however they sign in.1739        const by = Option.getOrElse(1740          asDecider(policy, caller.handle),1741          () => caller.handle1742        );17431744        const receiptOf = (1745          outcome: Outcome,1746          requestId = input.requestId1747        ): AnswerReceipt => ({1748          ask: input.ask,1749          base: input.base,1750          head: input.head,1751          outcome,1752          project: name,1753          requestId,1754        });17551756        // The same finish again: the request it queued, as it stands.1757        const queued = Array.findFirst(1758          h.answers,1759          ({ row }) =>1760            row.requestId === input.requestId && row.ask === input.ask1761        );17621763        if (Option.isSome(queued)) {1764          return receiptOf(outcomeOf(queued.value.record.landing));1765        }17661767        const waiting = awaitingFinish(h, input.ask);17681769        if (Option.isNone(waiting)) {1770          const answered = Array.findFirst(1771            h.answers,1772            ({ row }) => row.ask === input.ask && row.head === input.head1773          );17741775          return yield* Option.match(answered, {1776            onNone: () =>1777              Effect.fail(1778                new StaleBase({ base: input.base, conflicts: [], main })1779              ),1780            onSome: ({ record }) =>1781              Effect.succeed(receiptOf(outcomeOf(record.landing))),1782          });1783        }17841785        const { record, row } = waiting.value;1786        const { request } = record.landing;17871788        spent(h, writes, { decider: by, now, on: "finish" });17891790        if (input.head === request.head) {1791          const advanced = yield* advanceAndRun(1792            h,1793            writes,1794            now,1795            row.requestId,1796            LandingCommand.Finished({ by })1797          );17981799          return receiptOf(advanced.outcome);1800        }18011802        const stale = new StaleBase({ base: input.base, conflicts: [], main });18031804        const facts = yield* kernel1805          .withPorts(1806            pushFacts({1807              ask,1808              base: input.base,1809              claim: Option.none(),1810              claimsHeld: 0,1811              head: input.head,1812              landed: main,1813              policy,1814              project: name,1815              pusher: caller,1816              ref: mainRef,1817              repo: request.fork,1818            })1819          )1820          .pipe(1821            Effect.catchTags({1822              MissingCommit: () => Effect.fail(stale),1823              RepoNotFound: () => Effect.fail(stale),1824            })1825          );18261827        const stageOne = yield* scan.run(facts);1828        const judged = Array.findFirst(stageOne, isTouchedJudge);18291830        if (Option.isSome(judged)) {1831          return yield* new TouchedJudge({1832            paths: Match.value(judged.value).pipe(1833              Match.tag("TouchedJudge", ({ paths }) => paths),1834              Match.orElse(() => Array.of(RepoPath.make(mainRef)))1835            ),1836          });1837        }18381839        if (Array.isReadonlyArrayNonEmpty(stageOne)) {1840          return receiptOf(Outcome.cases.Refused.make({ refusals: stageOne }));1841        }18421843        return yield* kernel.enqueue(1844          writes,1845          {1846            ...request,1847            base: input.base,1848            credits: [...request.credits, { handle: by, role: "Finished-by" }],1849            head: input.head,1850            requestId: input.requestId,1851          },1852          { ask: input.ask, main, now }1853        );1854      });18551856  const carry = (1857    input: {1858      readonly env: UnlandedRunEnv;1859      readonly lanes: readonly CheckLane[];1860      readonly landings: AnswerQueue["landings"];1861      readonly message: string;1862      readonly now: DateTime.Utc;1863      readonly run: RunBlock;1864    },1865    step: Step,1866    turns: number1867  ): Effect.Effect<LandingState, never, DeciderPorts> =>1868    Effect.gen(function* () {1869      const next = step.effects.find(isStep);18701871      if (next === undefined || turns === 0) {1872        return step.state;1873      }18741875      const run: AnswerRun = {1876        admitted: true,1877        env: input.env,1878        finish: "optional",1879        lanes: input.lanes,1880        message: input.message,1881        repo,1882        run: input.run,1883        state: step.state,1884      };18851886      const reported = yield* runStep(run, next, input.landings);18871888      if (Option.isNone(reported)) {1889        return step.state;1890      }18911892      return yield* carry(1893        input,1894        transition(step.state, reported.value.command, input.now),1895        turns - 11896      );1897    });18981899  const landBody =1900    (1901      queue: AnswerQueue,1902      caller: Person,1903      input: Parameters<DeciderApi["land"]>[1]1904    ) =>1905    (h: H, writes: W, now: DateTime.Utc) =>1906      Effect.gen(function* () {1907        const live = liveOf(h);19081909        if (1910          Option.isNone(live) ||1911          !isDecider(live.value.policy, caller.handle)1912        ) {1913          return yield* new NotDecider({});1914        }19151916        const { landed: main, policy } = live.value;19171918        const receiptOf = (outcome: Outcome): LandReceipt => ({1919          base: input.base,1920          head: input.head,1921          outcome,1922          project: name,1923          requestId: input.requestId,1924        });19251926        // The same request again: the landing it made.1927        const earlier = Array.findFirst(1928          h.landings,1929          ({ author, requestId }) =>1930            requestId === input.requestId && sameHandle(author, caller.handle)1931        );19321933        if (Option.isSome(earlier)) {1934          return receiptOf(1935            Outcome.cases.Landed.make({ sha: earlier.value.sha })1936          );1937        }19381939        const fork = workingFork(name, caller.handle);1940        const stale = new StaleBase({ base: input.base, conflicts: [], main });19411942        const facts = yield* kernel1943          .withPorts(1944            pushFacts({1945              ask: Option.none(),1946              base: input.base,1947              claim: Option.none(),1948              claimsHeld: 0,1949              head: input.head,1950              landed: main,1951              policy,1952              project: name,1953              pusher: caller,1954              ref: mainRef,1955              repo: fork,1956            })1957          )1958          .pipe(1959            Effect.catchTags({1960              MissingCommit: () => Effect.fail(stale),1961              RepoNotFound: () => Effect.fail(stale),1962            }),1963            Effect.flatMap(kernel.withLayers)1964          );19651966        if (1967          facts.changes.some(1968            ({ path }) =>1969              !decidersFor(policy, [path]).some((each) =>1970                sameHandle(each, caller.handle)1971              )1972          )1973        ) {1974          return yield* new NotDecider({});1975        }19761977        // Stages 0–1, minus the touched-judge refusal: a maintainer may change the judge where they decide.1978        const gate = yield* runGate(pushStages, facts);19791980        const refusals = Option.match(gate, {1981          onNone: () => [],1982          onSome: (all) => all.filter((refusal) => !isTouchedJudge(refusal)),1983        });19841985        if (Array.isReadonlyArrayNonEmpty(refusals)) {1986          return receiptOf(Outcome.cases.Refused.make({ refusals }));1987        }19881989        const credits: readonly Credit[] = [1990          { handle: caller.handle, role: "Signed-off-by" },1991        ];19921993        const request: Request = {1994          answerer: caller.handle,1995          ask: Option.none(),1996          assisted: [],1997          base: input.base,1998          credits,1999          fork,2000          head: input.head,

The first 2,000 of 2,213 lines.