Skip to content
Myr

Merge build/212-lander: a checked answer lands on main as a platform commit that credits its people, or is refused as stale

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

authored by oscabriel · committed by oscabriel · parents 7b4ffd5, a3a3d24 · Browse files · 6 files+2360 added−1 removed
This commit

State

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

Diff stats

6 files+2360 added−1 removed

  • tests:+1085 added−0 removed
  • other:+1275 added−1 removed

6 files+2360 added−1 removed

modified:packages/git/src/notes.ts+5 added-1 removed
62 unmodified lines
63/** git's zlib stream, as a loose object holds it. */64const 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)));7475const sortKey = (entry: TreeEntry) =>
184 unmodified lines
added:packages/project/src/lander/isogit.ts+995 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 */23import {24 BranchName,25 ObjectId,26 RefName,27 RefOutcome,28 RepoHost,29 Revision,30} from "@repo/artifacts/repo-host";31import type {32 PushSource,33 RefUpdate,34 RepoNotFound,35 TreeEntry,36} from "@repo/artifacts/repo-host";37import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";38import { Brand } from "@repo/brand";39import { noteCommit, notesRef } from "@repo/git/notes";40import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";41import type { GitIdentity } from "@repo/git/trailers";42import { treeDiff } from "@repo/git/tree-diff";43import type { Verdict } from "@repo/protocol/domain/answer";44import { CommitSha, LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";45import type { RepoName, RequestId } from "@repo/protocol/ids";46import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";47import type { ConfigBundle } from "@repo/rules/rules-evaluator";48import { Array, Clock, DateTime, Effect, Layer, Option, Order } from "effect";49import {50 Errors,51 init,52 merge as mergeHistories,53 readTree as readScratchTree,54 writeBlob,55 writeCommit,56 writeRef,57 writeTree,58} from "isomorphic-git";5960import { composeRef, Lander, landedRef, Rebuild } from "../lander.ts";61import type {62 Bookkeeping,63 BundleJob,64 ComposedFile,65 ComposeJob,66 LandJob,67 MergeJob,68} from "../lander.ts";6970const mainRef = RefName.make("refs/heads/main");7172const mainBranch = BranchName.make("main");7374/**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 */79const sdkVersion = "0.0.0";8081// How far back from main's tip a second land looks for the first one's commit.82const LOOKBACK = 16;8384// git's test for a binary file: a NUL among its first bytes.85const SNIFF = 8000;8687const blocked = () => new VerifierBlocked({});8889/** A store that lost a repo cannot merge or land: `VerifierBlocked`. */90const unlessLost = <A, R>(91 effect: Effect.Effect<A, RepoNotFound, R>92): Effect.Effect<A, VerifierBlocked, R> => Effect.mapError(effect, blocked);9394/** An object the store should hold and does not: `VerifierBlocked` too. */95const 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 );107108const commitIn = (repo: RepoName, sha: CommitSha) =>109 found(RepoHost.use((host) => host.readCommit(repo, sha)));110111const treeIn = (repo: RepoName, tree: ObjectId) =>112 found(RepoHost.use((host) => host.readTree(repo, tree)));113114const blobIn = (repo: RepoName, blob: ObjectId) =>115 found(RepoHost.use((host) => host.readBlob(repo, blob)));116117const refsIn = (repo: RepoName) =>118 RepoHost.use((host) => host.refs(repo)).pipe(unlessLost);119120/** One ref's compare-and-swap, alone in its push; what it came to. */121const 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 );125126/** A push whose ref did not move, for a ref where that is not a refusal. */127const moves = (outcome: Option.Option<RefOutcome>) =>128 Option.exists(outcome, RefOutcome.$is("Updated"))129 ? Effect.void130 : Effect.fail(blocked());131132/** Clock time, in the whole seconds a git signature holds. */133const seconds = Effect.map(Clock.currentTimeMillis, (millis) =>134 Math.floor(millis / 1000)135);136137const git = <A>(run: () => Promise<A>) =>138 Effect.tryPromise(run).pipe(Effect.orDie);139140/** A git signature at `at` seconds past the epoch, in UTC. */141const signed = (who: GitIdentity, at: number) => ({142 email: who.email,143 name: who.name,144 timestamp: at,145 timezoneOffset: 0,146});147148/** A copy of an object must keep its id, or the push would name one it lacks. */149const kept = (id: ObjectId, made: ObjectId) =>150 made === id ? Effect.void : Effect.die(`copying ${id} produced ${made}`);151152/**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 */156const scratch = Effect.gen(function* () {157 const source: PushSource = { fs: memoryFs(), gitdir: "/lander.git" };158159 yield* git(() => init({ ...source, bare: true, defaultBranch: "main" }));160161 const blob = (bytes: Uint8Array) =>162 Effect.map(163 git(() => writeBlob({ ...source, blob: bytes })),164 (oid) => ObjectId.make(oid)165 );166167 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 );182183 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 );205206 /** 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 });219220 return yield* commit({221 at: 0,222 author: committerLine,223 message: "merge\n",224 parents,225 tree: yield* tree(files),226 });227 });228229 /**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, []);241242 const tips = {243 "refs/merge/ours": yield* fileCommit(Option.some(ours), [start]),244 "refs/merge/theirs": yield* fileCommit(Option.some(theirs), [start]),245 };246247 yield* Effect.forEach(Object.entries(tips), ([ref, value]) =>248 git(() => writeRef({ ...source, force: true, ref, value }))249 );250251 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 );273274 if (Option.isNone(merged)) {275 return Option.none();276 }277278 const { tree: entries } = yield* git(() =>279 readScratchTree({ ...source, oid: merged.value })280 );281282 return Option.map(Option.fromNullishOr(entries[0]), ({ oid }) =>283 ObjectId.make(oid)284 );285 });286287 return { blob, commit, lines, source, tree };288});289290type Scratch = Effect.Success<typeof scratch>;291292const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);293294const sameEntry = (one: TreeEntry | undefined, other: TreeEntry | undefined) =>295 one?.sha === other?.sha && one?.mode === other?.mode;296297const isFile = (entry: TreeEntry | undefined) =>298 entry?.mode === "100644" || entry?.mode === "100755";299300/** The folder an entry is, if it is one. */301const folderOf = (entry: TreeEntry | undefined) =>302 entry?.type === "tree" ? Option.some(entry.sha) : Option.none();303304const byName = (entries: readonly TreeEntry[]) =>305 new Map(entries.map((entry) => [entry.name, entry]));306307const entriesAt = (repo: RepoName, tree: Option.Option<ObjectId>) =>308 Option.match(tree, {309 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),310 onSome: (id) => treeIn(repo, id),311 });312313/** Where an answer's sides are read: main from canonical, base and head from the fork. */314interface Sides {315 readonly canonical: RepoName;316 readonly fork: RepoName;317}318319/** A merged folder's entries, or the paths under it that conflict. */320interface MergedTree {321 readonly entries: readonly TreeEntry[];322 readonly conflicts: readonly string[];323}324325const taken = (entry: TreeEntry | undefined): MergedTree => ({326 conflicts: [],327 entries: entry === undefined ? [] : [entry],328});329330const conflict = (path: string): MergedTree => ({331 conflicts: [path],332 entries: [],333});334335/**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 */341const 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 }350351 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 }357358 return Effect.gen(function* () {359 const children = yield* treeIn(sides.fork, theirs.sha);360 const before = byName(yield* entriesAt(sides.fork, folderOf(base)));361362 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};368369/** A file's mode once both sides changed it, unless they changed it differently. */370const 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 }378379 return base?.mode === ours.mode ? Option.some(theirs.mode) : Option.none();380};381382/** A file both sides changed, merged; `None` when the changes conflict. */383const 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);397398 if (Option.isNone(mode)) {399 return Option.none();400 }401402 const file = (sha: ObjectId): TreeEntry => ({403 mode: mode.value,404 name,405 sha,406 type: "blob",407 });408409 if (ours.sha === theirs.sha || base?.sha === theirs.sha) {410 return Option.some(file(ours.sha));411 }412413 if (base?.sha === ours.sha) {414 yield* adopt(sides, into, theirs, base);415416 return Option.some(file(theirs.sha));417 }418419 // Symlinks and submodules that both sides changed are not text to merge.420 if (!(isFile(ours) && isFile(theirs))) {421 return Option.none();422 }423424 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 ]);431432 if ([...Option.toArray(before), mine, yours].some(isBinary)) {433 return Option.none();434 }435436 return Option.map(yield* into.lines(before, mine, yours), file);437 });438439/**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 */444const 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 ]);456457 const names = Array.sort(458 new Set([...base.keys(), ...ours.keys(), ...theirs.keys()]),459 Order.String460 );461462 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}`;469470 if (sameEntry(o, t) || sameEntry(b, t)) {471 return Effect.succeed(taken(o));472 }473474 if (sameEntry(b, o)) {475 return t === undefined476 ? Effect.succeed(taken(t))477 : Effect.as(adopt(sides, into, t, b), taken(t));478 }479480 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 });487488 // 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 }492493 const sha = yield* into.tree(inner.entries);494495 return taken({ mode: "040000", name, sha, type: "tree" });496 });497 }498499 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 }513514 return Effect.succeed(conflict(path));515 }516 );517518 return {519 conflicts: merged.flatMap(({ conflicts }) => conflicts),520 entries: merged.flatMap(({ entries }) => entries),521 };522 });523524/**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 */529const 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 ]);536537 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 );547548 // Sorted as whole paths: the walk's folder-by-folder order puts549 // `src/a.ts` before `src-x.ts`, which a sort by path does not.550 if (merged.conflicts.length > 0) {551 return yield* new StaleBase({552 base: job.base,553 conflicts: Array.sort(merged.conflicts, Order.String).map((path) =>554 RepoPath.make(path)555 ),556 main: job.main,557 });558 }559560 return {561 base: TreeSha.make(base.tree),562 head: TreeSha.make(theirs.tree),563 tree: TreeSha.make(yield* into.tree(merged.entries)),564 };565 });566567/** A file to place, by the folders and name its path is made of. */568interface Placed {569 readonly segments: readonly string[];570 readonly content: string;571}572573/** A path's folders and file name; one that cannot name a file is a defect upstream. */574const placed = ({ content, path }: ComposedFile) => {575 const segments = path.split("/");576577 return segments.every((segment) => !["", ".", "..", ".git"].includes(segment))578 ? Effect.succeed<Placed>({ content, segments })579 : Effect.die(`${path} cannot name a file in a repo`);580};581582/**583 * `files` written into `repo`'s folder `tree` (or a new folder), folder by584 * folder, keeping every other entry: the new folder's id. A file where a585 * folder stands, or a folder where a file stands, is a defect upstream.586 */587const placeFiles = (588 repo: RepoName,589 into: Scratch,590 prefix: string,591 tree: Option.Option<ObjectId>,592 files: readonly Placed[]593): Effect.Effect<ObjectId, VerifierBlocked, RepoHost> =>594 Effect.gen(function* () {595 const entries = byName(yield* entriesAt(repo, tree));596 const groups = Array.groupBy(files, ({ segments }) => segments[0] ?? "");597598 for (const [name, group] of Object.entries(groups)) {599 const existing = entries.get(name);600 const path = `${prefix}${name}`;601 const inside = group.filter(({ segments }) => segments.length > 1);602 const content = group.findLast(({ segments }) => segments.length === 1);603604 if (content === undefined) {605 if (existing !== undefined && existing.type !== "tree") {606 return yield* Effect.die(607 `${path} cannot be both a file and a folder`608 );609 }610611 const sha = yield* placeFiles(612 repo,613 into,614 `${path}/`,615 folderOf(existing),616 inside.map((file) => ({ ...file, segments: file.segments.slice(1) }))617 );618619 entries.set(name, { mode: "040000", name, sha, type: "tree" });620 } else {621 if (622 inside.length > 0 ||623 (existing !== undefined && !isFile(existing))624 ) {625 return yield* Effect.die(626 `${path} cannot be both a file and a folder`627 );628 }629630 entries.set(name, {631 mode: existing?.mode ?? "100644",632 name,633 sha: yield* into.blob(new TextEncoder().encode(content.content)),634 type: "blob",635 });636 }637 }638639 return yield* into.tree([...entries.values()]);640 });641642/** `main` with `files` added, written into `into`: the new root. */643const composeOnto = (644 into: Scratch,645 repo: RepoName,646 main: CommitSha,647 files: readonly ComposedFile[]648) =>649 Effect.gen(function* () {650 const commit = yield* commitIn(repo, main);651 const paths = yield* Effect.forEach(files, placed);652653 return TreeSha.make(654 yield* placeFiles(repo, into, "", Option.some(commit.tree), paths)655 );656 });657658/** The tree a land rebuilds, written into `into` where it is new. */659const rebuilt = (into: Scratch, job: LandJob) =>660 Rebuild.$match(job.rebuild, {661 Compose: ({ files }) => composeOnto(into, job.repo, job.main, files),662 Existing: ({ commit }) =>663 Effect.map(commitIn(job.repo, commit), ({ tree }) => TreeSha.make(tree)),664 Merge: ({ base, fork, head }) =>665 Effect.map(666 mergeOnto(into, { base, fork, head, main: job.main, repo: job.repo }),667 ({ tree }) => tree668 ),669 });670671const requestIdOf = (message: string) =>672 parseTrailers(message).find(({ key }) => key.toLowerCase() === "request-id")673 ?.value;674675const carriesRequest = (message: string, requestId: RequestId) =>676 requestIdOf(message) === requestId677 ? Effect.void678 : Effect.die(`a landing's message must carry Request-Id: ${requestId}`);679680/**681 * The commit an earlier land of the same request put on `main`: a child of682 * the job's `main` carrying its `Request-Id`, on main's first parents.683 */684const landedBefore = (job: LandJob) =>685 Effect.gen(function* () {686 const history = yield* RepoHost.use((host) =>687 host.log(job.repo, Revision.Branch({ name: mainBranch }), LOOKBACK)688 ).pipe(unlessLost);689690 const mine = Array.takeWhile(history, ({ sha }) => sha !== job.main).find(691 ({ message, parents }) =>692 parents[0] === job.main && requestIdOf(message) === job.requestId693 );694695 return Option.fromNullishOr(mine?.sha);696 });697698/** The mirror ref moved to the landing, while the landing is still main's tip. */699const mirror = (repo: RepoName, landing: CommitSha) =>700 Effect.gen(function* () {701 const refs = yield* refsIn(repo);702 const current = Option.fromNullishOr(refs.get(landedRef));703704 // A later landing moved main on, and its own mirror supersedes this one.705 if (refs.get(mainRef) !== landing || Option.contains(current, landing)) {706 return;707 }708709 const empty = yield* scratch;710711 yield* moves(712 yield* pushOne(repo, empty.source, {713 from: current,714 ref: landedRef,715 to: landing,716 })717 );718 });719720/** Whether the notes at `tip` already hold a note on `target`. */721const noted = (722 repo: RepoName,723 tip: Option.Option<CommitSha>,724 target: CommitSha725) =>726 Option.match(tip, {727 onNone: () => Effect.succeed(false),728 onSome: (sha) =>729 Effect.gen(function* () {730 const commit = yield* commitIn(repo, sha);731 const entries = yield* treeIn(repo, commit.tree);732733 return entries.some(({ name }) => name === target);734 }),735 });736737/** The verdict written as the landing's note, unless it is there already. */738const note = (repo: RepoName, landing: CommitSha, verdict: Verdict) =>739 Effect.gen(function* () {740 const refs = yield* refsIn(repo);741 const parent = Option.fromNullishOr(refs.get(notesRef));742743 if (yield* noted(repo, parent, landing)) {744 return;745 }746747 const { commit, source } = yield* noteCommit({748 notesParent: parent,749 now: yield* DateTime.now,750 repo,751 target: landing,752 verdict,753 });754755 yield* moves(756 yield* pushOne(repo, source, { from: parent, ref: notesRef, to: commit })757 );758 });759760/** One piece of bookkeeping: `None` once written, its name when it was not. */761const attempt = <E>(762 item: Bookkeeping,763 write: Effect.Effect<void, E, RepoHost>764) =>765 write.pipe(766 Effect.as(Option.none<Bookkeeping>()),767 Effect.catchCause((cause) =>768 Effect.as(769 Effect.logWarning(`a landing's ${item} was not written`, cause),770 Option.some(item)771 )772 )773 );774775/**776 * What follows a landing on `main`, in order and each in its own push: the777 * mirror ref, then the verdict note. Neither fails the landing; what was not778 * written comes back pending, and landing the same job again writes it.779 */780const settle = (job: LandJob, landing: CommitSha) =>781 Effect.gen(function* () {782 const mirrored = yield* attempt("mirror", mirror(job.repo, landing));783784 const noteWritten = yield* Option.match(job.verdict, {785 onNone: () => Effect.succeedNone,786 onSome: (verdict) => attempt("notes", note(job.repo, landing, verdict)),787 });788789 return {790 pending: Array.getSomes([mirrored, noteWritten]),791 sha: LandedSha.make(landing),792 };793 });794795/** The base a stale land names: the answer's own, or the main it was built on. */796const baseOf = (job: LandJob) =>797 Rebuild.$match(job.rebuild, {798 Compose: () => job.main,799 Existing: () => job.main,800 Merge: ({ base }) => base,801 });802803/** A land that found `main` at `tip`: the earlier land of the same request, or stale. */804const moved = (job: LandJob, tip: Option.Option<CommitSha>) =>805 Effect.gen(function* () {806 const earlier = yield* landedBefore(job);807808 if (Option.isSome(earlier)) {809 return yield* settle(job, earlier.value);810 }811812 return yield* new StaleBase({813 base: baseOf(job),814 conflicts: [],815 main: Option.getOrElse(tip, () => job.main),816 });817 });818819const land = (job: LandJob) =>820 Effect.gen(function* () {821 yield* carriesRequest(job.message, job.requestId);822823 const tip = Option.fromNullishOr((yield* refsIn(job.repo)).get(mainRef));824825 if (!Option.contains(tip, job.main)) {826 return yield* moved(job, tip);827 }828829 const into = yield* scratch;830 const tree = yield* rebuilt(into, job);831832 if (tree !== job.tree) {833 return yield* blocked();834 }835836 const commit = yield* into.commit({837 at: yield* seconds,838 author: authorLine(job.author),839 message: job.message,840 parents: [job.main],841 tree: ObjectId.make(tree),842 });843844 // Never forced: if main moved since `job.main`, this push is refused.845 const outcome = yield* pushOne(job.repo, into.source, {846 from: Option.some(job.main),847 ref: mainRef,848 to: commit,849 }).pipe(850 Effect.catchTags({851 HostBusy: () => Effect.fail(new RepoBusy({})),852 RepoNotFound: () => Effect.fail(blocked()),853 })854 );855856 return Option.exists(outcome, RefOutcome.$is("Updated"))857 ? yield* settle(job, commit)858 : yield* moved(859 job,860 Option.flatMap(outcome, (stale) =>861 RefOutcome.$is("Stale")(stale) ? stale.tip : Option.none()862 )863 );864 });865866const compose = (job: ComposeJob) =>867 Effect.gen(function* () {868 const into = yield* scratch;869 const tree = yield* composeOnto(into, job.repo, job.main, job.files);870 const ref = composeRef(tree);871 const existing = Option.fromNullishOr((yield* refsIn(job.repo)).get(ref));872873 // Composed before onto the same main: the commit a Checker already has.874 if (Option.isSome(existing)) {875 const before = yield* commitIn(job.repo, existing.value);876877 if (878 before.tree === ObjectId.make(tree) &&879 before.parents[0] === job.main880 ) {881 return { commit: existing.value, tree };882 }883 }884885 const commit = yield* into.commit({886 at: yield* seconds,887 author: committerLine,888 message: "Compose files onto main for a check\n",889 parents: [job.main],890 tree: ObjectId.make(tree),891 });892893 yield* pushOne(job.repo, into.source, {894 from: existing,895 ref,896 to: commit,897 }).pipe(898 Effect.catchTags({899 HostBusy: () => Effect.fail(blocked()),900 RepoNotFound: () => Effect.fail(blocked()),901 }),902 Effect.flatMap(moves)903 );904905 return { commit, tree };906 });907908/** Every file under the folder `tree`, by repo path, as committed. */909const filesUnder = (910 repo: RepoName,911 tree: ObjectId,912 prefix: string913): Effect.Effect<914 readonly (readonly [string, string])[],915 VerifierBlocked,916 RepoHost917> =>918 Effect.gen(function* () {919 const entries = yield* treeIn(repo, tree);920921 const nested = yield* Effect.forEach(entries, (entry) => {922 const path = `${prefix}${entry.name}`;923924 if (entry.type === "tree") {925 return filesUnder(repo, entry.sha, `${path}/`);926 }927928 return isFile(entry)929 ? Effect.map(blobIn(repo, entry.sha), (bytes) => [930 [path, new TextDecoder().decode(bytes)] as const,931 ])932 : Effect.succeed([]);933 });934935 return nested.flat();936 });937938/** The config folder in the root `root`, if the commit has one. */939const configFolder = (repo: RepoName, root: ObjectId) =>940 Effect.reduce(941 Brand.configDir.split("/"),942 (): Option.Option<ObjectId> => Option.some(root),943 (folder, segment) =>944 Option.match(folder, {945 onNone: () => Effect.succeedNone,946 onSome: (id) =>947 Effect.map(treeIn(repo, id), (entries) =>948 folderOf(entries.find(({ name }) => name === segment))949 ),950 })951 );952953const bundleRules = (job: BundleJob) =>954 Effect.gen(function* () {955 const commit = yield* commitIn(job.repo, job.at);956 const folder = yield* configFolder(job.repo, commit.tree);957958 const files = yield* Option.match(folder, {959 onNone: () => Effect.succeed([]),960 onSome: (tree) => filesUnder(job.repo, tree, `${Brand.configDir}/`),961 });962963 return {964 entry: `${Brand.configDir}/project.ts`,965 modules: Object.fromEntries(files),966 sdkVersion,967 } satisfies ConfigBundle;968 });969970const merge = (job: MergeJob) =>971 Effect.gen(function* () {972 const into = yield* scratch;973 const { base, head, tree } = yield* mergeOnto(into, job);974975 // What the answer changed against its own base, not what main did.976 const changes = yield* treeDiff(job.fork, base, head).pipe(unlessLost);977978 return { changes, tree };979 });980981/** The Lander over isomorphic-git, reading and pushing through `RepoHost`. */982export const LanderIsogit: Layer.Layer<Lander, never, RepoHost> = Layer.effect(983 Lander,984 Effect.gen(function* () {985 const host = yield* RepoHost;986 const provided = Effect.provideService(RepoHost, host);987988 return Lander.of({989 bundleRules: (job) => provided(bundleRules(job)),990 compose: (job) => provided(compose(job)),991 land: (job) => provided(land(job)),992 merge: (job) => provided(merge(job)),993 });994 })995);
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 */7import type { RepoBusy, StaleBase } from "@repo/protocol/refusal";8import { VerifierBlocked } from "@repo/protocol/refusal";9import type { ConfigBundle } from "@repo/rules/rules-evaluator";10import { Array, Data, Effect, Layer } from "effect";11import type { Result } from "effect";1213import { Lander } from "../lander.ts";14import type {15 BundleJob,16 ComposeJob,17 Composed,18 Landed,19 LandJob,20 MergeJob,21 Merged,22} from "../lander.ts";2324/** One call the scripted Lander answered, with the job it was given. */25export 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}>;3132export const LanderJob = Data.taggedEnum<LanderJob>();3334/** Each operation's results, in the order its calls get them. */35export 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}4748/** A scripted Lander, and the jobs it has been given so far. */49export type ScriptedLander = Layer.Layer<Lander> & {50 readonly jobs: Effect.Effect<readonly LanderJob[]>;51};5253export 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>();6162 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;6970 jobs.push(job);71 served.set(operation, count + 1);7273 if (results === undefined || !Array.isReadonlyArrayNonEmpty(results)) {74 return Effect.fail(new VerifierBlocked({}));75 }7677 return Effect.fromResult(78 results[Math.min(count, results.length - 1)] ?? results[0]79 );80 });8182 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 });9091 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 */17import { RefName } from "@repo/artifacts/repo-host";18import { Brand } from "@repo/brand";19import type { Change } from "@repo/git/tree-diff";20import type { Verdict } from "@repo/protocol/domain/answer";21import type {22 CommitSha,23 Handle,24 LandedSha,25 RepoName,26 RepoPath,27 RequestId,28 TreeSha,29} from "@repo/protocol/ids";30import type {31 RepoBusy,32 StaleBase,33 VerifierBlocked,34} from "@repo/protocol/refusal";35import type { ConfigBundle } from "@repo/rules/rules-evaluator";36import { Context, Data } from "effect";37import type { Array, Effect, Option } from "effect";3839export type { Change } from "@repo/git/tree-diff";4041/**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 */45export const landedRef = RefName.make(`${Brand.refsPrefix}landed`);4647/**48 * Where a composed commit waits, in the canonical repo, for a Checker to49 * fetch it by id. It is never `main`.50 */51export const composeRef = (tree: TreeSha) =>52 RefName.make(`${Brand.refsPrefix}compose/${tree}`);5354/** An answer's head to merge onto canonical `main`. */55export 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}6667/** An answer merged onto main: the tree to check, and what the answer changed. */68export interface Merged {69 readonly tree: TreeSha;70 /** The answer's changes against its base, not main's. */71 readonly changes: readonly Change[];72}7374/** One file a decider adds at its path, such as an ask file or its check. */75export interface ComposedFile {76 readonly path: RepoPath;77 readonly content: string;78}7980/**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 */85export 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}>;9495export const Rebuild = Data.taggedEnum<Rebuild>();9697/** A checked tree to land on canonical `main` as a platform commit. */98export 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}116117/** Bookkeeping written after `main` moved, each in its own push (S1 #6). */118export type Bookkeeping = "mirror" | "notes";119120/**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 */125export interface Landed {126 readonly sha: LandedSha;127 readonly pending: readonly Bookkeeping[];128}129130/** A decider's files to compose onto canonical `main`, so an ask's check can run red first. */131export interface ComposeJob {132 readonly repo: RepoName;133 readonly main: LandedSha;134 readonly files: Array.NonEmptyReadonlyArray<ComposedFile>;135}136137/** Main with the files added: its tree, and the commit a Checker fetches it by. */138export interface Composed {139 readonly tree: TreeSha;140 /** On `composeRef(tree)` in the canonical repo; its parent is `main`. */141 readonly commit: CommitSha;142}143144/** The config folder to read at one landed commit. */145export interface BundleJob {146 readonly repo: RepoName;147 readonly at: LandedSha;148}149150export 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+943 added
1import { describe, expect, it } from "@effect/vitest";2import {3 BranchName,4 HostBusy,5 ObjectId,6 RefName,7 RepoHost,8 RepoName,9 Revision,10} from "@repo/artifacts/repo-host";11import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";12import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";13import { Brand } from "@repo/brand";14import { notesRef } from "@repo/git/notes";15import {16 authorLine,17 committerLine,18 formatLanding,19 parseTrailers,20} from "@repo/git/trailers";21import { Verdict } from "@repo/protocol/domain/answer";22import { Outcome } from "@repo/protocol/domain/outcome";23import {24 AskId,25 BlobSha,26 CheckVersion,27 CommitSha,28 Handle,29 LandedSha,30 PatchId,31 ProjectName,32 RepoPath,33 RequestId,34 TreeSha,35} from "@repo/protocol/ids";36import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";37import { advanceTo, at } from "@repo/testkit/clock";38import { gitClient } from "@repo/testkit/git-client";39import type { Files } from "@repo/testkit/git-client";40import { Context, DateTime, Effect, Layer, Option, Ref, Schema } from "effect";41import { hashBlob, readCommit, writeCommit } from "isomorphic-git";4243import { composeRef, Lander, landedRef, Rebuild } from "../src/lander.ts";44import type { LandJob } from "../src/lander.ts";45import { LanderIsogit } from "../src/lander/isogit.ts";4647const demo = RepoName.make("demo");4849const fork = RepoName.make("demo--fix-parser--alice");5051const mainRef = RefName.make("refs/heads/main");5253const alice = Handle.make("alice");5455const bob = Handle.make("bob");5657const requestId = RequestId.make("request-fix-parser-1");5859// When the landing in the first land test is made, by the TestClock.60const landingTime = "2026-10-07T12:30:00Z";6162/** The Lander over a fresh memory store, with the store itself for the test to read. */63const world = Layer.provideMerge(LanderIsogit, RepoHostMemory);6465/** The refs whose pushes the store refuses as busy; the test sets them as it goes. */66class BusyRefs extends Context.Service<67 BusyRefs,68 Ref.Ref<ReadonlySet<RefName>>69>()("test/BusyRefs") {}7071/** From now on, the store refuses every push of one of `refs` as busy. */72const busy = (...refs: readonly RefName[]) =>73 BusyRefs.use((busyRefs) => Ref.set(busyRefs, new Set(refs)));7475/**76 * The Lander over a fresh memory store that refuses as busy any push of a77 * ref in `BusyRefs` (none at first), with the store for the test to read.78 */79const busyWorld = Layer.provideMerge(80 LanderIsogit,81 Layer.effect(82 RepoHost,83 Effect.gen(function* () {84 const host = yield* RepoHost;85 const busyRefs = yield* BusyRefs;8687 return RepoHost.of({88 ...host,89 push: (name, source, updates) =>90 Effect.gen(function* () {91 const refused = yield* Ref.get(busyRefs);9293 if (updates.some(({ ref }) => refused.has(ref))) {94 return yield* new HostBusy({ name });95 }9697 return yield* host.push(name, source, updates);98 }),99 });100 })101 ).pipe(102 Layer.provide(RepoHostMemory),103 Layer.provideMerge(104 Layer.effect(BusyRefs, Ref.make<ReadonlySet<RefName>>(new Set()))105 )106 )107);108109/** git's id for a blob holding `text`. */110const blobOf = (text: string) =>111 Effect.promise(() => hashBlob({ object: text })).pipe(112 Effect.map(({ oid }) => BlobSha.make(oid))113 );114115/**116 * Canonical `demo` with `files` on main, and alice's claim fork of it. The117 * test builds commits in its own client and pushes them with plain118 * compare-and-swaps, as git would.119 */120const project = (files: Files) =>121 Effect.gen(function* () {122 const repos = yield* RepoHost;123 const client = yield* gitClient(memoryFs());124 const base = yield* client.commit("Start", files);125126 yield* repos.create(demo);127 yield* repos.push(demo, client.source, [128 { from: Option.none(), ref: mainRef, to: base },129 ]);130 yield* repos.fork(demo, fork);131132 /** A commit of `files` on `parent`, pushed to `repo`'s main. */133 const advance = (134 repo: RepoName,135 parent: CommitSha,136 message: string,137 next: Files138 ) =>139 Effect.gen(function* () {140 const sha = yield* client.commit(message, next, [parent]);141142 yield* repos.push(repo, client.source, [143 { from: Option.some(parent), ref: mainRef, to: sha },144 ]);145146 return sha;147 });148149 /** The tree git makes of `next`, built in the client and never pushed. */150 const treeOf = (next: Files) =>151 Effect.gen(function* () {152 const sha = yield* client.commit("Expected", next);153154 const { commit } = yield* Effect.promise(() =>155 readCommit({ ...client.source, oid: sha })156 );157158 return TreeSha.make(commit.tree);159 });160161 /**162 * The id git gives a platform commit of `tree` on `parent` by `author`,163 * made at `iso`: written in the client and never pushed.164 */165 const platformCommitOf = (input: {166 readonly tree: TreeSha;167 readonly parent: CommitSha;168 readonly author: Handle;169 readonly message: string;170 readonly iso: string;171 }) =>172 Effect.gen(function* () {173 const timestamp = Math.floor(174 DateTime.toEpochMillis(at(input.iso)) / 1000175 );176177 const oid = yield* Effect.promise(() =>178 writeCommit({179 ...client.source,180 commit: {181 author: {182 ...authorLine(input.author),183 timestamp,184 timezoneOffset: 0,185 },186 committer: { ...committerLine, timestamp, timezoneOffset: 0 },187 message: input.message,188 parent: [input.parent],189 tree: input.tree,190 },191 })192 );193194 return CommitSha.make(oid);195 });196197 return { advance, base, platformCommitOf, treeOf };198 });199200/** The tip of `main`, as the platform last landed it. */201const landed = (sha: CommitSha) => LandedSha.make(sha);202203const checkedAt = DateTime.makeUnsafe("2026-10-07T12:00:00Z");204205const verdictOn = (head: CommitSha, base: CommitSha, tree: TreeSha) =>206 Verdict.make({207 ask: AskId.make("fix-parser"),208 at: checkedAt,209 base,210 checkVersion: CheckVersion.make("redThenGreen@0.0.0+abc"),211 head,212 heldBack: [],213 lanes: [],214 outcome: Outcome.cases.Checking.make({ stage: "checks" }),215 patchId: PatchId.make("2".repeat(64)),216 project: ProjectName.make("demo"),217 stage: "checks",218 tree,219 verifier: "platform",220 });221222const message = formatLanding({223 assisted: [],224 credits: [225 { handle: bob, role: "Asked-by" },226 { handle: alice, role: "Signed-off-by" },227 ],228 requestId,229 subject: "Fix the parser",230});231232/** The note on `target` in `repo`'s notes, as plain git finds it. */233const noteOn = (repo: RepoName, target: CommitSha) =>234 Effect.gen(function* () {235 const repos = yield* RepoHost;236 const tip = (yield* repos.refs(repo)).get(notesRef);237238 if (tip === undefined) {239 return Option.none();240 }241242 const commit = Option.getOrThrow(yield* repos.readCommit(repo, tip));243 const entries = Option.getOrThrow(yield* repos.readTree(repo, commit.tree));244 const entry = entries.find(({ name }) => name === target);245246 if (entry === undefined) {247 return Option.none();248 }249250 const bytes = yield* repos.readBlob(repo, ObjectId.make(entry.sha));251252 return Option.map(bytes, (note) => new TextDecoder().decode(note));253 });254255const decodeNote = Schema.decodeEffect(Schema.fromJsonString(Verdict));256257const start: Files = [258 ["src/a.ts", "a1\n"],259 ["src/b.ts", "b1\n"],260];261262/**263 * main changed `src/b.ts` since the fork; alice's head changed `src/a.ts`264 * and added `docs/guide.md`.265 */266const diverged = Effect.gen(function* () {267 const { advance, base, platformCommitOf, treeOf } = yield* project(start);268269 const main = yield* advance(demo, base, "Touch b", [270 ["src/a.ts", "a1\n"],271 ["src/b.ts", "b2\n"],272 ]);273274 const head = yield* advance(fork, base, "Fix a", [275 ["docs/guide.md", "read me\n"],276 ["src/a.ts", "a2\n"],277 ["src/b.ts", "b1\n"],278 ]);279280 return {281 advance,282 base,283 head,284 main: landed(main),285 platformCommitOf,286 treeOf,287 };288});289290/** A land of alice's merged answer onto `main`. */291const landOf = (input: {292 readonly main: LandedSha;293 readonly base: CommitSha;294 readonly head: CommitSha;295 readonly tree: TreeSha;296}): LandJob => ({297 author: alice,298 main: input.main,299 message,300 rebuild: Rebuild.Merge({ base: input.base, fork, head: input.head }),301 repo: demo,302 requestId,303 tree: input.tree,304 verdict: Option.some(verdictOn(input.head, input.base, input.tree)),305});306307describe("the isomorphic-git Lander", () => {308 describe("merge", () => {309 it.effect(310 "merges a head that changed one file onto a main that changed another, with the answer's own changes",311 () =>312 Effect.gen(function* () {313 const lander = yield* Lander;314 const { base, head, main, treeOf } = yield* diverged;315316 const merged = yield* lander.merge({317 base,318 fork,319 head,320 main,321 repo: demo,322 });323324 expect(merged).toStrictEqual({325 changes: [326 {327 after: yield* blobOf("read me\n"),328 path: RepoPath.make("docs/guide.md"),329 status: "added",330 },331 {332 after: yield* blobOf("a2\n"),333 before: yield* blobOf("a1\n"),334 path: RepoPath.make("src/a.ts"),335 status: "modified",336 },337 ],338 tree: yield* treeOf([339 ["docs/guide.md", "read me\n"],340 ["src/a.ts", "a2\n"],341 ["src/b.ts", "b2\n"],342 ]),343 });344 }).pipe(Effect.provide(world))345 );346347 it.effect("merges two changes to different lines of one file", () =>348 Effect.gen(function* () {349 const lander = yield* Lander;350351 const { advance, base, treeOf } = yield* project([352 ["src/a.ts", "1\n2\n3\n4\n5\n"],353 ]);354355 const main = yield* advance(demo, base, "Top", [356 ["src/a.ts", "one\n2\n3\n4\n5\n"],357 ]);358359 const head = yield* advance(fork, base, "Bottom", [360 ["src/a.ts", "1\n2\n3\n4\nfive\n"],361 ]);362363 const merged = yield* lander.merge({364 base,365 fork,366 head,367 main: landed(main),368 repo: demo,369 });370371 expect(merged.tree).toBe(372 yield* treeOf([["src/a.ts", "one\n2\n3\n4\nfive\n"]])373 );374 }).pipe(Effect.provide(world))375 );376377 it.effect(378 "refuses a head that conflicts with main as StaleBase, naming every conflicting path in order",379 () =>380 Effect.gen(function* () {381 const lander = yield* Lander;382383 const { advance, base } = yield* project([384 ...start,385 ["src-x.ts", "x1\n"],386 ]);387388 const main = yield* advance(demo, base, "Main's a and x", [389 ["src-x.ts", "x-main\n"],390 ["src/a.ts", "a-main\n"],391 ["src/b.ts", "b1\n"],392 ]);393394 const head = yield* advance(fork, base, "Alice's a and x", [395 ["src-x.ts", "x-alice\n"],396 ["src/a.ts", "a-alice\n"],397 ["src/b.ts", "b1\n"],398 ]);399400 const refused = yield* lander401 .merge({ base, fork, head, main: landed(main), repo: demo })402 .pipe(Effect.flip);403404 expect(refused).toStrictEqual(405 new StaleBase({406 base,407 conflicts: [RepoPath.make("src-x.ts"), RepoPath.make("src/a.ts")],408 main,409 })410 );411 }).pipe(Effect.provide(world))412 );413 });414415 describe("land", () => {416 it.effect(417 "lands one platform commit on main that credits its people, then the mirror ref and the verdict note",418 () =>419 Effect.gen(function* () {420 const lander = yield* Lander;421 const repos = yield* RepoHost;422 const { base, head, main, platformCommitOf } = yield* diverged;423424 const merged = yield* lander.merge({425 base,426 fork,427 head,428 main,429 repo: demo,430 });431432 yield* advanceTo(landingTime);433434 const job = landOf({ base, head, main, tree: merged.tree });435 const result = yield* lander.land(job);436 const refs = yield* repos.refs(demo);437438 const commit = Option.getOrThrow(439 yield* repos.readCommit(demo, result.sha)440 );441442 expect({443 mirror: refs.get(landedRef),444 onMain: refs.get(mainRef),445 pending: result.pending,446 }).toStrictEqual({447 mirror: result.sha,448 onMain: result.sha,449 pending: [],450 });451 expect({452 author: commit.author,453 committer: commit.committer,454 parents: commit.parents,455 trailers: parseTrailers(commit.message),456 tree: commit.tree,457 }).toStrictEqual({458 author: authorLine(alice),459 committer: committerLine,460 parents: [main],461 trailers: [462 { key: "Asked-by", value: `bob <bob@users.${Brand.domain}>` },463 {464 key: "Signed-off-by",465 value: `alice <alice@users.${Brand.domain}>`,466 },467 { key: "Request-Id", value: requestId },468 ],469 tree: merged.tree,470 });471 // The whole commit, its time from the Clock included.472 expect(result.sha).toBe(473 yield* platformCommitOf({474 author: alice,475 iso: landingTime,476 message,477 parent: main,478 tree: merged.tree,479 })480 );481 expect(landedRef).toBe(`${Brand.refsPrefix}landed`);482483 const note = Option.getOrThrow(yield* noteOn(demo, result.sha));484485 expect(yield* decodeNote(note)).toStrictEqual(486 Option.getOrThrow(job.verdict)487 );488 }).pipe(Effect.provide(world))489 );490491 it.effect(492 "refuses as StaleBase when main moved after the merge, and never forces main",493 () =>494 Effect.gen(function* () {495 const lander = yield* Lander;496 const repos = yield* RepoHost;497 const { advance, base, head, main } = yield* diverged;498499 const merged = yield* lander.merge({500 base,501 fork,502 head,503 main,504 repo: demo,505 });506507 const other = yield* advance(demo, main, "Someone else landed", [508 ["src/a.ts", "a1\n"],509 ["src/b.ts", "b3\n"],510 ]);511512 const refused = yield* lander513 .land(landOf({ base, head, main, tree: merged.tree }))514 .pipe(Effect.flip);515516 expect(refused).toStrictEqual(517 new StaleBase({ base, conflicts: [], main: other })518 );519 expect((yield* repos.refs(demo)).get(mainRef)).toBe(other);520 }).pipe(Effect.provide(world))521 );522523 it.effect(524 "lands a request once: a second land with the same request id returns the first commit",525 () =>526 Effect.gen(function* () {527 const lander = yield* Lander;528 const repos = yield* RepoHost;529 const { base, head, main } = yield* diverged;530531 const merged = yield* lander.merge({532 base,533 fork,534 head,535 main,536 repo: demo,537 });538539 const job = landOf({ base, head, main, tree: merged.tree });540 const first = yield* lander.land(job);541 const second = yield* lander.land(job);542543 const history = yield* repos.log(544 demo,545 Revision.Branch({ name: BranchName.make("main") }),546 3547 );548549 expect(second).toStrictEqual(first);550 expect(history.map(({ sha }) => sha)).toStrictEqual([551 first.sha,552 main,553 base,554 ]);555 }).pipe(Effect.provide(world))556 );557558 it.effect(559 "still lands when the mirror ref and the note cannot be written, and says they are pending",560 () =>561 Effect.gen(function* () {562 const lander = yield* Lander;563 const repos = yield* RepoHost;564 const { base, head, main } = yield* diverged;565566 const merged = yield* lander.merge({567 base,568 fork,569 head,570 main,571 repo: demo,572 });573574 yield* busy(landedRef, notesRef);575576 const result = yield* lander.land(577 landOf({ base, head, main, tree: merged.tree })578 );579580 const refs = yield* repos.refs(demo);581582 expect(result.pending).toStrictEqual(["mirror", "notes"]);583 expect(refs.get(mainRef)).toBe(result.sha);584 expect([refs.has(landedRef), refs.has(notesRef)]).toStrictEqual([585 false,586 false,587 ]);588 }).pipe(Effect.provide(busyWorld))589 );590591 it.effect(592 "writes the pending mirror ref and note when the same job lands again, with no new commit",593 () =>594 Effect.gen(function* () {595 const lander = yield* Lander;596 const repos = yield* RepoHost;597 const { base, head, main } = yield* diverged;598599 const merged = yield* lander.merge({600 base,601 fork,602 head,603 main,604 repo: demo,605 });606607 const job = landOf({ base, head, main, tree: merged.tree });608609 yield* busy(landedRef, notesRef);610611 const first = yield* lander.land(job);612613 yield* busy();614615 const again = yield* lander.land(job);616 const refs = yield* repos.refs(demo);617618 expect({619 again,620 first: first.pending,621 mirror: refs.get(landedRef),622 onMain: refs.get(mainRef),623 }).toStrictEqual({624 again: { pending: [], sha: first.sha },625 first: ["mirror", "notes"],626 mirror: first.sha,627 onMain: first.sha,628 });629630 const note = Option.getOrThrow(yield* noteOn(demo, first.sha));631632 expect(yield* decodeNote(note)).toStrictEqual(633 Option.getOrThrow(job.verdict)634 );635 }).pipe(Effect.provide(busyWorld))636 );637638 it.effect(639 "never moves the mirror back to an earlier landing that lands again after a later one",640 () =>641 Effect.gen(function* () {642 const lander = yield* Lander;643 const repos = yield* RepoHost;644 const { base, head, main } = yield* diverged;645 const forked = Option.getOrThrow(yield* repos.readCommit(demo, base));646 const revertId = RequestId.make("request-revert-1");647648 const merged = yield* lander.merge({649 base,650 fork,651 head,652 main,653 repo: demo,654 });655656 const job = landOf({ base, head, main, tree: merged.tree });657658 yield* busy(landedRef);659660 const first = yield* lander.land(job);661662 yield* busy();663664 const later = yield* lander.land({665 author: bob,666 main: first.sha,667 message: formatLanding({668 assisted: [],669 credits: [{ handle: bob, role: "Signed-off-by" }],670 requestId: revertId,671 subject: "Revert the parser fix",672 }),673 rebuild: Rebuild.Existing({ commit: base }),674 repo: demo,675 requestId: revertId,676 tree: TreeSha.make(forked.tree),677 verdict: Option.none(),678 });679680 const again = yield* lander.land(job);681682 expect({683 again,684 first: first.pending,685 mirror: (yield* repos.refs(demo)).get(landedRef),686 }).toStrictEqual({687 again: { pending: [], sha: first.sha },688 first: ["mirror"],689 mirror: later.sha,690 });691 }).pipe(Effect.provide(busyWorld))692 );693694 it.effect(695 "refuses as RepoBusy when the store is busy with main, and leaves main where it was",696 () =>697 Effect.gen(function* () {698 const lander = yield* Lander;699 const repos = yield* RepoHost;700 const { base, head, main } = yield* diverged;701702 const merged = yield* lander.merge({703 base,704 fork,705 head,706 main,707 repo: demo,708 });709710 yield* busy(mainRef);711712 const refused = yield* lander713 .land(landOf({ base, head, main, tree: merged.tree }))714 .pipe(Effect.flip);715716 expect(refused).toStrictEqual(new RepoBusy({}));717 expect((yield* repos.refs(demo)).get(mainRef)).toBe(main);718 }).pipe(Effect.provide(busyWorld))719 );720721 it.effect(722 "refuses a rebuild that does not give the checked tree, leaving main where it was",723 () =>724 Effect.gen(function* () {725 const lander = yield* Lander;726 const repos = yield* RepoHost;727 const { base, head, main } = yield* diverged;728729 const refused = yield* lander730 .land(landOf({ base, head, main, tree: TreeSha.make(main) }))731 .pipe(Effect.flip);732733 expect(refused).toStrictEqual(new VerifierBlocked({}));734 expect((yield* repos.refs(demo)).get(mainRef)).toBe(main);735 }).pipe(Effect.provide(world))736 );737738 it.effect(739 "lands a decider's composed files as the platform commit that opens an ask",740 () =>741 Effect.gen(function* () {742 const lander = yield* Lander;743 const repos = yield* RepoHost;744 const { base } = yield* project(start);745 const main = landed(base);746747 const files = [748 {749 content: "export default {}\n",750 path: RepoPath.make(`${Brand.configDir}/asks/x.ask.ts`),751 },752 ] as const;753754 const composed = yield* lander.compose({ files, main, repo: demo });755756 const result = yield* lander.land({757 author: bob,758 main,759 message,760 rebuild: Rebuild.Compose({ files }),761 repo: demo,762 requestId,763 tree: composed.tree,764 verdict: Option.none(),765 });766767 const commit = Option.getOrThrow(768 yield* repos.readCommit(demo, result.sha)769 );770771 expect(result.pending).toStrictEqual([]);772 expect({773 author: commit.author,774 parents: commit.parents,775 tree: commit.tree,776 }).toStrictEqual({777 author: authorLine(bob),778 parents: [base],779 tree: composed.tree,780 });781 }).pipe(Effect.provide(world))782 );783784 it.effect(785 "lands an existing commit's tree again on top of main, as a revert does",786 () =>787 Effect.gen(function* () {788 const lander = yield* Lander;789 const repos = yield* RepoHost;790 const { base, main } = yield* diverged;791 const before = Option.getOrThrow(yield* repos.readCommit(demo, base));792793 const result = yield* lander.land({794 author: bob,795 main,796 message,797 rebuild: Rebuild.Existing({ commit: base }),798 repo: demo,799 requestId,800 tree: TreeSha.make(before.tree),801 verdict: Option.none(),802 });803804 const commit = Option.getOrThrow(805 yield* repos.readCommit(demo, result.sha)806 );807808 expect({809 onMain: (yield* repos.refs(demo)).get(mainRef),810 parents: commit.parents,811 tree: commit.tree,812 }).toStrictEqual({813 onMain: result.sha,814 parents: [main],815 tree: before.tree,816 });817 }).pipe(Effect.provide(world))818 );819 });820821 describe("compose", () => {822 it.effect(823 "adds a decider's files to main's tree on a scratch ref, and leaves main alone",824 () =>825 Effect.gen(function* () {826 const lander = yield* Lander;827 const repos = yield* RepoHost;828 const { base, treeOf } = yield* project(start);829 const ask = `${Brand.configDir}/asks/x.ask.ts`;830 const check = "packages/p/test/x.test.ts";831832 const composed = yield* lander.compose({833 files: [834 { content: "export default {}\n", path: RepoPath.make(ask) },835 { content: "test('x')\n", path: RepoPath.make(check) },836 ],837 main: landed(base),838 repo: demo,839 });840841 const refs = yield* repos.refs(demo);842843 const commit = Option.getOrThrow(844 yield* repos.readCommit(demo, composed.commit)845 );846847 expect(composed.tree).toBe(848 yield* treeOf([849 ...start,850 [ask, "export default {}\n"],851 [check, "test('x')\n"],852 ])853 );854 expect({ parents: commit.parents, tree: commit.tree }).toStrictEqual({855 parents: [base],856 tree: composed.tree,857 });858 expect(composeRef(composed.tree)).toBe(859 `${Brand.refsPrefix}compose/${composed.tree}`860 );861 expect(refs.get(composeRef(composed.tree))).toBe(composed.commit);862 expect(refs.get(mainRef)).toBe(base);863 }).pipe(Effect.provide(world))864 );865866 it.effect(867 "composes the same files onto the same main to the same commit",868 () =>869 Effect.gen(function* () {870 const lander = yield* Lander;871 const { base } = yield* project(start);872873 const job = {874 files: [875 {876 content: "export default {}\n",877 path: RepoPath.make(`${Brand.configDir}/asks/x.ask.ts`),878 },879 ],880 main: landed(base),881 repo: demo,882 } as const;883884 const first = yield* lander.compose(job);885886 yield* advanceTo("2026-10-07T13:00:00Z");887888 expect(yield* lander.compose(job)).toStrictEqual(first);889 }).pipe(Effect.provide(world))890 );891 });892893 describe("bundleRules", () => {894 it.effect(895 "hands back every file under the config folder at a landed commit, as committed",896 () =>897 Effect.gen(function* () {898 const lander = yield* Lander;899 const entry = `${Brand.configDir}/project.ts`;900 const ask = `${Brand.configDir}/asks/x.ask.ts`;901902 const { base } = yield* project([903 [ask, "export default ask\n"],904 [entry, "export default project\n"],905 ["src/a.ts", "a1\n"],906 ]);907908 const bundle = yield* lander.bundleRules({909 at: landed(base),910 repo: demo,911 });912913 expect({914 entry: bundle.entry,915 modules: bundle.modules,916 }).toStrictEqual({917 entry,918 modules: {919 [ask]: "export default ask\n",920 [entry]: "export default project\n",921 },922 });923 }).pipe(Effect.provide(world))924 );925926 it.effect("hands back no modules when there is no config folder", () =>927 Effect.gen(function* () {928 const lander = yield* Lander;929 const { base } = yield* project(start);930931 const bundle = yield* lander.bundleRules({932 at: landed(base),933 repo: demo,934 });935936 expect({ entry: bundle.entry, modules: bundle.modules }).toStrictEqual({937 entry: `${Brand.configDir}/project.ts`,938 modules: {},939 });940 }).pipe(Effect.provide(world))941 );942 });943});
added:packages/project/test/lander-memory.test.ts+142 added
1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import {4 CommitSha,5 Handle,6 LandedSha,7 RepoName,8 RepoPath,9 RequestId,10 TreeSha,11} from "@repo/protocol/ids";12import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";13import { Effect, Option, Result } from "effect";1415import { Lander, Rebuild } from "../src/lander.ts";16import type { LandJob, MergeJob } from "../src/lander.ts";17import { LanderJob, LanderMemory } from "../src/lander/memory.ts";1819const sha = (n: number) => n.toString(16).padStart(40, "0");2021const demo = RepoName.make("demo");2223const main = LandedSha.make(CommitSha.make(sha(1)));2425const 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};3233const tree = TreeSha.make(sha(3));3435const 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};4950const stale = new StaleBase({51 base: mergeJob.base,52 conflicts: [RepoPath.make("src/a.ts")],53 main,54});5556const landedAt = LandedSha.make(CommitSha.make(sha(4)));5758describe("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 });6970 return Effect.gen(function* () {71 const lander = yield* Lander;7273 const merges = yield* Effect.forEach([1, 2, 3], () =>74 Effect.result(lander.merge(mergeJob))75 );7677 const lands = yield* Effect.forEach([1, 2, 3], () =>78 Effect.result(lander.land(landJob))79 );8081 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 );9495 it.effect("is VerifierBlocked for an operation with no script", () =>96 Effect.gen(function* () {97 const lander = yield* Lander;9899 expect(100 yield* Effect.flip(lander.bundleRules({ at: main, repo: demo }))101 ).toStrictEqual(new VerifierBlocked({}));102 }).pipe(Effect.provide(LanderMemory.layer({})))103 );104105 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;112113 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 });125126 return Effect.gen(function* () {127 const lander = yield* Lander;128129 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 });133134 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});