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