@sema-agent/core
Version:
Stateless, task-oriented AI agent core
429 lines (428 loc) • 30.3 kB
JavaScript
import { resolve } from "node:path";
import { Type } from "typebox";
import { defineTool, errorResult } from "../core/tools.js";
import { addWorktree, keptByHolds, managedTreeAt, managedWorktreeBaseOf, managedWorktreeBranchOf, namedIgnored, pruneWorktrees, removeManagedWorktree, resolveBaseCommit, treeHoldsOf, worktreeNameProblem, WORKTREE_PARENT, } from "../core/git-worktree-env.js";
import { mountRuleFace, toolFace } from "../core/tool-catalog-entries.js";
import { thrownText } from "../core/thrown-value.js";
import { outcomeFactOfThrown, withOutcomeNote } from "../core/exec-outcome.js";
import { GIT_READ_ONLY as G } from "../core/git-read-only.js";
export function currentCheckoutOf(session, taskRoot) {
const dir = session?.current?.worktreeDir;
if (dir === undefined)
return taskRoot.canonical;
const spelled = taskRoot.spelled.endsWith("/") ? taskRoot.spelled.slice(0, -1) : taskRoot.spelled;
if (spelled !== taskRoot.canonical && (dir === spelled || dir.startsWith(`${spelled}/`)))
return taskRoot.canonical + dir.slice(spelled.length);
return dir;
}
export function writeLocationOf(taskRoot, writeRoots = []) {
const seat = {};
const writeLocation = () => currentCheckoutOf(seat, taskRoot);
const checkout = () => {
const views = [];
const spellings = [[writeLocation(), "canonical"], [seat.current?.worktreeDir ?? taskRoot.spelled, "spelled"], ...writeRoots.flatMap((root) => [[root, "canonical"], [root, "spelled"]])];
for (const [at, kind] of spellings) {
const tree = managedTreeAt(at);
if (tree !== undefined && !views.some((v) => v.root === tree.root && v.kind === kind))
views.push({ root: tree.root, base: tree.base, kind });
}
return views.length > 0 ? views : undefined;
};
return { seat, writeLocation, checkout };
}
const ENTER_DESCRIPTION = "Use this tool ONLY when explicitly instructed to work in a worktree — either by the user directly, or by " +
"project instructions. This tool creates an isolated git worktree and switches the current session into it.\n" +
"\n" +
"## When to Use\n" +
"\n" +
'- The user explicitly says "worktree" (e.g., "start a worktree", "work in a worktree", "create a worktree", "use a worktree")\n' +
"- Project instructions direct you to work in a worktree for the current task\n" +
"\n" +
"## When NOT to Use\n" +
"\n" +
"- The user asks to create a branch, switch branches, or work on a different branch — use git commands instead\n" +
"- The user asks to fix a bug or work on a feature — use normal git workflow unless worktrees are explicitly " +
"requested by the user or project instructions\n" +
'- Never use this tool unless "worktree" is explicitly mentioned by the user or in project instructions\n' +
"\n" +
"## Behavior\n" +
"\n" +
`- Creates a new worktree under \`${WORKTREE_PARENT}/<name>/\` in the repository root on a new branch \`sema/<name>\` and ` +
"switches the session's working directory and write access to it: subsequent Bash commands run there, relative paths in " +
"Read/Edit/Write resolve against it, and file writes must land inside it (or in an additional working directory).\n" +
'- `baseRef` picks the starting point: `"fresh"` (default) starts from the default branch tip ' +
"(origin's default branch when a remote exists, else local main/master, else the current HEAD with " +
'an honest note); `"head"` starts from the current local HEAD (unpushed commits and current branch ' +
"state present).\n" +
"- Only one worktree session is tracked at a time: creating a NEW worktree (`name`) while one is active " +
"is refused — use ExitWorktree first (the unchanged worktree is removed; a changed one is kept and its " +
"path reported).\n" +
"- Pass `path` instead of `name` to switch the session into a worktree of this repository that already " +
"exists (it must appear in `git worktree list` and live under the task root). Switching with `path` also " +
"works while already in a worktree session — the previous worktree is left on disk, untouched, and only " +
"the new one is tracked for exit-time cleanup. ExitWorktree will not remove a worktree entered via `path`. After a further " +
"switch, previously-visited worktrees are no longer writable — re-issue EnterWorktree with `path` to return to one.\n" +
"- While a worktree is active, the base checkout and every other worktree are outside the write roots: where writes are " +
"confined to the write roots, Edit/Write refuse them and a shell command writing there asks first. Reads still reach the " +
"whole task root. Use ExitWorktree to " +
"write the base checkout again. This is not a sandbox: a program run in the shell can still write anywhere the process " +
"can — do not rely on the worktree as an isolation boundary.\n" +
"- Requires a git repository — there is no VCS-agnostic fallback in this deployment.";
const EXIT_DESCRIPTION = "Exit a worktree session created by EnterWorktree and return the session to the original working directory.\n" +
"\n" +
"## Scope\n" +
"\n" +
"This tool ONLY operates on worktrees created by EnterWorktree in this session. It will NOT touch:\n" +
"- Worktrees you created manually with `git worktree add`\n" +
"- Worktrees from a previous session (even if created by EnterWorktree then)\n" +
"- The directory you're in if EnterWorktree was never called\n" +
"\n" +
"If called outside an EnterWorktree session, the tool is a no-op: it reports that no worktree session is " +
"active and takes no action. Filesystem state is unchanged. The one exception is contradictory arguments " +
"(`keep: true` together with `discardChanges: true`), which are rejected before anything else, with or " +
"without an active session — that path changes nothing on disk either.\n" +
"\n" +
"## Behavior\n" +
"\n" +
"- Restores the session's working directory to where it was before EnterWorktree.\n" +
"- Default: if the worktree has NO changes (clean `git status`, no files git ignores, no new commits), it is removed and " +
"pruned; if it HAS uncommitted files, files git ignores (build output, `node_modules/`), or new commits (on its HEAD or its branch), it is KEPT on disk and its path and branch reported so the " +
"work can be inspected or merged — nothing is discarded.\n" +
"- A worktree entered via EnterWorktree `path` (not created by it) is NEVER removed — exit only restores " +
"the working directory.\n" +
"- `keep: true` always keeps the worktree on disk, changed or not.\n" +
"- `discardChanges: true` removes the worktree even when it HAS uncommitted files, files git ignores, or new commits — the files " +
"are permanently discarded; commits made on the worktree's branch stay on that branch (it is kept while it carries them). Only set this when the work is confirmed disposable (a throwaway experiment, " +
"or the user asked to discard it); it cannot be combined with `keep: true`.\n" +
"- Once exited, EnterWorktree can be called again to create a fresh worktree.";
function heldSentence(holds) {
const parts = [];
if (holds !== undefined) {
if (holds.files > 0)
parts.push(`${holds.files} uncommitted ${holds.files === 1 ? "file" : "files"}`);
if (holds.commits !== undefined && holds.commits > 0)
parts.push(`${holds.commits} new ${holds.commits === 1 ? "commit" : "commits"}`);
if (holds.ignored.length > 0)
parts.push(`${holds.ignored.length} ${holds.ignored.length === 1 ? "path" : "paths"} git ignores (${namedIgnored(holds.ignored)})`);
}
if (parts.length === 0)
return undefined;
return parts.length <= 2 ? parts.join(" and ") : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
}
function reasonOf(e) {
try {
if (typeof e === "object" && e !== null && !(e instanceof Error)) {
const m = e.message;
if (typeof m === "string" && m !== "")
return m;
}
}
catch {
}
return thrownText(e);
}
export function createWorktreeTools(env, opts) {
const { repoRoot, cwdRef } = opts;
const session = opts.session ?? {};
const enter = defineTool({
name: "EnterWorktree",
...toolFace("enter-worktree"),
ruleFace: mountRuleFace("enter-worktree"),
description: ENTER_DESCRIPTION,
parameters: Type.Object({
name: Type.Optional(Type.String({
description: 'Optional name for a new worktree. Each "/"-separated segment may contain only letters, digits, dots, underscores, and dashes; max 64 chars total. A random name is generated if not provided. Mutually exclusive with `path`.',
})),
path: Type.Optional(Type.String({
description: "Path to an existing worktree of the current repository to switch into instead of creating a new one. Must appear in `git worktree list` for the current repo (and live under the task root). Mutually exclusive with `name`.",
})),
baseRef: Type.Optional(Type.Union([Type.Literal("fresh"), Type.Literal("head")], {
description: '"fresh" (default) bases the worktree on the default branch tip (origin default branch, else local main/master, else the current HEAD with a note); "head" bases it on the current local HEAD (unpushed commits present).',
})),
}),
execute: async (args, ctx) => {
const { name, path, baseRef } = args;
if (path !== undefined && name !== undefined) {
return errorResult("Error (EnterWorktree): `name` and `path` are mutually exclusive — `path` enters an existing worktree, `name` creates a new one.");
}
if (path !== undefined && baseRef !== undefined) {
return errorResult("Error (EnterWorktree): `baseRef` only applies when creating a new worktree — an existing worktree entered via `path` keeps whatever state it has.");
}
if (session.current && path === undefined) {
return errorResult(`Error (EnterWorktree): already in a worktree session (${session.current.worktreeDir}). ` +
"Use ExitWorktree to leave it before creating a new worktree, or pass `path` to switch into an " +
"existing worktree of this repository.");
}
if (session.entering === true) {
return errorResult("Error (EnterWorktree): another EnterWorktree call on this session is already in progress — wait for it to " +
"finish and then act on its result. Two concurrent entries would leave one worktree untracked and unremovable.");
}
if (session.exiting === true) {
return errorResult("Error (EnterWorktree): an ExitWorktree call on this session is already in progress — wait for it to finish " +
"before entering another worktree.");
}
const readFloor = opts.readFloor?.(ctx.toolCallId);
session.entering = true;
try {
const probe = await env.exec(`${G} rev-parse --is-inside-work-tree`, { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
if (!probe.ok || probe.value.exitCode !== 0) {
const detail = probe.ok ? (probe.value.stderr || probe.value.stdout).trim().split("\n")[0] : thrownText(probe.error);
return errorResult(`Error (EnterWorktree): the working directory ${repoRoot} is not a git repository` +
`${detail ? ` (${detail})` : ""}. This deployment has no VCS-agnostic worktree extension point, ` +
"so worktree isolation is unavailable here.");
}
if (path !== undefined) {
const candidate = resolve(cwdRef.current, path);
const top = await env.exec(`${G} rev-parse --show-toplevel`, { cwd: candidate, ...(readFloor !== undefined ? { readFloor } : {}) });
if (!top.ok || top.value.exitCode !== 0) {
return errorResult(`Error (EnterWorktree): ${candidate} is not an accessible git worktree (cannot resolve its top-level directory).`);
}
const target = top.value.stdout.trim();
const list = await env.exec(`${G} worktree list --porcelain`, { cwd: repoRoot, ...(readFloor !== undefined ? { readFloor } : {}) });
if (!list.ok || list.value.exitCode !== 0) {
return errorResult("Error (EnterWorktree): could not read `git worktree list` for this repository.");
}
const registered = list.value.stdout
.split("\n")
.filter((l) => l.startsWith("worktree "))
.map((l) => l.slice("worktree ".length).trim());
if (!registered.includes(target)) {
return errorResult(`Error (EnterWorktree): ${target} is not a registered worktree of this repository ` +
"(it does not appear in `git worktree list`).");
}
if (target === registered[0]) {
return errorResult(`Error (EnterWorktree): ${target} is the main working tree, not a linked worktree — nothing to enter.`);
}
const rootCanon = await env.canonicalPath(repoRoot);
const fence = rootCanon.ok ? rootCanon.value : repoRoot;
if (target !== fence && !target.startsWith(fence.endsWith("/") ? fence : `${fence}/`) && managedWorktreeBaseOf(target) === undefined) {
return errorResult(`Error (EnterWorktree): the worktree ${target} lives outside the task root ${repoRoot}; ` +
"read containment stays anchored at the task root, so it cannot be entered from this session.");
}
const head = await env.exec(`${G} rev-parse HEAD`, { cwd: target, ...(readFloor !== undefined ? { readFloor } : {}) });
if (!head.ok || head.value.exitCode !== 0) {
return errorResult(`Error (EnterWorktree): cannot resolve HEAD of the worktree ${target}.`);
}
const previous = session.current;
const originalCwd = previous ? previous.originalCwd : cwdRef.current;
session.current = { worktreeDir: target, originalCwd, baseSha: head.value.stdout.trim(), entered: true };
cwdRef.current = target;
return {
content: `Switched into the existing worktree at ${target}${previous ? ` (the previous worktree at ${previous.worktreeDir} was left on disk, untouched, and is no longer writable)` : ""}. ` +
"The session's working directory and write access are now this worktree — subsequent commands and relative paths " +
"operate there, and writes outside it (the base checkout included) are outside the write roots. Reads still reach " +
"the whole task root; this is not a sandbox. ExitWorktree will restore the original directory but will NOT remove a " +
"worktree entered via `path`.",
details: { type: "worktree", action: "enter", worktreeDir: target },
};
}
const nameProblem = name === undefined ? undefined : worktreeNameProblem(name);
if (nameProblem !== undefined)
return errorResult(`Error (EnterWorktree): ${nameProblem.slice(0, 300)}.`);
const base = await resolveBaseCommit(env, repoRoot, baseRef ?? "fresh", readFloor);
if ("error" in base)
return errorResult(`Error (EnterWorktree): ${base.error}.`);
let created;
try {
created = await addWorktree(env, {
repoRoot,
sessionId: "worktree",
...(name !== undefined ? { name } : {}),
commit: base.sha,
readFloor: () => readFloor,
rootEnvAt: (dir) => Object.create(env, {
cwd: { value: dir, configurable: true },
destroy: { value: undefined, writable: true, configurable: true },
}),
});
}
catch (e) {
return errorResult(withOutcomeNote(`Error (EnterWorktree): ${thrownText(e)}`, outcomeFactOfThrown(e)));
}
const createdDir = created.worktreeDir;
session.current = {
worktreeDir: createdDir,
originalCwd: cwdRef.current,
baseSha: base.sha,
name: created.name,
branch: created.branch,
};
cwdRef.current = createdDir;
return {
content: `Created worktree at ${createdDir} (base: ${base.label}${base.note ?? ""}) on branch ${created.branch}. ` +
"The session's working directory and write access are now the worktree — subsequent commands and relative paths " +
"operate there, and writes outside it (the base checkout included) are outside the write roots. Reads still reach " +
"the rest of the task root; this is not a sandbox. " +
"Use ExitWorktree to leave (an unchanged worktree is removed; a changed one is kept).",
details: { type: "worktree", action: "create", worktreeDir: createdDir, base: base.label },
};
}
finally {
session.entering = false;
}
},
});
const exit = defineTool({
name: "ExitWorktree",
...toolFace("exit-worktree"),
ruleFace: mountRuleFace("exit-worktree"),
description: EXIT_DESCRIPTION,
parameters: Type.Object({
keep: Type.Optional(Type.Boolean({
description: "true = always keep the worktree on disk. Default: keep only when it has uncommitted files, files git ignores, or new commits; remove when it has none.",
})),
discardChanges: Type.Optional(Type.Boolean({
description: "true = remove the worktree even when it has uncommitted files, files git ignores, or new commits; the files are permanently discarded, the commits stay on the worktree's branch (kept while it carries them). Default false: a changed worktree is kept and its changes listed. Cannot be combined with `keep: true`.",
})),
action: Type.Optional(Type.Union([Type.Literal("keep"), Type.Literal("remove")], {
description: '"keep" leaves the worktree and its branch on disk. "remove" takes the default removal path: an unchanged worktree is removed, a changed one is still KEPT unless `discard_changes: true`. A removed worktree\'s branch is deleted with it only when it carries no commits beyond the base; a branch with commits is kept and named in the reply.',
})),
discard_changes: Type.Optional(Type.Boolean({
description: 'Set true to remove the worktree even when it has uncommitted files, files git ignores, or unmerged commits — the files are permanently discarded, the commits stay on the worktree\'s branch (kept while it carries them). Without it a changed worktree is KEPT (the exit still completes and the reply lists the changes plus this escape), never refused.',
})),
}),
execute: async (args, ctx) => {
const raw = args;
const keep = raw.keep ?? (raw.action === "keep" ? true : undefined);
const discardChanges = raw.discardChanges ?? raw.discard_changes;
const wantsRemove = raw.action === "remove";
if (keep === true && discardChanges === true) {
return errorResult("Error (ExitWorktree): `keep: true` and `discardChanges: true` contradict each other — pick one.");
}
if (!session.current) {
return ("No-op: there is no active EnterWorktree session to exit. This tool only operates on the " +
"worktree created by EnterWorktree in this session; no filesystem changes were made.");
}
if (session.exiting === true) {
return errorResult("Error (ExitWorktree): an exit of this worktree session is already in progress — wait for it to finish. " +
"Running a second exit now would race the same removal.");
}
const active = session.current;
const readFloor = opts.readFloor?.(ctx.toolCallId);
session.exiting = true;
try {
const outcome = await runExit(active, { keep, discardChanges, wantsRemove, readFloor });
session.current = undefined;
return outcome;
}
catch (e) {
return errorResult(`Error (ExitWorktree): the exit failed before it could complete (${reasonOf(e)}). The worktree session at ` +
`${active.worktreeDir} is still active and nothing was removed — retry ExitWorktree.`);
}
finally {
session.exiting = false;
}
},
});
async function runExit(active, opts2) {
const { keep, discardChanges, wantsRemove, readFloor } = opts2;
let restoredTo = active.originalCwd;
let restoreNote = "";
const origThere = await env.exists(active.originalCwd);
if (origThere.ok && !origThere.value) {
restoredTo = repoRoot;
restoreNote = ` (the original directory ${active.originalCwd} no longer exists — fell back to the repository root)`;
}
else if (!origThere.ok) {
restoreNote = ` (whether ${active.originalCwd} still exists could not be verified: ${reasonOf(origThere.error)} — the directory was restored as-is)`;
}
cwdRef.current = restoredTo;
if (active.entered) {
const discardNote = discardChanges === true ? " (`discardChanges` does not apply to a worktree this session did not create)" : "";
const enteredThere = await env.exists(active.worktreeDir);
if (enteredThere.ok && !enteredThere.value) {
return {
content: `Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree at ${active.worktreeDir} was entered via \`path\` (not created by this session), so this ` +
`session never touched it — but it is no longer on disk (removed by something else while it was entered)${discardNote}.`,
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: false },
};
}
const enteredUnverified = enteredThere.ok ? "" : ` (whether it is still on disk could not be verified: ${reasonOf(enteredThere.error)})`;
return {
content: `Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree at ${active.worktreeDir} was entered via \`path\` (not created by this session) and ` +
`was left on disk, untouched${enteredUnverified}${discardNote}.`,
details: {
type: "worktree",
action: "exit",
worktreeDir: active.worktreeDir,
...(enteredThere.ok ? { kept: true } : {}),
},
};
}
const wtThere = await env.exists(active.worktreeDir);
if (wtThere.ok && !wtThere.value) {
const pruned = await pruneWorktrees(env, repoRoot, readFloor);
return {
content: withOutcomeNote(`Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree at ${active.worktreeDir} was already gone from disk (removed externally, not by this ` +
"session — any uncommitted work in it is lost); " +
(pruned.ok
? "stale git worktree metadata was pruned."
: `stale git worktree metadata could NOT be pruned (${pruned.detail}) — run \`git worktree prune\` in ${repoRoot} to clear the leftover registration.`), pruned),
details: {
type: "worktree",
action: "exit",
worktreeDir: active.worktreeDir,
kept: false,
...(pruned.ok ? {} : { metadataPruned: false }),
},
};
}
const holds = await treeHoldsOf(env, active.worktreeDir, active.baseSha, () => readFloor, { rethrow: true });
const changed = keptByHolds(holds) !== undefined;
const held = heldSentence(holds);
if (keep === true || (changed && discardChanges !== true)) {
const why = keep === true ? "keep was requested" : held === undefined ? "its state could not be verified, so it is kept to be safe" : `it has ${held}`;
const branch = active.branch ?? managedWorktreeBranchOf(active.worktreeDir);
const onBranch = branch === undefined ? "" : `; its branch is ${branch}, and commits made on a branch stay on it even when the tree's HEAD has moved off it`;
const removeHint = wantsRemove && keep !== true
? " To remove the tree anyway, re-invoke with discard_changes: true — the files in it are then discarded for good, its commits stay on the branches that carry them."
: "";
return {
content: `Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree was KEPT at ${active.worktreeDir} (${why})${onBranch} — inspect or merge it there, and remove it ` +
"later with `git worktree remove` if no longer needed." +
removeHint,
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: true },
};
}
const removal = await removeManagedWorktree(env, repoRoot, active.worktreeDir, active.branch !== undefined ? { name: active.branch, baseSha: active.baseSha } : undefined, () => readFloor, "discard");
const removeFailure = removal.ok ? undefined : removal.detail.trim();
const branchNote = !removal.ok ? "" : removal.branchKept !== undefined ? ` Its branch was kept: ${removal.branchKept}.` : removal.branchDeleted !== undefined ? ` Its branch ${removal.branchDeleted} was deleted.` : "";
const pruned = await pruneWorktrees(env, repoRoot, readFloor);
const stillThere = await env.exists(active.worktreeDir);
const removalNote = removeFailure !== undefined ? ` (the removal command reported: ${removeFailure})` : "";
const pruneNote = pruned.ok ? "" : ` (stale git worktree metadata could NOT be pruned: ${pruned.detail} — run \`git worktree prune\` in ${repoRoot})`;
const pruneDetail = pruned.ok ? {} : { metadataPruned: false };
const commitsStay = holds !== undefined && (holds.commits ?? 0) > 0;
const discardNote = commitsStay
? "discardChanges was set — the tree and any uncommitted or ignored files in it are gone; its commits stay on the branches that carry them"
: "discarded — discardChanges was set";
const stateClause = changed ? `had ${held ?? "changes that could not be enumerated"} (${discardNote})` : "had no changes";
if (stillThere.ok && stillThere.value) {
return {
content: withOutcomeNote(`Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree at ${active.worktreeDir} ${changed ? "was marked for discard" : "had no changes"} but could NOT be removed — it is still on disk${removalNote}${pruneNote}; ` +
"remove it manually with `git worktree remove --force` if no longer needed.", pruned),
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: true, ...pruneDetail },
};
}
if (!stillThere.ok) {
return {
content: withOutcomeNote(`Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree at ${active.worktreeDir} ${stateClause}, and its removal was attempted but could NOT be verified ` +
`(${reasonOf(stillThere.error)})${removalNote}${pruneNote} — check ${active.worktreeDir} and remove it manually with ` +
"`git worktree remove --force` if it is still there.", removal, pruned),
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, ...pruneDetail },
};
}
return {
content: withOutcomeNote(`Exited the worktree session; working directory restored to ${restoredTo}${restoreNote}. ` +
`The worktree at ${active.worktreeDir} ${stateClause} and was removed.${removalNote}${pruneNote}${branchNote}`, removal.ok ? removal : undefined, pruned),
details: { type: "worktree", action: "exit", worktreeDir: active.worktreeDir, kept: false, ...pruneDetail },
};
}
return [enter, exit];
}