// Read-only git and version inspection for the runtime surface // (CV22.DS7.TS3). Port of the read half of `src/memory/cli/runtime.py`. // // BOUNDARY, enforced by a test that greps this file: nothing here mutates a // repository. `merge`, `tag`, `push`, `reset`, `checkout`, `commit`, and // `branch ` belong to the git-based updater and release machinery, which // the 2026-09-07 decision assigned to CV22.DS10 for redesign under npm // distribution. Every command below reads: `rev-parse`, `branch // --show-current`, `status --porcelain`, `rev-list --count`, `merge-base // --is-ancestor`, `cat-file -e`, `config --get`, and the one networked read, // `ls-remote`. // // Timeouts follow the oracle's two budgets, and for the reason recorded there: // local inspections are near-instant, while a single shared 2 s budget once // made a network operation report failure after it had already succeeded // (the v0.30.1 release incident). Network reads get 120 s, except where a // caller holds a tighter budget of its own: the welcome card's update check // runs inside the session start and passes what is left of its 5 s (CR135). import { spawnSync } from "node:child_process"; import { existsSync, readFileSync, realpathSync } from "node:fs"; import { join, resolve } from "node:path"; import { type InstallKind, renderInstallLines } from "#runtime/installKind.ts"; import { DEFAULT_CHANNEL, KNOWN_CHANNELS } from "#runtime/updatePipeline.ts"; export const GIT_LOCAL_TIMEOUT_MS = 2_000; export const GIT_NETWORK_TIMEOUT_MS = 120_000; const CLONE_ROLE_FILENAME = ".mirror-clone-role"; const UPDATE_CHANNEL_FILENAME = ".mirror-update-channel"; const DEFAULT_CLONE_ROLE = "production"; const KNOWN_CLONE_ROLES = new Set(["production", "dev"]); // The channel vocabulary is the pipeline's (one set for both install kinds // since CV22.DS10.US3 plateau 4); these are the names this module used. const DEFAULT_UPDATE_CHANNEL = DEFAULT_CHANNEL; const KNOWN_UPDATE_CHANNELS = KNOWN_CHANNELS; export interface GitStatus { repository: string | null; branch: string | null; commit: string | null; dirty: boolean | null; error: string | null; } export interface GitWorktreeEntry { status: string; path: string; } export interface MarkerValue { value: string; /** The marker file the value came from, or null when defaulted. */ source: string | null; note: string | null; } export interface RuntimeVersionReport { version: string; /** How the running front door is installed (CV22.DS10.US3 plateau 4; US2 D3). */ install: InstallKind; git: GitStatus; cloneRole: MarkerValue; updateChannel: MarkerValue; } export interface GitUpdatePlan { upstream: string | null; ahead: number | null; behind: number | null; ready: boolean; action: string; note: string | null; } export interface UpdateAvailability { version: string; upstream: string | null; local_commit: string | null; remote_commit: string | null; status: string; note: string | null; update_channel: MarkerValue; target_release: null; } /** * How a caller asks git for something. `runGit` is one; the update pipeline * injects others, so its decisions can be driven in tests without a remote. * Without a timeout, a command gets `runGit`'s local budget. */ export type GitRunner = ( args: readonly string[], cwd: string, timeoutMs?: number, ) => { code: number; stdout: string; stderr: string }; /** `(exit code, trimmed stdout, trimmed stderr)`, tolerant like the oracle's. */ export function runGit( args: readonly string[], cwd: string, timeoutMs: number = GIT_LOCAL_TIMEOUT_MS, ): { code: number; stdout: string; stderr: string } { const result = spawnSync("git", [...args], { cwd, encoding: "utf8", timeout: timeoutMs, // Arguments are passed as argv, never through a shell, so a ref or remote // name cannot become a second command. shell: false, }); if (result.error) return { code: 1, stdout: "", stderr: String(result.error.message ?? result.error) }; return { code: result.status ?? 1, stdout: (result.stdout ?? "").trim(), stderr: (result.stderr ?? "").trim(), }; } function resolveRepoRoot(start: string): string | null { const { code, stdout } = runGit(["rev-parse", "--show-toplevel"], start); if (code !== 0 || !stdout) return null; return realpathSync(stdout); } /** Port of `_parse_porcelain_line`: two status characters, then the path. */ function parsePorcelainLine(line: string): GitWorktreeEntry | null { if (!line) return null; const status = line.slice(0, 2); let path = line.slice(2).trim(); if (path.includes(" -> ")) path = path.split(" -> ", 2)[1] as string; return { status, path }; } export function inspectGitWorktree(repository: string | null): GitWorktreeEntry[] { if (repository === null) return []; const { code, stdout } = runGit(["status", "--porcelain"], repository); if (code !== 0 || !stdout) return []; return stdout .split("\n") .map(parsePorcelainLine) .filter((entry): entry is GitWorktreeEntry => entry !== null); } export function inspectGit(start: string): GitStatus { const top = runGit(["rev-parse", "--show-toplevel"], start); if (top.code !== 0 || !top.stdout) { return { repository: null, branch: null, commit: null, dirty: null, error: top.stderr || "not a git repository", }; } const repository = realpathSync(top.stdout); const branch = runGit(["branch", "--show-current"], repository); const commit = runGit(["rev-parse", "--short", "HEAD"], repository); const dirty = runGit(["status", "--porcelain"], repository); const errors = [branch, commit, dirty] .filter((result) => result.code !== 0 && result.stderr) .map((result) => result.stderr); return { repository, branch: branch.code === 0 && branch.stdout ? branch.stdout : null, commit: commit.code === 0 && commit.stdout ? commit.stdout : null, dirty: dirty.code === 0 ? Boolean(dirty.stdout) : null, error: errors.length > 0 ? errors.join("; ") : null, }; } /** Shared shape of the two marker files: allowlisted value, else the default. */ function inspectMarker( start: string, filename: string, known: ReadonlySet, fallback: string, label: string, ): MarkerValue { const repoRoot = resolveRepoRoot(resolve(start)); if (repoRoot === null) return { value: fallback, source: null, note: "no repository" }; const marker = join(repoRoot, filename); if (!existsSync(marker)) return { value: fallback, source: null, note: null }; let raw: string; try { raw = readFileSync(marker, "utf8"); } catch (error) { const message = error instanceof Error ? error.message : String(error); return { value: fallback, source: marker, note: `unreadable: ${message}` }; } const value = raw.trim().toLowerCase(); if (known.has(value)) return { value, source: marker, note: null }; return { value: fallback, source: marker, note: `unknown ${label} '${value}', defaulting to ${fallback}`, }; } export function inspectCloneRole(start: string): MarkerValue { return inspectMarker(start, CLONE_ROLE_FILENAME, KNOWN_CLONE_ROLES, DEFAULT_CLONE_ROLE, "role"); } export function inspectUpdateChannel(start: string, override: string | null = null): MarkerValue { if (override) { const value = override.trim().toLowerCase(); if (KNOWN_UPDATE_CHANNELS.has(value)) return { value, source: null, note: "command override" }; return { value: DEFAULT_UPDATE_CHANNEL, source: null, note: `unknown channel '${value}', defaulting to ${DEFAULT_UPDATE_CHANNEL}`, }; } return inspectMarker( start, UPDATE_CHANNEL_FILENAME, KNOWN_UPDATE_CHANNELS, DEFAULT_UPDATE_CHANNEL, "channel", ); } /** `origin/` — the only place a channel becomes a git ref. */ export function upstreamFor(channel: MarkerValue): string { return `origin/${channel.value}`; } /** `origin/main` -> `["origin", "main"]`; anything else is refused. */ export function splitUpstream(upstream: string): [string, string] | null { const index = upstream.indexOf("/"); if (index <= 0 || index === upstream.length - 1) return null; const remote = upstream.slice(0, index); const branch = upstream.slice(index + 1); if (remote.startsWith("-") || branch.startsWith("-")) return null; return [remote, branch]; } // Lives in `runtime/version.ts` now -- the MCP server needs it and should not // import this module to get it. Re-exported so runtime call sites do not move. export { packageVersion } from "./version.ts"; /** Port of `_classify_update_status`: ancestry from the local object database. */ function classifyUpdateStatus( repository: string, localCommit: string | null, remoteCommit: string, ): string { if (localCommit && (remoteCommit === localCommit || remoteCommit.startsWith(localCommit))) { return "up_to_date"; } if (runGit(["merge-base", "--is-ancestor", remoteCommit, "HEAD"], repository).code === 0) { return "local_ahead"; } if (runGit(["merge-base", "--is-ancestor", "HEAD", remoteCommit], repository).code === 0) { return "update_available"; } const known = runGit(["cat-file", "-e", `${remoteCommit}^{commit}`], repository); return known.code === 0 ? "diverged" : "update_available"; } function availability( version: string, updateChannel: MarkerValue, fields: Partial, ): UpdateAvailability { return { version, upstream: null, local_commit: null, remote_commit: null, status: "unknown", note: null, update_channel: updateChannel, target_release: null, ...fields, }; } /** * Is the channel's remote branch ahead of HEAD? The remote query is the only * authority: remote-tracking refs are only as fresh as the last fetch, and * trusting them is how a clone two releases behind gets told it is ahead. * * `networkTimeoutMs` bounds that query; `runtime update --check` keeps the * network budget, and the welcome card passes what is left of its own. */ export function checkUpdateAvailability( start: string, channel: string | null, version: string, networkTimeoutMs: number = GIT_NETWORK_TIMEOUT_MS, ): UpdateAvailability { const startPath = resolve(start); const git = inspectGit(startPath); const updateChannel = inspectUpdateChannel(startPath, channel); if (git.repository === null) { return availability(version, updateChannel, { note: "repository unavailable" }); } // With a channel the upstream is always `origin/`, so the oracle's // `no_upstream` branch is unreachable here: whether that ref exists locally // is the update PLAN's question (plateau 3), not this check's. An unfetched // channel therefore falls through to the remote query, which is the only // authority, and reports `unknown` when the branch does not exist remotely. const upstream = upstreamFor(updateChannel); const [remote, branch] = [ upstream.split("/", 1)[0] as string, upstream.split("/").slice(1).join("/"), ]; if (!remote || !branch) { return availability(version, updateChannel, { upstream, local_commit: git.commit, note: "unexpected upstream name", }); } const remoteUrl = runGit(["config", "--get", `remote.${remote}.url`], git.repository); if (remoteUrl.code !== 0 || !remoteUrl.stdout) { return availability(version, updateChannel, { upstream, local_commit: git.commit, note: remoteUrl.stderr || `remote ${remote} has no url`, }); } const lsRemote = runGit( ["ls-remote", remote, `refs/heads/${branch}`], git.repository, networkTimeoutMs, ); if (lsRemote.code !== 0 || !lsRemote.stdout) { return availability(version, updateChannel, { upstream, local_commit: git.commit, note: lsRemote.stderr || "remote query failed", }); } const parts = lsRemote.stdout.split(/\s+/); if (parts.length < 2) { return availability(version, updateChannel, { upstream, local_commit: git.commit, note: `unexpected ls-remote output: ${lsRemote.stdout}`, }); } const remoteCommit = parts[0] as string; const localFull = runGit(["rev-parse", "HEAD"], git.repository); const localCommit = localFull.code === 0 && localFull.stdout ? localFull.stdout : git.commit; return availability(version, updateChannel, { upstream, local_commit: localCommit, remote_commit: remoteCommit, status: classifyUpdateStatus(git.repository, localCommit, remoteCommit), }); } /** * Where a checkout stands against the channel branch it follows: one reading * for both the update plan (`strategies/clone.ts`) and `inspectGitUpdatePlan`, * so the two cannot disagree (CR186). `ahead` counts the checkout's commits * that the upstream lacks; `behind`, the upstream's commits that the checkout lacks. */ export type ChannelPosition = /** The two could not be compared; `reason` is git's, when it gave one. */ | { kind: "unreadable"; reason: string } | { kind: "current" } /** The channel has commits to take, and the checkout has none of its own. */ | { kind: "pull"; behind: number } /** * Every commit past the channel is already on the other channel's branch: * the channel is behind the checkout, and nothing here is the person's own. * Release promotion only fast-forwards `stable` to `main`, so this is a * `stable` clone that took `main`'s commits before their release. */ | { kind: "channel_behind"; ahead: number; channel: string; carriedBy: string; carriedByRef: string; } /** At least one commit past the channel is on no channel's branch. */ | { kind: "local_commits"; ahead: number } | { kind: "diverged"; ahead: number; behind: number }; type CommitCount = { value: number } | { reason: string }; function countCommits( repository: string, revisions: readonly string[], git: GitRunner, ): CommitCount { const result = git(["rev-list", "--count", ...revisions], repository); const value = Number.parseInt(result.stdout.trim(), 10); if (result.code !== 0 || Number.isNaN(value)) { return { reason: result.stderr.trim() || "cannot compare upstream" }; } return { value }; } /** * The other channel whose branch already has every commit past `upstream`, if * one does. Its ref is read as last fetched. A stale or missing ref can only * make published commits look local, which is the refusal a clone always had; * it can never make local work look published. */ function channelBehind( repository: string, upstream: string, ahead: number, git: GitRunner, ): ChannelPosition | null { const split = splitUpstream(upstream); if (split === null) return null; const [remote, channel] = split; if (!KNOWN_UPDATE_CHANNELS.has(channel)) return null; for (const other of KNOWN_UPDATE_CHANNELS) { if (other === channel) continue; const ref = `${remote}/${other}`; const unpublished = countCommits(repository, [`${upstream}..HEAD`, `^${ref}`], git); if ("value" in unpublished && unpublished.value === 0) { return { kind: "channel_behind", ahead, channel, carriedBy: other, carriedByRef: ref }; } } return null; } /** Read from the local object database only: the plan, not the remote check. */ export function readChannelPosition( repository: string, upstream: string, git: GitRunner = runGit, ): ChannelPosition { const ahead = countCommits(repository, [`${upstream}..HEAD`], git); if ("reason" in ahead) return { kind: "unreadable", reason: ahead.reason }; const behind = countCommits(repository, [`HEAD..${upstream}`], git); if ("reason" in behind) return { kind: "unreadable", reason: behind.reason }; if (ahead.value === 0) { return behind.value === 0 ? { kind: "current" } : { kind: "pull", behind: behind.value }; } if (behind.value > 0) return { kind: "diverged", ahead: ahead.value, behind: behind.value }; return ( channelBehind(repository, upstream, ahead.value, git) ?? { kind: "local_commits", ahead: ahead.value, } ); } /** The words both readers give a position: the plan's detail, the inspection's note. */ export function describeChannelPosition(position: ChannelPosition): string { switch (position.kind) { case "unreadable": return position.reason; case "current": return "already up to date"; case "pull": return `pull ${position.behind} remote commit(s)`; case "channel_behind": return `'${position.channel}' is behind this checkout (${position.ahead} commit(s), all on ${position.carriedByRef})`; case "local_commits": return "local commits present"; case "diverged": return "branch diverged"; } } /** * Port of `inspect_git_update_plan`: how far HEAD is from the channel's * upstream, and whether a fast-forward is the honest move. * * Unlike `checkUpdateAvailability`, this asks the LOCAL object database only -- * it is the plan, not the check, so an unfetched channel is `blocked` here * rather than a reason to query the remote. */ export function inspectGitUpdatePlan( git: GitStatus, updateChannel: MarkerValue | null = null, ): GitUpdatePlan { const blocked = (upstream: string | null, note: string): GitUpdatePlan => ({ upstream, ahead: null, behind: null, ready: false, action: "blocked", note, }); if (git.repository === null) return blocked(null, "repository unavailable"); let upstream: string; if (updateChannel === null) { const resolved = runGit( ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], git.repository, ); if (resolved.code !== 0 || !resolved.stdout) { return blocked(null, resolved.stderr || "no upstream configured"); } upstream = resolved.stdout; } else { upstream = upstreamFor(updateChannel); const verified = runGit(["rev-parse", "--verify", upstream], git.repository); if (verified.code !== 0) { return blocked( upstream, verified.stderr || `update channel ${updateChannel.value} is not fetched`, ); } } const position = readChannelPosition(git.repository, upstream); const note = describeChannelPosition(position); switch (position.kind) { case "unreadable": return blocked(upstream, note); case "current": return { upstream, ahead: 0, behind: 0, ready: true, action: "none", note }; case "pull": return { upstream, ahead: 0, behind: position.behind, ready: true, action: "pull", note }; case "diverged": return { upstream, ahead: position.ahead, behind: position.behind, ready: false, action: "blocked", note, }; case "channel_behind": case "local_commits": return { upstream, ahead: position.ahead, behind: 0, ready: false, action: "blocked", note }; } } /** A package's git facts: it has none, and none is not an error. */ export const NO_REPOSITORY: GitStatus = { repository: null, branch: null, commit: null, dirty: null, error: null, }; /** * The git facts of the install's `root` (`inspectionRootFor`): a package's * are `NO_REPOSITORY` (CV22.DS10.US3 plateau 4), since grading the cwd of a * package install as a tree read "not a git repository" as a git error. With * no root -- an install that cannot be identified, and no `--start` -- no * repository is inspected at all, and the rows say why (CR138, decision 2). */ export function inspectGitFor(install: InstallKind, root: string | null): GitStatus { if (install.kind === "package") return NO_REPOSITORY; if (root === null) { const reason = install.kind === "unknown" ? `install kind unknown: ${install.reason}` : "no repository"; return { ...NO_REPOSITORY, error: reason }; } return inspectGit(root); } /** * The clone role the install's checkout declares (CR138). A package has none * to declare. With no root, nothing is read, and the oracle's answer for no * repository stands: the default, with the note that says why. */ export function cloneRoleFor(install: InstallKind, root: string | null): MarkerValue { if (install.kind === "package") return { value: "none", source: null, note: "package install" }; if (root === null) return { value: DEFAULT_CLONE_ROLE, source: null, note: "no repository" }; return inspectCloneRole(root); } /** The clone-role rows of `status` and `version`, one renderer for both (CR138). */ export function renderCloneRoleLines(install: InstallKind, role: MarkerValue): string[] { if (install.kind === "package") return ["Clone role: none (package install)"]; const lines = [`Clone role: ${role.value}`]; if (role.note) lines.push(`Clone role note: ${role.note}`); return lines; } /** * `update --check` for an install whose repository is not asked: the same * shape as the check's own `unknown`, with the reason (CR138). An install that * cannot be identified has no checkout to ask, and the cwd is not one. */ export function unavailableUpdateCheck( version: string, updateChannel: MarkerValue, note: string, ): UpdateAvailability { return availability(version, updateChannel, { note }); } /** * The repository rows of `status` and `version`: the oracle's four for a * clone (dirty only where the report carries it), one honest row for a package. */ export function renderRepositoryLines( install: InstallKind, git: GitStatus, withDirty: boolean, ): string[] { if (install.kind === "package") return ["Repository: none (package install)"]; const lines = [ `Repository: ${git.repository ?? "unknown"}`, `Git branch: ${git.branch || "unknown"}`, `Git commit: ${git.commit || "unknown"}`, ]; if (withDirty) lines.push(`Git dirty: ${git.dirty === null ? "unknown" : git.dirty ? "yes" : "no"}`); if (git.error) lines.push(`Git status note: ${git.error}`); return lines; } export function renderRuntimeVersion(report: RuntimeVersionReport): string { const lines = ["Mirror runtime version", ""]; lines.push(`Version: ${report.version}`); lines.push(...renderInstallLines(report.install)); lines.push(...renderRepositoryLines(report.install, report.git, false)); lines.push(...renderCloneRoleLines(report.install, report.cloneRole)); lines.push(`Update channel: ${report.updateChannel.value}`); if (report.updateChannel.note) lines.push(`Update channel note: ${report.updateChannel.note}`); return `${lines.join("\n")}\n`; } export function renderRuntimeUpdateAvailability(report: UpdateAvailability): string { const lines = ["Mirror runtime update check", ""]; lines.push(`Version: ${report.version}`); lines.push(`Update channel: ${report.update_channel.value}`); if (report.update_channel.note) lines.push(`Update channel note: ${report.update_channel.note}`); lines.push(`Current: ${report.local_commit ? report.local_commit.slice(0, 7) : "unknown"}`); if (report.upstream) { const remote = report.remote_commit ? report.remote_commit.slice(0, 7) : "unknown"; lines.push(`Upstream: ${report.upstream} @ ${remote}`); } else { lines.push("Upstream: none"); } lines.push(`Availability: ${report.status}`); if (report.note) lines.push(`Reason: ${report.note}`); if (report.status === "update_available") { lines.push(""); if (report.update_channel.value === "stable") { lines.push( "Release details: not fetched by this check; dry-run can show them when local refs contain release notes.", ); } // CV22.DS10.US2: engine-neutral, changed in the oracle first and // regenerated into the golden. The TypeScript core told users to run the // interpreter this migration deletes; the COMMAND was always the same on // both engines, and the npm-era invocation does not exist until US3 // defines a `bin`. lines.push("Preview:"); lines.push("runtime update --dry-run"); lines.push(""); lines.push("Update:"); lines.push("runtime update"); } else if (report.status === "up_to_date") { lines.push(""); lines.push("Next: no update needed"); } return `${lines.join("\n")}\n`; }