UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,077 lines • 64.8 kB
import { randomUUID } from "node:crypto";
import { types } from "node:util";
import { appendSessionCheckout, checkoutDeclarationClosed, readSessionCheckout } from "../engine/session/session.js";
import { sameOccupant } from "../engine/session/repo-utils.js";
import { isSensitiveRecordKey } from "@sema-agent/primitives";
import { branchLeftOf, managedAnchorOf, managedWorktreeBaseOf, managedWorktreeBranchOf, managedWorktreeDir, mintManagedWorktree, removeManagedWorktree, removeTreeIfClean, repositoryRootOf, resolveBaseCommit, shq, symlinkedLevel, WORKTREE_PARENT, worktreeNameProblem, } from "./git-worktree-env.js";
import { describeFault, receive } from "./mods/kernel/receive.js";
import { strayMembersOf } from "./own-property-receipt.js";
import { readMember, thrownText } from "./thrown-value.js";
import { outcomeFactOfThrown, withOutcomeNote } from "./exec-outcome.js";
import { redactThenCut } from "./untrusted-egress.js";
import { isAbsence } from "../tools/fs/shell-read-environment.js";
import { GIT_READ_ONLY as G } from "./git-read-only.js";
export const WORKTREE_INCAPABLE_REASONS = Object.freeze([
    "name_invalid",
    "git_unavailable",
    "not_a_repository",
    "bare_repository",
    "no_commit",
    "managed_parent_symlinked",
    "parent_not_writable",
    "name_in_use",
]);
export { readSessionCheckout } from "../engine/session/session.js";
const refusal = (code, message) => Object.assign(new Error(message), { code });
const invalid = (problem) => refusal("config.session_workspace_invalid", `TaskSpec.workspace ${problem}`);
const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
const LIST_MAX = 64;
const DECLARATION_MEMBERS = Object.freeze(["isolation", "baseRef", "name", "sources", "roots"]);
const SOURCE_MEMBERS = Object.freeze(["root", "remote", "sha", "ref"]);
const DECLARATION_DATA = Object.freeze({ accessors: "refuse", depth: 4, others: "refuse", isProxy: (v) => types.isProxy(v) });
const UNRESERVED_CHARACTER = /^[A-Za-z0-9\-._~]$/;
function canonicalEscapes(path) {
    return path.replace(/%([0-9A-Fa-f]{2})/g, (escape, hex) => {
        const character = String.fromCharCode(parseInt(hex, 16));
        return UNRESERVED_CHARACTER.test(character) ? character : escape.toUpperCase();
    });
}
function repositoryPathOf(host, path) {
    for (;;) {
        const bare = canonicalEscapes(path).replace(/\/{2,}/g, "/").replace(/\/+$/, "").replace(/\.git$/, "");
        const next = bare === "" ? "" : new URL(`https://${host}${bare}`).pathname;
        if (next === path)
            return path;
        path = next;
    }
}
function normalizeRemote(remote, at) {
    if (typeof remote !== "string" || remote.length === 0 || remote.length > 2048)
        throw invalid(`${at}.remote must be an https repository URL`);
    let url;
    try {
        url = new URL(remote);
    }
    catch {
        throw invalid(`${at}.remote is not a URL`);
    }
    if (url.protocol !== "https:")
        throw invalid(`${at}.remote must be an https URL (got a ${url.protocol.replace(/:$/, "")} URL)`);
    if (url.username !== "" || url.password !== "")
        throw invalid(`${at}.remote carries a user name or password (${url.origin}); credentials never ride the declaration`);
    const fragment = new URLSearchParams(url.hash.replace(/^#/, ""));
    for (const params of [url.searchParams, fragment]) {
        for (const name of params.keys()) {
            if (isSensitiveRecordKey(name))
                throw invalid(`${at}.remote carries a credential parameter (${url.origin}); credentials never ride the declaration`);
        }
    }
    const host = url.host.toLowerCase();
    const path = repositoryPathOf(host, url.pathname);
    if (path === "" || path === "/")
        throw invalid(`${at}.remote names no repository (${url.origin})`);
    return `https://${host}${path}`;
}
function screenRoot(root, at) {
    if (root === "taskRoot")
        return "taskRoot";
    if (root !== null && typeof root === "object" && !Array.isArray(root)) {
        const keys = Object.keys(root);
        const directory = root.directory;
        if (keys.length === 1 && keys[0] === "directory" && typeof directory === "string" && directory.startsWith("/"))
            return { directory };
    }
    throw invalid(`${at} must be "taskRoot" or { directory } naming an absolute additionalDirectories entry`);
}
const rootKey = (root) => (root === "taskRoot" ? "taskRoot" : `dir:${root.directory}`);
export function screenWorkspaceDeclaration(value) {
    if (value === undefined)
        return undefined;
    if (value === null || typeof value !== "object" || Array.isArray(value))
        throw invalid("must be an object");
    const data = receive(value, DECLARATION_DATA);
    if (!data.ok)
        throw invalid(`must be plain data — ${describeFault(data.fault)}`);
    const v = data.value;
    const stray = strayMembersOf(v, { subject: "TaskSpec.workspace", unit: "member", moment: "when the leg starts" }, DECLARATION_MEMBERS);
    if (stray !== undefined)
        throw refusal("config.session_workspace_invalid", stray.sentence);
    if (v.isolation !== undefined && v.isolation !== "worktree")
        throw invalid('.isolation must be "worktree"');
    if (v.baseRef !== undefined && v.baseRef !== "fresh" && v.baseRef !== "head")
        throw invalid('.baseRef must be "fresh" or "head"');
    if ((v.baseRef !== undefined || v.name !== undefined || v.roots !== undefined) && v.isolation === undefined)
        throw invalid('.baseRef, .name and .roots only apply with isolation: "worktree"');
    if (v.name !== undefined) {
        if (typeof v.name !== "string")
            throw invalid(".name must be a string");
        const problem = worktreeNameProblem(v.name);
        if (problem !== undefined)
            throw invalid(`.name: ${problem}`);
    }
    let roots;
    if (v.roots !== undefined) {
        if (!Array.isArray(v.roots) || v.roots.length === 0 || v.roots.length > LIST_MAX)
            throw invalid(`.roots must be a non-empty list of at most ${LIST_MAX} entries`);
        const seen = new Set();
        roots = v.roots.map((r, i) => {
            const root = screenRoot(r, `.roots[${i}]`);
            if (seen.has(rootKey(root)))
                throw invalid(`.roots[${i}] names a root the list already names`);
            seen.add(rootKey(root));
            return root;
        });
        if (roots.length === 1 && roots[0] === "taskRoot")
            roots = undefined;
    }
    let sources;
    if (v.sources !== undefined) {
        if (!Array.isArray(v.sources) || v.sources.length === 0 || v.sources.length > LIST_MAX)
            throw invalid(`.sources must be a non-empty list of at most ${LIST_MAX} entries`);
        sources = [];
        const seen = new Set();
        v.sources.forEach((s, i) => {
            const at = `.sources[${i}]`;
            if (s === null || typeof s !== "object" || Array.isArray(s))
                throw invalid(`${at} must be an object`);
            const entry = s;
            const straySource = strayMembersOf(entry, { subject: `TaskSpec.workspace${at}`, unit: "member", moment: "when the leg starts" }, SOURCE_MEMBERS);
            if (straySource !== undefined)
                throw refusal("config.session_workspace_invalid", straySource.sentence);
            const root = screenRoot(entry.root, `${at}.root`);
            if (seen.has(rootKey(root)))
                throw invalid(`${at}.root names a root another source already names`);
            seen.add(rootKey(root));
            const remote = normalizeRemote(entry.remote, at);
            if (typeof entry.sha !== "string" || !FULL_SHA.test(entry.sha))
                throw invalid(`${at}.sha must be a full commit id (40 or 64 lowercase hex characters)`);
            if (entry.ref !== undefined && (typeof entry.ref !== "string" || entry.ref.length === 0 || entry.ref.length > 256))
                throw invalid(`${at}.ref must be a non-empty label of at most 256 characters`);
            sources.push({ root, remote, sha: entry.sha, ...(entry.ref !== undefined ? { ref: entry.ref } : {}) });
        });
    }
    if (v.isolation === undefined && sources === undefined)
        throw invalid('declares nothing (give isolation: "worktree", sources, or both)');
    return {
        ...(v.isolation !== undefined ? { isolation: "worktree" } : {}),
        ...(v.baseRef !== undefined ? { baseRef: v.baseRef } : {}),
        ...(v.name !== undefined ? { name: v.name } : {}),
        ...(roots !== undefined ? { roots } : {}),
        ...(sources !== undefined ? { sources } : {}),
    };
}
const declaredDigest = (d) => JSON.stringify([d.isolation ?? null, d.baseRef ?? null, d.name ?? null, (d.sources ?? []).map((s) => [rootKey(s.root), s.remote, s.sha, s.ref ?? null]), ...(d.roots !== undefined ? [d.roots.map(rootKey)] : [])]);
const listedRootsOf = (d) => (d.isolation === undefined ? [] : d.roots ?? ["taskRoot"]);
function legWorkspaceOf(raw) {
    if (raw === null)
        return { kind: "none" };
    const declared = screenWorkspaceDeclaration(raw);
    return declared === undefined ? { kind: "inherit" } : { kind: "declared", declared };
}
export function workspaceDeclared(raw) {
    return legWorkspaceOf(raw).kind === "declared";
}
export function checkoutRecordNeedsEnv(read, raw) {
    if (read.kind === "unreadable")
        return undefined;
    if (read.kind === "stands")
        return legWorkspaceOf(raw).kind !== "none";
    return read.kind === "record" && read.record.released !== true && legWorkspaceOf(raw).kind !== "none";
}
export async function readLegCheckout(session, sessionId, declaration) {
    if (workspaceDeclared(declaration))
        return { needsEnv: undefined };
    const read = await readSessionCheckout(session, sessionId);
    return { read, needsEnv: checkoutRecordNeedsEnv(read, declaration) };
}
const unreadStand = (sessionId, detail, session) => ({ session, sessionId, read: { kind: "unreadable", detail }, needsEnv: undefined });
export async function readRecordedStand(sessions, stand, declaration) {
    const id = stand.standsIn;
    let session;
    try {
        session = (await sessions.acquire(id, { requireExisting: true })).session;
    }
    catch (err) {
        return unreadStand(id, readMember(err, "code") === "not_found" ? `this session stands in the checkout of session ${id}, which the store no longer holds` : `the session ${id} whose checkout this session stands in cannot be opened (${thrownText(err)})`);
    }
    const read = await readSessionCheckout(session, id);
    if (read.kind === "unreadable")
        return unreadStand(id, `the checkout of session ${id}, which this session stands in, cannot be read (${read.detail})`, session);
    if (read.kind === "stands")
        return unreadStand(id, `this session stands in the checkout of session ${id}, which itself stands in another session's: a stand names the session that holds the tree`, session);
    if (read.kind === "none")
        return unreadStand(id, `this session stands in the checkout of session ${id}, which holds none`, session);
    if (!recordHoldsTree(read.record))
        return unreadStand(id, `this session stands in the checkout of session ${id}, whose record isolates no tree (a stand is a tree's)`, session);
    if (read.record.allocationId !== stand.allocationId)
        return unreadStand(id, `this session stands in allocation ${stand.allocationId} of session ${id}, whose checkout is allocation ${read.record.allocationId} (the id names another occupant)`, session);
    return { session, sessionId: id, read, needsEnv: checkoutRecordNeedsEnv(read, declaration) };
}
export async function readStandingCheckout(sessions, workSession, ownSessionId, declaration) {
    if (workSession === undefined || workSession === "" || workSession === ownSessionId)
        return undefined;
    const leg = legWorkspaceOf(declaration);
    if (leg.kind === "none")
        return undefined;
    let session;
    try {
        session = (await sessions.acquire(workSession, { requireExisting: true })).session;
    }
    catch (err) {
        if (readMember(err, "code") === "not_found")
            return undefined;
        return { session: undefined, sessionId: workSession, read: { kind: "unreadable", detail: `the session ${workSession} whose tree this leg stands in cannot be opened (${thrownText(err)})` }, needsEnv: undefined };
    }
    const read = await readSessionCheckout(session, workSession);
    if (read.kind === "none")
        return undefined;
    const held = read.kind === "stands" ? await readRecordedStand(sessions, read, declaration) : { session, sessionId: workSession, read, needsEnv: checkoutRecordNeedsEnv(read, declaration) };
    if (held.read.kind === "record" && leg.kind === "declared" && declaredDigest(leg.declared) !== declaredDigest(held.read.record.declared))
        return undefined;
    return held;
}
export async function ensureStand(session, sessionId, standing) {
    if (standing.read.kind !== "record")
        return;
    const holdsTree = recordHoldsTree(standing.read.record);
    const stand = { allocationId: standing.read.record.allocationId, sessionId, standsIn: standing.sessionId };
    const observedLeaf = await session.getStorage().getLeafId();
    const own = await readSessionCheckout(session, sessionId);
    if (own.kind === "stands") {
        if (holdsTree && own.standsIn === stand.standsIn && own.allocationId === stand.allocationId)
            return;
        throw refusal("config.session_workspace_changed", `This session stands in the checkout of session ${own.standsIn} (allocation ${own.allocationId}); a session's legs stand in one place, and this leg stands ${holdsTree ? `in session ${stand.standsIn}'s` : `where session ${stand.standsIn}'s legs stand, which isolates no tree (the base checkout)`}. The leg was not started.`);
    }
    if (!holdsTree)
        return;
    if (own.kind !== "none") {
        throw refusal("workspace.checkout_unavailable", own.kind === "record" ? "This session holds a checkout of its own and cannot also stand in another session's; the leg was not started." : `This session's checkout record cannot be read (${own.detail}); the leg was not started rather than record a stand beside it.`);
    }
    try {
        await appendSessionCheckout(session, stand, observedLeaf);
    }
    catch (err) {
        throw refusal("workspace.checkout_unavailable", `This session's stand in the checkout of session ${stand.standsIn} could not be recorded (${redactThenCut(thrownText(err), 300)}); the leg was not started.`);
    }
}
export async function recordsStand(sessions, sessionId) {
    let session;
    try {
        session = (await sessions.acquire(sessionId, { requireExisting: true })).session;
    }
    catch (err) {
        return readMember(err, "code") !== "not_found";
    }
    const read = await readSessionCheckout(session, sessionId);
    return read.kind === "stands" || read.kind === "unreadable" || (read.kind === "none" && read.window !== undefined);
}
function withEntries(list, extra) {
    if (list !== undefined && stringListOf(list) === undefined)
        return list;
    const own = stringListOf(list) ?? [];
    const added = extra.filter((entry) => !own.includes(entry));
    return list === undefined && added.length === 0 ? undefined : [...own, ...added];
}
export async function openStandingCheckout(standing, input) {
    const { ownSession, spec, judges, ...open } = input;
    const listed = judges === true && standing.read.kind === "record" ? listedRootsOf(standing.read.record.declared).flatMap((root) => (root === "taskRoot" ? [] : [root.directory])) : [];
    const opened = await openSessionCheckout({
        ...open,
        session: standing.session ?? ownSession,
        sessionId: standing.sessionId,
        read: standing.read,
        declaration: spec.workspace,
        additionalDirectories: spec.additionalDirectories,
        additionalReadDirectories: withEntries(spec.additionalReadDirectories, listed),
    });
    for (const dir of listed) {
        if (opened.directories?.find((d) => d.declared === dir)?.tree === undefined) {
            throw refusal("config.session_workspace_changed", `This session's checkout isolates ${dir}, but that directory no longer stands in a repository the session's trees were minted from (or cannot be placed in them); the leg that stands where the session stands was not started.`);
        }
    }
    const { record: _record, ...own } = opened;
    return own;
}
async function run(env, command, cwd) {
    try {
        const r = await env.exec(command, { cwd });
        return r.ok ? r.value : undefined;
    }
    catch {
        return undefined;
    }
}
function sessionTreeName(sessionId) {
    const slug = sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
    return slug === "" ? "session" : slug;
}
export async function probeWorktreeCapability(env, cwd, opts) {
    const no = (reason, detail, gitRoot) => ({ worktreeCapable: false, reason, detail, ...(gitRoot !== undefined ? { gitRoot } : {}) });
    if (opts?.name !== undefined) {
        const problem = worktreeNameProblem(opts.name);
        if (problem !== undefined)
            return no("name_invalid", problem);
    }
    const version = await run(env, `${G} --version`, cwd);
    if (version === undefined || version.exitCode !== 0)
        return no("git_unavailable", "git cannot be run in this environment");
    const bare = await run(env, `${G} rev-parse --is-bare-repository`, cwd);
    if (bare === undefined || bare.exitCode !== 0)
        return no("not_a_repository", `${cwd} is not inside a git repository`);
    if (bare.stdout.trim() === "true")
        return no("bare_repository", `${cwd} is a bare repository (it has no working tree to branch from)`);
    const inside = await run(env, `${G} rev-parse --is-inside-work-tree`, cwd);
    if (inside === undefined || inside.exitCode !== 0 || inside.stdout.trim() !== "true")
        return no("not_a_repository", `${cwd} is not inside a git work tree`);
    const head = await run(env, `${G} rev-parse --verify --quiet 'HEAD^{commit}'`, cwd);
    if (head === undefined || head.exitCode !== 0)
        return no("no_commit", `the repository at ${cwd} has no commit yet`);
    const gitRoot = await managedAnchorOf(env, cwd);
    const leaf = opts?.name !== undefined ? managedWorktreeDir(gitRoot, opts.name) : `${gitRoot}/${WORKTREE_PARENT}`;
    const symlinked = await symlinkedLevel(env, gitRoot, leaf);
    if (symlinked !== undefined)
        return no("managed_parent_symlinked", symlinked, gitRoot);
    let writable = gitRoot;
    for (const level of [`${gitRoot}/${WORKTREE_PARENT}`, `${gitRoot}/.sema`]) {
        const info = await env.fileInfo(level);
        if (info.ok) {
            writable = level;
            break;
        }
    }
    const canWrite = await run(env, `test -w ${shq(writable)}`, cwd);
    if (canWrite === undefined || canWrite.exitCode !== 0)
        return no("parent_not_writable", `${writable} cannot be written`, gitRoot);
    if (opts?.name !== undefined) {
        const dir = managedWorktreeDir(gitRoot, opts.name);
        const at = await env.fileInfo(dir);
        if (at.ok || at.error.code !== "not_found")
            return no("name_in_use", `a tree named "${opts.name}" already exists at ${dir}`, gitRoot);
        const branch = managedWorktreeBranchOf(dir);
        const ref = branch === undefined ? undefined : await run(env, `${G} rev-parse --verify --quiet ${shq(`refs/heads/${branch}`)}`, gitRoot);
        if (ref !== undefined && ref.exitCode === 0)
            return no("name_in_use", `the branch ${branch} already exists`, gitRoot);
    }
    return { worktreeCapable: true, gitRoot };
}
async function birthRecordPath(env, dir) {
    const gitDir = await run(env, `${G} rev-parse --absolute-git-dir`, dir);
    return gitDir !== undefined && gitDir.exitCode === 0 && gitDir.stdout.trim().startsWith("/") ? `${gitDir.stdout.trim()}/sema-allocation` : undefined;
}
async function readBirthMark(env, dir) {
    const unreadable = (detail) => ({ kind: "unreadable", detail });
    const own = await env.canonicalPath(dir);
    const top = await checkoutTopOf(env, dir);
    if (!own.ok || top === undefined)
        return unreadable(`git cannot say which checkout ${dir} is`);
    if (top !== own.value)
        return { kind: "absent" };
    const at = await birthRecordPath(env, dir);
    if (at === undefined)
        return unreadable(`git does not name the private directory of ${dir}`);
    const text = await env.readTextFile(at);
    if (!text.ok)
        return text.error.code === "not_found" ? { kind: "absent" } : unreadable(`its allocation mark cannot be read (${redactThenCut(thrownText(text.error), 200)})`);
    try {
        const v = JSON.parse(text.value);
        const occupant = v.incarnation === undefined || (typeof v.incarnation === "string" && v.incarnation !== "");
        if (occupant && typeof v.allocationId === "string" && typeof v.sessionId === "string" && typeof v.baseSha === "string" && FULL_SHA.test(v.baseSha) && typeof v.declared === "string") {
            const incarnation = typeof v.incarnation === "string" ? { incarnation: v.incarnation } : {};
            return { kind: "marked", mark: { allocationId: v.allocationId, sessionId: v.sessionId, ...incarnation, baseSha: v.baseSha, declared: v.declared } };
        }
    }
    catch {
    }
    return unreadable("its allocation mark is not a valid record");
}
const recordHoldsMark = (holder, mark) => holder.allocationId === mark.allocationId && sameOccupant(mark.incarnation, holder.occupant);
async function sessionRowOf(session, unread) {
    try {
        return await session.getMetadata();
    }
    catch (err) {
        throw refusal("workspace.checkout_unavailable", `This session's row cannot be read (${redactThenCut(thrownText(err), 300)}), so whose session tree is whose cannot be told; ${unread}`);
    }
}
const holds = (path, top) => path === top || top.startsWith(`${path === "/" ? "" : path}/`);
const inside = (path, top) => path.startsWith(`${top === "/" ? "" : top}/`);
const canonicalOf = async (env, path) => {
    const r = await env.canonicalPath(path);
    return r.ok ? r.value : path;
};
async function checkoutTopOf(env, dir) {
    const top = await run(env, `${G} rev-parse --show-toplevel`, dir);
    return top !== undefined && top.exitCode === 0 && top.stdout.trim().startsWith("/") ? canonicalOf(env, top.stdout.trim()) : undefined;
}
async function rootPlaceRead(env, root) {
    try {
        const own = await env.canonicalPath(root);
        if (!own.ok)
            return isAbsence(own.error.code) ? { none: true } : { unread: `${root} cannot be resolved (${own.error.code})` };
        const answer = await run(env, `${G} rev-parse --show-toplevel --git-common-dir`, own.value);
        if (answer === undefined)
            return { unread: `git could not be run at ${own.value}` };
        if (answer.exitCode !== 0)
            return (await gitEntryAtOrAbove(env, own.value)) ? { unread: `git exited ${answer.exitCode} at ${own.value}, below a .git entry` } : { none: true };
        const [topSpelled, commonSpelled] = answer.stdout.split("\n").map((line) => line.trim());
        const malformed = { unread: `git's answer at ${own.value} is not a checkout top and a common directory` };
        if (topSpelled === undefined || !topSpelled.startsWith("/") || commonSpelled === undefined || commonSpelled === "")
            return malformed;
        const top = await env.canonicalPath(topSpelled);
        const common = await env.canonicalPath(commonSpelled.startsWith("/") ? commonSpelled : `${own.value}/${commonSpelled}`);
        if (!top.ok || !common.ok || !(own.value === top.value || own.value.startsWith(`${top.value}/`)))
            return malformed;
        return { place: { canonical: own.value, top: top.value, repository: common.value } };
    }
    catch (err) {
        return { unread: `reading where ${root} stands threw (${thrownText(err)})` };
    }
}
async function gitEntryAtOrAbove(env, dir) {
    for (let at = dir;; at = at.slice(0, at.lastIndexOf("/")) || "/") {
        const info = await env.fileInfo(`${at === "/" ? "" : at}/.git`);
        if (info.ok || !isAbsence(info.error.code))
            return true;
        if (at === "/")
            return false;
    }
}
async function rootPlaceOf(env, root) {
    const read = await rootPlaceRead(env, root);
    return "place" in read ? read.place : undefined;
}
const stringListOf = (value) => (Array.isArray(value) && value.every((v) => typeof v === "string") ? value : undefined);
const treeOf = (root, trees) => (root.place === undefined ? undefined : trees.find((tree) => tree.repository === root.place.repository));
function effectiveOf(root, trees) {
    const tree = treeOf(root, trees);
    return tree === undefined ? root.declared : `${tree.dir}${root.place.canonical.slice(root.place.top.length)}`;
}
function unplacedLeg(input) {
    const bare = (value) => stringListOf(value)?.map((declared) => ({ declared }));
    return { taskRoot: { declared: input.baseRoot }, write: bare(input.additionalDirectories), read: bare(input.additionalReadDirectories) };
}
async function declaredPlaceOf(env, declared, role) {
    const read = await rootPlaceRead(env, declared);
    if ("unread" in read)
        throw refusal("workspace.checkout_unavailable", `Where this leg's ${role} ${declared} stands in git cannot be read (${read.unread}), so it is not placed in or outside the session's trees; the leg was not started.`);
    return "place" in read ? read.place : undefined;
}
const roleOf = (root) => (root === "taskRoot" ? "task root" : "additionalDirectories entry");
async function placeLeg(env, trees, input) {
    if (trees.length === 0)
        return unplacedLeg(input);
    const placed = async (declared, role) => {
        if (declared.trim() === "")
            return { declared };
        const place = await declaredPlaceOf(env, declared, role);
        return place === undefined ? { declared } : { declared, place };
    };
    const list = async (value, role) => {
        const entries = stringListOf(value);
        if (entries === undefined)
            return undefined;
        const out = [];
        for (const entry of entries)
            out.push(await placed(entry, role));
        return out;
    };
    return { taskRoot: await placed(input.baseRoot, "task root"), write: await list(input.additionalDirectories, "additionalDirectories entry"), read: await list(input.additionalReadDirectories, "additionalReadDirectories entry") };
}
async function refuseExposedBase(env, trees, leg) {
    if (trees.length === 0)
        return;
    const writable = [leg.taskRoot, ...(leg.write ?? [])];
    const isolatedTops = new Set();
    for (const tree of trees)
        isolatedTops.add(await canonicalOf(env, tree.anchor));
    for (const root of writable)
        if (treeOf(root, trees) !== undefined)
            isolatedTops.add(root.place.top);
    for (const root of writable) {
        if (root.declared.trim() === "" || treeOf(root, trees) !== undefined)
            continue;
        const at = root.place?.canonical ?? (await canonicalOf(env, root.declared));
        for (const top of isolatedTops) {
            const which = root === leg.taskRoot ? `the task root ${root.declared}` : `additionalDirectories entry ${root.declared}`;
            if (holds(at, top)) {
                throw invalid(`isolates the checkout ${top}, but ${which} is in none of the session's trees and holds that checkout — writes there would land in the base checkout. Start from inside the isolated repository, drop that directory, or work without isolation.`);
            }
            if (root.place === undefined && inside(at, top)) {
                throw invalid(`isolates the checkout ${top}, but ${which} lies inside it and git places it in no repository (it does not exist yet), so it cannot be placed in the session's tree — writes there could land in the base checkout. Drop that directory, or work without isolation.`);
            }
        }
    }
}
const standingNamed = (label, root) => `${label} ${root.declared} (checkout ${root.place.top})`;
async function refuseSplitCheckout(env, trees, leg) {
    const own = new Set();
    for (const tree of trees)
        own.add(await canonicalOf(env, tree.dir));
    const named = [{ label: "the task root", root: leg.taskRoot }];
    for (const root of leg.write ?? [])
        named.push({ label: "additionalDirectories entry", root });
    for (const root of leg.read ?? [])
        named.push({ label: "additionalReadDirectories entry", root });
    const first = new Map();
    for (const { label, root } of named) {
        if (root.place === undefined || treeOf(root, trees) === undefined || own.has(root.place.top))
            continue;
        const seen = first.get(root.place.repository);
        if (seen === undefined) {
            first.set(root.place.repository, { label, root });
            continue;
        }
        if (seen.root.place.top === root.place.top)
            continue;
        throw refusal("workspace.isolation_unavailable", `The session's tree cannot hold both: ${standingNamed(seen.label, seen.root)} and ${standingNamed(label, root)} are two checkouts of one repository (${root.place.repository}), and one tree cannot stand in for both — the second root would be placed in a tree that is not its checkout. Declare the roots of one checkout, or work without isolation. The leg was not started.`);
    }
}
async function resolvedIn(env, root, trees) {
    const effective = effectiveOf(root, trees);
    const at = await env.canonicalPath(effective);
    if (!at.ok)
        return undefined;
    const tree = treeOf(root, trees);
    if (tree !== undefined) {
        const dir = await canonicalOf(env, tree.dir);
        if (at.value !== dir && !inside(at.value, dir))
            throw invalid(`places ${root.declared} at ${effective} in the session's tree ${tree.dir}, but that path resolves outside the tree (${at.value}) — a link in the tree leads it out. Drop that root, or work without isolation.`);
    }
    return at.value;
}
const reportedRootsOf = (leg) => [[leg.write, "write"], [leg.read, "read"]].flatMap(([list, access]) => (list ?? []).filter((root) => root.declared.trim() !== "").map((root) => ({ root, access })));
async function directoriesIn(env, trees, reported) {
    const directories = [];
    for (const { root, access } of reported) {
        const at = await resolvedIn(env, root, trees);
        if (at === undefined)
            continue;
        const tree = treeOf(root, trees);
        directories.push({ declared: root.declared, at, access, ...(tree !== undefined ? { tree: tree.dir } : {}) });
    }
    return directories;
}
const mappedRoots = (trees, leg) => ({
    taskRoot: effectiveOf(leg.taskRoot, trees),
    ...(leg.write !== undefined ? { additionalDirectories: leg.write.map((root) => effectiveOf(root, trees)) } : {}),
    ...(leg.read !== undefined ? { additionalReadDirectories: leg.read.map((root) => effectiveOf(root, trees)) } : {}),
});
const withDirectories = (roots, directories) => (directories.length > 0 ? { ...roots, directories } : roots);
async function rootsInSession(env, trees, leg) {
    await resolvedIn(env, leg.taskRoot, trees);
    return withDirectories(mappedRoots(trees, leg), await directoriesIn(env, trees, reportedRootsOf(leg)));
}
const rootNamed = (root, location) => (root === "taskRoot" ? `the task root ${location}` : `the additional directory ${location}`);
export async function sessionRootOf(input, refusedAs) {
    try {
        return (await openSessionCheckout({ ...legless(input), session: input.session, sessionId: input.sessionId, ...(input.sessions !== undefined ? { sessions: input.sessions } : {}) })).taskRoot;
    }
    catch (err) {
        throw keyedRefusal(err, refusedAs);
    }
}
const legless = (input) => ({ env: input.env, declaration: undefined, baseRoot: input.baseRoot, additionalDirectories: undefined, additionalReadDirectories: undefined });
const keyedRefusal = (err, refusedAs) => {
    const code = readMember(err, "code");
    return refusal(typeof code === "string" && code !== "" ? code : "workspace.checkout_unavailable", `${refusedAs} The checkout's answer: ${thrownText(err)}`);
};
export async function recordedRootOf(input, source) {
    const read = await readSessionCheckout(input.session, source);
    const keyedAtBase = read.kind === "none" ? read.window === undefined : read.kind === "record" && !recordHoldsTree(read.record);
    return keyedAtBase ? input.baseRoot : undefined;
}
export async function forkHasOwnTree(session, sessionId, forkedFrom) {
    if (forkedFrom === undefined)
        return false;
    const read = await readSessionCheckout(session, sessionId);
    if (read.kind === "unreadable") {
        throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}), so whether this fork works in a tree of its own is not known; nothing was rewound and no file history was recorded.`);
    }
    return read.kind === "stands" || (read.kind === "record" && recordHoldsTree(read.record));
}
const recordHoldsTree = (record) => record.checkouts.some((cell) => cell.dir !== undefined);
export function withEffectiveDirectories(spec, opened) {
    return {
        ...spec,
        ...(opened.additionalDirectories !== undefined ? { additionalDirectories: [...opened.additionalDirectories] } : {}),
        ...(opened.additionalReadDirectories !== undefined ? { additionalReadDirectories: [...opened.additionalReadDirectories] } : {}),
    };
}
export async function openSessionCheckout(input) {
    const { session, sessionId } = input;
    const leg = legWorkspaceOf(input.declaration);
    const observedLeaf = leg.kind === "declared" ? await session.getStorage().getLeafId() : null;
    const read = input.read ?? (await readSessionCheckout(session, sessionId));
    if (read.kind === "unreadable") {
        throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}); the leg was not started rather than run outside the session's checkout.`);
    }
    if (read.kind === "record")
        return reopen(input, leg, read.record);
    if (read.kind === "stands") {
        if (input.sessions === undefined) {
            throw refusal("workspace.checkout_unavailable", `This session stands in the checkout of session ${read.standsIn} and the session store that holds it was not handed here; the leg was not started rather than run outside the session's checkout.`);
        }
        return openStandingCheckout(await readRecordedStand(input.sessions, read, input.declaration), {
            env: input.env,
            baseRoot: input.baseRoot,
            ...(input.restoredCwd !== undefined ? { restoredCwd: input.restoredCwd } : {}),
            ownSession: session,
            ...(input.judges === true ? { judges: true } : {}),
            spec: { workspace: input.declaration, additionalDirectories: input.additionalDirectories, additionalReadDirectories: input.additionalReadDirectories },
        });
    }
    if (leg.kind !== "declared")
        return inPlace(input, atRoot(input.baseRoot));
    const declared = leg.declared;
    if (await checkoutDeclarationClosed(session.getStorage(), await session.getMetadata())) {
        throw refusal("config.session_workspace_changed", "TaskSpec.workspace is declared on a session that already began without it (its log holds a turn or a compaction); a session's workspace is fixed at its birth. Start a new session to work in a declared workspace.");
    }
    return allocate(input, declared, observedLeaf);
}
function inPlace(input, sessionRoot) {
    const leg = unplacedLeg(input);
    const roots = { ...mappedRoots([], leg), sessionRoot };
    const reported = reportedRootsOf(leg);
    return reported.length === 0 ? roots : directoriesIn(input.env, [], reported).then((directories) => ({ ...withDirectories(roots, directories), sessionRoot }));
}
const atRoot = (root) => () => Promise.resolve({ root });
async function treeHoldingCwd(env, cwd, record) {
    const where = await canonicalOf(env, cwd);
    for (const cell of record.checkouts) {
        if (cell.dir === undefined)
            continue;
        const tree = await canonicalOf(env, cell.dir);
        if (where === tree || where.startsWith(`${tree}/`))
            return cell.dir;
    }
    return undefined;
}
async function reopen(input, leg, record) {
    const env = input.env;
    if (record.released === true) {
        throw refusal("config.session_workspace_changed", "This session's checkout was released; a released session runs no further leg. Start a new session.");
    }
    if (leg.kind === "none") {
        const standing = input.restoredCwd === undefined ? undefined : await treeHoldingCwd(env, input.restoredCwd, record);
        if (standing !== undefined) {
            throw refusal("config.session_workspace_changed", `TaskSpec.workspace is null on a resumed leg whose pending action stands in the session's tree ${standing} (the checkpoint's working directory); it would run there while the leg reports no checkout. Resume it with the session's workspace (omit it, or send the declaration); send null on a leg that starts fresh.`);
        }
        return inPlace(input, () => nullLegRootOf(input, record));
    }
    if (leg.kind === "declared" && declaredDigest(leg.declared) !== declaredDigest(record.declared)) {
        throw refusal("config.session_workspace_changed", `TaskSpec.workspace differs from the declaration this session's checkout was opened under (allocation ${record.allocationId}); a session's workspace is fixed by its first leg. Omit it (the leg takes the session's), send the same declaration, send null for a leg that wants no tree, or start a new session.`);
    }
    const roots = await placedInSession(input, record, await sessionTreesOf(input, record));
    return { ...roots, record, sessionRoot: atRoot(roots.taskRoot) };
}
async function sessionTreesOf(input, record) {
    const env = input.env;
    const holder = recordHoldsTree(record) ? { allocationId: record.allocationId, occupant: (await sessionRowOf(input.session, "the leg was not started.")).incarnation } : undefined;
    const trees = [];
    for (const cell of record.checkouts) {
        if (cell.dir === undefined)
            continue;
        const info = await env.fileInfo(cell.dir);
        if (!info.ok) {
            if (info.error.code === "not_found") {
                throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} no longer exists; the leg was not started (it is never run in the base checkout instead). Release the session's checkout (releaseSessionCheckout) and start a new session.`);
            }
            throw refusal("workspace.checkout_unavailable", `This session's tree ${cell.dir} cannot be read (${thrownText(info.error)}); the leg was not started.`);
        }
        if (info.value.kind !== "directory")
            throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer a directory; the leg was not started.`);
        const birth = await readBirthMark(env, cell.dir);
        if (birth.kind !== "marked" || holder === undefined || !recordHoldsMark(holder, birth.mark)) {
            throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer the tree this session minted (its allocation mark is missing, or names another allocation or another occupant of this session id); the leg was not started. Release the session's checkout and start a new session.`);
        }
        const tree = await sessionTreeAt(env, cell.dir, cell.repository);
        if (tree === undefined)
            throw refusal("workspace.checkout_unavailable", `Which repository this session's tree ${cell.dir} belongs to cannot be read; the leg was not started.`);
        trees.push(tree);
    }
    return trees;
}
async function sessionTreeAt(env, dir, anchor) {
    const place = await rootPlaceOf(env, dir);
    return place === undefined ? undefined : { repository: place.repository, dir, anchor };
}
async function placedInSession(input, record, trees) {
    const env = input.env;
    const placed = await placeLeg(env, trees, input);
    for (const listed of listedRootsOf(record.declared)) {
        const root = listed === "taskRoot" ? placed.taskRoot : placed.write?.find((entry) => entry.declared === listed.directory);
        if (root !== undefined && treeOf(root, trees) === undefined) {
            throw refusal("config.session_workspace_changed", `This leg's ${rootNamed(listed, root.declared)} is not in a repository this session's trees were minted from (${record.checkouts.flatMap((cell) => (cell.dir === undefined ? [] : [cell.repository])).join(", ")}).`);
        }
    }
    await refuseExposedBase(env, trees, placed);
    await refuseSplitCheckout(env, trees, placed);
    return rootsInSession(env, trees, placed);
}
async function nullLegRootOf(input, record) {
    const lead = `TaskSpec.workspace is null on a leg of session "${input.sessionId}"`;
    const unkeyed = "A leg that records no file history (TaskSpec.fileHistory: \"disabled\", or capture off), or that mounts no tool that can change a file, does not need it.";
    const unread = (refused, why) => {
        if (input.writes !== false)
            throw refused;
        return { outside: { notice: `file history is not live for this leg — ${lead}, ${why}, and the leg mounts no tool that can change a file, so it runs and records no file history: no rewind restores anything it did.`, refusal: refused } };
    };
    let trees;
    try {
        trees = await sessionTreesOf(input, record);
    }
    catch (err) {
        return unread(keyedRefusal(err, `${lead}, whose file history is keyed to the session's own checkout, and that checkout cannot be resolved — this leg's edits could not be recorded where the session's rewinds read them back, so the leg was not started. ${unkeyed}`), `whose session's checkout cannot be resolved (${thrownText(err)})`);
    }
    let keyed;
    try {
        const leg = await placeLeg(input.env, trees, legless(input));
        if (trees.length === 0 || treeOf(leg.taskRoot, trees) !== undefined)
            keyed = (await rootsInSession(input.env, trees, leg)).taskRoot;
    }
    catch (err) {
        return unread(keyedRefusal(err, `${lead}: where its file history is keyed cannot be read, so the leg was not started. ${unkeyed}`), `where its file history is keyed cannot be read (${thrownText(err)})`);
    }
    if (keyed !== undefined)
        return { root: keyed };
    const where = `${lead} whose root ${input.baseRoot} stands outside the session's checkout, so this leg records no file history`;
    const named = `The session's trees: ${trees.map((tree) => tree.dir).join(", ")}.`;
    return {
        outside: {
            notice: `file history is not live for this leg — ${where}: its edits are not in the session's history and no rewind restores them. ${named}`,
            refusal: refusal("config.session_workspace_changed", `${where} and cannot rewind the session's files; the leg was not started. Send the rewind on a leg that omits TaskSpec.workspace, or through Runner.rewindFiles. ${named}`),
        },
    };
}
async function allocate(input, declared, observedLeaf) {
    const { env, sessionId, baseRoot } = input;
    const additional = stringListOf(input.additionalDirectories) ?? [];
    const locationOf = (root, what) => {
        if (root === "taskRoot")
            return baseRoot;
        if (!additional.includes(root.directory))
            throw invalid(`${what} root ${root.directory} is not an additionalDirectories entry (the same spelling is required)`);
        return root.directory;
    };
    const isolated = [];
    for (const root of listedRootsOf(declared)) {
        const location = locationOf(root, "listed");
        const probe = await probeWorktreeCapability(env, location);
        if (!probe.worktreeCapable || probe.gitRoot === undefined) {
            throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(root, location)}: ${probe.detail ?? "the checkout cannot hold a managed tree"} (${probe.reason ?? "unknown"}). No tree was made and the leg was not started in the base checkout instead.`);
        }
        const place = await declaredPlaceOf(env, location, roleOf(root));
        if (place === undefined)
            throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(root, location)}: git places it in no repository. No tree was made.`);
        if (!isolated.some((r) => r.repository === place.repository))
            isolated.push({ repository: place.repository, anchor: probe.gitRoot, root, location });
    }
    const sourceCells = [];
    const sourced = new Set();
    for (const source of declared.sources ?? []) {
        const location = locationOf(source.root, "source");
        const place = await declaredPlaceOf(env, location, roleOf(source.root));
        const repository = await repositoryRootOf(env, location);
        if (repository === undefined || place === undefined)
            throw refusal("workspace.source_mismatch", `The declared source for ${location} names a repository, but ${location} is not in a git checkout.`);
        if (sourced.has(place.repository))
            throw invalid(`declares two sources for the repository at ${repository} (one source per repository)`);
        sourced.add(place.repository);
        const tree = isolated.find((r) => r.repository === place.repository);
        if (tree !== undefined) {
            tree.source = source;
            continue;
        }
        const head = await run(env, `${G} rev-parse --verify --quiet 'HEAD^{commit}'`, place.top);
        if (head === undefined || head.exitCode !== 0 || head.stdout.trim() !== source.sha) {
            throw refusal("workspace.source_mismatch", `The checkout at ${place.top} is not at the declared commit ${source.sha} (it is at ${head?.exitCode === 0 ? head.stdout.trim() : "an unreadable HEAD"}); the leg was not started.`);
        }
        sourceCells.push({ repository, root: source.root, baseSha: source.sha, source: { remote: source.remote, sha: source.sha, ...(source.ref !== undefined ? { ref: source.ref } : {}) } });
    }
    if (declared.baseRef !== undefined && isolated.length > 0 && isolated.every((r) => r.source !== undefined)) {
        throw invalid(".baseRef starts no tree: every isolated repository starts at its declared source; drop .baseRef");
    }
    const name = declared.name ?? sessionTreeName(sessionId);
    const planned = isolated.map((r) => ({ repository: r.repository, anchor: r.anchor, dir: managedWorktreeDir(r.anchor, name) }));
    const placed = await placeLeg(env, planned, input);
    await refuseExposedBase(env, planned, placed);
    await refuseSplitCheckout(env, planned, placed);
    const occupant = isolated.length === 0 ? undefined : (await sessionRowOf(input.session, "the leg was not started.")).incarnation;
    const plans = [];
    for (const repo of isolated) {
        const dir = managedWorktreeDir(repo.anchor, name);
        const existing = await env.fileInfo(dir);
        if (existing.ok || existing.error.code !== "not_found") {
            const read = await readBirthMark(env, dir);
            const birth = read.kind === "marked" ? read.mark : undefined;
            if (birth === undefined || birth.sessionId !== sessionId || !sameOccupant(birth.incarnation, occupant)) {
                throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: a tree named "${name}" already exists at ${dir} and was not minted by this session (name_in_use). Declare another name — or, when no session's record holds that tree, release it with releaseOrphanSessionTree (listOrphanSessionTrees lists such trees).`);
            }
            if (birth.declared !== declaredDigest(declared)) {
                const atOtherCommit = repo.source !== undefined && birth.baseSha !== repo.source.sha;
                throw refusal(atOtherCommit ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: the tree this session minted earlier at ${dir} was minted under another declaration${atOtherCommit ? ` (it starts at ${birth.baseSha}, not at the declared commit ${repo.source.sha})` : ""} (name_in_use). Declare what it was minted under, or another name.`);
            }
            plans.push({ repo, dir, taken: { branch: managedWorktreeBranchOf(dir) ?? `sema/${name}`, baseSha: birth.baseSha, allocationId: birth.allocationId } });
            continue;
        }
        const named = await probeWorktreeCapability(env, repo.location, { name });
        if (!named.worktreeCapable) {
            throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: ${named.detail ?? "the name is taken"} (${named.reason ?? "unknown"}). Declare another name.`);
        }
        let commit;
        if (repo.source !== undefined)
            commit = repo.source.sha;
        else {
            const base = await resolveBaseCommit(env, repo.location, declared.baseRef ?? "fresh", undefined);
            if ("error" in base)
                throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made for ${rootNamed(repo.root, repo.location)}: ${base.error}.`);
            commit = base.sha;
        }
        plans.push({ repo, dir, commit });
    }
    const takenAllocations = [...new Set(plans.flatMap((plan) => (plan.taken === undefined ? [] : [plan.taken.allocationId])))];
    if (takenAllocations.length > 1) {
        throw refusal("workspace.isolation_unavailable", `The session's trees cannot be taken back: the trees this session minted earlier name different allocations (${takenAllocations.join(", ")}) (name_in_use). Declare another name — or release them with releaseOrphanSessionTree (listOrphanSessionTrees lists such trees).`);
    }
    const allocationId = takenAllocations[0] ?? randomUUID();
    const undo = async (why, code, ...whyFacts) => {
        const kept = [];
        const left = [];
        const facts = [...whyFacts];
        for (const plan of plans) {
            const tree = plan.minted;
            if (tree === undefined)
                continue;
            const mark = await readBirthMark(env, tree.worktreeDir);
            if (mark.kind !== "absent") {
                kept.push(`The tree is kept at ${tree.worktreeDir} (its allocation mark ${mark.kind === "marked" ? "was written" : "cannot be read"})`);
                continue;
            }
            const removed = await removeManagedWorktree(env, tree.anchor, tree.worktreeDir, tree.baseSha !== undefined ? { name: tree.branch, baseSha: tree.baseSha } : undefined, undefined, "clean");
            if (!removed.ok)
                left.push(` The tree minted for it was left at ${tree.worktreeDir} (${removed.detail.trim().slice(0, 200)}).`);
            facts.push(removed);
        }
        const keptSentence = kept.length === 0 ? "" : ` ${kept.join("; ")}; a tree no record holds is listed by listOrphanSessionTrees.`;
        const leftSentence = left.join("");
        throw refusal(code, withOutcomeNote(`${why}${keptSentence}${leftSentence}`, ...facts));
    };
    for (const plan of plans) {
        if (plan.commit === undefined)
            continue;
        const source = plan.repo.source;
        const code = source !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable";
        let made;
        try {
            made = await mintManagedWorktree(env, { repoRoot: plan.repo.location, sessionId, name, commit: plan.commit });
        }
        catch (err) {
            return undo(`The session's tree cannot be made for ${rootNamed(plan.repo.root, plan.repo.location)}${source !== undefined ? ` at the declared commit ${source.sha}` : ""}: ${redactThenCut(thrownText(err), 600)} No tree of this allocation was kept unless named below; the leg was not started.`, code, outcomeFactOfThrown(err));
        }
        plan.minted = { worktreeDir: made.worktreeDir, branch: made.branch, anchor: made.anchor, ...(made.baseSha !== undefined ? { baseSha: made.baseSha } : {}) };
        if (made.baseSha === undefined || (source !== undefined && made.baseSha !== source.sha)) {
            return undo(`The session's tree for ${rootNamed(plan.repo.root, plan.repo.location)} is not at ${source !== undefined ? `the declared commit ${source.sha}` : "a readable base commit"}; the leg was not started.`, code);
        }
    }
    for (const plan of plans) {
        if (plan.minted === undefined)
            continue;
        const birthAt = await birthRecordPath(env, plan.minted.worktreeDir);
        const wrote = birthAt === undefined ? undefined : await env.writeFile(birthAt, JSON.stringify({ allocationId, sessionId, ...(typeof occupant === "string" && occupant !== "" ? { incarnation: occupant } : {}), baseSha: plan.minted.baseSha, declared: declaredDigest(declared) }));
        if (wrote === undefined || !wrote.ok)
            return undo(`The session's tree ${plan.minted.worktreeDir} could not be marked as this session's; the leg was not started.`, "workspace.isolation_unavailable");
    }
    const trees = [];
    const cells = [];
    for (const plan of plans) {
        const dir = plan.minted?.worktreeDir ?? plan.dir;
        const source = plan.repo.source;
        trees.push({ repository: plan.repo.repository, anchor: plan.repo.anchor, dir });
        cells.push({
            repository: plan.repo.anchor,
            root: plan.repo.root,
            baseSha: plan.minted?.baseSha ?? plan.taken.baseSha,
            dir,
            name,
            branch: plan.minted?.branch ?? plan.taken.branch,
            baseRef: source !== undefined ? "source" : declared.baseRef ?? "fresh",
            ...(source !== undefined ? { source: { remote: source.remote, sha: source.sha, ...(source.ref !== undefined ? { ref: source.ref } : {}) } } : {}),
        });
    }
    let roots;
    try {
        roots = await rootsInSession(env, trees, placed);
    }
    catch (err) {
        return undo(`TaskSpec.workspace ${thrownText(err).replace(/^TaskSpec\.workspace /, "")} The leg was not started.`, "config.session_workspace_invalid");
    }
    const record = await recordNow(input.session, { allocationId, sessionId, declared, checkouts: [...cells, ...sourceCells] }, observedLeaf);
    return { ...roots, record, sessionRoot: atRoot(roots.taskRoot) };
}
async function recordNow(session, record, observedLeaf) {
    try {
        await appendSessionCheckout(session, record, observedLeaf);
    }
    catch (err) {
        const dirs = record.checkouts.flatMap((cell) => (cell.dir === undefined ? [] : [cell.dir]));
        const kept = dirs.length === 0
            ? ""
            : ` The tree is kept at ${dirs.join(", ")}. If the record was written, the next leg reopens it and releaseSessionCheckout releases it; if not, the next leg of this session with the same declaration takes it back; a tree no record holds is listed by listOrphanSessionTrees.`;
        throw refusal("workspace.checkout_unavailable", `This session's checkout could not be recorded (${redactThenCut(thrownText(err), 300)}); the leg was not started.${kept}`);
    }
    return record;
}
export async function releaseSessionCheckout(env, session, opts) {
    const onExit = opts?.onExit ?? "keep-if-dirty";
    if (onExit !== "keep-if-dirty" && onExit !== "keep") {
        throw refusal("config.invalid_argument", `releaseSessionCheckout: onExit must be "keep-if-dirty" or "keep" (a removal that discards changes is not offered)`);
    }
    const row = await sessionRowOf(session, "nothing was removed.");
    const read = await readSessionCheckout(session, row.id);
    if (read.kind === "unreadable")
        throw refusal("workspace.checkout_unavailable", `This session's checkout record cannot be read (${read.detail}); nothing was removed.`);
    if (read.kind === "none" || read.kind === "stands")
        return { trees: [] };
    const record = read.record;
    const trees = [];
    for (const cell of record.checkouts) {
        if (cell.dir === undefined || cell.branch === undefined)
            continue;
        trees.push(await releaseTree(env, { path: cell.dir, repository: cell.repository, branch: cell.branch, baseSha: cell.baseSha }, { allocationId: record.allocationId, occupant: row.incarnation }, onExit));
    }
    if (record.released !== true)
        await appendSessionCheckout(session, { ...record, released: true });
    return { trees };
}
async function goneTree(env, tree) {
    await run(env, "git worktree prune", tree.repository);
    return { path: tree.path, removed: true, ...(await branchLeftOf(env, tree.repository, tree.branch)) };
}
async function releaseTree(env, tree, holder, onExit) {
    const { path, repository, branch } = tree;
    const at = await env.fileInfo(path);
    if (!at.ok) {
        if (at.error.code !== "not_found")
            return { path, removed: false, kept: "unverifiable", branch, detail: redactThenCut(thrownText(at.error), 300) };
        return goneTree(env, tree);
    }
    const held = async () => {
        const mark = await readBirthMark(env, path);
        return mark.kind === "marked" && recordHoldsMark(holder, mark.mark);
    };
    const notOwned = async () => ({ path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, repository, branch)) });
    if (!(await held()))
        return notOwned();
    if (onExit === "keep")
        return { path, removed: false, kept: "requested", branch };
    return removeTreeIfClean(env, tree, undefined, async () => ((await held()) ? undefined : notOwned()));
}
async function standingOf(env, dir, sessionOf) {
    const read = await readBirthMark(env, dir);
    if (read.kind !== "marked")
        return { kind: "unmarked", read };
    const mark = read.mark;
    const orphan = (why, detail) => ({ kind: "orphan", mark, why, ...(detail !== undefined ? { detail: detail.slice(0, 300) } : {}) });
    let checkout;
    let occupant;
    try {
        const session = await sessionOf(mark.sessionId);
        if (session === undefined)
            return orphan("unrecorded");
        occupant = (await session.getMetadata()).incarnation;
        if (!sameOccupant(mark.incarnation, occupant))
            return orphan("unrecorded", `the session id ${mark.sessionId} now names another occupant than the one the tree was minted for`);
        checkout = await readSessionCheckout(session, mark.sessionId);
    }
    catch (err) {
        return orphan("record_unreadable", `the session ${mark.sessionId} could not be read (${thrownText(err)})`);
    }
    if (checkout.kind === "unreadable")
        return orphan("record_unreadable", checkout.detail);
    if (checkout.kind === "stands")
        return orphan("record_elsewhere", `the session stands in the checkout of session ${checkout.standsIn} and holds no allocation of its own`);
    if (checkout.kind === "none") {
        return checkout.window === undefined ? orphan("unrecorded") : orphan("record_unreadable", `the session's log is loaded from a bounded window (floor ${checkout.window.floor}); a checkout record below the floor cannot be ruled out`);
    }
    if (!recordHoldsMark({ allocationId: checkout.record.allocationId, occupant }, mark))
        return orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId}`);
    const own = await canonicalOf(env, dir);
    for (const cell of checkout.record.checkouts)
        if (cell.dir !== undefined && (await canonicalOf(env, cell.dir)) === own)
            return { kind: "held", mark };
    return orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId} without this tree`);
}
function lookupOf(door, opts) {
    const sessionOf = opts !== null && typeof opts === "object" ? opts.sessionOf : undefined;
    if (typeof sessionOf !== "function")
        throw refusal("config.invalid_argument", `${door}: opts.sessionOf must be a function (the host's lookup of a session by id in its durable store)`);
    return sessionOf;
}
export async function listOrphanSessionTrees(env, root, opts) {
    const sessionOf = lookupOf("listOrphanSessionTrees", opts);
    if (typeof root !== "string" || !root.startsWith("/"))
        throw refusal("config.invalid_argument", "listOrphanSessionTrees: root must be an absolute path");
    const repository = await managedAnchorOf(env, root);
    const parent = `${repository}/${WORKTREE_PARENT}`;
    const listed = await env.listDir(parent);
    if (!listed.ok) {
        if (listed.error.code === "not_found")
            return { repository, trees: [] };
        throw refusal("workspace.checkout_unavailable", `listOrphanSessionTrees: the managed parent ${parent} cannot be listed (${redactThenCut(thrownText(listed.error), 200)}); nothing was judged.`);
    }
    const trees = [];
    for (const child of [...listed.value].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
        if (child.kind !== "directory")
            continue;
        const path = managedWorktreeDir(repository, child.name);
        const standing = await standingOf(env, path, sessionOf);
        if (standing.kind !== "orphan")
            continue;
        const { mark, why, detail } = standing;
        const branch = managedWorktreeBranchOf(path);
        trees.push({
            path,
            ...(branch !== undefined ? await branchLeftOf(env, repository, branch) : {}),
            sessionId: mark.sessionId,
            allocationId: mark.allocationId,
            baseSha: mark.baseSha,
            why,
            ...(detail !== undefined ? { detail } : {}),
            modifiedAt: child.mtimeMs,
        });
    }
    return { repository, trees };
}
export async function releaseOrphanSessionTree(env, path, opts) {
    const sessionOf = lookupOf("releaseOrphanSessionTree", opts);
    const repository = typeof path === "string" ? managedWorktreeBaseOf(path) : undefined;
    const branch = repository !== undefined ? managedWorktreeBranchOf(path) : undefined;
    if (repository === undefined || branch === undefined) {
        throw refusal("config.invalid_argument", `releaseOrphanSessionTree: ${String(path).slice(0, 200)} is not a managed tree path (<repository root>/${WORKTREE_PARENT}/<name>)`);
    }
    const at = await env.fileInfo(path);
    if (!at.ok)
        return at.error.code === "not_found" ? goneTree(env, { path, repository, branch }) : { path, removed: false, kept: "unverifiable", branch, detail: redactThenCut(thrownText(at.error), 300) };
    const standing = await standingOf(env, path, sessionOf);
    if (standing.kind === "unmarked") {
        return standing.read.kind === "absent"
            ? { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, repository, branch)), detail: "it carries no allocation mark: it is no session tree" }
            : { path, removed: false, kept: "unverifiable", branch, detail: standing.read.detail };
    }
    if (standing.kind === "held")
        return { path, removed: false, kept: "not_owned", branch, detail: "a session's record holds this tree; releaseSessionCheckout releases it" };
    if (standing.why === "record_unreadable")
        return { path, removed: false, kept: "unverifiable", branch, ...(standing.detail !== undefined ? { detail: standing.detail } : {}) };
    return releaseTree(env, { path, repository, branch, baseSha: standing.mark.baseSha }, { allocationId: standing.mark.allocationId, occupant: standing.mark.incarnation }, "keep-if-dirty");
}
const rootCopy = (root) => (root === "taskRoot" ? "taskRoot" : { directory: root.directory });
export function sessionFrameOf(record) {
    if (record === undefined || record.checkouts.length === 0)
        return {};
    const d = record.declared;
    return {
        session: record.checkouts.map((cell) => ({ ...cell, root: rootCopy(cell.root), ...(cell.source !== undefined ? { source: { ...cell.source } } : {}) })),
        declaration: { ...d, ...(d.roots !== undefined ? { roots: d.roots.map(rootCopy) } : {}), ...(d.sources !== undefined ? { sources: d.sources.map((source) => ({ ...source, root: rootCopy(source.root) })) } : {}) },
    };
}