Pulls: propose a change, talk about it, squash it into main
Misha Kaletsky, 2026-11-24 22:38 UTC · d76ec5f83ddefb263cbc3b85ba556631a470b2bc · parent 0ad00e1
12 files changed
- M app.ts
- A pages.ts
- A public/mind.js
- A public/page.css
- A public/page.js
- A pulls.ts
- M tests/app.test.mjs
- A tests/fixtures.mjs
- M tests/local-mind.mjs
- M tests/pages.test.mjs
- A tests/pulls.test.mjs
- M tests/serve.mjs
M app.ts
@@ -1,20 +1,30 @@ // app.ts — THE MIND'S REPOS AT git.<domain>, as config/worker.ts mounts it: a git remote for git -// itself, and pages for a person who reads a repo in a browser. +// itself, and pages for a person who reads a repo, or proposes a change to it, in a browser. // // GET / the repos // GET /repos/<name> the repo's files and its README // GET /repos/<name>/tree/main/<path> a folder of it, or a file // GET /repos/<name>/commits its newest commits // GET /repos/<name>/commit/<oid> one commit: what it changed +// GET /repos/<name>/pulls its pulls, and the branches that have none +// GET /repos/<name>/compare/<branch> a branch against main, and the box that opens a pull +// GET /repos/<name>/pull/<number> one pull: its conversation and what it changes // // GET /repos/<name>/info/refs?service=git-upload-pack | git-receive-pack // POST /repos/<name>/git-upload-pack clone, fetch // POST /repos/<name>/git-receive-pack push // -// WHO MAY READ. A repo that worker.ts lists as public is for anyone: its pages, and a clone with -// no credential. Any other repo's pages are for a member of the mind, and git needs the caller's -// own Artifacts token for it. A push needs that token for every repo. +// The files: this one (who may do what, and the remote), pages.ts (each page's HTML), pulls.ts +// (what a pull is), and public/ (what the browser runs). // +// WHO MAY READ. A repo that worker.ts lists as public is for anyone: its pages, its pulls, and a +// clone with no credential. Any other repo's pages are for a member of the mind, and git needs +// the caller's own Artifacts token for it. A push needs that token for every repo. +// +// WHO MAY WRITE. A member alone opens a pull, comments and merges: the page does each through the +// member's own `itx` (public/mind.js, over the socket that `host.auth.memberPage` answers), so the +// platform records who did it. This file writes nothing of a pull. +// // THE REMOTE IS A PASS-THROUGH. Each of git's three requests goes to the repo's Cloudflare // Artifacts remote as it came, body streamed, answer streamed back. The app adds two things. The // address is the mind's own. And for a public repo it adds a read token of its own, minted once @@ -24,31 +34,37 @@ // memory alone would mint a token for almost every clone. A kv read takes 12 to 32 ms, a mint 150 // (measured on tthq.app, 24 Nov 2026). What stops a push is Artifacts' own limit of 64 MiB a // push, with the same words through this app as straight to Artifacts. -// -// THE PAGES ARE PLAIN HTML, written in this file with no build. Each one reads the repo through -// the mind's own `itx` and is whole with no script: the names, the lists, a file's text. The -// script at the foot of this file then draws three things in their places, with components that -// the browser loads from a CDN: the file tree, a file or a diff with its colours (@pierre/trees, -// @pierre/diffs), and a README as markdown (@iterate-com/ui). -// -// A COMMIT'S PAGE COSTS TWO READS OF A WHOLE TREE, the commit's and its parent's: a repo answers -// with files, never with changes. A commit never changes, so the app keeps what it worked out in -// the mind's kv, and the next reader of that commit costs one kv read. -// -// Only `main` is shown, and a file as text. A page shows the names of members to anyone, as a -// clone does, and no address. -import type { RepoLogEntry } from "iterate/api"; -import type { IterateConfigEntrypoint } from "iterate/sdk"; +import { type AppDescription, type IterateConfigEntrypoint, serveFiles } from "iterate/sdk"; import { z } from "zod"; +import { openFile } from "../stdlib/open-files.ts"; +import theme from "../stdlib/theme.css"; +import { + codePage, + commitPage, + commitsPage, + comparePage, + nameOf, + note, + page, + PAGE_PATH, + pullPage, + pullsPage, + reposPage, +} from "./pages.ts"; +import files from "./public/"; type Host = Pick<IterateConfigEntrypoint, "getItx" | "auth">; -type Itx = ReturnType<Host["getItx"]>; -type Repo = ReturnType<Itx["repos"]["get"]>; +/** What the app says of itself to the mind's sign-in pages. Reading needs no sign-in; the one + * who signs in from here is a member. */ +const GIT: AppDescription = { name: "Git", icon: "/icon.svg", for: "members" }; + +/** What the browser asks for beside a page: the app's own files, and the theme that every app of + * the mind shares (theme.css of /repos/stdlib). */ +const FILES = { ...files, "theme.css": theme }; + const GIT_PATH = /^(\/repos\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*?)\/(info\/refs|git-upload-pack|git-receive-pack)$/; -/** A repo's pages: its name, then `tree/main/<path>`, `commits` or `commit/<oid>`. */ -const PAGE_PATH = /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|commits|commit)(?:\/(.*))?)?$/; /** What git sends that Artifacts needs. A cookie or a stamp of the mind's never leaves. */ const REQUEST_HEADERS = [ @@ -65,13 +81,6 @@ /** A mint is billed: one token serves every anonymous read of the repo for this long. */ const READ_TOKEN_SECONDS = 3600; -/** How many commits the list shows, and how far back a commit's page finds a commit. */ -const COMMITS_SHOWN = 100; -const COMMITS_SEARCHED = 300; -/** The most text a commit's page carries, both sides of every file together. The files past it - * are named with no diff. */ -const DIFF_CHARACTERS_SHOWN = 600_000; - /** What the app keeps of a repo, in the mind's kv under `git-app:<repo>`: where Artifacts serves * it, and for a public repo a read token and the moment that token ends. */ const Kept = z.object({ @@ -79,79 +88,64 @@ readToken: z.object({ authorization: z.string(), until: z.number() }).optional(), }); -/** What the app keeps of a commit, under `git-app:commit:<repo>:<oid>`: what its page shows. */ -const KeptCommit = z.object({ - oid: z.string(), - parents: z.array(z.string()), - message: z.string(), - author: z.string(), - timestamp: z.number(), - changes: z.array( - z.object({ - path: z.string(), - status: z.enum(["added", "deleted", "modified"]), - /** The file's text before and after; null when the page shows no diff, and `note` says why. */ - sides: z.object({ before: z.string(), after: z.string() }).nullable(), - note: z.string().nullable(), - }), - ), -}); -type KeptCommit = z.infer<typeof KeptCommit>; - /** `public`: the repos that anyone may read, clone and fetch, by path (`/repos/<name>`). - * `icon`: the answer for the mind's icon, and `theme`: the stylesheet that every app of the - * mind shares (theme.css of /repos/stdlib). worker.ts hands both over. */ -export function gitApp({ - public: publicRepos, - icon, - theme, -}: { - public: string[]; - icon: () => Response; - theme: string; -}) { + * `icon`: the answer for the mind's icon, which every app serves as its own + * (../stdlib/open-files.ts). */ +export function gitApp({ public: publicRepos, icon }: { public: string[]; icon: () => Response }) { return { + /** The app's description and icon, for anyone: the mind's sign-in pages ask for both. */ + open: (request: Request) => openFile(request, GIT, icon), /** Every request on the app's host. No guard stands before it: the app says who may read. */ async fetch(request: Request, host: Host): Promise<Response> { const url = new URL(request.url); const wire = GIT_PATH.exec(url.pathname); if (wire) return remote(request, url, wire, host, publicRepos); + // a member's page writes through the member's own itx: its socket, and what the socket's + // script asks of its host. Anyone else gets the mind's sign-in there. + const forMemberPage = host.auth.memberPage(request); + if (forMemberPage) return forMemberPage; const pathname = url.pathname.replace(/\/+$/, "") || "/"; - if (pathname === "/theme.css") - return new Response(theme, { - headers: { "content-type": "text/css; charset=utf-8", "cache-control": "no-cache" }, - }); - if (pathname === "/icon.svg") return icon(); - // the mind's sign-in, then back to the list, which then shows the member every repo - if (pathname === "/sign-in") - return host.auth.require(request) || Response.redirect(`${url.origin}/`, 302); + if (Object.hasOwn(FILES, pathname.slice(1))) return serveFiles(request, { files: FILES }); + // the mind's sign-in, then back to the page the person came from + if (pathname === "/sign-in") { + const to = url.searchParams.get("to") || "/"; + const back = to.startsWith("/") && !to.startsWith("//") ? to : "/"; + return host.auth.require(request) || Response.redirect(`${url.origin}${back}`, 302); + } if (pathname === "/") return reposPage(request, url, host, publicRepos); const match = PAGE_PATH.exec(pathname); if (!match) return new Response("git: clone or push at /repos/<name>\n", { status: 404 }); const repo = `/repos/${match[1]}`; const isPublic = publicRepos.includes(repo); - const refused = isPublic ? null : host.auth.require(request); - if (refused) return refused; - - const view = { url, repo, isPublic }; + // null for a member; for anyone else the mind's sign-in, which a repo that is not public + // answers with + const signIn = host.auth.require(request); + if (signIn && !isPublic) return signIn; + // the member, as a page shows them: the name before the `@` of their address + const me = signIn ? null : host.auth.principal(request)?.email?.split("@")[0] || "a member"; + const view = { url, repo, isPublic, me }; + const rest = match[3] || ""; try { using itx = host.getItx(); const handle = itx.repos.get(repo); if (match[2] === "commits") return await commitsPage(view, handle); - if (match[2] === "commit") return await commitPage(view, handle, itx, match[3] || ""); - const [branch, ...segments] = match[2] === "tree" ? (match[3] || "").split("/") : ["main"]; + if (match[2] === "commit") return await commitPage(view, handle, itx, rest); + if (match[2] === "pulls") return await pullsPage(view, handle, itx); + if (match[2] === "pull") return await pullPage(view, handle, itx, rest); + if (match[2] === "compare") return await comparePage(view, handle, itx, rest); + const [branch, ...segments] = match[2] === "tree" ? rest.split("/") : ["main"]; if (branch !== "main") - return page(view, 404, "code", "Not found", note("Only main is shown here."), null); + return page(view, 404, "code", "Not found", note("Only main is shown here."), {}); const path = segments.filter(Boolean).map(decodeURIComponent).join("/"); return await codePage(view, handle, path, url.searchParams.has("plain")); } catch (error) { const message = error instanceof Error ? error.message : String(error); // the repo's own words for a path that holds no repo, or held one if (/: (not created|deleted)/.test(message)) - return page(view, 404, null, "Not found", note(`The mind has no repo ${match[1]}.`), null); - return page(view, 502, null, "Not read", note(`The repo was not read: ${message}`), null); + return page(view, 404, null, "Not found", note(`The mind has no repo ${nameOf(repo)}.`), {}); + return page(view, 502, null, "Not read", note(`The repo was not read: ${message}`), {}); } }, }; @@ -226,572 +220,3 @@ return new Response(upstream.body, { status: upstream.status, headers: answerHeaders }); } -// ── THE PAGES ── - -/** What every page of a repo is drawn with: the request's address, the repo's path, and whether - * anyone may read it. */ -type View = { url: URL; repo: string; isPublic: boolean }; - -/** `/`: the repos, each with the command that clones it. Anyone sees the public ones, with no - * question to the mind. A member sees every repo. */ -async function reposPage( - request: Request, - url: URL, - host: Host, - publicRepos: string[], -): Promise<Response> { - const isMember = host.auth.require(request) === null; - let repos = publicRepos; - if (isMember) { - using itx = host.getItx(); - const all = (await itx.repos.list()).map(({ path }) => path); - repos = all.filter((path) => PAGE_PATH.test(path)).sort(); - } - const rows = repos.map((repo) => { - const tag = publicRepos.includes(repo) ? "" : ` <span class="tag">private</span>`; - return `<li><a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>${tag} <code class="clone">git clone ${esc(url.origin + repo)}</code></li>`; - }); - const signIn = isMember - ? "" - : `<p class="note"><a href="/sign-in">Sign in</a> to see the repos that are not public.</p>`; - const zone = zoneOf(url); - const main = `<h1>The repos of ${esc(zone)}</h1><ul class="repos">${rows.join("")}</ul>${signIn}`; - return page({ url, repo: null, isPublic: true }, 200, null, `The repos of ${zone}`, main, null); -} - -/** A folder of the repo at `main`, with its README, or a file. The file tree stands beside it. */ -async function codePage(view: View, handle: Repo, path: string, plain: boolean) { - const { repo } = view; - const { commitOid, paths } = await handle.listFiles(); - if (!commitOid) - return page(view, 200, "code", nameOf(repo), note("This repo has no commit yet."), null); - const isFile = paths.includes(path); - const under = path ? `${path}/` : ""; - const within = paths.filter((file) => file.startsWith(under)); - if (!isFile && within.length === 0) { - const missing = note(`${nameOf(repo)} has no file or folder ${path} on main.`); - return page(view, 404, "code", "Not found", missing, null); - } - - // the way here: the repo, each folder above, then this file or folder - const segments = path ? path.split("/") : []; - const crumbs = segments.map((segment, index) => - index === segments.length - 1 - ? `<b>${esc(segment)}</b>` - : `<a href="${treeHref(repo, segments.slice(0, index + 1).join("/"))}">${esc(segment)}</a>`, - ); - const top = `<a href="${esc(repo)}">${esc(nameOf(repo))}</a>`; - const at = `<span class="at">main at <a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a></span>`; - const way = `<p class="crumbs">${[top, ...crumbs].join(" / ")}${at}</p>`; - - const content = isFile - ? await fileContent(view, handle, path, plain) - : await folderContent(view, handle, under, within); - const main = `<div class="code"><nav id="tree" aria-label="Files"></nav><div id="content">${way}${content}</div></div>`; - const title = path ? `${path} · ${nameOf(repo)}` : nameOf(repo); - return page(view, 200, "code", title, main, { repo, paths, path }); -} - -/** The folder's own entries, folders first, and its README under them. */ -async function folderContent(view: View, handle: Repo, under: string, within: string[]) { - const folders = new Set<string>(); - const files: string[] = []; - for (const file of within) { - const rest = file.slice(under.length); - const slash = rest.indexOf("/"); - if (slash < 0) files.push(rest); - else folders.add(rest.slice(0, slash)); - } - const row = (name: string, shown: string) => - `<li><a href="${treeHref(view.repo, under + name)}">${esc(shown)}</a></li>`; - const entries = [ - ...[...folders].sort().map((name) => row(name, `${name}/`)), - ...files.sort().map((name) => row(name, name)), - ]; - const readme = files.find((name) => /^readme(\.(md|markdown|txt))?$/i.test(name)); - const text = readme ? await handle.readFile(under + readme) : null; - const shown = - readme && text !== null - ? `<article class="readme"><h2>${esc(readme)}</h2>${fileText(under + readme, text, false)}</article>` - : ""; - return `<ul class="entries">${entries.join("")}</ul>${shown}`; -} - -/** The file's text. A markdown file is shown as it reads, and `?plain` shows its source. */ -async function fileContent(view: View, handle: Repo, path: string, plain: boolean) { - let text: string | null; - try { - text = await handle.readFile(path); - } catch (error) { - // the repo's own refusal of a file that is not text (an image, a font) - if (/is not text/.test(error instanceof Error ? error.message : "")) text = null; - else throw error; - } - if (text === null) return note("This file is not text, so it is not shown. A clone has it."); - const here = treeHref(view.repo, path); - const other = isMarkdown(path) - ? plain - ? `<p class="note"><a href="${here}">As it reads</a></p>` - : `<p class="note"><a href="${here}?plain">Its source</a></p>` - : ""; - return other + fileText(path, text, plain); -} - -/** A file's text as a `<pre>`, marked for the script: `data-markdown` is drawn as markdown (its - * links are read against `data-dir`, the file's folder), `data-file` with the file's colours. */ -function fileText(path: string, text: string, plain: boolean) { - const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; - const mark = - isMarkdown(path) && !plain ? `data-markdown data-dir="${esc(dir)}"` : `data-file="${esc(path)}"`; - return `<pre ${mark}>${esc(text)}</pre>`; -} - -/** The newest commits on `main`: each one's oid, the first line of its message, who and when. */ -async function commitsPage(view: View, handle: Repo) { - const commits = await handle.log({ limit: COMMITS_SHOWN }); - const rows = commits.map( - (commit) => - `<li><a href="${esc(view.repo)}/commit/${commit.oid}"><code>${commit.oid.slice(0, 7)}</code></a> ${esc(subjectOf(commit.message))} <span class="by">${esc(commit.author.name)}, ${utcStamp(commit.timestamp)}</span></li>`, - ); - const more = commits.length === COMMITS_SHOWN ? note(`The newest ${COMMITS_SHOWN} commits.`) : ""; - const list = rows.length ? `<ul class="commits">${rows.join("")}</ul>` : note("No commit yet."); - const main = `<h1>Commits on main</h1>${list}${more}`; - return page(view, 200, "commits", `Commits · ${nameOf(view.repo)}`, main, null); -} - -/** One commit: its message, and each file it changed against its first parent, as a diff that - * folds away under the file's name. */ -async function commitPage(view: View, handle: Repo, itx: Itx, wanted: string) { - const { repo } = view; - if (!/^[0-9a-f]{7,40}$/.test(wanted)) - return page(view, 404, "commits", "Not found", note("That is no commit's oid."), null); - // A commit never changes, so what the app worked out of it is kept under its whole oid. A - // shorter oid is found in the log first. - const keptOf = async (oid: string) => { - const text = await itx.kv.get(`git-app:commit:${repo}:${oid}`); - return text ? KeptCommit.parse(JSON.parse(text)) : null; - }; - let commit = wanted.length === 40 ? await keptOf(wanted) : null; - if (!commit) { - const found = (await handle.log({ limit: COMMITS_SEARCHED })).find(({ oid }) => - oid.startsWith(wanted), - ); - if (!found) { - const missing = note( - `${nameOf(repo)} has no commit ${wanted} among its newest ${COMMITS_SEARCHED}.`, - ); - return page(view, 404, "commits", "Not found", missing, null); - } - commit = wanted.length === 40 ? null : await keptOf(found.oid); - if (!commit) { - commit = { - oid: found.oid, - parents: found.parents, - message: found.message, - author: found.author.name, - timestamp: found.timestamp, - changes: await changesOf(handle, found), - }; - await itx.kv.put(`git-app:commit:${repo}:${commit.oid}`, JSON.stringify(commit)); - } - } - - const [subject, ...rest] = commit.message.trim().split("\n"); - const body = rest.join("\n").trim(); - const parents = commit.parents.map( - (oid) => `<a href="${esc(repo)}/commit/${oid}"><code>${oid.slice(0, 7)}</code></a>`, - ); - const from = - parents.length === 0 - ? "the first commit" - : parents.length === 1 - ? `parent ${parents[0]}` - : `a merge of ${parents.join(" and ")}, shown against ${parents[0]}`; - const letter = { added: "A", deleted: "D", modified: "M" }; - const names = commit.changes.map( - (change, index) => - `<li><span class="status ${change.status}">${letter[change.status]}</span> <a href="#diff-${index}">${esc(change.path)}</a></li>`, - ); - const diffs = commit.changes.map((change, index) => { - const shown = change.sides - ? `<div class="diff" data-diff="${index}"></div>` - : note(change.note || ""); - // each file folds: the reader closes the ones they have read - return `<details id="diff-${index}" open><summary><span class="status ${change.status}">${letter[change.status]}</span> ${esc(change.path)}</summary>${shown}</details>`; - }); - const count = `${commit.changes.length} file${commit.changes.length === 1 ? "" : "s"} changed`; - const main = [ - `<article class="commit"><h1>${esc(subject || "")}</h1>`, - body ? `<pre class="message">${esc(body)}</pre>` : "", - `<p class="by">${esc(commit.author)}, ${utcStamp(commit.timestamp)} · <code>${commit.oid}</code> · ${from}</p>`, - `<p>${count}</p><ul class="changes">${names.join("")}</ul>${diffs.join("")}</article>`, - ].join(""); - // the script draws each diff from the two texts - const data = { - diffs: commit.changes.map(({ path, sides }) => (sides ? { path, ...sides } : null)), - }; - const title = `${subject} · ${nameOf(repo)}`; - return page(view, 200, "commits", title, main, data); -} - -/** The files a commit changed against its first parent, each with both texts while the page has - * room for them. */ -async function changesOf( - handle: Repo, - commit: Pick<RepoLogEntry, "oid" | "parents">, -): Promise<KeptCommit["changes"]> { - const parent = commit.parents[0]; - // The parent first: a repo holds the files of the commit it read last, and the newer one is - // the likelier next read. - const before = parent ? await handle.files({ commitOid: parent }) : {}; - const after = await handle.files({ commitOid: commit.oid }); - let room = DIFF_CHARACTERS_SHOWN; - const changes: KeptCommit["changes"] = []; - for (const path of Object.keys({ ...before, ...after }).sort()) { - const was = Object.hasOwn(before, path) ? before[path]! : null; - const is = Object.hasOwn(after, path) ? after[path]! : null; - // a file that is not text comes as `{ base64 }`: the same bytes are the same file - const same = - typeof was === "string" || typeof is === "string" - ? was === is - : was !== null && is !== null && was.base64 === is.base64; - if (same) continue; - const status = was === null ? "added" : is === null ? "deleted" : "modified"; - if ((was !== null && typeof was !== "string") || (is !== null && typeof is !== "string")) { - changes.push({ path, status, sides: null, note: "Not text, so no diff is shown." }); - continue; - } - const sides = { before: was || "", after: is || "" }; - const characters = sides.before.length + sides.after.length; - if (characters > room) { - const large = "Not shown: the commit is larger than this page shows. A clone has it."; - changes.push({ path, status, sides: null, note: large }); - continue; - } - room -= characters; - changes.push({ path, status, sides, note: null }); - } - return changes; -} - -// ── WHAT EVERY PAGE IS MADE OF ── - -/** One page: the head, the row that says where the reader is, `main`, and the script with - * `data`, what it draws from. `tab` is the row's link that is marked as the one shown. */ -function page( - view: { url: URL; repo: string | null; isPublic: boolean }, - status: number, - tab: "code" | "commits" | null, - title: string, - main: string, - data: unknown, -): Response { - const { url, repo } = view; - const zone = zoneOf(url); - const current = (name: string) => (tab === name ? ` aria-current="page"` : ""); - const where = repo - ? [ - `<p><a href="/">${esc(zone)}</a> / <a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>`, - view.isPublic ? "" : ` <span class="tag">private</span>`, - `</p><nav><a href="${esc(repo)}"${current("code")}>Code</a>`, - `<a href="${esc(repo)}/commits"${current("commits")}>Commits</a></nav>`, - `<code class="clone">git clone ${esc(url.origin + repo)}</code>`, - ].join("") - : `<p><a href="/">${esc(zone)}</a></p>`; - const html = `<!doctype html> -<html lang="en"> - <head> - <meta charset="utf-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1" /> - <title>${esc(title)} · ${esc(zone)}</title> - <link rel="icon" href="/icon.svg" type="image/svg+xml" /> - <link rel="preconnect" href="https://esm.iterate.com" crossorigin /> - <script type="importmap">${IMPORT_MAP}</script> - <link rel="stylesheet" crossorigin href="${UI}/dist/styles.css" /> - <link rel="stylesheet" href="/theme.css" /> - <script> - if (getComputedStyle(document.documentElement).colorScheme === "dark") - document.documentElement.classList.add("dark"); - </script> - <style>${STYLE}</style> - </head> - <body> - <header class="where">${where}</header> - <main>${main}</main> - <script type="application/json" id="data">${JSON.stringify(data).replace(/</g, "\\u003c")}</script> - <script type="module">${SCRIPT}</script> - </body> -</html> -`; - return new Response(html, { - status, - headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" }, - }); -} - -const ESCAPES: Record<string, string> = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", -}; -const esc = (text: string) => text.replace(/[&<>"']/g, (character) => ESCAPES[character]!); -const note = (text: string) => `<p class="note">${esc(text)}</p>`; -const nameOf = (repo: string) => repo.slice("/repos/".length); -/** The zone the app is on: its hostname is one label under it. */ -const zoneOf = (url: URL) => url.hostname.split(".").slice(1).join("."); -const isMarkdown = (path: string) => /\.(md|markdown)$/i.test(path); -const subjectOf = (message: string) => message.trim().split("\n")[0] || ""; -/** The page of a file or a folder; the repo's own page for its root. */ -const treeHref = (repo: string, path: string) => - esc(path ? `${repo}/tree/main/${path.split("/").map(encodeURIComponent).join("/")}` : repo); -/** A moment as `2026-11-24 15:39 UTC`: the same for every reader. */ -const utcStamp = (timestamp: number) => - `${new Date(timestamp).toISOString().slice(0, 16).replace("T", " ")} UTC`; - -/** iterate's components, pinned to one build: the one the Dash pins. */ -const UI = "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390"; -const IMPORT_MAP = JSON.stringify({ - imports: { - "@iterate-com/ui/": `${UI}/`, - react: `${UI}/react`, - "react/": `${UI}/react/`, - "react-dom": `${UI}/react-dom`, - "react-dom/": `${UI}/react-dom/`, - "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom", - "@pierre/trees/react": "https://esm.iterate.com/@pierre/trees@1.0.0/react?external=react,react-dom", - "@pierre/diffs/react": "https://esm.iterate.com/@pierre/diffs@1.7.1/react?external=react,react-dom", - }, -}); - -/** The pages' own look, over the UI kit's stylesheet (which resets every element) and the mind's - * theme.css, whose colours these are. */ -const STYLE = ` - body { margin: 0; font-size: 0.875rem; } - a { text-decoration: underline; text-underline-offset: 2px; } - code, pre { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.75rem; } - h1 { font-size: 1.125rem; font-weight: 600; margin-bottom: 0.75rem; } - .where { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 1.5rem; - padding: 0.625rem 1rem; border-bottom: 1px solid var(--border); } - .where nav { display: flex; gap: 1rem; } - .where nav a { text-decoration: none; color: var(--muted-foreground); } - .where nav a[aria-current] { color: var(--foreground); font-weight: 600; } - .where .clone { margin-left: auto; } - .clone { color: var(--muted-foreground); user-select: all; } - .tag { border: 1px solid var(--border); border-radius: 999px; padding: 0 0.5rem; - font-size: 0.75rem; color: var(--muted-foreground); } - .note, .by, .at { color: var(--muted-foreground); } - main > h1, main > ul, main > p, .commit { margin-left: 1rem; margin-right: 1rem; } - main > h1 { margin-top: 1rem; } - .repos li, .commits li { padding: 0.25rem 0; } - .repos .clone { margin-left: 0.75rem; } - - .code { display: grid; grid-template-columns: 17rem minmax(0, 1fr); } - #tree { position: sticky; top: 0; height: 100vh; overflow: auto; - border-right: 1px solid var(--border); } - #content { min-width: 0; padding: 0.875rem 1.25rem 3rem; } - @media (max-width: 48rem) { .code { display: block; } #tree { display: none; } } - .crumbs { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.35rem; - margin-bottom: 0.75rem; } - .crumbs .at { margin-left: auto; font-size: 0.75rem; } - .entries { border: 1px solid var(--border); border-radius: 0.5rem; overflow: hidden; } - .entries li + li { border-top: 1px solid var(--border); } - .entries a { display: block; padding: 0.3rem 0.75rem; text-decoration: none; - font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.8125rem; } - .entries a:hover { background: var(--accent); } - .readme { margin-top: 1.25rem; border: 1px solid var(--border); border-radius: 0.5rem; } - .readme > h2 { padding: 0.4rem 0.75rem; border-bottom: 1px solid var(--border); - font-size: 0.75rem; color: var(--muted-foreground); } - .readme > :not(h2), .markdown { padding: 1rem 1.25rem; } - #content > .markdown { padding: 0; } - pre { overflow: auto; line-height: 1.5; } - #content > pre, #content > .file { border: 1px solid var(--border); border-radius: 0.5rem; } - #content > pre { padding: 0.75rem; } - #content > .file { overflow: hidden; } - #content > .note { margin-bottom: 0.5rem; font-size: 0.75rem; } - - .commit { margin-top: 1rem; margin-bottom: 3rem; } - .commit .message { margin-bottom: 0.75rem; white-space: pre-wrap; } - .commit > p { margin-bottom: 0.5rem; } - .changes { margin-bottom: 1.5rem; } - .changes li, .commit summary { font-family: var(--font-mono, ui-monospace, monospace); - font-size: 0.8125rem; } - .commit details { margin-top: 1.25rem; border: 1px solid var(--border); - border-radius: 0.5rem; } - /* the file's name stays at the top of the window while its diff is read */ - .commit summary { position: sticky; top: 0; z-index: 1; padding: 0.4rem 0.75rem; - cursor: pointer; background: var(--background); border-radius: 0.5rem; } - .commit details[open] > summary { border-bottom: 1px solid var(--border); - border-radius: 0.5rem 0.5rem 0 0; } - .commit details .note { padding: 0.5rem 0.75rem; } - .diff { min-height: 4rem; overflow: hidden; border-radius: 0 0 0.5rem 0.5rem; } - .status { font-weight: 600; } - .status.added { color: light-dark(oklch(0.5 0.15 150), oklch(0.75 0.15 150)); } - .status.deleted { color: var(--destructive); } - .status.modified { color: light-dark(oklch(0.5 0.13 250), oklch(0.75 0.13 250)); } -`; - -/** WHAT THE BROWSER RUNS. The page is whole without it. It draws the file tree, each file and - * README in the place of its `<pre>`, and each diff of a commit when the reader scrolls near - * it. On a page of files a click on a file or a folder fetches that page and takes its content - * alone, so the tree stays as the reader left it. - * - * It is text in a template, so it has no backtick and no dollar-brace of its own. */ -const SCRIPT = String.raw` - import { createElement as h } from "react"; - import { createRoot } from "react-dom/client"; - - const data = JSON.parse(document.getElementById("data").textContent); - // The page's look is the mind's theme.css. Pierre's components would follow the visitor's - // system, so they are told. - const dark = getComputedStyle(document.documentElement).colorScheme === "dark"; - const pierre = { - theme: { light: "pierre-light", dark: "pierre-dark" }, - themeType: dark ? "dark" : "light", - disableFileHeader: true, - }; - - // what is drawn in the content, to take down when the content is replaced - let drawn = []; - function draw(place, node) { - const root = createRoot(place); - root.render(node); - drawn.push(root); - } - // The <pre> stays until the component has drawn something, so the text never blinks away. - function inPlaceOf(pre, className) { - const place = document.createElement("div"); - place.className = className; - pre.after(place); - const waiting = new ResizeObserver(() => { - if (place.offsetHeight === 0) return; - waiting.disconnect(); - pre.remove(); - }); - waiting.observe(place); - return place; - } - - async function drawContent() { - const content = document.getElementById("content"); - if (!content) return; - const files = [...content.querySelectorAll("pre[data-file]")]; - const markdowns = [...content.querySelectorAll("pre[data-markdown]")]; - if (files.length) { - const { File } = await import("@pierre/diffs/react"); - for (const pre of files.filter((pre) => pre.isConnected)) { - const file = { name: pre.dataset.file, contents: pre.textContent }; - draw(inPlaceOf(pre, "file"), h(File, { file, options: pierre })); - } - } - if (markdowns.length) { - const { Markdown } = await import("@iterate-com/ui/components/agent-chat/chat-parts"); - for (const pre of markdowns.filter((pre) => pre.isConnected)) { - const place = inPlaceOf(pre, "markdown"); - place.dataset.dir = pre.dataset.dir; - draw(place, h(Markdown, null, pre.textContent)); - } - } - } - - // A commit's diffs, each drawn when the reader scrolls near it: a commit may change many files. - async function drawDiffs() { - const places = document.querySelectorAll("[data-diff]"); - if (places.length === 0) return; - // a file's name in the list of changes opens that file, if the reader had folded it - document.addEventListener("click", (event) => { - const link = event.target.closest(".changes a"); - const file = link && document.querySelector(link.getAttribute("href")); - if (file) file.open = true; - }); - const { MultiFileDiff } = await import("@pierre/diffs/react"); - const near = new IntersectionObserver( - (entries) => { - for (const entry of entries.filter((entry) => entry.isIntersecting)) { - near.unobserve(entry.target); - const { path, before, after } = data.diffs[Number(entry.target.dataset.diff)]; - const sides = { - oldFile: { name: path, contents: before }, - newFile: { name: path, contents: after }, - }; - draw(entry.target, h(MultiFileDiff, { ...sides, options: { ...pierre, diffStyle: "unified" } })); - } - }, - { rootMargin: "800px" }, - ); - for (const place of places) near.observe(place); - } - - // ── a page of files: the tree, and a click that takes the next page's content alone ── - - const treePlace = document.getElementById("tree"); - const treeHref = (path) => - path ? data.repo + "/tree/main/" + path.split("/").map(encodeURIComponent).join("/") : data.repo; - const shownPath = () => - decodeURIComponent(location.pathname.slice((data.repo + "/tree/main/").length)); - let tree; - - async function visit(href, push) { - const answer = await fetch(href); - const next = new DOMParser().parseFromString(await answer.text(), "text/html"); - const content = next.getElementById("content"); - // a page with no content of this kind (a sign-in, an error) is shown whole - if (!content) return location.assign(href); - for (const root of drawn) root.unmount(); - drawn = []; - document.getElementById("content").replaceWith(document.adoptNode(content)); - document.title = next.title; - if (push) history.pushState(null, "", href); - scrollTo(0, 0); - const item = tree && tree.getItem(shownPath()); - if (item && !item.isDirectory() && !item.isSelected()) item.select(); - await drawContent(); - } - - async function drawTree() { - if (!treePlace) return; - const { FileTree, useFileTree } = await import("@pierre/trees/react"); - const files = new Set(data.paths); - // the folders above what is shown are open; a small repo is open whole - const segments = data.path.split("/").filter(Boolean); - const above = segments.map((_, index) => segments.slice(0, index + 1).join("/")); - function Tree() { - const { model } = useFileTree({ - paths: data.paths, - initialExpansion: data.paths.length > 150 ? "closed" : "open", - initialExpandedPaths: above, - initialSelectedPaths: files.has(data.path) ? [data.path] : [], - search: true, - onSelectionChange: (paths) => { - if (files.has(paths[0]) && paths[0] !== shownPath()) visit(treeHref(paths[0]), true); - }, - }); - tree = model; - return h(FileTree, { model, style: { colorScheme: "inherit", height: "100%" } }); - } - createRoot(treePlace).render(h(Tree)); - - addEventListener("popstate", () => visit(location.href, false)); - document.addEventListener("click", (event) => { - const plain = event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey; - const link = plain && !event.defaultPrevented && event.target.closest("#content a[href]"); - if (!link) return; - // a link in a README is written against the folder of the file it is in - const written = link.getAttribute("href"); - const markdown = link.closest(".markdown"); - const relative = markdown && !/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(written); - const dir = markdown && markdown.dataset.dir ? treeHref(markdown.dataset.dir) + "/" : data.repo + "/tree/main/"; - const folder = location.origin + dir; - const url = new URL(relative ? new URL(written, folder) : link.href); - const ofThisRepo = url.pathname === data.repo || url.pathname.startsWith(data.repo + "/tree/"); - if (url.origin !== location.origin || !ofThisRepo) return; - event.preventDefault(); - visit(url.pathname + url.search, true); - }); - } - - drawTree(); - drawContent(); - drawDiffs(); -`;
A pages.ts
@@ -0,0 +1,615 @@ +// pages.ts — THE PAGES A PERSON READS A REPO WITH, as plain HTML. app.ts says who may read and +// calls one function here for each page. Each one reads the repo through the mind's own `itx` +// and is whole with no script: the names, the lists, a file's text, a pull's conversation. +// public/page.js then draws in their places what wants a script: the file tree, a file or a diff +// with its colours, markdown, and for a member the boxes that write (a comment, a pull, a merge). +// +// WHAT A PULL IS, and where its events are, is pulls.ts. A page here only reads. +// +// THE DIFFERENCE BETWEEN TWO COMMITS COSTS TWO READS OF A WHOLE TREE: a repo answers with files, +// never with changes. Two commits never change, so the app keeps what it worked out in the +// mind's kv, and the next reader costs one kv read. +// +// Only `main` and the branches of open pulls are shown, and a file as text. A page shows people +// by the name before the `@` of their address, and no address. +import type { RepoLogEntry } from "iterate/api"; +import type { IterateConfigEntrypoint } from "iterate/sdk"; +import { z } from "zod"; +import { type LinePlace, type Pull, pullsIn, type Standing, standingOf } from "./pulls.ts"; + +type Host = Pick<IterateConfigEntrypoint, "getItx" | "auth">; +export type Itx = ReturnType<Host["getItx"]>; +export type Repo = ReturnType<Itx["repos"]["get"]>; + +/** What every page of a repo is drawn with: the request's address, the repo's path, whether + * anyone may read it, and `me`: the member who asks, as a page shows them. `me` is null for + * anyone else, who reads and writes nothing. */ +export type View = { url: URL; repo: string; isPublic: boolean; me: string | null }; + +/** A repo's pages: its name, then what of it. */ +export const PAGE_PATH = + /^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|commits|commit|pulls|pull|compare)(?:\/(.*))?)?$/; + +/** How many commits the list shows, and how far back a short oid is looked for. */ +const COMMITS_SHOWN = 100; +const COMMITS_SEARCHED = 300; +/** The most text a page of diffs carries, both sides of every file together. The files past it + * are named with no diff. */ +const DIFF_CHARACTERS_SHOWN = 600_000; + +/** One file that differs between two commits. `sides` is its text before and after; null when + * the page shows no diff, and `note` says why. */ +const Change = z.object({ + path: z.string(), + status: z.enum(["added", "deleted", "modified"]), + sides: z.object({ before: z.string(), after: z.string() }).nullable(), + note: z.string().nullable(), +}); +type Change = z.infer<typeof Change>; + +/** What the app keeps of a commit, under `git-app:commit:<repo>:<oid>`: what its page shows. */ +const KeptCommit = z.object({ + oid: z.string(), + parents: z.array(z.string()), + message: z.string(), + author: z.string(), + timestamp: z.number(), + changes: z.array(Change), +}); +type KeptCommit = z.infer<typeof KeptCommit>; + +// ── THE REPOS, A REPO'S FILES, ITS COMMITS ── + +/** `/`: the repos, each with the command that clones it. Anyone sees the public ones, with no + * question to the mind. A member sees every repo. */ +export async function reposPage( + request: Request, + url: URL, + host: Host, + publicRepos: string[], +): Promise<Response> { + const isMember = host.auth.require(request) === null; + let repos = publicRepos; + if (isMember) { + using itx = host.getItx(); + const all = (await itx.repos.list()).map(({ path }) => path); + repos = all.filter((path) => PAGE_PATH.test(path)).sort(); + } + const rows = repos.map((repo) => { + const tag = publicRepos.includes(repo) ? "" : ` <span class="tag">private</span>`; + return `<li><a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>${tag} <code class="clone">git clone ${esc(url.origin + repo)}</code></li>`; + }); + const signIn = isMember + ? "" + : `<p class="note"><a href="/sign-in">Sign in</a> to see the repos that are not public.</p>`; + const zone = zoneOf(url); + const main = `<h1>The repos of ${esc(zone)}</h1><ul class="repos">${rows.join("")}</ul>${signIn}`; + const view = { url, repo: null, isPublic: true, me: isMember ? "member" : null }; + return page(view, 200, null, `The repos of ${zone}`, main, {}); +} + +/** A folder of the repo at `main`, with its README, or a file. The file tree stands beside it. */ +export async function codePage(view: View, handle: Repo, path: string, plain: boolean) { + const { repo } = view; + const { commitOid, paths } = await handle.listFiles(); + if (!commitOid) + return page(view, 200, "code", nameOf(repo), note("This repo has no commit yet."), {}); + const isFile = paths.includes(path); + const under = path ? `${path}/` : ""; + const within = paths.filter((file) => file.startsWith(under)); + if (!isFile && within.length === 0) { + const missing = note(`${nameOf(repo)} has no file or folder ${path} on main.`); + return page(view, 404, "code", "Not found", missing, {}); + } + + // the way here: the repo, each folder above, then this file or folder + const segments = path ? path.split("/") : []; + const crumbs = segments.map((segment, index) => + index === segments.length - 1 + ? `<b>${esc(segment)}</b>` + : `<a href="${treeHref(repo, segments.slice(0, index + 1).join("/"))}">${esc(segment)}</a>`, + ); + const top = `<a href="${esc(repo)}">${esc(nameOf(repo))}</a>`; + const at = `<span class="at">main at <a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a></span>`; + const way = `<p class="crumbs">${[top, ...crumbs].join(" / ")}${at}</p>`; + + const content = isFile + ? await fileContent(view, handle, path, plain) + : await folderContent(view, handle, under, within); + const main = `<div class="code"><nav id="tree" aria-label="Files"></nav><div id="content">${way}${content}</div></div>`; + const title = path ? `${path} · ${nameOf(repo)}` : nameOf(repo); + return page(view, 200, "code", title, main, { paths, path }); +} + +/** The folder's own entries, folders first, and its README under them. */ +async function folderContent(view: View, handle: Repo, under: string, within: string[]) { + const folders = new Set<string>(); + const files: string[] = []; + for (const file of within) { + const rest = file.slice(under.length); + const slash = rest.indexOf("/"); + if (slash < 0) files.push(rest); + else folders.add(rest.slice(0, slash)); + } + const row = (name: string, shown: string) => + `<li><a href="${treeHref(view.repo, under + name)}">${esc(shown)}</a></li>`; + const entries = [ + ...[...folders].sort().map((name) => row(name, `${name}/`)), + ...files.sort().map((name) => row(name, name)), + ]; + const readme = files.find((name) => /^readme(\.(md|markdown|txt))?$/i.test(name)); + const text = readme ? await handle.readFile(under + readme) : null; + const shown = + readme && text !== null + ? `<article class="readme"><h2>${esc(readme)}</h2>${fileText(under + readme, text, false)}</article>` + : ""; + return `<ul class="entries">${entries.join("")}</ul>${shown}`; +} + +/** The file's text. A markdown file is shown as it reads, and `?plain` shows its source. */ +async function fileContent(view: View, handle: Repo, path: string, plain: boolean) { + let text: string | null; + try { + text = await handle.readFile(path); + } catch (error) { + // the repo's own refusal of a file that is not text (an image, a font) + if (/is not text/.test(error instanceof Error ? error.message : "")) text = null; + else throw error; + } + if (text === null) return note("This file is not text, so it is not shown. A clone has it."); + const here = treeHref(view.repo, path); + const other = isMarkdown(path) + ? plain + ? `<p class="note"><a href="${here}">As it reads</a></p>` + : `<p class="note"><a href="${here}?plain">Its source</a></p>` + : ""; + return other + fileText(path, text, plain); +} + +/** A file's text as a `<pre>`, marked for the script: `data-markdown` is drawn as markdown (its + * links are read against `data-dir`, the file's folder), `data-file` with the file's colours. */ +function fileText(path: string, text: string, plain: boolean) { + const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; + const mark = + isMarkdown(path) && !plain ? `data-markdown data-dir="${esc(dir)}"` : `data-file="${esc(path)}"`; + return `<pre ${mark}>${esc(text)}</pre>`; +} + +/** The newest commits on `main`: each one's oid, the first line of its message, who and when. */ +export async function commitsPage(view: View, handle: Repo) { + const commits = await handle.log({ limit: COMMITS_SHOWN }); + const more = commits.length === COMMITS_SHOWN ? note(`The newest ${COMMITS_SHOWN} commits.`) : ""; + const list = commits.length ? commitRows(view, commits) : note("No commit yet."); + const main = `<h1>Commits on main</h1>${list}${more}`; + return page(view, 200, "commits", `Commits · ${nameOf(view.repo)}`, main, {}); +} + +/** Commits as a list, newest first: each one's oid, the first line of its message, who and when. */ +function commitRows(view: View, commits: RepoLogEntry[]) { + const rows = commits.map( + (commit) => + `<li><a href="${esc(view.repo)}/commit/${commit.oid}"><code>${commit.oid.slice(0, 7)}</code></a> ${esc(subjectOf(commit.message))} <span class="by">${esc(commit.author.name)}, ${utcStamp(commit.timestamp)}</span></li>`, + ); + return `<ul class="commits">${rows.join("")}</ul>`; +} + +/** One commit: its message, and each file it changed against its first parent, as a diff that + * folds away under the file's name. */ +export async function commitPage(view: View, handle: Repo, itx: Itx, wanted: string) { + const { repo } = view; + if (!/^[0-9a-f]{7,40}$/.test(wanted)) + return page(view, 404, "commits", "Not found", note("That is no commit's oid."), {}); + // A commit never changes, so what the app worked out of it is kept under its whole oid. A + // whole oid names a commit on any branch; a shorter one is looked for on main. + const whole = wanted.length === 40; + const keptOf = async (oid: string) => { + const text = await itx.kv.get(`git-app:commit:${repo}:${oid}`); + return text ? KeptCommit.parse(JSON.parse(text)) : null; + }; + let commit = whole ? await keptOf(wanted) : null; + if (!commit) { + const found = whole + ? await commitAt(handle, wanted) + : (await handle.log({ limit: COMMITS_SEARCHED })).find(({ oid }) => oid.startsWith(wanted)); + if (!found) { + const where = whole ? "" : ` among the newest ${COMMITS_SEARCHED} of main`; + const missing = note(`${nameOf(repo)} has no commit ${wanted}${where}.`); + return page(view, 404, "commits", "Not found", missing, {}); + } + commit = whole ? null : await keptOf(found.oid); + if (!commit) { + commit = { + oid: found.oid, + parents: found.parents, + message: found.message, + author: found.author.name, + timestamp: found.timestamp, + changes: await changesOf(handle, found.parents[0] || null, found.oid), + }; + await itx.kv.put(`git-app:commit:${repo}:${commit.oid}`, JSON.stringify(commit)); + } + } + + const [subject, ...rest] = commit.message.trim().split("\n"); + const body = rest.join("\n").trim(); + const parents = commit.parents.map( + (oid) => `<a href="${esc(repo)}/commit/${oid}"><code>${oid.slice(0, 7)}</code></a>`, + ); + const from = + parents.length === 0 + ? "the first commit" + : parents.length === 1 + ? `parent ${parents[0]}` + : `a merge of ${parents.join(" and ")}, shown against ${parents[0]}`; + const main = [ + `<article class="commit"><h1>${esc(subject || "")}</h1>`, + body ? `<pre class="message">${esc(body)}</pre>` : "", + `<p class="by">${esc(commit.author)}, ${utcStamp(commit.timestamp)} · <code>${commit.oid}</code> · ${from}</p>`, + `${filesHtml(commit.changes)}</article>`, + ].join(""); + const title = `${subject} · ${nameOf(repo)}`; + return page(view, 200, "commits", title, main, { diffs: diffsOf(commit.changes) }); +} + +/** One commit by its whole oid, on any branch; undefined when the repo has no such commit. */ +async function commitAt(handle: Repo, oid: string) { + try { + return (await handle.log({ limit: 1, from: oid }))[0]; + } catch (error) { + // git's own words for an oid that names nothing here; any other failure is a failure + const words = error instanceof Error ? error.message : String(error); + if (/not our ref|bad object|unknown revision|not a valid object|upload-pack/i.test(words)) + return undefined; + throw error; + } +} + +// ── PULLS ── + +/** The repo's pulls: the open ones, then the branches that could be proposed, then the pulls + * that are merged or closed. */ +export async function pullsPage(view: View, handle: Repo, itx: Itx) { + const { repo } = view; + const pulls = (await pullsIn(itx, repo)).toReversed(); + const row = (pull: Pull) => { + const comments = pull.threads.reduce((count, thread) => count + thread.comments.length, 0); + const said = comments ? `, ${comments} comment${comments === 1 ? "" : "s"}` : ""; + const status = pull.status === "open" ? "" : `, ${pull.status}`; + return `<li><a href="${esc(repo)}/pull/${pull.number}">${esc(pull.title)}</a> <span class="by">#${pull.number}${status}, <code>${esc(pull.branch)}</code>, ${esc(pull.by)}, ${utcStamp(Date.parse(pull.openedAt))}${said}</span></li>`; + }; + const open = pulls.filter((pull) => pull.status === "open"); + const done = pulls.filter((pull) => pull.status !== "open"); + // A branch is offered for a pull unless its newest pull is open, or merged: a squashed branch + // is done, and what it had is on main under another commit. + const newest = new Map(pulls.toReversed().map((pull) => [pull.branch, pull.status])); + const loose = (await handle.branches()).filter( + ({ name }) => name !== "main" && (!newest.has(name) || newest.get(name) === "closed"), + ); + const looseRows = loose.map( + ({ name }) => + `<li><a href="${compareHref(repo, name)}"><code>${esc(name)}</code></a> <span class="by">no pull yet: compare it with main</span></li>`, + ); + const main = [ + `<h1>Pulls</h1>`, + open.length ? `<ul class="pulls">${open.map(row).join("")}</ul>` : note("No pull is open."), + loose.length ? `<h2>Branches</h2><ul class="pulls">${looseRows.join("")}</ul>` : "", + done.length + ? `<details class="done"><summary>Merged and closed (${done.length})</summary><ul class="pulls">${done.map(row).join("")}</ul></details>` + : "", + `<p class="note">To propose a change: push a branch, then open <code>${esc(view.url.origin + repo)}/compare/<branch></code>.</p>`, + ].join(""); + return page(view, 200, "pulls", `Pulls · ${nameOf(repo)}`, main, {}); +} + +/** A branch against main, before it is a pull: its commits and what it changes, and for a member + * the box that opens the pull. A branch that has an open pull goes to the pull's page. */ +export async function comparePage(view: View, handle: Repo, itx: Itx, rest: string) { + const { repo, url } = view; + const branch = decodeURIComponent(rest); + const open = (await pullsIn(itx, repo)).find( + (pull) => pull.status === "open" && pull.branch === branch, + ); + if (open) return Response.redirect(`${url.origin}${repo}/pull/${open.number}`, 302); + const stand = await standingOf(handle, branch); + const missing = !stand.head + ? `${nameOf(repo)} has no branch ${branch}.` + : !stand.base + ? `${branch} and main share no commit in the history read.` + : stand.own.length === 0 + ? `${branch} has nothing that main has not.` + : null; + if (missing || !stand.head) + return page(view, stand.head ? 200 : 404, "pulls", "Compare", note(missing || ""), {}); + const changes = await keptChanges(view, handle, itx, stand.base, stand.head); + // the branch's first commit names the pull, as a start + const [subject, ...body] = stand.own.at(-1)!.message.trim().split("\n"); + const opener = view.me + ? `<div id="open-pull"></div>` + : `<p class="note"><a href="${signInHref(view)}">Sign in</a> to open a pull.</p>`; + const main = [ + `<article class="pull"><h1><code>${esc(branch)}</code> into <code>main</code></h1>`, + standingNote(stand, branch), + opener, + `<h2>Commits</h2>${commitRows(view, stand.own)}`, + `<h2>Files</h2>${filesHtml(changes)}</article>`, + ].join(""); + const data = { + compare: { branch, title: subject || branch, body: body.join("\n").trim() }, + diffs: diffsOf(changes), + }; + return page(view, 200, "pulls", `${branch} · ${nameOf(repo)}`, main, data); +} + +/** One pull: what it asks, its conversation, its commits and what it changes, with the comments + * that were made on lines. */ +export async function pullPage(view: View, handle: Repo, itx: Itx, rest: string) { + const { repo } = view; + const pull = /^[1-9][0-9]*$/.test(rest) + ? (await pullsIn(itx, repo)).find((pull) => pull.number === Number(rest)) + : undefined; + if (!pull) + return page(view, 404, "pulls", "Not found", note(`${nameOf(repo)} has no pull #${rest}.`), {}); + + // WHAT THE PULL CHANGES. A merged one: the commit it became, against that commit's parent. Any + // other: its branch against where the branch stands on main, while the repo has the branch. + let stand: Standing | null = null; + let changes: Change[] = []; + if (pull.status === "merged" && pull.commitOid) { + const commit = await commitAt(handle, pull.commitOid); + if (commit) + changes = await keptChanges(view, handle, itx, commit.parents[0] || null, commit.oid); + } else { + stand = await standingOf(handle, pull.branch); + if (stand.head && stand.base) + changes = await keptChanges(view, handle, itx, stand.base, stand.head); + } + + // A comment on a line stays on the line while the line still reads as it did. + const threads = pull.threads.map((thread) => { + const now = thread.place ? lineNow(changes, thread.place) : null; + const outdated = Boolean(thread.place && now?.text !== thread.place.quote); + return { ...thread, diff: now ? now.diff : null, outdated }; + }); + const conversation = threads.map((thread) => { + const place = thread.place + ? `<p class="place">${thread.diff === null ? "" : `<a href="#diff-${thread.diff}">`}<code>${esc(thread.place.path)}</code>${thread.diff === null ? "" : "</a>"} line ${thread.place.line}${thread.outdated ? ", which has changed since" : ""}<code class="quote">${esc(thread.place.quote)}</code></p>` + : ""; + const comments = thread.comments.map( + (comment) => + `<div class="comment"><p class="by">${esc(comment.by)}, ${utcStamp(Date.parse(comment.at))}</p><pre>${esc(comment.body)}</pre></div>`, + ); + return `<article class="thread" id="comment-${thread.id}">${place}${comments.join("")}${thread.resolved ? `<p class="by">Resolved.</p>` : ""}</article>`; + }); + + const branch = `<code>${esc(pull.branch)}</code>`; + const asks = + pull.status === "merged" + ? `squashed ${branch} into <code>main</code> as <a href="${esc(repo)}/commit/${pull.commitOid}"><code>${(pull.commitOid || "").slice(0, 7)}</code></a>` + : `wants ${branch} squashed into <code>main</code>`; + const standing = + pull.status !== "open" || !stand + ? "" + : !stand.head + ? note(`The branch ${pull.branch} is gone.`) + : standingNote(stand, pull.branch); + const writes = view.me + ? `<div id="merge"></div>` + : `<p class="note"><a href="${signInHref(view)}">Sign in</a> to comment or to merge.</p>`; + const main = [ + `<article class="pull"><h1>${esc(pull.title)} <span class="by">#${pull.number}</span></h1>`, + `<p class="by"><span class="tag ${pull.status}">${pull.status}</span> ${esc(pull.by)} ${asks}, ${utcStamp(Date.parse(pull.openedAt))}</p>`, + pull.body.trim() ? `<div class="body"><pre data-markdown data-dir="">${esc(pull.body)}</pre></div>` : "", + standing, + `<h2>Conversation</h2><section id="conversation">${conversation.join("") || note("Nobody has said anything yet.")}</section>`, + writes, + stand && stand.own.length ? `<h2>Commits</h2>${commitRows(view, stand.own)}` : "", + `<h2>Files</h2>${filesHtml(changes)}</article>`, + ].join(""); + const data = { + pull: { number: pull.number, title: pull.title, branch: pull.branch, status: pull.status }, + // what a squash asks for: the branch has main's newest commit, and changes something + mergeable: Boolean(stand?.upToDate && changes.length), + threads, + diffs: diffsOf(changes), + }; + return page(view, 200, "pulls", `${pull.title} #${pull.number} · ${nameOf(repo)}`, main, data); +} + +/** How a branch stands on main, in words: what it adds, and whether main has moved past what + * the branch has, which stops a squash. */ +function standingNote(stand: Standing, branch: string) { + const adds = `${stand.own.length} commit${stand.own.length === 1 ? "" : "s"}`; + const moved = stand.upToDate + ? "" + : note(`main has moved since ${branch} last had it. To merge: merge main into ${branch}, and push.`); + return `<p class="by"><code>${esc(branch)}</code> adds ${adds} to <code>main</code>.</p>${moved}`; +} + +/** The text now on the line a comment was made on, and which file of the page it is in; null + * when the page shows no such line. */ +function lineNow(changes: Change[], place: LinePlace) { + const diff = changes.findIndex(({ path }) => path === place.path); + const sides = diff < 0 ? null : changes[diff]!.sides; + if (!sides) return null; + const lines = (place.side === "additions" ? sides.after : sides.before).split("\n"); + return { diff, text: lines[place.line - 1] }; +} + +// ── THE DIFFERENCE BETWEEN TWO COMMITS ── + +/** The files that differ between two commits, kept in the mind's kv under + * `git-app:changes:<repo>:<before>:<after>`: neither commit ever changes. */ +async function keptChanges( + view: View, + handle: Repo, + itx: Itx, + before: string | null, + after: string, +): Promise<Change[]> { + const key = `git-app:changes:${view.repo}:${before || "nothing"}:${after}`; + const kept = await itx.kv.get(key); + if (kept) return z.array(Change).parse(JSON.parse(kept)); + const changes = await changesOf(handle, before, after); + await itx.kv.put(key, JSON.stringify(changes)); + return changes; +} + +/** The files that differ between the commit `beforeOid` (null: no files) and `afterOid`, each + * with both texts while the page has room for them. */ +async function changesOf(handle: Repo, beforeOid: string | null, afterOid: string) { + // The older one first: a repo holds the files of the commit it read last, and the newer one + // is the likelier next read. + const before = beforeOid ? await handle.files({ commitOid: beforeOid }) : {}; + const after = await handle.files({ commitOid: afterOid }); + let room = DIFF_CHARACTERS_SHOWN; + const changes: Change[] = []; + for (const path of Object.keys({ ...before, ...after }).sort()) { + const was = Object.hasOwn(before, path) ? before[path]! : null; + const is = Object.hasOwn(after, path) ? after[path]! : null; + // a file that is not text comes as `{ base64 }`: the same bytes are the same file + const same = + typeof was === "string" || typeof is === "string" + ? was === is + : was !== null && is !== null && was.base64 === is.base64; + if (same) continue; + const status = was === null ? "added" : is === null ? "deleted" : "modified"; + if ((was !== null && typeof was !== "string") || (is !== null && typeof is !== "string")) { + changes.push({ path, status, sides: null, note: "Not text, so no diff is shown." }); + continue; + } + const sides = { before: was || "", after: is || "" }; + const characters = sides.before.length + sides.after.length; + if (characters > room) { + const large = "Not shown: the change is larger than this page shows. A clone has it."; + changes.push({ path, status, sides: null, note: large }); + continue; + } + room -= characters; + changes.push({ path, status, sides, note: null }); + } + return changes; +} + +/** The files that changed: how many, their names, then each one under a name that folds it. The + * script draws each diff in its `data-diff` from the two texts (`diffsOf`). */ +function filesHtml(changes: Change[]) { + const letter = { added: "A", deleted: "D", modified: "M" }; + const names = changes.map( + (change, index) => + `<li><span class="status ${change.status}">${letter[change.status]}</span> <a href="#diff-${index}">${esc(change.path)}</a></li>`, + ); + const diffs = changes.map((change, index) => { + const shown = change.sides + ? `<div class="diff" data-diff="${index}"></div>` + : note(change.note || ""); + // each file folds: the reader closes the ones they have read + return `<details class="changed" id="diff-${index}" open><summary><span class="status ${change.status}">${letter[change.status]}</span> ${esc(change.path)}</summary>${shown}</details>`; + }); + const count = `${changes.length} file${changes.length === 1 ? "" : "s"} changed`; + return `<p>${count}</p><ul class="changes">${names.join("")}</ul>${diffs.join("")}`; +} + +/** What the script draws the page's diffs from: each file's path and its two texts, or null + * where the page shows no diff. */ +const diffsOf = (changes: Change[]) => + changes.map(({ path, sides }) => (sides ? { path, ...sides } : null)); + +// ── WHAT EVERY PAGE IS MADE OF ── + +/** One page: the head, the row that says where the reader is, `main`, and `data`, what the + * script draws from (with the repo's path and the member's name beside it). `tab` is the row's + * link that is marked as the one shown. */ +export function page( + view: { url: URL; repo: string | null; isPublic: boolean; me: string | null }, + status: number, + tab: "code" | "commits" | "pulls" | null, + title: string, + main: string, + data: Record<string, unknown>, +): Response { + const { url, repo } = view; + const zone = zoneOf(url); + const current = (name: string) => (tab === name ? ` aria-current="page"` : ""); + const where = repo + ? [ + `<p><a href="/">${esc(zone)}</a> / <a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>`, + view.isPublic ? "" : ` <span class="tag">private</span>`, + `</p><nav><a href="${esc(repo)}"${current("code")}>Code</a>`, + `<a href="${esc(repo)}/commits"${current("commits")}>Commits</a>`, + `<a href="${esc(repo)}/pulls"${current("pulls")}>Pulls</a></nav>`, + `<code class="clone">git clone ${esc(url.origin + repo)}</code>`, + ].join("") + : `<p><a href="/">${esc(zone)}</a></p>`; + const forScript = JSON.stringify({ repo, me: view.me, ...data }).replace(/</g, "\\u003c"); + const html = `<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>${esc(title)} · ${esc(zone)}</title> + <link rel="icon" href="/icon.svg" type="image/svg+xml" /> + <link rel="preconnect" href="https://esm.iterate.com" crossorigin /> + <script type="importmap">${IMPORT_MAP}</script> + <link rel="stylesheet" crossorigin href="${UI}/dist/styles.css" /> + <link rel="stylesheet" href="/theme.css" /> + <script> + if (getComputedStyle(document.documentElement).colorScheme === "dark") + document.documentElement.classList.add("dark"); + </script> + <link rel="stylesheet" href="/page.css" /> + </head> + <body> + <header class="where">${where}</header> + <main>${main}</main> + <script type="application/json" id="data">${forScript}</script> + <script type="module" src="/page.js"></script> + </body> +</html> +`; + return new Response(html, { + status, + headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" }, + }); +} + +const ESCAPES: Record<string, string> = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", +}; +const esc = (text: string) => text.replace(/[&<>"']/g, (character) => ESCAPES[character]!); +export const note = (text: string) => `<p class="note">${esc(text)}</p>`; +export const nameOf = (repo: string) => repo.slice("/repos/".length); +/** The zone the app is on: its hostname is one label under it. */ +const zoneOf = (url: URL) => url.hostname.split(".").slice(1).join("."); +const isMarkdown = (path: string) => /\.(md|markdown)$/i.test(path); +const subjectOf = (message: string) => message.trim().split("\n")[0] || ""; +/** The page of a file or a folder; the repo's own page for its root. */ +const treeHref = (repo: string, path: string) => + esc(path ? `${repo}/tree/main/${path.split("/").map(encodeURIComponent).join("/")}` : repo); +/** A moment as `2026-11-24 15:39 UTC`: the same for every reader. */ +const utcStamp = (timestamp: number) => + `${new Date(timestamp).toISOString().slice(0, 16).replace("T", " ")} UTC`; + +/** The page that compares a branch with main. */ +const compareHref = (repo: string, branch: string) => + esc(`${repo}/compare/${branch.split("/").map(encodeURIComponent).join("/")}`); +/** The mind's sign-in, and then back to this page. */ +const signInHref = (view: View) => esc(`/sign-in?to=${encodeURIComponent(view.url.pathname)}`); + +/** iterate's components, pinned to one build: the one the Dash pins. */ +const UI = "https://esm.iterate.com/@iterate-com/ui@0.1.0-main.20261124T154040Z-83b4390"; +const IMPORT_MAP = JSON.stringify({ + imports: { + "@iterate-com/ui/": `${UI}/`, + react: `${UI}/react`, + "react/": `${UI}/react/`, + "react-dom": `${UI}/react-dom`, + "react-dom/": `${UI}/react-dom/`, + "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom", + "@pierre/trees/react": "https://esm.iterate.com/@pierre/trees@1.0.0/react?external=react,react-dom", + "@pierre/diffs/react": "https://esm.iterate.com/@pierre/diffs@1.7.1/react?external=react,react-dom", + }, +});
A public/mind.js
@@ -0,0 +1,10 @@ +// mind.js — THE MEMBER'S itx, FOR THE PAGE. page.js asks for this module at the first thing a +// member writes: a comment, a pull, a merge. The itx is a session over a socket to this host's +// /itx, which app.ts answers for a member alone (`host.auth.memberPage`), so what the page writes +// is written as the member, and the platform records who. +// +// tests/serve.mjs serves another module at this address: one that writes to the stand-in mind on +// this machine. +import { memberItx } from "@iterate-com/ui/live"; + +export const itx = memberItx();
A public/page.css
@@ -0,0 +1,118 @@ +/* page.css — THE PAGES' OWN LOOK, over the UI kit's stylesheet (which resets every element) and + the mind's theme.css, whose colours these are. */ +body { margin: 0; font-size: 0.875rem; } +a { text-decoration: underline; text-underline-offset: 2px; } +code, pre { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.75rem; } +h1 { font-size: 1.125rem; font-weight: 600; margin-bottom: 0.75rem; } +.where { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 1.5rem; + padding: 0.625rem 1rem; border-bottom: 1px solid var(--border); } +.where nav { display: flex; gap: 1rem; } +.where nav a { text-decoration: none; color: var(--muted-foreground); } +.where nav a[aria-current] { color: var(--foreground); font-weight: 600; } +.where .clone { margin-left: auto; } +.clone { color: var(--muted-foreground); user-select: all; } +.tag { border: 1px solid var(--border); border-radius: 999px; padding: 0 0.5rem; + font-size: 0.75rem; color: var(--muted-foreground); } +.note, .by, .at { color: var(--muted-foreground); } +main > h1, main > ul, main > p, .commit { margin-left: 1rem; margin-right: 1rem; } +main > h1 { margin-top: 1rem; } +.repos li, .commits li { padding: 0.25rem 0; } +.repos .clone { margin-left: 0.75rem; } + +.code { display: grid; grid-template-columns: 17rem minmax(0, 1fr); } +#tree { position: sticky; top: 0; height: 100vh; overflow: auto; + border-right: 1px solid var(--border); } +#content { min-width: 0; padding: 0.875rem 1.25rem 3rem; } +@media (max-width: 48rem) { .code { display: block; } #tree { display: none; } } +.crumbs { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.35rem; + margin-bottom: 0.75rem; } +.crumbs .at { margin-left: auto; font-size: 0.75rem; } +.entries { border: 1px solid var(--border); border-radius: 0.5rem; overflow: hidden; } +.entries li + li { border-top: 1px solid var(--border); } +.entries a { display: block; padding: 0.3rem 0.75rem; text-decoration: none; + font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.8125rem; } +.entries a:hover { background: var(--accent); } +.readme { margin-top: 1.25rem; border: 1px solid var(--border); border-radius: 0.5rem; } +.readme > h2 { padding: 0.4rem 0.75rem; border-bottom: 1px solid var(--border); + font-size: 0.75rem; color: var(--muted-foreground); } +.readme > :not(h2), .markdown { padding: 1rem 1.25rem; } +#content > .markdown { padding: 0; } +pre { overflow: auto; line-height: 1.5; } +#content > pre, #content > .file { border: 1px solid var(--border); border-radius: 0.5rem; } +#content > pre { padding: 0.75rem; } +#content > .file { overflow: hidden; } +#content > .note { margin-bottom: 0.5rem; font-size: 0.75rem; } + +.commit { margin-top: 1rem; margin-bottom: 3rem; } +.commit .message { margin-bottom: 0.75rem; white-space: pre-wrap; } +.commit > p { margin-bottom: 0.5rem; } +.changes { margin-bottom: 1.5rem; } +.changes li, .changed > summary { font-family: var(--font-mono, ui-monospace, monospace); + font-size: 0.8125rem; } +.changed { margin-top: 1.25rem; border: 1px solid var(--border); border-radius: 0.5rem; } +/* the file's name stays at the top of the window while its diff is read */ +.changed > summary { position: sticky; top: 0; z-index: 1; padding: 0.4rem 0.75rem; + cursor: pointer; background: var(--background); border-radius: 0.5rem; } +.changed[open] > summary { border-bottom: 1px solid var(--border); + border-radius: 0.5rem 0.5rem 0 0; } +.changed > .note { padding: 0.5rem 0.75rem; } +.diff { min-height: 4rem; overflow: hidden; border-radius: 0 0 0.5rem 0.5rem; } +.status { font-weight: 600; } +.status.added { color: light-dark(oklch(0.5 0.15 150), oklch(0.75 0.15 150)); } +.status.deleted { color: var(--destructive); } +.status.modified { color: light-dark(oklch(0.5 0.13 250), oklch(0.75 0.13 250)); } + +/* ── pulls ── */ +h2 { margin: 1.5rem 0 0.5rem; font-size: 0.9375rem; font-weight: 600; } +main > h2, main > details { margin-left: 1rem; margin-right: 1rem; } +.pulls li { padding: 0.25rem 0; } +.done { margin-top: 1.25rem; } +.done summary { cursor: pointer; color: var(--muted-foreground); } +.pull { margin: 1rem 1rem 3rem; } +.pull > p { margin-bottom: 0.5rem; } +.pull .changes { margin-bottom: 1.5rem; } +.tag.open { color: light-dark(oklch(0.5 0.15 150), oklch(0.75 0.15 150)); } +.tag.merged { color: light-dark(oklch(0.5 0.15 300), oklch(0.75 0.15 300)); } +.body, .thread, .box { border: 1px solid var(--border); border-radius: 0.5rem; } +.body { margin: 0.75rem 0; padding: 0.75rem 1rem; } +.thread { margin: 0.5rem 0; max-width: 46rem; background: var(--background); + font-family: var(--font-sans, system-ui, sans-serif); font-size: 0.8125rem; white-space: normal; } +.thread.resolved { opacity: 0.6; } +.thread .place { padding: 0.4rem 0.75rem; border-bottom: 1px solid var(--border); + color: var(--muted-foreground); font-size: 0.75rem; } +.thread .quote { display: block; margin-top: 0.25rem; overflow: hidden; text-overflow: ellipsis; + white-space: pre; color: var(--foreground); } +.comment { padding: 0.5rem 0.75rem; } +.comment + .comment { border-top: 1px solid var(--border); } +.comment .by { margin-bottom: 0.25rem; font-size: 0.75rem; } +.comment pre { white-space: pre-wrap; font-family: inherit; font-size: inherit; } +.thread .actions { position: relative; padding: 0.4rem 0.75rem; + border-top: 1px solid var(--border); } +.reply summary { display: inline-block; cursor: pointer; color: var(--muted-foreground); } +.reply[open] summary { margin-bottom: 0.5rem; } +/* beside "Reply", wherever the reply box is open or shut */ +.thread .resolve { position: absolute; top: 0.3rem; right: 0.75rem; padding: 0.1rem 0.6rem; + font-size: 0.75rem; } +.thread .reply .box { padding: 0; border: 0; } +/* a thread on a line of a diff: pierre lays it out under the line */ +.diff .thread { margin: 0.5rem; } + +.box { display: grid; gap: 0.5rem; max-width: 46rem; margin: 0.75rem 0; padding: 0.75rem; + background: var(--background); font-family: var(--font-sans, system-ui, sans-serif); + font-size: 0.8125rem; white-space: normal; } + +.diff .box { margin: 0.5rem; } +.box input, .box textarea { width: 100%; padding: 0.4rem 0.6rem; border: 1px solid var(--input); + border-radius: 0.375rem; background: var(--background); font: inherit; } +.box textarea { min-height: 4.5rem; resize: vertical; } +.box .row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; } +.box .problem { color: var(--destructive); } +button { padding: 0.3rem 0.75rem; border: 1px solid var(--border); border-radius: 0.375rem; + background: var(--secondary); color: var(--secondary-foreground); font-size: 0.8125rem; + cursor: pointer; } +button.main { border-color: var(--primary); background: var(--primary); + color: var(--primary-foreground); } +button:disabled { opacity: 0.5; cursor: default; } +.merge { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0.75rem 0; } +.merge .box { margin: 0; padding: 0; border: 0; } +h1 code { font-size: 0.9em; }
A public/page.js
@@ -0,0 +1,391 @@ +// page.js — WHAT THE BROWSER RUNS on every page of the git app. ../pages.ts writes each page whole, +// and hands this script `data` (a JSON element of the page). The script draws, in their places: +// +// - the file tree, and each file and README in the place of its <pre> +// - each diff, when the reader scrolls near it +// - on a pull, for a member: the conversation with its reply boxes, a comment box on any line +// of a diff, and the buttons that merge or close; on a compare page, the box that opens a pull +// +// WHAT A MEMBER WRITES IS ONE APPEND to the repo's context (../pulls.ts says which events), through +// the member's own itx (mind.js). The page then shows what was written from what it sent: it does +// not read the pull again. +// +// Nothing here keeps state in a component. What changes is in the few arrays below, and `redraw` +// draws the roots again from them. +import { html } from "@iterate-com/ui/page"; +import { createRoot } from "react-dom/client"; + +const data = JSON.parse(document.getElementById("data").textContent); +// The page's look is the mind's theme.css. Pierre's components would follow the visitor's system, +// so they are told. +const dark = getComputedStyle(document.documentElement).colorScheme === "dark"; +const pierre = { + theme: { light: "pierre-light", dark: "pierre-dark" }, + themeType: dark ? "dark" : "light", + disableFileHeader: true, +}; + +// what is drawn in the content of a page of files, to take down when that content is replaced +let drawn = []; +function draw(place, node) { + const root = createRoot(place); + root.render(node); + drawn.push(root); +} +// The <pre> stays until the component has drawn something, so the text never blinks away. +function inPlaceOf(pre, className) { + const place = document.createElement("div"); + place.className = className; + pre.after(place); + const waiting = new ResizeObserver(() => { + if (place.offsetHeight === 0) return; + waiting.disconnect(); + pre.remove(); + }); + waiting.observe(place); + return place; +} + +// Markdown as a chat of the mind draws it: loaded once, when a page has some to draw. +let Markdown; +async function markdown() { + Markdown ||= (await import("@iterate-com/ui/components/agent-chat/chat-parts")).Markdown; +} + +/** Each <pre> of a file or a README in its richer form: with its colours, or as markdown. */ +async function drawContent() { + const files = [...document.querySelectorAll("pre[data-file]")]; + const markdowns = [...document.querySelectorAll("pre[data-markdown]")]; + if (files.length) { + const { File } = await import("@pierre/diffs/react"); + for (const pre of files.filter((pre) => pre.isConnected)) { + const file = { name: pre.dataset.file, contents: pre.textContent }; + draw(inPlaceOf(pre, "file"), html`<${File} file=${file} options=${pierre} />`); + } + } + if (markdowns.length) { + await markdown(); + for (const pre of markdowns.filter((pre) => pre.isConnected)) { + const place = inPlaceOf(pre, "markdown"); + place.dataset.dir = pre.dataset.dir; + draw(place, html`<${Markdown}>${pre.textContent}<//>`); + } + } +} + +// ── WHAT A MEMBER WRITES ── + +let mindModule; +/** The member's itx, asked for at the first write: a page that is only read opens no socket. */ +const mind = () => (mindModule ||= import("/mind.js")).then((module) => module.itx); +/** One event on the repo's context, which is where its pulls are. */ +const append = async (type, payload) => (await (await mind()).cd(data.repo).append({ type, payload }))[0]; + +/** A box that writes: its fields, the button that sends them, and what went wrong if the mind + * refused. `send` gets the fields by name. Cmd or Ctrl with Enter sends too. */ +function Form({ button, quiet, disabled, send, cancel, children }) { + async function submitted(event) { + event.preventDefault(); + const form = event.currentTarget; + const buttons = [...form.querySelectorAll("button")]; + const problem = form.querySelector(".problem"); + problem.textContent = ""; + for (const each of buttons) each.disabled = true; + try { + await send(Object.fromEntries(new FormData(form))); + form.reset(); + } catch (error) { + problem.textContent = error instanceof Error ? error.message : String(error); + } + for (const each of buttons) each.disabled = false; + } + const keyed = (event) => { + if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) event.currentTarget.requestSubmit(); + }; + return html`<form className="box" onSubmit=${submitted} onKeyDown=${keyed}> + ${children} + <div className="row"> + <button className=${quiet ? null : "main"} disabled=${disabled}>${button}</button> + ${cancel && html`<button type="button" onClick=${cancel}>Cancel</button>`} + <span className="problem"></span> + </div> + </form>`; +} + +// ── A PULL: its threads, in the conversation and on the lines of the diffs ── + +/** The pull's threads as the page came with them, then with what this member wrote. A thread on + * a line has `place` and `diff`, the file of this page it is in; `outdated` says the line has + * changed since. */ +const threads = data.threads || []; +/** A comment being written on a line: `{ diff, side, line }`. */ +const drafts = []; + +const stamp = (at) => new Date(at).toISOString().slice(0, 16).replace("T", " ") + " UTC"; +const said = (event, body) => ({ id: event.offset, by: data.me, at: event.createdAt, body }); + +async function comment(body, place, draft) { + const pull = data.pull.number; + const event = await append("pull/commented", { pull, body: body.trim(), replyTo: null, at: place }); + if (draft) drafts.splice(drafts.indexOf(draft), 1); + const diff = draft ? draft.diff : null; + threads.push({ id: event.offset, place, diff, outdated: false, resolved: false, comments: [said(event, body.trim())] }); + redraw(); +} +async function reply(thread, body) { + const pull = data.pull.number; + const event = await append("pull/commented", { pull, body: body.trim(), replyTo: thread.id, at: null }); + thread.comments.push(said(event, body.trim())); + redraw(); +} +async function resolve(thread) { + await append("pull/resolved", { pull: data.pull.number, comment: thread.id }); + thread.resolved = true; + redraw(); +} + +/** One thread: what was said, and for a member the box that replies and the button that + * resolves. `listed` is the thread in the conversation, where it says which line it is on. */ +function Thread({ thread, listed }) { + const place = thread.place; + const where = + listed && + place && + html`<p className="place"> + ${thread.diff === null ? html`<code>${place.path}</code>` : html`<a href=${"#diff-" + thread.diff}><code>${place.path}</code></a>`} + ${" line " + place.line}${thread.outdated ? ", which has changed since" : ""} + <code className="quote">${place.quote}</code> + </p>`; + // the reply box opens under "Reply": a thread is read far more often than answered + const writes = + data.me && + html`<details className="reply"> + <summary>Reply</summary> + <${Form} button="Reply" send=${({ text }) => reply(thread, text)}> + <textarea name="text" placeholder="Reply" required></textarea> + <//> + </details>`; + const resolves = + data.me && + !thread.resolved && + html`<button type="button" className="resolve" onClick=${() => resolve(thread)}>Resolve</button>`; + return html`<article className=${thread.resolved ? "thread resolved" : "thread"} id=${listed ? "comment-" + thread.id : null}> + ${where} + ${thread.comments.map( + (each) => html`<div className="comment" key=${each.id}> + <p className="by">${each.by}, ${stamp(each.at)}</p> + <${Markdown}>${each.body}<//> + </div>`, + )} + ${thread.resolved && html`<p className="by comment">Resolved.</p>`} + ${data.me && html`<div className="actions">${writes} ${resolves}</div>`} + </article>`; +} + +function Conversation() { + return html`<div> + ${threads.length === 0 && html`<p className="note">Nobody has said anything yet.</p>`} + ${threads.map((thread) => html`<${Thread} key=${thread.id} thread=${thread} listed />`)} + ${data.me && + html`<${Form} button="Comment" send=${({ text }) => comment(text, null, null)}> + <textarea name="text" placeholder="Say something about this pull" required></textarea> + <//>`} + </div>`; +} + +/** The box under a line of a diff where a member writes a comment on that line. */ +function Draft({ draft }) { + const { path, before, after } = data.diffs[draft.diff]; + // the line's own text goes with the comment: the comment stays on the line while it reads so + const quote = (draft.side === "additions" ? after : before).split("\n")[draft.line - 1] || ""; + const place = { path, side: draft.side, line: draft.line, quote }; + const discard = () => { + drafts.splice(drafts.indexOf(draft), 1); + drawDiff(draft.diff); + }; + return html`<${Form} button="Comment" send=${({ text }) => comment(text, place, draft)} cancel=${discard}> + <textarea name="text" placeholder="Comment on this line" required autoFocus></textarea> + <//>`; +} + +/** The buttons of an open pull. A squash is offered while the branch has main's newest commit. */ +function MergeBox() { + const merge = async () => { + await (await mind()).config.pullMerge(data.repo, data.pull.number); + location.reload(); + }; + const close = async () => { + await append("pull/closed", { pull: data.pull.number }); + location.reload(); + }; + return html`<div className="merge"> + <${Form} button="Squash and merge" disabled=${!data.mergeable} send=${merge} /> + <${Form} button="Close without merging" quiet send=${close} /> + </div>`; +} + +/** On a compare page: the box that opens the pull, which the server then shows in this page's + * place. */ +function OpenPull() { + const open = async ({ title, body }) => { + await append("pull/opened", { branch: data.compare.branch, title: title.trim(), body }); + location.reload(); + }; + return html`<${Form} button="Open a pull" send=${open}> + <input name="title" defaultValue=${data.compare.title} aria-label="Title" required /> + <textarea name="body" defaultValue=${data.compare.body} placeholder="What this changes, and why"></textarea> + <//>`; +} + +// ── THE DIFFS ── + +let MultiFileDiff; +/** Each diff's root, by its number on the page, once it is drawn; and what it is drawn from, + * kept so that a redraw hands pierre the same objects and it does not work the diff out again. */ +const diffRoots = new Map(); +const diffProps = new Map(); + +function drawDiff(index) { + const { path, before, after } = data.diffs[index]; + const fixed = diffProps.get(index) || { + oldFile: { name: path, contents: before }, + newFile: { name: path, contents: after }, + options: { + ...pierre, + diffStyle: "unified", + // a member comments on a line of a pull: the button that pierre shows beside the line + enableGutterUtility: Boolean(data.pull && data.me), + onGutterUtilityClick: (range) => { + drafts.push({ diff: index, side: range.side || "additions", line: range.start }); + drawDiff(index); + }, + }, + renderAnnotation: ({ metadata }) => + metadata.thread ? html`<${Thread} thread=${metadata.thread} />` : html`<${Draft} draft=${metadata.draft} />`, + }; + diffProps.set(index, fixed); + const here = threads.filter((thread) => thread.diff === index && !thread.outdated && !thread.resolved); + const lineAnnotations = [ + ...here.map((thread) => ({ side: thread.place.side, lineNumber: thread.place.line, metadata: { thread } })), + ...drafts.filter((draft) => draft.diff === index).map((draft) => ({ side: draft.side, lineNumber: draft.line, metadata: { draft } })), + ]; + diffRoots.get(index).render(html`<${MultiFileDiff} ...${fixed} lineAnnotations=${lineAnnotations} />`); +} + +// Each diff is drawn when the reader scrolls near it: a commit may change many files. +async function drawDiffs() { + const places = document.querySelectorAll("[data-diff]"); + if (places.length === 0) return; + // a file's name in the list of changes opens that file, if the reader had folded it + document.addEventListener("click", (event) => { + const link = event.target.closest(".changes a"); + const file = link && document.querySelector(link.getAttribute("href")); + if (file) file.open = true; + }); + MultiFileDiff = (await import("@pierre/diffs/react")).MultiFileDiff; + // a thread on a line is drawn with markdown + if (threads.length || data.me) await markdown(); + const near = new IntersectionObserver( + (entries) => { + for (const entry of entries.filter((entry) => entry.isIntersecting)) { + near.unobserve(entry.target); + const index = Number(entry.target.dataset.diff); + diffRoots.set(index, createRoot(entry.target)); + drawDiff(index); + } + }, + { rootMargin: "800px" }, + ); + for (const place of places) near.observe(place); +} + +let conversation; +/** Everything that shows the pull's threads, drawn again from `threads` and `drafts`. */ +function redraw() { + if (conversation) conversation.render(html`<${Conversation} />`); + for (const index of diffRoots.keys()) drawDiff(index); +} + +async function drawPull() { + const place = document.getElementById("conversation"); + if (place) { + await markdown(); + conversation = createRoot(place); + redraw(); + } + const merge = document.getElementById("merge"); + if (merge && data.pull.status === "open") createRoot(merge).render(html`<${MergeBox} />`); + const open = document.getElementById("open-pull"); + if (open) createRoot(open).render(html`<${OpenPull} />`); +} + +// ── A PAGE OF FILES: the tree, and a click that takes the next page's content alone ── + +const treePlace = document.getElementById("tree"); +const treeHref = (path) => + path ? data.repo + "/tree/main/" + path.split("/").map(encodeURIComponent).join("/") : data.repo; +const shownPath = () => decodeURIComponent(location.pathname.slice((data.repo + "/tree/main/").length)); +let tree; + +async function visit(href, push) { + const answer = await fetch(href); + const next = new DOMParser().parseFromString(await answer.text(), "text/html"); + const content = next.getElementById("content"); + // a page with no content of this kind (a sign-in, an error) is shown whole + if (!content) return location.assign(href); + for (const root of drawn) root.unmount(); + drawn = []; + document.getElementById("content").replaceWith(document.adoptNode(content)); + document.title = next.title; + if (push) history.pushState(null, "", href); + scrollTo(0, 0); + const item = tree && tree.getItem(shownPath()); + if (item && !item.isDirectory() && !item.isSelected()) item.select(); + await drawContent(); +} + +async function drawTree() { + if (!treePlace) return; + const { FileTree, useFileTree } = await import("@pierre/trees/react"); + const files = new Set(data.paths); + // the folders above what is shown are open; a small repo is open whole + const segments = data.path.split("/").filter(Boolean); + const above = segments.map((_, index) => segments.slice(0, index + 1).join("/")); + function Tree() { + const { model } = useFileTree({ + paths: data.paths, + initialExpansion: data.paths.length > 150 ? "closed" : "open", + initialExpandedPaths: above, + initialSelectedPaths: files.has(data.path) ? [data.path] : [], + search: true, + onSelectionChange: (paths) => { + if (files.has(paths[0]) && paths[0] !== shownPath()) visit(treeHref(paths[0]), true); + }, + }); + tree = model; + return html`<${FileTree} model=${model} style=${{ colorScheme: "inherit", height: "100%" }} />`; + } + createRoot(treePlace).render(html`<${Tree} />`); + + addEventListener("popstate", () => visit(location.href, false)); + document.addEventListener("click", (event) => { + const plain = event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey; + const link = plain && !event.defaultPrevented && event.target.closest("#content a[href]"); + if (!link) return; + // a link in a README is written against the folder of the file it is in + const written = link.getAttribute("href"); + const inMarkdown = link.closest(".markdown"); + const relative = inMarkdown && !/^([a-z][a-z0-9+.-]*:|\/|#)/i.test(written); + const dir = inMarkdown && inMarkdown.dataset.dir ? treeHref(inMarkdown.dataset.dir) + "/" : data.repo + "/tree/main/"; + const url = new URL(relative ? new URL(written, location.origin + dir) : link.href); + const ofThisRepo = url.pathname === data.repo || url.pathname.startsWith(data.repo + "/tree/"); + if (url.origin !== location.origin || !ofThisRepo) return; + event.preventDefault(); + visit(url.pathname + url.search, true); + }); +} + +drawTree(); +drawContent(); +drawDiffs(); +drawPull();
A pulls.ts
@@ -0,0 +1,257 @@ +// pulls.ts — WHAT A PULL IS: a branch that someone asks to have squashed into `main`, with a +// title, a body and a conversation. +// +// A REPO'S PULLS ARE EVENTS ON THE REPO'S OWN CONTEXT (/repos/<name>), beside the repo's own +// (`repo/pushed`, `repo/commit-completed`). Nothing else holds them: +// +// pull/opened { branch, title, body } +// pull/edited { pull, title, body } +// pull/commented { pull, body, replyTo, at } at: { path, side, line, quote }, or null +// pull/resolved { pull, comment } +// pull/merged { pull, commitOid } +// pull/closed { pull } +// +// A PULL'S NUMBER IS ITS PLACE AMONG THE `pull/opened` EVENTS: the seventh one is #7. The log's +// order decides, so nothing hands numbers out. A COMMENT'S ID IS ITS EVENT'S OFFSET: `replyTo` +// and `comment` name offsets. WHO AND WHEN are the event's own (`source.principal`, `createdAt`), +// which the platform stamps and no writer can set. +// +// To open a pull, to comment or to close one is one append to the repo's context, by a member's +// page or by an agent: +// +// itx.cd("/repos/git").append({ type: "pull/commented", payload: { pull: 7, body, replyTo: null, at: null } }) +// +// TO MERGE IS THE ONE CALL (`mergePull`, which the mind's API offers as `itx.config.pullMerge`). +// A pull is squashed: one commit on main with the branch's files, named `<title> (#7)` with the +// body under it. It is taken only while the branch has main's newest commit in its history, so +// no two changes are ever woven together here: when main has moved, merge main into the branch +// and push. Main is then a straight line, each commit one pull. +import type { RepoLogEntry } from "iterate/api"; +import type { IterateConfigEntrypoint } from "iterate/sdk"; +import type { StreamEvent } from "iterate/stream/processor"; +import { z } from "zod"; + +type Itx = ReturnType<IterateConfigEntrypoint["getItx"]>; +type Repo = ReturnType<Itx["repos"]["get"]>; +type Files = Awaited<ReturnType<Repo["files"]>>; + +/** Where a comment on a line is: the file, the side of the diff, the line's number on that side, + * and the line's text when the comment was written. The comment stays on the line while the line + * still reads so. */ +const LinePlace = z.object({ + path: z.string().min(1), + side: z.enum(["additions", "deletions"]), + line: z.number().int().positive(), + quote: z.string(), +}); +export type LinePlace = z.infer<typeof LinePlace>; + +const Opened = z.object({ branch: z.string().min(1), title: z.string().min(1), body: z.string() }); +const Edited = z.object({ pull: z.number(), title: z.string().min(1), body: z.string() }); +const Commented = z.object({ + pull: z.number(), + body: z.string().min(1), + replyTo: z.number().nullable(), + at: LinePlace.nullable(), +}); +const Resolved = z.object({ pull: z.number(), comment: z.number() }); +const Merged = z.object({ pull: z.number(), commitOid: z.string().regex(/^[0-9a-f]{40}$/) }); +const Closed = z.object({ pull: z.number() }); + +export type PullComment = { id: number; by: string; at: string; body: string }; +/** A comment and the replies to it. `place` is there for a comment on a line. */ +export type PullThread = { + id: number; + place: LinePlace | null; + resolved: boolean; + comments: PullComment[]; +}; +export type Pull = { + number: number; + branch: string; + title: string; + body: string; + /** Who opened it, as a page shows them, and as git names an author. */ + by: string; + author: { name: string; email: string } | null; + openedAt: string; + status: "open" | "merged" | "closed"; + /** The commit on main that a merged pull became. */ + commitOid: string | null; + threads: PullThread[]; +}; + +/** Who wrote an event, as a page shows them: the name before the `@` of a person's address, or + * for code with nobody behind it the context it ran in. */ +export function writerOf(event: Pick<StreamEvent, "source">): string { + const person = event.source.principal || event.source.onBehalfOf?.principal; + if (person?.email) return person.email.split("@")[0]!; + return person?.name || event.source.origin; +} + +/** THE PULLS THAT A REPO'S EVENTS MAKE, oldest first. An event that is no pull's, or whose + * payload does not parse, changes nothing. */ +export function pullsOf(events: StreamEvent[]): Pull[] { + const pulls: Pull[] = []; + const open = (number: number) => pulls.find((pull) => pull.number === number); + for (const event of events) { + const payload = event.payload || {}; + if (event.type === "pull/opened") { + const opened = Opened.safeParse(payload); + if (!opened.success) continue; + const person = event.source.principal || event.source.onBehalfOf?.principal; + pulls.push({ + ...opened.data, + number: pulls.length + 1, + by: writerOf(event), + author: person?.email ? { name: writerOf(event), email: person.email } : null, + openedAt: event.createdAt, + status: "open", + commitOid: null, + threads: [], + }); + } else if (event.type === "pull/edited") { + const edited = Edited.safeParse(payload); + const pull = edited.success ? open(edited.data.pull) : undefined; + if (pull && edited.success) Object.assign(pull, { title: edited.data.title, body: edited.data.body }); + } else if (event.type === "pull/commented") { + const commented = Commented.safeParse(payload); + const pull = commented.success ? open(commented.data.pull) : undefined; + if (!pull || !commented.success) continue; + const comment = { id: event.offset, by: writerOf(event), at: event.createdAt, body: commented.data.body }; + const thread = pull.threads.find(({ id }) => id === commented.data.replyTo); + if (thread) thread.comments.push(comment); + else pull.threads.push({ id: event.offset, place: commented.data.at, resolved: false, comments: [comment] }); + } else if (event.type === "pull/resolved") { + const resolved = Resolved.safeParse(payload); + const pull = resolved.success ? open(resolved.data.pull) : undefined; + const thread = pull?.threads.find(({ id }) => resolved.success && id === resolved.data.comment); + if (thread) thread.resolved = true; + } else if (event.type === "pull/merged") { + const merged = Merged.safeParse(payload); + const pull = merged.success ? open(merged.data.pull) : undefined; + if (pull?.status === "open" && merged.success) + Object.assign(pull, { status: "merged", commitOid: merged.data.commitOid }); + } else if (event.type === "pull/closed") { + const closed = Closed.safeParse(payload); + const pull = closed.success ? open(closed.data.pull) : undefined; + if (pull?.status === "open") pull.status = "closed"; + } + } + return pulls; +} + +/** The repo's pulls, read from its context's whole log. */ +export async function pullsIn(itx: Itx, repo: string): Promise<Pull[]> { + const events: StreamEvent[] = []; + let after = 0; + for (;;) { + const page = await itx.cd(repo).readEvents(after, 1000); + events.push(...page.events); + if (page.atHead) return pullsOf(events); + after = page.scannedThroughOffset; + } +} + +/** How far back the two histories are read to find where a branch stands. */ +const HISTORY_READ = 300; + +/** WHERE A BRANCH STANDS ON MAIN. `head` is its newest commit, `own` the commits that are its + * own (newest first), and `base` the newest commit of main that it has in its history: where it + * left main, or the commit of main it last merged in. `upToDate` says that `base` is main's + * newest, which is what a squash asks for. `head` is null for a branch the repo has not got, and + * `base` when the two share no commit in the history read. */ +export type Standing = { + head: string | null; + mainTip: string | null; + base: string | null; + own: RepoLogEntry[]; + upToDate: boolean; +}; + +export async function standingOf(handle: Repo, branch: string): Promise<Standing> { + const head = (await handle.branches()).find(({ name }) => name === branch)?.commitOid || null; + const main = await handle.log({ limit: HISTORY_READ }); + const mainTip = main[0]?.oid || null; + if (!head) return { head, mainTip, base: null, own: [], upToDate: false }; + return { head, mainTip, ...baseOf(main, await handle.log({ limit: HISTORY_READ, from: head })) }; +} + +/** `main` and `branch` are each a history, newest first, along first parents. Main is a straight + * line, so a commit of main reaches a branch in two ways alone: the branch began at it, or the + * branch merged it in, where it is a merge's second parent. The newest of those is the base. */ +export function baseOf(main: RepoLogEntry[], branch: RepoLogEntry[]) { + const placeOnMain = new Map(main.map(({ oid }, index) => [oid, index])); + const own: RepoLogEntry[] = []; + const reached: number[] = []; + for (const commit of branch) { + const place = placeOnMain.get(commit.oid); + // the commit where the branch began: everything older is main's own + if (place !== undefined) { + reached.push(place); + break; + } + own.push(commit); + for (const merged of commit.parents.slice(1)) { + const mergedAt = placeOnMain.get(merged); + if (mergedAt !== undefined) reached.push(mergedAt); + } + } + const newest = reached.length ? Math.min(...reached) : null; + return { base: newest === null ? null : main[newest]!.oid, own, upToDate: newest === 0 }; +} + +/** The message of the commit that a pull becomes: `Make the header red (#7)`, then the body. */ +export const squashMessage = (pull: Pick<Pull, "number" | "title" | "body">) => + `${pull.title} (#${pull.number})\n\n${pull.body.trim()}`.trim() + "\n"; + +/** SQUASH A PULL INTO MAIN: one commit on main that makes main's files the branch's, then the + * `pull/merged` event that says so. It throws, in words for the person who asked, when the pull + * is not open, its branch is gone, or main has moved past what the branch has. */ +export async function mergePull(itx: Itx, repo: string, number: number) { + const pull = (await pullsIn(itx, repo)).find((pull) => pull.number === number); + if (!pull) throw new Error(`${repo} has no pull #${number}`); + if (pull.status !== "open") throw new Error(`#${number} is ${pull.status} already`); + const handle = itx.repos.get(repo); + const { head, mainTip, upToDate } = await standingOf(handle, pull.branch); + if (!head) throw new Error(`the branch ${pull.branch} is gone`); + if (!upToDate || !mainTip) + throw new Error( + `main has moved since ${pull.branch} last had it: merge main into ${pull.branch}, push, and merge again`, + ); + const changes = fileChanges( + await handle.files({ commitOid: mainTip }), + await handle.files({ commitOid: head }), + ); + if (changes.length === 0) throw new Error(`${pull.branch} changes nothing on main`); + const { commitOid } = await handle.commitFiles({ + message: squashMessage(pull), + changes, + // refused if main moved while this was read + parent: mainTip, + ...(pull.author && { author: pull.author }), + }); + if (!commitOid) throw new Error("the commit was not made"); + await itx.cd(repo).append({ + type: "pull/merged", + // one pull is merged once: a second try of this call lands no second event + idempotencyKey: `pull/merged:${number}`, + payload: { pull: number, commitOid }, + }); + return { commitOid }; +} + +/** What a commit must change to turn the files `before` into the files `after`. */ +function fileChanges(before: Files, after: Files) { + const changes: Parameters<Repo["commitFiles"]>[0]["changes"] = []; + for (const path of Object.keys({ ...before, ...after }).sort()) { + const was = Object.hasOwn(before, path) ? before[path]! : null; + const is = Object.hasOwn(after, path) ? after[path]! : null; + if (is === null) changes.push({ path, delete: true }); + else if (typeof is === "string") { + if (was !== is) changes.push({ path, content: is }); + } else if (was === null || typeof was === "string" || was.base64 !== is.base64) + changes.push({ path, bytes: Uint8Array.from(atob(is.base64), (c) => c.charCodeAt(0)) }); + } + return changes; +}
M tests/app.test.mjs
@@ -3,11 +3,13 @@ // mind is a fake `itx` with a kv and the Artifacts verbs the app calls. The app's own fetch goes // to that server. pages.test.mjs has the pages a browser reads. // Run it from the repo's root with `node --test "tests/*.test.mjs"`. +import "../../mind-loader.mjs"; import assert from "node:assert/strict"; import { createServer } from "node:http"; import { test } from "node:test"; -import { gitApp } from "../app.ts"; +const { gitApp } = await import("../app.ts"); + test("anyone clones a public repo: the app adds a read token of its own, minted once and kept in the mind's kv", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); @@ -181,7 +183,7 @@ // ── the fixtures ── /** What worker.ts hands the app for its pages, which no test here reads. */ -const look = { icon: () => new Response("the icon"), theme: "" }; +const look = { icon: () => new Response("the icon") }; /** The mind as the app reaches it: a kv, and the Artifacts repos `kernel` and `config`, served * by `remote`. It records each token it mints and each repo whose remote it was asked for. */ @@ -213,7 +215,8 @@ }, [Symbol.dispose]() {}, }; - return { kv, minted, remotesAsked, getItx: () => itx }; + // what is no git request is asked whether it is a member's socket: here none is + return { kv, minted, remotesAsked, getItx: () => itx, auth: { memberPage: () => null } }; } /** A repo's Artifacts remote: a server on this machine that records each request and answers as
A tests/fixtures.mjs
@@ -0,0 +1,91 @@ +// tests/fixtures.mjs — what the tests of the git app's pages share: a repo made with git itself, +// and two readers of a page's HTML. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +/** A repo in a folder of its own, made by one step for each entry of `history`, a minute apart + * from 10:01 UTC on 24 Nov 2026, all by Ada Author. + * + * { message, files } a commit on main: each file written, or deleted when null + * { on: "a-fix", message, files } a commit on that branch, which starts at main's newest + * { on: "a-fix", merge: "main" } that branch takes main in, as a merge commit + * + * `commits` are the oids in the order made, and `more(step)` makes one more later in the test. + * The folder goes when the test ends. */ +export function repoWith(history) { + const folder = mkdtempSync(join(tmpdir(), "git-app-")); + const git = (args, minute) => + execFileSync("git", ["-C", folder, ...args], { + env: { + PATH: process.env.PATH, + // this machine's own git settings stay out of the test (hooks, signing) + GIT_CONFIG_GLOBAL: "/dev/null", + GIT_CONFIG_SYSTEM: "/dev/null", + GIT_AUTHOR_NAME: "Ada Author", + GIT_AUTHOR_EMAIL: "ada@example.com", + GIT_COMMITTER_NAME: "Ada Author", + GIT_COMMITTER_EMAIL: "ada@example.com", + GIT_AUTHOR_DATE: `2026-11-24T10:${String(minute).padStart(2, "0")}:00Z`, + GIT_COMMITTER_DATE: `2026-11-24T10:${String(minute).padStart(2, "0")}:00Z`, + }, + }) + .toString() + .trim(); + git(["init", "--quiet", "--initial-branch=main"], 0); + const branches = new Set(["main"]); + let checkedOut = "main"; + const checkOut = (branch, minute) => { + if (branch === checkedOut) return; + // a branch that is new starts where main is + git(["checkout", "--quiet", ...(branches.has(branch) ? [] : ["-b"]), branch], minute); + branches.add(branch); + checkedOut = branch; + }; + let minute = 0; + const made = (step) => { + minute += 1; + checkOut(step.on || "main", minute); + if (step.merge) git(["merge", "--quiet", "--no-ff", "-m", `Merge ${step.merge}`, step.merge], minute); + else { + for (const [path, content] of Object.entries(step.files)) { + const file = join(folder, path); + if (content === null) rmSync(file); + else { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, content); + } + } + git(["add", "--all"], minute); + git(["commit", "--quiet", "--message", step.message], minute); + } + const oid = git(["rev-parse", "HEAD"], minute); + checkOut("main", minute); + return oid; + }; + return { + folder, + commits: history.map(made), + /** One more step, later in the test: its commit's oid. */ + more: made, + /** What git itself says of the repo: `site.git("log", "-1", "--format=%B", "main")`. */ + git: (...args) => git(args, 59), + [Symbol.dispose]: () => rmSync(folder, { recursive: true, force: true }), + }; +} + +/** The links in the element of the page with that class, each as [href, text]. */ +export function linksIn(html, className) { + const start = html.indexOf(`class="${className}"`); + assert.ok(start > 0, `the page has an element with class ${className}`); + const end = html.indexOf(className === "crumbs" ? "</p>" : "</ul>", start); + const links = html.slice(start, end).matchAll(/<a href="([^"]*)"[^>]*>(.*?)<\/a>/g); + return [...links].map(([, href, text]) => [href, text.replace(/<[^>]+>/g, "")]); +} + +/** What the page hands its script. */ +export function dataOf(html) { + return JSON.parse(/<script type="application\/json" id="data">(.*?)<\/script>/s.exec(html)[1]); +}
M tests/local-mind.mjs
@@ -1,20 +1,35 @@ -// tests/local-mind.mjs — A MIND'S REPOS FROM FOLDERS ON THIS MACHINE. It answers what the app's -// pages ask of the mind (../app.ts): the repo verbs they call, a kv, and who is a member. Each -// answer comes from git itself, run in the folder that holds the repo. serve.mjs shows the app -// over the repos cloned beside this one, and pages.test.mjs over a repo it makes. +// 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"; -/** `folders`: where each repo is, by its path in the mind (`/repos/<name>`). `member`: whether - * the visitor is one. `kv` is the mind's kv as the app left it, and `asked` each call the app - * made of a repo or of the list, in order (`files /repos/kernel`). */ +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. + * + * 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 }) { const kv = {}; const asked = []; - const git = (repo, args, input) => - execFileSync("git", ["-C", folders[repo], ...args], { input, maxBuffer: 2 ** 30 }); + 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 git(repo, ["rev-parse", "--verify", "--quiet", "HEAD"]).toString().trim(); + return said(repo, ["rev-parse", "--verify", "--quiet", MAIN]); } catch { return null; // a repo with no commit yet } @@ -33,7 +48,8 @@ }) .filter(({ type }) => type === "blob"); // one git process for every blob: `<oid> blob <size>\n<bytes>\n`, in the order asked - const packed = git(repo, ["cat-file", "--batch"], blobs.map(({ oid }) => oid).join("\n") + "\n"); + 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) { @@ -71,11 +87,25 @@ created("files"); return filesAt(repo, options.commitOid); }, - async log({ limit }) { + 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"); - if (!tipOf(repo)) return []; + const start = from || tipOf(repo); + if (!start) return []; const format = ["%H", "%P", "%an", "%ae", "%at", "%B"].join("%x1f") + "%x1e"; - return git(repo, ["log", "-n", String(limit), `--format=${format}`]) + 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()) @@ -92,10 +122,48 @@ }; }); }, + // 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 }); + } + }, }; }; - const itx = { + /** 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) => ({ kv: { get: async (key) => kv[key] || null, put: async (key, value) => { @@ -109,15 +177,46 @@ 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, - getItx: () => itx, + 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, }, }; }
M tests/pages.test.mjs
@@ -2,15 +2,14 @@ // with git itself, and local-mind.mjs answers the mind's part from it. The pages are whole // without their script, so each test reads the HTML that the app answers. // Run it from the repo's root with `node --test "tests/*.test.mjs"`. +import "../../mind-loader.mjs"; import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; import { test } from "node:test"; -import { gitApp } from "../app.ts"; +import { dataOf, linksIn, repoWith } from "./fixtures.mjs"; import { localMind } from "./local-mind.mjs"; +const { gitApp } = await import("../app.ts"); + test("a repo's own page lists its files, folders first, shows its README and says how to clone it", async () => { using kernel = repoWith([ { @@ -23,7 +22,7 @@ }, }, ]); - const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: null }); const git = gitApp({ public: ["/repos/kernel"], ...look }); const answer = await git.fetch(new Request("https://git.example.com/repos/kernel"), mind); @@ -46,6 +45,7 @@ // what the file tree is drawn from assert.deepEqual(dataOf(html), { repo: "/repos/kernel", + me: null, paths: ["README.md", "core/lib/api.ts", "core/sdk.ts", "package.json"], path: "", }); @@ -61,7 +61,7 @@ }, }, ]); - const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: null }); const git = gitApp({ public: ["/repos/kernel"], ...look }); const read = async (path) => (await git.fetch(new Request(`https://git.example.com${path}`), mind)).text(); @@ -87,7 +87,7 @@ test("a markdown file is shown as it reads, and with ?plain as its source", async () => { using home = repoWith([{ message: "Start", files: { "todo/first.md": "# First\n" } }]); - const mind = localMind({ folders: { "/repos/home": home.folder }, member: false }); + const mind = localMind({ folders: { "/repos/home": home.folder }, member: null }); const git = gitApp({ public: ["/repos/home"], ...look }); const read = async (path) => (await git.fetch(new Request(`https://git.example.com${path}`), mind)).text(); @@ -105,7 +105,7 @@ { message: "Start\n\nThe first files.", files: { "a.ts": "1\n" } }, { message: "Add b", files: { "b.ts": "2\n" } }, ]); - const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: null }); const git = gitApp({ public: ["/repos/kernel"], ...look }); const answer = await git.fetch(new Request("https://git.example.com/repos/kernel/commits"), mind); @@ -116,8 +116,8 @@ [`/repos/kernel/commit/${addB}`, addB.slice(0, 7)], [`/repos/kernel/commit/${start}`, start.slice(0, 7)], ]); - assert.ok(html.includes(`</a> Add b <span class="by">Ada Author, 2026-11-24 10:01 UTC</span>`)); - assert.ok(html.includes(`</a> Start <span class="by">Ada Author, 2026-11-24 10:00 UTC</span>`)); + assert.ok(html.includes(`</a> Add b <span class="by">Ada Author, 2026-11-24 10:02 UTC</span>`)); + assert.ok(html.includes(`</a> Start <span class="by">Ada Author, 2026-11-24 10:01 UTC</span>`)); assert.ok(!html.includes("ada@example.com")); }); @@ -129,7 +129,7 @@ files: { "changed.ts": "new\n", "came.ts": "hello\n", "gone.ts": null }, }, ]); - const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: null }); const git = gitApp({ public: ["/repos/kernel"], ...look }); const [start, change] = kernel.commits; const read = () => @@ -149,10 +149,12 @@ // each file is open, under its name: a click on the name folds it, with no script assert.ok( html.includes( - `<details id="diff-1" open><summary><span class="status modified">M</span> changed.ts</summary><div class="diff" data-diff="1"></div></details>`, + `<details class="changed" id="diff-1" open><summary><span class="status modified">M</span> changed.ts</summary><div class="diff" data-diff="1"></div></details>`, ), ); assert.deepEqual(dataOf(html), { + repo: "/repos/kernel", + me: null, diffs: [ { path: "came.ts", before: "", after: "hello\n" }, { path: "changed.ts", before: "old\n", after: "new\n" }, @@ -172,7 +174,7 @@ { message: "Start", files: { "small.ts": "1\n" } }, { message: "A large file", files: { "large.txt": "x".repeat(700_000), "small.ts": "2\n" } }, ]); - const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: false }); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: null }); const git = gitApp({ public: ["/repos/kernel"], ...look }); const short = kernel.commits[1].slice(0, 7); @@ -186,10 +188,8 @@ ["#diff-0", "large.txt"], ["#diff-1", "small.ts"], ]); - assert.ok(html.includes("Not shown: the commit is larger than this page shows.")); - assert.deepEqual(dataOf(html), { - diffs: [null, { path: "small.ts", before: "1\n", after: "2\n" }], - }); + assert.ok(html.includes("Not shown: the change is larger than this page shows.")); + assert.deepEqual(dataOf(html).diffs, [null, { path: "small.ts", before: "1\n", after: "2\n" }]); // the short oid's second reader asks the log which commit it is, and no files await git.fetch(new Request(`https://git.example.com/repos/kernel/commit/${short}`), mind); @@ -207,13 +207,13 @@ const git = gitApp({ public: [], ...look }); const read = (mind) => git.fetch(new Request("https://git.example.com/repos/config"), mind); - const anyone = localMind({ folders, member: false }); + const anyone = localMind({ folders, member: null }); const refused = await read(anyone); assert.equal(refused.status, 401); assert.equal(await refused.text(), "Sign in\n"); assert.deepEqual(anyone.asked, []); - const member = localMind({ folders, member: true }); + const member = localMind({ folders, member: "ada@example.com" }); const html = await (await read(member)).text(); assert.deepEqual(linksIn(html, "entries"), [["/repos/config/tree/main/worker.ts", "worker.ts"]]); assert.ok(html.includes(`<span class="tag">private</span>`)); @@ -226,14 +226,14 @@ const read = async (mind) => (await git.fetch(new Request("https://git.example.com/"), mind)).text(); - const anyone = localMind({ folders, member: false }); + const anyone = localMind({ folders, member: null }); const forAnyone = await read(anyone); assert.deepEqual(linksIn(forAnyone, "repos"), [["/repos/kernel", "kernel"]]); assert.ok(forAnyone.includes("git clone https://git.example.com/repos/kernel")); assert.ok(forAnyone.includes(`<a href="/sign-in">Sign in</a>`)); assert.deepEqual(anyone.asked, []); - const forMember = await read(localMind({ folders, member: true })); + const forMember = await read(localMind({ folders, member: "ada@example.com" })); assert.deepEqual(linksIn(forMember, "repos"), [ ["/repos/config", "config"], ["/repos/kernel", "kernel"], @@ -246,7 +246,7 @@ using kernel = repoWith([ { message: "Start", files: { "a.ts": "1\n", "logo.png": Buffer.from([137, 80, 78, 71, 0, 1]) } }, ]); - const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: true }); + const mind = localMind({ folders: { "/repos/kernel": kernel.folder }, member: "ada@example.com" }); const git = gitApp({ public: ["/repos/kernel"], ...look }); const read = async (path) => { const answer = await git.fetch(new Request(`https://git.example.com${path}`), mind); @@ -275,62 +275,5 @@ // ── the fixtures ── -/** What worker.ts hands the app: the mind's icon, and the stylesheet every app shares. */ -const look = { icon: () => new Response("the icon"), theme: ":root { color-scheme: light; }" }; - -/** The links in the element of the page with that class, each as [href, text]. */ -function linksIn(html, className) { - const start = html.indexOf(`class="${className}"`); - assert.ok(start > 0, `the page has an element with class ${className}`); - const end = html.indexOf(className === "crumbs" ? "</p>" : "</ul>", start); - const links = html.slice(start, end).matchAll(/<a href="([^"]*)"[^>]*>(.*?)<\/a>/g); - return [...links].map(([, href, text]) => [href, text.replace(/<[^>]+>/g, "")]); -} - -/** What the page hands its script. */ -function dataOf(html) { - return JSON.parse(/<script type="application\/json" id="data">(.*?)<\/script>/s.exec(html)[1]); -} - -/** A repo in a folder of its own, with one commit for each entry, a minute apart from 10:00 UTC - * on 24 Nov 2026, all by Ada Author. `files` are written, and a file whose content is null is - * deleted. `commits` are the oids, oldest first. The folder goes when the test ends. */ -function repoWith(history) { - const folder = mkdtempSync(join(tmpdir(), "git-app-")); - const git = (args, minute) => - execFileSync("git", ["-C", folder, ...args], { - env: { - PATH: process.env.PATH, - // this machine's own git settings stay out of the test (hooks, signing) - GIT_CONFIG_GLOBAL: "/dev/null", - GIT_CONFIG_SYSTEM: "/dev/null", - GIT_AUTHOR_NAME: "Ada Author", - GIT_AUTHOR_EMAIL: "ada@example.com", - GIT_COMMITTER_NAME: "Ada Author", - GIT_COMMITTER_EMAIL: "ada@example.com", - GIT_AUTHOR_DATE: `2026-11-24T10:0${minute}:00Z`, - GIT_COMMITTER_DATE: `2026-11-24T10:0${minute}:00Z`, - }, - }) - .toString() - .trim(); - git(["init", "--quiet", "--initial-branch=main"], 0); - const commits = history.map(({ message, files }, minute) => { - for (const [path, content] of Object.entries(files)) { - const file = join(folder, path); - if (content === null) rmSync(file); - else { - mkdirSync(dirname(file), { recursive: true }); - writeFileSync(file, content); - } - } - git(["add", "--all"], minute); - git(["commit", "--quiet", "--message", message], minute); - return git(["rev-parse", "HEAD"], minute); - }); - return { - folder, - commits, - [Symbol.dispose]: () => rmSync(folder, { recursive: true, force: true }), - }; -} +/** What worker.ts hands the app: the mind's icon. */ +const look = { icon: () => new Response("the icon") };
A tests/pulls.test.mjs
@@ -0,0 +1,344 @@ +// tests/pulls.test.mjs — a pull, from a pushed branch to one commit on main (../pulls.ts), and the +// pages that show it (../pages.ts). Each test makes a repo with git itself; local-mind.mjs answers +// the mind's part, and holds the repo's events as the mind does. +// Run it from the repo's root with `node --test "tests/*.test.mjs"`. +import "../../mind-loader.mjs"; +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { baseOf, mergePull, pullsOf } from "../pulls.ts"; +import { dataOf, linksIn, repoWith } from "./fixtures.mjs"; +import { localMind } from "./local-mind.mjs"; + +const { gitApp } = await import("../app.ts"); + +test("a pushed branch is compared with main: its own commits, what it changes, and for a member the box that opens a pull", async () => { + using site = repoWith([ + { message: "Start", files: { "header.css": "header { color: black; }\n", "README.md": "# site\n" } }, + { on: "red-header", message: "Make the header red\n\nBlack was hard to read.", files: { "header.css": "header { color: red; }\n" } }, + { on: "red-header", message: "Say so in the README", files: { "README.md": "# site\n\nThe header is red.\n" } }, + ]); + const [, red, readme] = site.commits; + const mind = localMind({ folders: { "/repos/site": site.folder }, member: "ada@example.com" }); + const git = gitApp({ public: ["/repos/site"], ...look }); + + const answer = await git.fetch(new Request("https://git.example.com/repos/site/compare/red-header"), mind); + const html = await answer.text(); + + assert.equal(answer.status, 200); + assert.ok(html.includes("<code>red-header</code> adds 2 commits to <code>main</code>.")); + assert.deepEqual(linksIn(html, "commits"), [ + [`/repos/site/commit/${readme}`, readme.slice(0, 7)], + [`/repos/site/commit/${red}`, red.slice(0, 7)], + ]); + assert.deepEqual(linksIn(html, "changes"), [ + ["#diff-0", "README.md"], + ["#diff-1", "header.css"], + ]); + // the pull starts as the branch's first commit says it + assert.deepEqual(dataOf(html), { + repo: "/repos/site", + me: "ada", + compare: { branch: "red-header", title: "Make the header red", body: "Black was hard to read." }, + diffs: [ + { path: "README.md", before: "# site\n", after: "# site\n\nThe header is red.\n" }, + { path: "header.css", before: "header { color: black; }\n", after: "header { color: red; }\n" }, + ], + }); + assert.ok(html.includes(`<div id="open-pull"></div>`)); +}); + +test("a pull is opened, talked about and merged, each by one event on the repo's context; it lands as one commit on main, named after the pull", async () => { + using site = repoWith([ + { message: "Start", files: { "header.css": "header { color: black; }\n" } }, + { on: "red-header", message: "wip", files: { "header.css": "header { color: red; }\n" } }, + { on: "red-header", message: "more", files: { "note.txt": "red\n" } }, + ]); + const repo = "/repos/site"; + const mind = localMind({ folders: { [repo]: site.folder }, member: "ada@example.com" }); + const git = gitApp({ public: [repo], ...look }); + const read = async (path) => + (await git.fetch(new Request(`https://git.example.com${path}`), mind)).text(); + const ada = mind.as("ada@example.com").cd(repo); + const grace = mind.as("grace@example.com").cd(repo); + + // Ada's page opens the pull. It is the repo's first, so it is #1. + await ada.append({ + type: "pull/opened", + payload: { branch: "red-header", title: "Make the header red", body: "Black was hard to read." }, + }); + // Grace says something about it, and something about one line, which Ada answers and resolves. + await grace.append({ + type: "pull/commented", + payload: { pull: 1, body: "Looks right to me.", replyTo: null, at: null }, + }); + const line = { path: "header.css", side: "additions", line: 1, quote: "header { color: red; }" }; + const [onLine] = await grace.append({ + type: "pull/commented", + payload: { pull: 1, body: "Why not `crimson`?", replyTo: null, at: line }, + }); + await ada.append({ + type: "pull/commented", + payload: { pull: 1, body: "Red is in the brand book.", replyTo: onLine.offset, at: null }, + }); + await ada.append({ type: "pull/resolved", payload: { pull: 1, comment: onLine.offset } }); + + const open = await read("/repos/site/pull/1"); + assert.ok(open.includes(`<h1>Make the header red <span class="by">#1</span></h1>`)); + assert.ok(open.includes(`<span class="tag open">open</span> ada wants <code>red-header</code> squashed into <code>main</code>`)); + assert.ok(open.includes(`<pre data-markdown data-dir="">Black was hard to read.</pre>`)); + // the conversation is in the page as it stands, with no script: who, when, and their words + assert.ok(open.includes(`<p class="by">grace, 2026-11-24 12:02 UTC</p><pre>Looks right to me.</pre>`)); + assert.ok(open.includes(`<pre>Why not \`crimson\`?</pre>`)); + assert.deepEqual(dataOf(open), { + repo, + me: "ada", + pull: { number: 1, title: "Make the header red", branch: "red-header", status: "open" }, + mergeable: true, + threads: [ + { + id: 2, + place: null, + resolved: false, + comments: [{ id: 2, by: "grace", at: "2026-11-24T12:02:00.000Z", body: "Looks right to me." }], + diff: null, + outdated: false, + }, + { + // the comment on a line: on the page's first file, where the line still reads the same + id: 3, + place: line, + resolved: true, + comments: [ + { id: 3, by: "grace", at: "2026-11-24T12:03:00.000Z", body: "Why not `crimson`?" }, + { id: 4, by: "ada", at: "2026-11-24T12:04:00.000Z", body: "Red is in the brand book." }, + ], + diff: 0, + outdated: false, + }, + ], + diffs: [ + { path: "header.css", before: "header { color: black; }\n", after: "header { color: red; }\n" }, + { path: "note.txt", before: "", after: "red\n" }, + ], + }); + + // The merge: one commit on main with the branch's files, by the one who opened the pull. + const { commitOid } = await mergePull(mind.getItx(), repo, 1); + + assert.equal( + site.git("log", "--format=%an <%ae>%n%B", "main", "-1"), + "ada <ada@example.com>\nMake the header red (#1)\n\nBlack was hard to read.", + ); + assert.equal(site.git("rev-list", "--count", "main"), "2"); + assert.equal(site.git("show", "main:header.css"), "header { color: red; }"); + assert.equal(site.git("show", "main:note.txt"), "red"); + assert.deepEqual(mind.events[repo].at(-1).payload, { pull: 1, commitOid }); + + const merged = await read("/repos/site/pull/1"); + assert.ok(merged.includes(`<span class="tag merged">merged</span> ada squashed <code>red-header</code> into <code>main</code> as <a href="/repos/site/commit/${commitOid}">`)); + // what it shows now is what that commit changed + assert.deepEqual(linksIn(merged, "changes"), [ + ["#diff-0", "header.css"], + ["#diff-1", "note.txt"], + ]); + assert.equal(dataOf(merged).mergeable, false); + // the branch is done: the list of pulls no longer offers it for a pull + assert.ok(!(await read("/repos/site/pulls")).includes("/repos/site/compare/red-header")); + // and it is merged once: a second try is refused in words + await assert.rejects(mergePull(mind.getItx(), repo, 1), /#1 is merged already/); +}); + +test("a pull's number is its place among the pulls that were opened, and an event that is no pull's changes nothing", () => { + const events = [ + event(1, "events.iterate.com/repo/pushed", { ref: "refs/heads/main" }), + event(2, "pull/opened", { branch: "one", title: "The first", body: "" }, "ada@example.com"), + // a payload that is no pull's: no number is spent on it + event(3, "pull/opened", { title: "No branch" }, "ada@example.com"), + event(4, "pull/opened", { branch: "two", title: "The second", body: "why" }, "grace@example.com"), + event(5, "pull/commented", { pull: 2, body: "On the second.", replyTo: null, at: null }, "ada@example.com"), + // about a pull that does not exist, and a reply to a comment that does not: neither is lost or loud + event(6, "pull/commented", { pull: 9, body: "Nowhere.", replyTo: null, at: null }, "ada@example.com"), + event(7, "pull/commented", { pull: 2, body: "A thread of its own.", replyTo: 99, at: null }, "ada@example.com"), + event(8, "pull/edited", { pull: 1, title: "The first, renamed", body: "now with a body" }, "ada@example.com"), + event(9, "pull/closed", { pull: 1 }, "ada@example.com"), + // code with nobody behind it is shown as the context it ran in + event(10, "pull/commented", { pull: 2, body: "From an agent.", replyTo: 5, at: null }, null), + ]; + + assert.deepEqual( + pullsOf(events).map(({ number, branch, title, body, by, status, threads }) => ({ + number, + branch, + title, + body, + by, + status, + said: threads.map(({ id, comments }) => [id, ...comments.map(({ by, body }) => `${by}: ${body}`)]), + })), + [ + { number: 1, branch: "one", title: "The first, renamed", body: "now with a body", by: "ada", status: "closed", said: [] }, + { + number: 2, + branch: "two", + title: "The second", + body: "why", + by: "grace", + status: "open", + said: [ + [5, "ada: On the second.", "/agents/reviewer: From an agent."], + [7, "ada: A thread of its own."], + ], + }, + ], + ); +}); + +test("a comment on a line stays on its line while the line reads as it did, and says so when the line has changed", async () => { + using site = repoWith([ + { message: "Start", files: { "header.css": "header { color: black; }\n" } }, + { on: "red-header", message: "Red", files: { "header.css": "header { color: red; }\n" } }, + ]); + const repo = "/repos/site"; + const mind = localMind({ folders: { [repo]: site.folder }, member: "ada@example.com" }); + const git = gitApp({ public: [repo], ...look }); + const threads = async () => + dataOf(await (await git.fetch(new Request("https://git.example.com/repos/site/pull/1"), mind)).text()) + .threads.map(({ diff, outdated }) => ({ diff, outdated })); + const ada = mind.as("ada@example.com").cd(repo); + await ada.append({ type: "pull/opened", payload: { branch: "red-header", title: "Red", body: "" } }); + const line = { path: "header.css", side: "additions", line: 1, quote: "header { color: red; }" }; + await ada.append({ type: "pull/commented", payload: { pull: 1, body: "Too bright?", replyTo: null, at: line } }); + + assert.deepEqual(await threads(), [{ diff: 0, outdated: false }]); + + // a new commit on the branch changes that line + site.more({ on: "red-header", message: "Crimson", files: { "header.css": "header { color: crimson; }\n" } }); + assert.deepEqual(await threads(), [{ diff: 0, outdated: true }]); + const html = await (await git.fetch(new Request("https://git.example.com/repos/site/pull/1"), mind)).text(); + assert.ok(html.includes(`line 1, which has changed since<code class="quote">header { color: red; }</code>`)); +}); + +test("a squash is taken only while the branch has main's newest commit: when main has moved, the branch merges main in first", async () => { + using site = repoWith([ + { message: "Start", files: { "a.txt": "a\n" } }, + { on: "add-b", message: "Add b", files: { "b.txt": "b\n" } }, + { message: "Meanwhile on main", files: { "c.txt": "c\n" } }, + ]); + const repo = "/repos/site"; + const mind = localMind({ folders: { [repo]: site.folder }, member: "ada@example.com" }); + const git = gitApp({ public: [repo], ...look }); + const page = async () => + (await git.fetch(new Request("https://git.example.com/repos/site/pull/1"), mind)).text(); + await mind.as("ada@example.com").cd(repo).append({ type: "pull/opened", payload: { branch: "add-b", title: "Add b", body: "" } }); + + // the page shows what the branch itself changed, not what main did meanwhile, and offers no merge + const behind = await page(); + assert.deepEqual(linksIn(behind, "changes"), [["#diff-0", "b.txt"]]); + assert.ok(behind.includes("main has moved since add-b last had it. To merge: merge main into add-b, and push.")); + assert.equal(dataOf(behind).mergeable, false); + await assert.rejects(mergePull(mind.getItx(), repo, 1), /main has moved since add-b last had it/); + + site.more({ on: "add-b", merge: "main" }); + const ready = await page(); + assert.deepEqual(linksIn(ready, "changes"), [["#diff-0", "b.txt"]]); + assert.equal(dataOf(ready).mergeable, true); + await mergePull(mind.getItx(), repo, 1); + assert.equal(site.git("log", "--format=%s", "main"), "Add b (#1)\nMeanwhile on main\nStart"); + assert.deepEqual(site.git("ls-tree", "--name-only", "main").split("\n"), ["a.txt", "b.txt", "c.txt"]); +}); + +test("where a branch stands on main is read from the two histories: where it began, or the commit of main it last merged in", () => { + const commit = (oid, ...parents) => ({ oid, parents }); + const main = [commit("m3", "m2"), commit("m2", "m1"), commit("m1")]; + + // began at m1, and never took main in since + assert.deepEqual(baseOf(main, [commit("b2", "b1"), commit("b1", "m1"), commit("m1")]), { + base: "m1", + own: [commit("b2", "b1"), commit("b1", "m1")], + upToDate: false, + }); + // began at m1, then merged m3 in: it has main's newest + const merge = commit("b3", "b1", "m3"); + assert.deepEqual(baseOf(main, [merge, commit("b1", "m1"), commit("m1")]), { + base: "m3", + own: [merge, commit("b1", "m1")], + upToDate: true, + }); + // nothing of its own + assert.deepEqual(baseOf(main, [commit("m3", "m2")]), { base: "m3", own: [], upToDate: true }); + // no commit in common in what was read + assert.deepEqual(baseOf(main, [commit("x1")]), { base: null, own: [commit("x1")], upToDate: false }); +}); + +test("the pulls page lists the open pulls, the branches that have none, and the pulls that are done; a branch with an open pull goes to its pull", async () => { + using site = repoWith([ + { message: "Start", files: { "a.txt": "a\n" } }, + { on: "one", message: "One", files: { "one.txt": "1\n" } }, + { on: "two", message: "Two", files: { "two.txt": "2\n" } }, + { on: "three", message: "Three", files: { "three.txt": "3\n" } }, + ]); + const repo = "/repos/site"; + const mind = localMind({ folders: { [repo]: site.folder }, member: null }); + const git = gitApp({ public: [repo], ...look }); + const ada = mind.as("ada@example.com").cd(repo); + await ada.append({ type: "pull/opened", payload: { branch: "one", title: "The first", body: "" } }); + await ada.append({ type: "pull/opened", payload: { branch: "two", title: "The second", body: "" } }); + await ada.append({ type: "pull/commented", payload: { pull: 2, body: "Hm.", replyTo: null, at: null } }); + await ada.append({ type: "pull/closed", payload: { pull: 1 } }); + + // anyone reads a public repo's pulls + const answer = await git.fetch(new Request("https://git.example.com/repos/site/pulls"), mind); + const html = await answer.text(); + const [open, loose, done] = html.split(`<ul class="pulls">`).slice(1); + + assert.equal(answer.status, 200); + assert.ok(open.startsWith(`<li><a href="/repos/site/pull/2">The second</a> <span class="by">#2, <code>two</code>, ada, 2026-11-24 12:02 UTC, 1 comment</span></li></ul>`)); + // `one` is here too: its pull was closed, so the branch can be proposed again + assert.deepEqual( + [...loose.split("</ul>")[0].matchAll(/href="([^"]*)"/g)].map(([, href]) => href), + ["/repos/site/compare/one", "/repos/site/compare/three"], + ); + assert.ok(done.startsWith(`<li><a href="/repos/site/pull/1">The first</a> <span class="by">#1, closed, <code>one</code>`)); + + const compared = await git.fetch(new Request("https://git.example.com/repos/site/compare/two"), mind); + assert.equal(compared.status, 302); + assert.equal(compared.headers.get("location"), "https://git.example.com/repos/site/pull/2"); +}); + +test("anyone reads a public repo's pull and is offered the sign-in to write; a pull of any other repo is for members", async () => { + using site = repoWith([ + { message: "Start", files: { "a.txt": "a\n" } }, + { on: "one", message: "One", files: { "one.txt": "1\n" } }, + ]); + const repo = "/repos/site"; + const mind = localMind({ folders: { [repo]: site.folder }, member: null }); + await mind.as("ada@example.com").cd(repo).append({ type: "pull/opened", payload: { branch: "one", title: "The first", body: "" } }); + const read = (publicRepos) => + gitApp({ public: publicRepos, ...look }).fetch(new Request("https://git.example.com/repos/site/pull/1"), mind); + + const html = await (await read([repo])).text(); + assert.ok(html.includes(`<a href="/sign-in?to=%2Frepos%2Fsite%2Fpull%2F1">Sign in</a> to comment or to merge.`)); + assert.ok(!html.includes(`id="merge"`)); + assert.equal(dataOf(html).me, null); + + const refused = await read([]); + assert.equal(refused.status, 401); + + const missing = await gitApp({ public: [repo], ...look }).fetch(new Request("https://git.example.com/repos/site/pull/7"), mind); + assert.equal(missing.status, 404); + assert.ok((await missing.text()).includes("site has no pull #7.")); +}); + +// ── the fixtures ── + +/** What worker.ts hands the app: the mind's icon. */ +const look = { icon: () => new Response("the icon") }; + +/** An event as a context's log holds it, written by a member (their address) or, with no + * address, by code that ran in the context /agents/reviewer. */ +function event(offset, type, payload, address) { + const source = address + ? { origin: "/repos/site", principal: { actor: address, email: address } } + : { origin: "/agents/reviewer" }; + return { offset, type, payload, createdAt: `2026-11-24T12:${String(offset).padStart(2, "0")}:00.000Z`, path: "/repos/site", source }; +}
M tests/serve.mjs
@@ -1,30 +1,108 @@ -// tests/serve.mjs — THE APP'S PAGES ON THIS MACHINE, over the repos cloned beside this one, to -// try a change before a push: +// tests/serve.mjs — THE APP ON THIS MACHINE, to try a change before a push: // -// node tests/serve.mjs then open http://git.localhost:4173 +// node tests/serve.mjs then open http://git.localhost:4173 // VISITOR=anyone node tests/serve.mjs as someone who is no member // -// The pages only: git itself is not served here (no clone, no push). -import { readFileSync } from "node:fs"; +// It serves COPIES of the repos cloned beside this one, made in a temporary folder that goes when +// the server stops: a merge here writes a commit to a copy, never to your clone. The copy of this +// repo has a branch of its own, `a-proposal`, to open a pull from. +// +// The mind is local-mind.mjs. What a member's page writes goes to it too: this server answers the +// page's /mind.js with a module of its own (below), in the place of the one that dials the mind. +// Git itself is not served here (no clone, no push). +import "../../mind-loader.mjs"; +import { execFileSync } from "node:child_process"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; -import { gitApp } from "../app.ts"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { mergePull } from "../pulls.ts"; import { localMind } from "./local-mind.mjs"; +const { gitApp } = await import("../app.ts"); + // The folder that holds every repo is itself the repo `home`. const home = new URL("../../", import.meta.url).pathname; -const folders = { "/repos/home": home }; -for (const name of ["kernel", "stdlib", "dash", "tasks", "git", "config"]) - folders[`/repos/${name}`] = `${home}${name}`; +const copies = mkdtempSync(join(tmpdir(), "git-app-serve-")); +process.on("exit", () => rmSync(copies, { recursive: true, force: true })); +process.on("SIGINT", () => process.exit()); +process.on("SIGTERM", () => process.exit()); -const mind = localMind({ folders, member: process.env.VISITOR !== "anyone" }); +const folders = {}; +for (const name of ["home", "kernel", "stdlib", "dash", "tasks", "git", "config"]) { + folders[`/repos/${name}`] = join(copies, name); + const from = name === "home" ? home : join(home, name); + execFileSync("git", ["clone", "--quiet", "--branch", "main", from, folders[`/repos/${name}`]]); +} + +// A branch to open a pull from: two commits on the copy of this repo. +{ + const folder = folders["/repos/git"]; + const git = (...args) => execFileSync("git", ["-C", folder, "-c", "user.name=Ada Author", "-c", "user.email=ada@example.com", ...args]); + git("checkout", "--quiet", "-b", "a-proposal"); + writeFileSync(join(folder, "README.md"), "# git\n\nThe mind's repos, to read, to clone and to propose a change to.\n"); + git("commit", "--quiet", "--all", "--message", "Say what the app is for in one line\n\nThe README opened with how, not what."); + writeFileSync(join(folder, "NOTES.md"), "A note that the proposal adds.\n"); + git("add", "NOTES.md"); + git("commit", "--quiet", "--message", "Add a note"); + git("checkout", "--quiet", "main"); +} + +const visitor = process.env.VISITOR === "anyone" ? null : "ada@example.com"; +const mind = localMind({ folders, member: visitor }); const git = gitApp({ public: Object.keys(folders).filter((repo) => repo !== "/repos/config"), - icon: () => new Response("<svg xmlns='http://www.w3.org/2000/svg'/>", { headers: { "content-type": "image/svg+xml" } }), - theme: readFileSync(`${home}stdlib/theme.css`, "utf8"), + icon: () => + new Response("<svg xmlns='http://www.w3.org/2000/svg'/>", { + headers: { "content-type": "image/svg+xml" }, + }), }); +/** THE PAGE'S itx HERE: the two things a member's page does, sent to this server, which does + * them on the local mind as that member. */ +const MIND_MODULE = ` + const ask = async (path, body) => { + const answer = await fetch(path, { method: "POST", body: JSON.stringify(body) }); + if (!answer.ok) throw new Error(await answer.text()); + return answer.json(); + }; + export const itx = { + cd: (path) => ({ append: (event) => ask("/local-mind/append", { path, event }) }), + config: { pullMerge: (repo, number) => ask("/local-mind/merge", { repo, number }) }, + }; +`; + +const written = async (path, body) => { + if (path === "/local-mind/append") return mind.as(visitor).cd(body.path).append(body.event); + if (path === "/local-mind/merge") return mergePull(mind.getItx(), body.repo, body.number); +}; + const port = 4173; createServer(async (request, response) => { + const { pathname } = new URL(request.url, "http://localhost"); + if (pathname === "/mind.js") { + response.writeHead(200, { "content-type": "text/javascript; charset=utf-8" }).end(MIND_MODULE); + return; + } + // The page's own files as they are on disk now: the app holds them as they were when this + // server started, so an edit to public/ shows on the next load with no restart. + const file = new URL(`../public${pathname}`, import.meta.url); + if (/^\/[a-z-]+\.(js|css)$/.test(pathname) && existsSync(file)) { + const type = pathname.endsWith(".css") ? "text/css" : "text/javascript"; + response.writeHead(200, { "content-type": `${type}; charset=utf-8` }).end(readFileSync(file)); + return; + } + if (pathname.startsWith("/local-mind/")) { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + try { + const answer = await written(pathname, JSON.parse(Buffer.concat(chunks).toString())); + response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(answer)); + } catch (error) { + response.writeHead(400).end(error instanceof Error ? error.message : String(error)); + } + return; + } const answer = await git.fetch(new Request(`http://${request.headers.host}${request.url}`), mind); response.writeHead(answer.status, Object.fromEntries(answer.headers)); response.end(Buffer.from(await answer.arrayBuffer()));