iterate.com / git

git clone https://git.iterate.com/repos/git

git / tests / local-mind.mjsmain at 517348b

// tests/local-mind.mjs — A MIND FROM FOLDERS ON THIS MACHINE. It answers what the git app asks of
// the mind (../app.ts, ../pages.ts, ../pulls.ts): the repo verbs they call, a context's events, a
// kv, and who is a member. Each answer about a repo comes from git itself, run in the folder that
// holds the repo. serve.mjs shows the app over copies of the repos cloned beside this one, and
// the tests over repos they make.
import { execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

const MAIN = "refs/heads/main";

/** `folders`: where each repo is, by its path in the mind (`/repos/<name>`). `member`: the
 *  visitor's address when they are a member, null when they are not. `remote`: where git's own
 *  smart HTTP serves the folders (git-http.mjs `gitServer`), which is what Cloudflare Artifacts is
 *  to the mind: only what reads or writes a tag asks for it (../releases.ts).
 *
 *  What it gives back: `getItx()`, the mind's own itx, as the app's code holds it; `as(address)`,
 *  the itx of a member's page, whose events are stamped with that member; `kv`, the mind's kv as
 *  the app left it; `events`, each context's log by path; and `asked`, each call the app made of
 *  a repo or of the list, in order (`files /repos/kernel`). */
export function localMind({ folders, member, remote }) {
  const kv = {};
  const asked = [];
  // each token that was minted, as `<scope> <repo>`
  const minted = [];
  const events = {};
  // each event a minute after the one before, from noon on 24 Nov 2026
  let minutes = 0;

  const git = (repo, args, options) =>
    execFileSync("git", ["-C", folders[repo], ...args], { maxBuffer: 2 ** 30, ...options });
  const said = (repo, args) => git(repo, args).toString().trim();
  const tipOf = (repo) => {
    try {
      return said(repo, ["rev-parse", "--verify", "--quiet", MAIN]);
    } catch {
      return null; // a repo with no commit yet
    }
  };

  /** Every file of a commit: text, or `{ base64 }` for a file that is not text. */
  const filesAt = (repo, commitOid) => {
    const blobs = git(repo, ["ls-tree", "-r", "-z", commitOid])
      .toString()
      .split("\0")
      .filter(Boolean)
      .map((line) => {
        const [meta, path] = line.split("\t");
        const [, type, oid] = meta.split(" ");
        return { path, type, oid };
      })
      .filter(({ type }) => type === "blob");
    // one git process for every blob: `<oid> blob <size>\n<bytes>\n`, in the order asked
    const input = blobs.map(({ oid }) => oid).join("\n") + "\n";
    const packed = git(repo, ["cat-file", "--batch"], { input });
    const files = {};
    let at = 0;
    for (const { path } of blobs) {
      const headerEnd = packed.indexOf("\n", at);
      const size = Number(packed.subarray(at, headerEnd).toString().split(" ")[2]);
      const bytes = packed.subarray(headerEnd + 1, headerEnd + 1 + size);
      files[path] = bytes.includes(0) ? { base64: bytes.toString("base64") } : bytes.toString();
      at = headerEnd + 1 + size + 1;
    }
    return files;
  };

  const handleOf = (repo) => {
    // the mind's own words for a path that holds no repo
    const created = (verb) => {
      asked.push(`${verb} ${repo}`);
      if (!folders[repo]) throw new Error(`repo ${repo}: not created`);
    };
    return {
      async listFiles() {
        created("listFiles");
        const commitOid = tipOf(repo);
        return { commitOid, paths: commitOid ? Object.keys(filesAt(repo, commitOid)).sort() : [] };
      },
      async readFile(path, options) {
        created("readFile");
        const commitOid = options ? options.commitOid : tipOf(repo);
        const files = commitOid ? filesAt(repo, commitOid) : {};
        if (!Object.hasOwn(files, path)) return null;
        if (typeof files[path] !== "string")
          throw new Error(`repo: ${path} is not text: read it with readBytes`);
        return files[path];
      },
      async files(options) {
        created("files");
        return filesAt(repo, options.commitOid);
      },
      async branches() {
        created("branches");
        return said(repo, ["for-each-ref", "--format=%(refname) %(objectname)", "refs/heads/"])
          .split("\n")
          .filter(Boolean)
          .map((line) => {
            const [ref, commitOid] = line.split(" ");
            return { name: ref.slice("refs/heads/".length), commitOid };
          });
      },
      // newest first along first parents, from main's tip or `from` any commit
      async log({ limit, from }) {
        created("log");
        const start = from || tipOf(repo);
        if (!start) return [];
        const format = ["%H", "%P", "%an", "%ae", "%at", "%B"].join("%x1f") + "%x1e";
        const args = ["log", "--first-parent", "-n", String(limit), `--format=${format}`, start];
        // git's complaint about an oid that names nothing is the caller's to read, not the terminal's
        return git(repo, args, { stdio: ["ignore", "pipe", "pipe"] })
          .toString()
          .split("\x1e")
          .map((entry) => entry.trim())
          .filter(Boolean)
          .map((entry) => {
            const [oid, parents, name, email, seconds, message] = entry.split("\x1f");
            return {
              oid,
              parents: parents.split(" ").filter(Boolean),
              author: { name, email },
              committer: { name, email },
              timestamp: Number(seconds) * 1000,
              message,
            };
          });
      },
      // one commit on main, made with git's own plumbing in an index of its own: the folder's
      // checked-out files are not touched
      async commitFiles({ message, changes, parent, author }) {
        created("commitFiles");
        const tip = tipOf(repo);
        if (parent !== undefined && parent !== tip)
          throw new Error(
            `repo ${repo}: the commit was refused: main is at ${tip}, not at the parent it names`,
          );
        const scratch = mkdtempSync(join(tmpdir(), "git-app-index-"));
        const env = {
          PATH: process.env.PATH,
          GIT_INDEX_FILE: join(scratch, "index"),
          GIT_AUTHOR_NAME: author ? author.name : "iterate",
          GIT_AUTHOR_EMAIL: author ? author.email : "iterate@example.com",
          GIT_COMMITTER_NAME: "iterate",
          GIT_COMMITTER_EMAIL: "iterate@example.com",
        };
        const run = (args, input) => git(repo, args, { env, input }).toString().trim();
        try {
          run(["read-tree", tip]);
          for (const change of changes) {
            if (change.delete) run(["update-index", "--force-remove", change.path]);
            else {
              const content = "content" in change ? change.content : Buffer.from(change.bytes);
              const blob = run(["hash-object", "-w", "--stdin"], content);
              run(["update-index", "--add", "--cacheinfo", `100644,${blob},${change.path}`]);
            }
          }
          const commitOid = run(["commit-tree", run(["write-tree"]), "-p", tip, "-m", message]);
          run(["update-ref", MAIN, commitOid, tip]);
          return { commitOid, changedPaths: changes.map(({ path }) => path) };
        } finally {
          rmSync(scratch, { recursive: true, force: true });
        }
      },
    };
  };

  /** An itx whose events are stamped as `principal` wrote them: a member's page, or with none
   *  the mind's own code. */
  const itxOf = (principal) => ({
    url: async () => "https://example.com",
    cfArtifacts: {
      get: async (repo) => ({
        remote: async () => {
          if (!remote) throw new Error("this local mind was given no remote");
          return `${remote}${repo}`;
        },
        createToken: async (scope) => {
          minted.push(`${scope} ${repo}`);
          return { plaintext: `art_${scope}` };
        },
      }),
    },
    kv: {
      get: async (key) => kv[key] || null,
      put: async (key, value) => {
        kv[key] = value;
      },
    },
    repos: {
      get: handleOf,
      list: async () => {
        asked.push("list");
        return Object.keys(folders).map((path) => ({ path, createdAt: "" }));
      },
    },
    cd: (path) => ({
      async append(...inputs) {
        const log = (events[path] ||= []);
        return inputs.map((input) => {
          // the same key twice is the same event, as on a context's log
          const already =
            input.idempotencyKey &&
            log.find((event) => event.idempotencyKey === input.idempotencyKey);
          if (already) return already;
          const createdAt = new Date(Date.UTC(2026, 10, 24, 12, (minutes += 1))).toISOString();
          const source = principal ? { origin: path, principal } : { origin: "/" };
          const event = { ...input, offset: log.length + 1, createdAt, path, source };
          log.push(event);
          return event;
        });
      },
      async readEvents(after, limit) {
        const log = events[path] || [];
        const page = log.filter((event) => event.offset > after).slice(0, limit);
        const scannedThroughOffset = page.length ? page.at(-1).offset : after;
        return { events: page, scannedThroughOffset, atHead: scannedThroughOffset >= log.length };
      },
    }),
    [Symbol.dispose]() {},
  });

  const principalOf = (address) => ({ actor: address, email: address });
  const own = itxOf(null);
  return {
    kv,
    asked,
    minted,
    events,
    getItx: () => own,
    as: (address) => itxOf(principalOf(address)),
    auth: {
      // null lets a member in; anyone else gets the mind's sign-in, which here is a bare 401
      require: () => (member ? null : new Response("Sign in\n", { status: 401 })),
      principal: () => (member ? principalOf(member) : null),
      // the member's socket and what its script asks: none of it is served here
      memberPage: () => null,
    },
  };
}