UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

292 lines (291 loc) • 14 kB
import { createHash } from "node:crypto"; import { gitAt, shq } from "../git-worktree-env.js"; import { CHANGES_CONTENT_MAX_BYTES, CHANGES_ROWS_MAX, changesContentBudget, changesContentOf, changesSideOf } from "../session-changes.js"; import { readObjectAt, readWithin } from "../../tools/fs/bound-open.js"; export const GIT_CHANGES_START_TIMEOUT_MS = 5_000; export const GIT_CHANGES_START_MAX_OUTPUT_BYTES = 4 * 1024 * 1024; const EMPTY = "SESSION_CHANGES_EMPTY"; const GIT_CHANGES_ENV = Object.freeze({ LC_ALL: "C", GIT_NO_LAZY_FETCH: "1", [EMPTY]: "" }); const GIT = "git --no-pager --no-optional-locks -c diff.autoRefreshIndex=false -c diff.relative=false -c core.quotePath=false -c core.fsmonitor="; const FILTER_PROGRAM_KEYS = new Set(["clean", "smudge", "process"]); const ATTR_PATHS_MAX_BYTES = 32 * 1024; const EMPTY_TREE = { sha1: "4b825dc642cb6eb9a060e54bf8d69288fbee4904", sha256: "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321" }; const REPLACEMENT = String.fromCharCode(0xfffd); const GITLINK = "160000"; export async function readGitChanges(input) { const { env, root, contentOf, signal } = input; const bounds = { timeoutMs: GIT_CHANGES_START_TIMEOUT_MS, maxOutputBytes: GIT_CHANGES_START_MAX_OUTPUT_BYTES, env: GIT_CHANGES_ENV, ...(signal !== undefined ? { signal } : {}) }; const startWith = (options) => (args, cwd) => gitAt(env, `${options} ${args}`, cwd, undefined, false, bounds); const unavailable = (reason) => ({ kind: "unavailable", reason }); const where = await startWith(GIT)("rev-parse --show-toplevel", root); if (where === undefined) return unavailable("git_failed"); if (where.exitCode !== 0) return unavailable(/not a git repository|must be run in a work tree/.test(where.stderr) ? "not_a_repository" : "git_failed"); const top = lineOf(where.stdout); const dir = top === undefined ? undefined : await startWith(GIT)("rev-parse --absolute-git-dir", top); const gitDir = dir === undefined || dir.exitCode !== 0 ? undefined : lineOf(dir.stdout); if (top === undefined || gitDir === undefined) return unavailable("git_failed"); const drivers = await repositoryFilterDrivers(startWith(GIT), top); if (drivers === undefined) return unavailable("git_failed"); const git = startWith([GIT, ...[...drivers].flatMap((name) => ["clean", "smudge", "process", "required"].map((key) => `--config-env=${shq(`filter.${name}.${key}=${EMPTY}`)}`))].join(" ")); for (const marker of ["MERGE_HEAD", "rebase-merge", "rebase-apply"]) { const at = await env.joinPath([gitDir, marker], signal); if (!at.ok) return unavailable("git_failed"); const there = await env.exists(at.value, signal); if (!there.ok) return unavailable("git_failed"); if (there.value) return unavailable("repository_busy"); } const head = await git(`rev-parse --verify -q ${shq("HEAD^{commit}")}`, top); if (head === undefined) return unavailable("git_failed"); let base; let before; if (head.exitCode === 0 && head.stdout.trim() !== "") { base = head.stdout.trim(); before = { kind: "git", base: "head", commit: base }; } else { const named = await git("rev-parse --verify -q HEAD", top); if (named === undefined || named.exitCode !== 1) return unavailable("git_failed"); const format = await git("rev-parse --show-object-format", top); const objectFormat = format?.exitCode === 0 ? format.stdout.trim() : undefined; const empty = objectFormat === "sha1" || objectFormat === "sha256" ? EMPTY_TREE[objectFormat] : undefined; if (empty === undefined) return unavailable("git_failed"); base = empty; before = { kind: "git", base: "empty_tree" }; } const diff = await git(`diff --no-ext-diff --no-textconv --no-color --ignore-submodules=dirty --submodule=short --no-abbrev --raw --numstat -z -M ${shq(base)} --`, top); if (diff === undefined || diff.exitCode !== 0 || !wholeZ(diff.stdout)) return unavailable("git_failed"); const status = await git("status --porcelain=v2 -z --untracked-files=no --no-renames --ignore-submodules=dirty", top); const changed = status === undefined || status.exitCode !== 0 ? undefined : statusPaths(status.stdout); if (changed === undefined) return unavailable("git_failed"); const records = parseRawNumstat(diff.stdout, changed); if (records === undefined) return unavailable("git_failed"); const others = await git("ls-files -z --others --exclude-standard --full-name", top); if (others === undefined || others.exitCode !== 0 || !wholeZ(others.stdout)) return unavailable("git_failed"); const all = [...records]; for (const path of others.stdout.split("\0")) { if (path !== "") all.push({ status: "untracked", path, srcMode: "000000", dstMode: "100644", srcBlob: "", lines: { uncounted: "untracked" } }); } if (drivers.size > 0) { const governed = await governedPaths(git, top, all.map((r) => r.path), drivers); if (governed === undefined) return unavailable("git_failed"); for (const r of all) { if (!governed.has(r.path) || r.srcMode === GITLINK || r.dstMode === GITLINK) continue; r.lines = { uncounted: "repository_filter" }; delete r.modeOnly; r.filtered = true; } } const budget = changesContentBudget(); const rowOf = async (r) => { const row = { path: r.path, status: r.status, ...(r.from !== undefined ? { renamedFrom: r.from } : {}), ...(r.modeOnly === true ? { modeOnly: true } : {}), lines: r.lines }; return contentOf.has(r.path) ? { ...row, content: await contentOfRecord(env, git, top, r, budget, signal) } : row; }; const after = { kind: "working_tree" }; if (all.length <= CHANGES_ROWS_MAX) { const rows = []; for (const r of all) rows.push(await rowOf(r)); return { kind: "rows", before, after, rows }; } let files = 0; let insertions = 0; let deletions = 0; const uncounted = {}; const named = []; for (const r of all) { if ("uncounted" in r.lines) uncounted[r.lines.uncounted] = (uncounted[r.lines.uncounted] ?? 0) + 1; else { files += 1; insertions += r.lines.insertions; deletions += r.lines.deletions; } if (contentOf.has(r.path)) named.push(await rowOf(r)); } return { kind: "totals", before, after, filesCount: all.length, counted: { files, insertions, deletions }, uncounted, named }; } function parseRawNumstat(out, changed) { const t = out.split("\0"); let i = 0; const raw = []; while (i < t.length && t[i].startsWith(":")) { const m = /^:(\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) ([A-Z])(\d*)$/.exec(t[i]); if (m === null) return undefined; const [srcMode, dstMode, srcBlob, letter] = [m[1], m[2], m[3], m[5]]; const two = letter === "R" || letter === "C"; const first = t[i + 1]; const second = two ? t[i + 2] : undefined; if (first === undefined || (two && second === undefined)) return undefined; i += two ? 3 : 2; const status = letter === "A" || letter === "C" ? "added" : letter === "D" ? "deleted" : letter === "R" ? "renamed" : "modified"; raw.push({ letter, status, path: two ? second : first, ...(letter === "R" ? { from: first } : {}), srcMode, dstMode, srcBlob, lines: { insertions: 0, deletions: 0 } }); } const counted = new Map(); while (i < t.length && t[i] !== "") { const m = /^(\d+|-)\t(\d+|-)\t(.*)$/s.exec(t[i]); if (m === null) return undefined; const path = m[3] === "" ? t[i + 2] : m[3]; if (path === undefined) return undefined; i += m[3] === "" ? 3 : 1; counted.set(path, [m[1], m[2]]); } if (!t.slice(i).every((rest) => rest === "")) return undefined; const records = []; for (const { letter, ...r } of raw) { const gitlink = r.srcMode === GITLINK || r.dstMode === GITLINK; if (!changed.has(r.path)) continue; const c = counted.get(r.path); if (gitlink) r.lines = { uncounted: "submodule" }; else if (c === undefined) { if (r.srcMode === r.dstMode) continue; return undefined; } else r.lines = c[0] === "-" || c[1] === "-" ? { uncounted: "binary" } : { insertions: Number(c[0]), deletions: Number(c[1]) }; if (letter === "M" && REGULAR.has(r.srcMode) && REGULAR.has(r.dstMode) && r.srcMode !== r.dstMode && c?.[0] === "0" && c[1] === "0") r.modeOnly = true; records.push(r); } return records; } const REGULAR = new Set(["100644", "100755"]); function statusPaths(out) { if (!wholeZ(out)) return undefined; const paths = new Set(); for (const record of out.split("\0")) { if (record === "") continue; const fields = record.startsWith("1 ") ? 8 : record.startsWith("u ") ? 10 : undefined; if (fields === undefined) return undefined; const parts = record.split(" "); if (parts.length <= fields) return undefined; paths.add(parts.slice(fields).join(" ")); } return paths; } async function repositoryFilterDrivers(git, top) { const names = new Set(); for (const scoped of [true, false]) { const listed = await git(`config ${scoped ? "--show-scope" : "--local"} --name-only -z --get-regexp ${shq("^filter\\.")}`, top); if (listed === undefined || !wholeZ(listed.stdout) || !(listed.exitCode === 0 || (listed.exitCode === 1 && listed.stdout === ""))) return undefined; if (listed.stdout.includes(REPLACEMENT)) return undefined; const fields = listed.stdout.split("\0").slice(0, -1); for (let i = 0; i < fields.length; i += scoped ? 2 : 1) { if (scoped && fields[i] !== "local" && fields[i] !== "worktree") continue; const key = fields[scoped ? i + 1 : i] ?? ""; const dot = key.lastIndexOf("."); if (dot >= "filter.".length && FILTER_PROGRAM_KEYS.has(key.slice(dot + 1))) names.add(key.slice("filter.".length, dot)); } } return names; } async function governedPaths(git, top, paths, drivers) { const governed = new Set(); for (let i = 0; i < paths.length;) { const asked = []; for (let bytes = 0; i < paths.length && (asked.length === 0 || bytes + Buffer.byteLength(shq(paths[i])) < ATTR_PATHS_MAX_BYTES); i++) { bytes += Buffer.byteLength(shq(paths[i])) + 1; asked.push(paths[i]); } const out = await git(`check-attr -z filter -- ${asked.map(shq).join(" ")}`, top); if (out === undefined || out.exitCode !== 0 || !wholeZ(out.stdout)) return undefined; const t = out.stdout.split("\0"); if (t.length !== asked.length * 3 + 1) return undefined; for (const [k, path] of asked.entries()) { if (t[3 * k] !== path || t[3 * k + 1] !== "filter") return undefined; if (drivers.has(t[3 * k + 2])) governed.add(path); } } return governed; } function wholeZ(out) { return out === "" || out.endsWith("\0"); } function lineOf(out) { const line = out.endsWith("\n") ? out.slice(0, -1) : out; return line === "" ? undefined : line; } async function contentOfRecord(env, git, top, r, budget, signal) { if (r.srcMode === GITLINK || r.dstMode === GITLINK) return { omitted: "submodule" }; if (r.filtered === true) return { omitted: "repository_filter" }; if (r.modeOnly === true) return { omitted: "mode_only" }; const before = r.status === "added" || r.status === "untracked" ? changesSideOf(null) : await committedSide(git, top, r.srcBlob); const after = r.status === "deleted" ? changesSideOf(null) : await workingSide(env, top, r.path, signal); return changesContentOf(before, after, budget); } async function committedSide(git, top, blob) { const size = await git(`cat-file -s ${shq(blob)}`, top); if (size === undefined || size.exitCode !== 0 || !/^\d+$/.test(size.stdout.trim())) return { omitted: "unreadable" }; if (Number(size.stdout.trim()) > CHANGES_CONTENT_MAX_BYTES) return { omitted: "too_large" }; const read = await git(`cat-file blob ${shq(blob)}`, top); if (read === undefined || read.exitCode !== 0) return { omitted: "unreadable" }; const bytes = Buffer.from(read.stdout, "utf8"); if (gitBlobIdOf(bytes, blob.length) === blob) return changesSideOf(bytes); return { omitted: read.stdout.includes(REPLACEMENT) ? "binary" : "unreadable" }; } async function workingSide(env, top, path, signal) { const at = await env.joinPath([top, path], signal); if (!at.ok) return { omitted: "unreadable" }; const opened = await readObjectAt(env, at.value, async () => true, signal); if (!opened.ok) return { omitted: "unreadable" }; try { const read = await readWithin(opened.value, CHANGES_CONTENT_MAX_BYTES, signal); if (read.kind === "over") return { omitted: "too_large" }; if (read.kind === "failed") return { omitted: "unreadable" }; return changesSideOf(read.bytes); } finally { await opened.value.close(); } } function gitBlobIdOf(bytes, hexLength) { return createHash(hexLength === 64 ? "sha256" : "sha1").update(`blob ${bytes.byteLength}\0`).update(bytes).digest("hex"); }