Land a checked answer on main as a platform commit that credits its people, or refuse it as stale
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Adds the Lander port to packages/project with a scripted /memory adapter and an /isogit adapter over RepoHost (212). - Port (src/lander.ts): merge, land, compose and bundleRules, with the three additions the issue marks: compose (for running an ask's check red first), land's rebuild (Merge | Compose | Existing), since merge and land run in separate stateless calls, and land's verdict, the note written after main moves. landedRef and composeRef come from Brand, so no adapter spells a ref. - /isogit merges three ways at the tree level through RepoHost with the answer's base as the merge base, descending only into folders both sides changed. A file both sides changed merges line by line through isomorphic-git's merge over a scratch history of that one file, so the fallback refuses no more than git would for edits to different lines. Changes are the answer's own (treeDiff of base and head in the fork). - land pushes main with a non-force compare-and-swap from a scratch git directory that holds only new objects; a moved main is StaleBase and main is left alone. Then the mirror ref and the verdict note, each in its own push; a failure there comes back in Landed.pending and never fails the landing. Author is authorLine(answerer), committer the platform, time from Clock. - Idempotent by Request-Id: a second land finds its own commit (a child of job.main carrying the job's Request-Id) and writes only missing bookkeeping, and never moves the mirror off a later landing. A message without its Request-Id trailer is a defect. - compose pushes to refs/<brand>/compose/<tree> and returns the same commit when composed again onto the same main. bundleRules returns the config folder's sources as committed (no bundling here; 306 bundles). - Outside the territory, one line: git/notes.ts copies the bytes before `new Blob`, since @repo/project sees Node's Blob types, which refused the view once project imported notes. Recorded in 212's Comments. - Tests: lander-isogit.test.ts (14) over RepoHostMemory, a claim fork and testkit's git client; lander-memory.test.ts (3). The isogit check failed by assertion against a stub first. - ASSUMPTION: an answer's base is on canonical's history, so objects equal to the base are already there. ASSUMPTION: bundleRules reports sdkVersion 0.0.0, since project may not import @repo/sdk (299 decides).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+2140 added−1 removed
- tests:+869 added−0 removed
- other:+1271 added−1 removed
Provenance
- Commit
204f254- Tree
12c3301- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
7b4ffd5
6 files changed+2140 added−1 removed
modified:packages/git/src/notes.ts+5 added-1 removed
62 unmodified lines63 /** git's zlib stream, as a loose object holds it. */64 const deflate = (bytes: Uint8Array) =>65 Effect.promise(() =>66 new Response(67+ // A copy on its own `ArrayBuffer`: Node's `Blob` types refuse a view68+ // that may sit on a `SharedArrayBuffer`, as `@repo/project` sees them.69+ new Blob([Uint8Array.from(bytes)])70+ .stream()67- new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"))71+ .pipeThrough(new CompressionStream("deflate"))72 ).arrayBuffer()73 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));74 75 const sortKey = (entry: TreeEntry) =>184 unmodified linesadded:packages/project/src/lander/isogit.ts+991 added
1+/**2+ * The `Lander` over isomorphic-git in a Worker (spec D6): the production3+ * fallback until the container Lander in `apps/sandbox` passes, and the one4+ * the core-loop tests run on. It runs no project code and installs nothing.5+ *6+ * It is stateless. Each call reads the commits, trees and blobs it needs7+ * through `RepoHost` (never `fetch`), writes the objects it makes into a8+ * scratch git directory in memory, and pushes from there: canonical `main`9+ * with a non-force compare-and-swap, then the mirror ref and the verdict10+ * note, each in its own push, since Artifacts has no atomic multi-ref push11+ * (S1 #6). A scratch directory holds only the objects the repo lacks; the12+ * rest are referenced by id.13+ *14+ * The merge is three-way at the tree level, read through the port: it15+ * descends only into folders both sides changed, and a file both sides16+ * changed is merged line by line by isomorphic-git's `merge` over a scratch17+ * history of that one file.18+ *19+ * `bundleRules` returns the config folder's sources as committed. This20+ * adapter bundles no TypeScript; the container Lander bundles with Bun (W321+ * 306).22+ */23+import {24+ BranchName,25+ ObjectId,26+ RefName,27+ RefOutcome,28+ RepoHost,29+ Revision,30+} from "@repo/artifacts/repo-host";31+import type {32+ PushSource,33+ RefUpdate,34+ RepoNotFound,35+ TreeEntry,36+} from "@repo/artifacts/repo-host";37+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";38+import { Brand } from "@repo/brand";39+import { noteCommit, notesRef } from "@repo/git/notes";40+import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";41+import type { GitIdentity } from "@repo/git/trailers";42+import { treeDiff } from "@repo/git/tree-diff";43+import type { Verdict } from "@repo/protocol/domain/answer";44+import { CommitSha, LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";45+import type { RepoName, RequestId } from "@repo/protocol/ids";46+import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";47+import type { ConfigBundle } from "@repo/rules/rules-evaluator";48+import { Array, Clock, DateTime, Effect, Layer, Option, Order } from "effect";49+import {50+ Errors,51+ init,52+ merge as mergeHistories,53+ readTree as readScratchTree,54+ writeBlob,55+ writeCommit,56+ writeRef,57+ writeTree,58+} from "isomorphic-git";59+60+import { composeRef, Lander, landedRef, Rebuild } from "../lander.ts";61+import type {62+ Bookkeeping,63+ BundleJob,64+ ComposedFile,65+ ComposeJob,66+ LandJob,67+ MergeJob,68+} from "../lander.ts";69+70+const mainRef = RefName.make("refs/heads/main");71+72+const mainBranch = BranchName.make("main");73+74+/**75+ * The SDK version a bundle reports. ASSUMPTION: the platform's own, `0.0.0`76+ * until release. `@repo/project` may not import `@repo/sdk`, which states it,77+ * so 299 decides where this comes from (212's Comments).78+ */79+const sdkVersion = "0.0.0";80+81+// How far back from main's tip a second land looks for the first one's commit.82+const LOOKBACK = 16;83+84+// git's test for a binary file: a NUL among its first bytes.85+const SNIFF = 8000;86+87+const blocked = () => new VerifierBlocked({});88+89+/** A store that lost a repo cannot merge or land: `VerifierBlocked`. */90+const unlessLost = <A, R>(91+ effect: Effect.Effect<A, RepoNotFound, R>92+): Effect.Effect<A, VerifierBlocked, R> => Effect.mapError(effect, blocked);93+94+/** An object the store should hold and does not: `VerifierBlocked` too. */95+const found = <A, R>(96+ read: Effect.Effect<Option.Option<A>, RepoNotFound, R>97+): Effect.Effect<A, VerifierBlocked, R> =>98+ read.pipe(99+ unlessLost,100+ Effect.flatMap(101+ Option.match({102+ onNone: () => Effect.fail(blocked()),103+ onSome: Effect.succeed,104+ })105+ )106+ );107+108+const commitIn = (repo: RepoName, sha: CommitSha) =>109+ found(RepoHost.use((host) => host.readCommit(repo, sha)));110+111+const treeIn = (repo: RepoName, tree: ObjectId) =>112+ found(RepoHost.use((host) => host.readTree(repo, tree)));113+114+const blobIn = (repo: RepoName, blob: ObjectId) =>115+ found(RepoHost.use((host) => host.readBlob(repo, blob)));116+117+const refsIn = (repo: RepoName) =>118+ RepoHost.use((host) => host.refs(repo)).pipe(unlessLost);119+120+/** One ref's compare-and-swap, alone in its push; what it came to. */121+const pushOne = (repo: RepoName, source: PushSource, update: RefUpdate) =>122+ RepoHost.use((host) => host.push(repo, source, [update])).pipe(123+ Effect.map((outcomes) => Option.fromNullishOr(outcomes[0]))124+ );125+126+/** A push whose ref did not move, for a ref where that is not a refusal. */127+const moves = (outcome: Option.Option<RefOutcome>) =>128+ Option.exists(outcome, RefOutcome.$is("Updated"))129+ ? Effect.void130+ : Effect.fail(blocked());131+132+/** Clock time, in the whole seconds a git signature holds. */133+const seconds = Effect.map(Clock.currentTimeMillis, (millis) =>134+ Math.floor(millis / 1000)135+);136+137+const git = <A>(run: () => Promise<A>) =>138+ Effect.tryPromise(run).pipe(Effect.orDie);139+140+/** A git signature at `at` seconds past the epoch, in UTC. */141+const signed = (who: GitIdentity, at: number) => ({142+ email: who.email,143+ name: who.name,144+ timestamp: at,145+ timezoneOffset: 0,146+});147+148+/** A copy of an object must keep its id, or the push would name one it lacks. */149+const kept = (id: ObjectId, made: ObjectId) =>150+ made === id ? Effect.void : Effect.die(`copying ${id} produced ${made}`);151+152+/**153+ * A bare git directory in memory: what a call writes its new objects into154+ * and pushes from. One per call; nothing outlives it.155+ */156+const scratch = Effect.gen(function* () {157+ const source: PushSource = { fs: memoryFs(), gitdir: "/lander.git" };158+159+ yield* git(() => init({ ...source, bare: true, defaultBranch: "main" }));160+161+ const blob = (bytes: Uint8Array) =>162+ Effect.map(163+ git(() => writeBlob({ ...source, blob: bytes })),164+ (oid) => ObjectId.make(oid)165+ );166+167+ const tree = (entries: readonly TreeEntry[]) =>168+ Effect.map(169+ git(() =>170+ writeTree({171+ ...source,172+ tree: entries.map(({ mode, name, sha, type }) => ({173+ mode,174+ oid: sha,175+ path: name,176+ type,177+ })),178+ })179+ ),180+ (oid) => ObjectId.make(oid)181+ );182+183+ const commit = (input: {184+ readonly tree: ObjectId;185+ readonly parents: readonly CommitSha[];186+ readonly author: GitIdentity;187+ readonly message: string;188+ readonly at: number;189+ }) =>190+ Effect.map(191+ git(() =>192+ writeCommit({193+ ...source,194+ commit: {195+ author: signed(input.author, input.at),196+ committer: signed(committerLine, input.at),197+ message: input.message,198+ parent: [...input.parents],199+ tree: input.tree,200+ },201+ })202+ ),203+ (oid) => CommitSha.make(oid)204+ );205+206+ /** A commit of one file holding `bytes` (or of nothing) on `parents`. */207+ const fileCommit = (208+ bytes: Option.Option<Uint8Array>,209+ parents: readonly CommitSha[]210+ ) =>211+ Effect.gen(function* () {212+ const files = yield* Option.match(bytes, {213+ onNone: () => Effect.succeed([]),214+ onSome: (content) =>215+ Effect.map(blob(content), (sha) => [216+ { mode: "100644", name: "file", sha, type: "blob" } as const,217+ ]),218+ });219+220+ return yield* commit({221+ at: 0,222+ author: committerLine,223+ message: "merge\n",224+ parents,225+ tree: yield* tree(files),226+ });227+ });228+229+ /**230+ * One file's three versions merged line by line, by isomorphic-git's231+ * `merge` over a history of that file alone: the merged blob, or `None`232+ * when the changes conflict.233+ */234+ const lines = (235+ base: Option.Option<Uint8Array>,236+ ours: Uint8Array,237+ theirs: Uint8Array238+ ) =>239+ Effect.gen(function* () {240+ const start = yield* fileCommit(base, []);241+242+ const tips = {243+ "refs/merge/ours": yield* fileCommit(Option.some(ours), [start]),244+ "refs/merge/theirs": yield* fileCommit(Option.some(theirs), [start]),245+ };246+247+ yield* Effect.forEach(Object.entries(tips), ([ref, value]) =>248+ git(() => writeRef({ ...source, force: true, ref, value }))249+ );250+251+ const merged = yield* Effect.tryPromise(() =>252+ mergeHistories({253+ ...source,254+ abortOnConflict: true,255+ author: signed(committerLine, 0),256+ committer: signed(committerLine, 0),257+ fastForward: false,258+ message: "merge",259+ noUpdateBranch: true,260+ ours: "refs/merge/ours",261+ theirs: "refs/merge/theirs",262+ })263+ ).pipe(264+ Effect.map(({ tree: root }) => Option.fromNullishOr(root)),265+ Effect.catchIf(266+ ({ cause }) =>267+ cause instanceof Errors.MergeConflictError ||268+ cause instanceof Errors.MergeNotSupportedError,269+ () => Effect.succeedNone270+ ),271+ Effect.orDie272+ );273+274+ if (Option.isNone(merged)) {275+ return Option.none();276+ }277+278+ const { tree: entries } = yield* git(() =>279+ readScratchTree({ ...source, oid: merged.value })280+ );281+282+ return Option.map(Option.fromNullishOr(entries[0]), ({ oid }) =>283+ ObjectId.make(oid)284+ );285+ });286+287+ return { blob, commit, lines, source, tree };288+});289+290+type Scratch = Effect.Success<typeof scratch>;291+292+const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);293+294+const sameEntry = (one: TreeEntry | undefined, other: TreeEntry | undefined) =>295+ one?.sha === other?.sha && one?.mode === other?.mode;296+297+const isFile = (entry: TreeEntry | undefined) =>298+ entry?.mode === "100644" || entry?.mode === "100755";299+300+/** The folder an entry is, if it is one. */301+const folderOf = (entry: TreeEntry | undefined) =>302+ entry?.type === "tree" ? Option.some(entry.sha) : Option.none();303+304+const byName = (entries: readonly TreeEntry[]) =>305+ new Map(entries.map((entry) => [entry.name, entry]));306+307+const entriesAt = (repo: RepoName, tree: Option.Option<ObjectId>) =>308+ Option.match(tree, {309+ onNone: () => Effect.succeed<readonly TreeEntry[]>([]),310+ onSome: (id) => treeIn(repo, id),311+ });312+313+/** Where an answer's sides are read: main from canonical, base and head from the fork. */314+interface Sides {315+ readonly canonical: RepoName;316+ readonly fork: RepoName;317+}318+319+/** A merged folder's entries, or the paths under it that conflict. */320+interface MergedTree {321+ readonly entries: readonly TreeEntry[];322+ readonly conflicts: readonly string[];323+}324+325+const taken = (entry: TreeEntry | undefined): MergedTree => ({326+ conflicts: [],327+ entries: entry === undefined ? [] : [entry],328+});329+330+const conflict = (path: string): MergedTree => ({331+ conflicts: [path],332+ entries: [],333+});334+335+/**336+ * Makes `theirs`, an entry the merge takes from the head, pushable: every337+ * object under it that differs from the base's entry at its path is copied338+ * from the fork into the scratch directory. What equals the base is already339+ * in canonical, since the base is a commit on canonical's history.340+ */341+const adopt = (342+ sides: Sides,343+ into: Scratch,344+ theirs: TreeEntry,345+ base: TreeEntry | undefined346+): Effect.Effect<void, VerifierBlocked, RepoHost> => {347+ if (sameEntry(theirs, base) || theirs.type === "commit") {348+ return Effect.void;349+ }350+351+ if (theirs.type === "blob") {352+ return blobIn(sides.fork, theirs.sha).pipe(353+ Effect.flatMap(into.blob),354+ Effect.flatMap((made) => kept(theirs.sha, made))355+ );356+ }357+358+ return Effect.gen(function* () {359+ const children = yield* treeIn(sides.fork, theirs.sha);360+ const before = byName(yield* entriesAt(sides.fork, folderOf(base)));361+362+ yield* Effect.forEach(children, (child) =>363+ adopt(sides, into, child, before.get(child.name))364+ );365+ yield* kept(theirs.sha, yield* into.tree(children));366+ });367+};368+369+/** A file's mode once both sides changed it, unless they changed it differently. */370+const mergedMode = (371+ base: TreeEntry | undefined,372+ ours: TreeEntry,373+ theirs: TreeEntry374+): Option.Option<TreeEntry["mode"]> => {375+ if (ours.mode === theirs.mode || base?.mode === theirs.mode) {376+ return Option.some(ours.mode);377+ }378+379+ return base?.mode === ours.mode ? Option.some(theirs.mode) : Option.none();380+};381+382+/** A file both sides changed, merged; `None` when the changes conflict. */383+const mergeFile = (384+ sides: Sides,385+ into: Scratch,386+ name: string,387+ {388+ base,389+ ours,390+ theirs,391+ }: Record<"ours" | "theirs", TreeEntry> & {392+ readonly base: TreeEntry | undefined;393+ }394+): Effect.Effect<Option.Option<TreeEntry>, VerifierBlocked, RepoHost> =>395+ Effect.gen(function* () {396+ const mode = mergedMode(base, ours, theirs);397+398+ if (Option.isNone(mode)) {399+ return Option.none();400+ }401+402+ const file = (sha: ObjectId): TreeEntry => ({403+ mode: mode.value,404+ name,405+ sha,406+ type: "blob",407+ });408+409+ if (ours.sha === theirs.sha || base?.sha === theirs.sha) {410+ return Option.some(file(ours.sha));411+ }412+413+ if (base?.sha === ours.sha) {414+ yield* adopt(sides, into, theirs, base);415+416+ return Option.some(file(theirs.sha));417+ }418+419+ // Symlinks and submodules that both sides changed are not text to merge.420+ if (!(isFile(ours) && isFile(theirs))) {421+ return Option.none();422+ }423+424+ const [before, mine, yours] = yield* Effect.all([425+ base !== undefined && isFile(base)426+ ? Effect.asSome(blobIn(sides.fork, base.sha))427+ : Effect.succeedNone,428+ blobIn(sides.canonical, ours.sha),429+ blobIn(sides.fork, theirs.sha),430+ ]);431+432+ if ([...Option.toArray(before), mine, yours].some(isBinary)) {433+ return Option.none();434+ }435+436+ return Option.map(yield* into.lines(before, mine, yours), file);437+ });438+439+/**440+ * Three folders merged by name. An entry only one side changed is taken from441+ * that side; a folder both changed is merged inside; a file both changed is442+ * merged line by line; anything else both changed conflicts.443+ */444+const mergeTrees = (445+ sides: Sides,446+ into: Scratch,447+ prefix: string,448+ trees: Record<"base" | "ours" | "theirs", Option.Option<ObjectId>>449+): Effect.Effect<MergedTree, VerifierBlocked, RepoHost> =>450+ Effect.gen(function* () {451+ const [base, ours, theirs] = yield* Effect.all([452+ Effect.map(entriesAt(sides.fork, trees.base), byName),453+ Effect.map(entriesAt(sides.canonical, trees.ours), byName),454+ Effect.map(entriesAt(sides.fork, trees.theirs), byName),455+ ]);456+457+ const names = Array.sort(458+ new Set([...base.keys(), ...ours.keys(), ...theirs.keys()]),459+ Order.String460+ );461+462+ const merged = yield* Effect.forEach(463+ names,464+ (name): Effect.Effect<MergedTree, VerifierBlocked, RepoHost> => {465+ const b = base.get(name);466+ const o = ours.get(name);467+ const t = theirs.get(name);468+ const path = `${prefix}${name}`;469+470+ if (sameEntry(o, t) || sameEntry(b, t)) {471+ return Effect.succeed(taken(o));472+ }473+474+ if (sameEntry(b, o)) {475+ return t === undefined476+ ? Effect.succeed(taken(t))477+ : Effect.as(adopt(sides, into, t, b), taken(t));478+ }479+480+ if (o?.type === "tree" && t?.type === "tree") {481+ return Effect.gen(function* () {482+ const inner = yield* mergeTrees(sides, into, `${path}/`, {483+ base: folderOf(b),484+ ours: Option.some(o.sha),485+ theirs: Option.some(t.sha),486+ });487+488+ // Both sides emptied it, or something in it conflicts.489+ if (inner.conflicts.length > 0 || inner.entries.length === 0) {490+ return { conflicts: inner.conflicts, entries: [] };491+ }492+493+ const sha = yield* into.tree(inner.entries);494+495+ return taken({ mode: "040000", name, sha, type: "tree" });496+ });497+ }498+499+ if (o?.type === "blob" && t?.type === "blob") {500+ return mergeFile(sides, into, name, {501+ base: b?.type === "blob" ? b : undefined,502+ ours: o,503+ theirs: t,504+ }).pipe(505+ Effect.map(506+ Option.match({507+ onNone: () => conflict(path),508+ onSome: taken,509+ })510+ )511+ );512+ }513+514+ return Effect.succeed(conflict(path));515+ }516+ );517+518+ return {519+ conflicts: merged.flatMap(({ conflicts }) => conflicts),520+ entries: merged.flatMap(({ entries }) => entries),521+ };522+ });523+524+/**525+ * The answer's head merged onto `main`, with the base as the merge base:526+ * the merged root (written into `into`) and the base's and head's roots, or527+ * `StaleBase` with every path that conflicts.528+ */529+const mergeOnto = (into: Scratch, job: MergeJob) =>530+ Effect.gen(function* () {531+ const [base, ours, theirs] = yield* Effect.all([532+ commitIn(job.fork, job.base),533+ commitIn(job.repo, job.main),534+ commitIn(job.fork, job.head),535+ ]);536+537+ const merged = yield* mergeTrees(538+ { canonical: job.repo, fork: job.fork },539+ into,540+ "",541+ {542+ base: Option.some(base.tree),543+ ours: Option.some(ours.tree),544+ theirs: Option.some(theirs.tree),545+ }546+ );547+548+ if (merged.conflicts.length > 0) {549+ return yield* new StaleBase({550+ base: job.base,551+ conflicts: merged.conflicts.map((path) => RepoPath.make(path)),552+ main: job.main,553+ });554+ }555+556+ return {557+ base: TreeSha.make(base.tree),558+ head: TreeSha.make(theirs.tree),559+ tree: TreeSha.make(yield* into.tree(merged.entries)),560+ };561+ });562+563+/** A file to place, by the folders and name its path is made of. */564+interface Placed {565+ readonly segments: readonly string[];566+ readonly content: string;567+}568+569+/** A path's folders and file name; one that cannot name a file is a defect upstream. */570+const placed = ({ content, path }: ComposedFile) => {571+ const segments = path.split("/");572+573+ return segments.every((segment) => !["", ".", "..", ".git"].includes(segment))574+ ? Effect.succeed<Placed>({ content, segments })575+ : Effect.die(`${path} cannot name a file in a repo`);576+};577+578+/**579+ * `files` written into `repo`'s folder `tree` (or a new folder), folder by580+ * folder, keeping every other entry: the new folder's id. A file where a581+ * folder stands, or a folder where a file stands, is a defect upstream.582+ */583+const placeFiles = (584+ repo: RepoName,585+ into: Scratch,586+ prefix: string,587+ tree: Option.Option<ObjectId>,588+ files: readonly Placed[]589+): Effect.Effect<ObjectId, VerifierBlocked, RepoHost> =>590+ Effect.gen(function* () {591+ const entries = byName(yield* entriesAt(repo, tree));592+ const groups = Array.groupBy(files, ({ segments }) => segments[0] ?? "");593+594+ for (const [name, group] of Object.entries(groups)) {595+ const existing = entries.get(name);596+ const path = `${prefix}${name}`;597+ const inside = group.filter(({ segments }) => segments.length > 1);598+ const content = group.findLast(({ segments }) => segments.length === 1);599+600+ if (content === undefined) {601+ if (existing !== undefined && existing.type !== "tree") {602+ return yield* Effect.die(603+ `${path} cannot be both a file and a folder`604+ );605+ }606+607+ const sha = yield* placeFiles(608+ repo,609+ into,610+ `${path}/`,611+ folderOf(existing),612+ inside.map((file) => ({ ...file, segments: file.segments.slice(1) }))613+ );614+615+ entries.set(name, { mode: "040000", name, sha, type: "tree" });616+ } else {617+ if (618+ inside.length > 0 ||619+ (existing !== undefined && !isFile(existing))620+ ) {621+ return yield* Effect.die(622+ `${path} cannot be both a file and a folder`623+ );624+ }625+626+ entries.set(name, {627+ mode: existing?.mode ?? "100644",628+ name,629+ sha: yield* into.blob(new TextEncoder().encode(content.content)),630+ type: "blob",631+ });632+ }633+ }634+635+ return yield* into.tree([...entries.values()]);636+ });637+638+/** `main` with `files` added, written into `into`: the new root. */639+const composeOnto = (640+ into: Scratch,641+ repo: RepoName,642+ main: CommitSha,643+ files: readonly ComposedFile[]644+) =>645+ Effect.gen(function* () {646+ const commit = yield* commitIn(repo, main);647+ const paths = yield* Effect.forEach(files, placed);648+649+ return TreeSha.make(650+ yield* placeFiles(repo, into, "", Option.some(commit.tree), paths)651+ );652+ });653+654+/** The tree a land rebuilds, written into `into` where it is new. */655+const rebuilt = (into: Scratch, job: LandJob) =>656+ Rebuild.$match(job.rebuild, {657+ Compose: ({ files }) => composeOnto(into, job.repo, job.main, files),658+ Existing: ({ commit }) =>659+ Effect.map(commitIn(job.repo, commit), ({ tree }) => TreeSha.make(tree)),660+ Merge: ({ base, fork, head }) =>661+ Effect.map(662+ mergeOnto(into, { base, fork, head, main: job.main, repo: job.repo }),663+ ({ tree }) => tree664+ ),665+ });666+667+const requestIdOf = (message: string) =>668+ parseTrailers(message).find(({ key }) => key.toLowerCase() === "request-id")669+ ?.value;670+671+const carriesRequest = (message: string, requestId: RequestId) =>672+ requestIdOf(message) === requestId673+ ? Effect.void674+ : Effect.die(`a landing's message must carry Request-Id: ${requestId}`);675+676+/**677+ * The commit an earlier land of the same request put on `main`: a child of678+ * the job's `main` carrying its `Request-Id`, on main's first parents.679+ */680+const landedBefore = (job: LandJob) =>681+ Effect.gen(function* () {682+ const history = yield* RepoHost.use((host) =>683+ host.log(job.repo, Revision.Branch({ name: mainBranch }), LOOKBACK)684+ ).pipe(unlessLost);685+686+ const mine = Array.takeWhile(history, ({ sha }) => sha !== job.main).find(687+ ({ message, parents }) =>688+ parents[0] === job.main && requestIdOf(message) === job.requestId689+ );690+691+ return Option.fromNullishOr(mine?.sha);692+ });693+694+/** The mirror ref moved to the landing, while the landing is still main's tip. */695+const mirror = (repo: RepoName, landing: CommitSha) =>696+ Effect.gen(function* () {697+ const refs = yield* refsIn(repo);698+ const current = Option.fromNullishOr(refs.get(landedRef));699+700+ // A later landing moved main on, and its own mirror supersedes this one.701+ if (refs.get(mainRef) !== landing || Option.contains(current, landing)) {702+ return;703+ }704+705+ const empty = yield* scratch;706+707+ yield* moves(708+ yield* pushOne(repo, empty.source, {709+ from: current,710+ ref: landedRef,711+ to: landing,712+ })713+ );714+ });715+716+/** Whether the notes at `tip` already hold a note on `target`. */717+const noted = (718+ repo: RepoName,719+ tip: Option.Option<CommitSha>,720+ target: CommitSha721+) =>722+ Option.match(tip, {723+ onNone: () => Effect.succeed(false),724+ onSome: (sha) =>725+ Effect.gen(function* () {726+ const commit = yield* commitIn(repo, sha);727+ const entries = yield* treeIn(repo, commit.tree);728+729+ return entries.some(({ name }) => name === target);730+ }),731+ });732+733+/** The verdict written as the landing's note, unless it is there already. */734+const note = (repo: RepoName, landing: CommitSha, verdict: Verdict) =>735+ Effect.gen(function* () {736+ const refs = yield* refsIn(repo);737+ const parent = Option.fromNullishOr(refs.get(notesRef));738+739+ if (yield* noted(repo, parent, landing)) {740+ return;741+ }742+743+ const { commit, source } = yield* noteCommit({744+ notesParent: parent,745+ now: yield* DateTime.now,746+ repo,747+ target: landing,748+ verdict,749+ });750+751+ yield* moves(752+ yield* pushOne(repo, source, { from: parent, ref: notesRef, to: commit })753+ );754+ });755+756+/** One piece of bookkeeping: `None` once written, its name when it was not. */757+const attempt = <E>(758+ item: Bookkeeping,759+ write: Effect.Effect<void, E, RepoHost>760+) =>761+ write.pipe(762+ Effect.as(Option.none<Bookkeeping>()),763+ Effect.catchCause((cause) =>764+ Effect.as(765+ Effect.logWarning(`a landing's ${item} was not written`, cause),766+ Option.some(item)767+ )768+ )769+ );770+771+/**772+ * What follows a landing on `main`, in order and each in its own push: the773+ * mirror ref, then the verdict note. Neither fails the landing; what was not774+ * written comes back pending, and landing the same job again writes it.775+ */776+const settle = (job: LandJob, landing: CommitSha) =>777+ Effect.gen(function* () {778+ const mirrored = yield* attempt("mirror", mirror(job.repo, landing));779+780+ const noteWritten = yield* Option.match(job.verdict, {781+ onNone: () => Effect.succeedNone,782+ onSome: (verdict) => attempt("notes", note(job.repo, landing, verdict)),783+ });784+785+ return {786+ pending: Array.getSomes([mirrored, noteWritten]),787+ sha: LandedSha.make(landing),788+ };789+ });790+791+/** The base a stale land names: the answer's own, or the main it was built on. */792+const baseOf = (job: LandJob) =>793+ Rebuild.$match(job.rebuild, {794+ Compose: () => job.main,795+ Existing: () => job.main,796+ Merge: ({ base }) => base,797+ });798+799+/** A land that found `main` at `tip`: the earlier land of the same request, or stale. */800+const moved = (job: LandJob, tip: Option.Option<CommitSha>) =>801+ Effect.gen(function* () {802+ const earlier = yield* landedBefore(job);803+804+ if (Option.isSome(earlier)) {805+ return yield* settle(job, earlier.value);806+ }807+808+ return yield* new StaleBase({809+ base: baseOf(job),810+ conflicts: [],811+ main: Option.getOrElse(tip, () => job.main),812+ });813+ });814+815+const land = (job: LandJob) =>816+ Effect.gen(function* () {817+ yield* carriesRequest(job.message, job.requestId);818+819+ const tip = Option.fromNullishOr((yield* refsIn(job.repo)).get(mainRef));820+821+ if (!Option.contains(tip, job.main)) {822+ return yield* moved(job, tip);823+ }824+825+ const into = yield* scratch;826+ const tree = yield* rebuilt(into, job);827+828+ if (tree !== job.tree) {829+ return yield* blocked();830+ }831+832+ const commit = yield* into.commit({833+ at: yield* seconds,834+ author: authorLine(job.author),835+ message: job.message,836+ parents: [job.main],837+ tree: ObjectId.make(tree),838+ });839+840+ // Never forced: if main moved since `job.main`, this push is refused.841+ const outcome = yield* pushOne(job.repo, into.source, {842+ from: Option.some(job.main),843+ ref: mainRef,844+ to: commit,845+ }).pipe(846+ Effect.catchTags({847+ HostBusy: () => Effect.fail(new RepoBusy({})),848+ RepoNotFound: () => Effect.fail(blocked()),849+ })850+ );851+852+ return Option.exists(outcome, RefOutcome.$is("Updated"))853+ ? yield* settle(job, commit)854+ : yield* moved(855+ job,856+ Option.flatMap(outcome, (stale) =>857+ RefOutcome.$is("Stale")(stale) ? stale.tip : Option.none()858+ )859+ );860+ });861+862+const compose = (job: ComposeJob) =>863+ Effect.gen(function* () {864+ const into = yield* scratch;865+ const tree = yield* composeOnto(into, job.repo, job.main, job.files);866+ const ref = composeRef(tree);867+ const existing = Option.fromNullishOr((yield* refsIn(job.repo)).get(ref));868+869+ // Composed before onto the same main: the commit a Checker already has.870+ if (Option.isSome(existing)) {871+ const before = yield* commitIn(job.repo, existing.value);872+873+ if (874+ before.tree === ObjectId.make(tree) &&875+ before.parents[0] === job.main876+ ) {877+ return { commit: existing.value, tree };878+ }879+ }880+881+ const commit = yield* into.commit({882+ at: yield* seconds,883+ author: committerLine,884+ message: "Compose files onto main for a check\n",885+ parents: [job.main],886+ tree: ObjectId.make(tree),887+ });888+889+ yield* pushOne(job.repo, into.source, {890+ from: existing,891+ ref,892+ to: commit,893+ }).pipe(894+ Effect.catchTags({895+ HostBusy: () => Effect.fail(blocked()),896+ RepoNotFound: () => Effect.fail(blocked()),897+ }),898+ Effect.flatMap(moves)899+ );900+901+ return { commit, tree };902+ });903+904+/** Every file under the folder `tree`, by repo path, as committed. */905+const filesUnder = (906+ repo: RepoName,907+ tree: ObjectId,908+ prefix: string909+): Effect.Effect<910+ readonly (readonly [string, string])[],911+ VerifierBlocked,912+ RepoHost913+> =>914+ Effect.gen(function* () {915+ const entries = yield* treeIn(repo, tree);916+917+ const nested = yield* Effect.forEach(entries, (entry) => {918+ const path = `${prefix}${entry.name}`;919+920+ if (entry.type === "tree") {921+ return filesUnder(repo, entry.sha, `${path}/`);922+ }923+924+ return isFile(entry)925+ ? Effect.map(blobIn(repo, entry.sha), (bytes) => [926+ [path, new TextDecoder().decode(bytes)] as const,927+ ])928+ : Effect.succeed([]);929+ });930+931+ return nested.flat();932+ });933+934+/** The config folder in the root `root`, if the commit has one. */935+const configFolder = (repo: RepoName, root: ObjectId) =>936+ Effect.reduce(937+ Brand.configDir.split("/"),938+ (): Option.Option<ObjectId> => Option.some(root),939+ (folder, segment) =>940+ Option.match(folder, {941+ onNone: () => Effect.succeedNone,942+ onSome: (id) =>943+ Effect.map(treeIn(repo, id), (entries) =>944+ folderOf(entries.find(({ name }) => name === segment))945+ ),946+ })947+ );948+949+const bundleRules = (job: BundleJob) =>950+ Effect.gen(function* () {951+ const commit = yield* commitIn(job.repo, job.at);952+ const folder = yield* configFolder(job.repo, commit.tree);953+954+ const files = yield* Option.match(folder, {955+ onNone: () => Effect.succeed([]),956+ onSome: (tree) => filesUnder(job.repo, tree, `${Brand.configDir}/`),957+ });958+959+ return {960+ entry: `${Brand.configDir}/project.ts`,961+ modules: Object.fromEntries(files),962+ sdkVersion,963+ } satisfies ConfigBundle;964+ });965+966+const merge = (job: MergeJob) =>967+ Effect.gen(function* () {968+ const into = yield* scratch;969+ const { base, head, tree } = yield* mergeOnto(into, job);970+971+ // What the answer changed against its own base, not what main did.972+ const changes = yield* treeDiff(job.fork, base, head).pipe(unlessLost);973+974+ return { changes, tree };975+ });976+977+/** The Lander over isomorphic-git, reading and pushing through `RepoHost`. */978+export const LanderIsogit: Layer.Layer<Lander, never, RepoHost> = Layer.effect(979+ Lander,980+ Effect.gen(function* () {981+ const host = yield* RepoHost;982+ const provided = Effect.provideService(RepoHost, host);983+984+ return Lander.of({985+ bundleRules: (job) => provided(bundleRules(job)),986+ compose: (job) => provided(compose(job)),987+ land: (job) => provided(land(job)),988+ merge: (job) => provided(merge(job)),989+ });990+ })991+);added:packages/project/src/lander/memory.ts+93 added
1+/**2+ * `Lander` from a script, for tests: each operation returns its scripted3+ * results in order, and the last one again once they run out. An operation4+ * with no script is `VerifierBlocked`, as a Lander that cannot run is. It5+ * records every job it is given, in order, for the test to read back.6+ */7+import type { RepoBusy, StaleBase } from "@repo/protocol/refusal";8+import { VerifierBlocked } from "@repo/protocol/refusal";9+import type { ConfigBundle } from "@repo/rules/rules-evaluator";10+import { Array, Data, Effect, Layer } from "effect";11+import type { Result } from "effect";12+13+import { Lander } from "../lander.ts";14+import type {15+ BundleJob,16+ ComposeJob,17+ Composed,18+ Landed,19+ LandJob,20+ MergeJob,21+ Merged,22+} from "../lander.ts";23+24+/** One call the scripted Lander answered, with the job it was given. */25+export type LanderJob = Data.TaggedEnum<{26+ Merge: { readonly job: MergeJob };27+ Land: { readonly job: LandJob };28+ Compose: { readonly job: ComposeJob };29+ BundleRules: { readonly job: BundleJob };30+}>;31+32+export const LanderJob = Data.taggedEnum<LanderJob>();33+34+/** Each operation's results, in the order its calls get them. */35+export interface LanderScript {36+ readonly merge?: readonly Result.Result<37+ Merged,38+ StaleBase | VerifierBlocked39+ >[];40+ readonly land?: readonly Result.Result<41+ Landed,42+ StaleBase | RepoBusy | VerifierBlocked43+ >[];44+ readonly compose?: readonly Result.Result<Composed, VerifierBlocked>[];45+ readonly bundle?: readonly Result.Result<ConfigBundle, VerifierBlocked>[];46+}47+48+/** A scripted Lander, and the jobs it has been given so far. */49+export type ScriptedLander = Layer.Layer<Lander> & {50+ readonly jobs: Effect.Effect<readonly LanderJob[]>;51+};52+53+export const LanderMemory = {54+ /**55+ * One scripted Lander: every build of the layer shares its script's place56+ * and its record of jobs, so a test reads `jobs` after providing it.57+ */58+ layer: (script: LanderScript): ScriptedLander => {59+ const jobs: LanderJob[] = [];60+ const served = new Map<keyof LanderScript, number>();61+62+ const answer = <A, E>(63+ operation: keyof LanderScript,64+ results: readonly Result.Result<A, E>[] | undefined,65+ job: LanderJob66+ ): Effect.Effect<A, E | VerifierBlocked> =>67+ Effect.suspend((): Effect.Effect<A, E | VerifierBlocked> => {68+ const count = served.get(operation) ?? 0;69+70+ jobs.push(job);71+ served.set(operation, count + 1);72+73+ if (results === undefined || !Array.isReadonlyArrayNonEmpty(results)) {74+ return Effect.fail(new VerifierBlocked({}));75+ }76+77+ return Effect.fromResult(78+ results[Math.min(count, results.length - 1)] ?? results[0]79+ );80+ });81+82+ const layer = Layer.succeed(Lander, {83+ bundleRules: (job) =>84+ answer("bundle", script.bundle, LanderJob.BundleRules({ job })),85+ compose: (job) =>86+ answer("compose", script.compose, LanderJob.Compose({ job })),87+ land: (job) => answer("land", script.land, LanderJob.Land({ job })),88+ merge: (job) => answer("merge", script.merge, LanderJob.Merge({ job })),89+ });90+91+ return Object.assign(layer, { jobs: Effect.sync(() => [...jobs]) });92+ },93+};added:packages/project/src/lander.ts+182 added
1+/**2+ * The `Lander` port (spec §4.2): the one way an answer's head is merged onto3+ * main, a decider's ask files are composed onto it, a checked tree lands on4+ * canonical `main` as a platform commit, and the config folder is read at a5+ * landed commit. The Lander is trusted and runs no project code.6+ *7+ * Three additions to the spec's port (212): `land`'s `rebuild`, since `merge`8+ * and `land` run in separate calls (the Answer Workflow's steps), so a9+ * stateless adapter rebuilds the tree it lands; `land`'s `verdict`, the note10+ * written after main moves; and `compose`, for running an ask's check red11+ * first before the ask opens (spec §5 step 3).12+ *13+ * Adapters: `/memory` (scripted, for tests) and `/isogit` (isomorphic-git over14+ * `RepoHost`, the fallback until the container Lander in `apps/sandbox`15+ * passes, spec D6).16+ */17+import { RefName } from "@repo/artifacts/repo-host";18+import { Brand } from "@repo/brand";19+import type { Change } from "@repo/git/tree-diff";20+import type { Verdict } from "@repo/protocol/domain/answer";21+import type {22+ CommitSha,23+ Handle,24+ LandedSha,25+ RepoName,26+ RepoPath,27+ RequestId,28+ TreeSha,29+} from "@repo/protocol/ids";30+import type {31+ RepoBusy,32+ StaleBase,33+ VerifierBlocked,34+} from "@repo/protocol/refusal";35+import type { ConfigBundle } from "@repo/rules/rules-evaluator";36+import { Context, Data } from "effect";37+import type { Array, Effect, Option } from "effect";38+39+export type { Change } from "@repo/git/tree-diff";40+41+/**42+ * The mirror of canonical `main` (ADR 0005, spec D22): it moves only after43+ * `main` did, in its own push, and only to the commit `main` points at.44+ */45+export const landedRef = RefName.make(`${Brand.refsPrefix}landed`);46+47+/**48+ * Where a composed commit waits, in the canonical repo, for a Checker to49+ * fetch it by id. It is never `main`.50+ */51+export const composeRef = (tree: TreeSha) =>52+ RefName.make(`${Brand.refsPrefix}compose/${tree}`);53+54+/** An answer's head to merge onto canonical `main`. */55+export interface MergeJob {56+ /** The canonical repo. */57+ readonly repo: RepoName;58+ /** Where canonical `main` stood when the merge was asked for. */59+ readonly main: LandedSha;60+ /** The commit the answer was made on. */61+ readonly base: CommitSha;62+ readonly head: CommitSha;63+ /** The claim's fork, which holds the answer's commits. */64+ readonly fork: RepoName;65+}66+67+/** An answer merged onto main: the tree to check, and what the answer changed. */68+export interface Merged {69+ readonly tree: TreeSha;70+ /** The answer's changes against its base, not main's. */71+ readonly changes: readonly Change[];72+}73+74+/** One file a decider adds at its path, such as an ask file or its check. */75+export interface ComposedFile {76+ readonly path: RepoPath;77+ readonly content: string;78+}79+80+/**81+ * How a stateless adapter rebuilds the tree it lands: an answer's merge,82+ * a decider's files composed onto main, or an existing commit's tree (a83+ * revert). The rebuilt tree must be the job's `tree`.84+ */85+export type Rebuild = Data.TaggedEnum<{86+ Merge: {87+ readonly fork: RepoName;88+ readonly base: CommitSha;89+ readonly head: CommitSha;90+ };91+ Compose: { readonly files: Array.NonEmptyReadonlyArray<ComposedFile> };92+ Existing: { readonly commit: CommitSha };93+}>;94+95+export const Rebuild = Data.taggedEnum<Rebuild>();96+97+/** A checked tree to land on canonical `main` as a platform commit. */98+export interface LandJob {99+ readonly repo: RepoName;100+ /** The `main` the tree was made and checked on: the push's compare-and-swap. */101+ readonly main: LandedSha;102+ readonly tree: TreeSha;103+ /** The accountable person: the commit's author. The platform commits it. */104+ readonly author: Handle;105+ /**106+ * The whole message, trailers included (`formatLanding`), with the107+ * `Request-Id` trailer that makes a second land of the same request find108+ * the first one's commit.109+ */110+ readonly message: string;111+ readonly requestId: RequestId;112+ readonly rebuild: Rebuild;113+ /** The note written on the new commit once `main` has moved. */114+ readonly verdict: Option.Option<Verdict>;115+}116+117+/** Bookkeeping written after `main` moved, each in its own push (S1 #6). */118+export type Bookkeeping = "mirror" | "notes";119+120+/**121+ * A landing: the new tip of `main`, and the bookkeeping that did not get122+ * written. A pending item never fails the landing; the service queues it in123+ * the outbox and lands it again later.124+ */125+export interface Landed {126+ readonly sha: LandedSha;127+ readonly pending: readonly Bookkeeping[];128+}129+130+/** A decider's files to compose onto canonical `main`, so an ask's check can run red first. */131+export interface ComposeJob {132+ readonly repo: RepoName;133+ readonly main: LandedSha;134+ readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;135+}136+137+/** Main with the files added: its tree, and the commit a Checker fetches it by. */138+export interface Composed {139+ readonly tree: TreeSha;140+ /** On `composeRef(tree)` in the canonical repo; its parent is `main`. */141+ readonly commit: CommitSha;142+}143+144+/** The config folder to read at one landed commit. */145+export interface BundleJob {146+ readonly repo: RepoName;147+ readonly at: LandedSha;148+}149+150+export class Lander extends Context.Service<151+ Lander,152+ {153+ /**154+ * The answer's head merged three ways onto `main` (its base the merge155+ * base), or `StaleBase` with the paths that conflict.156+ */157+ readonly merge: (158+ job: MergeJob159+ ) => Effect.Effect<Merged, StaleBase | VerifierBlocked>;160+ /**161+ * One commit on canonical `main` whose parent is `main` and whose tree is162+ * `tree`, pushed with a non-force compare-and-swap: if `main` moved, the163+ * land is `StaleBase`, never a force push. Then, each in its own push,164+ * the mirror ref and the verdict note. A second land of the same request165+ * returns the first one's commit.166+ */167+ readonly land: (168+ job: LandJob169+ ) => Effect.Effect<Landed, StaleBase | RepoBusy | VerifierBlocked>;170+ /** `main` with the files added, pushed to `composeRef(tree)`; `main` never moves. */171+ readonly compose: (172+ job: ComposeJob173+ ) => Effect.Effect<Composed, VerifierBlocked>;174+ /**175+ * Every file under the config folder at `at`, for the rules evaluator.176+ * No folder gives no modules: the project runs on the defaults.177+ */178+ readonly bundleRules: (179+ job: BundleJob180+ ) => Effect.Effect<ConfigBundle, VerifierBlocked>;181+ }182+>()("project/Lander") {}added:packages/project/test/lander-isogit.test.ts+727 added
1+import { describe, expect, it } from "@effect/vitest";2+import {3+ BranchName,4+ HostBusy,5+ ObjectId,6+ RefName,7+ RepoHost,8+ RepoName,9+ Revision,10+} from "@repo/artifacts/repo-host";11+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12+import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13+import { Brand } from "@repo/brand";14+import { notesRef } from "@repo/git/notes";15+import {16+ authorLine,17+ committerLine,18+ formatLanding,19+ parseTrailers,20+} from "@repo/git/trailers";21+import { Verdict } from "@repo/protocol/domain/answer";22+import { Outcome } from "@repo/protocol/domain/outcome";23+import type { CommitSha } from "@repo/protocol/ids";24+import {25+ AskId,26+ BlobSha,27+ CheckVersion,28+ Handle,29+ LandedSha,30+ PatchId,31+ ProjectName,32+ RepoPath,33+ RequestId,34+ TreeSha,35+} from "@repo/protocol/ids";36+import { StaleBase, VerifierBlocked } from "@repo/protocol/refusal";37+import { advanceTo } from "@repo/testkit/clock";38+import { gitClient } from "@repo/testkit/git-client";39+import type { Files } from "@repo/testkit/git-client";40+import { DateTime, Effect, Layer, Option, Schema } from "effect";41+import { hashBlob, readCommit } from "isomorphic-git";42+43+import { composeRef, Lander, landedRef, Rebuild } from "../src/lander.ts";44+import type { LandJob } from "../src/lander.ts";45+import { LanderIsogit } from "../src/lander/isogit.ts";46+47+const demo = RepoName.make("demo");48+49+const fork = RepoName.make("demo--fix-parser--alice");50+51+const mainRef = RefName.make("refs/heads/main");52+53+const alice = Handle.make("alice");54+55+const bob = Handle.make("bob");56+57+const requestId = RequestId.make("request-fix-parser-1");58+59+/** The Lander over a fresh memory store, with the store itself for the test to read. */60+const world = Layer.provideMerge(LanderIsogit, RepoHostMemory);61+62+/**63+ * A memory store whose pushes of any ref but `main` are refused as busy: the64+ * bookkeeping after a landing cannot be written.65+ */66+const busyBookkeeping = Layer.provideMerge(67+ LanderIsogit,68+ Layer.effect(69+ RepoHost,70+ Effect.gen(function* () {71+ const host = yield* RepoHost;72+73+ return RepoHost.of({74+ ...host,75+ push: (name, source, updates) =>76+ updates.some(({ ref }) => ref !== mainRef)77+ ? Effect.fail(new HostBusy({ name }))78+ : host.push(name, source, updates),79+ });80+ })81+ ).pipe(Layer.provide(RepoHostMemory))82+);83+84+/** git's id for a blob holding `text`. */85+const blobOf = (text: string) =>86+ Effect.promise(() => hashBlob({ object: text })).pipe(87+ Effect.map(({ oid }) => BlobSha.make(oid))88+ );89+90+/**91+ * Canonical `demo` with `files` on main, and alice's claim fork of it. The92+ * test builds commits in its own client and pushes them with plain93+ * compare-and-swaps, as git would.94+ */95+const project = (files: Files) =>96+ Effect.gen(function* () {97+ const repos = yield* RepoHost;98+ const client = yield* gitClient(memoryFs());99+ const base = yield* client.commit("Start", files);100+101+ yield* repos.create(demo);102+ yield* repos.push(demo, client.source, [103+ { from: Option.none(), ref: mainRef, to: base },104+ ]);105+ yield* repos.fork(demo, fork);106+107+ /** A commit of `files` on `parent`, pushed to `repo`'s main. */108+ const advance = (109+ repo: RepoName,110+ parent: CommitSha,111+ message: string,112+ next: Files113+ ) =>114+ Effect.gen(function* () {115+ const sha = yield* client.commit(message, next, [parent]);116+117+ yield* repos.push(repo, client.source, [118+ { from: Option.some(parent), ref: mainRef, to: sha },119+ ]);120+121+ return sha;122+ });123+124+ /** The tree git makes of `next`, built in the client and never pushed. */125+ const treeOf = (next: Files) =>126+ Effect.gen(function* () {127+ const sha = yield* client.commit("Expected", next);128+129+ const { commit } = yield* Effect.promise(() =>130+ readCommit({ ...client.source, oid: sha })131+ );132+133+ return TreeSha.make(commit.tree);134+ });135+136+ return { advance, base, treeOf };137+ });138+139+/** The tip of `main`, as the platform last landed it. */140+const landed = (sha: CommitSha) => LandedSha.make(sha);141+142+const checkedAt = DateTime.makeUnsafe("2026-10-07T12:00:00Z");143+144+const verdictOn = (head: CommitSha, base: CommitSha, tree: TreeSha) =>145+ Verdict.make({146+ ask: AskId.make("fix-parser"),147+ at: checkedAt,148+ base,149+ checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),150+ head,151+ heldBack: [],152+ lanes: [],153+ outcome: Outcome.cases.Checking.make({ stage: "checks" }),154+ patchId: PatchId.make("2".repeat(64)),155+ project: ProjectName.make("demo"),156+ stage: "checks",157+ tree,158+ verifier: "platform",159+ });160+161+const message = formatLanding({162+ assisted: [],163+ credits: [164+ { handle: bob, role: "Asked-by" },165+ { handle: alice, role: "Signed-off-by" },166+ ],167+ requestId,168+ subject: "Fix the parser",169+});170+171+/** The note on `target` in `repo`'s notes, as plain git finds it. */172+const noteOn = (repo: RepoName, target: CommitSha) =>173+ Effect.gen(function* () {174+ const repos = yield* RepoHost;175+ const tip = (yield* repos.refs(repo)).get(notesRef);176+177+ if (tip === undefined) {178+ return Option.none();179+ }180+181+ const commit = Option.getOrThrow(yield* repos.readCommit(repo, tip));182+ const entries = Option.getOrThrow(yield* repos.readTree(repo, commit.tree));183+ const entry = entries.find(({ name }) => name === target);184+185+ if (entry === undefined) {186+ return Option.none();187+ }188+189+ const bytes = yield* repos.readBlob(repo, ObjectId.make(entry.sha));190+191+ return Option.map(bytes, (note) => new TextDecoder().decode(note));192+ });193+194+const decodeNote = Schema.decodeEffect(Schema.fromJsonString(Verdict));195+196+const start: Files = [197+ ["src/a.ts", "a1\n"],198+ ["src/b.ts", "b1\n"],199+];200+201+/**202+ * main changed `src/b.ts` since the fork; alice's head changed `src/a.ts`203+ * and added `docs/guide.md`.204+ */205+const diverged = Effect.gen(function* () {206+ const { advance, base, treeOf } = yield* project(start);207+208+ const main = yield* advance(demo, base, "Touch b", [209+ ["src/a.ts", "a1\n"],210+ ["src/b.ts", "b2\n"],211+ ]);212+213+ const head = yield* advance(fork, base, "Fix a", [214+ ["docs/guide.md", "read me\n"],215+ ["src/a.ts", "a2\n"],216+ ["src/b.ts", "b1\n"],217+ ]);218+219+ return { advance, base, head, main: landed(main), treeOf };220+});221+222+/** A land of alice's merged answer onto `main`. */223+const landOf = (input: {224+ readonly main: LandedSha;225+ readonly base: CommitSha;226+ readonly head: CommitSha;227+ readonly tree: TreeSha;228+}): LandJob => ({229+ author: alice,230+ main: input.main,231+ message,232+ rebuild: Rebuild.Merge({ base: input.base, fork, head: input.head }),233+ repo: demo,234+ requestId,235+ tree: input.tree,236+ verdict: Option.some(verdictOn(input.head, input.base, input.tree)),237+});238+239+describe("the isomorphic-git Lander", () => {240+ describe("merge", () => {241+ it.effect(242+ "merges a head that changed one file onto a main that changed another, with the answer's own changes",243+ () =>244+ Effect.gen(function* () {245+ const lander = yield* Lander;246+ const { base, head, main, treeOf } = yield* diverged;247+248+ const merged = yield* lander.merge({249+ base,250+ fork,251+ head,252+ main,253+ repo: demo,254+ });255+256+ expect(merged).toStrictEqual({257+ changes: [258+ {259+ after: yield* blobOf("read me\n"),260+ path: RepoPath.make("docs/guide.md"),261+ status: "added",262+ },263+ {264+ after: yield* blobOf("a2\n"),265+ before: yield* blobOf("a1\n"),266+ path: RepoPath.make("src/a.ts"),267+ status: "modified",268+ },269+ ],270+ tree: yield* treeOf([271+ ["docs/guide.md", "read me\n"],272+ ["src/a.ts", "a2\n"],273+ ["src/b.ts", "b2\n"],274+ ]),275+ });276+ }).pipe(Effect.provide(world))277+ );278+279+ it.effect("merges two changes to different lines of one file", () =>280+ Effect.gen(function* () {281+ const lander = yield* Lander;282+283+ const { advance, base, treeOf } = yield* project([284+ ["src/a.ts", "1\n2\n3\n4\n5\n"],285+ ]);286+287+ const main = yield* advance(demo, base, "Top", [288+ ["src/a.ts", "one\n2\n3\n4\n5\n"],289+ ]);290+291+ const head = yield* advance(fork, base, "Bottom", [292+ ["src/a.ts", "1\n2\n3\n4\nfive\n"],293+ ]);294+295+ const merged = yield* lander.merge({296+ base,297+ fork,298+ head,299+ main: landed(main),300+ repo: demo,301+ });302+303+ expect(merged.tree).toBe(304+ yield* treeOf([["src/a.ts", "one\n2\n3\n4\nfive\n"]])305+ );306+ }).pipe(Effect.provide(world))307+ );308+309+ it.effect(310+ "refuses a head that conflicts with main as StaleBase, naming the path",311+ () =>312+ Effect.gen(function* () {313+ const lander = yield* Lander;314+ const { advance, base } = yield* project(start);315+316+ const main = yield* advance(demo, base, "Main's a", [317+ ["src/a.ts", "a-main\n"],318+ ["src/b.ts", "b1\n"],319+ ]);320+321+ const head = yield* advance(fork, base, "Alice's a", [322+ ["src/a.ts", "a-alice\n"],323+ ["src/b.ts", "b1\n"],324+ ]);325+326+ const refused = yield* lander327+ .merge({ base, fork, head, main: landed(main), repo: demo })328+ .pipe(Effect.flip);329+330+ expect(refused).toStrictEqual(331+ new StaleBase({332+ base,333+ conflicts: [RepoPath.make("src/a.ts")],334+ main,335+ })336+ );337+ }).pipe(Effect.provide(world))338+ );339+ });340+341+ describe("land", () => {342+ it.effect(343+ "lands one platform commit on main that credits its people, then the mirror ref and the verdict note",344+ () =>345+ Effect.gen(function* () {346+ const lander = yield* Lander;347+ const repos = yield* RepoHost;348+ const { base, head, main } = yield* diverged;349+350+ const merged = yield* lander.merge({351+ base,352+ fork,353+ head,354+ main,355+ repo: demo,356+ });357+358+ yield* advanceTo("2026-10-07T12:30:00Z");359+360+ const job = landOf({ base, head, main, tree: merged.tree });361+ const result = yield* lander.land(job);362+ const refs = yield* repos.refs(demo);363+364+ const commit = Option.getOrThrow(365+ yield* repos.readCommit(demo, result.sha)366+ );367+368+ expect({369+ mirror: refs.get(landedRef),370+ onMain: refs.get(mainRef),371+ pending: result.pending,372+ }).toStrictEqual({373+ mirror: result.sha,374+ onMain: result.sha,375+ pending: [],376+ });377+ expect({378+ author: commit.author,379+ committer: commit.committer,380+ parents: commit.parents,381+ trailers: parseTrailers(commit.message),382+ tree: commit.tree,383+ }).toStrictEqual({384+ author: authorLine(alice),385+ committer: committerLine,386+ parents: [main],387+ trailers: [388+ { key: "Asked-by", value: `bob <bob@users.${Brand.domain}>` },389+ {390+ key: "Signed-off-by",391+ value: `alice <alice@users.${Brand.domain}>`,392+ },393+ { key: "Request-Id", value: requestId },394+ ],395+ tree: merged.tree,396+ });397+ expect(landedRef).toBe(`${Brand.refsPrefix}landed`);398+399+ const note = Option.getOrThrow(yield* noteOn(demo, result.sha));400+401+ expect(yield* decodeNote(note)).toStrictEqual(402+ Option.getOrThrow(job.verdict)403+ );404+ }).pipe(Effect.provide(world))405+ );406+407+ it.effect(408+ "refuses as StaleBase when main moved after the merge, and never forces main",409+ () =>410+ Effect.gen(function* () {411+ const lander = yield* Lander;412+ const repos = yield* RepoHost;413+ const { advance, base, head, main } = yield* diverged;414+415+ const merged = yield* lander.merge({416+ base,417+ fork,418+ head,419+ main,420+ repo: demo,421+ });422+423+ const other = yield* advance(demo, main, "Someone else landed", [424+ ["src/a.ts", "a1\n"],425+ ["src/b.ts", "b3\n"],426+ ]);427+428+ const refused = yield* lander429+ .land(landOf({ base, head, main, tree: merged.tree }))430+ .pipe(Effect.flip);431+432+ expect(refused).toStrictEqual(433+ new StaleBase({ base, conflicts: [], main: other })434+ );435+ expect((yield* repos.refs(demo)).get(mainRef)).toBe(other);436+ }).pipe(Effect.provide(world))437+ );438+439+ it.effect(440+ "lands a request once: a second land with the same request id returns the first commit",441+ () =>442+ Effect.gen(function* () {443+ const lander = yield* Lander;444+ const repos = yield* RepoHost;445+ const { base, head, main } = yield* diverged;446+447+ const merged = yield* lander.merge({448+ base,449+ fork,450+ head,451+ main,452+ repo: demo,453+ });454+455+ const job = landOf({ base, head, main, tree: merged.tree });456+ const first = yield* lander.land(job);457+ const second = yield* lander.land(job);458+459+ const history = yield* repos.log(460+ demo,461+ Revision.Branch({ name: BranchName.make("main") }),462+ 3463+ );464+465+ expect(second).toStrictEqual(first);466+ expect(history.map(({ sha }) => sha)).toStrictEqual([467+ first.sha,468+ main,469+ base,470+ ]);471+ }).pipe(Effect.provide(world))472+ );473+474+ it.effect(475+ "still lands when the mirror ref and the note cannot be written, and says they are pending",476+ () =>477+ Effect.gen(function* () {478+ const lander = yield* Lander;479+ const repos = yield* RepoHost;480+ const { base, head, main } = yield* diverged;481+482+ const merged = yield* lander.merge({483+ base,484+ fork,485+ head,486+ main,487+ repo: demo,488+ });489+490+ const result = yield* lander.land(491+ landOf({ base, head, main, tree: merged.tree })492+ );493+494+ const refs = yield* repos.refs(demo);495+496+ expect(result.pending).toStrictEqual(["mirror", "notes"]);497+ expect(refs.get(mainRef)).toBe(result.sha);498+ expect([refs.has(landedRef), refs.has(notesRef)]).toStrictEqual([499+ false,500+ false,501+ ]);502+ }).pipe(Effect.provide(busyBookkeeping))503+ );504+505+ it.effect(506+ "refuses a rebuild that does not give the checked tree, leaving main where it was",507+ () =>508+ Effect.gen(function* () {509+ const lander = yield* Lander;510+ const repos = yield* RepoHost;511+ const { base, head, main } = yield* diverged;512+513+ const refused = yield* lander514+ .land(landOf({ base, head, main, tree: TreeSha.make(main) }))515+ .pipe(Effect.flip);516+517+ expect(refused).toStrictEqual(new VerifierBlocked({}));518+ expect((yield* repos.refs(demo)).get(mainRef)).toBe(main);519+ }).pipe(Effect.provide(world))520+ );521+522+ it.effect(523+ "lands a decider's composed files as the platform commit that opens an ask",524+ () =>525+ Effect.gen(function* () {526+ const lander = yield* Lander;527+ const repos = yield* RepoHost;528+ const { base } = yield* project(start);529+ const main = landed(base);530+531+ const files = [532+ {533+ content: "export default {}\n",534+ path: RepoPath.make(`${Brand.configDir}/asks/x.ask.ts`),535+ },536+ ] as const;537+538+ const composed = yield* lander.compose({ files, main, repo: demo });539+540+ const result = yield* lander.land({541+ author: bob,542+ main,543+ message,544+ rebuild: Rebuild.Compose({ files }),545+ repo: demo,546+ requestId,547+ tree: composed.tree,548+ verdict: Option.none(),549+ });550+551+ const commit = Option.getOrThrow(552+ yield* repos.readCommit(demo, result.sha)553+ );554+555+ expect(result.pending).toStrictEqual([]);556+ expect({557+ author: commit.author,558+ parents: commit.parents,559+ tree: commit.tree,560+ }).toStrictEqual({561+ author: authorLine(bob),562+ parents: [base],563+ tree: composed.tree,564+ });565+ }).pipe(Effect.provide(world))566+ );567+568+ it.effect(569+ "lands an existing commit's tree again on top of main, as a revert does",570+ () =>571+ Effect.gen(function* () {572+ const lander = yield* Lander;573+ const repos = yield* RepoHost;574+ const { base, main } = yield* diverged;575+ const before = Option.getOrThrow(yield* repos.readCommit(demo, base));576+577+ const result = yield* lander.land({578+ author: bob,579+ main,580+ message,581+ rebuild: Rebuild.Existing({ commit: base }),582+ repo: demo,583+ requestId,584+ tree: TreeSha.make(before.tree),585+ verdict: Option.none(),586+ });587+588+ const commit = Option.getOrThrow(589+ yield* repos.readCommit(demo, result.sha)590+ );591+592+ expect({593+ onMain: (yield* repos.refs(demo)).get(mainRef),594+ parents: commit.parents,595+ tree: commit.tree,596+ }).toStrictEqual({597+ onMain: result.sha,598+ parents: [main],599+ tree: before.tree,600+ });601+ }).pipe(Effect.provide(world))602+ );603+ });604+605+ describe("compose", () => {606+ it.effect(607+ "adds a decider's files to main's tree on a scratch ref, and leaves main alone",608+ () =>609+ Effect.gen(function* () {610+ const lander = yield* Lander;611+ const repos = yield* RepoHost;612+ const { base, treeOf } = yield* project(start);613+ const ask = `${Brand.configDir}/asks/x.ask.ts`;614+ const check = "packages/p/test/x.test.ts";615+616+ const composed = yield* lander.compose({617+ files: [618+ { content: "export default {}\n", path: RepoPath.make(ask) },619+ { content: "test('x')\n", path: RepoPath.make(check) },620+ ],621+ main: landed(base),622+ repo: demo,623+ });624+625+ const refs = yield* repos.refs(demo);626+627+ const commit = Option.getOrThrow(628+ yield* repos.readCommit(demo, composed.commit)629+ );630+631+ expect(composed.tree).toBe(632+ yield* treeOf([633+ ...start,634+ [ask, "export default {}\n"],635+ [check, "test('x')\n"],636+ ])637+ );638+ expect({ parents: commit.parents, tree: commit.tree }).toStrictEqual({639+ parents: [base],640+ tree: composed.tree,641+ });642+ expect(composeRef(composed.tree)).toBe(643+ `${Brand.refsPrefix}compose/${composed.tree}`644+ );645+ expect(refs.get(composeRef(composed.tree))).toBe(composed.commit);646+ expect(refs.get(mainRef)).toBe(base);647+ }).pipe(Effect.provide(world))648+ );649+650+ it.effect(651+ "composes the same files onto the same main to the same commit",652+ () =>653+ Effect.gen(function* () {654+ const lander = yield* Lander;655+ const { base } = yield* project(start);656+657+ const job = {658+ files: [659+ {660+ content: "export default {}\n",661+ path: RepoPath.make(`${Brand.configDir}/asks/x.ask.ts`),662+ },663+ ],664+ main: landed(base),665+ repo: demo,666+ } as const;667+668+ const first = yield* lander.compose(job);669+670+ yield* advanceTo("2026-10-07T13:00:00Z");671+672+ expect(yield* lander.compose(job)).toStrictEqual(first);673+ }).pipe(Effect.provide(world))674+ );675+ });676+677+ describe("bundleRules", () => {678+ it.effect(679+ "hands back every file under the config folder at a landed commit, as committed",680+ () =>681+ Effect.gen(function* () {682+ const lander = yield* Lander;683+ const entry = `${Brand.configDir}/project.ts`;684+ const ask = `${Brand.configDir}/asks/x.ask.ts`;685+686+ const { base } = yield* project([687+ [ask, "export default ask\n"],688+ [entry, "export default project\n"],689+ ["src/a.ts", "a1\n"],690+ ]);691+692+ const bundle = yield* lander.bundleRules({693+ at: landed(base),694+ repo: demo,695+ });696+697+ expect({698+ entry: bundle.entry,699+ modules: bundle.modules,700+ }).toStrictEqual({701+ entry,702+ modules: {703+ [ask]: "export default ask\n",704+ [entry]: "export default project\n",705+ },706+ });707+ }).pipe(Effect.provide(world))708+ );709+710+ it.effect("hands back no modules when there is no config folder", () =>711+ Effect.gen(function* () {712+ const lander = yield* Lander;713+ const { base } = yield* project(start);714+715+ const bundle = yield* lander.bundleRules({716+ at: landed(base),717+ repo: demo,718+ });719+720+ expect({ entry: bundle.entry, modules: bundle.modules }).toStrictEqual({721+ entry: `${Brand.configDir}/project.ts`,722+ modules: {},723+ });724+ }).pipe(Effect.provide(world))725+ );726+ });727+});added:packages/project/test/lander-memory.test.ts+142 added
1+import { describe, expect, it } from "@effect/vitest";2+import { Brand } from "@repo/brand";3+import {4+ CommitSha,5+ Handle,6+ LandedSha,7+ RepoName,8+ RepoPath,9+ RequestId,10+ TreeSha,11+} from "@repo/protocol/ids";12+import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";13+import { Effect, Option, Result } from "effect";14+15+import { Lander, Rebuild } from "../src/lander.ts";16+import type { LandJob, MergeJob } from "../src/lander.ts";17+import { LanderJob, LanderMemory } from "../src/lander/memory.ts";18+19+const sha = (n: number) => n.toString(16).padStart(40, "0");20+21+const demo = RepoName.make("demo");22+23+const main = LandedSha.make(CommitSha.make(sha(1)));24+25+const mergeJob: MergeJob = {26+ base: CommitSha.make(sha(1)),27+ fork: RepoName.make("demo--fix-parser--alice"),28+ head: CommitSha.make(sha(2)),29+ main,30+ repo: demo,31+};32+33+const tree = TreeSha.make(sha(3));34+35+const landJob: LandJob = {36+ author: Handle.make("alice"),37+ main,38+ message: "Fix the parser\n",39+ rebuild: Rebuild.Merge({40+ base: mergeJob.base,41+ fork: mergeJob.fork,42+ head: mergeJob.head,43+ }),44+ repo: demo,45+ requestId: RequestId.make("request-fix-parser-1"),46+ tree,47+ verdict: Option.none(),48+};49+50+const stale = new StaleBase({51+ base: mergeJob.base,52+ conflicts: [RepoPath.make("src/a.ts")],53+ main,54+});55+56+const landedAt = LandedSha.make(CommitSha.make(sha(4)));57+58+describe("the scripted Lander", () => {59+ it.effect(60+ "returns each operation's scripted results in order, then the last one again",61+ () => {62+ const scripted = LanderMemory.layer({63+ land: [64+ Result.fail(new RepoBusy({})),65+ Result.succeed({ pending: ["notes"], sha: landedAt }),66+ ],67+ merge: [Result.fail(stale), Result.succeed({ changes: [], tree })],68+ });69+70+ return Effect.gen(function* () {71+ const lander = yield* Lander;72+73+ const merges = yield* Effect.forEach([1, 2, 3], () =>74+ Effect.result(lander.merge(mergeJob))75+ );76+77+ const lands = yield* Effect.forEach([1, 2, 3], () =>78+ Effect.result(lander.land(landJob))79+ );80+81+ expect(merges).toStrictEqual([82+ Result.fail(stale),83+ Result.succeed({ changes: [], tree }),84+ Result.succeed({ changes: [], tree }),85+ ]);86+ expect(lands).toStrictEqual([87+ Result.fail(new RepoBusy({})),88+ Result.succeed({ pending: ["notes"], sha: landedAt }),89+ Result.succeed({ pending: ["notes"], sha: landedAt }),90+ ]);91+ }).pipe(Effect.provide(scripted));92+ }93+ );94+95+ it.effect("is VerifierBlocked for an operation with no script", () =>96+ Effect.gen(function* () {97+ const lander = yield* Lander;98+99+ expect(100+ yield* Effect.flip(lander.bundleRules({ at: main, repo: demo }))101+ ).toStrictEqual(new VerifierBlocked({}));102+ }).pipe(Effect.provide(LanderMemory.layer({})))103+ );104+105+ it.effect("records the jobs it was given, in order", () => {106+ const files = [107+ {108+ content: "export default {}\n",109+ path: RepoPath.make(`${Brand.configDir}/asks/x.ask.ts`),110+ },111+ ] as const;112+113+ const scripted = LanderMemory.layer({114+ bundle: [115+ Result.succeed({116+ entry: `${Brand.configDir}/project.ts`,117+ modules: {},118+ sdkVersion: "0.0.0",119+ }),120+ ],121+ compose: [Result.succeed({ commit: CommitSha.make(sha(5)), tree })],122+ land: [Result.succeed({ pending: [], sha: landedAt })],123+ merge: [Result.succeed({ changes: [], tree })],124+ });125+126+ return Effect.gen(function* () {127+ const lander = yield* Lander;128+129+ yield* lander.compose({ files, main, repo: demo });130+ yield* lander.merge(mergeJob);131+ yield* lander.land(landJob);132+ yield* lander.bundleRules({ at: landedAt, repo: demo });133+134+ expect(yield* scripted.jobs).toStrictEqual([135+ LanderJob.Compose({ job: { files, main, repo: demo } }),136+ LanderJob.Merge({ job: mergeJob }),137+ LanderJob.Land({ job: landJob }),138+ LanderJob.BundleRules({ job: { at: landedAt, repo: demo } }),139+ ]);140+ }).pipe(Effect.provide(scripted));141+ });142+});