@sema-agent/core
Version:
Stateless, task-oriented AI agent core
350 lines (349 loc) • 18.7 kB
JavaScript
import { randomUUID } from "node:crypto";
import { thrownLabel, thrownText } from "./thrown-value.js";
import { outcomeFactOf, withOutcomeNote } from "./exec-outcome.js";
import { repositoryTopOf } from "../tools/fs/shell-read-object-path.js";
import { pathFamilyOf } from "../tools/fs/safety.js";
import { GIT_READ_ONLY as G } from "./git-read-only.js";
export const WORKTREE_PARENT = ".sema/worktrees";
const WORKTREE_BRANCH_PREFIX = "sema";
const NAME_SEGMENT = /^[a-zA-Z0-9._-]+$/;
const NAME_MAX = 64;
export function worktreeNameProblem(name) {
if (name.length > NAME_MAX)
return `Invalid worktree name: must be ${NAME_MAX} characters or fewer (got ${name.length})`;
for (const segment of name.split("/")) {
if (segment === "." || segment === "..")
return `Invalid worktree name "${name}": must not contain "." or ".." path segments`;
if (segment.toLowerCase().replace(/\.+$/, "") === ".git")
return `Invalid worktree name "${name}": "${segment}" is a reserved git directory name`;
if (!NAME_SEGMENT.test(segment))
return `Invalid worktree name "${name}": each "/"-separated segment must be non-empty and contain only letters, digits, dots, underscores, and dashes`;
}
return undefined;
}
function slugOf(name) {
return name.replaceAll("/", "+");
}
export function managedWorktreeDir(repoRoot, name) {
return `${repoRoot}/${WORKTREE_PARENT}/${slugOf(name)}`;
}
export function managedWorktreeBaseOf(dir) {
const parts = dir.split("/");
if (parts.length < 4)
return undefined;
const [dot, parent, slug] = parts.slice(-3);
if (dot !== ".sema" || parent !== "worktrees" || slug === undefined || slug === "" || slug === "." || slug === "..")
return undefined;
const base = parts.slice(0, -3).join("/");
return base === "" ? "/" : base;
}
export function managedTreeAt(dir) {
const parts = dir.split("/");
for (let end = parts.length; end >= 4; end--) {
const root = parts.slice(0, end).join("/");
const base = managedWorktreeBaseOf(root);
if (base === undefined)
continue;
return parts.slice(end).some((s) => s === "." || s === "..") ? undefined : { root, base };
}
return undefined;
}
const MANAGED_MARKER = `/${WORKTREE_PARENT}/`;
export async function repositoryRootOf(env, dir, signal) {
const canonical = await env.canonicalPath(dir, signal);
const spelled = canonical.ok ? canonical.value : dir;
const at = spelled.indexOf(MANAGED_MARKER);
const base = at < 0 ? dir : at === 0 ? "/" : spelled.slice(0, at);
return repositoryTopOf(env, base, pathFamilyOf({ root: base }), signal);
}
export async function managedAnchorOf(env, root) {
const top = await repositoryRootOf(env, root);
if (top === undefined)
return root;
const own = await env.canonicalPath(root);
return own.ok && own.value === top ? root : top;
}
export function managedWorktreeBranchOf(dir) {
if (managedWorktreeBaseOf(dir) === undefined)
return undefined;
return `${WORKTREE_BRANCH_PREFIX}/${dir.slice(dir.lastIndexOf("/") + 1)}`;
}
export async function gitAt(env, command, cwd, readFloor, rethrow = false, bounds) {
const stop = bounds !== undefined ? new AbortController() : undefined;
let over = false;
let seen = 0;
const count = (chunk) => {
seen += Buffer.byteLength(chunk, "utf8");
if (bounds !== undefined && seen > bounds.maxOutputBytes && !over) {
over = true;
stop?.abort();
}
};
const timer = bounds !== undefined ? setTimeout(() => ((over = true), stop?.abort()), bounds.timeoutMs) : undefined;
try {
const floor = readFloor?.();
const bounded = bounds !== undefined && stop !== undefined
? { timeout: Math.ceil(bounds.timeoutMs / 1000), abortSignal: bounds.signal !== undefined ? AbortSignal.any([stop.signal, bounds.signal]) : stop.signal, ...(bounds.env !== undefined ? { env: { ...bounds.env } } : {}), onStdout: count, onStderr: count }
: {};
const r = await env.exec(command, { cwd, ...(floor !== undefined ? { readFloor: floor } : {}), ...bounded });
if (!r.ok)
return undefined;
if (bounds !== undefined && (over || bounds.signal?.aborted === true || Buffer.byteLength(r.value.stdout, "utf8") + Buffer.byteLength(r.value.stderr, "utf8") > bounds.maxOutputBytes))
return undefined;
return r.value;
}
catch (err) {
if (rethrow)
throw err;
return undefined;
}
finally {
if (timer !== undefined)
clearTimeout(timer);
}
}
const IGNORED_NAMED = 5;
export function namedIgnored(paths) {
const named = paths.slice(0, IGNORED_NAMED).map((p) => p.slice(0, 120)).join(", ");
return paths.length > IGNORED_NAMED ? `${named} and ${paths.length - IGNORED_NAMED} more` : named;
}
function ignoredDetail(paths) {
return `the tree holds files git ignores (${namedIgnored(paths)}), which removing it would delete — delete or move them, then release again`;
}
export async function treeHoldsOf(env, path, baseSha, readFloor, opts) {
const rethrow = opts?.rethrow === true;
const status = await gitAt(env, `${G} status --porcelain --ignored --untracked-files=normal`, path, readFloor, rethrow);
if (status === undefined || status.exitCode !== 0)
return undefined;
const entries = status.stdout.split("\n").filter((line) => line !== "");
const ignored = entries.filter((line) => line.startsWith("!! ")).map((line) => line.slice(3));
let commits;
const branch = managedWorktreeBranchOf(path);
if (baseSha !== undefined && branch !== undefined) {
const countOf = async (tips) => {
const ahead = await gitAt(env, `${G} rev-list --count ${[...tips, `^${baseSha}`].map(shq).join(" ")} --`, path, readFloor, rethrow);
const counted = ahead !== undefined && ahead.exitCode === 0 ? Number.parseInt(ahead.stdout.trim(), 10) : Number.NaN;
return Number.isFinite(counted) ? counted : undefined;
};
commits = await countOf([`refs/heads/${branch}`, "HEAD"]);
if (commits === undefined && (await branchAbsentOf(env, path, branch, readFloor, rethrow)))
commits = await countOf(["HEAD"]);
}
return { files: entries.length - ignored.length, ignored, commits };
}
export function keptByHolds(holds) {
if (holds === undefined)
return { kept: "unverifiable" };
if (holds.files > 0)
return { kept: "dirty" };
if (holds.ignored.length > 0)
return { kept: "ignored", detail: ignoredDetail(holds.ignored) };
if (holds.commits === undefined)
return { kept: "unverifiable" };
return holds.commits > 0 ? { kept: "commits" } : undefined;
}
export async function judgeManagedTree(env, tree, options) {
const keep = keptByHolds(await treeHoldsOf(env, tree.path, tree.baseSha, options?.readFloor));
return keep === undefined ? { collectable: true } : { collectable: false, ...keep };
}
async function branchListingOf(env, cwd, branch, readFloor, rethrow = false) {
const ref = `refs/heads/${branch}`;
const listed = await gitAt(env, `${G} for-each-ref --count=1 --format=${shq("%(refname)")} ${shq(ref)}`, cwd, readFloor, rethrow);
if (listed === undefined || listed.exitCode !== 0 || listed.stderr.trim() !== "")
return "unread";
const names = listed.stdout.trim();
return names === ref ? "present" : names === "" ? "empty" : "unread";
}
async function branchAbsentOf(env, cwd, branch, readFloor, rethrow = false) {
if ((await branchListingOf(env, cwd, branch, readFloor, rethrow)) !== "empty")
return false;
const verified = await gitAt(env, `printf 'start\\nverify %s\\nprepare\\nabort\\n' ${shq(`refs/heads/${branch}`)} | git update-ref --stdin`, cwd, readFloor, rethrow);
return verified !== undefined && verified.exitCode === 0;
}
export async function branchLeftOf(env, repository, branch, readFloor) {
return (await branchListingOf(env, repository, branch, readFloor)) === "present" ? { branch } : {};
}
export async function removeTreeIfClean(env, tree, readFloor, stillOurs) {
const { path, repository, branch, baseSha } = tree;
const verdict = await judgeManagedTree(env, { path, baseSha }, { readFloor });
if (!verdict.collectable)
return { path, removed: false, branch, kept: verdict.kept, ...(verdict.detail !== undefined ? { detail: verdict.detail } : {}) };
const notOurs = await stillOurs?.();
if (notOurs !== undefined)
return notOurs;
const removed = await removeManagedWorktree(env, repository, path, baseSha !== undefined ? { name: branch, baseSha } : undefined, readFloor, "clean");
if (!removed.ok)
return { path, removed: false, kept: "unverifiable", branch, detail: withOutcomeNote(removed.detail.trim().slice(0, 300), removed) };
return { path, removed: true, ...(await branchLeftOf(env, repository, branch, readFloor)) };
}
export function shq(s) {
return `'${s.replace(/'/g, "'\\''")}'`;
}
export async function symlinkedLevel(env, repoRoot, worktreeDir) {
for (const level of [`${repoRoot}/.sema`, `${repoRoot}/${WORKTREE_PARENT}`, worktreeDir]) {
const info = await env.fileInfo(level);
if (!info.ok) {
if (info.error.code === "not_found")
continue;
return `Cannot create worktree: failed to read ${level} (${thrownText(info.error)}); a level of the managed path whose kind is unknown could be a symlink. Nothing was created.`;
}
if (info.value.kind === "symlink") {
return `Cannot create worktree: ${level} is a symlink. A symlink at .sema, .sema/worktrees or .sema/worktrees/<name> could redirect worktree creation outside the repository. Remove the symlink and retry.`;
}
}
return undefined;
}
export async function removeManagedWorktree(baseEnv, repoRoot, worktreeDir, branch, readFloor, how) {
const readFloorNow = () => { const f = readFloor?.(); return f !== undefined ? { readFloor: f } : {}; };
let detail = "";
let unknownEarlier;
let removed = false;
for (let attempt = 0; attempt < 2 && !removed; attempt++) {
try {
const r = await baseEnv.exec(`git worktree remove ${how === "discard" ? "--force " : ""}${shq(worktreeDir)}`, { cwd: repoRoot, ...readFloorNow() });
if (r.ok && r.value.exitCode === 0)
removed = true;
else
detail = r.ok ? r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}` : thrownText(r.error);
if (!r.ok && outcomeFactOf(r.error).outcomeUnknown === true)
unknownEarlier ??= detail;
}
catch (err) {
detail = thrownLabel(err);
}
}
if (!removed)
return { ok: false, detail: unknownEarlier !== undefined && unknownEarlier !== detail ? `${detail} (after an earlier attempt: ${unknownEarlier})` : detail, ...(unknownEarlier !== undefined ? { outcomeUnknown: true } : {}) };
if (branch === undefined || branch.name !== managedWorktreeBranchOf(worktreeDir))
return { ok: true };
if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(branch.baseSha) || /^0+$/.test(branch.baseSha))
return { ok: true, branchKept: `${branch.name} (its base commit is not a usable witness)` };
try {
const del = await baseEnv.exec(`git update-ref --no-deref -d ${shq(`refs/heads/${branch.name}`)} ${shq(branch.baseSha)}`, { cwd: repoRoot, ...readFloorNow() });
if (del.ok && del.value.exitCode === 0)
return { ok: true, branchDeleted: branch.name };
const tip = await baseEnv.exec(`${G} rev-parse --verify --quiet ${shq(`refs/heads/${branch.name}`)}`, { cwd: repoRoot, ...readFloorNow() });
if (tip.ok && tip.value.exitCode !== 0)
return { ok: true };
if (tip.ok && tip.value.stdout.trim() !== branch.baseSha)
return { ok: true, branchKept: `${branch.name} (it carries commits made in the worktree)` };
const unknown = !del.ok && !tip.ok ? outcomeFactOf(del.error) : {};
return { ok: true, branchKept: `${branch.name} (it could not be deleted: ${del.ok ? (del.value.stderr || del.value.stdout).trim() : thrownText(del.error)})`, ...unknown };
}
catch (err) {
return { ok: true, branchKept: `${branch.name} (it could not be deleted: ${thrownLabel(err)})` };
}
}
export async function addWorktree(baseEnv, opts) {
const onExit = opts.onExit ?? "discard";
if (onExit !== "discard" && onExit !== "keep-if-dirty") {
throw Object.assign(new Error(`addWorktree: onExit must be "discard" or "keep-if-dirty"; nothing was created`), { code: "config.invalid_argument" });
}
const { worktreeDir, name, branch, anchor, baseSha } = await mintManagedWorktree(baseEnv, opts);
const branchRule = baseSha !== undefined ? { name: branch, baseSha } : undefined;
let inner;
try {
inner = await opts.rootEnvAt(worktreeDir);
}
catch (err) {
await removeManagedWorktree(baseEnv, anchor, worktreeDir, branchRule, opts.readFloor, "discard");
throw err;
}
const innerDestroy = inner.destroy;
const env = inner;
const release = async () => {
if (onExit === "keep-if-dirty")
return removeTreeIfClean(baseEnv, { path: worktreeDir, repository: anchor, branch, baseSha }, opts.readFloor);
const removed = await removeManagedWorktree(baseEnv, anchor, worktreeDir, branchRule, opts.readFloor, "discard");
if (!removed.ok) {
throw new Error(withOutcomeNote(removed.outcomeUnknown === true
? `git worktree remove did not succeed — whether ${worktreeDir} and its registration remain is not known (check it; if it is still there, remove it manually): ${removed.detail}`
: `git worktree remove failed twice — ${worktreeDir} is now an orphan (dir + registration remain; \`git worktree prune\` cannot reclaim it while the dir exists — remove it manually): ${removed.detail}`, removed));
}
};
env.destroy = async () => {
let innerFailure;
try {
if (typeof innerDestroy === "function")
await innerDestroy.call(inner);
}
catch (error) {
innerFailure = { error };
}
const released = await release();
if (innerFailure !== undefined)
throw innerFailure.error;
return released;
};
return { env, worktreeDir, name, branch, ...(baseSha !== undefined ? { baseSha } : {}) };
}
export async function mintManagedWorktree(baseEnv, opts) {
const name = opts.name ?? `${(opts.sessionId || "task").replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 50)}-${randomUUID().slice(0, 8)}`;
const nameProblem = worktreeNameProblem(name);
if (nameProblem !== undefined)
throw new Error(nameProblem);
const anchor = await managedAnchorOf(baseEnv, opts.repoRoot);
const worktreeDir = managedWorktreeDir(anchor, name);
const branch = `${WORKTREE_BRANCH_PREFIX}/${slugOf(name)}`;
const symlinked = await symlinkedLevel(baseEnv, anchor, worktreeDir);
if (symlinked !== undefined)
throw new Error(symlinked);
const readFloorNow = () => { const readFloor = opts.readFloor?.(); return readFloor !== undefined ? { readFloor } : {}; };
const add = await baseEnv.exec(`git worktree add --no-track -b ${shq(branch)} ${shq(worktreeDir)} ${shq(opts.commit ?? "HEAD")}`, {
cwd: opts.repoRoot,
...readFloorNow(),
});
if (!add.ok || add.value.exitCode !== 0) {
const detail = add.ok ? add.value.stderr || add.value.stdout : thrownText(add.error);
throw Object.assign(new Error(`git worktree add failed: ${detail}`), add.ok ? {} : outcomeFactOf(add.error));
}
const excludeLine = shq(`/${WORKTREE_PARENT}/`);
await Promise.resolve()
.then(() => baseEnv.exec(`ex="$(${G} rev-parse --git-path info/exclude)" && mkdir -p "$(dirname "$ex")" && ` +
`{ grep -qxF ${excludeLine} "$ex" 2>/dev/null || printf '%s\\n' ${excludeLine} >> "$ex"; }`, { cwd: anchor, ...readFloorNow() }))
.catch(() => undefined);
const baseSha = await Promise.resolve()
.then(() => baseEnv.exec(`${G} rev-parse HEAD`, { cwd: worktreeDir, ...readFloorNow() }))
.then((r) => (r.ok && r.value.exitCode === 0 && r.value.stdout.trim() !== "" ? r.value.stdout.trim() : undefined))
.catch(() => undefined);
return { worktreeDir, name, branch, anchor, ...(baseSha !== undefined ? { baseSha } : {}) };
}
export async function resolveBaseCommit(env, repoRoot, baseRef, readFloor) {
const rev = async (ref) => {
const r = await env.exec(`${G} rev-parse --verify --quiet ${shq(`${ref}^{commit}`)}`, { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
return r.ok && r.value.exitCode === 0 ? r.value.stdout.trim() : undefined;
};
if (baseRef === "head") {
const sha = await rev("HEAD");
return sha ? { sha, label: "HEAD" } : { error: "cannot resolve HEAD (empty repository with no commits?)" };
}
const sym = await env.exec(`${G} symbolic-ref --quiet refs/remotes/origin/HEAD`, { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
if (sym.ok && sym.value.exitCode === 0) {
const branch = sym.value.stdout.trim().replace(/^refs\/remotes\//, "");
if (branch) {
const sha = await rev(branch);
if (sha)
return { sha, label: branch };
}
}
for (const candidate of ["main", "master"]) {
const sha = await rev(candidate);
if (sha)
return { sha, label: candidate };
}
const sha = await rev("HEAD");
return sha
? { sha, label: "HEAD", note: " (no remote default branch or local main/master found — fell back to HEAD)" }
: { error: "cannot resolve a fresh base (no default branch and no HEAD)" };
}
export async function pruneWorktrees(baseEnv, repoRoot, readFloor) {
try {
const r = await baseEnv.exec("git worktree prune", { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
if (r.ok && r.value.exitCode === 0)
return { ok: true };
return r.ok ? { ok: false, detail: (r.value.stderr || r.value.stdout || `exit ${r.value.exitCode}`).trim() } : { ok: false, detail: thrownText(r.error), ...outcomeFactOf(r.error) };
}
catch (err) {
return { ok: false, detail: thrownLabel(err) };
}
}