Merge build/214-project-service-core: one project runs open → claim → push → answer → land over memory adapters
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents c5f1296, 1e18284 · Browse files · 17 files·+5936 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+5936 added−10 removed
- tests:+1548 added−10 removed
- other:+4388 added−0 removed
Provenance
- Commit
4ede6c4- Tree
29fa0d3- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
c5f1296- Parent 2
1e18284
17 files changed+5936 added−10 removed
added:packages/project/src/alarms/memory.ts+28 added
12345678910111213141516171819202122232425262728/** * `Alarms` in memory, for tests: like a Durable Object it holds one alarm, * the one set last, which the service always computes as its earliest * pending deadline. Nothing fires by itself: a test reads `ScheduledAlarm`, * moves the TestClock there, and calls the project's `onAlarm`. */import { Context, Effect, Layer, Option, Ref } from "effect";import type { DateTime } from "effect";
import { Alarms } from "../alarms.ts";
/** When the memory alarm is set to go off, if it is set. */export class ScheduledAlarm extends Context.Service< ScheduledAlarm, { readonly at: Effect.Effect<Option.Option<DateTime.Utc>> }>()("project/ScheduledAlarm") {}
/** A fresh alarm each time the layer is built, and the reading of it. */export const AlarmsMemory: Layer.Layer<Alarms | ScheduledAlarm> = Layer.effectContext( Effect.gen(function* () { const alarm = yield* Ref.make(Option.none<DateTime.Utc>());
return Context.make(Alarms, { set: (at) => Ref.set(alarm, Option.some(at)), }).pipe(Context.add(ScheduledAlarm, { at: Ref.get(alarm) })); }) );added:packages/project/src/answer-runs/inline.ts+56 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556/** * `AnswerRuns` in process, for tests and W2: `start` drives the answer's * steps (merge, checks, land) through the project's own answer queue until * the answer lands, is refused, or waits (on a person, the landing slot, or * a retry the project's alarm starts again). A run already under way for the * same request is not started twice. */import type { CheckRunner } from "@repo/checks/check-runner";import type { RequestId } from "@repo/protocol/ids";import { Effect, Layer, Ref } from "effect";
import { AnswerRuns } from "../answer-runs.ts";import type { Lander } from "../lander.ts";import { drive } from "./steps.ts";
export const AnswerRunsInline: Layer.Layer< AnswerRuns, never, CheckRunner | Lander> = Layer.effect( AnswerRuns, Effect.gen(function* () { const ports = yield* Effect.context<CheckRunner | Lander>(); const running = yield* Ref.make<ReadonlySet<RequestId>>(new Set());
const claimRun = (requestId: RequestId) => Ref.modify(running, (under) => under.has(requestId) ? [false, under] : [true, new Set(under).add(requestId)] );
const endRun = (requestId: RequestId) => Ref.update(running, (under) => { const rest = new Set(under);
rest.delete(requestId);
return rest; });
return AnswerRuns.of({ start: (requestId, queue) => Effect.gen(function* () { if (!(yield* claimRun(requestId))) { return; }
yield* drive(queue, requestId).pipe( Effect.provideContext(ports), Effect.ensuring(endRun(requestId)) ); }), }); }));added:packages/project/src/answer-runs/steps.ts+332 added
1+/**2+ * An answer run's steps, as Effect programs over the ports. Each port call a3+ * `LandingEffect` names becomes the `LandingCommand` that reports it: a4+ * merge, the checks on the exact merged tree, or the land on main. A step5+ * decides nothing: the landing lifecycle does, in the project's6+ * `advanceAnswer`, and the gate classifies a failing lane.7+ *8+ * The inline adapter drives them in a loop (`drive`); the Answer Workflow9+ * (W3 304) runs each as a durable step.10+ */11+import { CheckAt, CheckRunner } from "@repo/checks/check-runner";12+import type { CheckLane, CheckRun } from "@repo/checks/check-runner";13+import { classifyFailure } from "@repo/gate/classify";14+import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";15+import { LandedSha } from "@repo/protocol/ids";16+import type { LaneName, RepoPath, RequestId } from "@repo/protocol/ids";17+import type { Refusal, VerifierBlocked } from "@repo/protocol/refusal";18+import { Array, Effect, Option } from "effect";19+20+import type { AnswerQueue, AnswerReport, AnswerRun } from "../answer-runs.ts";21+import { Lander, Rebuild } from "../lander.ts";22+import {23+ LandingCommand,24+ LandingEffect,25+ LandingState,26+ pendingEffects,27+} from "../landing.ts";28+29+/** A step's result: the command it reports, and what it saw beside it. */30+export interface Reported {31+ readonly command: LandingCommand;32+ readonly report?: AnswerReport;33+}34+35+/** Whether an effect is a port call a run makes, rather than the project's to settle. */36+export const isStep = (effect: LandingEffect) =>37+ LandingEffect.$is("Merge")(effect) ||38+ LandingEffect.$is("RunChecks")(effect) ||39+ LandingEffect.$is("Land")(effect);40+41+/**42+ * The port calls a run makes now: the one its state waits on, except a43+ * land, which runs only while the request holds the project's landing slot.44+ */45+export const nextSteps = (run: AnswerRun): readonly LandingEffect[] =>46+ LandingState.guards.Landing(run.state) && !run.admitted47+ ? []48+ : pendingEffects(run.state);49+50+/** The attempt a port's `Busy` or `Blocked` report is about: the state's own. */51+const attemptOf = (state: LandingState) =>52+ LandingState.matchOrElse(53+ state,54+ {55+ Checking: ({ attempt }) => attempt,56+ Landing: ({ attempt }) => attempt,57+ Merging: ({ attempt }) => attempt,58+ },59+ () => 060+ );61+62+const reported = (command: LandingCommand, report?: AnswerReport): Reported =>63+ report === undefined ? { command } : { command, report };64+65+/** The answer's head merged onto `main`: the tree to check, or the paths that conflict. */66+const merge = (67+ run: AnswerRun,68+ step: Extract<LandingEffect, { readonly _tag: "Merge" }>69+) =>70+ Lander.use((lander) =>71+ lander.merge({72+ base: step.base,73+ fork: step.fork,74+ head: step.head,75+ main: step.main,76+ repo: run.repo,77+ })78+ ).pipe(79+ Effect.map(({ changes, tree }) =>80+ reported(LandingCommand.Merged({ changes, main: step.main, tree }))81+ ),82+ Effect.catchTags({83+ StaleBase: ({ conflicts }) =>84+ Effect.succeed(85+ reported(LandingCommand.MergeConflict({ conflicts, main: step.main }))86+ ),87+ VerifierBlocked: () =>88+ Effect.succeed(89+ reported(LandingCommand.Blocked({ attempt: attemptOf(run.state) }))90+ ),91+ })92+ );93+94+/** Each lane's result in a run, by lane. */95+const resultsOf = (run: CheckRun): ReadonlyMap<LaneName, LaneResult> =>96+ new Map(run.lanes.map((lane) => [lane.lane, lane]));97+98+const isTrouble = (result: LaneOutcome) =>99+ result === "flaked" || result === "blocked";100+101+/** Where a lane's log is kept when its run named no place: by request and lane. */102+const logRefOf = (requestId: RequestId, lane: LaneName) =>103+ `${requestId}/${lane}`;104+105+/**106+ * The checks on the exact merged tree, every lane every time. A lane that107+ * did not pass is classified by the gate: a checker that never started gets108+ * one fresh run, and a project lane is run on main too, since a lane red on109+ * main is the gate's trouble, not the answer's. The ask's own check is red110+ * on main by design, so it counts as passing there.111+ */112+const checks = (113+ run: AnswerRun,114+ checking: Extract<LandingState, { readonly _tag: "Checking" }>115+): Effect.Effect<Reported, VerifierBlocked, CheckRunner> =>116+ Effect.gen(function* () {117+ const runner = yield* CheckRunner;118+ const { request } = checking;119+120+ const job = (at: CheckAt, lanes: readonly CheckLane[]) =>121+ runner.run({122+ at,123+ lanes,124+ placeholders: [],125+ project: request.project,126+ proxies: [],127+ repo: run.repo,128+ });129+130+ const lanesNamed = (names: ReadonlySet<LaneName>) =>131+ run.lanes.filter(({ lane }) => names.has(lane));132+133+ const onTree = CheckAt.cases.Tree.make({ tree: checking.tree });134+ const merged = yield* job(onTree, run.lanes);135+ const failing = merged.lanes.filter(({ result }) => result !== "passed");136+137+ const troubled = new Set(138+ failing.filter(({ result }) => isTrouble(result)).map(({ lane }) => lane)139+ );140+141+ const onMainNeeded = new Set(142+ failing.map(({ lane }) => lane).filter((lane) => lane !== run.askLane)143+ );144+145+ const rerun =146+ troubled.size === 0147+ ? new Map<LaneName, LaneResult>()148+ : resultsOf(yield* job(onTree, lanesNamed(troubled)));149+150+ const onMain =151+ onMainNeeded.size === 0152+ ? new Map<LaneName, LaneResult>()153+ : resultsOf(154+ yield* job(155+ CheckAt.cases.Commit.make({ commit: checking.main }),156+ lanesNamed(onMainNeeded)157+ )158+ );159+160+ const changed = new Set<RepoPath>(checking.changes.map(({ path }) => path));161+162+ const refusals = Array.getSomes(163+ failing.map((lane) =>164+ classifyFailure(165+ {166+ command: lane.command,167+ failingPaths: [],168+ isDoctor: false,169+ lane: lane.lane,170+ logRef: lane.logRef ?? logRefOf(request.requestId, lane.lane),171+ onMain: onMainNeeded.has(lane.lane)172+ ? (onMain.get(lane.lane)?.result ?? "blocked")173+ : "passed",174+ onMerged: lane.result,175+ rerun: Option.map(176+ Option.fromUndefinedOr(rerun.get(lane.lane)),177+ ({ result }) => result178+ ),179+ },180+ changed,181+ { base: request.base, main: checking.main }182+ )183+ )184+ );185+186+ const lanes = merged.lanes.map((lane) => rerun.get(lane.lane) ?? lane);187+188+ return reported(189+ LandingCommand.Checked({190+ decisions: [],191+ finish: run.finish,192+ refusals: refusals satisfies readonly Refusal[],193+ tree: checking.tree,194+ }),195+ { heldBack: merged.heldBack, lanes }196+ );197+ });198+199+/**200+ * The checked tree landed on main as the platform's commit, with the201+ * message the project wrote. A moved main sends it back to merge; a busy202+ * repo or a blocked Lander waits and tries again.203+ */204+const land = (205+ run: AnswerRun,206+ landing: Extract<LandingState, { readonly _tag: "Landing" }>,207+ message: string208+) =>209+ Lander.use((lander) =>210+ lander.land({211+ author: landing.request.answerer,212+ main: landing.main,213+ message,214+ rebuild: Rebuild.Merge({215+ base: landing.request.base,216+ fork: landing.request.fork,217+ head: landing.request.head,218+ }),219+ repo: run.repo,220+ requestId: landing.request.requestId,221+ tree: landing.tree,222+ verdict: Option.fromUndefinedOr(run.verdict),223+ })224+ ).pipe(225+ Effect.map(({ pending, sha }) =>226+ reported(227+ LandingCommand.LandedOk({ sha }),228+ Array.isReadonlyArrayNonEmpty(pending) ? { pending } : undefined229+ )230+ ),231+ Effect.catchTags({232+ RepoBusy: () =>233+ Effect.succeed(234+ reported(LandingCommand.Busy({ attempt: landing.attempt }))235+ ),236+ StaleBase: ({ main }) =>237+ Effect.succeed(238+ reported(239+ LandingCommand.MainMoved({240+ from: landing.main,241+ main: LandedSha.make(main),242+ })243+ )244+ ),245+ VerifierBlocked: () =>246+ Effect.succeed(247+ reported(LandingCommand.Blocked({ attempt: landing.attempt }))248+ ),249+ })250+ );251+252+/**253+ * One step: the port call `effect` names, run for `run`, and the command254+ * that reports it. `None` when the run's state no longer waits on that call255+ * (a replay after the state moved on).256+ */257+export const runStep = (258+ run: AnswerRun,259+ effect: LandingEffect260+): Effect.Effect<Option.Option<Reported>, never, CheckRunner | Lander> =>261+ LandingEffect.$match(effect, {262+ Emit: () => Effect.succeedNone,263+ Land: () =>264+ LandingState.guards.Landing(run.state) && run.message !== undefined265+ ? Effect.asSome(land(run, run.state, run.message))266+ : Effect.succeedNone,267+ Merge: (merging) => Effect.asSome(merge(run, merging)),268+ Record: () => Effect.succeedNone,269+ Retry: () => Effect.succeedNone,270+ RunChecks: () =>271+ LandingState.guards.Checking(run.state)272+ ? checks(run, run.state).pipe(273+ Effect.catchTag("VerifierBlocked", () =>274+ Effect.succeed(275+ reported(276+ LandingCommand.Blocked({ attempt: attemptOf(run.state) })277+ )278+ )279+ ),280+ Effect.asSome281+ )282+ : Effect.succeedNone,283+ });284+285+/**286+ * Carries one answer as far as it goes now: runs the step its state waits287+ * on, reports it, and goes on with the steps the report returns, until the288+ * answer lands, is refused, waits on a person or the queue, or must wait for289+ * a retry (the project's alarm starts it again).290+ */291+export const drive = (292+ queue: AnswerQueue,293+ requestId: RequestId294+): Effect.Effect<void, never, CheckRunner | Lander> => {295+ const go = (296+ steps: readonly LandingEffect[]297+ ): Effect.Effect<void, never, CheckRunner | Lander> =>298+ Effect.gen(function* () {299+ const effect = steps.find(isStep);300+301+ if (effect === undefined || steps.some(LandingEffect.$is("Retry"))) {302+ return;303+ }304+305+ const run = yield* queue.answer(requestId);306+307+ if (Option.isNone(run)) {308+ return;309+ }310+311+ const step = yield* runStep(run.value, effect);312+313+ if (Option.isNone(step)) {314+ return;315+ }316+317+ const advanced = yield* queue.advanceAnswer(318+ requestId,319+ step.value.command,320+ step.value.report321+ );322+323+ yield* go(advanced.effects);324+ });325+326+ return Effect.flatMap(queue.answer(requestId), (run) =>327+ Option.match(run, {328+ onNone: () => Effect.void,329+ onSome: (found) => go(nextSteps(found)),330+ })331+ );332+};added:packages/project/src/projection/memory.ts+46 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546/** * `Projection` in memory, for tests: it keeps every row it was given, once * per row id, in the order it first took them, and reads them back as the * events they carry. */import { Context, Effect, Layer, Ref, Schema } from "effect";
import type { OutboxRow } from "../project-store/rows.ts";import { Projection, ProjectedEvent } from "../projection.ts";
const decodeProjected = Schema.decodeUnknownEffect(ProjectedEvent);
/** What the memory projection has taken so far. */export class ProjectedRows extends Context.Service< ProjectedRows, { readonly events: Effect.Effect<readonly ProjectedEvent[]> }>()("project/ProjectedRows") {}
/** A fresh, empty projection each time the layer is built, and its reading. */export const ProjectionMemory: Layer.Layer<Projection | ProjectedRows> = Layer.effectContext( Effect.gen(function* () { const taken = yield* Ref.make<ReadonlyMap<string, OutboxRow>>(new Map());
return Context.make(Projection, { apply: (rows) => Ref.update(taken, (kept) => { const next = new Map(kept);
for (const row of rows) { next.set(row.id, next.get(row.id) ?? row); }
return next; }), }).pipe( Context.add(ProjectedRows, { events: Effect.flatMap(Ref.get(taken), (kept) => Effect.forEach([...kept.values()], (row) => Effect.orDie(decodeProjected(row.body)) ) ), }) ); }) );added:packages/project/src/projects/memory.ts+63 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263/** * `Projects` in memory: each project is one service over its own * `ProjectStoreMemory`, built when the project is made and kept in a `Ref` * the layer makes (never in a module-level variable). Every project shares * the other ports the layer is given. */import type { ProjectName } from "@repo/protocol/ids";import { ProjectExists, UnknownProject } from "@repo/protocol/refusal";import { Context, Effect, Layer, Option, SynchronizedRef } from "effect";
import type { ProjectStore } from "../project-store.ts";import { ProjectStoreMemory } from "../project-store/memory.ts";import { projectService } from "../project.ts";import type { ProjectApi, ProjectPorts } from "../project.ts";import { Projects } from "../projects.ts";
export const ProjectsMemory: Layer.Layer< Projects, never, Exclude<ProjectPorts, ProjectStore>> = Layer.effect( Projects, Effect.gen(function* () { const ports = yield* Effect.context<Exclude<ProjectPorts, ProjectStore>>(); const scope = yield* Effect.scope;
const made = yield* SynchronizedRef.make< ReadonlyMap<ProjectName, ProjectApi> >(new Map());
/** A new project's service, over a store of its own that lives as long as the layer. */ const build = (project: ProjectName) => Effect.gen(function* () { // Fresh, or the build would reuse a store an enclosing layer made. const store = yield* Layer.buildWithScope( Layer.fresh(ProjectStoreMemory), scope );
return yield* projectService(project).pipe( Effect.provideContext(Context.merge(ports, store)) ); });
return Projects.of({ create: (project) => SynchronizedRef.modifyEffect(made, (projects) => projects.has(project) ? Effect.fail(new ProjectExists({ project })) : Effect.map( build(project), (api) => [api, new Map(projects).set(project, api)] as const ) ), get: (project) => Effect.flatMap(SynchronizedRef.get(made), (projects) => Effect.fromOption(Option.fromUndefinedOr(projects.get(project))).pipe( Effect.mapError(() => new UnknownProject({ project })) ) ), }); }));added:packages/project/src/alarms.ts+17 added
1234567891011121314151617/** * The `Alarms` port: how a project asks to be woken. A Durable Object holds * one alarm, so `set` replaces whatever was set before; the project service * decides when (the earliest claim deadline, outbox retry or answer retry * still pending) and calls `onAlarm` when it fires. Adapters: `/memory` * here, the DO's storage alarm in `apps/platform` (W3 302). */import { Context } from "effect";import type { DateTime, Effect } from "effect";
export class Alarms extends Context.Service< Alarms, { /** Wake the project at `at`, in place of any alarm set before. */ readonly set: (at: DateTime.Utc) => Effect.Effect<void>; }>()("project/Alarms") {}added:packages/project/src/answer-runs.ts+167 added
1+/**2+ * The `AnswerRuns` port: how the project service starts carrying an admitted3+ * answer to its verdict and onto main. The project only records where each4+ * answer stands; a run does the slow part (merge, checks, land) through the5+ * project's answer queue, step by step, and reports each step back.6+ *7+ * Adapters: `/inline` here, which runs the steps in process (tests, W2), and8+ * the Answer Workflow in `apps/platform` (W3 304), which runs each step as a9+ * durable Workflow step. Both drive the same two methods, `answer` and10+ * `advanceAnswer`, with the same steps (`answer-runs/steps.ts`), so they11+ * reach the same outcome.12+ */13+import { CheckLane } from "@repo/checks/check-runner";14+import {15+ HeldBackResult,16+ LaneResult,17+ Verdict,18+} from "@repo/protocol/domain/answer";19+import { Ask } from "@repo/protocol/domain/ask";20+import { Choice } from "@repo/protocol/domain/decision";21+import { AskKind } from "@repo/protocol/domain/kind";22+import { Outcome } from "@repo/protocol/domain/outcome";23+import {24+ AskId,25+ CommitSha,26+ DecisionId,27+ Handle,28+ LandedSha,29+ LaneName,30+ RepoName,31+ RepoPath,32+ TreeSha,33+} from "@repo/protocol/ids";34+import type { RequestId } from "@repo/protocol/ids";35+import { Refusal } from "@repo/protocol/refusal";36+import { Context, Schema } from "effect";37+import type { Effect, Option } from "effect";38+39+import { Change, LandingState, PendingDecision } from "./landing.ts";40+import type { LandingCommand, LandingEffect } from "./landing.ts";41+42+const Attempt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));43+44+/**45+ * A `LandingCommand` as it crosses a boundary: what a step reports back to46+ * the project (W3's Answer Workflow calls `advanceAnswer` over the Project47+ * Durable Object's boundary with it).48+ */49+export const ReportedCommand = Schema.TaggedUnion({50+ Blocked: { attempt: Attempt },51+ Busy: { attempt: Attempt },52+ Checked: {53+ decisions: Schema.Array(PendingDecision),54+ finish: AskKind.fields.finish,55+ refusals: Schema.Array(Refusal),56+ tree: TreeSha,57+ },58+ Decided: { by: Handle, choice: Choice, decision: DecisionId },59+ Finished: { by: Handle },60+ LandedOk: { sha: LandedSha },61+ MainMoved: { from: LandedSha, main: LandedSha },62+ MergeConflict: { conflicts: Schema.Array(RepoPath), main: LandedSha },63+ Merged: { changes: Schema.Array(Change), main: LandedSha, tree: TreeSha },64+ Start: { main: LandedSha },65+ Wait: { parent: AskId },66+});67+68+/**69+ * A port call a run makes next, as `advanceAnswer` returns it: a merge, the70+ * checks, a land, or a `Retry` to wait for (the project's alarm starts the71+ * run again then). The project settles every other `LandingEffect` itself.72+ */73+export const NextStep = Schema.TaggedUnion({74+ Land: { main: LandedSha, tree: TreeSha },75+ Merge: { base: CommitSha, fork: RepoName, head: CommitSha, main: LandedSha },76+ Retry: { at: Schema.DateTimeUtcFromString },77+ RunChecks: { tree: TreeSha },78+});79+80+/** What `advanceAnswer` returns, as it crosses a boundary: `Advanced`. */81+export const Steps = Schema.Struct({82+ effects: Schema.Array(NextStep),83+ outcome: Outcome,84+});85+86+/**87+ * One answer request as a run needs it: where it stands, whether it holds88+ * the project's one landing slot, and the policy's facts its steps use. It89+ * crosses the Project Durable Object's boundary, so it is a schema.90+ */91+export const AnswerRun = Schema.Struct({92+ /** Whether the request holds the landing slot: a `Landing` lands only then. */93+ admitted: Schema.Boolean,94+ /** The ask it answers; absent for a decider's own landing. */95+ ask: Schema.optionalKey(Ask),96+ /** The lane the ask's own check reports as, which is red on main by design. */97+ askLane: Schema.optionalKey(LaneName),98+ /** Whether a decider must finish it before it lands: the ask kind's `finish`. */99+ finish: AskKind.fields.finish,100+ /** What the checks run on the merged tree: the ask's check first, then every project lane. */101+ lanes: Schema.Array(CheckLane),102+ /** The landing commit's whole message, trailers included, once the answer is checked. */103+ message: Schema.optionalKey(Schema.String),104+ /** The canonical repo the answer lands on. */105+ repo: RepoName,106+ state: LandingState,107+ /** The verdict on the merged tree, once the checks judged it. */108+ verdict: Schema.optionalKey(Verdict),109+});110+111+export type AnswerRun = typeof AnswerRun.Type;112+113+/**114+ * What a step saw beside the command it reports: the lanes and held-back115+ * areas a check run judged (the verdict is made from them), and the116+ * bookkeeping a land left unwritten (the project retries it).117+ */118+export const AnswerReport = Schema.Struct({119+ heldBack: Schema.optionalKey(Schema.Array(HeldBackResult)),120+ lanes: Schema.optionalKey(Schema.Array(LaneResult)),121+ pending: Schema.optionalKey(122+ Schema.Array(Schema.Literals(["mirror", "notes"]))123+ ),124+});125+126+export type AnswerReport = typeof AnswerReport.Type;127+128+/** What one reported step changed: where the answer stands now, and the port calls to run next. */129+export interface Advanced {130+ readonly effects: readonly LandingEffect[];131+ readonly outcome: Outcome;132+}133+134+/**135+ * A project's answer queue, as a run sees it: read one answer's run, and136+ * report what a step came to. `advanceAnswer` returns only the port calls137+ * the run makes next (`Merge`, `RunChecks`, `Land`), and a `Retry` when it138+ * should stop and wait for the project's alarm; the project settles139+ * everything else itself.140+ */141+export interface AnswerQueue {142+ readonly advanceAnswer: (143+ requestId: RequestId,144+ command: LandingCommand,145+ report?: AnswerReport146+ ) => Effect.Effect<Advanced>;147+ readonly answer: (148+ requestId: RequestId149+ ) => Effect.Effect<Option.Option<AnswerRun>>;150+}151+152+/**153+ * Starts the run of one answer request. Idempotent by id: starting a run154+ * already under way, or already over, changes nothing. `queue` is the155+ * project's own answer queue, which an in-process adapter drives directly;156+ * the Workflow adapter reaches the same queue through the project's Durable157+ * Object and ignores it.158+ */159+export class AnswerRuns extends Context.Service<160+ AnswerRuns,161+ {162+ readonly start: (163+ requestId: RequestId,164+ queue: AnswerQueue165+ ) => Effect.Effect<void>;166+ }167+>()("project/AnswerRuns") {}added:packages/project/src/events.ts+65 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465/** * A project's events (`ProjectEvent`): what the service says happened, in * the order its store numbers them. Events are written in the same commit as * the rows that made them, and each one also goes to the projection through * the outbox, so the front page hears every one. */import type { Ask, AskListing } from "@repo/protocol/domain/ask";import { ProjectEvent } from "@repo/protocol/domain/event";import type { Outcome } from "@repo/protocol/domain/outcome";import type { AskId, CommitSha, LandedSha } from "@repo/protocol/ids";import { Effect, Schema } from "effect";import type { DateTime } from "effect";
import { ProjectEventInput as EventInput } from "./claim.ts";import type { ProjectEventInput } from "./project-store/rows.ts";
/** An ask as `listAsks`, the front page and `AskOpened` show it. */export const listingOf = (ask: Ask): AskListing => { const listing = { ask: ask.id, blockedBy: ask.blockedBy, claimed: ask.state === "claimed", kind: ask.kind, territory: ask.territory.module, want: ask.brief.want, };
return ask.reserve === undefined ? listing : { ...listing, reserve: ask.reserve };};
/** An ask opened. */export const askOpened = (ask: Ask, at: DateTime.Utc): ProjectEventInput => EventInput.AskOpened({ ask: listingOf(ask), at });
/** An answer's landing closed its ask. */export const askClosed = ( ask: AskId, landing: LandedSha, at: DateTime.Utc): ProjectEventInput => EventInput.AskClosed({ ask, at, landing });
/** An answer was judged: its checks or its merge decided where it stands. */export const judged = ( ask: AskId, head: CommitSha, outcome: Outcome, at: DateTime.Utc): ProjectEventInput => EventInput.Judged({ ask, at, head, outcome });
const asEvent = Schema.decodeUnknownEffect(Schema.toType(ProjectEvent));
/** * The events as the store will number them when the same commit writes * them: on from `lastSeq`, in order. The service commits under the * project's lock, so nothing numbers an event in between. */export const numbered = ( lastSeq: number, events: readonly ProjectEventInput[]): Effect.Effect<readonly ProjectEvent[]> => Effect.forEach(events, (event, index) => Effect.orDie(asEvent({ ...event, seq: lastSeq + index + 1 })) );added:packages/project/src/facts.ts+438 added
1+/**2+ * The facts the gate and the rules evaluator decide over, gathered from the3+ * repos through `RepoHost`: the gate's `PushFacts` for one push (its change4+ * list, the lines it added, where it goes), and the rules' `EvaluationFacts`5+ * at one commit (its CI and manifest files, its workspaces, its vouch file).6+ * Neither the gate nor rule code reads a repo; the project service hands7+ * them these.8+ */9+import { ObjectId, RepoHost, Revision } from "@repo/artifacts/repo-host";10+import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";11+import { PushTarget } from "@repo/gate/facts";12+import type { PushFacts } from "@repo/gate/facts";13+import { addedLines, treeDiff } from "@repo/git/tree-diff";14+import type { Change } from "@repo/git/tree-diff";15+import type { Ask } from "@repo/protocol/domain/ask";16+import type { ClaimView } from "@repo/protocol/domain/claim";17+import { RefNameText } from "@repo/protocol/domain/common";18+import type { Policy } from "@repo/protocol/domain/policy";19+import {20+ AskId,21+ Handle,22+ LayerName,23+ RepoPath,24+ TreeSha,25+} from "@repo/protocol/ids";26+import type {27+ CommitSha,28+ LandedSha,29+ ProjectName,30+ RepoName,31+} from "@repo/protocol/ids";32+import type { Principal } from "@repo/protocol/principal";33+import type { EvaluationFacts } from "@repo/rules/rules-evaluator";34+import { Array, Effect, Option, Predicate, Schema } from "effect";35+import type { DateTime } from "effect";36+37+/** A commit the push names that the repo does not hold. */38+export class MissingCommit extends Schema.TaggedError<MissingCommit>()(39+ "MissingCommit",40+ { sha: Schema.String }41+) {}42+43+const asAsk = Schema.decodeUnknownOption(AskId);44+45+const asHandle = Schema.decodeUnknownOption(Handle);46+47+const asLayer = Schema.decodeUnknownOption(LayerName);48+49+/**50+ * Where a push goes, read from the repo's name (spec §4.5): `<project>`,51+ * `<project>--<ask>--<handle>`, `<project>--me--<handle>` or52+ * `<project>--<layer>`. Any other name is read as canonical's, which takes53+ * no push.54+ */55+export const targetOf = (repo: RepoName, project: ProjectName): PushTarget => {56+ const [named, second, third, ...rest] = repo.split("--");57+ const canonical = PushTarget.Canonical({ project });58+59+ if (named !== project || rest.length > 0 || second === undefined) {60+ return canonical;61+ }62+63+ if (third === undefined) {64+ return Option.match(asLayer(second), {65+ onNone: () => canonical,66+ onSome: (layer) => PushTarget.Layer({ layer, project }),67+ });68+ }69+70+ if (second === "me") {71+ return Option.match(asHandle(third), {72+ onNone: () => canonical,73+ onSome: (owner) => PushTarget.WorkingFork({ owner, project }),74+ });75+ }76+77+ return Option.match(78+ Option.all({ ask: asAsk(second), claimant: asHandle(third) }),79+ {80+ onNone: () => canonical,81+ onSome: ({ ask, claimant }) =>82+ PushTarget.ClaimFork({ ask, claimant, project }),83+ }84+ );85+};86+87+const commitIn = (repo: RepoName, sha: CommitSha) =>88+ RepoHost.use((host) => host.readCommit(repo, sha)).pipe(89+ Effect.flatMap(90+ Option.match({91+ onNone: () => Effect.fail(new MissingCommit({ sha })),92+ onSome: Effect.succeed,93+ })94+ )95+ );96+97+const textOf = (bytes: Uint8Array) => new TextDecoder().decode(bytes);98+99+const ScriptsOf = Schema.fromJsonString(100+ Schema.Struct({ scripts: Schema.optionalKey(Schema.Json) })101+);102+103+const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);104+105+/** A `package.json` blob's `scripts`, as canonical JSON text; none when it reads as no manifest. */106+const scriptsIn = (repo: RepoName, blob: string | undefined) =>107+ blob === undefined108+ ? Effect.succeed("")109+ : RepoHost.use((host) => host.readBlob(repo, ObjectId.make(blob))).pipe(110+ Effect.map((bytes) =>111+ Option.flatMap(bytes, (read) => decodeScripts(textOf(read))).pipe(112+ Option.map(({ scripts }) => JSON.stringify(scripts ?? null)),113+ Option.getOrElse(() => "")114+ )115+ )116+ );117+118+/** Whether the root manifest's `scripts` differ between the change's two blobs. */119+const scriptsChanged = (repo: RepoName, changes: readonly Change[]) =>120+ Option.match(121+ Array.findFirst(changes, (change) => change.path === "package.json"),122+ {123+ onNone: () => Effect.succeed(false),124+ onSome: (change) =>125+ Effect.map(126+ Effect.all([127+ scriptsIn(repo, change.before),128+ scriptsIn(repo, change.after),129+ ]),130+ ([before, after]) => before !== after131+ ),132+ }133+ );134+135+/** What `pushFacts` is told: the push, and what the project knows about it. */136+export interface PushInput {137+ readonly ask: Option.Option<Ask>;138+ readonly base: CommitSha;139+ readonly claim: Option.Option<ClaimView>;140+ /** How many live claims the pusher holds, for `CapReached`. */141+ readonly claimsHeld: number;142+ readonly head: CommitSha;143+ readonly landed: LandedSha;144+ readonly policy: Policy;145+ readonly project: ProjectName;146+ readonly pusher: Principal;147+ readonly ref: string;148+ /** The repo the push went to, which holds `base` and `head`. */149+ readonly repo: RepoName;150+}151+152+/**153+ * The gate's facts for one push: its change list from `base` to `head` (by154+ * subtree ids, through the port), the lines it added, where it goes, and155+ * whether it moved the root manifest's scripts. No layer paths or ratchet156+ * counts yet (W6, W4). A commit the repo lacks is `MissingCommit`.157+ */158+export const pushFacts = (159+ input: PushInput160+): Effect.Effect<PushFacts, RepoNotFound | MissingCommit, RepoHost> =>161+ Effect.gen(function* () {162+ const base = yield* commitIn(input.repo, input.base);163+ const head = yield* commitIn(input.repo, input.head);164+165+ const changes = yield* treeDiff(166+ input.repo,167+ TreeSha.make(base.tree),168+ TreeSha.make(head.tree)169+ );170+171+ return {172+ addedLines: yield* addedLines(input.repo, changes),173+ ask: input.ask,174+ base: input.base,175+ changes,176+ claim: input.claim,177+ claimsHeld: input.claimsHeld,178+ head: input.head,179+ landed: input.landed,180+ layerPaths: new Set(),181+ opensAsk: false,182+ policy: input.policy,183+ pusher: input.pusher,184+ ratchetCounts: new Map(),185+ ref: Option.getOrElse(Schema.decodeOption(RefNameText)(input.ref), () =>186+ RefNameText.make("refs/heads/main")187+ ),188+ scriptsChanged: yield* scriptsChanged(input.repo, changes),189+ target: targetOf(input.repo, input.project),190+ } satisfies PushFacts;191+ });192+193+// ------------------------------------------------------------ rules facts194+195+// The folders whose files the run-block finder reads (spec §4.2 `checks`).196+const CI_FOLDERS = [".github/workflows", ".forgejo/workflows", ".husky"];197+198+// A file the finder reads is small; a large one is no config.199+const MAX_FACT_BYTES = 256 * 1024;200+201+const Manifest = Schema.fromJsonString(202+ Schema.Struct({203+ exports: Schema.optionalKey(Schema.Json),204+ name: Schema.optionalKey(Schema.String),205+ workspaces: Schema.optionalKey(Schema.Json),206+ })207+);208+209+const decodeManifest = Schema.decodeUnknownOption(Manifest);210+211+/** The entries of the folder at `path` (`""` for the root) of a tree. */212+const folderAt = (213+ repo: RepoName,214+ root: ObjectId,215+ path: string216+): Effect.Effect<readonly TreeEntry[], RepoNotFound, RepoHost> =>217+ Effect.reduce(218+ path === "" ? [] : path.split("/"),219+ (): Option.Option<ObjectId> => Option.some(root),220+ (folder, segment) =>221+ Option.match(folder, {222+ onNone: () => Effect.succeedNone,223+ onSome: (id) =>224+ RepoHost.use((host) => host.readTree(repo, id)).pipe(225+ Effect.map((entries) =>226+ Option.flatMap(entries, (found) =>227+ Option.fromNullishOr(228+ found.find(229+ (entry) => entry.name === segment && entry.type === "tree"230+ )?.sha231+ )232+ )233+ )234+ ),235+ })236+ ).pipe(237+ Effect.flatMap(238+ Option.match({239+ onNone: () => Effect.succeed([]),240+ onSome: (id) =>241+ RepoHost.use((host) => host.readTree(repo, id)).pipe(242+ Effect.map(Option.getOrElse(() => []))243+ ),244+ })245+ )246+ );247+248+/** Each blob directly in a folder, as a path and its text. */249+const filesIn = (repo: RepoName, root: ObjectId, folder: string) =>250+ Effect.flatMap(folderAt(repo, root, folder), (entries) =>251+ Effect.forEach(252+ entries.filter(({ type }) => type === "blob"),253+ (entry) =>254+ RepoHost.use((host) => host.readBlob(repo, entry.sha)).pipe(255+ Effect.map((bytes) =>256+ Option.filter(bytes, (read) => read.length <= MAX_FACT_BYTES).pipe(257+ Option.map((read) => ({258+ content: textOf(read),259+ path: RepoPath.make(260+ folder === "" ? entry.name : `${folder}/${entry.name}`261+ ),262+ }))263+ )264+ )265+ )266+ ).pipe(Effect.map(Array.getSomes))267+ );268+269+const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>270+ globalThis.Array.isArray(value);271+272+const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>273+ Predicate.isObject(value) && !isJsonArray(value);274+275+const strings = (value: Schema.Json | undefined): readonly string[] =>276+ value !== undefined && isJsonArray(value)277+ ? value.filter(Predicate.isString)278+ : [];279+280+/** A manifest's `workspaces`: an array of globs, or `{ packages: [...] }`. */281+const workspaceGlobs = (value: Schema.Json | undefined): readonly string[] => {282+ if (value === undefined || value === null) {283+ return [];284+ }285+286+ if (isJsonArray(value)) {287+ return strings(value);288+ }289+290+ return isJsonObject(value) ? strings(value.packages) : [];291+};292+293+/** Every string an `exports` field leads to, nested conditions included. */294+const exportTargets = (value: Schema.Json | undefined): readonly string[] => {295+ if (value === undefined || value === null) {296+ return [];297+ }298+299+ if (Predicate.isString(value)) {300+ return [value];301+ }302+303+ if (isJsonArray(value)) {304+ return value.flatMap(exportTargets);305+ }306+307+ return isJsonObject(value) ? Object.values(value).flatMap(exportTargets) : [];308+};309+310+const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");311+312+/**313+ * The folders a workspace glob names: `packages/*` is every folder in314+ * `packages`, and a glob with no `*` is its own folder. Deeper globs are315+ * read as their folder prefix's children.316+ */317+const foldersOf = (repo: RepoName, root: ObjectId, glob: string) => {318+ const clean = withoutDotSlash(glob).replace(/\/+$/u, "");319+ const star = clean.indexOf("*");320+321+ if (star === -1) {322+ return Effect.succeed([clean]);323+ }324+325+ const parent = clean.slice(0, star).replace(/\/+$/u, "");326+327+ return Effect.map(folderAt(repo, root, parent), (entries) =>328+ entries329+ .filter(({ type }) => type === "tree")330+ .map(({ name }) => (parent === "" ? name : `${parent}/${name}`))331+ );332+};333+334+/** One workspace package: its folder, its name, and the files its `exports` name. */335+const workspaceAt = (repo: RepoName, root: ObjectId, dir: string) =>336+ Effect.map(filesIn(repo, root, dir), (files) =>337+ Option.flatMap(338+ Option.fromNullishOr(339+ files.find(({ path }) => path === `${dir}/package.json`)340+ ),341+ ({ content }) => decodeManifest(content)342+ ).pipe(343+ Option.flatMap((manifest) =>344+ Option.map(Option.fromNullishOr(manifest.name), (name) => ({345+ dir,346+ exports: exportTargets(manifest.exports).map((target) =>347+ RepoPath.make(`${dir}/${withoutDotSlash(target)}`)348+ ),349+ name,350+ }))351+ ),352+ Option.filter(({ name }) => name.length > 0)353+ )354+ );355+356+/** What `evaluationFacts` is told besides the commit. */357+export interface FactsInput {358+ readonly initializer: Handle;359+ readonly now: DateTime.Utc;360+ readonly project: ProjectName;361+ /** Where the vouch file is, as the policy before this commit says. */362+ readonly vouchFile: RepoPath;363+}364+365+/**366+ * The rules' facts at one commit of `repo`: the files at its root and in367+ * its CI folders (what the run-block finder and the judge closure read), the368+ * workspaces its root manifest declares, and its vouch file. The seed is the369+ * commit's own first eight hex digits, so the same commit always sees the370+ * same randomness. A commit the repo lacks gives empty facts: the evaluation371+ * then decides on its config folder alone.372+ */373+export const evaluationFacts = (374+ repo: RepoName,375+ at: CommitSha,376+ input: FactsInput377+): Effect.Effect<EvaluationFacts, never, RepoHost> => {378+ const empty: EvaluationFacts = {379+ ci: [],380+ initializer: input.initializer,381+ now: input.now,382+ project: input.project,383+ seed: Number.parseInt(at.slice(0, 8), 16),384+ workspaces: [],385+ };386+387+ return Effect.gen(function* () {388+ const commit = yield* RepoHost.use((host) => host.readCommit(repo, at));389+390+ if (Option.isNone(commit)) {391+ return empty;392+ }393+394+ const root = commit.value.tree;395+ const atRoot = yield* filesIn(repo, root, "");396+397+ const ci = [398+ ...atRoot,399+ ...(yield* Effect.forEach(CI_FOLDERS, (folder) =>400+ filesIn(repo, root, folder)401+ )).flat(),402+ ];403+404+ const globs = Option.match(405+ Option.flatMap(406+ Option.fromNullishOr(407+ atRoot.find(({ path }) => path === "package.json")408+ ),409+ ({ content }) => decodeManifest(content)410+ ),411+ {412+ onNone: () => [],413+ onSome: (manifest) => workspaceGlobs(manifest.workspaces),414+ }415+ );416+417+ const dirs = Array.dedupe(418+ (yield* Effect.forEach(globs, (glob) =>419+ foldersOf(repo, root, glob)420+ )).flat()421+ );422+423+ const workspaces = Array.getSomes(424+ yield* Effect.forEach(dirs, (dir) => workspaceAt(repo, root, dir))425+ );426+427+ const vouch = yield* RepoHost.use((host) =>428+ host.readFile(repo, Revision.Commit({ sha: at }), input.vouchFile)429+ );430+431+ const facts: EvaluationFacts = { ...empty, ci, workspaces };432+433+ return Option.match(vouch, {434+ onNone: () => facts,435+ onSome: (bytes) => ({ ...facts, vouchFile: textOf(bytes) }),436+ });437+ }).pipe(Effect.catchTag("RepoNotFound", () => Effect.succeed(empty)));438+};added:packages/project/src/outbox.ts+243 added
1+/**2+ * The outbox: side effects a call's commit asked for, kept with the rows3+ * that made them until they are done (ADR 0012's settle). A row is written in4+ * the same commit as its transition, run right after it, and acknowledged5+ * once it succeeded; one that failed stays, with a later `notBefore`, and the6+ * next alarm runs it again. Each is safe to run twice.7+ *8+ * Kinds: a projected event for the read models (`Projected`), a claim's9+ * fork (`MakeFork`), the start of an answer run (`StartAnswer`), and a10+ * landing's unwritten bookkeeping, written by landing the same job again11+ * (`Bookkeeping`).12+ */13+import { RefName, RepoHost } from "@repo/artifacts/repo-host";14+import { Verdict } from "@repo/protocol/domain/answer";15+import type { ProjectEvent } from "@repo/protocol/domain/event";16+import {17+ CommitSha,18+ Handle,19+ LandedSha,20+ RepoName,21+ RequestId,22+ TreeSha,23+} from "@repo/protocol/ids";24+import type { ProjectName } from "@repo/protocol/ids";25+import { Array, DateTime, Effect, Option, Order, Schema } from "effect";26+27+import { AnswerRuns } from "./answer-runs.ts";28+import type { AnswerQueue } from "./answer-runs.ts";29+import { Lander, Rebuild } from "./lander.ts";30+import { backoff } from "./landing.ts";31+import type { OutboxRow } from "./project-store/rows.ts";32+import { Projection, ProjectedEvent } from "./projection.ts";33+34+const mainRef = RefName.make("refs/heads/main");35+36+/** An answer's landing job, as its bookkeeping retry lands it again. */37+export const LandAgain = Schema.Struct({38+ author: Handle,39+ base: CommitSha,40+ fork: RepoName,41+ head: CommitSha,42+ main: LandedSha,43+ message: Schema.String,44+ repo: RepoName,45+ requestId: RequestId,46+ tree: TreeSha,47+ verdict: Schema.optionalKey(Verdict),48+});49+50+export type LandAgain = typeof LandAgain.Type;51+52+/** What one outbox row asks for. */53+export const OutboxBody = Schema.Union([54+ ProjectedEvent,55+ Schema.TaggedStruct("MakeFork", { from: RepoName, name: RepoName }),56+ Schema.TaggedStruct("StartAnswer", { requestId: RequestId }),57+ Schema.TaggedStruct("Bookkeeping", { job: LandAgain }),58+]).pipe(Schema.toTaggedUnion("_tag"));59+60+export type OutboxBody = typeof OutboxBody.Type;61+62+const BodyJson = Schema.toCodecJson(OutboxBody);63+64+const encodeBody = Schema.encodeEffect(BodyJson);65+66+const decodeBody = Schema.decodeUnknownEffect(BodyJson);67+68+/** A row asking for `body`, due at `notBefore`; a row with the same id is replaced. */69+export const outboxRow = (70+ id: string,71+ body: OutboxBody,72+ notBefore: DateTime.Utc73+): Effect.Effect<OutboxRow> =>74+ Effect.map(Effect.orDie(encodeBody(body)), (encoded) => ({75+ attempts: 0,76+ body: encoded,77+ id,78+ kind: body._tag,79+ notBefore,80+ }));81+82+/** One row per event, for the read models, keyed by the event's number. */83+export const projectedRows = (84+ project: ProjectName,85+ events: readonly ProjectEvent[],86+ now: DateTime.Utc87+): Effect.Effect<readonly OutboxRow[]> =>88+ Effect.forEach(events, (event) =>89+ outboxRow(90+ `projected:${event.seq}`,91+ ProjectedEvent.make({ event, project }),92+ now93+ )94+ );95+96+/** The row that starts (or resumes) an answer's run at `at`. */97+export const startRow = (requestId: RequestId, at: DateTime.Utc) =>98+ outboxRow(99+ `start:${requestId}:${DateTime.toEpochMillis(at)}`,100+ OutboxBody.cases.StartAnswer.make({ requestId }),101+ at102+ );103+104+/** Whether a row is due at `now`. */105+export const isDue = (row: OutboxRow, now: DateTime.Utc) =>106+ DateTime.isLessThanOrEqualTo(row.notBefore, now);107+108+/** What running some rows came to: the ids done, and the rows to run again later. */109+export interface OutboxRun {110+ readonly done: readonly string[];111+ readonly retry: readonly OutboxRow[];112+}113+114+/** The row again, after `attempts` failures: due after a backoff from `now`. */115+const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({116+ ...row,117+ attempts: row.attempts + 1,118+ notBefore: DateTime.addDuration(now, backoff(row.attempts)),119+});120+121+interface Decoded {122+ readonly body: OutboxBody;123+ readonly row: OutboxRow;124+}125+126+const ran = (row: OutboxRow, ok: boolean, now: DateTime.Utc): OutboxRun =>127+ ok ? { done: [row.id], retry: [] } : { done: [], retry: [later(row, now)] };128+129+const all = (runs: readonly OutboxRun[]): OutboxRun => ({130+ done: runs.flatMap(({ done }) => done),131+ retry: runs.flatMap(({ retry }) => retry),132+});133+134+/**135+ * A claim's fork, made or found made. Artifacts may answer a fork that136+ * worked with an error (S7): a fork that exists and has `main` is made.137+ */138+const fork = (from: RepoName, name: RepoName) =>139+ RepoHost.use((host) =>140+ host.fork(from, name).pipe(141+ Effect.as(true),142+ Effect.catchTag("RepoExists", () =>143+ host.refs(name).pipe(144+ Effect.map((refs) => refs.has(mainRef)),145+ Effect.orElseSucceed(() => false)146+ )147+ ),148+ Effect.orElseSucceed(() => false)149+ )150+ );151+152+/** The landing job again: its unwritten bookkeeping is written, and nothing else moves. */153+const landAgain = (job: LandAgain) =>154+ Lander.use((lander) =>155+ lander.land({156+ author: job.author,157+ main: job.main,158+ message: job.message,159+ rebuild: Rebuild.Merge({160+ base: job.base,161+ fork: job.fork,162+ head: job.head,163+ }),164+ repo: job.repo,165+ requestId: job.requestId,166+ tree: job.tree,167+ verdict: Option.fromUndefinedOr(job.verdict),168+ })169+ ).pipe(170+ Effect.map(({ pending }) => pending.length === 0),171+ Effect.orElseSucceed(() => false)172+ );173+174+const bySeq = Order.mapInput(Order.Number, ({ body }: Decoded) =>175+ OutboxBody.guards.Projected(body) ? body.event.seq : 0176+);177+178+/**179+ * Runs the rows: projected events first, in their order and in one call,180+ * then forks, bookkeeping, and last the answer runs (which may run long, and181+ * settle their own rows). Nothing here fails: each row is done, or retried.182+ */183+export const runOutbox = (184+ rows: readonly OutboxRow[],185+ queue: AnswerQueue,186+ now: DateTime.Utc187+): Effect.Effect<188+ OutboxRun,189+ never,190+ AnswerRuns | Lander | Projection | RepoHost191+> =>192+ Effect.gen(function* () {193+ const decoded = yield* Effect.forEach(rows, (row) =>194+ Effect.map(Effect.orDie(decodeBody(row.body)), (body) => ({ body, row }))195+ );196+197+ const of = <Tag extends OutboxBody["_tag"]>(tag: Tag) =>198+ decoded.filter(199+ (200+ each201+ ): each is Decoded & {202+ readonly body: Extract<OutboxBody, { readonly _tag: Tag }>;203+ } => OutboxBody.guards[tag](each.body)204+ );205+206+ const projected = Array.sort(of("Projected"), bySeq);207+208+ const delivered = Array.isReadonlyArrayNonEmpty(projected)209+ ? yield* Projection.use((projection) =>210+ projection.apply(projected.map(({ row }) => row))211+ ).pipe(212+ Effect.as(true),213+ Effect.catchTag("ProjectionFailed", (failed) =>214+ Effect.as(215+ Effect.logWarning("the projection refused rows", failed),216+ false217+ )218+ )219+ )220+ : true;221+222+ const forks = yield* Effect.forEach(of("MakeFork"), ({ body, row }) =>223+ Effect.map(fork(body.from, body.name), (ok) => ran(row, ok, now))224+ );225+226+ const kept = yield* Effect.forEach(of("Bookkeeping"), ({ body, row }) =>227+ Effect.map(landAgain(body.job), (ok) => ran(row, ok, now))228+ );229+230+ const runs = yield* Effect.forEach(of("StartAnswer"), ({ body, row }) =>231+ Effect.as(232+ AnswerRuns.use((answers) => answers.start(body.requestId, queue)),233+ ran(row, true, now)234+ )235+ );236+237+ return all([238+ ...projected.map(({ row }) => ran(row, delivered, now)),239+ ...forks,240+ ...kept,241+ ...runs,242+ ]);243+ });added:packages/project/src/project.ts+2814 added
1+/**2+ * The project service: every contract's server logic for one project3+ * (spec §4.2), host-free, over ports. Each call hydrates the project from4+ * its store, moves its lifecycles by pure transitions, persists rows, outbox5+ * and events in one commit, then settles the outbox (ADR 0012): forks,6+ * projected events, answer runs and unwritten bookkeeping, each retried by7+ * the next alarm when it fails. Deadlines (claims warned and lapsed, retries)8+ * run on the project's one alarm, set to the earliest pending one.9+ *10+ * Calls that write run one at a time per project; the slow part of an11+ * answer (merge, checks, land) runs outside that lock, in the answer's run,12+ * which reports each step back through `advanceAnswer`. Every method checks13+ * its arguments and its result against the contract's or the domain's14+ * schemas (`MethodSchemas`, principle 2), which W3's Durable Object boundary15+ * reuses.16+ */17+import { BranchName, RefName, RepoHost } from "@repo/artifacts/repo-host";18+import type { RepoNotFound } from "@repo/artifacts/repo-host";19+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";20+import { Brand } from "@repo/brand";21+import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";22+import { findRunBlock } from "@repo/checks/finder";23+import { judgeClosure } from "@repo/checks/judge";24+import { checkVersion, commandFor } from "@repo/checks/kinds";25+import { redFirstOfRuns } from "@repo/checks/red-first";26+import { weaknessesOf } from "@repo/checks/weak-shapes";27+import { PushTarget } from "@repo/gate/facts";28+import type { PushFacts } from "@repo/gate/facts";29+import { pushStages, runGate } from "@repo/gate/gate";30+import { scan } from "@repo/gate/stages/shape";31+import { verdictOf } from "@repo/gate/verdict";32+import { patchId } from "@repo/git/patch-id";33+import { formatLanding } from "@repo/git/trailers";34+import {35+ Claim as ClaimContract,36+ InitProject,37+ LandingOf,38+ ListAsks,39+ OpenAsk,40+ Release,41+ ShowAsk,42+ Status,43+ SubmitAnswer,44+ VerdictOf,45+} from "@repo/protocol/contracts";46+import { AnswerReceipt, Verdict } from "@repo/protocol/domain/answer";47+import type {48+ AnswerView,49+ HeldBackResult,50+ LaneResult,51+} from "@repo/protocol/domain/answer";52+import type { Ask, AskListing } from "@repo/protocol/domain/ask";53+import { CheckSpec } from "@repo/protocol/domain/check";54+import type { ClaimView } from "@repo/protocol/domain/claim";55+import { RefNameText } from "@repo/protocol/domain/common";56+import type { Credit } from "@repo/protocol/domain/credit";57+import { ProjectEvent } from "@repo/protocol/domain/event";58+import type { AskKind } from "@repo/protocol/domain/kind";59+import type { LandingView } from "@repo/protocol/domain/landing";60+import type { Outcome, StageName } from "@repo/protocol/domain/outcome";61+import { Policy } from "@repo/protocol/domain/policy";62+import {63+ AskId,64+ CommitSha,65+ LandedSha,66+ RepoName,67+ RepoPath,68+ RequestId,69+} from "@repo/protocol/ids";70+import type { Handle, LaneName, ProjectName } from "@repo/protocol/ids";71+import { Person, Principal } from "@repo/protocol/principal";72+import {73+ AskFull,74+ DirectPush,75+ ImportFailed,76+ IncompleteBrief,77+ NotClaimed,78+ NotDecider,79+ NotRedFirst,80+ ProjectExists,81+ Refusal,82+ StaleBase,83+ TouchedJudge,84+ UnknownAsk,85+ UnknownCommit,86+ VerifierBlocked,87+ WeakCheck,88+} from "@repo/protocol/refusal";89+import type {90+ AskBlocked,91+ CapReached,92+ ClaimLapsed,93+ Denounced,94+ NotVouched,95+ OutOfScope,96+ PrivatePathInPublicTree,97+ ReachedInternals,98+ RepoBusy,99+ Weakened,100+} from "@repo/protocol/refusal";101+import { Finishers } from "@repo/rules/finish";102+import { RulesEvaluator } from "@repo/rules/rules-evaluator";103+import {104+ Array,105+ Context,106+ DateTime,107+ Effect,108+ Layer,109+ Match,110+ Option,111+ Order,112+ Record,113+ Result,114+ Schema,115+ Semaphore,116+} from "effect";117+import { init } from "isomorphic-git";118+119+import { Alarms } from "./alarms.ts";120+import {121+ AnswerReport,122+ AnswerRun,123+ ReportedCommand,124+ Steps,125+} from "./answer-runs.ts";126+import type { AnswerQueue, AnswerRuns } from "./answer-runs.ts";127+import { isStep } from "./answer-runs/steps.ts";128+import { decidersFor } from "./attention/decisions.ts";129+import { recordOf, sameHandle } from "./attention/record.ts";130+import { mayClaim, standing } from "./attention/vouch.ts";131+import {132+ ClaimCommand,133+ ClaimEffect,134+ ClaimState,135+ forkName,136+ toView,137+ transition as claimTransition,138+} from "./claim.ts";139+import type { ClaimStep, Live } from "./claim.ts";140+import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";141+import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";142+import type { MissingCommit } from "./facts.ts";143+import { Lander, Rebuild } from "./lander.ts";144+import type { ComposedFile } from "./lander.ts";145+import {146+ LandingCommand,147+ LandingEffect,148+ LandingState,149+ outcomeOf,150+ transition as landingTransition,151+} from "./landing.ts";152+import type { LandingQueue, Request } from "./landing.ts";153+import {154+ isDue,155+ outboxRow,156+ OutboxBody,157+ projectedRows,158+ runOutbox,159+ startRow,160+} from "./outbox.ts";161+import { ProjectStore } from "./project-store.ts";162+import type { ProjectWrites } from "./project-store.ts";163+import type {164+ AnswerRow,165+ ClaimRow,166+ OutboxRow,167+ ProjectEventInput,168+ ProjectRow,169+ PushEventRow,170+} from "./project-store/rows.ts";171+import type { Projection } from "./projection.ts";172+import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";173+174+/** Every port one project's service runs on. */175+export type ProjectPorts =176+ | Alarms177+ | AnswerRuns178+ | CheckRunner179+ | Lander180+ | ProjectStore181+ | Projection182+ | RepoHost183+ | RulesEvaluator;184+185+/**186+ * The platform's gateway, where every repo's git URL starts: what a claim's187+ * and a project's `remote` name. Never an Artifacts URL. The platform's188+ * Worker sets its own (W3); the default is the product's domain.189+ */190+export const GatewayUrl = Context.Reference<string>("project/GatewayUrl", {191+ defaultValue: () => `https://${Brand.domain}`,192+});193+194+/**195+ * The SDK version a check's version is keyed by. ASSUMPTION: the platform's196+ * own, `0.0.0` until release, as the isogit Lander reports it (212's197+ * Comments); 299 decides where both come from.198+ */199+const sdkVersion = "0.0.0";200+201+/**202+ * The rules evaluator's finishers from `@repo/checks`: the run-block finder203+ * and the judge closure (spec §4.2 `rules`, which may not import `checks`).204+ * Every rules evaluator adapter needs it beside the project's ports.205+ */206+export const FinishersFromChecks: Layer.Layer<Finishers> = Layer.succeed(207+ Finishers,208+ { findRunBlock, judgeClosure }209+);210+211+/** A push one repo took, as the gateway's custody reports it (W3 303). */212+export const PushReport = Schema.Struct({213+ after: CommitSha,214+ before: Schema.Option(CommitSha),215+ /** The push event's id; the same event reported twice is acted on once. */216+ eventId: Schema.NonEmptyString,217+ pusher: Principal,218+ ref: Schema.NonEmptyString,219+ repo: RepoName,220+});221+222+export type PushReport = typeof PushReport.Type;223+224+/** One file a decider opens an ask with: its ask file, or its check. */225+export interface AskFile {226+ readonly content: string;227+ readonly path: RepoPath;228+}229+230+/** The refusals `submitAnswer` answers with. */231+export type SubmitRefusal =232+ | NotClaimed233+ | ClaimLapsed234+ | StaleBase235+ | RepoBusy236+ | OutOfScope237+ | TouchedJudge238+ | Weakened239+ | ReachedInternals240+ | PrivatePathInPublicTree;241+242+/**243+ * Every contract's server logic for one project. Each method takes its244+ * caller explicitly: one project's service serves many callers.245+ */246+export interface ProjectApi extends AnswerQueue {247+ // reads248+ readonly listAsks: (249+ caller: Principal250+ ) => Effect.Effect<{ readonly asks: readonly AskListing[] }>;251+ readonly showAsk: (252+ caller: Principal,253+ ask: AskId254+ ) => Effect.Effect<{ readonly ask: Ask; readonly brief: string }, UnknownAsk>;255+ readonly status: (caller: Person) => Effect.Effect<{256+ readonly answers: readonly AnswerView[];257+ readonly claims: readonly ClaimView[];258+ }>;259+ readonly verdict: (260+ caller: Principal,261+ input: { readonly ask: AskId; readonly head?: CommitSha }262+ ) => Effect.Effect<{ readonly verdict?: Verdict }, UnknownAsk>;263+ readonly landing: (264+ caller: Principal,265+ sha: CommitSha266+ ) => Effect.Effect<{ readonly landing: LandingView }, UnknownCommit>;267+ readonly events: (268+ since: number,269+ limit: number270+ ) => Effect.Effect<271+ readonly { readonly event: ProjectEvent; readonly seq: number }[]272+ >;273+ // writes274+ readonly initProject: (275+ caller: Person,276+ input: {277+ readonly import?: { readonly branch?: string; readonly url: string };278+ }279+ ) => Effect.Effect<280+ {281+ readonly landed?: LandedSha;282+ readonly project: ProjectName;283+ readonly remote: string;284+ },285+ ProjectExists | ImportFailed286+ >;287+ readonly recordFirstPush: (288+ caller: Person,289+ head: CommitSha290+ ) => Effect.Effect<{ readonly landed: LandedSha }, DirectPush>;291+ readonly openAsk: (292+ caller: Person,293+ input: {294+ readonly ask: AskId;295+ readonly files: Array.NonEmptyReadonlyArray<AskFile>;296+ }297+ ) => Effect.Effect<298+ { readonly ask: Ask; readonly landed: LandedSha },299+ | NotDecider300+ | NotRedFirst301+ | WeakCheck302+ | IncompleteBrief303+ | TouchedJudge304+ | VerifierBlocked305+ | StaleBase306+ >;307+ readonly claim: (308+ caller: Person,309+ ask: AskId310+ ) => Effect.Effect<311+ { readonly claim: ClaimView },312+ UnknownAsk | AskFull | AskBlocked | CapReached | NotVouched | Denounced313+ >;314+ readonly release: (315+ caller: Person,316+ ask: AskId317+ ) => Effect.Effect<{ readonly released: boolean }, NotClaimed>;318+ /**319+ * A push a claim fork took: liveness for its claimant's claim, and stages320+ * 0–1 over it. The fork keeps the commit whatever the gate says; the321+ * refusals, every one at once, reach the pusher in git's output. The same322+ * push event reported again changes nothing.323+ */324+ readonly recordPush: (input: PushReport) => Effect.Effect<readonly Refusal[]>;325+ /**326+ * Stages 0–1 over the answer, then its run starts and the receipt says it327+ * is being checked (spec D5). The same `requestId`, or the same head from328+ * the same person while its first answer stands, returns the first receipt.329+ * Of stage 1's refusals the first comes back; `recordPush` lists them all.330+ */331+ readonly submitAnswer: (332+ caller: Person,333+ input: {334+ readonly ask: AskId;335+ readonly base: CommitSha;336+ readonly head: CommitSha;337+ readonly requestId: RequestId;338+ }339+ ) => Effect.Effect<AnswerReceipt, SubmitRefusal>;340+ /** The project's alarm fired: deadlines that passed move, and outbox rows due run again. */341+ readonly onAlarm: () => Effect.Effect<void>;342+ // ---------------------------------------------------------------------343+ // 221 adds the decider-facing methods here: today, proposeAsk, flagAsk,344+ // decide, finish, land, fork, vouch, credits, ledger, envShape, setEnv.345+ // ---------------------------------------------------------------------346+}347+348+/** The schemas one method's arguments (in order), success and failure cross a boundary with. */349+export interface MethodSchema {350+ readonly args: readonly Schema.Top[];351+ readonly error: Schema.Top;352+ readonly success: Schema.Top & { readonly EncodingServices: never };353+}354+355+/**356+ * Every `ProjectApi` method's schemas: contract methods take their success357+ * and failure from `Contracts`, the rest from the domain. The service checks358+ * each argument and each success against them; W3's Durable Object boundary359+ * (302) encodes and decodes with the same ones.360+ */361+export const MethodSchemas = {362+ advanceAnswer: {363+ args: [RequestId, ReportedCommand, Schema.UndefinedOr(AnswerReport)],364+ error: Schema.Never,365+ success: Steps,366+ },367+ answer: {368+ args: [RequestId],369+ error: Schema.Never,370+ success: Schema.Option(AnswerRun),371+ },372+ claim: {373+ args: [Person, AskId],374+ error: ClaimContract.errorSchema,375+ success: ClaimContract.successSchema,376+ },377+ events: {378+ args: [Schema.Int, Schema.Int],379+ error: Schema.Never,380+ success: Schema.Array(381+ Schema.Struct({ event: ProjectEvent, seq: Schema.Int })382+ ),383+ },384+ initProject: {385+ args: [386+ Person,387+ Schema.Struct({ import: InitProject.payloadSchema.fields.import }),388+ ],389+ error: InitProject.errorSchema,390+ success: InitProject.successSchema,391+ },392+ landing: {393+ args: [Principal, CommitSha],394+ error: LandingOf.errorSchema,395+ success: LandingOf.successSchema,396+ },397+ listAsks: {398+ args: [Principal],399+ error: ListAsks.errorSchema,400+ success: ListAsks.successSchema,401+ },402+ onAlarm: { args: [], error: Schema.Never, success: Schema.Void },403+ openAsk: {404+ args: [405+ Person,406+ Schema.Struct({ ask: AskId, files: OpenAsk.payloadSchema.fields.files }),407+ ],408+ error: OpenAsk.errorSchema,409+ success: OpenAsk.successSchema,410+ },411+ recordFirstPush: {412+ args: [Person, CommitSha],413+ error: DirectPush,414+ success: Schema.Struct({ landed: LandedSha }),415+ },416+ recordPush: {417+ args: [PushReport],418+ error: Schema.Never,419+ success: Schema.Array(Refusal),420+ },421+ release: {422+ args: [Person, AskId],423+ error: Release.errorSchema,424+ success: Release.successSchema,425+ },426+ showAsk: {427+ args: [Principal, AskId],428+ error: ShowAsk.errorSchema,429+ success: ShowAsk.successSchema,430+ },431+ status: {432+ args: [Person],433+ error: Status.errorSchema,434+ success: Status.successSchema,435+ },436+ submitAnswer: {437+ args: [438+ Person,439+ Schema.Struct({440+ ask: AskId,441+ base: CommitSha,442+ head: CommitSha,443+ requestId: RequestId,444+ }),445+ ],446+ error: SubmitAnswer.errorSchema,447+ success: SubmitAnswer.successSchema,448+ },449+ verdict: {450+ args: [451+ Principal,452+ Schema.Struct({ ask: AskId, head: Schema.optionalKey(CommitSha) }),453+ ],454+ error: VerdictOf.errorSchema,455+ success: VerdictOf.successSchema,456+ },457+} as const satisfies { readonly [M in keyof ProjectApi]: MethodSchema };458+459+/**460+ * Where one answer stands, as its row keeps it: the landing lifecycle's461+ * state, the receipt its request was first given (a replay gets it again),462+ * and the verdict on its last checked tree.463+ */464+export const AnswerRecord = Schema.Struct({465+ landing: LandingState,466+ receipt: AnswerReceipt,467+ verdict: Schema.optionalKey(Verdict),468+});469+470+export type AnswerRecord = typeof AnswerRecord.Type;471+472+const ClaimJson = Schema.toCodecJson(ClaimState);473+474+const AnswerJson = Schema.toCodecJson(AnswerRecord);475+476+const PolicyJson = Schema.toCodecJson(Policy);477+478+const decodeClaim = Schema.decodeUnknownEffect(ClaimJson);479+480+const encodeClaim = Schema.encodeEffect(ClaimJson);481+482+const decodeAnswer = Schema.decodeUnknownEffect(AnswerJson);483+484+const encodeAnswer = Schema.encodeEffect(AnswerJson);485+486+const decodePolicy = Schema.decodeUnknownEffect(PolicyJson);487+488+const encodePolicy = Schema.encodeEffect(PolicyJson);489+490+/**491+ * A method run between the check of its arguments (each against its492+ * schema's type side: a value that is not one is the caller's defect, since493+ * the boundary that decoded it would have refused it) and the check that its494+ * success encodes.495+ */496+const checked = <A, E>(497+ schemas: MethodSchema,498+ args: readonly unknown[],499+ run: Effect.Effect<A, E>500+): Effect.Effect<A, E> =>501+ Effect.forEach(502+ schemas.args,503+ (schema, index) =>504+ Effect.orDie(505+ Schema.decodeUnknownEffect(Schema.toType(schema))(args[index])506+ ),507+ { discard: true }508+ ).pipe(509+ Effect.andThen(run),510+ Effect.tap((value) =>511+ Effect.orDie(Schema.encodeUnknownEffect(schemas.success)(value))512+ )513+ );514+515+const mainRef = RefName.make("refs/heads/main");516+517+const HOUR = 3_600_000;518+519+/** The claim deadlines before a project has a policy: the defaults (spec §2.5). */520+const defaultClaims: Policy["claims"] = {521+ lapseAfterMs: 24 * HOUR,522+ warnAfterMs: 2 * HOUR,523+};524+525+interface Claimed {526+ readonly row: ClaimRow;527+ readonly state: ClaimState;528+}529+530+interface Answered {531+ readonly record: AnswerRecord;532+ readonly row: AnswerRow;533+}534+535+/** A project as one call reads it at its start. */536+interface Hydrated {537+ readonly answers: readonly Answered[];538+ readonly asks: ReadonlyMap<AskId, Ask>;539+ readonly claims: readonly Claimed[];540+ readonly landings: readonly LandingView[];541+ readonly lastSeq: number;542+ readonly outbox: readonly OutboxRow[];543+ readonly policy: Option.Option<Policy>;544+ readonly project: Option.Option<ProjectRow>;545+ readonly queue: LandingQueue;546+}547+548+/**549+ * What one call writes, gathered as it goes and committed at its end. The550+ * project row and the queue are kept in one-entry maps, so the record itself551+ * never changes.552+ */553+interface Writes {554+ readonly answers: Map<RequestId, AnswerRow>;555+ readonly asks: Map<AskId, Ask>;556+ readonly claims: Map<string, ClaimRow>;557+ readonly events: ProjectEventInput[];558+ readonly landings: LandingView[];559+ readonly outbox: OutboxRow[];560+ readonly project: Map<"row", ProjectRow>;561+ readonly pushEvents: PushEventRow[];562+ readonly queue: Map<"queue", LandingQueue>;563+}564+565+const writesOf = (): Writes => ({566+ answers: new Map(),567+ asks: new Map(),568+ claims: new Map(),569+ events: [],570+ landings: [],571+ outbox: [],572+ project: new Map(),573+ pushEvents: [],574+ queue: new Map(),575+});576+577+const isEmpty = (writes: Writes) =>578+ [579+ writes.answers.size,580+ writes.asks.size,581+ writes.claims.size,582+ writes.events.length,583+ writes.landings.length,584+ writes.outbox.length,585+ writes.project.size,586+ writes.pushEvents.length,587+ writes.queue.size,588+ ].every((count) => count === 0);589+590+const claimKey = (ask: AskId, claimant: Handle) =>591+ JSON.stringify([ask, claimant.toLowerCase()]);592+593+/** A claim's own fields, in every state but `Open`. */594+const claimOf = (state: ClaimState): Option.Option<Live> =>595+ ClaimState.match(state, {596+ Answered: (claim) => Option.some<Live>(claim),597+ Lapsed: (claim) => Option.some<Live>(claim),598+ Live: (claim) => Option.some<Live>(claim),599+ Open: () => Option.none(),600+ Released: (claim) => Option.some<Live>(claim),601+ Warned: (claim) => Option.some<Live>(claim),602+ });603+604+const isLive = ClaimState.isAnyOf(["Live", "Warned"]);605+606+/** When a live claim's next deadline is: its warning, or once warned its lapse. */607+const deadlineOf = (state: ClaimState): Option.Option<DateTime.Utc> =>608+ ClaimState.match(state, {609+ Answered: () => Option.none(),610+ Lapsed: () => Option.none(),611+ Live: ({ warnsAt }) => Option.some(warnsAt),612+ Open: () => Option.none(),613+ Released: () => Option.none(),614+ Warned: ({ lapsesAt }) => Option.some(lapsesAt),615+ });616+617+const isDecider = (policy: Policy, handle: Handle) =>618+ policy.deciders.some(({ handles }) =>619+ handles.some((each) => sameHandle(each, handle))620+ );621+622+/**623+ * Whether `handle` decides for the ask's territory: a deciders entry whose624+ * glob holds one of the territory's globs, each read as the path it spells625+ * (`packages/**` holds `packages/parser/**`; `**` holds every territory).626+ */627+const decidesOn = (policy: Policy, ask: Ask, handle: Handle) =>628+ decidersFor(629+ policy,630+ ask.territory.paths.map((glob) => RepoPath.make(glob))631+ ).some((each) => sameHandle(each, handle));632+633+/** A path a composed commit can hold: plain folder names and a file name. */634+const isPlainPath = (path: string) =>635+ path636+ .split("/")637+ .every(638+ (segment) =>639+ segment !== "" &&640+ segment !== "." &&641+ segment !== ".." &&642+ segment !== ".git"643+ );644+645+/** Whether the brief holds a field its kind requires. */646+const holds = (ask: Ask, wanted: AskKind["requires"][number]) =>647+ Match.value(wanted).pipe(648+ Match.when("want", () => ask.brief.want.length > 0),649+ Match.when("current", () => ask.brief.current !== undefined),650+ Match.when("outOfScope", () => ask.brief.outOfScope !== undefined),651+ Match.when("terms", () => ask.brief.terms !== undefined),652+ Match.when("context", () => ask.brief.context !== undefined),653+ Match.whenOr("check", "territory", () => true),654+ Match.exhaustive655+ );656+657+/** An optional field as an object to spread: the field when present, nothing when not. */658+const field = <K extends string, A>(659+ key: K,660+ value: Option.Option<A>661+): Partial<Record<K, A>> =>662+ Option.match(value, {663+ onNone: () => ({}),664+ onSome: (present) => Record.singleton(key, present),665+ });666+667+/** The credit an answer's landing carries: who asked, who answered, who mentored. */668+const creditsFor = (ask: Ask, answerer: Handle): readonly Credit[] => [669+ { handle: ask.askedBy, role: "Asked-by" },670+ { handle: answerer, role: "Signed-off-by" },671+ ...Option.toArray(672+ Option.map(Option.fromUndefinedOr(ask.mentor), (handle): Credit => ({673+ handle,674+ role: "Mentored-by",675+ }))676+ ),677+];678+679+/** What a check of `ask` runs, and the lane it reports as. */680+const askLaneOf = (policy: Policy, ask: Ask) =>681+ commandFor(ask.check, policy.run, policy.ratchets);682+683+/** The lanes an answer's checks run: the ask's own check, then every project lane. */684+const lanesOf = (685+ policy: Policy,686+ ask: Option.Option<Ask>687+): readonly CheckLane[] => [688+ ...Option.toArray(689+ Option.flatMap(ask, (asked) =>690+ Option.map(askLaneOf(policy, asked), ({ command, lane }) =>691+ CheckLane.make({ command, lane })692+ )693+ )694+ ),695+ ...Record.toEntries(policy.run.checks).map(([lane, command]) =>696+ CheckLane.make({ command, lane })697+ ),698+];699+700+/** A section of a brief, when it has lines. */701+const section = (heading: string, lines: readonly string[] | undefined) =>702+ lines === undefined || lines.length === 0703+ ? []704+ : ["", `## ${heading}`, "", ...lines];705+706+const listed = (lines: readonly string[] | undefined) =>707+ lines?.map((line) => `- ${line}`);708+709+/** What an ask's check holds it to, in a sentence. */710+const checkLine = (check: CheckSpec) =>711+ CheckSpec.match(check, {712+ LintToZero: ({ rule }) =>713+ `The lint rule \`${rule}\` reports nothing in the territory.`,714+ Migrate: ({ from, to }) =>715+ to === undefined716+ ? `No caller uses \`${from}\`.`717+ : `No caller uses \`${from}\`; they use \`${to}\`.`,718+ Ratchet: ({ ratchet }) => `The ratchet \`${ratchet}\` goes down.`,719+ RedThenGreen: ({ path }) =>720+ `\`${path}\` fails on main by an assertion; it passes once answered.`,721+ SymbolAbsent: ({ symbol }) => `Nothing uses \`${symbol}\` any more.`,722+ });723+724+/** The ask as an answerer reads it first, in Markdown. */725+const briefOf = (ask: Ask): string => {726+ const { brief, territory } = ask;727+ const paths = territory.paths.map((path) => `\`${path}\``).join(", ");728+729+ return [730+ `# ${brief.want}`,731+ "",732+ `Ask \`${ask.id}\` in ${ask.project}, a \`${ask.kind}\` ask from ${ask.askedBy}.`,733+ ...section("Territory", [`The module \`${territory.module}\`: ${paths}.`]),734+ ...section(735+ "Current",736+ Option.toArray(Option.fromUndefinedOr(brief.current))737+ ),738+ ...section("Check", [checkLine(ask.check)]),739+ ...section("Out of scope", listed(brief.outOfScope)),740+ ...section("Terms", listed(brief.terms)),741+ ...section("Context", listed(brief.context)),742+ "",743+ ].join("\n");744+};745+746+/** The refusal `submitAnswer` gives for one from the gate: its own, or `NotClaimed`. */747+const submitRefusal = (refusal: Refusal, ask: AskId): SubmitRefusal =>748+ Match.value(refusal).pipe(749+ Match.tag(750+ "ClaimLapsed",751+ "NotClaimed",752+ "OutOfScope",753+ "PrivatePathInPublicTree",754+ "ReachedInternals",755+ "RepoBusy",756+ "StaleBase",757+ "TouchedJudge",758+ "Weakened",759+ (kept): SubmitRefusal => kept760+ ),761+ Match.orElse(() => NotClaimed.of(ask))762+ );763+764+/** A landing's commit message, from the platform's own rows (spec §5 step 8). */765+const messageOf = (766+ request: Request,767+ ask: Option.Option<Ask>,768+ verdict: Verdict769+): string => {770+ const message = {771+ assisted: request.assisted,772+ credits: request.credits,773+ requestId: request.requestId,774+ subject: "Land a change",775+ verdict: { checkVersion: verdict.checkVersion, patchId: verdict.patchId },776+ };777+778+ return formatLanding(779+ Option.match(ask, {780+ onNone: () => message,781+ onSome: ({ brief, id, project }) => ({782+ ...message,783+ ask: { ask: id, project },784+ body: brief.want,785+ subject: `Answer ${id}`,786+ }),787+ })788+ );789+};790+791+/** Answers oldest first, by when their row last moved. */792+const byUpdated = Order.mapInput(793+ DateTime.Order,794+ ({ row }: Answered) => row.updatedAt795+);796+797+/** A `Landed` event with the verdict the landing carries; any other event as it is. */798+const withVerdict = (799+ event: ProjectEventInput,800+ verdict: Option.Option<Verdict>801+): ProjectEventInput =>802+ Match.value(event).pipe(803+ Match.tag("Landed", (landed): ProjectEventInput => ({804+ ...landed,805+ landing: { ...landed.landing, ...field("verdict", verdict) },806+ })),807+ Match.orElse((other) => other)808+ );809+810+/** Whether a landing's effect is for the answer's run: a step, or a retry to wait for. */811+const runnable = (effect: LandingEffect) =>812+ isStep(effect) || LandingEffect.$is("Retry")(effect);813+814+const isTouchedJudge = (refusal: Refusal): refusal is TouchedJudge =>815+ Match.value(refusal).pipe(816+ Match.tag("TouchedJudge", () => true),817+ Match.orElse(() => false)818+ );819+820+type Checking = Extract<LandingState, { readonly _tag: "Checking" }>;821+822+type Landing = Extract<LandingState, { readonly _tag: "Landing" }>;823+824+/** What a landing's effects leave: the steps to hand to the run, and the queue. */825+interface Settled {826+ readonly queue: LandingQueue;827+ readonly steps: readonly LandingEffect[];828+}829+830+/** Starts the run of a request the queue just admitted, unless it is the one advancing. */831+const startOther = (832+ writes: Writes,833+ admitted: Option.Option<RequestId>,834+ advancing: RequestId,835+ now: DateTime.Utc836+) =>837+ Option.match(838+ Option.filter(admitted, (id) => id !== advancing),839+ {840+ onNone: () => Effect.void,841+ onSome: (id) =>842+ Effect.map(startRow(id, now), (row) => writes.outbox.push(row)),843+ }844+ );845+846+/** Whether an ask's check file has one of the five weak shapes. */847+const weakness = (ask: Ask, files: readonly AskFile[]) => {848+ const { check } = ask;849+850+ const file = CheckSpec.guards.RedThenGreen(check)851+ ? Option.fromUndefinedOr(files.find(({ path }) => path === check.path))852+ : Option.none<AskFile>();853+854+ return Option.flatMap(file, (found) =>855+ Array.head(weaknessesOf(found, ask.territory.paths))856+ );857+};858+859+/** Stage 0–1's refusals for a push, every one; what a missing commit or repo comes to. */860+const gateOf = (861+ facts: Effect.Effect<PushFacts, RepoNotFound | MissingCommit>,862+ missing: readonly Refusal[],863+ stale: readonly Refusal[]864+) =>865+ facts.pipe(866+ Effect.flatMap((each) => runGate(pushStages, each)),867+ Effect.map((found) =>868+ Option.getOrElse(869+ Option.map(found, (all): readonly Refusal[] => all),870+ () => []871+ )872+ ),873+ Effect.catchTags({874+ MissingCommit: () => Effect.succeed(stale),875+ RepoNotFound: () => Effect.succeed(missing),876+ })877+ );878+879+/** The queue once a request no longer landing has left its place in it. */880+const leaveIfDone = (881+ writes: Writes,882+ queue: LandingQueue,883+ input: {884+ readonly now: DateTime.Utc;885+ readonly requestId: RequestId;886+ readonly state: LandingState;887+ }888+) => {889+ const { requestId } = input;890+891+ const inLine = holdsSlot(queue, requestId) || queue.order.includes(requestId);892+893+ if (LandingState.guards.Landing(input.state) || !inLine) {894+ return Effect.succeed(queue);895+ }896+897+ const left = leave(queue, requestId);898+899+ return Effect.as(900+ startOther(writes, left.admitted, requestId, input.now),901+ left.queue902+ );903+};904+905+/** One project's service over the ports. */906+export const projectService = (907+ name: ProjectName908+): Effect.Effect<ProjectApi, never, ProjectPorts> =>909+ Effect.gen(function* () {910+ const ports = yield* Effect.context<ProjectPorts>();911+ const store = Context.get(ports, ProjectStore);912+ const host = Context.get(ports, RepoHost);913+ const lander = Context.get(ports, Lander);914+ const runner = Context.get(ports, CheckRunner);915+ const rules = Context.get(ports, RulesEvaluator);916+ const alarms = Context.get(ports, Alarms);917+ const lock = yield* Semaphore.make(1);918+ const repo = RepoName.make(name);919+920+ const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>921+ Effect.provideContext(effect, ports);922+923+ // ----------------------------------------------------------- hydrate924+925+ const hydrate: Effect.Effect<Hydrated> = Effect.gen(function* () {926+ const snapshot = yield* store.load();927+928+ const policy = yield* Option.match(929+ Option.flatMap(snapshot.project, (row) =>930+ Option.fromUndefinedOr(row.policy)931+ ),932+ {933+ onNone: () => Effect.succeedNone,934+ onSome: (json) => Effect.asSome(Effect.orDie(decodePolicy(json))),935+ }936+ );937+938+ const claims = yield* Effect.forEach(snapshot.claims, (row) =>939+ Effect.map(Effect.orDie(decodeClaim(row.state)), (state) => ({940+ row,941+ state,942+ }))943+ );944+945+ const answers = yield* Effect.forEach(snapshot.answers, (row) =>946+ Effect.map(Effect.orDie(decodeAnswer(row.state)), (record) => ({947+ record,948+ row,949+ }))950+ );951+952+ return {953+ answers,954+ asks: new Map(snapshot.asks.map((ask) => [ask.id, ask])),955+ claims,956+ landings: snapshot.landings,957+ lastSeq: snapshot.lastSeq,958+ outbox: snapshot.outbox,959+ policy,960+ project: snapshot.project,961+ queue: yield* queueOf(snapshot.queue),962+ };963+ });964+965+ /** The project row once it is live: it has a landed SHA. */966+ const liveRow = (h: Hydrated) =>967+ Option.flatMap(h.project, (row) =>968+ row.state === "live" && row.landed !== undefined969+ ? Option.some({ landed: row.landed, row })970+ : Option.none()971+ );972+973+ /** The ask as this call has it: as written so far, or as hydrated. */974+ const askNow = (h: Hydrated, writes: Writes, id: AskId) =>975+ Option.fromUndefinedOr(writes.asks.get(id) ?? h.asks.get(id));976+977+ const ownClaim = (h: Hydrated, ask: AskId, handle: Handle) =>978+ Option.fromUndefinedOr(979+ h.claims.find(980+ ({ row }) => row.ask === ask && sameHandle(row.claimant, handle)981+ )982+ );983+984+ const heldBy = (h: Hydrated, handle: Handle, except?: AskId) =>985+ h.claims.filter(986+ ({ row, state }) =>987+ isLive(state) &&988+ row.ask !== except &&989+ sameHandle(row.claimant, handle)990+ ).length;991+992+ const findAnswer = (h: Hydrated, requestId: RequestId) =>993+ Option.fromUndefinedOr(994+ h.answers.find(({ row }) => row.requestId === requestId)995+ );996+997+ const claimsPolicy = (h: Hydrated) =>998+ Option.getOrElse(999+ Option.map(h.policy, ({ claims }) => claims),1000+ () => defaultClaims1001+ );1002+1003+ /** A claim as its claimant sees it: with its fork's gateway URL and its check. */1004+ const viewOf = (1005+ policy: Option.Option<Policy>,1006+ ask: Option.Option<Ask>,1007+ state: ClaimState1008+ ) =>1009+ Effect.gen(function* () {1010+ const gateway = yield* GatewayUrl;1011+1012+ const checkCommand = Option.getOrElse(1013+ Option.flatMap(1014+ Option.all({ ask, policy }),1015+ ({ ask: asked, policy: at }) =>1016+ Option.map(askLaneOf(at, asked), ({ command }): string => command)1017+ ),1018+ () => `${Brand.cli} check`1019+ );1020+1021+ return Option.flatMap(claimOf(state), ({ fork }) =>1022+ toView(state, {1023+ checkCommand,1024+ project: name,1025+ remote: `${gateway}/${fork}.git`,1026+ })1027+ );1028+ });1029+1030+ // ------------------------------------------------------------ commit1031+1032+ /**1033+ * Writes everything the call gathered in one commit, with the events'1034+ * projection rows beside them, and returns the outbox rows it wrote. A1035+ * commit carrying a push event already stored wrote nothing: none.1036+ */1037+ const commit = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1038+ Effect.gen(function* () {1039+ if (isEmpty(writes)) {1040+ return [];1041+ }1042+1043+ const events = yield* numbered(h.lastSeq, writes.events);1044+ const projected = yield* projectedRows(name, events, now);1045+1046+ const outbox = [...writes.outbox, ...projected];1047+1048+ const queue = yield* Effect.forEach(writes.queue.values(), (each) =>1049+ storedQueue(each)1050+ );1051+1052+ const all: ProjectWrites = {1053+ answers: [...writes.answers.values()],1054+ asks: [...writes.asks.values()],1055+ claims: [...writes.claims.values()],1056+ events: writes.events,1057+ landings: writes.landings,1058+ outbox,1059+ pushEvents: writes.pushEvents,1060+ ...field(1061+ "project",1062+ Option.fromUndefinedOr(writes.project.get("row"))1063+ ),1064+ ...field("queue", Array.head(queue)),1065+ };1066+1067+ const committed = yield* store.commit(all);1068+1069+ if (committed.duplicatePushEvents.length > 0) {1070+ return [];1071+ }1072+1073+ const expected = events.map(({ seq }) => seq);1074+1075+ if (1076+ committed.seqs.length !== expected.length ||1077+ committed.seqs.some((seq, index) => seq !== expected[index])1078+ ) {1079+ return yield* Effect.die(1080+ "the store numbered a commit's events otherwise than its projection rows"1081+ );1082+ }1083+1084+ return outbox;1085+ });1086+1087+ // ------------------------------------------------------------ settle1088+1089+ /** Sets the project's alarm to its earliest pending deadline or retry. */1090+ const armAlarm = Effect.gen(function* () {1091+ const h = yield* hydrate;1092+1093+ const deadlines = [1094+ ...h.claims.flatMap(({ state }) => Option.toArray(deadlineOf(state))),1095+ ...h.outbox.map(({ notBefore }) => notBefore),1096+ ];1097+1098+ if (Array.isReadonlyArrayNonEmpty(deadlines)) {1099+ yield* alarms.set(Array.min(deadlines, DateTime.Order));1100+ }1101+ });1102+1103+ /**1104+ * Runs the outbox rows that are due, acknowledges the ones done, puts1105+ * the rest back with a later time, then sets the alarm.1106+ */1107+ const settle = (queue: AnswerQueue, rows: readonly OutboxRow[]) =>1108+ Effect.gen(function* () {1109+ const now = yield* DateTime.now;1110+1111+ const due = Array.dedupeWith(1112+ rows.filter((row) => isDue(row, now)),1113+ (one, other) => one.id === other.id1114+ );1115+1116+ if (Array.isReadonlyArrayNonEmpty(due)) {1117+ const ran = yield* withPorts(runOutbox(due, queue, now));1118+1119+ yield* store.ackOutbox(ran.done);1120+1121+ if (Array.isReadonlyArrayNonEmpty(ran.retry)) {1122+ yield* lock.withPermits(1)(store.commit({ outbox: ran.retry }));1123+ }1124+ }1125+1126+ yield* armAlarm;1127+ });1128+1129+ /**1130+ * One call that writes: under the project's lock it hydrates, runs1131+ * `body` (pure transitions, and the port calls that decide them), and1132+ * commits what it gathered; then, outside the lock, settles the outbox1133+ * rows it wrote. A body that fails commits nothing.1134+ */1135+ const write = <A, E>(1136+ queue: AnswerQueue,1137+ body: (1138+ h: Hydrated,1139+ writes: Writes,1140+ now: DateTime.Utc1141+ ) => Effect.Effect<A, E>1142+ ): Effect.Effect<A, E> =>1143+ Effect.gen(function* () {1144+ const [answered, rows] = yield* lock.withPermits(1)(1145+ Effect.gen(function* () {1146+ const h = yield* hydrate;1147+ const now = yield* DateTime.now;1148+ const writes = writesOf();1149+ const result = yield* body(h, writes, now);1150+1151+ return [result, yield* commit(h, writes, now)] as const;1152+ })1153+ );1154+1155+ yield* settle(queue, rows);1156+1157+ return answered;1158+ });1159+1160+ // ------------------------------------------------------------ claims1161+1162+ /** The ask's state once a claim on it moved: claimed while a live claim holds it. */1163+ const askAfter = (1164+ h: Hydrated,1165+ writes: Writes,1166+ ask: AskId,1167+ step: ClaimStep1168+ ) => {1169+ const open = Option.filter(1170+ askNow(h, writes, ask),1171+ ({ state }) =>1172+ state !== "closed" && !ClaimState.guards.Answered(step.state)1173+ );1174+1175+ if (Option.isNone(open)) {1176+ return;1177+ }1178+1179+ const claimant = Option.map(1180+ claimOf(step.state),1181+ (claim) => claim.claimant1182+ );1183+1184+ const others = h.claims.some(1185+ ({ row, state }) =>1186+ row.ask === ask &&1187+ isLive(state) &&1188+ !Option.exists(claimant, (each) => sameHandle(row.claimant, each))1189+ );1190+1191+ const next = isLive(step.state) || others ? "claimed" : "open";1192+1193+ if (next !== open.value.state) {1194+ writes.asks.set(ask, { ...open.value, state: next });1195+ }1196+ };1197+1198+ /** Records a claim's step: its row, its fork, its events and its ask's state. */1199+ const applyClaim = (1200+ h: Hydrated,1201+ writes: Writes,1202+ ask: AskId,1203+ step: ClaimStep,1204+ now: DateTime.Utc1205+ ) =>1206+ Effect.gen(function* () {1207+ const claim = claimOf(step.state);1208+1209+ if (Option.isNone(claim)) {1210+ return;1211+ }1212+1213+ const { claimant } = claim.value;1214+1215+ writes.claims.set(claimKey(ask, claimant), {1216+ ask,1217+ claimant,1218+ state: yield* Effect.orDie(encodeClaim(step.state)),1219+ updatedAt: now,1220+ });1221+1222+ yield* Effect.forEach(1223+ step.effects,1224+ (effect) =>1225+ ClaimEffect.$match(effect, {1226+ Emit: ({ event }) => Effect.sync(() => writes.events.push(event)),1227+ MakeFork: ({ from, name: fork }) =>1228+ Effect.map(1229+ outboxRow(1230+ `fork:${fork}`,1231+ OutboxBody.cases.MakeFork.make({ from, name: fork }),1232+ now1233+ ),1234+ (row) => writes.outbox.push(row)1235+ ),1236+ // Custody reads the claim's state: a lapsed or released claim's1237+ // fork takes no push, and the fork stays.1238+ RevokeAccess: () => Effect.void,1239+ // The alarm is set once settled, to the earliest deadline of all.1240+ SetAlarm: () => Effect.void,1241+ }),1242+ { discard: true }1243+ );1244+1245+ askAfter(h, writes, ask, step);1246+ });1247+1248+ // ------------------------------------------------------------ policy1249+1250+ /** The config folder at a commit, evaluated; none when it can't be. */1251+ const evaluateAt = (row: ProjectRow, at: LandedSha, now: DateTime.Utc) =>1252+ Effect.gen(function* () {1253+ const previous = yield* Option.match(1254+ Option.fromUndefinedOr(row.policy),1255+ {1256+ onNone: () => Effect.succeedNone,1257+ onSome: (json) => Effect.asSome(Effect.orDie(decodePolicy(json))),1258+ }1259+ );1260+1261+ const vouchFile = Option.getOrElse(1262+ Option.map(previous, ({ vouch }) => vouch.file),1263+ () => RepoPath.make(`${Brand.configDir}/vouched.td`)1264+ );1265+1266+ const bundle = yield* Effect.option(lander.bundleRules({ at, repo }));1267+1268+ if (Option.isNone(bundle)) {1269+ yield* Effect.logWarning(1270+ `the config folder at ${at} could not be read`1271+ );1272+1273+ return Option.none<Policy>();1274+ }1275+1276+ const facts = yield* withPorts(1277+ evaluationFacts(repo, at, {1278+ initializer: row.initializer,1279+ now,1280+ project: name,1281+ vouchFile,1282+ })1283+ );1284+1285+ return yield* rules.evaluate({ at, facts, modules: bundle.value }).pipe(1286+ Effect.asSome,1287+ Effect.catchTag("RulesFailed", (failed) =>1288+ Effect.as(1289+ Effect.logWarning(`the policy at ${at} did not evaluate`, failed),1290+ Option.none<Policy>()1291+ )1292+ )1293+ );1294+ });1295+1296+ /**1297+ * The project row with the policy at `at`: the config folder bundled1298+ * there and evaluated. A Lander or evaluator that fails keeps the policy1299+ * the row held (spec §5 step 2).1300+ */1301+ const withPolicyAt = (row: ProjectRow, at: LandedSha, now: DateTime.Utc) =>1302+ Effect.flatMap(evaluateAt(row, at, now), (policy) =>1303+ Option.match(policy, {1304+ onNone: () => Effect.succeed(row),1305+ onSome: (found) =>1306+ Effect.map(Effect.orDie(encodePolicy(found)), (encoded) => ({1307+ ...row,1308+ policy: encoded,1309+ policyAt: at,1310+ })),1311+ })1312+ );1313+1314+ /** A `main` for an imported repo whose branch had another name, at its tip. */1315+ const mainAt = (tip: CommitSha) =>1316+ Effect.gen(function* () {1317+ const empty = { fs: memoryFs(), gitdir: "/adopt.git" };1318+1319+ yield* Effect.tryPromise(() => init({ ...empty, bare: true })).pipe(1320+ Effect.orDie1321+ );1322+1323+ yield* host1324+ .push(repo, empty, [{ from: Option.none(), ref: mainRef, to: tip }])1325+ .pipe(1326+ Effect.mapError(1327+ () => new ImportFailed({ reason: "main could not be made" })1328+ )1329+ );1330+ });1331+1332+ /**1333+ * An imported repo adopted: its tip becomes the first landed SHA, on a1334+ * `main` of its own when the imported branch had another name.1335+ */1336+ const adopt = (from: { readonly branch?: string; readonly url: string }) =>1337+ Effect.gen(function* () {1338+ const branch = Option.map(1339+ Option.fromUndefinedOr(from.branch),1340+ Schema.decodeOption(BranchName)1341+ );1342+1343+ if (Option.exists(branch, Option.isNone)) {1344+ return yield* new ImportFailed({1345+ reason: `${from.branch} is no branch name`,1346+ });1347+ }1348+1349+ const named = Option.flatten(branch);1350+1351+ yield* host1352+ .importFrom(repo, { url: from.url, ...field("branch", named) })1353+ .pipe(1354+ Effect.catchTags({1355+ ImportRefused: ({ reason }) =>1356+ Effect.fail(1357+ new ImportFailed({1358+ reason: reason === "" ? "the import was refused" : reason,1359+ })1360+ ),1361+ RepoExists: () =>1362+ Effect.fail(new ProjectExists({ project: name })),1363+ })1364+ );1365+1366+ const refs = yield* host.refs(repo).pipe(Effect.orDie);1367+1368+ const imported = RefName.make(1369+ `refs/heads/${Option.getOrElse(named, () => "main")}`1370+ );1371+1372+ const tip = Option.fromNullishOr(1373+ refs.get(mainRef) ?? refs.get(imported)1374+ );1375+1376+ if (Option.isNone(tip)) {1377+ return yield* new ImportFailed({1378+ reason: `${from.url} has no commits`,1379+ });1380+ }1381+1382+ if (!refs.has(mainRef)) {1383+ yield* mainAt(tip.value);1384+ }1385+1386+ return LandedSha.make(tip.value);1387+ });1388+1389+ // ------------------------------------------------------------ answers1390+1391+ /** The answer's run, as `answer` and a step see it. */1392+ const runOf = (h: Hydrated, found: Answered): AnswerRun => {1393+ const { landing, verdict } = found.record;1394+ const { request } = landing;1395+1396+ const ask = Option.flatMap(request.ask, (id) =>1397+ Option.fromUndefinedOr(h.asks.get(id))1398+ );1399+1400+ const known = Option.all({ ask, policy: h.policy });1401+1402+ const finish = Option.getOrElse(1403+ Option.flatMap(known, ({ ask: asked, policy }) =>1404+ Option.fromUndefinedOr(1405+ policy.kinds.find((kind) => kind.name === asked.kind)?.finish1406+ )1407+ ),1408+ (): AskKind["finish"] => "optional"1409+ );1410+1411+ const askLane = Option.flatMap(known, ({ ask: asked, policy }) =>1412+ Option.map(askLaneOf(policy, asked), ({ lane }): LaneName => lane)1413+ );1414+1415+ const judgedRun = Option.map(Option.fromUndefinedOr(verdict), (each) => ({1416+ message: messageOf(request, ask, each),1417+ verdict: each,1418+ }));1419+1420+ return {1421+ admitted: holdsSlot(h.queue, request.requestId),1422+ finish,1423+ lanes: Option.getOrElse(1424+ Option.map(h.policy, (policy) => lanesOf(policy, ask)),1425+ () => []1426+ ),1427+ repo,1428+ state: landing,1429+ ...field("ask", ask),1430+ ...field("askLane", askLane),1431+ ...Option.getOrElse(judgedRun, () => ({})),1432+ };1433+ };1434+1435+ /** The verdict on a checked tree: the gate's `verdictOf` over what the checks saw. */1436+ const verdictFor = (input: {1437+ readonly ask: Ask;1438+ readonly checking: Checking;1439+ readonly heldBack: readonly HeldBackResult[];1440+ readonly lanes: readonly LaneResult[];1441+ readonly now: DateTime.Utc;1442+ readonly outcome: Outcome;1443+ readonly policy: Policy;1444+ readonly stage: StageName;1445+ }) =>1446+ Effect.gen(function* () {1447+ const { ask, checking, policy } = input;1448+ const { request } = checking;1449+1450+ // `verdictOf` reads the ask, base and head; the rest stand as the1451+ // answer's merge left them.1452+ const facts: PushFacts = {1453+ addedLines: new Map(),1454+ ask: Option.some(ask),1455+ base: request.base,1456+ changes: checking.changes,1457+ claim: Option.none(),1458+ claimsHeld: 0,1459+ head: request.head,1460+ landed: checking.main,1461+ layerPaths: new Set(),1462+ opensAsk: false,1463+ policy,1464+ pusher: Person.make({ handle: request.answerer }),1465+ ratchetCounts: new Map(),1466+ ref: RefNameText.make("refs/heads/main"),1467+ scriptsChanged: false,1468+ target: PushTarget.ClaimFork({1469+ ask: ask.id,1470+ claimant: request.answerer,1471+ project: name,1472+ }),1473+ };1474+1475+ return yield* Effect.orDie(1476+ Effect.fromResult(1477+ verdictOf({1478+ checkVersion: checkVersion(1479+ ask.check,1480+ sdkVersion,1481+ policy.run,1482+ policy.ratchets1483+ ),1484+ facts,1485+ heldBack: input.heldBack,1486+ lanes: input.lanes,1487+ now: input.now,1488+ outcome: input.outcome,1489+ patchId: yield* patchId(checking.changes),1490+ stage: input.stage,1491+ tree: checking.tree,1492+ })1493+ )1494+ );1495+ });1496+1497+ /** The claim that answered an ask, answered by its landing. */1498+ const answerClaim = (1499+ h: Hydrated,1500+ writes: Writes,1501+ ask: AskId,1502+ landing: { readonly answerer: Handle; readonly sha: LandedSha },1503+ now: DateTime.Utc1504+ ) =>1505+ Option.match(ownClaim(h, ask, landing.answerer), {1506+ onNone: () => Effect.void,1507+ onSome: ({ state }) =>1508+ Result.match(1509+ claimTransition(1510+ state,1511+ ClaimCommand.cases.Land.make({ landing: landing.sha }),1512+ now,1513+ claimsPolicy(h)1514+ ),1515+ {1516+ onFailure: () => Effect.void,1517+ onSuccess: (step) => applyClaim(h, writes, ask, step, now),1518+ }1519+ ),1520+ });1521+1522+ /**1523+ * A landing on main recorded: the landing, its ask closed, the answering1524+ * claim answered, the landed SHA moved and the policy read there.1525+ */1526+ const recordLanding = (1527+ h: Hydrated,1528+ writes: Writes,1529+ landing: Landing,1530+ landed: {1531+ readonly sha: LandedSha;1532+ readonly verdict: Option.Option<Verdict>;1533+ },1534+ now: DateTime.Utc1535+ ) =>1536+ Effect.gen(function* () {1537+ const { request } = landing;1538+ const { sha } = landed;1539+1540+ writes.landings.push({1541+ assisted: request.assisted,1542+ author: request.answerer,1543+ credits: request.credits,1544+ landedAt: now,1545+ parent: landing.main,1546+ project: name,1547+ requestId: request.requestId,1548+ sha,1549+ ...field("ask", request.ask),1550+ ...field("verdict", landed.verdict),1551+ });1552+1553+ if (Option.isSome(request.ask)) {1554+ const id = request.ask.value;1555+ const ask = askNow(h, writes, id);1556+1557+ if (Option.isSome(ask)) {1558+ writes.asks.set(id, { ...ask.value, state: "closed" });1559+ }1560+1561+ writes.events.push(askClosed(id, sha, now));1562+1563+ yield* answerClaim(1564+ h,1565+ writes,1566+ id,1567+ { answerer: request.answerer, sha },1568+ now1569+ );1570+ }1571+1572+ const row = Option.orElse(1573+ Option.fromUndefinedOr(writes.project.get("row")),1574+ () => h.project1575+ );1576+1577+ if (Option.isSome(row)) {1578+ writes.project.set(1579+ "row",1580+ yield* withPolicyAt({ ...row.value, landed: sha }, sha, now)1581+ );1582+ }1583+ });1584+1585+ /** One of a landing's effects, settled by the project or handed to its run. */1586+ const settleEffect = (1587+ context: {1588+ readonly before: LandingState;1589+ readonly h: Hydrated;1590+ readonly now: DateTime.Utc;1591+ readonly requestId: RequestId;1592+ readonly verdict: Option.Option<Verdict>;1593+ readonly writes: Writes;1594+ },1595+ settled: Settled,1596+ effect: LandingEffect1597+ ): Effect.Effect<Settled> => {1598+ const { before, h, now, requestId, verdict, writes } = context;1599+ const handed = { ...settled, steps: [...settled.steps, effect] };1600+1601+ return LandingEffect.$match(effect, {1602+ Emit: ({ event }) =>1603+ Effect.sync(() => {1604+ writes.events.push(withVerdict(event, verdict));1605+1606+ return settled;1607+ }),1608+ Land: () =>1609+ Effect.gen(function* () {1610+ const asked = askToLand(settled.queue, requestId);1611+1612+ yield* startOther(writes, asked.admitted, requestId, now);1613+1614+ return {1615+ queue: asked.queue,1616+ steps: holdsSlot(asked.queue, requestId)1617+ ? handed.steps1618+ : settled.steps,1619+ };1620+ }),1621+ Merge: () => Effect.succeed(handed),1622+ Record: ({ sha }) =>1623+ LandingState.guards.Landing(before)1624+ ? Effect.as(1625+ recordLanding(h, writes, before, { sha, verdict }, now),1626+ settled1627+ )1628+ : Effect.succeed(settled),1629+ Retry: ({ at }) =>1630+ Effect.map(startRow(requestId, at), (row) => {1631+ writes.outbox.push(row);1632+1633+ return handed;1634+ }),1635+ RunChecks: () => Effect.succeed(handed),1636+ });1637+ };1638+1639+ /**1640+ * The verdict after a step: a fresh one when the checks just judged the1641+ * tree under way, else the one the answer had.1642+ */1643+ const verdictAfter = (input: {1644+ readonly ask: Option.Option<Ask>;1645+ readonly before: LandingState;1646+ readonly command: LandingCommand;1647+ readonly h: Hydrated;1648+ readonly kept: Option.Option<Verdict>;1649+ readonly now: DateTime.Utc;1650+ readonly report: AnswerReport | undefined;1651+ readonly state: LandingState;1652+ }) => {1653+ const { before, command, state } = input;1654+ const known = Option.all({ ask: input.ask, policy: input.h.policy });1655+1656+ if (1657+ !LandingCommand.$is("Checked")(command) ||1658+ !LandingState.guards.Checking(before) ||1659+ before.tree !== command.tree ||1660+ state === before ||1661+ Option.isNone(known)1662+ ) {1663+ return Effect.succeed({ fresh: false, verdict: input.kept });1664+ }1665+1666+ return Effect.map(1667+ verdictFor({1668+ ask: known.value.ask,1669+ checking: before,1670+ heldBack: input.report?.heldBack ?? [],1671+ lanes: input.report?.lanes ?? [],1672+ now: input.now,1673+ outcome: outcomeOf(state),1674+ policy: known.value.policy,1675+ stage: command.refusals.length > 0 ? "checks" : "human",1676+ }),1677+ (made) => ({ fresh: true, verdict: Option.some(made) })1678+ );1679+ };1680+1681+ /** The row that lands a request's job again, for the bookkeeping it left unwritten. */1682+ const bookkeepingRow = (input: {1683+ readonly ask: Option.Option<Ask>;1684+ readonly landing: Landing;1685+ readonly now: DateTime.Utc;1686+ readonly verdict: Verdict;1687+ }) => {1688+ const { request } = input.landing;1689+1690+ return outboxRow(1691+ `bookkeeping:${request.requestId}`,1692+ OutboxBody.cases.Bookkeeping.make({1693+ job: {1694+ author: request.answerer,1695+ base: request.base,1696+ fork: request.fork,1697+ head: request.head,1698+ main: input.landing.main,1699+ message: messageOf(request, input.ask, input.verdict),1700+ repo,1701+ requestId: request.requestId,1702+ tree: input.landing.tree,1703+ verdict: input.verdict,1704+ },1705+ }),1706+ DateTime.addDuration(input.now, "1 second")1707+ );1708+ };1709+1710+ /** Bookkeeping a land reported unwritten: landed again later, for it alone. */1711+ const keepBooks = (input: {1712+ readonly ask: Option.Option<Ask>;1713+ readonly before: LandingState;1714+ readonly command: LandingCommand;1715+ readonly now: DateTime.Utc;1716+ readonly report: AnswerReport | undefined;1717+ readonly verdict: Option.Option<Verdict>;1718+ readonly writes: Writes;1719+ }) => {1720+ const { before } = input;1721+ const pending = input.report?.pending ?? [];1722+1723+ if (1724+ !LandingCommand.$is("LandedOk")(input.command) ||1725+ !LandingState.guards.Landing(before) ||1726+ pending.length === 0 ||1727+ Option.isNone(input.verdict)1728+ ) {1729+ return Effect.void;1730+ }1731+1732+ return Effect.map(1733+ bookkeepingRow({1734+ ask: input.ask,1735+ landing: before,1736+ now: input.now,1737+ verdict: input.verdict.value,1738+ }),1739+ (row) => input.writes.outbox.push(row)1740+ );1741+ };1742+1743+ /** One reported step of an answer, under the lock: its transition and all it settles. */1744+ const advanceBody =1745+ (requestId: RequestId, command: LandingCommand, report?: AnswerReport) =>1746+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1747+ Effect.gen(function* () {1748+ const found = findAnswer(h, requestId);1749+1750+ if (Option.isNone(found)) {1751+ return yield* Effect.die(`no answer request ${requestId}`);1752+ }1753+1754+ const { record, row } = found.value;1755+ const before = record.landing;1756+ const { effects, state } = landingTransition(before, command, now);1757+ const { request } = state;1758+1759+ const ask = Option.flatMap(request.ask, (id) =>1760+ askNow(h, writes, id)1761+ );1762+1763+ const { fresh, verdict } = yield* verdictAfter({1764+ ask,1765+ before,1766+ command,1767+ h,1768+ kept: Option.fromUndefinedOr(record.verdict),1769+ now,1770+ report,1771+ state,1772+ });1773+1774+ const refusedNow =1775+ LandingState.guards.Refused(state) &&1776+ !LandingState.guards.Refused(before);1777+1778+ if (Option.isSome(request.ask) && (fresh || refusedNow)) {1779+ writes.events.push(1780+ judged(request.ask.value, request.head, outcomeOf(state), now)1781+ );1782+ }1783+1784+ const settled = yield* Effect.reduce(1785+ effects,1786+ (): Settled => ({ queue: h.queue, steps: [] }),1787+ (each, effect) =>1788+ settleEffect(1789+ { before, h, now, requestId, verdict, writes },1790+ each,1791+ effect1792+ )1793+ );1794+1795+ const queue = yield* leaveIfDone(writes, settled.queue, {1796+ now,1797+ requestId,1798+ state,1799+ });1800+1801+ if (queue !== h.queue) {1802+ writes.queue.set("queue", queue);1803+ }1804+1805+ yield* keepBooks({1806+ ask,1807+ before,1808+ command,1809+ now,1810+ report,1811+ verdict,1812+ writes,1813+ });1814+1815+ if (state !== before || fresh) {1816+ writes.answers.set(requestId, {1817+ ...row,1818+ state: yield* Effect.orDie(1819+ encodeAnswer({1820+ ...record,1821+ landing: state,1822+ ...field("verdict", verdict),1823+ })1824+ ),1825+ updatedAt: now,1826+ });1827+ }1828+1829+ return {1830+ effects: settled.steps.filter(runnable),1831+ outcome: outcomeOf(state),1832+ };1833+ });1834+1835+ // ------------------------------------------------------------ writes1836+1837+ const initBody =1838+ (1839+ caller: Person,1840+ input: {1841+ readonly import?: { readonly branch?: string; readonly url: string };1842+ }1843+ ) =>1844+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1845+ Effect.gen(function* () {1846+ if (Option.isSome(h.project)) {1847+ return yield* new ProjectExists({ project: name });1848+ }1849+1850+ const remote = `${yield* GatewayUrl}/${name}.git`;1851+1852+ const made: ProjectRow = {1853+ createdAt: now,1854+ initializer: caller.handle,1855+ project: name,1856+ state: "awaitingFirstPush",1857+ };1858+1859+ if (input.import === undefined) {1860+ // A repo left by a call that failed after making it is this project's.1861+ yield* host1862+ .create(repo)1863+ .pipe(Effect.catchTag("RepoExists", () => Effect.void));1864+1865+ writes.project.set("row", made);1866+1867+ return { project: name, remote };1868+ }1869+1870+ const landed = yield* adopt(input.import);1871+1872+ writes.project.set(1873+ "row",1874+ yield* withPolicyAt({ ...made, landed, state: "live" }, landed, now)1875+ );1876+1877+ return { landed, project: name, remote };1878+ });1879+1880+ const firstPushBody =1881+ (caller: Person, head: CommitSha) =>1882+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>1883+ Effect.gen(function* () {1884+ const refused = new DirectPush({ ref: mainRef });1885+ const row = Option.getOrUndefined(h.project);1886+1887+ if (1888+ row === undefined ||1889+ !sameHandle(row.initializer, caller.handle)1890+ ) {1891+ return yield* refused;1892+ }1893+1894+ const landed = LandedSha.make(head);1895+1896+ if (row.state === "live") {1897+ return row.landed === landed ? { landed } : yield* refused;1898+ }1899+1900+ writes.project.set(1901+ "row",1902+ yield* withPolicyAt({ ...row, landed, state: "live" }, landed, now)1903+ );1904+1905+ return { landed };1906+ });1907+1908+ /**1909+ * The ask a decider's files state, read from the config folder at the1910+ * commit they compose; its kind, as every rule but the ask itself, is1911+ * main's (ADR 0005).1912+ */1913+ const statedAsk = (input: {1914+ readonly composed: CommitSha;1915+ readonly id: AskId;1916+ readonly now: DateTime.Utc;1917+ readonly policy: Policy;1918+ readonly row: ProjectRow;1919+ }) =>1920+ Effect.gen(function* () {1921+ const { id, policy } = input;1922+1923+ // The composed commit is never main; the evaluator reads it as it1924+ // would a landing, which is all the port knows how to name.1925+ const evaluated = yield* evaluateAt(1926+ input.row,1927+ LandedSha.make(input.composed),1928+ input.now1929+ );1930+1931+ if (Option.isNone(evaluated)) {1932+ return yield* new VerifierBlocked({});1933+ }1934+1935+ const stated = evaluated.value.asks.find((ask) => ask.id === id);1936+1937+ if (stated === undefined) {1938+ return yield* new IncompleteBrief({ missing: ["want"] });1939+ }1940+1941+ const kind = policy.kinds.find((each) => each.name === stated.kind);1942+1943+ const missing =1944+ kind === undefined1945+ ? ["kind"]1946+ : kind.requires.filter((each) => !holds(stated, each));1947+1948+ if (Array.isReadonlyArrayNonEmpty(missing)) {1949+ return yield* new IncompleteBrief({ missing });1950+ }1951+1952+ return stated;1953+ });1954+1955+ /** The judge an ask's files touch beyond their own (stage 1, as an ask opens). */1956+ const touchedJudge = (input: {1957+ readonly ask: Ask;1958+ readonly caller: Person;1959+ readonly files: readonly AskFile[];1960+ readonly head: CommitSha;1961+ readonly main: LandedSha;1962+ readonly policy: Policy;1963+ }) =>1964+ Effect.map(1965+ scan.run({1966+ addedLines: new Map(),1967+ ask: Option.some(input.ask),1968+ base: input.main,1969+ changes: input.files.map(({ path }) => ({1970+ path,1971+ status: "added" as const,1972+ })),1973+ claim: Option.none(),1974+ claimsHeld: 0,1975+ head: input.head,1976+ landed: input.main,1977+ layerPaths: new Set(),1978+ opensAsk: true,1979+ policy: input.policy,1980+ pusher: input.caller,1981+ ratchetCounts: new Map(),1982+ ref: RefNameText.make("refs/heads/main"),1983+ scriptsChanged: false,1984+ target: PushTarget.Canonical({ project: name }),1985+ }),1986+ (refusals) => Array.findFirst(refusals, isTouchedJudge)1987+ );1988+1989+ /** Red first: the ask's check fails twice on the composed commit, the same way. */1990+ const redTwice = (policy: Policy, ask: Ask, composed: CommitSha) =>1991+ Effect.gen(function* () {1992+ const lane = askLaneOf(policy, ask);1993+1994+ if (Option.isNone(lane)) {1995+ return yield* new NotRedFirst({});1996+ }1997+1998+ const job = {1999+ at: CheckAt.cases.Commit.make({ commit: composed }),2000+ lanes: [CheckLane.make(lane.value)],2001+ placeholders: [],2002+ project: name,2003+ proxies: [],2004+ repo,2005+ };2006+2007+ const first = yield* runner.run(job);2008+ const second = yield* runner.run(job);2009+2010+ return yield* Effect.fromResult(2011+ redFirstOfRuns([first, second], lane.value.lane)2012+ );2013+ });2014+2015+ /** The landing that opens an ask: its files on main, asked by the decider. */2016+ const landAsk = (input: {2017+ readonly ask: Ask;2018+ readonly caller: Person;2019+ readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;2020+ readonly main: LandedSha;2021+ readonly tree: Checking["tree"];2022+ }) => {2023+ const requestId = RequestId.make(`open-${input.tree}`);2024+2025+ const credits: readonly Credit[] = [2026+ { handle: input.caller.handle, role: "Asked-by" },2027+ ];2028+2029+ const landing = lander2030+ .land({2031+ author: input.caller.handle,2032+ main: input.main,2033+ message: formatLanding({2034+ ask: { ask: input.ask.id, project: name },2035+ assisted: [],2036+ body: input.ask.brief.want,2037+ credits,2038+ requestId,2039+ subject: `Open ask ${input.ask.id}`,2040+ }),2041+ rebuild: Rebuild.Compose({ files: input.files }),2042+ repo,2043+ requestId,2044+ tree: input.tree,2045+ verdict: Option.none(),2046+ })2047+ .pipe(2048+ Effect.catchTag("RepoBusy", () =>2049+ Effect.fail(new VerifierBlocked({}))2050+ )2051+ );2052+2053+ return Effect.map(landing, ({ sha }) => ({ credits, requestId, sha }));2054+ };2055+2056+ const openBody =2057+ (2058+ caller: Person,2059+ input: {2060+ readonly ask: AskId;2061+ readonly files: Array.NonEmptyReadonlyArray<AskFile>;2062+ }2063+ ) =>2064+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2065+ Effect.gen(function* () {2066+ const live = liveRow(h);2067+2068+ if (Option.isNone(live) || Option.isNone(h.policy)) {2069+ return yield* new VerifierBlocked({});2070+ }2071+2072+ const policy = h.policy.value;2073+2074+ if (!isDecider(policy, caller.handle)) {2075+ return yield* new NotDecider({});2076+ }2077+2078+ // An ask still open (or claimed) is not opened twice: the same2079+ // call again finds it as it stands, and nothing lands.2080+ const stillOpen = Option.filter(2081+ askNow(h, writes, input.ask),2082+ ({ state }) => state !== "closed"2083+ );2084+2085+ if (Option.isSome(stillOpen)) {2086+ return decidesOn(policy, stillOpen.value, caller.handle)2087+ ? { ask: stillOpen.value, landed: stillOpen.value.openedIn }2088+ : yield* new NotDecider({});2089+ }2090+2091+ const unplain = input.files.flatMap(({ path }) =>2092+ isPlainPath(path) ? [] : [path]2093+ );2094+2095+ if (Array.isReadonlyArrayNonEmpty(unplain)) {2096+ return yield* new TouchedJudge({ paths: unplain });2097+ }2098+2099+ const { landed: main, row } = live.value;2100+ const { files } = input;2101+ const composed = yield* lander.compose({ files, main, repo });2102+2103+ const stated = yield* statedAsk({2104+ composed: composed.commit,2105+ id: input.ask,2106+ now,2107+ policy,2108+ row,2109+ });2110+2111+ if (!decidesOn(policy, stated, caller.handle)) {2112+ return yield* new NotDecider({});2113+ }2114+2115+ const ask: Ask = {2116+ ...stated,2117+ askedBy: caller.handle,2118+ openedAt: now,2119+ project: name,2120+ state: "open",2121+ };2122+2123+ const touched = yield* touchedJudge({2124+ ask,2125+ caller,2126+ files,2127+ head: composed.commit,2128+ main,2129+ policy,2130+ });2131+2132+ if (Option.isSome(touched)) {2133+ return yield* touched.value;2134+ }2135+2136+ const weak = weakness(ask, files);2137+2138+ if (Option.isSome(weak)) {2139+ return yield* new WeakCheck({ weakness: weak.value });2140+ }2141+2142+ yield* redTwice(policy, ask, composed.commit);2143+2144+ const landed = yield* landAsk({2145+ ask,2146+ caller,2147+ files,2148+ main,2149+ tree: composed.tree,2150+ });2151+2152+ const opened: Ask = { ...ask, openedIn: landed.sha };2153+2154+ writes.asks.set(opened.id, opened);2155+ writes.events.push(askOpened(opened, now));2156+ writes.landings.push({2157+ assisted: [],2158+ author: caller.handle,2159+ credits: landed.credits,2160+ landedAt: now,2161+ parent: main,2162+ project: name,2163+ requestId: landed.requestId,2164+ sha: landed.sha,2165+ });2166+ writes.project.set(2167+ "row",2168+ yield* withPolicyAt({ ...row, landed: landed.sha }, landed.sha, now)2169+ );2170+2171+ return { ask: opened, landed: landed.sha };2172+ });2173+2174+ /** Whether a person may claim an ask, by the trust rules (220), and the ask's race. */2175+ const trustOf = (2176+ h: Hydrated,2177+ policy: Policy,2178+ ask: Ask,2179+ input: { readonly caller: Person; readonly now: DateTime.Utc }2180+ ) => {2181+ const { handle } = input.caller;2182+ const kind = policy.kinds.find((each) => each.name === ask.kind);2183+ const who = standing(policy, [], handle);2184+2185+ const record = recordOf({2186+ asks: h.asks,2187+ landings: h.landings,2188+ now: input.now,2189+ policy: policy.record,2190+ reverted: new Set(),2191+ })(handle);2192+2193+ const landingsInProject = h.landings.filter(({ author }) =>2194+ sameHandle(author, handle)2195+ ).length;2196+2197+ const admitted =2198+ kind !== undefined &&2199+ Result.isSuccess(2200+ mayClaim({2201+ ask,2202+ kind,2203+ landingsInProject,2204+ policy,2205+ record,2206+ standing: who,2207+ })2208+ );2209+2210+ return {2211+ denounced: who === "denounced",2212+ race: kind?.race ?? 1,2213+ vouched: admitted,2214+ };2215+ };2216+2217+ const claimBody =2218+ (caller: Person, id: AskId) =>2219+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2220+ Effect.gen(function* () {2221+ const ask = askNow(h, writes, id);2222+ const live = liveRow(h);2223+2224+ if (2225+ Option.isNone(ask) ||2226+ Option.isNone(h.policy) ||2227+ Option.isNone(live)2228+ ) {2229+ return yield* new UnknownAsk({ ask: id });2230+ }2231+2232+ const policy = h.policy.value;2233+2234+ if (ask.value.state === "closed") {2235+ return yield* new AskFull({ ask: id });2236+ }2237+2238+ const trust = trustOf(h, policy, ask.value, { caller, now });2239+2240+ const command = ClaimCommand.cases.Claim.make({2241+ base: live.value.landed,2242+ blockedBy: ask.value.blockedBy.filter(2243+ (blocker) => h.asks.get(blocker)?.state !== "closed"2244+ ),2245+ cap: policy.caps.claimsPerPerson,2246+ denounced: trust.denounced,2247+ heldByWho: heldBy(h, caller.handle, id),2248+ liveCount: h.claims.filter(2249+ ({ row, state }) =>2250+ row.ask === id &&2251+ isLive(state) &&2252+ !sameHandle(row.claimant, caller.handle)2253+ ).length,2254+ project: name,2255+ race: trust.race,2256+ vouched: trust.vouched,2257+ who: caller,2258+ });2259+2260+ const from = Option.match(ownClaim(h, id, caller.handle), {2261+ onNone: () => ClaimState.cases.Open.make({ ask: id }),2262+ onSome: ({ state }) => state,2263+ });2264+2265+ const step = yield* Effect.fromResult(2266+ claimTransition(from, command, now, policy.claims)2267+ ).pipe(2268+ Effect.catchTags({2269+ ClaimLapsed: (refused) => Effect.die(refused),2270+ NotClaimed: (refused) => Effect.die(refused),2271+ })2272+ );2273+2274+ if (step.effects.length > 0) {2275+ yield* applyClaim(h, writes, id, step, now);2276+ }2277+2278+ const view = yield* viewOf(h.policy, ask, step.state);2279+2280+ return yield* Option.match(view, {2281+ onNone: () => Effect.die("a granted claim has no view"),2282+ onSome: (claim) => Effect.succeed({ claim }),2283+ });2284+ });2285+2286+ const releaseBody =2287+ (caller: Person, id: AskId) =>2288+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2289+ Effect.gen(function* () {2290+ const own = ownClaim(h, id, caller.handle);2291+2292+ if (Option.isNone(own)) {2293+ return yield* NotClaimed.of(id);2294+ }2295+2296+ const step = yield* Effect.fromResult(2297+ claimTransition(2298+ own.value.state,2299+ ClaimCommand.cases.Release.make({ who: caller.handle }),2300+ now,2301+ claimsPolicy(h)2302+ )2303+ ).pipe(2304+ Effect.catchTags({2305+ AskBlocked: (refused) => Effect.die(refused),2306+ AskFull: (refused) => Effect.die(refused),2307+ CapReached: (refused) => Effect.die(refused),2308+ ClaimLapsed: (refused) => Effect.die(refused),2309+ Denounced: (refused) => Effect.die(refused),2310+ NotVouched: (refused) => Effect.die(refused),2311+ })2312+ );2313+2314+ if (step.effects.length > 0) {2315+ yield* applyClaim(h, writes, id, step, now);2316+ }2317+2318+ return { released: step.effects.length > 0 };2319+ });2320+2321+ /** The claimant's own push keeps their claim alive, whatever the gate says of it. */2322+ const keepAlive = (2323+ h: Hydrated,2324+ writes: Writes,2325+ input: {2326+ readonly claimed: Option.Option<Claimed>;2327+ readonly push: PushReport;2328+ },2329+ now: DateTime.Utc2330+ ) => {2331+ const { pusher } = input.push;2332+2333+ const own = Option.filter(2334+ input.claimed,2335+ ({ row }) =>2336+ Principal.guards.Person(pusher) &&2337+ sameHandle(pusher.handle, row.claimant)2338+ );2339+2340+ return Option.match(own, {2341+ onNone: () => Effect.void,2342+ onSome: ({ row, state }) =>2343+ Result.match(2344+ claimTransition(2345+ state,2346+ ClaimCommand.cases.Push.make({2347+ head: input.push.after,2348+ who: row.claimant,2349+ }),2350+ now,2351+ claimsPolicy(h)2352+ ),2353+ {2354+ onFailure: () => Effect.void,2355+ onSuccess: (step) => applyClaim(h, writes, row.ask, step, now),2356+ }2357+ ),2358+ });2359+ };2360+2361+ const pushBody =2362+ (input: PushReport) => (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2363+ Effect.gen(function* () {2364+ const live = liveRow(h);2365+2366+ if (Option.isNone(live) || Option.isNone(h.policy)) {2367+ return [];2368+ }2369+2370+ const target = targetOf(input.repo, name);2371+2372+ const fork = PushTarget.$is("ClaimFork")(target)2373+ ? Option.some(target)2374+ : Option.none();2375+2376+ const ask = Option.flatMap(fork, (on) => askNow(h, writes, on.ask));2377+2378+ const claimed = Option.flatMap(fork, (on) =>2379+ ownClaim(h, on.ask, on.claimant)2380+ );2381+2382+ const view = yield* Option.match(claimed, {2383+ onNone: () => Effect.succeedNone,2384+ onSome: ({ state }) => viewOf(h.policy, ask, state),2385+ });2386+2387+ const base = Option.getOrElse(2388+ Option.map(2389+ Option.flatMap(claimed, ({ state }) => claimOf(state)),2390+ (claim) => claim.base2391+ ),2392+ () => live.value.landed2393+ );2394+2395+ const refusals = yield* gateOf(2396+ withPorts(2397+ pushFacts({2398+ ask,2399+ base,2400+ claim: view,2401+ claimsHeld: Principal.guards.Person(input.pusher)2402+ ? heldBy(h, input.pusher.handle)2403+ : 0,2404+ head: input.after,2405+ landed: live.value.landed,2406+ policy: h.policy.value,2407+ project: name,2408+ pusher: input.pusher,2409+ ref: input.ref,2410+ repo: input.repo,2411+ })2412+ ),2413+ Option.match(fork, {2414+ onNone: () => [],2415+ onSome: (on) => [NotClaimed.of(on.ask)],2416+ }),2417+ [new StaleBase({ base, conflicts: [], main: live.value.landed })]2418+ );2419+2420+ yield* keepAlive(h, writes, { claimed, push: input }, now);2421+2422+ writes.pushEvents.push({2423+ after: input.after,2424+ at: now,2425+ eventId: input.eventId,2426+ ref: input.ref,2427+ repo: input.repo,2428+ ...field("before", input.before),2429+ });2430+2431+ return refusals;2432+ });2433+2434+ /**2435+ * The receipt of an answer given before: the caller's own request2436+ * again, or the same head from them while that answer stands. A2437+ * request id another person's answer holds is not the caller's to2438+ * replay, nor to take: `NotClaimed`.2439+ */2440+ const earlier = (2441+ h: Hydrated,2442+ caller: Person,2443+ input: {2444+ readonly ask: AskId;2445+ readonly head: CommitSha;2446+ readonly requestId: RequestId;2447+ }2448+ ): Effect.Effect<Option.Option<AnswerReceipt>, NotClaimed> => {2449+ const own = (row: AnswerRow) => sameHandle(row.answerer, caller.handle);2450+ const same = findAnswer(h, input.requestId);2451+2452+ if (Option.isSome(same) && !own(same.value.row)) {2453+ return Effect.fail(NotClaimed.of(input.ask));2454+ }2455+2456+ const given = Option.orElse(same, () =>2457+ Option.fromUndefinedOr(2458+ h.answers.find(2459+ ({ record, row }) =>2460+ row.ask === input.ask &&2461+ row.head === input.head &&2462+ own(row) &&2463+ !LandingState.guards.Refused(record.landing)2464+ )2465+ )2466+ );2467+2468+ return Effect.succeed(Option.map(given, ({ record }) => record.receipt));2469+ };2470+2471+ /** A new answer request, queued and started on main as it stands, with its receipt. */2472+ const queueAnswer = (2473+ writes: Writes,2474+ request: Request,2475+ input: {2476+ readonly ask: AskId;2477+ readonly main: LandedSha;2478+ readonly now: DateTime.Utc;2479+ }2480+ ) =>2481+ Effect.gen(function* () {2482+ const started = landingTransition(2483+ LandingState.cases.Queued.make({ request }),2484+ LandingCommand.Start({ main: input.main }),2485+ input.now2486+ );2487+2488+ const receipt: AnswerReceipt = {2489+ ask: input.ask,2490+ base: request.base,2491+ head: request.head,2492+ outcome: outcomeOf(started.state),2493+ project: name,2494+ requestId: request.requestId,2495+ };2496+2497+ writes.answers.set(request.requestId, {2498+ answerer: request.answerer,2499+ head: request.head,2500+ requestId: request.requestId,2501+ state: yield* Effect.orDie(2502+ encodeAnswer({ landing: started.state, receipt })2503+ ),2504+ updatedAt: input.now,2505+ ...field("ask", request.ask),2506+ });2507+ writes.outbox.push(yield* startRow(request.requestId, input.now));2508+2509+ return receipt;2510+ });2511+2512+ const submitBody =2513+ (2514+ caller: Person,2515+ input: {2516+ readonly ask: AskId;2517+ readonly base: CommitSha;2518+ readonly head: CommitSha;2519+ readonly requestId: RequestId;2520+ }2521+ ) =>2522+ (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2523+ Effect.gen(function* () {2524+ const given = yield* earlier(h, caller, input);2525+2526+ if (Option.isSome(given)) {2527+ return given.value;2528+ }2529+2530+ const refused = NotClaimed.of(input.ask);2531+ const ask = askNow(h, writes, input.ask);2532+ const live = liveRow(h);2533+2534+ if (2535+ Option.isNone(ask) ||2536+ Option.isNone(live) ||2537+ Option.isNone(h.policy)2538+ ) {2539+ return yield* refused;2540+ }2541+2542+ const own = ownClaim(h, input.ask, caller.handle);2543+2544+ const fork = Option.getOrElse(2545+ Option.map(2546+ Option.flatMap(own, ({ state }) => claimOf(state)),2547+ (held) => held.fork2548+ ),2549+ () => forkName(name, input.ask, caller.handle)2550+ );2551+2552+ const view = yield* Option.match(own, {2553+ onNone: () => Effect.succeedNone,2554+ onSome: ({ state }) => viewOf(h.policy, ask, state),2555+ });2556+2557+ const facts = yield* withPorts(2558+ pushFacts({2559+ ask,2560+ base: input.base,2561+ claim: view,2562+ claimsHeld: heldBy(h, caller.handle),2563+ head: input.head,2564+ landed: live.value.landed,2565+ policy: h.policy.value,2566+ project: name,2567+ pusher: caller,2568+ ref: mainRef,2569+ repo: fork,2570+ })2571+ ).pipe(2572+ Effect.catchTags({2573+ MissingCommit: () =>2574+ Effect.fail(2575+ new StaleBase({2576+ base: input.base,2577+ conflicts: [],2578+ main: live.value.landed,2579+ })2580+ ),2581+ RepoNotFound: () => Effect.fail(refused),2582+ })2583+ );2584+2585+ const gate = yield* runGate(pushStages, facts);2586+2587+ if (Option.isSome(gate)) {2588+ return yield* submitRefusal(2589+ Array.headNonEmpty(gate.value),2590+ input.ask2591+ );2592+ }2593+2594+ return yield* queueAnswer(2595+ writes,2596+ {2597+ answerer: caller.handle,2598+ ask: Option.some(input.ask),2599+ assisted: [],2600+ base: input.base,2601+ credits: creditsFor(ask.value, caller.handle),2602+ fork,2603+ head: input.head,2604+ project: name,2605+ requestId: input.requestId,2606+ },2607+ { ask: input.ask, main: live.value.landed, now }2608+ );2609+ });2610+2611+ /** Every live claim whose deadline passed, moved by `Tick`. */2612+ const tickAll = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2613+ Effect.forEach(2614+ h.claims.filter(({ state }) => isLive(state)),2615+ ({ row, state }) =>2616+ Result.match(2617+ claimTransition(2618+ state,2619+ ClaimCommand.cases.Tick.make({}),2620+ now,2621+ claimsPolicy(h)2622+ ),2623+ {2624+ onFailure: () => Effect.void,2625+ onSuccess: (step) =>2626+ step.effects.length > 02627+ ? applyClaim(h, writes, row.ask, step, now)2628+ : Effect.void,2629+ }2630+ ),2631+ { discard: true }2632+ );2633+2634+ // ------------------------------------------------------------ reads2635+2636+ const statusOf = (caller: Person) =>2637+ Effect.gen(function* () {2638+ const h = yield* hydrate;2639+2640+ const claims = yield* Effect.forEach(2641+ h.claims.filter(({ row }) => sameHandle(row.claimant, caller.handle)),2642+ ({ row, state }) =>2643+ viewOf(h.policy, Option.fromUndefinedOr(h.asks.get(row.ask)), state)2644+ );2645+2646+ const answers = h.answers.flatMap(({ record, row }): AnswerView[] =>2647+ row.ask === undefined || !sameHandle(row.answerer, caller.handle)2648+ ? []2649+ : [2650+ {2651+ ask: row.ask,2652+ at: row.updatedAt,2653+ head: row.head,2654+ outcome: outcomeOf(record.landing),2655+ requestId: row.requestId,2656+ },2657+ ]2658+ );2659+2660+ return { answers, claims: Array.getSomes(claims) };2661+ });2662+2663+ const verdictOn = (input: {2664+ readonly ask: AskId;2665+ readonly head?: CommitSha;2666+ }) =>2667+ Effect.flatMap(hydrate, (h) => {2668+ if (!h.asks.has(input.ask)) {2669+ return Effect.fail(new UnknownAsk({ ask: input.ask }));2670+ }2671+2672+ const latest = Array.last(2673+ Array.sort(2674+ h.answers.filter(2675+ ({ record, row }) =>2676+ row.ask === input.ask &&2677+ record.verdict !== undefined &&2678+ (input.head === undefined || row.head === input.head)2679+ ),2680+ byUpdated2681+ )2682+ );2683+2684+ const verdict = Option.flatMap(latest, ({ record }) =>2685+ Option.map(Option.fromUndefinedOr(record.verdict), (made) => ({2686+ ...made,2687+ outcome: outcomeOf(record.landing),2688+ }))2689+ );2690+2691+ return Effect.succeed(field("verdict", verdict));2692+ });2693+2694+ const alarmed = (queue: AnswerQueue) =>2695+ Effect.gen(function* () {2696+ const rows = yield* lock.withPermits(1)(2697+ Effect.gen(function* () {2698+ const h = yield* hydrate;2699+ const now = yield* DateTime.now;2700+ const writes = writesOf();2701+2702+ yield* tickAll(h, writes, now);2703+2704+ return [...(yield* commit(h, writes, now)), ...h.outbox];2705+ })2706+ );2707+2708+ yield* settle(queue, rows);2709+ });2710+2711+ // ------------------------------------------------------------ the api2712+2713+ const api: ProjectApi = {2714+ advanceAnswer: (requestId, command, report) =>2715+ checked(2716+ MethodSchemas.advanceAnswer,2717+ [requestId, command, report],2718+ write(api, advanceBody(requestId, command, report))2719+ ),2720+ answer: (requestId) =>2721+ checked(2722+ MethodSchemas.answer,2723+ [requestId],2724+ Effect.map(hydrate, (h) =>2725+ Option.map(findAnswer(h, requestId), (found) => runOf(h, found))2726+ )2727+ ),2728+ claim: (caller, id) =>2729+ checked(2730+ MethodSchemas.claim,2731+ [caller, id],2732+ write(api, claimBody(caller, id))2733+ ),2734+ events: (since, limit) =>2735+ checked(2736+ MethodSchemas.events,2737+ [since, limit],2738+ Effect.map(store.eventsSince(since, limit), (rows) =>2739+ rows.map(({ event, seq }) => ({ event, seq }))2740+ )2741+ ),2742+ initProject: (caller, input) =>2743+ checked(2744+ MethodSchemas.initProject,2745+ [caller, input],2746+ write(api, initBody(caller, input))2747+ ),2748+ landing: (caller, sha) =>2749+ checked(2750+ MethodSchemas.landing,2751+ [caller, sha],2752+ Effect.flatMap(store.landing(sha), (found) =>2753+ Option.match(found, {2754+ onNone: () => Effect.fail(new UnknownCommit({ sha })),2755+ onSome: (landing) => Effect.succeed({ landing }),2756+ })2757+ )2758+ ),2759+ listAsks: (caller) =>2760+ checked(2761+ MethodSchemas.listAsks,2762+ [caller],2763+ Effect.map(hydrate, (h) => ({2764+ asks: [...h.asks.values()].flatMap((ask) =>2765+ ask.state === "closed" ? [] : [listingOf(ask)]2766+ ),2767+ }))2768+ ),2769+ onAlarm: () => checked(MethodSchemas.onAlarm, [], alarmed(api)),2770+ openAsk: (caller, input) =>2771+ checked(2772+ MethodSchemas.openAsk,2773+ [caller, input],2774+ write(api, openBody(caller, input))2775+ ),2776+ recordFirstPush: (caller, head) =>2777+ checked(2778+ MethodSchemas.recordFirstPush,2779+ [caller, head],2780+ write(api, firstPushBody(caller, head))2781+ ),2782+ recordPush: (input) =>2783+ checked(MethodSchemas.recordPush, [input], write(api, pushBody(input))),2784+ release: (caller, id) =>2785+ checked(2786+ MethodSchemas.release,2787+ [caller, id],2788+ write(api, releaseBody(caller, id))2789+ ),2790+ showAsk: (caller, id) =>2791+ checked(2792+ MethodSchemas.showAsk,2793+ [caller, id],2794+ Effect.flatMap(hydrate, (h) =>2795+ Option.match(Option.fromUndefinedOr(h.asks.get(id)), {2796+ onNone: () => Effect.fail(new UnknownAsk({ ask: id })),2797+ onSome: (ask) => Effect.succeed({ ask, brief: briefOf(ask) }),2798+ })2799+ )2800+ ),2801+ status: (caller) =>2802+ checked(MethodSchemas.status, [caller], statusOf(caller)),2803+ submitAnswer: (caller, input) =>2804+ checked(2805+ MethodSchemas.submitAnswer,2806+ [caller, input],2807+ write(api, submitBody(caller, input))2808+ ),2809+ verdict: (caller, input) =>2810+ checked(MethodSchemas.verdict, [caller, input], verdictOn(input)),2811+ };2812+2813+ return api;2814+ });added:packages/project/src/projection.ts+36 added
123456789101112131415161718192021222324252627282930313233343536/** * The `Projection` port: where the project's events go to feed read models * outside its Durable Object, such as the front page's D1 table (W3 309). * The settle step hands it the outbox rows whose body is a `ProjectedEvent`, * in the order the events were numbered; it is retried from the outbox on * failure, so `apply` must be idempotent by `(project, event.seq)`. */import { ProjectEvent } from "@repo/protocol/domain/event";import { ProjectName } from "@repo/protocol/ids";import { Context, Schema } from "effect";import type { Effect } from "effect";
import type { OutboxRow } from "./project-store/rows.ts";
/** An outbox row's body for the projection: one numbered event of one project. */export const ProjectedEvent = Schema.TaggedStruct("Projected", { event: ProjectEvent, project: ProjectName,});
export type ProjectedEvent = typeof ProjectedEvent.Type;
/** The read model refused or could not take the rows; they stay in the outbox. */export class ProjectionFailed extends Schema.TaggedError<ProjectionFailed>()( "ProjectionFailed", { reason: Schema.String }) {}
export class Projection extends Context.Service< Projection, { readonly apply: ( rows: readonly OutboxRow[] ) => Effect.Effect<void, ProjectionFailed>; }>()("project/Projection") {}added:packages/project/src/projects.ts+27 added
123456789101112131415161718192021222324252627/** * The `Projects` port: the one way a caller reaches a project by its name. * Each project is one service over its own store (one Durable Object in W3, * 302's `DoProjects`); this port finds it, or makes a new one. * * Adapters: `/memory` here, which keeps one memory store per project. */import type { ProjectName } from "@repo/protocol/ids";import type { ProjectExists, UnknownProject } from "@repo/protocol/refusal";import { Context } from "effect";import type { Effect } from "effect";
import type { ProjectApi } from "./project.ts";
export class Projects extends Context.Service< Projects, { /** A project made before; one never made is `UnknownProject`. */ readonly get: ( project: ProjectName ) => Effect.Effect<ProjectApi, UnknownProject>; /** A new, empty project, ready for `initProject`; a name taken is `ProjectExists`. */ readonly create: ( project: ProjectName ) => Effect.Effect<ProjectApi, ProjectExists>; }>()("project/Projects") {}added:packages/project/src/queue.ts+56 added
1+/**2+ * The project's serial landing queue, over the landing lifecycle's3+ * `LandingQueue` value: answers are checked side by side, but land on main4+ * one at a time. A request asks for the slot when its lifecycle reaches5+ * `Landing`, lands only while it holds it, and leaves when it is no longer6+ * landing (landed, refused, or sent back to merge by a moved main); the7+ * next in line is admitted then.8+ */9+import type { RequestId } from "@repo/protocol/ids";10+import { Effect, Option, Schema } from "effect";11+12+import { enqueue, LandingQueue, next as admitNext, settle } from "./landing.ts";13+14+/** No request waiting, none landing. */15+export const emptyQueue: LandingQueue = { active: Option.none(), order: [] };16+17+const decodeQueue = Schema.decodeUnknownEffect(LandingQueue);18+19+const encodeQueue = Schema.encodeEffect(LandingQueue);20+21+/** The queue as the store held it: `null` until a commit first writes one. */22+export const queueOf = (stored: Schema.Json): Effect.Effect<LandingQueue> =>23+ stored === null24+ ? Effect.succeed(emptyQueue)25+ : Effect.orDie(decodeQueue(stored));26+27+/** The queue as the store keeps it. */28+export const storedQueue = (queue: LandingQueue): Effect.Effect<Schema.Json> =>29+ Effect.orDie(encodeQueue(queue));30+31+/** Whether `id` holds the landing slot. */32+export const holdsSlot = (queue: LandingQueue, id: RequestId): boolean =>33+ Option.contains(queue.active, id);34+35+/** A move of the queue, and the request it admitted to the slot, if any. */36+export interface Moved {37+ readonly admitted: Option.Option<RequestId>;38+ readonly queue: LandingQueue;39+}40+41+/**42+ * `id` asks for the slot: it joins the back of the line (or keeps its43+ * place), and the front of the line is admitted if the slot is free.44+ */45+export const askToLand = (queue: LandingQueue, id: RequestId): Moved => {46+ const { admit, queue: moved } = admitNext(enqueue(queue, id));47+48+ return { admitted: admit, queue: moved };49+};50+51+/** `id` leaves the line or the slot, and the next in line is admitted if the slot is free. */52+export const leave = (queue: LandingQueue, id: RequestId): Moved => {53+ const { admit, queue: moved } = admitNext(settle(queue, id));54+55+ return { admitted: admit, queue: moved };56+};added:packages/project/test/project.test.ts+1221 added
1+import { describe, expect, it } from "@effect/vitest";2+import { RefName, RepoHost } from "@repo/artifacts/repo-host";3+import { Brand } from "@repo/brand";4+import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";5+import { Verdict } from "@repo/protocol/domain/answer";6+import type { Ask } from "@repo/protocol/domain/ask";7+import { CheckSpec } from "@repo/protocol/domain/check";8+import { ClaimView } from "@repo/protocol/domain/claim";9+import { Glob } from "@repo/protocol/domain/common";10+import { Outcome } from "@repo/protocol/domain/outcome";11+import {12+ AskId,13+ LandedSha,14+ LaneName,15+ ProjectName,16+ RepoName,17+ RepoPath,18+ RequestId,19+} from "@repo/protocol/ids";20+import type { CommitSha } from "@repo/protocol/ids";21+import { Anonymous, Person } from "@repo/protocol/principal";22+import {23+ AskFull,24+ ClaimLapsed,25+ DirectPush,26+ ImportFailed,27+ NotClaimed,28+ NotDecider,29+ NotRedFirst,30+ OutOfScope,31+ ProjectExists,32+ StaleBase,33+ TouchedJudge,34+ UnknownProject,35+} from "@repo/protocol/refusal";36+import { advanceTo, at as instant } from "@repo/testkit/clock";37+import type { Files } from "@repo/testkit/git-client";38+import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";39+import {40+ Array,41+ DateTime,42+ Effect,43+ Exit,44+ Layer,45+ Option,46+ Result,47+ Schema,48+} from "effect";49+50+import { ScheduledAlarm } from "../src/alarms/memory.ts";51+import { ProjectStore } from "../src/project-store.ts";52+import type { ProjectApi } from "../src/project.ts";53+import { projectService } from "../src/project.ts";54+import { ProjectedRows } from "../src/projection/memory.ts";55+import { Projects } from "../src/projects.ts";56+import { ProjectsMemory } from "../src/projects/memory.ts";57+import {58+ CheckScript,59+ cleanMergeAt,60+ composedAt,61+ Evaluated,62+ mergedAt,63+ Pusher,64+ worldOf,65+} from "./world.ts";66+import type { StoreKind, WorldScenario } from "./world.ts";67+68+const people = ["bob", "carol", "dave", "eve", "frank"];69+70+const scenario = aProject({ people }).pipe(71+ withVouches(people),72+ withAsk({ id: "parse-iso", territory: "packages/parser" }),73+ withAsk({ id: "parse-green", territory: "packages/parser" }),74+ withAsk({ id: "format-date", territory: "packages/format" }),75+ withAsk({ id: "lex-tokens", territory: "packages/lexer" }),76+ withAsk({ id: "trim-input", territory: "packages/trim" }),77+ withAsk({ id: "tidy-all", territory: "." })78+);79+80+const { project } = scenario;81+82+const repo = RepoName.make(project);83+84+const mainRef = RefName.make("refs/heads/main");85+86+const person = (name: string) =>87+ Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });88+89+const alice = person("alice");90+91+const bob = person("bob");92+93+const carol = person("carol");94+95+const dave = person("dave");96+97+const eve = person("eve");98+99+const frank = person("frank");100+101+const anyone = Anonymous.make({});102+103+const remoteOf = (name: string) => `https://${Brand.domain}/${name}.git`;104+105+const forkOf = (ask: string, who: Person) =>106+ RepoName.make(`${project}--${ask}--${who.handle}`);107+108+const userOf = (handle: string) =>109+ `${handle} <${handle}@users.${Brand.domain}>`;110+111+const askOf = (id: string): Ask =>112+ Option.getOrThrow(113+ Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)114+ );115+116+const redThenGreen = LaneName.make("redThenGreen");117+118+const lanes = [redThenGreen, LaneName.make("lint"), LaneName.make("types")];119+120+const noon = instant("2026-10-07T12:00:00Z");121+122+const hoursAfter = (from: DateTime.Utc, count: number) =>123+ DateTime.add(from, { hours: count });124+125+/** The project as alice first pushes it: a library of four small packages. */126+const start: Files = [127+ ["package.json", '{ "name": "datekit", "workspaces": ["packages/*"] }\n'],128+ [129+ "packages/format/src/format.ts",130+ "export const format = (d) => String(d);\n",131+ ],132+ ["packages/lexer/src/lex.ts", "export const lex = (s) => s.split(' ');\n"],133+ ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],134+ ["packages/trim/src/trim.ts", "export const trim = (s) => s;\n"],135+];136+137+const fixedParse = "export const parse = (s) => ({ year: 2026 });\n";138+139+/** An ask's own files: its file in the config folder, and its check. */140+const askFiles = (id: string) => {141+ const { check, file, territory } = askOf(id);142+ const subject = territory.module === "." ? "tidy" : territory.module;143+144+ return Array.make(145+ { content: `export default "${id}";\n`, path: file },146+ {147+ content: [148+ `import { expect, it } from "vitest";`,149+ `import { ${subject} } from "../src/${subject}.ts";`,150+ ``,151+ `it("${id}", () => {`,152+ ` expect(${subject}("2026-10-07")).toStrictEqual({ year: 2026 });`,153+ `});`,154+ ``,155+ ].join("\n"),156+ path: CheckSpec.guards.RedThenGreen(check)157+ ? check.path158+ : RepoPath.make(`test/${id}.test.ts`),159+ }160+ );161+};162+163+/** The files main holds after `ids`' asks opened on it. */164+const withAskFiles = (files: Files, ...ids: readonly string[]): Files => [165+ ...files,166+ ...ids.flatMap((id) =>167+ askFiles(id).map(({ content, path }) => [path, content] as const)168+ ),169+];170+171+/** `files` with `path` holding `content`, added or replaced. */172+const changed = (files: Files, path: string, content: string): Files => [173+ ...files.filter(([each]) => each !== path),174+ [path, content],175+];176+177+/** Where canonical `main` stands now. */178+const mainTip = Effect.gen(function* () {179+ const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);180+181+ return LandedSha.make(182+ Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))183+ );184+});185+186+const commitOf = (sha: CommitSha) =>187+ Effect.gen(function* () {188+ const host = yield* RepoHost;189+ const read = yield* host.readCommit(repo, sha).pipe(Effect.orDie);190+ const { author, committer, message, parents } = Option.getOrThrow(read);191+192+ return { author, committer, parents, trailers: parseTrailers(message) };193+ });194+195+/** Every lane on `on` scripted to come out `result` each time. */196+const scriptAll = (197+ on: Parameters<CheckScript["Service"]["script"]>[0],198+ result: "passed" | "failed"199+) =>200+ CheckScript.use((checker) =>201+ Effect.forEach(lanes, (lane) => checker.script(on, lane, [result]), {202+ discard: true,203+ })204+ );205+206+/** `decider` opens an ask whose check the Checker fails twice the same way on the composed tree. */207+const openRed = (api: ProjectApi, id: string, decider: Person = alice) =>208+ Effect.gen(function* () {209+ const files = askFiles(id);210+ const composed = yield* composedAt(repo, yield* mainTip, files);211+212+ yield* CheckScript.use((checker) =>213+ checker.script(composed, redThenGreen, ["failed", "failed"])214+ );215+216+ return yield* api.openAsk(decider, { ask: AskId.make(id), files });217+ });218+219+/** What each event is, in the order the project numbered them. */220+const eventTags = (api: ProjectApi) =>221+ Effect.map(api.events(0, 1000), (events) =>222+ events.map(({ event }) => event._tag)223+ );224+225+const scheduled = ScheduledAlarm.use(({ at }) => at);226+227+/** The project's state as its store keeps it, once it is made. */228+const projectState = ProjectStore.use((store) => store.load()).pipe(229+ Effect.map(({ project: row }) => Option.map(row, ({ state }) => state))230+);231+232+const states = (api: ProjectApi, who: Person) =>233+ Effect.map(api.status(who), ({ claims }) => claims.map(({ state }) => state));234+235+const outcomes = (api: ProjectApi, who: Person) =>236+ Effect.map(api.status(who), ({ answers }) =>237+ answers.map(({ outcome }) => outcome)238+ );239+240+const parseIso = AskId.make("parse-iso");241+242+/** Steps 1 and 2: the project made, and its first ask opened. */243+const opening = (api: ProjectApi) =>244+ Effect.gen(function* () {245+ const made = yield* Effect.exit(api.initProject(alice, {}));246+ const awaiting = yield* projectState;247+248+ const first = yield* Pusher.use((pusher) =>249+ pusher.push(repo, Option.none(), start, "Start")250+ );251+252+ const notHers = yield* api.recordFirstPush(bob, first).pipe(Effect.flip);253+ const recorded = yield* api.recordFirstPush(alice, first);254+ const evaluated = yield* Evaluated.use(({ shas }) => shas);255+ const opened = yield* openRed(api, "parse-iso");256+ const greenFiles = askFiles("parse-green");257+258+ yield* scriptAll(259+ yield* composedAt(repo, opened.landed, greenFiles),260+ "passed"261+ );262+263+ const green = { ask: AskId.make("parse-green"), files: greenFiles };264+ const greenRefused = yield* api.openAsk(alice, green).pipe(Effect.flip);265+ const bobRefused = yield* api.openAsk(bob, green).pipe(Effect.flip);266+267+ return {268+ asked: yield* commitOf(opened.landed),269+ awaiting,270+ bobRefused,271+ evaluated,272+ first,273+ greenRefused,274+ listed: yield* api.listAsks(anyone),275+ made,276+ mainAfterRefusals: yield* mainTip,277+ notHers,278+ opened,279+ recorded,280+ shown: yield* api.showAsk(anyone, parseIso),281+ };282+ });283+284+/** Steps 3 and 4: bob claims, then pushes out of his territory. */285+const claiming = (api: ProjectApi, opened: LandedSha) =>286+ Effect.gen(function* () {287+ const host = yield* RepoHost;288+ const bobFork = forkOf("parse-iso", bob);289+ const { claim } = yield* api.claim(bob, parseIso);290+ const forkRefs = yield* host.refs(bobFork).pipe(Effect.orDie);291+ const alarmAfterClaim = yield* scheduled;292+ const carolRefused = yield* api.claim(carol, parseIso).pipe(Effect.flip);293+294+ const carolFork = yield* Effect.exit(host.refs(forkOf("parse-iso", carol)));295+296+ const wideFiles = changed(297+ changed(298+ changed(299+ withAskFiles(start, "parse-iso"),300+ "packages/parser/src/parse.ts",301+ fixedParse302+ ),303+ "packages/format/src/format.ts",304+ "export const format = (d) => d.toString();\n"305+ ),306+ ".github/workflows/ci.yml",307+ "on: push\n"308+ );309+310+ const wide = yield* Pusher.use((pusher) =>311+ pusher.push(bobFork, Option.some(opened), wideFiles)312+ );313+314+ const wideRefusals = yield* api.recordPush({315+ after: wide,316+ before: Option.some(opened),317+ eventId: "push-wide",318+ pusher: bob,319+ ref: "refs/heads/main",320+ repo: bobFork,321+ });322+323+ const wideSubmitted = yield* api324+ .submitAnswer(bob, {325+ ask: parseIso,326+ base: opened,327+ head: wide,328+ requestId: RequestId.make("req-wide-0001"),329+ })330+ .pipe(Effect.flip);331+332+ return {333+ alarmAfterClaim,334+ carolFork,335+ carolRefused,336+ claim,337+ forkMain: forkRefs.get(mainRef),338+ wide,339+ wideRefusals,340+ wideSubmitted,341+ };342+ });343+344+/** Steps 5 and 6: bob's fix is checked green and lands, and a replay changes nothing. */345+const landing = (api: ProjectApi, opened: LandedSha, wide: CommitSha) =>346+ Effect.gen(function* () {347+ const bobFork = forkOf("parse-iso", bob);348+349+ const fixedFiles = changed(350+ withAskFiles(start, "parse-iso"),351+ "packages/parser/src/parse.ts",352+ fixedParse353+ );354+355+ const fix = yield* Pusher.use((pusher) =>356+ pusher.push(bobFork, Option.some(wide), fixedFiles)357+ );358+359+ const fixRefusals = yield* api.recordPush({360+ after: fix,361+ before: Option.some(wide),362+ eventId: "push-fix",363+ pusher: bob,364+ ref: "refs/heads/main",365+ repo: bobFork,366+ });367+368+ yield* scriptAll(369+ yield* mergedAt({370+ base: opened,371+ fork: bobFork,372+ head: fix,373+ main: opened,374+ repo,375+ }),376+ "passed"377+ );378+379+ const requestId = RequestId.make("req-fix-0001");380+ const submission = { ask: parseIso, base: opened, head: fix, requestId };381+ const receipt = yield* api.submitAnswer(bob, submission);382+ const landed = yield* mainTip;383+ const { verdict } = yield* api.verdict(anyone, { ask: parseIso });384+385+ const roundTrip = yield* Option.match(Option.fromUndefinedOr(verdict), {386+ onNone: () => Effect.succeedNone,387+ onSome: (made) =>388+ Schema.encodeEffect(Verdict)(made).pipe(389+ Effect.flatMap(Schema.decodeEffect(Verdict)),390+ Effect.asSome,391+ Effect.orDie392+ ),393+ });394+395+ return {396+ events: yield* eventTags(api),397+ fix,398+ fixRefusals,399+ fixedFiles,400+ landed,401+ landing: yield* commitOf(landed),402+ listedAfter: yield* api.listAsks(anyone),403+ projected: yield* ProjectedRows.use(({ events }) =>404+ Effect.map(events, (rows) => rows.map(({ event }) => event._tag))405+ ),406+ receipt,407+ replay: yield* api.submitAnswer(bob, submission),408+ replayByCarol: yield* Effect.result(api.submitAnswer(carol, submission)),409+ requestId,410+ roundTrip,411+ status: yield* api.status(bob),412+ tipAfterReplay: yield* mainTip,413+ verdict,414+ view: (yield* api.landing(anyone, landed)).landing,415+ };416+ });417+418+/** Step 7: dave claims and never pushes; warned at 2 h, lapsed at 24 h. */419+const lapsing = (api: ProjectApi, files: Files) =>420+ Effect.gen(function* () {421+ const formatDate = AskId.make("format-date");422+423+ yield* openRed(api, "format-date");424+ yield* api.claim(dave, formatDate);425+426+ const alarmAfterClaim = yield* scheduled;427+428+ yield* advanceTo("2026-10-07T14:00:00Z");429+ yield* api.onAlarm();430+431+ const warned = {432+ alarm: yield* scheduled,433+ last: (yield* eventTags(api)).at(-1),434+ states: yield* states(api, dave),435+ };436+437+ yield* advanceTo("2026-10-08T12:00:00Z");438+ yield* api.onAlarm();439+440+ const lapsed = {441+ last: (yield* eventTags(api)).at(-1),442+ states: yield* states(api, dave),443+ };444+445+ const base = yield* mainTip;446+447+ const late = yield* Pusher.use((pusher) =>448+ pusher.push(449+ forkOf("format-date", dave),450+ Option.some(base),451+ changed(452+ withAskFiles(files, "format-date"),453+ "packages/format/src/format.ts",454+ "export const format = (d) => ({ year: 2026 });\n"455+ )456+ )457+ );458+459+ const lateRefused = yield* api460+ .submitAnswer(dave, {461+ ask: formatDate,462+ base,463+ head: late,464+ requestId: RequestId.make("req-late-0001"),465+ })466+ .pipe(Effect.flip);467+468+ return { alarmAfterClaim, lapsed, lateRefused, warned };469+ });470+471+/** Who answers in a race, with which ask and which change. */472+interface Racer {473+ readonly ask: string;474+ readonly change: readonly [path: string, content: string];475+ readonly who: Person;476+}477+478+/**479+ * Step 8: two answers on one base. The first one's Checker cannot start, so480+ * it waits on a retry while the second lands; then its land finds main481+ * moved, and it is merged again onto the new main.482+ */483+const racing = (484+ api: ProjectApi,485+ files: Files,486+ [first, second]: readonly [Racer, Racer]487+) =>488+ Effect.gen(function* () {489+ yield* openRed(api, first.ask);490+ yield* openRed(api, second.ask);491+492+ const base = yield* mainTip;493+ const onBase = withAskFiles(files, "format-date", first.ask, second.ask);494+495+ const answer = (racer: Racer) =>496+ Effect.gen(function* () {497+ const fork = forkOf(racer.ask, racer.who);498+499+ yield* api.claim(racer.who, AskId.make(racer.ask));500+501+ const head = yield* Pusher.use((pusher) =>502+ pusher.push(fork, Option.some(base), changed(onBase, ...racer.change))503+ );504+505+ return { fork, head };506+ });507+508+ const submit = (racer: Racer, head: CommitSha) =>509+ api.submitAnswer(racer.who, {510+ ask: AskId.make(racer.ask),511+ base,512+ head,513+ requestId: RequestId.make(`req-${racer.ask}`),514+ });515+516+ const one = yield* answer(first);517+ const other = yield* answer(second);518+519+ yield* submit(first, one.head);520+521+ const waiting = yield* outcomes(api, first.who);522+523+ yield* scriptAll(524+ yield* mergedAt({ ...other, base, main: base, repo }),525+ "passed"526+ );527+ yield* submit(second, other.head);528+529+ const between = yield* mainTip;530+531+ // Now the first one's checks pass on its merge, and on a clean re-merge.532+ yield* scriptAll(533+ yield* mergedAt({ ...one, base, main: base, repo }),534+ "passed"535+ );536+537+ const remerged = yield* cleanMergeAt({ ...one, base, main: between, repo });538+539+ if (Option.isSome(remerged)) {540+ yield* scriptAll(remerged.value, "passed");541+ }542+543+ yield* advanceTo(DateTime.formatIso(Option.getOrThrow(yield* scheduled)));544+ yield* api.onAlarm();545+546+ const tip = yield* mainTip;547+548+ return {549+ base,550+ between,551+ betweenParents: (yield* commitOf(between)).parents,552+ outcomes: yield* outcomes(api, first.who),553+ tip,554+ tipParents: (yield* commitOf(tip)).parents,555+ waiting,556+ };557+ });558+559+/** Steps 1 to 7, once, recording what each step saw. */560+const core = Effect.gen(function* () {561+ yield* advanceTo("2026-10-07T12:00:00Z");562+563+ const api = yield* projectService(project);564+ const opened = yield* opening(api);565+ const claimed = yield* claiming(api, opened.opened.landed);566+ const answered = yield* landing(api, opened.opened.landed, claimed.wide);567+ const lapsed = yield* lapsing(api, answered.fixedFiles);568+569+ return { answered, api, claimed, lapsed, opened };570+});571+572+/** The whole core loop, step 8's race included. */573+const story = Effect.gen(function* () {574+ const { api, ...seen } = yield* core;575+576+ const raced = yield* racing(api, seen.answered.fixedFiles, [577+ {578+ ask: "lex-tokens",579+ change: [580+ "packages/lexer/src/lex.ts",581+ "export const lex = (s) => s.split(/ +/);\n",582+ ],583+ who: eve,584+ },585+ {586+ ask: "trim-input",587+ change: [588+ "packages/trim/src/trim.ts",589+ "export const trim = (s) => s.trim();\n",590+ ],591+ who: frank,592+ },593+ ]);594+595+ return { ...seen, raced };596+});597+598+/** Step 8 with a re-merge that conflicts: the second answer touched the same line. */599+const conflicting = Effect.gen(function* () {600+ const { api, answered } = yield* core;601+602+ return yield* racing(api, answered.fixedFiles, [603+ {604+ ask: "lex-tokens",605+ change: [606+ "packages/lexer/src/lex.ts",607+ "export const lex = (s) => s.split(/ +/);\n",608+ ],609+ who: eve,610+ },611+ {612+ ask: "tidy-all",613+ change: [614+ "packages/lexer/src/lex.ts",615+ "export const lex = (s) => s.split('\\t');\n",616+ ],617+ who: frank,618+ },619+ ]);620+});621+622+describe.each(["memory", "sqlite"] as const)(623+ "one project over memory adapters, its store in %s",624+ (store: StoreKind) => {625+ const seen = story.pipe(Effect.provide(worldOf(scenario, store)));626+627+ it.effect(628+ "1. alice makes it empty, and her first push becomes its landed SHA",629+ () =>630+ Effect.map(seen, ({ opened }) => {631+ expect(opened.made).toStrictEqual(632+ Exit.succeed({ project, remote: remoteOf(project) })633+ );634+ expect(opened.awaiting).toStrictEqual(635+ Option.some("awaitingFirstPush")636+ );637+ expect(opened.notHers).toStrictEqual(638+ new DirectPush({ ref: mainRef })639+ );640+ expect(opened.recorded).toStrictEqual({ landed: opened.first });641+ expect(opened.evaluated).toStrictEqual([opened.first]);642+ })643+ );644+645+ it.effect(646+ "2. an ask red twice on the composed tree lands as a platform commit asked by alice",647+ () =>648+ Effect.map(seen, ({ opened }) => {649+ const { asked, first, opened: open } = opened;650+651+ expect({652+ askedBy: open.ask.askedBy,653+ openedIn: open.ask.openedIn,654+ state: open.ask.state,655+ }).toStrictEqual({656+ askedBy: alice.handle,657+ openedIn: open.landed,658+ state: "open",659+ });660+ expect({661+ author: asked.author,662+ committer: asked.committer,663+ parents: asked.parents,664+ }).toStrictEqual({665+ author: authorLine(alice.handle),666+ committer: committerLine,667+ parents: [first],668+ });669+ expect(asked.trailers).toContainEqual({670+ key: "Asked-by",671+ value: userOf("alice"),672+ });673+ expect(opened.listed).toStrictEqual({674+ asks: [675+ {676+ ask: parseIso,677+ blockedBy: [],678+ claimed: false,679+ kind: askOf("parse-iso").kind,680+ territory: "parser",681+ want: askOf("parse-iso").brief.want,682+ },683+ ],684+ });685+ expect({686+ ask: opened.shown.ask,687+ readsWant: opened.shown.brief.includes(open.ask.brief.want),688+ }).toStrictEqual({ ask: open.ask, readsWant: true });689+ })690+ );691+692+ it.effect(693+ "2. an ask green on main is not red first, and only a decider opens one",694+ () =>695+ Effect.map(seen, ({ opened }) => {696+ expect(opened.greenRefused).toStrictEqual(new NotRedFirst({}));697+ expect(opened.bobRefused).toStrictEqual(new NotDecider({}));698+ expect(opened.mainAfterRefusals).toBe(opened.opened.landed);699+ })700+ );701+702+ it.effect(703+ "3. bob claims it and gets his fork; carol finds it full and gets none",704+ () =>705+ Effect.map(seen, ({ claimed, opened }) => {706+ const bobFork = forkOf("parse-iso", bob);707+708+ expect(claimed.claim).toStrictEqual(709+ ClaimView.make({710+ ask: parseIso,711+ base: opened.opened.landed,712+ checkCommand: "bun test packages/parser/test/parse-iso.test.ts",713+ claimant: bob.handle,714+ fork: bobFork,715+ lapsesAt: hoursAfter(noon, 24),716+ openedAt: noon,717+ project,718+ remote: remoteOf(bobFork),719+ state: "live",720+ warnsAt: hoursAfter(noon, 2),721+ })722+ );723+ expect(claimed.forkMain).toBe(opened.opened.landed);724+ expect(claimed.alarmAfterClaim).toStrictEqual(725+ Option.some(hoursAfter(noon, 2))726+ );727+ expect(claimed.carolRefused).toStrictEqual(728+ new AskFull({ ask: parseIso })729+ );730+ expect(Exit.isFailure(claimed.carolFork)).toBeTruthy();731+ })732+ );733+734+ it.effect(735+ "4. a push out of territory that edits CI hears both at once; submitting it is OutOfScope",736+ () =>737+ Effect.map(seen, ({ claimed }) => {738+ const outside = new OutOfScope({739+ paths: [RepoPath.make("packages/format/src/format.ts")],740+ });741+742+ expect(claimed.wideRefusals).toStrictEqual([743+ outside,744+ new TouchedJudge({745+ paths: [RepoPath.make(".github/workflows/ci.yml")],746+ }),747+ ]);748+ expect(claimed.wideSubmitted).toStrictEqual(outside);749+ })750+ );751+752+ it.effect(753+ "5. the fix is checked and lands, authored by bob, committed by the platform, credited",754+ () =>755+ Effect.map(seen, ({ answered, opened }) => {756+ expect(answered.fixRefusals).toStrictEqual([]);757+ expect(answered.receipt).toStrictEqual({758+ ask: parseIso,759+ base: opened.opened.landed,760+ head: answered.fix,761+ outcome: Outcome.cases.Checking.make({ stage: "merge" }),762+ project,763+ requestId: answered.requestId,764+ });765+ expect({766+ author: answered.landing.author,767+ committer: answered.landing.committer,768+ parents: answered.landing.parents,769+ }).toStrictEqual({770+ author: authorLine(bob.handle),771+ committer: committerLine,772+ parents: [opened.opened.landed],773+ });774+ expect(775+ answered.landing.trailers.filter(({ key }) =>776+ ["Asked-by", "Signed-off-by"].includes(key)777+ )778+ ).toStrictEqual([779+ { key: "Asked-by", value: userOf("alice") },780+ { key: "Signed-off-by", value: userOf("bob") },781+ ]);782+ })783+ );784+785+ it.effect(786+ "5. status, the verdict, the landing and the asks read the landing back",787+ () =>788+ Effect.map(seen, ({ answered, opened }) => {789+ expect({790+ answers: answered.status.answers.map(({ outcome, requestId }) => ({791+ outcome,792+ requestId,793+ })),794+ claims: answered.status.claims.map(({ state }) => state),795+ }).toStrictEqual({796+ answers: [797+ {798+ outcome: Outcome.cases.Landed.make({ sha: answered.landed }),799+ requestId: answered.requestId,800+ },801+ ],802+ claims: ["answered"],803+ });804+ expect(answered.roundTrip).toStrictEqual(805+ Option.fromUndefinedOr(answered.verdict)806+ );807+ expect({808+ head: answered.verdict?.head,809+ lanes: answered.verdict?.lanes.map(({ lane, result }) => ({810+ lane,811+ result,812+ })),813+ }).toStrictEqual({814+ head: answered.fix,815+ lanes: lanes.map((lane) => ({ lane, result: "passed" })),816+ });817+ expect(answered.view).toMatchObject({818+ ask: parseIso,819+ author: bob.handle,820+ credits: [821+ { handle: alice.handle, role: "Asked-by" },822+ { handle: bob.handle, role: "Signed-off-by" },823+ ],824+ parent: opened.opened.landed,825+ requestId: answered.requestId,826+ sha: answered.landed,827+ });828+ expect(answered.listedAfter).toStrictEqual({ asks: [] });829+ })830+ );831+832+ it.effect(833+ "5. its events come in order, and the projection heard every one",834+ () =>835+ Effect.map(seen, ({ answered }) => {836+ expect(answered.events).toStrictEqual([837+ "AskOpened",838+ "Claimed",839+ "Pushed",840+ "Pushed",841+ "Judged",842+ "Landed",843+ "AskClosed",844+ ]);845+ expect(answered.projected).toStrictEqual(answered.events);846+ })847+ );848+849+ it.effect(850+ "6. the same request again gets the same receipt, and nothing lands twice; nobody else's request is theirs",851+ () =>852+ Effect.map(seen, ({ answered }) => {853+ expect(answered.replay).toStrictEqual(answered.receipt);854+ expect(answered.tipAfterReplay).toBe(answered.landed);855+ expect(answered.replayByCarol).toStrictEqual(856+ Result.fail(NotClaimed.of(parseIso))857+ );858+ })859+ );860+861+ it.effect(862+ "7. a claim with no push is warned at 2 h and lapses at 24 h, and its answer is refused",863+ () =>864+ Effect.map(seen, ({ lapsed }) => {865+ expect(lapsed.alarmAfterClaim).toStrictEqual(866+ Option.some(hoursAfter(noon, 2))867+ );868+ expect(lapsed.warned).toStrictEqual({869+ alarm: Option.some(hoursAfter(noon, 24)),870+ last: "Warned",871+ states: ["warned"],872+ });873+ expect(lapsed.lapsed).toStrictEqual({874+ last: "Lapsed",875+ states: ["lapsed"],876+ });877+ expect(lapsed.lateRefused).toStrictEqual(878+ ClaimLapsed.of(AskId.make("format-date"))879+ );880+ })881+ );882+883+ it.effect(884+ "8. an answer whose land finds main moved re-merges cleanly and lands after the other",885+ () =>886+ Effect.map(seen, ({ raced }) => {887+ expect(raced.waiting).toStrictEqual([888+ Outcome.cases.Checking.make({ stage: "checks" }),889+ ]);890+ expect(raced.betweenParents).toStrictEqual([raced.base]);891+ expect(raced.tipParents).toStrictEqual([raced.between]);892+ expect(raced.outcomes).toStrictEqual([893+ Outcome.cases.Landed.make({ sha: raced.tip }),894+ ]);895+ })896+ );897+898+ it.effect(899+ "8. an answer whose re-merge conflicts is refused as stale, and main stays",900+ () =>901+ Effect.map(902+ conflicting.pipe(Effect.provide(worldOf(scenario, store))),903+ (raced) => {904+ expect(raced.tip).toBe(raced.between);905+ expect(raced.outcomes).toStrictEqual([906+ Outcome.cases.Refused.make({907+ refusals: [908+ new StaleBase({909+ base: raced.base,910+ conflicts: [RepoPath.make("packages/lexer/src/lex.ts")],911+ main: raced.between,912+ }),913+ ],914+ }),915+ ]);916+ }917+ )918+ );919+ }920+);921+922+/** The project up to bob's claim, in a world whose first fork and first projection fail. */923+const settling = Effect.gen(function* () {924+ yield* advanceTo("2026-10-07T12:00:00Z");925+926+ const api = yield* projectService(project);927+928+ yield* api.initProject(alice, {});929+930+ const first = yield* Pusher.use((pusher) =>931+ pusher.push(repo, Option.none(), start, "Start")932+ );933+934+ yield* api.recordFirstPush(alice, first);935+ yield* openRed(api, "parse-iso");936+ yield* api.claim(bob, parseIso);937+938+ const fork = forkOf("parse-iso", bob);939+ const host = yield* RepoHost;940+941+ const outboxOf = ProjectStore.use((store) => store.load()).pipe(942+ Effect.map(({ outbox }) => outbox.map(({ kind }) => kind).toSorted())943+ );944+945+ const before = {946+ alarm: yield* scheduled,947+ fork: Exit.isSuccess(yield* Effect.exit(host.refs(fork))),948+ outbox: yield* outboxOf,949+ };950+951+ yield* advanceTo(DateTime.formatIso(Option.getOrThrow(before.alarm)));952+ yield* api.onAlarm();953+954+ return {955+ after: {956+ fork: Exit.isSuccess(yield* Effect.exit(host.refs(fork))),957+ outbox: yield* outboxOf,958+ projected: yield* ProjectedRows.use(({ events }) =>959+ Effect.map(events, (rows) => rows.map(({ event }) => event._tag))960+ ),961+ },962+ before,963+ };964+});965+966+/** Two projects made through `ProjectsMemory`, each over its own store. */967+const routing = Effect.gen(function* () {968+ yield* advanceTo("2026-10-07T12:00:00Z");969+970+ const projects = yield* Projects;971+ const other = ProjectName.make("burrow");972+ const made = yield* projects.create(project);973+ const again = yield* projects.create(project).pipe(Effect.flip);974+ const unknown = yield* projects.get(other).pipe(Effect.flip);975+976+ yield* made.initProject(alice, {});977+ yield* projects.create(other);978+979+ const found = yield* projects.get(project);980+981+ return {982+ again,983+ initializedAgain: yield* found.initProject(alice, {}).pipe(Effect.flip),984+ otherInitialized: yield* Effect.exit(985+ Effect.flatMap(projects.get(other), (api) => api.initProject(bob, {}))986+ ),987+ unknown,988+ };989+});990+991+/** A project adopted from a public repo: its tip is the first landed SHA. */992+const importing = Effect.gen(function* () {993+ yield* advanceTo("2026-10-07T12:00:00Z");994+995+ const host = yield* RepoHost;996+ const upstream = RepoName.make("upstream");997+998+ yield* host.create(upstream).pipe(Effect.orDie);999+1000+ const tip = yield* Pusher.use((pusher) =>1001+ pusher.push(upstream, Option.none(), start, "Start")1002+ );1003+1004+ const api = yield* projectService(project);1005+1006+ // A repo it can't read leaves no project behind: the next import works.1007+ const refused = yield* api1008+ .initProject(alice, { import: { url: "https://example.com/none.git" } })1009+ .pipe(Effect.flip);1010+1011+ const made = yield* api.initProject(alice, {1012+ import: { url: "https://example.com/upstream.git" },1013+ });1014+1015+ return {1016+ evaluated: yield* Evaluated.use(({ shas }) => shas),1017+ made,1018+ main: yield* mainTip,1019+ refused,1020+ tip,1021+ };1022+});1023+1024+/** One push event reported twice: its liveness and its `Pushed` event happen once. */1025+const replaying = Effect.gen(function* () {1026+ yield* advanceTo("2026-10-07T12:00:00Z");1027+1028+ const api = yield* projectService(project);1029+ const opened = yield* opening(api);1030+ const claimed = yield* claiming(api, opened.opened.landed);1031+ const before = yield* eventTags(api);1032+1033+ const again = yield* api.recordPush({1034+ after: claimed.wide,1035+ before: Option.some(opened.opened.landed),1036+ eventId: "push-wide",1037+ pusher: bob,1038+ ref: "refs/heads/main",1039+ repo: forkOf("parse-iso", bob),1040+ });1041+1042+ return {1043+ again,1044+ events: [before, yield* eventTags(api)],1045+ first: claimed.wideRefusals,1046+ };1047+});1048+1049+/** An ask bob claimed, opened again by alice with the same files. */1050+const reopening = Effect.gen(function* () {1051+ yield* advanceTo("2026-10-07T12:00:00Z");1052+1053+ const api = yield* projectService(project);1054+ const { opened } = yield* opening(api);1055+1056+ yield* api.claim(bob, parseIso);1057+1058+ const before = yield* eventTags(api);1059+ const again = yield* openRed(api, "parse-iso");1060+1061+ return {1062+ again,1063+ events: [before, yield* eventTags(api)],1064+ listed: yield* api.listAsks(anyone),1065+ main: yield* mainTip,1066+ opened,1067+ };1068+});1069+1070+/** dave decides for `packages/format/**` only. */1071+const narrowDecider: WorldScenario = {1072+ policy: {1073+ ...scenario.policy,1074+ deciders: [1075+ ...scenario.policy.deciders,1076+ {1077+ handles: Array.make(dave.handle),1078+ paths: Glob.make("packages/format/**"),1079+ },1080+ ],1081+ },1082+};1083+1084+/** dave opens an ask in the format package, and one in the parser. */1085+const decidingNarrowly = Effect.gen(function* () {1086+ yield* advanceTo("2026-10-07T12:00:00Z");1087+1088+ const api = yield* projectService(project);1089+1090+ yield* api.initProject(alice, {});1091+1092+ const first = yield* Pusher.use((pusher) =>1093+ pusher.push(repo, Option.none(), start, "Start")1094+ );1095+1096+ yield* api.recordFirstPush(alice, first);1097+1098+ const outside = yield* Effect.result(openRed(api, "parse-iso", dave));1099+ const inside = yield* Effect.result(openRed(api, "format-date", dave));1100+1101+ return {1102+ inside: Result.map(inside, ({ ask }) => [ask.id, ask.askedBy]),1103+ outside,1104+ };1105+});1106+1107+describe("opening an ask", () => {1108+ it.effect(1109+ "again, once it is claimed, answers with the ask as it stands and lands nothing",1110+ () =>1111+ Effect.map(1112+ reopening.pipe(Effect.provide(worldOf(scenario, "memory"))),1113+ ({ again, events, listed, main, opened }) => {1114+ expect(again).toStrictEqual({1115+ ask: { ...opened.ask, state: "claimed" },1116+ landed: opened.landed,1117+ });1118+ expect(main).toBe(opened.landed);1119+ expect(events[1]).toStrictEqual(events[0]);1120+ expect(listed.asks.map(({ claimed }) => claimed)).toStrictEqual([1121+ true,1122+ ]);1123+ }1124+ )1125+ );1126+1127+ it.effect("is for a decider whose paths hold the ask's territory", () =>1128+ Effect.map(1129+ decidingNarrowly.pipe(Effect.provide(worldOf(narrowDecider, "memory"))),1130+ ({ inside, outside }) => {1131+ expect(outside).toStrictEqual(Result.fail(new NotDecider({})));1132+ expect(inside).toStrictEqual(1133+ Result.succeed([AskId.make("format-date"), dave.handle])1134+ );1135+ }1136+ )1137+ );1138+});1139+1140+describe("the project's outbox", () => {1141+ it.effect(1142+ "keeps a fork and a projection that failed, and the next alarm runs them again",1143+ () =>1144+ Effect.map(1145+ settling.pipe(1146+ Effect.provide(worldOf(scenario, "memory", { failOnce: true }))1147+ ),1148+ ({ after, before }) => {1149+ expect(before).toStrictEqual({1150+ alarm: Option.some(DateTime.add(noon, { seconds: 1 })),1151+ fork: false,1152+ outbox: ["MakeFork", "Projected"],1153+ });1154+ expect(after).toStrictEqual({1155+ fork: true,1156+ outbox: [],1157+ projected: ["Claimed", "AskOpened"],1158+ });1159+ }1160+ )1161+ );1162+1163+ it.effect("acts on one push event once, however often it is reported", () =>1164+ Effect.map(1165+ replaying.pipe(Effect.provide(worldOf(scenario, "memory"))),1166+ ({ again, events, first }) => {1167+ expect(again).toStrictEqual(first);1168+ expect(events[1]).toStrictEqual(events[0]);1169+ }1170+ )1171+ );1172+});1173+1174+describe("projects", () => {1175+ it.effect("are made once each, found by name, and kept apart", () =>1176+ Effect.map(1177+ routing.pipe(1178+ Effect.provide(1179+ ProjectsMemory.pipe(Layer.provideMerge(worldOf(scenario, "memory")))1180+ )1181+ ),1182+ (seen) => {1183+ expect(seen.again).toStrictEqual(new ProjectExists({ project }));1184+ expect(seen.unknown).toStrictEqual(1185+ new UnknownProject({ project: ProjectName.make("burrow") })1186+ );1187+ expect(seen.initializedAgain).toStrictEqual(1188+ new ProjectExists({ project })1189+ );1190+ expect(seen.otherInitialized).toStrictEqual(1191+ Exit.succeed({1192+ project: ProjectName.make("burrow"),1193+ remote: remoteOf("burrow"),1194+ })1195+ );1196+ }1197+ )1198+ );1199+1200+ it.effect(1201+ "adopt an imported repo's tip as their first landing, and refuse a repo they can't read",1202+ () =>1203+ Effect.map(1204+ importing.pipe(Effect.provide(worldOf(scenario, "memory"))),1205+ (seen) => {1206+ expect(seen.made).toStrictEqual({1207+ landed: seen.tip,1208+ project,1209+ remote: remoteOf(project),1210+ });1211+ expect([seen.main, seen.evaluated]).toStrictEqual([1212+ seen.tip,1213+ [seen.tip],1214+ ]);1215+ expect(seen.refused).toStrictEqual(1216+ new ImportFailed({ reason: "no repo at memory://none.git" })1217+ );1218+ }1219+ )1220+ );1221+});deleted:packages/project/test/smoke.test.ts-10 removed
1-import { describe, expect, it } from "@effect/vitest";2-3-import manifest from "../package.json" with { type: "json" };4-5-// A skeleton's one test, so vitest finds a file; real tests replace it.6-describe("the package", () => {7- it("is @repo/project", () => {8- expect(manifest.name).toBe("@repo/project");9- });10-});added:packages/project/test/world.ts+327 added
1+/**2+ * One project's whole world over memory adapters, for the service's3+ * scenario test (and the shape W3 310 copies for the platform's core-loop4+ * test): `RepoHostMemory`, the isomorphic-git `Lander` over it, a scripted5+ * `CheckRunnerMemory`, a `RulesEvaluator` that returns the scenario's policy,6+ * `AlarmsMemory`, `AnswerRunsInline`, `ProjectionMemory`, and the project7+ * store in memory or on SQLite (sqlite-node).8+ *9+ * The test drives only the service's methods; this file holds what stands10+ * in for the outside world: pushes into forks as git would make them, and11+ * the scripts the Checker follows.12+ */13+import { SqliteClient } from "@effect/sql-sqlite-node";14+import { ForkInProgress, RefName, RepoHost } from "@repo/artifacts/repo-host";15+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";16+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";17+import { CheckAt } from "@repo/checks/check-runner";18+import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";19+import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";20+import type { Policy } from "@repo/protocol/domain/policy";21+import type {22+ CommitSha,23+ LandedSha,24+ LaneName,25+ RepoName,26+ RepoPath,27+} from "@repo/protocol/ids";28+import { Finishers } from "@repo/rules/finish";29+import { RulesEvaluator } from "@repo/rules/rules-evaluator";30+import { gitClient } from "@repo/testkit/git-client";31+import type { Files } from "@repo/testkit/git-client";32+import type { Scenario } from "@repo/testkit/scenarios";33+import { Context, Effect, Layer, Option, Ref } from "effect";34+import type { Array } from "effect";35+36+import { AlarmsMemory } from "../src/alarms/memory.ts";37+import { AnswerRunsInline } from "../src/answer-runs/inline.ts";38+import { Lander } from "../src/lander.ts";39+import { LanderIsogit } from "../src/lander/isogit.ts";40+import type { ProjectStore } from "../src/project-store.ts";41+import { ProjectStoreMemory } from "../src/project-store/memory.ts";42+import { ProjectStoreSqlite } from "../src/project-store/sqlite.ts";43+import { FinishersFromChecks } from "../src/project.ts";44+import { Projection, ProjectionFailed } from "../src/projection.ts";45+import { ProjectionMemory } from "../src/projection/memory.ts";46+47+const mainRef = RefName.make("refs/heads/main");48+49+/** Where the project's store keeps its rows. */50+export type StoreKind = "memory" | "sqlite";51+52+/** What a world reads from a scenario: the policy its rules evaluator returns. */53+export type WorldScenario = Pick<Scenario, "policy">;54+55+/**56+ * What the Checker answers, by `(tree or commit, lane)`: the test adds to57+ * it as it learns the trees an answer will be checked on.58+ */59+export class CheckScript extends Context.Service<60+ CheckScript,61+ {62+ readonly script: (63+ at: CheckAt,64+ lane: LaneName,65+ results: readonly LaneOutcome[]66+ ) => Effect.Effect<void>;67+ }68+>()("test/CheckScript") {}69+70+/** Every landed commit the rules evaluator was asked about, in order. */71+export class Evaluated extends Context.Service<72+ Evaluated,73+ { readonly shas: Effect.Effect<readonly LandedSha[]> }74+>()("test/Evaluated") {}75+76+/** Commits made the way an answerer's git would make them, pushed to a repo's `main`. */77+export class Pusher extends Context.Service<78+ Pusher,79+ {80+ /**81+ * A commit of the whole tree `files` on `parent` (or a first commit),82+ * pushed to `repo`'s main with a compare-and-swap from `parent`.83+ */84+ readonly push: (85+ repo: RepoName,86+ parent: Option.Option<CommitSha>,87+ files: Files,88+ message?: string89+ ) => Effect.Effect<CommitSha>;90+ }91+>()("test/Pusher") {}92+93+/** The store's layer of one kind, fresh each time it is built. */94+const storeOf = (kind: StoreKind): Layer.Layer<ProjectStore> =>95+ kind === "memory"96+ ? ProjectStoreMemory97+ : ProjectStoreSqlite.pipe(98+ Layer.provide(99+ SqliteClient.layer({ filename: ":memory:" }).pipe(Layer.orDie)100+ )101+ );102+103+/**104+ * A `RulesEvaluator` that evaluates nothing: at any commit it returns the105+ * scenario's policy at that commit, holding the scenario's asks whose files106+ * the commit's config folder has, and the judge closure `checks` derives.107+ */108+const rulesOf = (scenario: WorldScenario) =>109+ Layer.effectContext(110+ Effect.gen(function* () {111+ const finishers = yield* Finishers;112+ const seen = yield* Ref.make<readonly LandedSha[]>([]);113+114+ const evaluator = RulesEvaluator.of({115+ call: () => Effect.succeed(false),116+ evaluate: ({ at, facts, modules }) =>117+ Effect.gen(function* () {118+ yield* Ref.update(seen, (shas) => [...shas, at]);119+120+ const { policy } = scenario;121+122+ return {123+ ...policy,124+ asks: policy.asks.filter(({ file }) => file in modules.modules),125+ at,126+ judge: finishers.judgeClosure(policy.run, facts.ci),127+ } satisfies Policy;128+ }),129+ });130+131+ return Context.make(RulesEvaluator, evaluator).pipe(132+ Context.add(Evaluated, { shas: Ref.get(seen) })133+ );134+ })135+ );136+137+const scriptOf = Layer.effectContext(138+ Effect.gen(function* () {139+ // The Checker reads its script when it runs, so the test may add to it later.140+ const script = new Map<string, readonly LaneResult[]>();141+142+ const runner = yield* Layer.build(CheckRunnerMemory.layer(script));143+144+ return runner.pipe(145+ Context.add(CheckScript, {146+ script: (at, lane, results) =>147+ Effect.sync(() => {148+ script.set(149+ scriptKey(at, lane),150+ results.map((result) => ({151+ command: `run ${lane}`,152+ durationMs: 1,153+ lane,154+ result,155+ }))156+ );157+ }),158+ })159+ );160+ })161+);162+163+const pusher = Layer.effect(164+ Pusher,165+ Effect.gen(function* () {166+ const host = yield* RepoHost;167+ const client = yield* gitClient(memoryFs());168+169+ return Pusher.of({170+ push: (repo, parent, files, message = "Work") =>171+ Effect.gen(function* () {172+ const sha = yield* client.commit(173+ message,174+ files,175+ Option.toArray(parent)176+ );177+178+ yield* host179+ .push(repo, client.source, [180+ { from: parent, ref: mainRef, to: sha },181+ ])182+ .pipe(Effect.orDie);183+184+ return sha;185+ }),186+ });187+ })188+);189+190+/** What fails in a world before it works. */191+export interface Faults {192+ /** The first fork and the first projection fail; every later one works. */193+ readonly failOnce?: boolean;194+}195+196+/**197+ * `RepoHostMemory`, where a public remote `https://example.com/<name>.git`198+ * is the store's own repo `<name>`, so a test can import one.199+ */200+const hostOf = (base: Layer.Layer<RepoHost>) =>201+ Layer.effect(202+ RepoHost,203+ Effect.gen(function* () {204+ const host = yield* RepoHost;205+206+ return RepoHost.of({207+ ...host,208+ importFrom: (name, source) =>209+ host.importFrom(name, {210+ ...source,211+ url: source.url.replace(/^https:\/\/example\.com\//u, "memory://"),212+ }),213+ });214+ })215+ ).pipe(Layer.provide(base));216+217+/** `RepoHostMemory`, whose first fork is still in progress. */218+const flakyHost = Layer.effect(219+ RepoHost,220+ Effect.gen(function* () {221+ const host = yield* RepoHost;222+ const failed = yield* Ref.make(false);223+224+ return RepoHost.of({225+ ...host,226+ fork: (base, name) =>227+ Effect.flatMap(Ref.getAndSet(failed, true), (before) =>228+ before229+ ? host.fork(base, name)230+ : Effect.fail(new ForkInProgress({ name }))231+ ),232+ });233+ })234+).pipe(Layer.provide(RepoHostMemory));235+236+/** `ProjectionMemory`, whose first apply is refused. */237+const flakyProjection = Layer.effectContext(238+ Effect.gen(function* () {239+ const kept = yield* Layer.build(ProjectionMemory);240+ const projection = Context.get(kept, Projection);241+ const failed = yield* Ref.make(false);242+243+ return kept.pipe(244+ Context.add(Projection, {245+ apply: (rows) =>246+ Effect.flatMap(Ref.getAndSet(failed, true), (before) =>247+ before248+ ? projection.apply(rows)249+ : Effect.fail(250+ new ProjectionFailed({ reason: "the read model is down" })251+ )252+ ),253+ })254+ );255+ })256+);257+258+/** Every service the scenario test reads besides the project's ports. */259+const fixtures = (scenario: WorldScenario) =>260+ Layer.mergeAll(scriptOf, rulesOf(scenario), pusher).pipe(261+ Layer.provideMerge(FinishersFromChecks)262+ );263+264+/**265+ * The scenario's world: every port the project service needs, and what the266+ * test reads back (the store, the alarm, the projection, the repos), built267+ * fresh for each test.268+ */269+export const worldOf = (270+ scenario: WorldScenario,271+ store: StoreKind,272+ faults: Faults = {}273+) =>274+ Layer.mergeAll(275+ AnswerRunsInline,276+ AlarmsMemory,277+ faults.failOnce === true ? flakyProjection : ProjectionMemory,278+ storeOf(store)279+ ).pipe(280+ Layer.provideMerge(fixtures(scenario)),281+ Layer.provideMerge(LanderIsogit),282+ Layer.provideMerge(283+ hostOf(faults.failOnce === true ? flakyHost : RepoHostMemory)284+ )285+ );286+287+/** The commit an ask's files compose onto main as, where its check runs red first. */288+export const composedAt = (289+ repo: RepoName,290+ main: LandedSha,291+ files: Array.NonEmptyReadonlyArray<{292+ readonly content: string;293+ readonly path: RepoPath;294+ }>295+) =>296+ Effect.map(297+ Lander.use((lander) => lander.compose({ files, main, repo })),298+ ({ commit }) => CheckAt.cases.Commit.make({ commit })299+ ).pipe(Effect.orDie);300+301+/** The tree an answer merges onto main as, where its checks run. */302+export const mergedAt = (input: {303+ readonly repo: RepoName;304+ readonly main: LandedSha;305+ readonly base: CommitSha;306+ readonly head: CommitSha;307+ readonly fork: RepoName;308+}) =>309+ Effect.map(310+ Lander.use((lander) => lander.merge(input)),311+ ({ tree }): CheckAt => CheckAt.cases.Tree.make({ tree })312+ ).pipe(Effect.orDie);313+314+/** The tree an answer merges onto main as, or none when the merge conflicts. */315+export const cleanMergeAt = (input: {316+ readonly repo: RepoName;317+ readonly main: LandedSha;318+ readonly base: CommitSha;319+ readonly head: CommitSha;320+ readonly fork: RepoName;321+}) =>322+ Effect.option(323+ Effect.map(324+ Lander.use((lander) => lander.merge(input)),325+ ({ tree }): CheckAt => CheckAt.cases.Tree.make({ tree })326+ )327+ );