Skip to content
Myr

lander.test.ts

This file

Path

apps/sandbox/test/lander.test.ts

1,196 lines · 37.1 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Brand } from "@repo/brand";3import { MergeExit, MergeWire, Rebuild } from "@repo/project/lander/wire";4import { Verdict } from "@repo/protocol/domain/answer";5import { CommitSha, LandedSha, RepoPath } from "@repo/protocol/ids";6import type { TreeSha } from "@repo/protocol/ids";7import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";8import { sdkVersion } from "@repo/rules/rules-evaluator";9import { gitOk } from "@repo/testkit/git";10import { untouchable } from "@repo/testkit/untouchable";11import {12  Deferred,13  Effect,14  Exit,15  FileSystem,16  Layer,17  Logger,18  Option,19  Path,20  Predicate,21  Queue,22  Redacted,23  Schema,24  Semaphore,25} from "effect";2627import { Box } from "../src/box.ts";28import { Lander, landerJobs, runMerge } from "../src/lander.ts";29import { bundleRules, compose, land, merge } from "../src/lander/run.ts";30import { landScript, mergeScript } from "../src/lander/script.ts";31import {32  bob,33  box,34  bundleWire,35  config,36  configFolder,37  diverged,38  fork,39  inRepo,40  landedRefName,41  message,42  project,43  requestId,44  sdk,45  secret,46  startedWith,47  TestServices,48  verdictOn,49  world,50} from "./lander.fixtures.ts";51import type { Files, World } from "./lander.fixtures.ts";5253const mergeWire = (54  repos: World,55  job: {56    readonly base: CommitSha;57    readonly head: CommitSha;58    readonly main: LandedSha;59  }60) => ({61  fork: repos.remote(repos.fork),62  job: { ...job, fork, repo: project },63  main: repos.remote(repos.canonical),64});6566const landWire = (67  repos: World,68  job: {69    readonly base: CommitSha;70    readonly head: CommitSha;71    readonly main: LandedSha;72    readonly tree: TreeSha;73  }74) => ({75  fork: repos.remote(repos.fork),76  job: {77    author: bob,78    main: job.main,79    message,80    rebuild: Rebuild.cases.Merge.make({ base: job.base, fork, head: job.head }),81    repo: project,82    requestId,83    tree: job.tree,84    verdict: Option.some(verdictOn(job)),85  },86  main: repos.remote(repos.canonical),87});8889const commitIn = (repo: string, sha: string) =>90  Effect.gen(function* () {91    const shown = yield* gitOk(92      repo,93      "show",94      "--no-patch",95      "--format=%an <%ae>%n%cn <%ce>%n%P%n%T",96      sha97    );9899    const [author, committer, parents, tree] = shown.split("\n");100    const raw = yield* gitOk(repo, "cat-file", "commit", sha);101102    return {103      author,104      committer,105      message: raw.slice(raw.indexOf("\n\n") + 2),106      parents: parents?.split(" "),107      tree,108    };109  });110111const decodeNote = Schema.decodeEffect(Schema.fromJsonString(Verdict));112113const pushesMain = (argv: readonly string[]) =>114  argv.includes("push") && argv.at(-1)?.endsWith(":refs/heads/main") === true;115116const beforeMainIsPushed =117  (first: Effect.Effect<void>) =>118  (inner: Box["Service"]): Box["Service"] => ({119    ...inner,120    exec: (argv, options) =>121      pushesMain(argv)122        ? Effect.andThen(first, inner.exec(argv, options))123        : inner.exec(argv, options),124  });125126const movedBy = (repos: World, parent: CommitSha) =>127  Effect.gen(function* () {128    const other = yield* repos.commit(129      parent,130      { "README.md": "datekit, by someone else\n" },131      "Retitle the readme"132    );133134    yield* repos.push(repos.canonical, other);135136    return other;137  });138139interface Handed {140  readonly argv: readonly string[];141  readonly env: Readonly<Record<string, string>>;142}143144const recording =145  (handed: Handed[]) =>146  (inner: Box["Service"]): Box["Service"] => ({147    ...inner,148    exec: (argv, options = {}) =>149      Effect.andThen(150        Effect.sync(() => handed.push({ argv, env: { ...options.env } })),151        inner.exec(argv, options)152      ),153  });154155const mirrorRefused = (inner: Box["Service"]): Box["Service"] => ({156  ...inner,157  exec: (argv, options) =>158    argv.at(-1)?.endsWith(`:${landedRefName}`) === true159      ? Effect.succeed({160          exitCode: 1,161          stderr: "error: failed to push some refs\n",162          stdout: `!\t${argv.at(-1) ?? ""}\t[remote rejected] (refused)\nDone\n`,163        })164      : inner.exec(argv, options),165});166167/** A busy Artifacts answers one side-band error packet and no report. */168const busyOnMain = (inner: Box["Service"]): Box["Service"] => ({169  ...inner,170  exec: (argv, options) =>171    pushesMain(argv)172      ? Effect.succeed({173          exitCode: 128,174          stderr:175            "remote: artifacts_git_receive_pack_busy\n\nfatal: the remote end hung up unexpectedly\nerror: failed to push some refs\n",176          stdout: "",177        })178      : inner.exec(argv, options),179});180181const mainDeclined = (inner: Box["Service"]): Box["Service"] => ({182  ...inner,183  exec: (argv, options) =>184    pushesMain(argv)185      ? Effect.succeed({186          exitCode: 1,187          stderr: `remote: no push for ${secret}\nerror: failed to push some refs\n`,188          stdout: `!\t${argv.at(-1) ?? ""}\t[remote rejected] (pre-receive hook declined)\nDone\n`,189        })190      : inner.exec(argv, options),191});192193const tracing = (inner: Box["Service"]): Box["Service"] => ({194  ...inner,195  exec: (argv, options = {}) =>196    options.env?.GIT_CONFIG_VALUE_0 === undefined197      ? inner.exec(argv, options)198      : Effect.succeed({199          exitCode: 128,200          stderr: `> ${options.env.GIT_CONFIG_VALUE_0}\nfatal: ${argv.join(" ")}`,201          stdout: "",202        }),203});204205const keeping = (lines: string[]) =>206  Logger.layer([207    Logger.make((options) => {208      lines.push(JSON.stringify(Logger.formatStructured.log(options)));209    }),210  ]);211212interface Imported {213  readonly default: unknown;214}215216const importedFrom = (217  modules: Readonly<Record<string, string>>,218  file: string219) =>220  Effect.gen(function* () {221    const fs = yield* FileSystem.FileSystem;222    const path = yield* Path.Path;223    const root = yield* fs.makeTempDirectoryScoped({ prefix: "modules-" });224225    for (const [key, source] of Object.entries(modules)) {226      const at = path.join(root, key);227228      yield* fs.makeDirectory(path.dirname(at), { recursive: true });229      yield* fs.writeFileString(at, source);230    }231232    const target = path.join(root, file);233234    return yield* Effect.promise((): Promise<Imported> => import(target));235  });236237const SDK_NAMES = [`"${Brand.cliPackage}/rules"`, '"@repo/sdk"'];238239const pointedAtSdk = (source: string) => {240  let pointed = source;241242  for (const name of SDK_NAMES) {243    pointed = pointed.replaceAll(name, JSON.stringify(sdk.entry));244  }245246  return pointed;247};248249const asCommitted = (files: Files) =>250  Object.fromEntries(251    Object.entries(files).flatMap(([file, source]) =>252      source === null ? [] : [[file, pointedAtSdk(source)] as const]253    )254  );255256const dataOf = ({ default: definition }: Imported) =>257  JSON.stringify(definition);258259interface Claimant {260  readonly handle: string;261  readonly kind: string;262  readonly record: number;263  readonly territory: string;264  readonly vouched: boolean;265}266267const FUNCTIONS = Symbol.for("@repo/sdk/Functions");268269type Admit = (facts: Claimant) => boolean;270271const isAdmit = (rule: unknown): rule is Admit => Predicate.isFunction(rule);272273const admits = ({ default: definition }: Imported, facts: Claimant) => {274  const functions = Predicate.hasProperty(definition, FUNCTIONS)275    ? definition[FUNCTIONS]276    : undefined;277278  const admit = Predicate.hasProperty(functions, "admit")279    ? functions.admit280    : undefined;281282  return isAdmit(admit) ? admit(facts) : "no admit rule";283};284285const claimant = (record: number): Claimant => ({286  handle: "bob",287  kind: "fix",288  record,289  territory: ".",290  vouched: true,291});292293describe("the Lander's git", () => {294  describe(merge, () => {295    it.live(296      "merges a clean answer onto main: the tree git's own merge makes, the answer's changes, nothing written to canonical, and the merged commit kept on the fork for the Checker",297      () =>298        Effect.gen(function* () {299          const repos = yield* world;300          const { base, head, main } = yield* diverged(repos);301          const before = yield* repos.stateOf(repos.canonical);302303          const merged = yield* merge(304            mergeWire(repos, { base, head, main })305          ).pipe(Effect.provide(box(repos.work)), Effect.exit);306307          const tree = yield* repos.mergedTree(main, head);308309          const kept = yield* repos.revision(310            repos.fork,311            `${Brand.refsPrefix}merge/${tree}`312          );313314          expect(merged).toStrictEqual(315            Exit.succeed({316              changes: [317                {318                  after: yield* repos.blobAt(head, "src/date.ts"),319                  before: yield* repos.blobAt(base, "src/date.ts"),320                  path: RepoPath.make("src/date.ts"),321                  status: "modified",322                },323                {324                  after: yield* repos.blobAt(head, "test/iso.test.ts"),325                  path: RepoPath.make("test/iso.test.ts"),326                  status: "added",327                },328              ],329              tree,330            })331          );332          expect(yield* repos.stateOf(repos.canonical)).toStrictEqual(before);333          expect(334            yield* Effect.forEach(Option.toArray(kept), (commit) =>335              Effect.all([336                gitOk(repos.fork, "rev-parse", `${commit}^{tree}`),337                gitOk(repos.fork, "rev-parse", `${commit}^1`, `${commit}^2`),338              ])339            )340          ).toStrictEqual([[tree, `${main}\n${head}`]]);341        }).pipe(Effect.scoped, Effect.provide(TestServices))342    );343344    it.live(345      "refuses an answer that changed the same lines main did with StaleBase, naming the paths that conflict",346      () =>347        Effect.gen(function* () {348          const repos = yield* world;349          const { base, clash, main } = yield* diverged(repos);350351          const merged = yield* merge(352            mergeWire(repos, { base, head: clash, main })353          ).pipe(Effect.provide(box(repos.work)), Effect.exit);354355          expect(merged).toStrictEqual(356            Exit.fail(357              new StaleBase({358                base,359                conflicts: [RepoPath.make("src/date.ts")],360                main,361              })362            )363          );364        }).pipe(Effect.scoped, Effect.provide(TestServices))365    );366  });367368  describe(land, () => {369    it.live(370      "lands one commit on main by the answerer, committed by the platform, with its trailers, then the mirror ref and the verdict note",371      () =>372        Effect.gen(function* () {373          const repos = yield* world;374          const sides = yield* diverged(repos);375          const tree = yield* repos.mergedTree(sides.main, sides.head);376          const wire = landWire(repos, { ...sides, tree });377378          const landed = yield* land(wire).pipe(379            Effect.provide(box(repos.work)),380            Effect.exit381          );382383          const tip = CommitSha.make(384            yield* gitOk(repos.canonical, "rev-parse", "refs/heads/main")385          );386387          expect(landed).toStrictEqual(388            Exit.succeed({ pending: [], sha: LandedSha.make(tip) })389          );390          expect(yield* commitIn(repos.canonical, tip)).toStrictEqual({391            author: `bob <bob@users.${Brand.domain}>`,392            committer: `${Brand.name} <platform@${Brand.domain}>`,393            message: message.trim(),394            parents: [sides.main],395            tree,396          });397          expect(398            yield* repos.revision(repos.canonical, landedRefName)399          ).toStrictEqual(Option.some(tip));400          expect(401            yield* decodeNote(402              yield* gitOk(403                repos.canonical,404                "notes",405                `--ref=${Brand.slug}`,406                "show",407                tip408              )409            )410          ).toStrictEqual(Option.getOrThrow(wire.job.verdict));411        }).pipe(Effect.scoped, Effect.provide(TestServices))412    );413414    it.live(415      "blocks a land whose rebuilt tree is not the tree it was asked to land, and leaves main alone",416      () =>417        Effect.gen(function* () {418          const repos = yield* world;419          const sides = yield* diverged(repos);420          const checked = yield* repos.mergedTree(sides.main, sides.head);421422          // The tree of main itself: not what merging the head again makes.423          const tree = yield* repos.mergedTree(sides.main, sides.main);424425          expect(tree).not.toBe(checked);426427          const landed = yield* land(landWire(repos, { ...sides, tree })).pipe(428            Effect.provide(box(repos.work)),429            Effect.exit430          );431432          expect(landed).toStrictEqual(Exit.fail(new VerifierBlocked({})));433          expect(434            yield* repos.revision(repos.canonical, "refs/heads/main")435          ).toStrictEqual(Option.some(sides.main));436        }).pipe(Effect.scoped, Effect.provide(TestServices))437    );438439    it.live(440      "refuses a land onto a main that moved since the job's main with StaleBase, and leaves main where it moved",441      () =>442        Effect.gen(function* () {443          const repos = yield* world;444          const sides = yield* diverged(repos);445          const tree = yield* repos.mergedTree(sides.main, sides.head);446          const other = yield* movedBy(repos, sides.main);447448          const landed = yield* land(landWire(repos, { ...sides, tree })).pipe(449            Effect.provide(box(repos.work)),450            Effect.exit451          );452453          expect(landed).toStrictEqual(454            Exit.fail(455              new StaleBase({ base: sides.base, conflicts: [], main: other })456            )457          );458          expect(459            yield* Effect.all([460              repos.revision(repos.canonical, "refs/heads/main"),461              repos.revision(repos.canonical, landedRefName),462            ])463          ).toStrictEqual([Option.some(other), Option.none()]);464        }).pipe(Effect.scoped, Effect.provide(TestServices))465    );466467    it.live(468      "pushes main without force: when main moves between the Lander's fetch and its push, git refuses the push, the land is StaleBase, and the other commit stays",469      () =>470        Effect.gen(function* () {471          const repos = yield* world;472          const sides = yield* diverged(repos);473          const tree = yield* repos.mergedTree(sides.main, sides.head);474          const moved = yield* Deferred.make<CommitSha>();475476          const move = movedBy(repos, sides.main).pipe(477            Effect.flatMap((other) => Deferred.succeed(moved, other)),478            Effect.asVoid,479            Effect.provide(TestServices),480            Effect.orDie481          );482483          const landed = yield* land(landWire(repos, { ...sides, tree })).pipe(484            Effect.provide(box(repos.work, beforeMainIsPushed(move))),485            Effect.exit486          );487488          const other = yield* Deferred.await(moved);489490          expect(landed).toStrictEqual(491            Exit.fail(492              new StaleBase({ base: sides.base, conflicts: [], main: other })493            )494          );495          expect(496            yield* repos.revision(repos.canonical, "refs/heads/main")497          ).toStrictEqual(Option.some(other));498        }).pipe(Effect.scoped, Effect.provide(TestServices))499    );500501    it.live(502      "answers RepoBusy when Artifacts is busy with another push to the repo, and leaves main alone",503      () =>504        Effect.gen(function* () {505          const repos = yield* world;506          const sides = yield* diverged(repos);507          const tree = yield* repos.mergedTree(sides.main, sides.head);508509          const landed = yield* land(landWire(repos, { ...sides, tree })).pipe(510            Effect.provide(box(repos.work, busyOnMain)),511            Effect.exit512          );513514          expect(landed).toStrictEqual(Exit.fail(new RepoBusy({})));515          expect(516            yield* Effect.all([517              repos.revision(repos.canonical, "refs/heads/main"),518              repos.revision(repos.canonical, landedRefName),519            ])520          ).toStrictEqual([Option.some(sides.main), Option.none()]);521        }).pipe(Effect.scoped, Effect.provide(TestServices))522    );523524    it.live(525      "blocks a land whose push of main the remote refuses for a reason of its own, and logs what git said with the token taken out",526      () =>527        Effect.gen(function* () {528          const repos = yield* world;529          const sides = yield* diverged(repos);530          const tree = yield* repos.mergedTree(sides.main, sides.head);531          const lines: string[] = [];532533          const landed = yield* land(landWire(repos, { ...sides, tree })).pipe(534            Effect.provide(535              Layer.merge(box(repos.work, mainDeclined), keeping(lines))536            ),537            Effect.exit538          );539540          expect(landed).toStrictEqual(Exit.fail(new VerifierBlocked({})));541          expect(542            yield* repos.revision(repos.canonical, "refs/heads/main")543          ).toStrictEqual(Option.some(sides.main));544          expect([545            lines.filter(546              (line) =>547                line.includes("pre-receive hook declined") &&548                line.includes("no push for [token]")549            ).length,550            lines.filter((line) => line.includes(secret)),551          ]).toStrictEqual([1, []]);552        }).pipe(Effect.scoped, Effect.provide(TestServices))553    );554555    it.live(556      "keeps a landing whose mirror push fails: main has moved, the note is written, and the mirror comes back pending",557      () =>558        Effect.gen(function* () {559          const repos = yield* world;560          const sides = yield* diverged(repos);561          const tree = yield* repos.mergedTree(sides.main, sides.head);562563          const landed = yield* land(landWire(repos, { ...sides, tree })).pipe(564            Effect.provide(box(repos.work, mirrorRefused)),565            Effect.exit566          );567568          const tip = yield* repos.revision(repos.canonical, "refs/heads/main");569570          expect(landed).toStrictEqual(571            Exit.succeed({572              pending: ["mirror"],573              sha: LandedSha.make(Option.getOrThrow(tip)),574            })575          );576          expect(577            yield* Effect.all([578              repos.revision(repos.canonical, "refs/heads/main~1"),579              repos.revision(repos.canonical, landedRefName),580              Effect.map(581                repos.revision(repos.canonical, `refs/notes/${Brand.slug}`),582                Option.isSome583              ),584            ])585          ).toStrictEqual([Option.some(sides.main), Option.none(), true]);586        }).pipe(Effect.scoped, Effect.provide(TestServices))587    );588589    it.live(590      "lands a request once: landing it again finds its own commit by its Request-Id and writes only the bookkeeping that is missing",591      () =>592        Effect.gen(function* () {593          const repos = yield* world;594          const sides = yield* diverged(repos);595          const tree = yield* repos.mergedTree(sides.main, sides.head);596          const wire = landWire(repos, { ...sides, tree });597          const first = yield* land(wire).pipe(Effect.provide(box(repos.work)));598599          // The mirror and the note were lost after main moved.600          yield* gitOk(repos.canonical, "update-ref", "-d", landedRefName);601          yield* gitOk(602            repos.canonical,603            "update-ref",604            "-d",605            `refs/notes/${Brand.slug}`606          );607608          const again = yield* land(wire).pipe(609            Effect.provide(box(repos.work)),610            Effect.exit611          );612613          expect(again).toStrictEqual(Exit.succeed(first));614          expect(615            yield* Effect.all([616              repos.revision(repos.canonical, "refs/heads/main~1"),617              repos.revision(repos.canonical, landedRefName),618              Effect.map(619                repos.revision(repos.canonical, `refs/notes/${Brand.slug}`),620                Option.isSome621              ),622            ])623          ).toStrictEqual([624            Option.some(sides.main),625            Option.some(first.sha),626            true,627          ]);628        }).pipe(Effect.scoped, Effect.provide(TestServices))629    );630  });631632  describe(bundleRules, () => {633    it.live(634      "bundles the project module, the visibility module and each ask file with the sdk inlined, to the data and rules the committed folder gives, beside its other files",635      () =>636        Effect.gen(function* () {637          const repos = yield* world;638          const at = yield* startedWith(repos, configFolder);639640          const bundled = yield* bundleRules(bundleWire(repos, at)).pipe(641            Effect.provide(box(repos.work))642          );643644          const committed = asCommitted(configFolder);645646          expect({647            ...bundled,648            modules: Object.keys(bundled.modules).toSorted(),649          }).toStrictEqual({650            entry: config("project.ts"),651            modules: [652              config("asks/parse-iso.ask.ts"),653              expect.stringMatching(/^\.[^/]+\/chunk-\w+\.js$/u),654              config("project.ts"),655              config("visibility.ts"),656              config("vouched.td"),657            ],658            sdkVersion,659          });660          expect(bundled.modules[config("vouched.td")]).toBe("dora\nbob\n");661662          const visibilityModule = yield* importedFrom(663            bundled.modules,664            config("visibility.ts")665          );666667          const visibilityAsCommitted = yield* importedFrom(668            committed,669            config("visibility.ts")670          );671672          expect(dataOf(visibilityModule)).toStrictEqual(673            dataOf(visibilityAsCommitted)674          );675676          const projectModule = yield* importedFrom(677            bundled.modules,678            config("project.ts")679          );680681          const askModule = yield* importedFrom(682            bundled.modules,683            config("asks/parse-iso.ask.ts")684          );685686          const projectAsCommitted = yield* importedFrom(687            committed,688            config("project.ts")689          );690691          const askAsCommitted = yield* importedFrom(692            committed,693            config("asks/parse-iso.ask.ts")694          );695696          expect([dataOf(projectModule), dataOf(askModule)]).toStrictEqual([697            dataOf(projectAsCommitted),698            dataOf(askAsCommitted),699          ]);700          expect([701            admits(projectModule, claimant(2)),702            admits(projectModule, claimant(1)),703          ]).toStrictEqual([true, false]);704        }).pipe(Effect.scoped, Effect.provide(TestServices))705    );706707    it.live(708      "gives no modules for a repo with no config folder, so the project runs on the defaults",709      () =>710        Effect.gen(function* () {711          const repos = yield* world;712          const at = yield* startedWith(repos, {});713714          const bundled = yield* bundleRules(bundleWire(repos, at)).pipe(715            Effect.provide(box(repos.work)),716            Effect.exit717          );718719          expect(bundled).toStrictEqual(720            Exit.succeed({721              entry: `${Brand.configDir}/project.ts`,722              modules: {},723              sdkVersion,724            })725          );726        }).pipe(Effect.scoped, Effect.provide(TestServices))727    );728729    it.live(730      "never runs the folder's code while it bundles it: a macro import blocks the bundle and does not run",731      () =>732        Effect.gen(function* () {733          const repos = yield* world;734          const path = yield* Path.Path;735          const fs = yield* FileSystem.FileSystem;736          const marker = path.join(path.dirname(repos.work), "macro-ran");737738          const at = yield* startedWith(repos, {739            [`${Brand.configDir}/project.ts`]: [740              'import { stamp } from "./stamp.ts" with { type: "macro" };',741              "",742              "export default { stamp: stamp() };",743              "",744            ].join("\n"),745            [`${Brand.configDir}/stamp.ts`]: [746              "export const stamp = () => {",747              `  Bun.write(${JSON.stringify(marker)}, "ran");`,748              '  return "ran";',749              "};",750              "",751            ].join("\n"),752          });753754          const bundled = yield* bundleRules(bundleWire(repos, at)).pipe(755            Effect.provide(box(repos.work)),756            Effect.exit757          );758759          expect(bundled).toStrictEqual(Exit.fail(new VerifierBlocked({})));760          expect(yield* fs.exists(marker)).toBeFalsy();761        }).pipe(Effect.scoped, Effect.provide(TestServices))762    );763  });764  describe(compose, () => {765    it.live(766      "commits a maintainer's files onto main on a compose ref named by the tree, leaves main alone, and gives the same commit when asked again",767      () =>768        Effect.gen(function* () {769          const repos = yield* world;770          const sides = yield* diverged(repos);771          const ask = `${Brand.configDir}/asks/parse-iso.ask.ts`;772773          const wire = {774            job: {775              files: [776                { content: "export default {};\n", path: RepoPath.make(ask) },777                {778                  content: "expect(week(1)).toBe(1);\n",779                  path: RepoPath.make("test/iso.test.ts"),780                },781              ] as const,782              main: sides.main,783              repo: project,784            },785            main: repos.remote(repos.canonical),786          };787788          const composed = yield* compose(wire).pipe(789            Effect.provide(box(repos.work))790          );791792          const ref = `${Brand.refsPrefix}compose/${composed.tree}`;793794          expect(795            yield* Effect.all([796              repos.revision(repos.canonical, ref),797              repos.revision(repos.canonical, `${composed.commit}^`),798              repos.revision(repos.canonical, `${composed.commit}^{tree}`),799              gitOk(repos.canonical, "show", `${composed.commit}:${ask}`),800              gitOk(repos.canonical, "show", `${composed.commit}:README.md`),801              repos.revision(repos.canonical, "refs/heads/main"),802            ])803          ).toStrictEqual([804            Option.some(composed.commit),805            Option.some(sides.main),806            Option.some(composed.tree),807            "export default {};",808            "datekit",809            Option.some(sides.main),810          ]);811          expect(812            yield* compose(wire).pipe(813              Effect.provide(box(repos.work)),814              Effect.exit815            )816          ).toStrictEqual(Exit.succeed(composed));817        }).pipe(Effect.scoped, Effect.provide(TestServices))818    );819  });820821  describe("tokens", () => {822    it.live(823      "hands git each remote's token only as an http.extraHeader through GIT_CONFIG env: never in a URL, a command line, a result or a log",824      () =>825        Effect.gen(function* () {826          const repos = yield* world;827          const sides = yield* diverged(repos);828          const tree = yield* repos.mergedTree(sides.main, sides.head);829          const handed: Handed[] = [];830          const lines: string[] = [];831832          const recorded = Layer.merge(833            box(repos.work, recording(handed)),834            keeping(lines)835          );836837          const traced = Layer.merge(box(repos.work, tracing), keeping(lines));838839          const answer = {840            base: sides.base,841            head: sides.head,842            main: sides.main,843          };844845          const outcomes = [846            yield* merge(mergeWire(repos, answer)).pipe(847              Effect.provide(recorded),848              Effect.exit849            ),850            yield* land(landWire(repos, { ...sides, tree })).pipe(851              Effect.provide(recorded),852              Effect.exit853            ),854            yield* bundleRules(bundleWire(repos, sides.main)).pipe(855              Effect.provide(recorded),856              Effect.exit857            ),858          ];859860          const blocked = yield* merge(mergeWire(repos, answer)).pipe(861            Effect.provide(traced),862            Effect.exit863          );864865          const reaching = handed.filter(({ argv }) =>866            argv.some((part) => [repos.canonical, repos.fork].includes(part))867          );868869          expect(outcomes.map(({ _tag }) => _tag)).toStrictEqual([870            "Success",871            "Success",872            "Success",873          ]);874          expect(blocked).toStrictEqual(Exit.fail(new VerifierBlocked({})));875          expect(reaching.length).toBeGreaterThan(4);876          expect(877            reaching.map(({ env }) => [878              env.GIT_CONFIG_COUNT,879              env.GIT_CONFIG_KEY_0,880              env.GIT_CONFIG_VALUE_0,881            ])882          ).toStrictEqual(883            reaching.map(() => [884              "1",885              "http.extraHeader",886              `Authorization: Bearer ${secret}`,887            ])888          );889          expect(890            [891              ...handed.map(({ argv }) => argv.join(" ")),892              ...handed.flatMap((step) =>893                reaching.includes(step) ? [] : [JSON.stringify(step.env)]894              ),895              JSON.stringify([...outcomes, blocked]),896              ...lines,897            ].filter((text) => text.includes(secret))898          ).toStrictEqual([]);899        }).pipe(Effect.scoped, Effect.provide(TestServices))900    );901  });902});903904const RootManifest = Schema.fromJsonString(905  Schema.Struct({906    workspaces: Schema.Struct({907      catalog: Schema.Struct({ effect: Schema.String }),908    }),909  })910);911912describe("the land image", () => {913  it.effect(914    "installs the effect the repo's catalog pins beside its copy of the sdk, so a bundle inlines the effect the sdk was tested with",915    () =>916      Effect.gen(function* () {917        const fs = yield* FileSystem.FileSystem;918919        const dockerfile = yield* fs.readFileString(920          inRepo("apps/sandbox/images/land.Dockerfile")921        );922923        const manifest = yield* Schema.decodeEffect(RootManifest)(924          yield* fs.readFileString(inRepo("package.json"))925        );926927        expect(928          /\beffect@(?<version>\S+)/u.exec(dockerfile)?.groups?.version929        ).toBe(manifest.workspaces.catalog.effect);930      }).pipe(Effect.provide(TestServices))931  );932933  // A bare `bash` entrypoint exits at once with no stdin, which stops the934  // container and kills the first `exec` of every job (exit 137).935  it.effect.each(["check", "land"])(936    "keeps the %s container up until its Durable Object destroys it, since every command runs through exec",937    (image) =>938      Effect.gen(function* () {939        const fs = yield* FileSystem.FileSystem;940941        const dockerfile = yield* fs.readFileString(942          inRepo(`apps/sandbox/images/${image}.Dockerfile`)943        );944945        const finalStage = dockerfile.split(/^FROM /mu).at(-1) ?? "";946947        expect(/^CMD (?<command>.+)$/mu.exec(finalStage)?.groups?.command).toBe(948          '["sleep", "infinity"]'949        );950      }).pipe(Effect.provide(TestServices))951  );952});953954describe("the Lander's script, as data", () => {955  const main = LandedSha.make("1".repeat(40));956  const base = CommitSha.make("2".repeat(40));957  const head = CommitSha.make("3".repeat(40));958  const landing = CommitSha.make("4".repeat(40));959960  const remotes = {961    fork: "https://artifacts.invalid/datekit--parse-iso--bob.git",962    main: "https://artifacts.invalid/datekit.git",963  };964965  const merging = mergeScript(966    { base, fork, head, main, repo: project },967    remotes968  );969970  const pushes = landScript(971    { repo: project },972    remotes.main,973    landing,974    landedRefName975  );976977  const steps = [978    ...merging.fetch,979    merging.merge,980    merging.changes,981    pushes.main,982    pushes.mirror,983  ];984985  it("runs every git command with hooks off, no credential helper and no redirects, and names each remote only by its plain URL", () => {986    const gits = steps.filter(({ argv }) => argv[0] === "git");987988    expect(gits).toHaveLength(steps.length);989    expect(990      gits.map(({ argv }) =>991        [992          "core.hooksPath=/dev/null",993          "credential.helper=",994          "http.followRedirects=false",995        ].every((setting) => argv[argv.indexOf(setting) - 1] === "-c")996      )997    ).toStrictEqual(gits.map(() => true));998    expect(999      steps.flatMap(({ argv }) => argv.filter((part) => part.includes("://")))1000    ).toStrictEqual([remotes.main, remotes.fork, remotes.main, remotes.main]);1001  });10021003  it("merges with merge-tree on the answer's own base, writing to neither remote", () => {1004    expect(merging.merge.argv.slice(-8)).toStrictEqual([1005      "merge-tree",1006      "--write-tree",1007      "-z",1008      "--name-only",1009      "--no-messages",1010      `--merge-base=${base}`,1011      main,1012      head,1013    ]);1014    expect(1015      [...merging.fetch, merging.merge, merging.changes].filter(({ argv }) =>1016        argv.includes("push")1017      )1018    ).toStrictEqual([]);1019  });10201021  it("lands with a plain push of main, then the mirror ref in a push of its own: no force, no lease, no atomic push", () => {1022    expect([1023      pushes.main.argv.slice(-2),1024      pushes.mirror.argv.slice(-2),1025    ]).toStrictEqual([1026      [remotes.main, `${landing}:refs/heads/main`],1027      [remotes.main, `${landing}:${landedRefName}`],1028    ]);1029    expect(1030      [pushes.main, pushes.mirror].flatMap(({ argv }) =>1031        argv.filter((part) => /^\+|--force|--atomic|--mirror/u.test(part))1032      )1033    ).toStrictEqual([]);1034  });1035});10361037const idleMerge = {1038  fork: {1039    token: Redacted.make(secret),1040    url: "https://artifacts.invalid/datekit--parse-iso--bob.git",1041  },1042  job: {1043    base: CommitSha.make("1".repeat(40)),1044    fork,1045    head: CommitSha.make("2".repeat(40)),1046    main: LandedSha.make("3".repeat(40)),1047    repo: project,1048  },1049  main: {1050    token: Redacted.make(secret),1051    url: "https://artifacts.invalid/datekit.git",1052  },1053};10541055describe("the Lander's Durable Objects", () => {1056  it.live(1057    "runs each job in the Lander named by the job's canonical repo: the wire decoded, the job run, its Exit encoded",1058    () =>1059      Effect.gen(function* () {1060        const repos = yield* world;1061        const sides = yield* diverged(repos);1062        const named: string[] = [];1063        const jobs = landerJobs(box(repos.work), Semaphore.makeUnsafe(1));10641065        const env = {1066          LANDER: {1067            getByName: (name: string) => {1068              named.push(name);10691070              return jobs;1071            },1072          },1073        };10741075        const wire = yield* Schema.encodeEffect(MergeWire)(1076          mergeWire(repos, {1077            base: sides.base,1078            head: sides.clash,1079            main: sides.main,1080          })1081        );10821083        const merged = yield* Schema.decodeEffect(MergeExit)(1084          yield* Effect.promise(() => runMerge(env, wire))1085        );10861087        expect(named).toStrictEqual([project]);1088        expect(merged).toStrictEqual(1089          Exit.fail(1090            new StaleBase({1091              base: sides.base,1092              conflicts: [RepoPath.make("src/date.ts")],1093              main: sides.main,1094            })1095          )1096        );1097      }).pipe(Effect.scoped, Effect.provide(TestServices))1098  );10991100  it.live(1101    "runs one job at a time: a second job's first command waits until the first job is done",1102    () =>1103      Effect.gen(function* () {1104        const ran: string[] = [];1105        const finish = yield* Queue.unbounded<number>();11061107        // Every command waits until the test lets one finish, then exits 1.1108        const held = Layer.succeed(1109          Box,1110          Box.of({1111            destroy: () => Effect.void,1112            exec: (argv) =>1113              Effect.sync(() => ran.push(argv.join(" "))).pipe(1114                Effect.andThen(Queue.take(finish)),1115                Effect.as({ exitCode: 1, stderr: "", stdout: "" })1116              ),1117            writeFile: () => Effect.void,1118          })1119        );11201121        const jobs = landerJobs(held, Semaphore.makeUnsafe(1));1122        const wire = yield* Schema.encodeEffect(MergeWire)(idleMerge);1123        const first = jobs.merge(wire);1124        const second = jobs.merge(wire);11251126        yield* Effect.sleep("50 millis");11271128        const whileFirstRuns = ran.length;11291130        yield* Queue.offer(finish, 1);1131        yield* Effect.sleep("50 millis");11321133        const afterFirst = ran.length;11341135        yield* Queue.offer(finish, 2);11361137        const exits = yield* Effect.forEach([first, second], (outcome) =>1138          Effect.flatMap(1139            Effect.promise(() => outcome),1140            Schema.decodeEffect(MergeExit)1141          )1142        );11431144        expect([whileFirstRuns, afterFirst]).toStrictEqual([1, 2]);1145        expect(exits).toStrictEqual([1146          Exit.fail(new VerifierBlocked({})),1147          Exit.fail(new VerifierBlocked({})),1148        ]);1149      })1150  );11511152  it.live(1153    "starts its Durable Object's container from the land image with internet on",1154    () =>1155      Effect.gen(function* () {1156        const started: ContainerStartupOptions[] = [];11571158        const container = untouchable<Container>("container", {1159          exec: () =>1160            Promise.resolve(1161              untouchable<ExecProcess>("process", {1162                output: () =>1163                  Promise.resolve({1164                    exitCode: 1,1165                    stderr: new ArrayBuffer(0),1166                    stdout: new ArrayBuffer(0),1167                  }),1168              })1169            ),1170          images: { check: "check-image", land: "land-image" },1171          running: false,1172          start: (options) => {1173            if (options !== undefined) {1174              started.push(options);1175            }1176          },1177        });11781179        const lander = new Lander(1180          untouchable<DurableObjectState>("ctx", { container }),1181          untouchable<Env>("env")1182        );11831184        const wire = yield* Schema.encodeEffect(MergeWire)(idleMerge);11851186        const merged = yield* Schema.decodeEffect(MergeExit)(1187          yield* Effect.promise(() => lander.merge(wire))1188        );11891190        expect(merged).toStrictEqual(Exit.fail(new VerifierBlocked({})));1191        expect(started).toStrictEqual([1192          { enableInternet: true, image: "land-image", instance: "standard-2" },1193        ]);1194      })1195  );1196});