Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent c5f1296 · Browse files · 17 files+5763 added−10 removed
This commit

State

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

Diff stats

17 files+5763 added−10 removed

  • tests:+1423 added−10 removed
  • other:+4340 added−0 removed

17 files+5763 added−10 removed

added:packages/project/src/alarms/memory.ts+28 added
added:packages/project/src/answer-runs/inline.ts+56 added
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 */11import { CheckAt, CheckRunner } from "@repo/checks/check-runner";12import type { CheckLane, CheckRun } from "@repo/checks/check-runner";13import { classifyFailure } from "@repo/gate/classify";14import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";15import { LandedSha } from "@repo/protocol/ids";16import type { LaneName, RepoPath, RequestId } from "@repo/protocol/ids";17import type { Refusal, VerifierBlocked } from "@repo/protocol/refusal";18import { Array, Effect, Option } from "effect";1920import type { AnswerQueue, AnswerReport, AnswerRun } from "../answer-runs.ts";21import { Lander, Rebuild } from "../lander.ts";22import {23 LandingCommand,24 LandingEffect,25 LandingState,26 pendingEffects,27} from "../landing.ts";2829/** A step's result: the command it reports, and what it saw beside it. */30export interface Reported {31 readonly command: LandingCommand;32 readonly report?: AnswerReport;33}3435/** Whether an effect is a port call a run makes, rather than the project's to settle. */36export const isStep = (effect: LandingEffect) =>37 LandingEffect.$is("Merge")(effect) ||38 LandingEffect.$is("RunChecks")(effect) ||39 LandingEffect.$is("Land")(effect);4041/**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 */45export const nextSteps = (run: AnswerRun): readonly LandingEffect[] =>46 LandingState.guards.Landing(run.state) && !run.admitted47 ? []48 : pendingEffects(run.state);4950/** The attempt a port's `Busy` or `Blocked` report is about: the state's own. */51const attemptOf = (state: LandingState) =>52 LandingState.matchOrElse(53 state,54 {55 Checking: ({ attempt }) => attempt,56 Landing: ({ attempt }) => attempt,57 Merging: ({ attempt }) => attempt,58 },59 () => 060 );6162const reported = (command: LandingCommand, report?: AnswerReport): Reported =>63 report === undefined ? { command } : { command, report };6465/** The answer's head merged onto `main`: the tree to check, or the paths that conflict. */66const 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 );9394/** Each lane's result in a run, by lane. */95const resultsOf = (run: CheckRun): ReadonlyMap<LaneName, LaneResult> =>96 new Map(run.lanes.map((lane) => [lane.lane, lane]));9798const isTrouble = (result: LaneOutcome) =>99 result === "flaked" || result === "blocked";100101/** Where a lane's log is kept when its run named no place: by request and lane. */102const logRefOf = (requestId: RequestId, lane: LaneName) =>103 `${requestId}/${lane}`;104105/**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 */112const 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;119120 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 });129130 const lanesNamed = (names: ReadonlySet<LaneName>) =>131 run.lanes.filter(({ lane }) => names.has(lane));132133 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");136137 const troubled = new Set(138 failing.filter(({ result }) => isTrouble(result)).map(({ lane }) => lane)139 );140141 const onMainNeeded = new Set(142 failing.map(({ lane }) => lane).filter((lane) => lane !== run.askLane)143 );144145 const rerun =146 troubled.size === 0147 ? new Map<LaneName, LaneResult>()148 : resultsOf(yield* job(onTree, lanesNamed(troubled)));149150 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 );159160 const changed = new Set<RepoPath>(checking.changes.map(({ path }) => path));161162 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 );185186 const lanes = merged.lanes.map((lane) => rerun.get(lane.lane) ?? lane);187188 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 });198199/**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 */204const 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 );251252/**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 */257export 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 });284285/**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 */291export 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);300301 if (effect === undefined || steps.some(LandingEffect.$is("Retry"))) {302 return;303 }304305 const run = yield* queue.answer(requestId);306307 if (Option.isNone(run)) {308 return;309 }310311 const step = yield* runStep(run.value, effect);312313 if (Option.isNone(step)) {314 return;315 }316317 const advanced = yield* queue.advanceAnswer(318 requestId,319 step.value.command,320 step.value.report321 );322323 yield* go(advanced.effects);324 });325326 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
added:packages/project/src/projects/memory.ts+63 added
added:packages/project/src/alarms.ts+17 added
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 */13import { CheckLane } from "@repo/checks/check-runner";14import {15 HeldBackResult,16 LaneResult,17 Verdict,18} from "@repo/protocol/domain/answer";19import { Ask } from "@repo/protocol/domain/ask";20import { Choice } from "@repo/protocol/domain/decision";21import { AskKind } from "@repo/protocol/domain/kind";22import { Outcome } from "@repo/protocol/domain/outcome";23import {24 AskId,25 CommitSha,26 DecisionId,27 Handle,28 LandedSha,29 LaneName,30 RepoName,31 RepoPath,32 TreeSha,33} from "@repo/protocol/ids";34import type { RequestId } from "@repo/protocol/ids";35import { Refusal } from "@repo/protocol/refusal";36import { Context, Schema } from "effect";37import type { Effect, Option } from "effect";3839import { Change, LandingState, PendingDecision } from "./landing.ts";40import type { LandingCommand, LandingEffect } from "./landing.ts";4142const Attempt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));4344/**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 */49export 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});6768/**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 */73export 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});7980/** What `advanceAnswer` returns, as it crosses a boundary: `Advanced`. */81export const Steps = Schema.Struct({82 effects: Schema.Array(NextStep),83 outcome: Outcome,84});8586/**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 */91export 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});110111export type AnswerRun = typeof AnswerRun.Type;112113/**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 */118export 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});125126export type AnswerReport = typeof AnswerReport.Type;127128/** What one reported step changed: where the answer stands now, and the port calls to run next. */129export interface Advanced {130 readonly effects: readonly LandingEffect[];131 readonly outcome: Outcome;132}133134/**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 */141export 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}151152/**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 */159export 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
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 */9import { ObjectId, RepoHost, Revision } from "@repo/artifacts/repo-host";10import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";11import { PushTarget } from "@repo/gate/facts";12import type { PushFacts } from "@repo/gate/facts";13import { addedLines, treeDiff } from "@repo/git/tree-diff";14import type { Change } from "@repo/git/tree-diff";15import type { Ask } from "@repo/protocol/domain/ask";16import type { ClaimView } from "@repo/protocol/domain/claim";17import { RefNameText } from "@repo/protocol/domain/common";18import type { Policy } from "@repo/protocol/domain/policy";19import {20 AskId,21 Handle,22 LayerName,23 RepoPath,24 TreeSha,25} from "@repo/protocol/ids";26import type {27 CommitSha,28 LandedSha,29 ProjectName,30 RepoName,31} from "@repo/protocol/ids";32import type { Principal } from "@repo/protocol/principal";33import type { EvaluationFacts } from "@repo/rules/rules-evaluator";34import { Array, Effect, Option, Predicate, Schema } from "effect";35import type { DateTime } from "effect";3637/** A commit the push names that the repo does not hold. */38export class MissingCommit extends Schema.TaggedError<MissingCommit>()(39 "MissingCommit",40 { sha: Schema.String }41) {}4243const asAsk = Schema.decodeUnknownOption(AskId);4445const asHandle = Schema.decodeUnknownOption(Handle);4647const asLayer = Schema.decodeUnknownOption(LayerName);4849/**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 */55export const targetOf = (repo: RepoName, project: ProjectName): PushTarget => {56 const [named, second, third, ...rest] = repo.split("--");57 const canonical = PushTarget.Canonical({ project });5859 if (named !== project || rest.length > 0 || second === undefined) {60 return canonical;61 }6263 if (third === undefined) {64 return Option.match(asLayer(second), {65 onNone: () => canonical,66 onSome: (layer) => PushTarget.Layer({ layer, project }),67 });68 }6970 if (second === "me") {71 return Option.match(asHandle(third), {72 onNone: () => canonical,73 onSome: (owner) => PushTarget.WorkingFork({ owner, project }),74 });75 }7677 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};8687const 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 );9697const textOf = (bytes: Uint8Array) => new TextDecoder().decode(bytes);9899const ScriptsOf = Schema.fromJsonString(100 Schema.Struct({ scripts: Schema.optionalKey(Schema.Json) })101);102103const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);104105/** A `package.json` blob's `scripts`, as canonical JSON text; none when it reads as no manifest. */106const 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 );117118/** Whether the root manifest's `scripts` differ between the change's two blobs. */119const 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 );134135/** What `pushFacts` is told: the push, and what the project knows about it. */136export 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}151152/**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 */158export 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);164165 const changes = yield* treeDiff(166 input.repo,167 TreeSha.make(base.tree),168 TreeSha.make(head.tree)169 );170171 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 });192193// ------------------------------------------------------------ rules facts194195// The folders whose files the run-block finder reads (spec §4.2 `checks`).196const CI_FOLDERS = [".github/workflows", ".forgejo/workflows", ".husky"];197198// A file the finder reads is small; a large one is no config.199const MAX_FACT_BYTES = 256 * 1024;200201const 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);208209const decodeManifest = Schema.decodeUnknownOption(Manifest);210211/** The entries of the folder at `path` (`""` for the root) of a tree. */212const 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 );247248/** Each blob directly in a folder, as a path and its text. */249const 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 );268269const isJsonArray = (value: Schema.Json): value is Schema.JsonArray =>270 globalThis.Array.isArray(value);271272const isJsonObject = (value: Schema.Json): value is Schema.JsonObject =>273 Predicate.isObject(value) && !isJsonArray(value);274275const strings = (value: Schema.Json | undefined): readonly string[] =>276 value !== undefined && isJsonArray(value)277 ? value.filter(Predicate.isString)278 : [];279280/** A manifest's `workspaces`: an array of globs, or `{ packages: [...] }`. */281const workspaceGlobs = (value: Schema.Json | undefined): readonly string[] => {282 if (value === undefined || value === null) {283 return [];284 }285286 if (isJsonArray(value)) {287 return strings(value);288 }289290 return isJsonObject(value) ? strings(value.packages) : [];291};292293/** Every string an `exports` field leads to, nested conditions included. */294const exportTargets = (value: Schema.Json | undefined): readonly string[] => {295 if (value === undefined || value === null) {296 return [];297 }298299 if (Predicate.isString(value)) {300 return [value];301 }302303 if (isJsonArray(value)) {304 return value.flatMap(exportTargets);305 }306307 return isJsonObject(value) ? Object.values(value).flatMap(exportTargets) : [];308};309310const withoutDotSlash = (path: string) => path.replace(/^(?:\.\/)+/u, "");311312/**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 */317const foldersOf = (repo: RepoName, root: ObjectId, glob: string) => {318 const clean = withoutDotSlash(glob).replace(/\/+$/u, "");319 const star = clean.indexOf("*");320321 if (star === -1) {322 return Effect.succeed([clean]);323 }324325 const parent = clean.slice(0, star).replace(/\/+$/u, "");326327 return Effect.map(folderAt(repo, root, parent), (entries) =>328 entries329 .filter(({ type }) => type === "tree")330 .map(({ name }) => (parent === "" ? name : `${parent}/${name}`))331 );332};333334/** One workspace package: its folder, its name, and the files its `exports` name. */335const 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 );355356/** What `evaluationFacts` is told besides the commit. */357export 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}364365/**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 */373export 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 };387388 const commit = yield* RepoHost.use((host) => host.readCommit(repo, at));389390 if (Option.isNone(commit)) {391 return empty;392 }393394 const root = commit.value.tree;395 const atRoot = yield* filesIn(repo, root, "");396397 const ci = [398 ...atRoot,399 ...(yield* Effect.forEach(CI_FOLDERS, (folder) =>400 filesIn(repo, root, folder)401 )).flat(),402 ];403404 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 );416417 const dirs = Array.dedupe(418 (yield* Effect.forEach(globs, (glob) =>419 foldersOf(repo, root, glob)420 )).flat()421 );422423 const workspaces = Array.getSomes(424 yield* Effect.forEach(dirs, (dir) => workspaceAt(repo, root, dir))425 );426427 const vouch = yield* RepoHost.use((host) =>428 host.readFile(repo, Revision.Commit({ sha: at }), input.vouchFile)429 );430431 const facts: EvaluationFacts = { ...empty, ci, workspaces };432433 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 */13import { RefName, RepoHost } from "@repo/artifacts/repo-host";14import { Verdict } from "@repo/protocol/domain/answer";15import type { ProjectEvent } from "@repo/protocol/domain/event";16import {17 CommitSha,18 Handle,19 LandedSha,20 RepoName,21 RequestId,22 TreeSha,23} from "@repo/protocol/ids";24import type { ProjectName } from "@repo/protocol/ids";25import { Array, DateTime, Effect, Option, Order, Schema } from "effect";2627import { AnswerRuns } from "./answer-runs.ts";28import type { AnswerQueue } from "./answer-runs.ts";29import { Lander, Rebuild } from "./lander.ts";30import { backoff } from "./landing.ts";31import type { OutboxRow } from "./project-store/rows.ts";32import { Projection, ProjectedEvent } from "./projection.ts";3334const mainRef = RefName.make("refs/heads/main");3536/** An answer's landing job, as its bookkeeping retry lands it again. */37export 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});4950export type LandAgain = typeof LandAgain.Type;5152/** What one outbox row asks for. */53export 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"));5960export type OutboxBody = typeof OutboxBody.Type;6162const BodyJson = Schema.toCodecJson(OutboxBody);6364const encodeBody = Schema.encodeEffect(BodyJson);6566const decodeBody = Schema.decodeUnknownEffect(BodyJson);6768/** A row asking for `body`, due at `notBefore`; a row with the same id is replaced. */69export 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 }));8182/** One row per event, for the read models, keyed by the event's number. */83export 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 );9596/** The row that starts (or resumes) an answer's run at `at`. */97export const startRow = (requestId: RequestId, at: DateTime.Utc) =>98 outboxRow(99 `start:${requestId}:${DateTime.toEpochMillis(at)}`,100 OutboxBody.cases.StartAnswer.make({ requestId }),101 at102 );103104/** Whether a row is due at `now`. */105export const isDue = (row: OutboxRow, now: DateTime.Utc) =>106 DateTime.isLessThanOrEqualTo(row.notBefore, now);107108/** What running some rows came to: the ids done, and the rows to run again later. */109export interface OutboxRun {110 readonly done: readonly string[];111 readonly retry: readonly OutboxRow[];112}113114/** The row again, after `attempts` failures: due after a backoff from `now`. */115const later = (row: OutboxRow, now: DateTime.Utc): OutboxRow => ({116 ...row,117 attempts: row.attempts + 1,118 notBefore: DateTime.addDuration(now, backoff(row.attempts)),119});120121interface Decoded {122 readonly body: OutboxBody;123 readonly row: OutboxRow;124}125126const ran = (row: OutboxRow, ok: boolean, now: DateTime.Utc): OutboxRun =>127 ok ? { done: [row.id], retry: [] } : { done: [], retry: [later(row, now)] };128129const all = (runs: readonly OutboxRun[]): OutboxRun => ({130 done: runs.flatMap(({ done }) => done),131 retry: runs.flatMap(({ retry }) => retry),132});133134/**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 */138const 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 );151152/** The landing job again: its unwritten bookkeeping is written, and nothing else moves. */153const 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 );173174const bySeq = Order.mapInput(Order.Number, ({ body }: Decoded) =>175 OutboxBody.guards.Projected(body) ? body.event.seq : 0176);177178/**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 */183export 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 );196197 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 );205206 const projected = Array.sort(of("Projected"), bySeq);207208 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;221222 const forks = yield* Effect.forEach(of("MakeFork"), ({ body, row }) =>223 Effect.map(fork(body.from, body.name), (ok) => ran(row, ok, now))224 );225226 const kept = yield* Effect.forEach(of("Bookkeeping"), ({ body, row }) =>227 Effect.map(landAgain(body.job), (ok) => ran(row, ok, now))228 );229230 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 );236237 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 */17import { BranchName, RefName, RepoHost } from "@repo/artifacts/repo-host";18import type { RepoNotFound } from "@repo/artifacts/repo-host";19import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";20import { Brand } from "@repo/brand";21import { CheckAt, CheckLane, CheckRunner } from "@repo/checks/check-runner";22import { findRunBlock } from "@repo/checks/finder";23import { judgeClosure } from "@repo/checks/judge";24import { checkVersion, commandFor } from "@repo/checks/kinds";25import { redFirstOfRuns } from "@repo/checks/red-first";26import { weaknessesOf } from "@repo/checks/weak-shapes";27import { PushTarget } from "@repo/gate/facts";28import type { PushFacts } from "@repo/gate/facts";29import { pushStages, runGate } from "@repo/gate/gate";30import { scan } from "@repo/gate/stages/shape";31import { verdictOf } from "@repo/gate/verdict";32import { patchId } from "@repo/git/patch-id";33import { formatLanding } from "@repo/git/trailers";34import {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";46import { AnswerReceipt, Verdict } from "@repo/protocol/domain/answer";47import type {48 AnswerView,49 HeldBackResult,50 LaneResult,51} from "@repo/protocol/domain/answer";52import type { Ask, AskListing } from "@repo/protocol/domain/ask";53import { CheckSpec } from "@repo/protocol/domain/check";54import type { ClaimView } from "@repo/protocol/domain/claim";55import { RefNameText } from "@repo/protocol/domain/common";56import type { Credit } from "@repo/protocol/domain/credit";57import { ProjectEvent } from "@repo/protocol/domain/event";58import type { AskKind } from "@repo/protocol/domain/kind";59import type { LandingView } from "@repo/protocol/domain/landing";60import type { Outcome, StageName } from "@repo/protocol/domain/outcome";61import { Policy } from "@repo/protocol/domain/policy";62import {63 AskId,64 CommitSha,65 LandedSha,66 RepoName,67 RepoPath,68 RequestId,69} from "@repo/protocol/ids";70import type { Handle, LaneName, ProjectName } from "@repo/protocol/ids";71import { Person, Principal } from "@repo/protocol/principal";72import {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";89import 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";101import { Finishers } from "@repo/rules/finish";102import { RulesEvaluator } from "@repo/rules/rules-evaluator";103import {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";117import { init } from "isomorphic-git";118119import { Alarms } from "./alarms.ts";120import {121 AnswerReport,122 AnswerRun,123 ReportedCommand,124 Steps,125} from "./answer-runs.ts";126import type { AnswerQueue, AnswerRuns } from "./answer-runs.ts";127import { isStep } from "./answer-runs/steps.ts";128import { recordOf, sameHandle } from "./attention/record.ts";129import { mayClaim, standing } from "./attention/vouch.ts";130import {131 ClaimCommand,132 ClaimEffect,133 ClaimState,134 forkName,135 toView,136 transition as claimTransition,137} from "./claim.ts";138import type { ClaimStep, Live } from "./claim.ts";139import { askClosed, askOpened, judged, listingOf, numbered } from "./events.ts";140import { evaluationFacts, pushFacts, targetOf } from "./facts.ts";141import type { MissingCommit } from "./facts.ts";142import { Lander, Rebuild } from "./lander.ts";143import type { ComposedFile } from "./lander.ts";144import {145 LandingCommand,146 LandingEffect,147 LandingState,148 outcomeOf,149 transition as landingTransition,150} from "./landing.ts";151import type { LandingQueue, Request } from "./landing.ts";152import { isDue, outboxRow, OutboxBody, runOutbox, startRow } from "./outbox.ts";153import { ProjectStore } from "./project-store.ts";154import type { ProjectWrites } from "./project-store.ts";155import type {156 AnswerRow,157 ClaimRow,158 OutboxRow,159 ProjectEventInput,160 ProjectRow,161 PushEventRow,162} from "./project-store/rows.ts";163import type { Projection } from "./projection.ts";164import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";165166/** Every port one project's service runs on. */167export type ProjectPorts =168 | Alarms169 | AnswerRuns170 | CheckRunner171 | Lander172 | ProjectStore173 | Projection174 | RepoHost175 | RulesEvaluator;176177/**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 */182export const GatewayUrl = Context.Reference<string>("project/GatewayUrl", {183 defaultValue: () => `https://${Brand.domain}`,184});185186/**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 */191const sdkVersion = "0.0.0";192193/**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 */198export const FinishersFromChecks: Layer.Layer<Finishers> = Layer.succeed(199 Finishers,200 { findRunBlock, judgeClosure }201);202203/** A push one repo took, as the gateway's custody reports it (W3 303). */204export 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});213214export type PushReport = typeof PushReport.Type;215216/** One file a decider opens an ask with: its ask file, or its check. */217export interface AskFile {218 readonly content: string;219 readonly path: RepoPath;220}221222/** The refusals `submitAnswer` answers with. */223export type SubmitRefusal =224 | NotClaimed225 | ClaimLapsed226 | StaleBase227 | RepoBusy228 | OutOfScope229 | TouchedJudge230 | Weakened231 | ReachedInternals232 | PrivatePathInPublicTree;233234/**235 * Every contract's server logic for one project. Each method takes its236 * caller explicitly: one project's service serves many callers.237 */238export 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}339340/** The schemas one method's arguments (in order), success and failure cross a boundary with. */341export interface MethodSchema {342 readonly args: readonly Schema.Top[];343 readonly error: Schema.Top;344 readonly success: Schema.Top & { readonly EncodingServices: never };345}346347/**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 */353export 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 };450451/**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 */456export const AnswerRecord = Schema.Struct({457 landing: LandingState,458 receipt: AnswerReceipt,459 verdict: Schema.optionalKey(Verdict),460});461462export type AnswerRecord = typeof AnswerRecord.Type;463464const ClaimJson = Schema.toCodecJson(ClaimState);465466const AnswerJson = Schema.toCodecJson(AnswerRecord);467468const PolicyJson = Schema.toCodecJson(Policy);469470const decodeClaim = Schema.decodeUnknownEffect(ClaimJson);471472const encodeClaim = Schema.encodeEffect(ClaimJson);473474const decodeAnswer = Schema.decodeUnknownEffect(AnswerJson);475476const encodeAnswer = Schema.encodeEffect(AnswerJson);477478const decodePolicy = Schema.decodeUnknownEffect(PolicyJson);479480const encodePolicy = Schema.encodeEffect(PolicyJson);481482/**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 */488const 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 );506507const mainRef = RefName.make("refs/heads/main");508509const HOUR = 3_600_000;510511/** The claim deadlines before a project has a policy: the defaults (spec §2.5). */512const defaultClaims: Policy["claims"] = {513 lapseAfterMs: 24 * HOUR,514 warnAfterMs: 2 * HOUR,515};516517interface Claimed {518 readonly row: ClaimRow;519 readonly state: ClaimState;520}521522interface Answered {523 readonly record: AnswerRecord;524 readonly row: AnswerRow;525}526527/** A project as one call reads it at its start. */528interface 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}539540/**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 */545interface 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}556557const 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});568569const 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);581582const claimKey = (ask: AskId, claimant: Handle) =>583 JSON.stringify([ask, claimant.toLowerCase()]);584585/** A claim's own fields, in every state but `Open`. */586const 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 });595596const isLive = ClaimState.isAnyOf(["Live", "Warned"]);597598/** When a live claim's next deadline is: its warning, or once warned its lapse. */599const 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 });608609const isDecider = (policy: Policy, handle: Handle) =>610 policy.deciders.some(({ handles }) =>611 handles.some((each) => sameHandle(each, handle))612 );613614/** A path a composed commit can hold: plain folder names and a file name. */615const isPlainPath = (path: string) =>616 path617 .split("/")618 .every(619 (segment) =>620 segment !== "" &&621 segment !== "." &&622 segment !== ".." &&623 segment !== ".git"624 );625626/** Whether the brief holds a field its kind requires. */627const 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 );637638/** An optional field as an object to spread: the field when present, nothing when not. */639const 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 });647648/** The credit an answer's landing carries: who asked, who answered, who mentored. */649const 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];659660/** What a check of `ask` runs, and the lane it reports as. */661const askLaneOf = (policy: Policy, ask: Ask) =>662 commandFor(ask.check, policy.run, policy.ratchets);663664/** The lanes an answer's checks run: the ask's own check, then every project lane. */665const 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];680681/** A section of a brief, when it has lines. */682const section = (heading: string, lines: readonly string[] | undefined) =>683 lines === undefined || lines.length === 0684 ? []685 : ["", `## ${heading}`, "", ...lines];686687const listed = (lines: readonly string[] | undefined) =>688 lines?.map((line) => `- ${line}`);689690/** What an ask's check holds it to, in a sentence. */691const 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 });704705/** The ask as an answerer reads it first, in Markdown. */706const briefOf = (ask: Ask): string => {707 const { brief, territory } = ask;708 const paths = territory.paths.map((path) => `\`${path}\``).join(", ");709710 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};726727/** The refusal `submitAnswer` gives for one from the gate: its own, or `NotClaimed`. */728const 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 );744745/** A landing's commit message, from the platform's own rows (spec §5 step 8). */746const 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 };758759 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};771772/** Answers oldest first, by when their row last moved. */773const byUpdated = Order.mapInput(774 DateTime.Order,775 ({ row }: Answered) => row.updatedAt776);777778/** A `Landed` event with the verdict the landing carries; any other event as it is. */779const 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 );790791/** Whether a landing's effect is for the answer's run: a step, or a retry to wait for. */792const runnable = (effect: LandingEffect) =>793 isStep(effect) || LandingEffect.$is("Retry")(effect);794795const isTouchedJudge = (refusal: Refusal): refusal is TouchedJudge =>796 Match.value(refusal).pipe(797 Match.tag("TouchedJudge", () => true),798 Match.orElse(() => false)799 );800801type Checking = Extract<LandingState, { readonly _tag: "Checking" }>;802803type Landing = Extract<LandingState, { readonly _tag: "Landing" }>;804805/** What a landing's effects leave: the steps to hand to the run, and the queue. */806interface Settled {807 readonly queue: LandingQueue;808 readonly steps: readonly LandingEffect[];809}810811/** Starts the run of a request the queue just admitted, unless it is the one advancing. */812const 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 );826827/** Whether an ask's check file has one of the five weak shapes. */828const weakness = (ask: Ask, files: readonly AskFile[]) => {829 const { check } = ask;830831 const file = CheckSpec.guards.RedThenGreen(check)832 ? Option.fromUndefinedOr(files.find(({ path }) => path === check.path))833 : Option.none<AskFile>();834835 return Option.flatMap(file, (found) =>836 Array.head(weaknessesOf(found, ask.territory.paths))837 );838};839840/** Stage 0–1's refusals for a push, every one; what a missing commit or repo comes to. */841const 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 );859860/** The queue once a request no longer landing has left its place in it. */861const 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;871872 const inLine = holdsSlot(queue, requestId) || queue.order.includes(requestId);873874 if (LandingState.guards.Landing(input.state) || !inLine) {875 return Effect.succeed(queue);876 }877878 const left = leave(queue, requestId);879880 return Effect.as(881 startOther(writes, left.admitted, requestId, input.now),882 left.queue883 );884};885886/** One project's service over the ports. */887export 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);900901 const withPorts = <A, E>(effect: Effect.Effect<A, E, ProjectPorts>) =>902 Effect.provideContext(effect, ports);903904 // ----------------------------------------------------------- hydrate905906 const hydrate: Effect.Effect<Hydrated> = Effect.gen(function* () {907 const snapshot = yield* store.load();908909 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 );918919 const claims = yield* Effect.forEach(snapshot.claims, (row) =>920 Effect.map(Effect.orDie(decodeClaim(row.state)), (state) => ({921 row,922 state,923 }))924 );925926 const answers = yield* Effect.forEach(snapshot.answers, (row) =>927 Effect.map(Effect.orDie(decodeAnswer(row.state)), (record) => ({928 record,929 row,930 }))931 );932933 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 });945946 /** 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 );953954 /** 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));957958 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 );964965 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;972973 const findAnswer = (h: Hydrated, requestId: RequestId) =>974 Option.fromUndefinedOr(975 h.answers.find(({ row }) => row.requestId === requestId)976 );977978 const claimsPolicy = (h: Hydrated) =>979 Option.getOrElse(980 Option.map(h.policy, ({ claims }) => claims),981 () => defaultClaims982 );983984 /** 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;992993 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 );10011002 return Option.flatMap(claimOf(state), ({ fork }) =>1003 toView(state, {1004 checkCommand,1005 project: name,1006 remote: `${gateway}/${fork}.git`,1007 })1008 );1009 });10101011 // ------------------------------------------------------------ commit10121013 /**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 }10231024 const events = yield* numbered(h.lastSeq, writes.events);10251026 const projected = yield* Effect.forEach(events, (event) =>1027 outboxRow(1028 `projected:${event.seq}`,1029 OutboxBody.cases.Projected.make({ event, project: name }),1030 now1031 )1032 );10331034 const outbox = [...writes.outbox, ...projected];10351036 const queue = yield* Effect.forEach(writes.queue.values(), (each) =>1037 storedQueue(each)1038 );10391040 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 };10541055 const committed = yield* store.commit(all);10561057 if (committed.duplicatePushEvents.length > 0) {1058 return [];1059 }10601061 const expected = events.map(({ seq }) => seq);10621063 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 }10711072 return outbox;1073 });10741075 // ------------------------------------------------------------ settle10761077 /** Sets the project's alarm to its earliest pending deadline or retry. */1078 const armAlarm = Effect.gen(function* () {1079 const h = yield* hydrate;10801081 const deadlines = [1082 ...h.claims.flatMap(({ state }) => Option.toArray(deadlineOf(state))),1083 ...h.outbox.map(({ notBefore }) => notBefore),1084 ];10851086 if (Array.isReadonlyArrayNonEmpty(deadlines)) {1087 yield* alarms.set(Array.min(deadlines, DateTime.Order));1088 }1089 });10901091 /**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;10981099 const due = Array.dedupeWith(1100 rows.filter((row) => isDue(row, now)),1101 (one, other) => one.id === other.id1102 );11031104 if (Array.isReadonlyArrayNonEmpty(due)) {1105 const ran = yield* withPorts(runOutbox(due, queue, now));11061107 yield* store.ackOutbox(ran.done);11081109 if (Array.isReadonlyArrayNonEmpty(ran.retry)) {1110 yield* lock.withPermits(1)(store.commit({ outbox: ran.retry }));1111 }1112 }11131114 yield* armAlarm;1115 });11161117 /**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);11381139 return [result, yield* commit(h, writes, now)] as const;1140 })1141 );11421143 yield* settle(queue, rows);11441145 return answered;1146 });11471148 // ------------------------------------------------------------ claims11491150 /** 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 );11621163 if (Option.isNone(open)) {1164 return;1165 }11661167 const claimant = Option.map(1168 claimOf(step.state),1169 (claim) => claim.claimant1170 );11711172 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 );11781179 const next = isLive(step.state) || others ? "claimed" : "open";11801181 if (next !== open.value.state) {1182 writes.asks.set(ask, { ...open.value, state: next });1183 }1184 };11851186 /** 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);11961197 if (Option.isNone(claim)) {1198 return;1199 }12001201 const { claimant } = claim.value;12021203 writes.claims.set(claimKey(ask, claimant), {1204 ask,1205 claimant,1206 state: yield* Effect.orDie(encodeClaim(step.state)),1207 updatedAt: now,1208 });12091210 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 );12321233 askAfter(h, writes, ask, step);1234 });12351236 // ------------------------------------------------------------ policy12371238 /** 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 );12481249 const vouchFile = Option.getOrElse(1250 Option.map(previous, ({ vouch }) => vouch.file),1251 () => RepoPath.make(`${Brand.configDir}/vouched.td`)1252 );12531254 const bundle = yield* Effect.option(lander.bundleRules({ at, repo }));12551256 if (Option.isNone(bundle)) {1257 yield* Effect.logWarning(1258 `the config folder at ${at} could not be read`1259 );12601261 return Option.none<Policy>();1262 }12631264 const facts = yield* withPorts(1265 evaluationFacts(repo, at, {1266 initializer: row.initializer,1267 now,1268 project: name,1269 vouchFile,1270 })1271 );12721273 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 });12831284 /**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 );13011302 /** 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" };13061307 yield* Effect.tryPromise(() => init({ ...empty, bare: true })).pipe(1308 Effect.orDie1309 );13101311 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 });13191320 /**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 );13301331 if (Option.exists(branch, Option.isNone)) {1332 return yield* new ImportFailed({1333 reason: `${from.branch} is no branch name`,1334 });1335 }13361337 const named = Option.flatten(branch);13381339 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 );13531354 const refs = yield* host.refs(repo).pipe(Effect.orDie);13551356 const imported = RefName.make(1357 `refs/heads/${Option.getOrElse(named, () => "main")}`1358 );13591360 const tip = Option.fromNullishOr(1361 refs.get(mainRef) ?? refs.get(imported)1362 );13631364 if (Option.isNone(tip)) {1365 return yield* new ImportFailed({1366 reason: `${from.url} has no commits`,1367 });1368 }13691370 if (!refs.has(mainRef)) {1371 yield* mainAt(tip.value);1372 }13731374 return LandedSha.make(tip.value);1375 });13761377 // ------------------------------------------------------------ answers13781379 /** 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;13831384 const ask = Option.flatMap(request.ask, (id) =>1385 Option.fromUndefinedOr(h.asks.get(id))1386 );13871388 const known = Option.all({ ask, policy: h.policy });13891390 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 );13981399 const askLane = Option.flatMap(known, ({ ask: asked, policy }) =>1400 Option.map(askLaneOf(policy, asked), ({ lane }): LaneName => lane)1401 );14021403 const judgedRun = Option.map(Option.fromUndefinedOr(verdict), (each) => ({1404 message: messageOf(request, ask, each),1405 verdict: each,1406 }));14071408 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 };14221423 /** 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;14371438 // `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 };14621463 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 });14841485 /** 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 });15091510 /**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;15271528 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 });15401541 if (Option.isSome(request.ask)) {1542 const id = request.ask.value;1543 const ask = askNow(h, writes, id);15441545 if (Option.isSome(ask)) {1546 writes.asks.set(id, { ...ask.value, state: "closed" });1547 }15481549 writes.events.push(askClosed(id, sha, now));15501551 yield* answerClaim(1552 h,1553 writes,1554 id,1555 { answerer: request.answerer, sha },1556 now1557 );1558 }15591560 const row = Option.orElse(1561 Option.fromUndefinedOr(writes.project.get("row")),1562 () => h.project1563 );15641565 if (Option.isSome(row)) {1566 writes.project.set(1567 "row",1568 yield* withPolicyAt({ ...row.value, landed: sha }, sha, now)1569 );1570 }1571 });15721573 /** 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] };15881589 return LandingEffect.$match(effect, {1590 Emit: ({ event }) =>1591 Effect.sync(() => {1592 writes.events.push(withVerdict(event, verdict));15931594 return settled;1595 }),1596 Land: () =>1597 Effect.gen(function* () {1598 const asked = askToLand(settled.queue, requestId);15991600 yield* startOther(writes, asked.admitted, requestId, now);16011602 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);16201621 return handed;1622 }),1623 RunChecks: () => Effect.succeed(handed),1624 });1625 };16261627 /**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 });16431644 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 }16531654 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 };16681669 /** 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;16771678 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 };16971698 /** 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 ?? [];17101711 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 }17191720 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 };17301731 /** 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);17371738 if (Option.isNone(found)) {1739 return yield* Effect.die(`no answer request ${requestId}`);1740 }17411742 const { record, row } = found.value;1743 const before = record.landing;1744 const { effects, state } = landingTransition(before, command, now);1745 const { request } = state;17461747 const ask = Option.flatMap(request.ask, (id) =>1748 askNow(h, writes, id)1749 );17501751 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 });17611762 const refusedNow =1763 LandingState.guards.Refused(state) &&1764 !LandingState.guards.Refused(before);17651766 if (Option.isSome(request.ask) && (fresh || refusedNow)) {1767 writes.events.push(1768 judged(request.ask.value, request.head, outcomeOf(state), now)1769 );1770 }17711772 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 );17821783 const queue = yield* leaveIfDone(writes, settled.queue, {1784 now,1785 requestId,1786 state,1787 });17881789 if (queue !== h.queue) {1790 writes.queue.set("queue", queue);1791 }17921793 yield* keepBooks({1794 ask,1795 before,1796 command,1797 now,1798 report,1799 verdict,1800 writes,1801 });18021803 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 }18161817 return {1818 effects: settled.steps.filter(runnable),1819 outcome: outcomeOf(state),1820 };1821 });18221823 // ------------------------------------------------------------ writes18241825 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 }18371838 const remote = `${yield* GatewayUrl}/${name}.git`;18391840 const made: ProjectRow = {1841 createdAt: now,1842 initializer: caller.handle,1843 project: name,1844 state: "awaitingFirstPush",1845 };18461847 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));18521853 writes.project.set("row", made);18541855 return { project: name, remote };1856 }18571858 const landed = yield* adopt(input.import);18591860 writes.project.set(1861 "row",1862 yield* withPolicyAt({ ...made, landed, state: "live" }, landed, now)1863 );18641865 return { landed, project: name, remote };1866 });18671868 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);18741875 if (1876 row === undefined ||1877 !sameHandle(row.initializer, caller.handle)1878 ) {1879 return yield* refused;1880 }18811882 const landed = LandedSha.make(head);18831884 if (row.state === "live") {1885 return row.landed === landed ? { landed } : yield* refused;1886 }18871888 writes.project.set(1889 "row",1890 yield* withPolicyAt({ ...row, landed, state: "live" }, landed, now)1891 );18921893 return { landed };1894 });18951896 /** 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);19071908 if (Option.isNone(evaluated)) {1909 return yield* new VerifierBlocked({});1910 }19111912 const policy = evaluated.value;1913 const stated = policy.asks.find((ask) => ask.id === id);19141915 if (stated === undefined) {1916 return yield* new IncompleteBrief({ missing: ["want"] });1917 }19181919 const kind = policy.kinds.find((each) => each.name === stated.kind);19201921 const missing =1922 kind === undefined1923 ? ["kind"]1924 : kind.requires.filter((each) => !holds(stated, each));19251926 if (Array.isReadonlyArrayNonEmpty(missing)) {1927 return yield* new IncompleteBrief({ missing });1928 }19291930 return { policy, stated };1931 });19321933 /** 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 );19661967 /** 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);19711972 if (Option.isNone(lane)) {1973 return yield* new NotRedFirst({});1974 }19751976 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 };19841985 const first = yield* runner.run(job);1986 const second = yield* runner.run(job);19871988 return yield* Effect.fromResult(1989 redFirstOfRuns([first, second], lane.value.lane)1990 );1991 });19921993 /** 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}`);20022003 const credits: readonly Credit[] = [2004 { handle: input.caller.handle, role: "Asked-by" },2005 ];20062007 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 );20302031 return Effect.map(landing, ({ sha }) => ({ credits, requestId, sha }));2032 };20332034 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);20452046 if (Option.isNone(live) || Option.isNone(h.policy)) {2047 return yield* new VerifierBlocked({});2048 }20492050 if (!isDecider(h.policy.value, caller.handle)) {2051 return yield* new NotDecider({});2052 }20532054 const unplain = input.files.flatMap(({ path }) =>2055 isPlainPath(path) ? [] : [path]2056 );20572058 if (Array.isReadonlyArrayNonEmpty(unplain)) {2059 return yield* new TouchedJudge({ paths: unplain });2060 }20612062 const { landed: main, row } = live.value;2063 const { files } = input;2064 const composed = yield* lander.compose({ files, main, repo });20652066 const { policy, stated } = yield* statedAsk(2067 row,2068 composed.commit,2069 input.ask,2070 now2071 );20722073 const ask: Ask = {2074 ...stated,2075 askedBy: caller.handle,2076 openedAt: now,2077 project: name,2078 state: "open",2079 };20802081 const touched = yield* touchedJudge({2082 ask,2083 caller,2084 files,2085 head: composed.commit,2086 main,2087 policy,2088 });20892090 if (Option.isSome(touched)) {2091 return yield* touched.value;2092 }20932094 const weak = weakness(ask, files);20952096 if (Option.isSome(weak)) {2097 return yield* new WeakCheck({ weakness: weak.value });2098 }20992100 yield* redTwice(policy, ask, composed.commit);21012102 const landed = yield* landAsk({2103 ask,2104 caller,2105 files,2106 main,2107 tree: composed.tree,2108 });21092110 const opened: Ask = { ...ask, openedIn: landed.sha };21112112 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 );21282129 return { ask: opened, landed: landed.sha };2130 });21312132 /** 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);21422143 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);21502151 const landingsInProject = h.landings.filter(({ author }) =>2152 sameHandle(author, handle)2153 ).length;21542155 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 );21672168 return {2169 denounced: who === "denounced",2170 race: kind?.race ?? 1,2171 vouched: admitted,2172 };2173 };21742175 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);21812182 if (2183 Option.isNone(ask) ||2184 Option.isNone(h.policy) ||2185 Option.isNone(live)2186 ) {2187 return yield* new UnknownAsk({ ask: id });2188 }21892190 const policy = h.policy.value;21912192 if (ask.value.state === "closed") {2193 return yield* new AskFull({ ask: id });2194 }21952196 const trust = trustOf(h, policy, ask.value, { caller, now });21972198 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 });22172218 const from = Option.match(ownClaim(h, id, caller.handle), {2219 onNone: () => ClaimState.cases.Open.make({ ask: id }),2220 onSome: ({ state }) => state,2221 });22222223 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 );22312232 if (step.effects.length > 0) {2233 yield* applyClaim(h, writes, id, step, now);2234 }22352236 const view = yield* viewOf(h.policy, ask, step.state);22372238 return yield* Option.match(view, {2239 onNone: () => Effect.die("a granted claim has no view"),2240 onSome: (claim) => Effect.succeed({ claim }),2241 });2242 });22432244 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);22492250 if (Option.isNone(own)) {2251 return yield* NotClaimed.of(id);2252 }22532254 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 );22712272 if (step.effects.length > 0) {2273 yield* applyClaim(h, writes, id, step, now);2274 }22752276 return { released: step.effects.length > 0 };2277 });22782279 /** 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;22902291 const own = Option.filter(2292 input.claimed,2293 ({ row }) =>2294 Principal.guards.Person(pusher) &&2295 sameHandle(pusher.handle, row.claimant)2296 );22972298 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 };23182319 const pushBody =2320 (input: PushReport) => (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2321 Effect.gen(function* () {2322 const live = liveRow(h);23232324 if (Option.isNone(live) || Option.isNone(h.policy)) {2325 return [];2326 }23272328 const target = targetOf(input.repo, name);23292330 const fork = PushTarget.$is("ClaimFork")(target)2331 ? Option.some(target)2332 : Option.none();23332334 const ask = Option.flatMap(fork, (on) => askNow(h, writes, on.ask));23352336 const claimed = Option.flatMap(fork, (on) =>2337 ownClaim(h, on.ask, on.claimant)2338 );23392340 const view = yield* Option.match(claimed, {2341 onNone: () => Effect.succeedNone,2342 onSome: ({ state }) => viewOf(h.policy, ask, state),2343 });23442345 const base = Option.getOrElse(2346 Option.map(2347 Option.flatMap(claimed, ({ state }) => claimOf(state)),2348 (claim) => claim.base2349 ),2350 () => live.value.landed2351 );23522353 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 );23772378 yield* keepAlive(h, writes, { claimed, push: input }, now);23792380 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 });23882389 return refusals;2390 });23912392 /** 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 );24162417 /** 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 );24292430 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 };24382439 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));24502451 return receipt;2452 });24532454 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);24672468 if (Option.isSome(given)) {2469 return given.value;2470 }24712472 const refused = NotClaimed.of(input.ask);2473 const ask = askNow(h, writes, input.ask);2474 const live = liveRow(h);24752476 if (2477 Option.isNone(ask) ||2478 Option.isNone(live) ||2479 Option.isNone(h.policy)2480 ) {2481 return yield* refused;2482 }24832484 const own = ownClaim(h, input.ask, caller.handle);24852486 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 );24932494 const view = yield* Option.match(own, {2495 onNone: () => Effect.succeedNone,2496 onSome: ({ state }) => viewOf(h.policy, ask, state),2497 });24982499 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 );25262527 const gate = yield* runGate(pushStages, facts);25282529 if (Option.isSome(gate)) {2530 return yield* submitRefusal(2531 Array.headNonEmpty(gate.value),2532 input.ask2533 );2534 }25352536 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 });25522553 /** 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 );25752576 // ------------------------------------------------------------ reads25772578 const statusOf = (caller: Person) =>2579 Effect.gen(function* () {2580 const h = yield* hydrate;25812582 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 );25872588 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 );26012602 return { answers, claims: Array.getSomes(claims) };2603 });26042605 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 }26132614 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 );26252626 const verdict = Option.flatMap(latest, ({ record }) =>2627 Option.map(Option.fromUndefinedOr(record.verdict), (made) => ({2628 ...made,2629 outcome: outcomeOf(record.landing),2630 }))2631 );26322633 return Effect.succeed(field("verdict", verdict));2634 });26352636 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();26432644 yield* tickAll(h, writes, now);26452646 return [...(yield* commit(h, writes, now)), ...h.outbox];2647 })2648 );26492650 yield* settle(queue, rows);2651 });26522653 // ------------------------------------------------------------ the api26542655 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 };27542755 return api;2756 });
added:packages/project/src/projection.ts+36 added
added:packages/project/src/projects.ts+27 added
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 */9import type { RequestId } from "@repo/protocol/ids";10import { Effect, Option, Schema } from "effect";1112import { enqueue, LandingQueue, next as admitNext, settle } from "./landing.ts";1314/** No request waiting, none landing. */15export const emptyQueue: LandingQueue = { active: Option.none(), order: [] };1617const decodeQueue = Schema.decodeUnknownEffect(LandingQueue);1819const encodeQueue = Schema.encodeEffect(LandingQueue);2021/** The queue as the store held it: `null` until a commit first writes one. */22export const queueOf = (stored: Schema.Json): Effect.Effect<LandingQueue> =>23 stored === null24 ? Effect.succeed(emptyQueue)25 : Effect.orDie(decodeQueue(stored));2627/** The queue as the store keeps it. */28export const storedQueue = (queue: LandingQueue): Effect.Effect<Schema.Json> =>29 Effect.orDie(encodeQueue(queue));3031/** Whether `id` holds the landing slot. */32export const holdsSlot = (queue: LandingQueue, id: RequestId): boolean =>33 Option.contains(queue.active, id);3435/** A move of the queue, and the request it admitted to the slot, if any. */36export interface Moved {37 readonly admitted: Option.Option<RequestId>;38 readonly queue: LandingQueue;39}4041/**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 */45export const askToLand = (queue: LandingQueue, id: RequestId): Moved => {46 const { admit, queue: moved } = admitNext(enqueue(queue, id));4748 return { admitted: admit, queue: moved };49};5051/** `id` leaves the line or the slot, and the next in line is admitted if the slot is free. */52export const leave = (queue: LandingQueue, id: RequestId): Moved => {53 const { admit, queue: moved } = admitNext(settle(queue, id));5455 return { admitted: admit, queue: moved };56};
added:packages/project/test/project.test.ts+1099 added
1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";5import { Verdict } from "@repo/protocol/domain/answer";6import type { Ask } from "@repo/protocol/domain/ask";7import { CheckSpec } from "@repo/protocol/domain/check";8import { ClaimView } from "@repo/protocol/domain/claim";9import { Outcome } from "@repo/protocol/domain/outcome";10import {11 AskId,12 LandedSha,13 LaneName,14 ProjectName,15 RepoName,16 RepoPath,17 RequestId,18} from "@repo/protocol/ids";19import type { CommitSha } from "@repo/protocol/ids";20import { Anonymous, Person } from "@repo/protocol/principal";21import {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";33import { advanceTo, at as instant } from "@repo/testkit/clock";34import type { Files } from "@repo/testkit/git-client";35import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";36import { Array, DateTime, Effect, Exit, Layer, Option, Schema } from "effect";3738import { ScheduledAlarm } from "../src/alarms/memory.ts";39import { ProjectStore } from "../src/project-store.ts";40import type { ProjectApi } from "../src/project.ts";41import { projectService } from "../src/project.ts";42import { ProjectedRows } from "../src/projection/memory.ts";43import { Projects } from "../src/projects.ts";44import { ProjectsMemory } from "../src/projects/memory.ts";45import {46 CheckScript,47 cleanMergeAt,48 composedAt,49 Evaluated,50 mergedAt,51 Pusher,52 worldOf,53} from "./world.ts";54import type { StoreKind } from "./world.ts";5556const people = ["bob", "carol", "dave", "eve", "frank"];5758const 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);6768const { project } = scenario;6970const repo = RepoName.make(project);7172const mainRef = RefName.make("refs/heads/main");7374const person = (name: string) =>75 Person.make({ handle: scenario.people.get(name) ?? scenario.initializer });7677const alice = person("alice");7879const bob = person("bob");8081const carol = person("carol");8283const dave = person("dave");8485const eve = person("eve");8687const frank = person("frank");8889const anyone = Anonymous.make({});9091const remoteOf = (name: string) => `https://${Brand.domain}/${name}.git`;9293const forkOf = (ask: string, who: Person) =>94 RepoName.make(`${project}--${ask}--${who.handle}`);9596const userOf = (handle: string) =>97 `${handle} <${handle}@users.${Brand.domain}>`;9899const askOf = (id: string): Ask =>100 Option.getOrThrow(101 Array.findFirst(scenario.policy.asks, (ask) => ask.id === id)102 );103104const redThenGreen = LaneName.make("redThenGreen");105106const lanes = [redThenGreen, LaneName.make("lint"), LaneName.make("types")];107108const noon = instant("2026-10-07T12:00:00Z");109110const hoursAfter = (from: DateTime.Utc, count: number) =>111 DateTime.add(from, { hours: count });112113/** The project as alice first pushes it: a library of four small packages. */114const 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];124125const fixedParse = "export const parse = (s) => ({ year: 2026 });\n";126127/** An ask's own files: its file in the config folder, and its check. */128const askFiles = (id: string) => {129 const { check, file, territory } = askOf(id);130 const subject = territory.module === "." ? "tidy" : territory.module;131132 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};150151/** The files main holds after `ids`' asks opened on it. */152const 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];158159/** `files` with `path` holding `content`, added or replaced. */160const changed = (files: Files, path: string, content: string): Files => [161 ...files.filter(([each]) => each !== path),162 [path, content],163];164165/** Where canonical `main` stands now. */166const mainTip = Effect.gen(function* () {167 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);168169 return LandedSha.make(170 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))171 );172});173174const 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);179180 return { author, committer, parents, trailers: parseTrailers(message) };181 });182183/** Every lane on `on` scripted to come out `result` each time. */184const 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 );193194/** Opens an ask whose check the Checker fails twice the same way on the composed tree. */195const openRed = (api: ProjectApi, id: string) =>196 Effect.gen(function* () {197 const files = askFiles(id);198 const composed = yield* composedAt(repo, yield* mainTip, files);199200 yield* CheckScript.use((checker) =>201 checker.script(composed, redThenGreen, ["failed", "failed"])202 );203204 return yield* api.openAsk(alice, { ask: AskId.make(id), files });205 });206207/** What each event is, in the order the project numbered them. */208const eventTags = (api: ProjectApi) =>209 Effect.map(api.events(0, 1000), (events) =>210 events.map(({ event }) => event._tag)211 );212213const scheduled = ScheduledAlarm.use(({ at }) => at);214215const states = (api: ProjectApi, who: Person) =>216 Effect.map(api.status(who), ({ claims }) => claims.map(({ state }) => state));217218const outcomes = (api: ProjectApi, who: Person) =>219 Effect.map(api.status(who), ({ answers }) =>220 answers.map(({ outcome }) => outcome)221 );222223const parseIso = AskId.make("parse-iso");224225/** Steps 1 and 2: the project made, and its first ask opened. */226const opening = (api: ProjectApi) =>227 Effect.gen(function* () {228 const made = yield* Effect.exit(api.initProject(alice, {}));229230 const first = yield* Pusher.use((pusher) =>231 pusher.push(repo, Option.none(), start, "Start")232 );233234 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");238239 yield* scriptAll(240 yield* composedAt(repo, opened.landed, greenFiles),241 "passed"242 );243244 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);247248 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 });262263/** Steps 3 and 4: bob claims, then pushes out of his territory. */264const 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);272273 const carolFork = yield* Effect.exit(host.refs(forkOf("parse-iso", carol)));274275 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 );288289 const wide = yield* Pusher.use((pusher) =>290 pusher.push(bobFork, Option.some(opened), wideFiles)291 );292293 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 });301302 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);310311 return {312 alarmAfterClaim,313 carolFork,314 carolRefused,315 claim,316 forkMain: forkRefs.get(mainRef),317 wide,318 wideRefusals,319 wideSubmitted,320 };321 });322323/** Steps 5 and 6: bob's fix is checked green and lands, and a replay changes nothing. */324const landing = (api: ProjectApi, opened: LandedSha, wide: CommitSha) =>325 Effect.gen(function* () {326 const bobFork = forkOf("parse-iso", bob);327328 const fixedFiles = changed(329 withAskFiles(start, "parse-iso"),330 "packages/parser/src/parse.ts",331 fixedParse332 );333334 const fix = yield* Pusher.use((pusher) =>335 pusher.push(bobFork, Option.some(wide), fixedFiles)336 );337338 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 });346347 yield* scriptAll(348 yield* mergedAt({349 base: opened,350 fork: bobFork,351 head: fix,352 main: opened,353 repo,354 }),355 "passed"356 );357358 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 });363364 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 });373374 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 });395396/** Step 7: dave claims and never pushes; warned at 2 h, lapsed at 24 h. */397const lapsing = (api: ProjectApi, files: Files) =>398 Effect.gen(function* () {399 const formatDate = AskId.make("format-date");400401 yield* openRed(api, "format-date");402 yield* api.claim(dave, formatDate);403404 const alarmAfterClaim = yield* scheduled;405406 yield* advanceTo("2026-10-07T14:00:00Z");407 yield* api.onAlarm();408409 const warned = {410 alarm: yield* scheduled,411 last: (yield* eventTags(api)).at(-1),412 states: yield* states(api, dave),413 };414415 yield* advanceTo("2026-10-08T12:00:00Z");416 yield* api.onAlarm();417418 const lapsed = {419 last: (yield* eventTags(api)).at(-1),420 states: yield* states(api, dave),421 };422423 const base = yield* mainTip;424425 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 );436437 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);445446 return { alarmAfterClaim, lapsed, lateRefused, warned };447 });448449/** Who answers in a race, with which ask and which change. */450interface Racer {451 readonly ask: string;452 readonly change: readonly [path: string, content: string];453 readonly who: Person;454}455456/**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 */461const 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);469470 const base = yield* mainTip;471 const onBase = withAskFiles(files, "format-date", first.ask, second.ask);472473 const answer = (racer: Racer) =>474 Effect.gen(function* () {475 const fork = forkOf(racer.ask, racer.who);476477 yield* api.claim(racer.who, AskId.make(racer.ask));478479 const head = yield* Pusher.use((pusher) =>480 pusher.push(fork, Option.some(base), changed(onBase, ...racer.change))481 );482483 return { fork, head };484 });485486 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 });493494 const one = yield* answer(first);495 const other = yield* answer(second);496497 yield* submit(first, one.head);498499 const waiting = yield* outcomes(api, first.who);500501 yield* scriptAll(502 yield* mergedAt({ ...other, base, main: base, repo }),503 "passed"504 );505 yield* submit(second, other.head);506507 const between = yield* mainTip;508509 // 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 );514515 const remerged = yield* cleanMergeAt({ ...one, base, main: between, repo });516517 if (Option.isSome(remerged)) {518 yield* scriptAll(remerged.value, "passed");519 }520521 yield* advanceTo(DateTime.formatIso(Option.getOrThrow(yield* scheduled)));522 yield* api.onAlarm();523524 const tip = yield* mainTip;525526 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 });536537/** Steps 1 to 7, once, recording what each step saw. */538const core = Effect.gen(function* () {539 yield* advanceTo("2026-10-07T12:00:00Z");540541 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);546547 return { answered, api, claimed, lapsed, opened };548});549550/** The whole core loop, step 8's race included. */551const story = Effect.gen(function* () {552 const { api, ...seen } = yield* core;553554 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 ]);572573 return { ...seen, raced };574});575576/** Step 8 with a re-merge that conflicts: the second answer touched the same line. */577const conflicting = Effect.gen(function* () {578 const { api, answered } = yield* core;579580 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});599600describe.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)));604605 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 );616617 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;622623 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 );663664 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 );673674 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);679680 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 );705706 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 });713714 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 );723724 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 );756757 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 );803804 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 );820821 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 );829830 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 );851852 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 );866867 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);890891/** The project up to bob's claim, in a world whose first fork and first projection fail. */892const settling = Effect.gen(function* () {893 yield* advanceTo("2026-10-07T12:00:00Z");894895 const api = yield* projectService(project);896897 yield* api.initProject(alice, {});898899 const first = yield* Pusher.use((pusher) =>900 pusher.push(repo, Option.none(), start, "Start")901 );902903 yield* api.recordFirstPush(alice, first);904 yield* openRed(api, "parse-iso");905 yield* api.claim(bob, parseIso);906907 const fork = forkOf("parse-iso", bob);908 const host = yield* RepoHost;909910 const outboxOf = ProjectStore.use((store) => store.load()).pipe(911 Effect.map(({ outbox }) => outbox.map(({ kind }) => kind).toSorted())912 );913914 const before = {915 alarm: yield* scheduled,916 fork: Exit.isSuccess(yield* Effect.exit(host.refs(fork))),917 outbox: yield* outboxOf,918 };919920 yield* advanceTo(DateTime.formatIso(Option.getOrThrow(before.alarm)));921 yield* api.onAlarm();922923 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});934935/** Two projects made through `ProjectsMemory`, each over its own store. */936const routing = Effect.gen(function* () {937 yield* advanceTo("2026-10-07T12:00:00Z");938939 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);944945 yield* made.initProject(alice, {});946 yield* projects.create(other);947948 const found = yield* projects.get(project);949950 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});959960/** A project adopted from a public repo: its tip is the first landed SHA. */961const importing = Effect.gen(function* () {962 yield* advanceTo("2026-10-07T12:00:00Z");963964 const host = yield* RepoHost;965 const upstream = RepoName.make("upstream");966967 yield* host.create(upstream).pipe(Effect.orDie);968969 const tip = yield* Pusher.use((pusher) =>970 pusher.push(upstream, Option.none(), start, "Start")971 );972973 const api = yield* projectService(project);974975 // 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);979980 const made = yield* api.initProject(alice, {981 import: { url: "https://example.com/upstream.git" },982 });983984 return {985 evaluated: yield* Evaluated.use(({ shas }) => shas),986 made,987 main: yield* mainTip,988 refused,989 tip,990 };991});992993/** One push event reported twice: its liveness and its `Pushed` event happen once. */994const replaying = Effect.gen(function* () {995 yield* advanceTo("2026-10-07T12:00:00Z");996997 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);10011002 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 });10101011 return {1012 again,1013 events: [before, yield* eventTags(api)],1014 first: claimed.wideRefusals,1015 };1016});10171018describe("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 );10401041 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});10511052describe("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 );10771078 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
1import { describe, expect, it } from "@effect/vitest";23import manifest from "../package.json" with { type: "json" };45// A skeleton's one test, so vitest finds a file; real tests replace it.6describe("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 */13import { SqliteClient } from "@effect/sql-sqlite-node";14import { ForkInProgress, RefName, RepoHost } from "@repo/artifacts/repo-host";15import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";16import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";17import { CheckAt } from "@repo/checks/check-runner";18import { CheckRunnerMemory, scriptKey } from "@repo/checks/check-runner/memory";19import type { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";20import type { Policy } from "@repo/protocol/domain/policy";21import type {22 CommitSha,23 LandedSha,24 LaneName,25 RepoName,26 RepoPath,27} from "@repo/protocol/ids";28import { Finishers } from "@repo/rules/finish";29import { RulesEvaluator } from "@repo/rules/rules-evaluator";30import { gitClient } from "@repo/testkit/git-client";31import type { Files } from "@repo/testkit/git-client";32import type { Scenario } from "@repo/testkit/scenarios";33import { Context, Effect, Layer, Option, Ref } from "effect";34import type { Array } from "effect";3536import { AlarmsMemory } from "../src/alarms/memory.ts";37import { AnswerRunsInline } from "../src/answer-runs/inline.ts";38import { Lander } from "../src/lander.ts";39import { LanderIsogit } from "../src/lander/isogit.ts";40import type { ProjectStore } from "../src/project-store.ts";41import { ProjectStoreMemory } from "../src/project-store/memory.ts";42import { ProjectStoreSqlite } from "../src/project-store/sqlite.ts";43import { FinishersFromChecks } from "../src/project.ts";44import { Projection, ProjectionFailed } from "../src/projection.ts";45import { ProjectionMemory } from "../src/projection/memory.ts";4647const mainRef = RefName.make("refs/heads/main");4849/** Where the project's store keeps its rows. */50export type StoreKind = "memory" | "sqlite";5152/**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 */56export 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") {}6667/** Every landed commit the rules evaluator was asked about, in order. */68export class Evaluated extends Context.Service<69 Evaluated,70 { readonly shas: Effect.Effect<readonly LandedSha[]> }71>()("test/Evaluated") {}7273/** Commits made the way an answerer's git would make them, pushed to a repo's `main`. */74export 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") {}8990/** The store's layer of one kind, fresh each time it is built. */91const 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 );99100/**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 */105const rulesOf = (scenario: Scenario) =>106 Layer.effectContext(107 Effect.gen(function* () {108 const finishers = yield* Finishers;109 const seen = yield* Ref.make<readonly LandedSha[]>([]);110111 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]);116117 const { policy } = scenario;118119 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 });127128 return Context.make(RulesEvaluator, evaluator).pipe(129 Context.add(Evaluated, { shas: Ref.get(seen) })130 );131 })132 );133134const 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[]>();138139 const runner = yield* Layer.build(CheckRunnerMemory.layer(script));140141 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);159160const pusher = Layer.effect(161 Pusher,162 Effect.gen(function* () {163 const host = yield* RepoHost;164 const client = yield* gitClient(memoryFs());165166 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 );174175 yield* host176 .push(repo, client.source, [177 { from: parent, ref: mainRef, to: sha },178 ])179 .pipe(Effect.orDie);180181 return sha;182 }),183 });184 })185);186187/** What fails in a world before it works. */188export interface Faults {189 /** The first fork and the first projection fail; every later one works. */190 readonly failOnce?: boolean;191}192193/**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 */197const hostOf = (base: Layer.Layer<RepoHost>) =>198 Layer.effect(199 RepoHost,200 Effect.gen(function* () {201 const host = yield* RepoHost;202203 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));213214/** `RepoHostMemory`, whose first fork is still in progress. */215const flakyHost = Layer.effect(216 RepoHost,217 Effect.gen(function* () {218 const host = yield* RepoHost;219 const failed = yield* Ref.make(false);220221 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));232233/** `ProjectionMemory`, whose first apply is refused. */234const 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);239240 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);254255/** Every service the scenario test reads besides the project's ports. */256const fixtures = (scenario: Scenario) =>257 Layer.mergeAll(scriptOf, rulesOf(scenario), pusher).pipe(258 Layer.provideMerge(FinishersFromChecks)259 );260261/**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 */266export 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 );283284/** The commit an ask's files compose onto main as, where its check runs red first. */285export 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);297298/** The tree an answer merges onto main as, where its checks run. */299export 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);310311/** The tree an answer merges onto main as, or none when the merge conflicts. */312export 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 );