Skip to content
Myr

isogit.ts

This file

Path

packages/project/src/lander/isogit.ts

904 lines · 24.9 KiB · TypeScript

Last changed by

Merge build/comments-project into mainoscabrielbefore adoption49efd2a

History of this file

Take it

1import {2  BranchName,3  ObjectId,4  RefName,5  RefOutcome,6  RepoHost,7  Revision,8} from "@repo/artifacts/repo-host";9import type {10  PushSource,11  RefUpdate,12  RepoNotFound,13  TreeEntry,14} from "@repo/artifacts/repo-host";15import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";16import { Brand } from "@repo/brand";17import { noteCommit, notesRef } from "@repo/git/notes";18import { authorLine, committerLine, parseTrailers } from "@repo/git/trailers";19import type { GitIdentity } from "@repo/git/trailers";20import { treeDiff } from "@repo/git/tree-diff";21import type { Verdict } from "@repo/protocol/domain/answer";22import { CommitSha, LandedSha, RepoPath, TreeSha } from "@repo/protocol/ids";23import type { RepoName, RequestId } from "@repo/protocol/ids";24import { RepoBusy, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";25import { sdkVersion } from "@repo/rules/rules-evaluator";26import type { ConfigBundle } from "@repo/rules/rules-evaluator";27import { Array, Clock, DateTime, Effect, Layer, Option, Order } from "effect";28import {29  Errors,30  init,31  merge as mergeHistories,32  readTree as readScratchTree,33  writeBlob,34  writeCommit,35  writeRef,36  writeTree,37} from "isomorphic-git";3839import { composeRef, Lander, landedRef, Rebuild } from "../lander.ts";40import type {41  Bookkeeping,42  BundleJob,43  ComposedFile,44  ComposeJob,45  LandJob,46  MergeJob,47} from "../lander.ts";4849const mainRef = RefName.make("refs/heads/main");5051const mainBranch = BranchName.make("main");5253// How far back from main's tip a second land looks for the first one's commit.54const LOOKBACK = 16;5556// git's test for a binary file: a NUL among its first bytes.57const SNIFF = 8000;5859const blocked = () => new VerifierBlocked({});6061const unlessLost = <A, R>(62  effect: Effect.Effect<A, RepoNotFound, R>63): Effect.Effect<A, VerifierBlocked, R> => Effect.mapError(effect, blocked);6465const found = <A, R>(66  read: Effect.Effect<Option.Option<A>, RepoNotFound, R>67): Effect.Effect<A, VerifierBlocked, R> =>68  read.pipe(69    unlessLost,70    Effect.flatMap(71      Option.match({72        onNone: () => Effect.fail(blocked()),73        onSome: Effect.succeed,74      })75    )76  );7778const commitIn = (repo: RepoName, sha: CommitSha) =>79  found(RepoHost.use((host) => host.readCommit(repo, sha)));8081const treeIn = (repo: RepoName, tree: ObjectId) =>82  found(RepoHost.use((host) => host.readTree(repo, tree)));8384const blobIn = (repo: RepoName, blob: ObjectId) =>85  found(RepoHost.use((host) => host.readBlob(repo, blob)));8687const refsIn = (repo: RepoName) =>88  RepoHost.use((host) => host.refs(repo)).pipe(unlessLost);8990const pushOne = (repo: RepoName, source: PushSource, update: RefUpdate) =>91  RepoHost.use((host) => host.push(repo, source, [update])).pipe(92    Effect.map((outcomes) => Option.fromNullishOr(outcomes[0]))93  );9495const moves = (outcome: Option.Option<RefOutcome>) =>96  Option.exists(outcome, RefOutcome.$is("Updated"))97    ? Effect.void98    : Effect.fail(blocked());99100const seconds = Effect.map(Clock.currentTimeMillis, (millis) =>101  Math.floor(millis / 1000)102);103104const git = <A>(run: () => Promise<A>) =>105  Effect.tryPromise(run).pipe(Effect.orDie);106107const signed = (who: GitIdentity, at: number) => ({108  email: who.email,109  name: who.name,110  timestamp: at,111  timezoneOffset: 0,112});113114/** A copy of an object must keep its id, or the push would name one it lacks. */115const kept = (id: ObjectId, made: ObjectId) =>116  made === id ? Effect.void : Effect.die(`copying ${id} produced ${made}`);117118const scratch = Effect.gen(function* () {119  const source: PushSource = { fs: memoryFs(), gitdir: "/lander.git" };120121  yield* git(() => init({ ...source, bare: true, defaultBranch: "main" }));122123  const blob = (bytes: Uint8Array) =>124    Effect.map(125      git(() => writeBlob({ ...source, blob: bytes })),126      (oid) => ObjectId.make(oid)127    );128129  const tree = (entries: readonly TreeEntry[]) =>130    Effect.map(131      git(() =>132        writeTree({133          ...source,134          tree: entries.map(({ mode, name, sha, type }) => ({135            mode,136            oid: sha,137            path: name,138            type,139          })),140        })141      ),142      (oid) => ObjectId.make(oid)143    );144145  const commit = (input: {146    readonly tree: ObjectId;147    readonly parents: readonly CommitSha[];148    readonly author: GitIdentity;149    readonly message: string;150    readonly at: number;151  }) =>152    Effect.map(153      git(() =>154        writeCommit({155          ...source,156          commit: {157            author: signed(input.author, input.at),158            committer: signed(committerLine, input.at),159            message: input.message,160            parent: [...input.parents],161            tree: input.tree,162          },163        })164      ),165      (oid) => CommitSha.make(oid)166    );167168  const fileCommit = (169    bytes: Option.Option<Uint8Array>,170    parents: readonly CommitSha[]171  ) =>172    Effect.gen(function* () {173      const files = yield* Option.match(bytes, {174        onNone: () => Effect.succeed([]),175        onSome: (content) =>176          Effect.map(blob(content), (sha) => [177            { mode: "100644", name: "file", sha, type: "blob" } as const,178          ]),179      });180181      return yield* commit({182        at: 0,183        author: committerLine,184        message: "merge\n",185        parents,186        tree: yield* tree(files),187      });188    });189190  const lines = (191    base: Option.Option<Uint8Array>,192    ours: Uint8Array,193    theirs: Uint8Array194  ) =>195    Effect.gen(function* () {196      const start = yield* fileCommit(base, []);197198      const tips = {199        "refs/merge/ours": yield* fileCommit(Option.some(ours), [start]),200        "refs/merge/theirs": yield* fileCommit(Option.some(theirs), [start]),201      };202203      yield* Effect.forEach(Object.entries(tips), ([ref, value]) =>204        git(() => writeRef({ ...source, force: true, ref, value }))205      );206207      const merged = yield* Effect.tryPromise(() =>208        mergeHistories({209          ...source,210          abortOnConflict: true,211          author: signed(committerLine, 0),212          committer: signed(committerLine, 0),213          fastForward: false,214          message: "merge",215          noUpdateBranch: true,216          ours: "refs/merge/ours",217          theirs: "refs/merge/theirs",218        })219      ).pipe(220        Effect.map(({ tree: root }) => Option.fromNullishOr(root)),221        Effect.catchIf(222          ({ cause }) =>223            cause instanceof Errors.MergeConflictError ||224            cause instanceof Errors.MergeNotSupportedError,225          () => Effect.succeedNone226        ),227        Effect.orDie228      );229230      if (Option.isNone(merged)) {231        return Option.none();232      }233234      const { tree: entries } = yield* git(() =>235        readScratchTree({ ...source, oid: merged.value })236      );237238      return Option.map(Option.fromNullishOr(entries[0]), ({ oid }) =>239        ObjectId.make(oid)240      );241    });242243  return { blob, commit, lines, source, tree };244});245246type Scratch = Effect.Success<typeof scratch>;247248const isBinary = (bytes: Uint8Array) => bytes.subarray(0, SNIFF).includes(0);249250const sameEntry = (one: TreeEntry | undefined, other: TreeEntry | undefined) =>251  one?.sha === other?.sha && one?.mode === other?.mode;252253const isFile = (entry: TreeEntry | undefined) =>254  entry?.mode === "100644" || entry?.mode === "100755";255256const folderOf = (entry: TreeEntry | undefined) =>257  entry?.type === "tree" ? Option.some(entry.sha) : Option.none();258259const byName = (entries: readonly TreeEntry[]) =>260  new Map(entries.map((entry) => [entry.name, entry]));261262const entriesAt = (repo: RepoName, tree: Option.Option<ObjectId>) =>263  Option.match(tree, {264    onNone: () => Effect.succeed<readonly TreeEntry[]>([]),265    onSome: (id) => treeIn(repo, id),266  });267268interface Sides {269  readonly canonical: RepoName;270  readonly fork: RepoName;271}272273interface MergedTree {274  readonly entries: readonly TreeEntry[];275  readonly conflicts: readonly string[];276}277278const taken = (entry: TreeEntry | undefined): MergedTree => ({279  conflicts: [],280  entries: entry === undefined ? [] : [entry],281});282283const conflict = (path: string): MergedTree => ({284  conflicts: [path],285  entries: [],286});287288const adopt = (289  sides: Sides,290  into: Scratch,291  theirs: TreeEntry,292  base: TreeEntry | undefined293): Effect.Effect<void, VerifierBlocked, RepoHost> => {294  if (sameEntry(theirs, base) || theirs.type === "commit") {295    return Effect.void;296  }297298  if (theirs.type === "blob") {299    return blobIn(sides.fork, theirs.sha).pipe(300      Effect.flatMap(into.blob),301      Effect.flatMap((made) => kept(theirs.sha, made))302    );303  }304305  return Effect.gen(function* () {306    const children = yield* treeIn(sides.fork, theirs.sha);307    const before = byName(yield* entriesAt(sides.fork, folderOf(base)));308309    yield* Effect.forEach(children, (child) =>310      adopt(sides, into, child, before.get(child.name))311    );312    yield* kept(theirs.sha, yield* into.tree(children));313  });314};315316const mergedMode = (317  base: TreeEntry | undefined,318  ours: TreeEntry,319  theirs: TreeEntry320): Option.Option<TreeEntry["mode"]> => {321  if (ours.mode === theirs.mode || base?.mode === theirs.mode) {322    return Option.some(ours.mode);323  }324325  return base?.mode === ours.mode ? Option.some(theirs.mode) : Option.none();326};327328const mergeFile = (329  sides: Sides,330  into: Scratch,331  name: string,332  {333    base,334    ours,335    theirs,336  }: Record<"ours" | "theirs", TreeEntry> & {337    readonly base: TreeEntry | undefined;338  }339): Effect.Effect<Option.Option<TreeEntry>, VerifierBlocked, RepoHost> =>340  Effect.gen(function* () {341    const mode = mergedMode(base, ours, theirs);342343    if (Option.isNone(mode)) {344      return Option.none();345    }346347    const file = (sha: ObjectId): TreeEntry => ({348      mode: mode.value,349      name,350      sha,351      type: "blob",352    });353354    if (ours.sha === theirs.sha || base?.sha === theirs.sha) {355      return Option.some(file(ours.sha));356    }357358    if (base?.sha === ours.sha) {359      yield* adopt(sides, into, theirs, base);360361      return Option.some(file(theirs.sha));362    }363364    // Symlinks and submodules that both sides changed are not text to merge.365    if (!(isFile(ours) && isFile(theirs))) {366      return Option.none();367    }368369    const [before, mine, yours] = yield* Effect.all([370      base !== undefined && isFile(base)371        ? Effect.asSome(blobIn(sides.fork, base.sha))372        : Effect.succeedNone,373      blobIn(sides.canonical, ours.sha),374      blobIn(sides.fork, theirs.sha),375    ]);376377    if ([...Option.toArray(before), mine, yours].some(isBinary)) {378      return Option.none();379    }380381    return Option.map(yield* into.lines(before, mine, yours), file);382  });383384const mergeTrees = (385  sides: Sides,386  into: Scratch,387  prefix: string,388  trees: Record<"base" | "ours" | "theirs", Option.Option<ObjectId>>389): Effect.Effect<MergedTree, VerifierBlocked, RepoHost> =>390  Effect.gen(function* () {391    const [base, ours, theirs] = yield* Effect.all([392      Effect.map(entriesAt(sides.fork, trees.base), byName),393      Effect.map(entriesAt(sides.canonical, trees.ours), byName),394      Effect.map(entriesAt(sides.fork, trees.theirs), byName),395    ]);396397    const names = Array.sort(398      new Set([...base.keys(), ...ours.keys(), ...theirs.keys()]),399      Order.String400    );401402    const merged = yield* Effect.forEach(403      names,404      (name): Effect.Effect<MergedTree, VerifierBlocked, RepoHost> => {405        const b = base.get(name);406        const o = ours.get(name);407        const t = theirs.get(name);408        const path = `${prefix}${name}`;409410        if (sameEntry(o, t) || sameEntry(b, t)) {411          return Effect.succeed(taken(o));412        }413414        if (sameEntry(b, o)) {415          return t === undefined416            ? Effect.succeed(taken(t))417            : Effect.as(adopt(sides, into, t, b), taken(t));418        }419420        if (o?.type === "tree" && t?.type === "tree") {421          return Effect.gen(function* () {422            const inner = yield* mergeTrees(sides, into, `${path}/`, {423              base: folderOf(b),424              ours: Option.some(o.sha),425              theirs: Option.some(t.sha),426            });427428            if (inner.conflicts.length > 0 || inner.entries.length === 0) {429              return { conflicts: inner.conflicts, entries: [] };430            }431432            const sha = yield* into.tree(inner.entries);433434            return taken({ mode: "040000", name, sha, type: "tree" });435          });436        }437438        if (o?.type === "blob" && t?.type === "blob") {439          return mergeFile(sides, into, name, {440            base: b?.type === "blob" ? b : undefined,441            ours: o,442            theirs: t,443          }).pipe(444            Effect.map(445              Option.match({446                onNone: () => conflict(path),447                onSome: taken,448              })449            )450          );451        }452453        return Effect.succeed(conflict(path));454      }455    );456457    return {458      conflicts: merged.flatMap(({ conflicts }) => conflicts),459      entries: merged.flatMap(({ entries }) => entries),460    };461  });462463const mergeOnto = (into: Scratch, job: MergeJob) =>464  Effect.gen(function* () {465    const [base, ours, theirs] = yield* Effect.all([466      commitIn(job.fork, job.base),467      commitIn(job.repo, job.main),468      commitIn(job.fork, job.head),469    ]);470471    const merged = yield* mergeTrees(472      { canonical: job.repo, fork: job.fork },473      into,474      "",475      {476        base: Option.some(base.tree),477        ours: Option.some(ours.tree),478        theirs: Option.some(theirs.tree),479      }480    );481482    // Sorted as whole paths: the walk's folder-by-folder order puts483    // `src/a.ts` before `src-x.ts`, which a sort by path does not.484    if (merged.conflicts.length > 0) {485      return yield* new StaleBase({486        base: job.base,487        conflicts: Array.sort(merged.conflicts, Order.String).map((path) =>488          RepoPath.make(path)489        ),490        main: job.main,491      });492    }493494    return {495      base: TreeSha.make(base.tree),496      head: TreeSha.make(theirs.tree),497      tree: TreeSha.make(yield* into.tree(merged.entries)),498    };499  });500501interface Placed {502  readonly segments: readonly string[];503  readonly content: string;504}505506const placed = ({ content, path }: ComposedFile) => {507  const segments = path.split("/");508509  return segments.every((segment) => !["", ".", "..", ".git"].includes(segment))510    ? Effect.succeed<Placed>({ content, segments })511    : Effect.die(`${path} cannot name a file in a repo`);512};513514const placeFiles = (515  repo: RepoName,516  into: Scratch,517  prefix: string,518  tree: Option.Option<ObjectId>,519  files: readonly Placed[]520): Effect.Effect<ObjectId, VerifierBlocked, RepoHost> =>521  Effect.gen(function* () {522    const entries = byName(yield* entriesAt(repo, tree));523    const groups = Array.groupBy(files, ({ segments }) => segments[0] ?? "");524525    for (const [name, group] of Object.entries(groups)) {526      const existing = entries.get(name);527      const path = `${prefix}${name}`;528      const inside = group.filter(({ segments }) => segments.length > 1);529      const content = group.findLast(({ segments }) => segments.length === 1);530531      if (content === undefined) {532        if (existing !== undefined && existing.type !== "tree") {533          return yield* Effect.die(534            `${path} cannot be both a file and a folder`535          );536        }537538        const sha = yield* placeFiles(539          repo,540          into,541          `${path}/`,542          folderOf(existing),543          inside.map((file) => ({ ...file, segments: file.segments.slice(1) }))544        );545546        entries.set(name, { mode: "040000", name, sha, type: "tree" });547      } else {548        if (549          inside.length > 0 ||550          (existing !== undefined && !isFile(existing))551        ) {552          return yield* Effect.die(553            `${path} cannot be both a file and a folder`554          );555        }556557        entries.set(name, {558          mode: existing?.mode ?? "100644",559          name,560          sha: yield* into.blob(new TextEncoder().encode(content.content)),561          type: "blob",562        });563      }564    }565566    return yield* into.tree([...entries.values()]);567  });568569const composeOnto = (570  into: Scratch,571  repo: RepoName,572  main: CommitSha,573  files: readonly ComposedFile[]574) =>575  Effect.gen(function* () {576    const commit = yield* commitIn(repo, main);577    const paths = yield* Effect.forEach(files, placed);578579    return TreeSha.make(580      yield* placeFiles(repo, into, "", Option.some(commit.tree), paths)581    );582  });583584const rebuilt = (into: Scratch, job: LandJob) =>585  Rebuild.$match(job.rebuild, {586    Compose: ({ files }) => composeOnto(into, job.repo, job.main, files),587    Existing: ({ commit }) =>588      Effect.map(commitIn(job.repo, commit), ({ tree }) => TreeSha.make(tree)),589    Merge: ({ base, fork, head }) =>590      Effect.map(591        mergeOnto(into, { base, fork, head, main: job.main, repo: job.repo }),592        ({ tree }) => tree593      ),594  });595596const requestIdOf = (message: string) =>597  parseTrailers(message).find(({ key }) => key.toLowerCase() === "request-id")598    ?.value;599600const carriesRequest = (message: string, requestId: RequestId) =>601  requestIdOf(message) === requestId602    ? Effect.void603    : Effect.die(`a landing's message must carry Request-Id: ${requestId}`);604605const landedBefore = (job: LandJob) =>606  Effect.gen(function* () {607    const history = yield* RepoHost.use((host) =>608      host.log(job.repo, Revision.Branch({ name: mainBranch }), LOOKBACK)609    ).pipe(unlessLost);610611    const mine = Array.takeWhile(history, ({ sha }) => sha !== job.main).find(612      ({ message, parents }) =>613        parents[0] === job.main && requestIdOf(message) === job.requestId614    );615616    return Option.fromNullishOr(mine?.sha);617  });618619const mirror = (repo: RepoName, landing: CommitSha) =>620  Effect.gen(function* () {621    const refs = yield* refsIn(repo);622    const current = Option.fromNullishOr(refs.get(landedRef));623624    // A later landing moved main on, and its own mirror supersedes this one.625    if (refs.get(mainRef) !== landing || Option.contains(current, landing)) {626      return;627    }628629    const empty = yield* scratch;630631    yield* moves(632      yield* pushOne(repo, empty.source, {633        from: current,634        ref: landedRef,635        to: landing,636      })637    );638  });639640const noted = (641  repo: RepoName,642  tip: Option.Option<CommitSha>,643  target: CommitSha644) =>645  Option.match(tip, {646    onNone: () => Effect.succeed(false),647    onSome: (sha) =>648      Effect.gen(function* () {649        const commit = yield* commitIn(repo, sha);650        const entries = yield* treeIn(repo, commit.tree);651652        return entries.some(({ name }) => name === target);653      }),654  });655656const note = (repo: RepoName, landing: CommitSha, verdict: Verdict) =>657  Effect.gen(function* () {658    const refs = yield* refsIn(repo);659    const parent = Option.fromNullishOr(refs.get(notesRef));660661    if (yield* noted(repo, parent, landing)) {662      return;663    }664665    const { commit, source } = yield* noteCommit({666      notesParent: parent,667      now: yield* DateTime.now,668      repo,669      target: landing,670      verdict,671    });672673    yield* moves(674      yield* pushOne(repo, source, { from: parent, ref: notesRef, to: commit })675    );676  });677678const attempt = <E>(679  item: Bookkeeping,680  write: Effect.Effect<void, E, RepoHost>681) =>682  write.pipe(683    Effect.as(Option.none<Bookkeeping>()),684    Effect.catchCause((cause) =>685      Effect.as(686        Effect.logWarning(`a landing's ${item} was not written`, cause),687        Option.some(item)688      )689    )690  );691692// Mirror ref then verdict note, each in its own push. Neither fails the landing;693// what was not written comes back pending, and landing the job again writes it.694const settle = (job: LandJob, landing: CommitSha) =>695  Effect.gen(function* () {696    const mirrored = yield* attempt("mirror", mirror(job.repo, landing));697698    const noteWritten = yield* Option.match(job.verdict, {699      onNone: () => Effect.succeedNone,700      onSome: (verdict) => attempt("notes", note(job.repo, landing, verdict)),701    });702703    return {704      pending: Array.getSomes([mirrored, noteWritten]),705      sha: LandedSha.make(landing),706    };707  });708709const baseOf = (job: LandJob) =>710  Rebuild.$match(job.rebuild, {711    Compose: () => job.main,712    Existing: () => job.main,713    Merge: ({ base }) => base,714  });715716const moved = (job: LandJob, tip: Option.Option<CommitSha>) =>717  Effect.gen(function* () {718    const earlier = yield* landedBefore(job);719720    if (Option.isSome(earlier)) {721      return yield* settle(job, earlier.value);722    }723724    return yield* new StaleBase({725      base: baseOf(job),726      conflicts: [],727      main: Option.getOrElse(tip, () => job.main),728    });729  });730731const land = (job: LandJob) =>732  Effect.gen(function* () {733    yield* carriesRequest(job.message, job.requestId);734735    const tip = Option.fromNullishOr((yield* refsIn(job.repo)).get(mainRef));736737    if (!Option.contains(tip, job.main)) {738      return yield* moved(job, tip);739    }740741    const into = yield* scratch;742    const tree = yield* rebuilt(into, job);743744    if (tree !== job.tree) {745      return yield* blocked();746    }747748    const commit = yield* into.commit({749      at: yield* seconds,750      author: authorLine(job.author),751      message: job.message,752      parents: [job.main],753      tree: ObjectId.make(tree),754    });755756    // Never forced: if main moved since `job.main`, this push is refused.757    const outcome = yield* pushOne(job.repo, into.source, {758      from: Option.some(job.main),759      ref: mainRef,760      to: commit,761    }).pipe(762      Effect.catchTags({763        HostBusy: () => Effect.fail(new RepoBusy({})),764        RepoNotFound: () => Effect.fail(blocked()),765      })766    );767768    return Option.exists(outcome, RefOutcome.$is("Updated"))769      ? yield* settle(job, commit)770      : yield* moved(771          job,772          Option.flatMap(outcome, (stale) =>773            RefOutcome.$is("Stale")(stale) ? stale.tip : Option.none()774          )775        );776  });777778const compose = (job: ComposeJob) =>779  Effect.gen(function* () {780    const into = yield* scratch;781    const tree = yield* composeOnto(into, job.repo, job.main, job.files);782    const ref = composeRef(tree);783    const existing = Option.fromNullishOr((yield* refsIn(job.repo)).get(ref));784785    // Composed before onto the same main: the commit a Checker already has.786    if (Option.isSome(existing)) {787      const before = yield* commitIn(job.repo, existing.value);788789      if (790        before.tree === ObjectId.make(tree) &&791        before.parents[0] === job.main792      ) {793        return { commit: existing.value, tree };794      }795    }796797    const commit = yield* into.commit({798      at: yield* seconds,799      author: committerLine,800      message: "Compose files onto main for a check\n",801      parents: [job.main],802      tree: ObjectId.make(tree),803    });804805    yield* pushOne(job.repo, into.source, {806      from: existing,807      ref,808      to: commit,809    }).pipe(810      Effect.catchTags({811        HostBusy: () => Effect.fail(blocked()),812        RepoNotFound: () => Effect.fail(blocked()),813      }),814      Effect.flatMap(moves)815    );816817    return { commit, tree };818  });819820const filesUnder = (821  repo: RepoName,822  tree: ObjectId,823  prefix: string824): Effect.Effect<825  readonly (readonly [string, string])[],826  VerifierBlocked,827  RepoHost828> =>829  Effect.gen(function* () {830    const entries = yield* treeIn(repo, tree);831832    const nested = yield* Effect.forEach(entries, (entry) => {833      const path = `${prefix}${entry.name}`;834835      if (entry.type === "tree") {836        return filesUnder(repo, entry.sha, `${path}/`);837      }838839      return isFile(entry)840        ? Effect.map(blobIn(repo, entry.sha), (bytes) => [841            [path, new TextDecoder().decode(bytes)] as const,842          ])843        : Effect.succeed([]);844    });845846    return nested.flat();847  });848849const configFolder = (repo: RepoName, root: ObjectId) =>850  Effect.reduce(851    Brand.configDir.split("/"),852    (): Option.Option<ObjectId> => Option.some(root),853    (folder, segment) =>854      Option.match(folder, {855        onNone: () => Effect.succeedNone,856        onSome: (id) =>857          Effect.map(treeIn(repo, id), (entries) =>858            folderOf(entries.find(({ name }) => name === segment))859          ),860      })861  );862863const bundleRules = (job: BundleJob) =>864  Effect.gen(function* () {865    const commit = yield* commitIn(job.repo, job.at);866    const folder = yield* configFolder(job.repo, commit.tree);867868    const files = yield* Option.match(folder, {869      onNone: () => Effect.succeed([]),870      onSome: (tree) => filesUnder(job.repo, tree, `${Brand.configDir}/`),871    });872873    return {874      entry: `${Brand.configDir}/project.ts`,875      modules: Object.fromEntries(files),876      sdkVersion,877    } satisfies ConfigBundle;878  });879880const merge = (job: MergeJob) =>881  Effect.gen(function* () {882    const into = yield* scratch;883    const { base, head, tree } = yield* mergeOnto(into, job);884885    // What the answer changed against its own base, not what main did.886    const changes = yield* treeDiff(job.fork, base, head).pipe(unlessLost);887888    return { changes, tree };889  });890891export const LanderIsogit: Layer.Layer<Lander, never, RepoHost> = Layer.effect(892  Lander,893  Effect.gen(function* () {894    const host = yield* RepoHost;895    const provided = Effect.provideService(RepoHost, host);896897    return Lander.of({898      bundleRules: (job) => provided(bundleRules(job)),899      compose: (job) => provided(compose(job)),900      land: (job) => provided(land(job)),901      merge: (job) => provided(merge(job)),902    });903  })904);