import type { ExecutionEnv, ReadFloor } from "../internal/harness-types.js";
import { type OutcomeFact } from "./exec-outcome.js";
import { type RepositoryProbe } from "../tools/fs/shell-read-object-path.js";
/** The managed parent (under the repository root) that holds every managed worktree — the reference implementation's
 *  `.claude/worktrees/` under this project's brand — so {@link pruneWorktrees} and a userland reaper find orphans by one known
 *  location. Every tree the engine mints lives at `<repoRoot>/.sema/worktrees/<slug>` (see {@link managedWorktreeDir}). */
export declare const WORKTREE_PARENT = ".sema/worktrees";
/** Why `name` is not a managed worktree name, or `undefined` when it is one. */
export declare function worktreeNameProblem(name: string): string | undefined;
/** THE managed location of the tree named `name` under `repoRoot`. */
export declare function managedWorktreeDir(repoRoot: string, name: string): string;
/** The checkout a managed worktree directory was minted under — `dir` minus its `/.sema/worktrees/<slug>` tail — or `undefined`
 *  when `dir` is not shaped as a managed tree. Literal, byte-exact segments (no case fold): this answer EXEMPTS, and a fold
 *  would widen an exemption. */
export declare function managedWorktreeBaseOf(dir: string): string | undefined;
/** The managed tree `dir` is in — `dir` itself, or its nearest ancestor shaped as one (a task root in `pkg/` of a session's tree
 *  sits at `<tree>/pkg`) — as its root and the checkout it was minted under; `undefined` when no level is a managed tree or a
 *  level below the tree is `.` / `..` (where that lands is not decided lexically, and this answer exempts). */
export declare function managedTreeAt(dir: string): {
    readonly root: string;
    readonly base: string;
} | undefined;
/**
 * THE repository root the managed parent is anchored at (the path law): the root of the checkout `dir` belongs
 * to, read through the one repository-top reader ({@link repositoryTopOf} — no second walk). A managed tree is checked out
 * BELOW the repository root it was minted under and its `.git` is a `gitdir:` file, which the top reader answers `undefined`
 * for; so a `dir` at or below a managed tree (its root, a subdirectory of it, a symlink alias of either — read on the
 * canonical spelling) is first peeled to the root before the marker's outermost occurrence (a tree minted by an older engine
 * under another tree peels all the way out). `undefined` where the reader has no answer — not a repository, a linked work tree
 * of the person's own, a submodule, a lookup the environment did not answer; the caller then stays at the root it was given.
 */
export declare function repositoryRootOf(env: RepositoryProbe, dir: string, signal?: AbortSignal): Promise<string | undefined>;
/** Where the managed parent hangs for a mint asked at `root`: the repository root when the reader names one, spelled as the
 *  caller spelled `root` whenever that is the same directory (a consumer comparing the tree's path with its own root's keeps
 *  one spelling); `root` itself when no repository root is named. */
export declare function managedAnchorOf(env: ExecutionEnv, root: string): Promise<string>;
/** The branch the path law gives the managed tree at `dir` (`sema/<slug>`), or `undefined` when `dir` is not a managed tree —
 *  what a recorded branch must equal before anything deletes it (a record cannot name some other branch for removal). */
export declare function managedWorktreeBranchOf(dir: string): string | undefined;
export interface AddWorktreeOptions {
    /** Where the mint is asked (the caller's task root — a checkout of the repository, typically its root). The managed parent
     *  hangs at the REPOSITORY root that checkout belongs to ({@link repositoryRootOf}); with no repository root named, here. */
    repoRoot: string;
    /** Stable per-task identity: with no {@link name}, the tree's name is this (sanitized) plus a random suffix — a fresh name
     *  per mint, for the lanes that mint one tree per child. */
    sessionId: string;
    /** The managed name ({@link worktreeNameProblem} grammar), used as given: the tree lands at `.sema/worktrees/<slug>` on the
     *  new branch `sema/<slug>`. A name whose directory or branch already exists is refused, never reused or reset. */
    name?: string;
    /**
     * How to build a worktree-ROOTED {@link ExecutionEnv} for THIS env type — the only env-specific bit. Local:
     * `(dir) => new NodeExecutionEnv({ cwd: dir })`. A single-E2B deployment: an E2B env whose cwd is `dir`. The
     * returned env's fs/shell must operate relative to `dir`, so the agent's hands AND exec are confined there.
     */
    rootEnvAt: (worktreeDir: string) => ExecutionEnv | Promise<ExecutionEnv>;
    /** Base commit/ref for the worktree (default `HEAD` at creation time). */
    commit?: string;
    /** The byte floor (`ExecutionEnvExecOptions.readFloor`) of every start the mint and the tree's removal make, read as each
     *  start begins: a run's git bookkeeping is the run's own start and carries the run's table. A read that throws is that
     *  step's failure (the add's refuses the mint before anything exists). Absent ⇒ the starts carry none (no run). */
    readFloor?: () => ReadFloor | undefined;
    /** What the env's `destroy()` does with the tree. `"discard"` (default): removes it whatever it holds (`--force`), the
     *  caller having decided its changes go; `destroy()` answers nothing. `"keep-if-dirty"`: removes it only when
     *  {@link judgeManagedTree} — the judgment `releaseSessionCheckout` reads — finds nothing to keep (no uncommitted file, no file
     *  git ignores, no commit past the base the tree was minted at on its HEAD or its branch, a readable state), and then without `--force`; `destroy()`
     *  answers the tree's {@link ReleasedTree} — a tree with something in it stays where it is, with its branch, and the answer
     *  says why (`kept`). Any other value is refused before anything is created (`config.invalid_argument`). */
    onExit?: "discard" | "keep-if-dirty";
}
/** The release outcome of one tree — what `destroy()` of an {@link addWorktree} env and the release doors of a session's
 *  checkout answer. `branch` is present while the tree's branch still exists after the release. */
export interface ReleasedTree {
    readonly path: string;
    readonly removed: boolean;
    readonly branch?: string;
    readonly kept?: "dirty" | "ignored" | "commits" | "unverifiable" | "requested" | "not_owned";
    readonly detail?: string;
}
/** The reasons {@link judgeManagedTree} answers: a subset of {@link ReleasedTree.kept} (the other two are a door's own). */
export type TreeKeptReason = Extract<NonNullable<ReleasedTree["kept"]>, "dirty" | "ignored" | "commits" | "unverifiable">;
/** The bounds a read outside any run (`Runner.readSessionChanges`) puts on each git start it makes: past `timeoutMs`, or once
 *  its output passes `maxOutputBytes` (standard output and error together, counted as UTF-8), the start is stopped and answers
 *  nothing; `signal` stops it too. `env` is laid over the start's environment (the reader's locale and switches). */
export interface GitStartBounds {
    readonly timeoutMs: number;
    readonly maxOutputBytes: number;
    readonly signal?: AbortSignal;
    readonly env?: Readonly<Record<string, string>>;
}
/** THE one git start at `cwd`: its floor read as it begins (a run's git bookkeeping carries the run's table; a start with no
 *  floor reader carries none); `undefined` when it could not be made or reported no result (a floor that throws, or an
 *  environment whose `exec` rejects, is that start's failure — unless the caller asked for `rethrow`), or — with `bounds` — when
 *  it ran past them. */
export declare function gitAt(env: ExecutionEnv, command: string, cwd: string, readFloor: (() => ReadFloor | undefined) | undefined, rethrow?: boolean, bounds?: GitStartBounds): Promise<{
    exitCode: number;
    stdout: string;
    stderr: string;
} | undefined>;
/** The first {@link IGNORED_NAMED} ignored paths (each bounded) and how many more — how a tree's ignored files are named wherever
 *  a sentence names them (`removeTreeIfClean`'s `detail`, ExitWorktree's reply). */
export declare function namedIgnored(paths: readonly string[]): string;
/** What a managed tree holds that removing it would lose, as ONE reading of it answers ({@link treeHoldsOf}): `files` — the entries
 *  git lists as changed or untracked; `ignored` — the paths git ignores in it (an `.env`, build output, `node_modules/`); `commits` —
 *  how many commits sit past the base the tree was minted at, reached from its HEAD or from the branch it was minted on — a HEAD
 *  moved back to the base leaves them on the branch (`undefined`: no base was read, or the count did not answer). */
export interface TreeHolds {
    readonly files: number;
    readonly ignored: readonly string[];
    readonly commits: number | undefined;
}
/**
 * THE reading of a managed tree's contents, the one every door that removes a tree reads: one status read with
 * `--ignored --untracked-files=normal` (untracked files are listed whatever the repository's `status.showUntrackedFiles` says —
 * `no` would hide them) for the files and the ignored paths, then — when a base commit was read — one count of the commits past
 * it that the tree's HEAD or its own branch reaches (a commit only a reflog still names is not counted: the reference keeps a
 * worktree for the commits on its HEAD and its branch, and no further). `undefined` when the status read failed. The verdict is {@link keptByHolds}'s; a door that also says how much the tree
 * holds (ExitWorktree's reply) reads the counts off the same answer. A start that REJECTS (an environment whose `exec` throws, a
 * floor that cannot be read) is read as a failed reading — a tree is kept on a guess, never removed — unless the caller passes
 * `rethrow`: a door whose own state must survive a transient failure to retry it (ExitWorktree keeps its session active) lets the
 * rejection propagate.
 */
export declare function treeHoldsOf(env: ExecutionEnv, path: string, baseSha: string | undefined, readFloor?: () => ReadFloor | undefined, opts?: {
    readonly rethrow?: boolean;
}): Promise<TreeHolds | undefined>;
/**
 * THE keep verdict over {@link treeHoldsOf}'s reading: why the tree must not be removed, or `undefined` when nothing in it would be
 * lost. A tracked change or an untracked file keeps it (`dirty`); a file git ignores keeps it too (`ignored`), since removing the
 * tree would delete it with it; then a commit past the base keeps it (`commits`). A reading that failed, and a base that was never
 * read or a count that did not answer, are `unverifiable` — nothing is removed on a guess.
 */
export declare function keptByHolds(holds: TreeHolds | undefined): {
    readonly kept: TreeKeptReason;
    readonly detail?: string;
} | undefined;
/** What {@link judgeManagedTree} answers: nothing in the tree would be lost by removing it (`collectable: true`), or why it must
 *  stay — one word of the closed set {@link TreeKeptReason} (the same words a release answers in {@link ReleasedTree.kept}). */
export type ManagedTreeVerdict = {
    readonly collectable: true;
} | {
    readonly collectable: false;
    readonly kept: TreeKeptReason;
    readonly detail?: string;
};
/**
 * Can the managed tree at `tree.path` be removed now, and if not, why — THE keep verdict ({@link keptByHolds} over
 * {@link treeHoldsOf}) that every door removing a tree reads, offered to a host that mints trees itself (`addWorktree`) and decides
 * on its own when to collect one. It only reads: nothing is removed. `tree.path` is the tree's directory as `addWorktree` answers it
 * (`worktreeDir`) and `tree.baseSha` the base it answers (`undefined` when it could not read one); a path that is no managed tree
 * is never judged removable. A reading that fails or an environment whose `exec` rejects answers `unverifiable` — nothing is
 * judged removable on a guess. `options.readFloor` is read as each git start begins, as `addWorktree`'s is.
 */
export declare function judgeManagedTree(env: ExecutionEnv, tree: {
    readonly path: string;
    readonly baseSha: string | undefined;
}, options?: {
    readonly readFloor?: () => ReadFloor | undefined;
}): Promise<ManagedTreeVerdict>;
/** `{ branch }` while `branch` still exists in the repository at `repository`, else `{}`. */
export declare function branchLeftOf(env: ExecutionEnv, repository: string, branch: string, readFloor?: () => ReadFloor | undefined): Promise<{
    branch?: string;
}>;
/**
 * THE keeping removal of a managed tree: {@link judgeManagedTree} first (a tree with something in it is kept and named, its branch
 * left), then `stillOurs` — a door's own re-read right before the removal, answering the outcome when the tree is no longer
 * its to remove — then the removal without `--force` (a write landing after the judgment keeps the tree: `unverifiable`, with
 * git's words), its branch deleted with it only while the branch sits at the base commit.
 */
export declare function removeTreeIfClean(env: ExecutionEnv, tree: {
    readonly path: string;
    readonly repository: string;
    readonly branch: string;
    readonly baseSha: string | undefined;
}, readFloor: (() => ReadFloor | undefined) | undefined, stillOurs?: () => Promise<ReleasedTree | undefined>): Promise<ReleasedTree>;
/** Single-quote a path for the `exec` command STRING (the Shell API takes a command string, not argv). */
export declare function shq(s: string): string;
/**
 * THE path law's symlink half: from `.sema` down to the tree's own directory, NO level may be a symlink — a link committed to
 * the repository at any of them would redirect the mint outside it. Three levels exactly (the slug is one directory, see
 * {@link slugOf}); a level that does not exist yet is fine (git creates it), and a level whose kind cannot be read refuses.
 */
export declare function symlinkedLevel(env: ExecutionEnv, repoRoot: string, worktreeDir: string): Promise<string | undefined>;
/**
 * Remove a managed worktree and — by the ONE branch rule — its branch: the branch is deleted only when its tip is still the
 * commit the tree was minted at (it carries nothing the tree made); otherwise it is kept, so commits made in the tree stay
 * reachable after the directory is gone. The branch half is best-effort (a branch left behind is a name, not an orphaned
 * directory) and reported as `branchKept`.
 *
 * server [1796]②: the worktree removal itself used to be fire-and-forget — a transient failure (spawn EAGAIN/EMFILE under
 * load) then left the directory AND its registration behind, which `git worktree prune` can never reclaim (prune only
 * deregisters worktrees whose directory is gone). Check the result, retry once (the observed failures are transient),
 * and report the outcome.
 */
export declare function removeManagedWorktree(baseEnv: ExecutionEnv, repoRoot: string, worktreeDir: string, branch: {
    readonly name: string;
    readonly baseSha: string;
} | undefined, readFloor: (() => ReadFloor | undefined) | undefined, 
/** `"discard"` removes the tree whatever it holds (`--force`: the caller already decided its changes go); `"clean"` lets git
 *  refuse a tree with changes (no `--force`: whatever lands between the caller's own check and the removal keeps the tree). */
how: "discard" | "clean"): Promise<({
    ok: true;
    branchDeleted?: string;
    branchKept?: string;
} | {
    ok: false;
    detail: string;
}) & OutcomeFact>;
/**
 * design/97 CORE-6 — the env-agnostic git-WORKTREE isolation primitive, and the engine's ONE worktree mint. Creates a managed
 * worktree at `<repoRoot>/.sema/worktrees/<slug>` on the new branch `sema/<slug>` (via the BASE env's shell, refusing when
 * any level of that path is a symlink) and returns a worktree-ROOTED ExecutionEnv (built by `rootEnvAt`) whose `destroy()`
 * removes the worktree (and its branch, by the branch rule of {@link removeManagedWorktree}). A control-plane
 * `executionEnvFactory` calls this when its `ctx.isolation === "worktree"` and returns the result (with `destroy`); for a
 * non-isolated task it returns the SHARED base env (no `destroy`) so the Runner never tears the base down.
 *
 * ISOLATE-ONLY: the runtime never merges — the orchestrator script reads each worktree's result and
 * decides verify/merge in userland. Caveats: `git worktree` isolates the git WORKING COPY, not
 * arbitrary shell access (bash can still reach the host — sandbox separately); UNCOMMITTED changes in the base
 * repo are absent in the child (the tree starts at the base commit); a worktree orphaned by a process crash is reaped by
 * {@link pruneWorktrees} (userland — there is no Runner hook for post-kill cleanup).
 *
 * Under `onExit: "keep-if-dirty"`, `destroy()` answers the tree's {@link ReleasedTree}: `removed: true` once it is gone, or
 * `removed: false` with the reason it was kept (the tree and its branch left in place for the caller to inspect or merge).
 * Under `"discard"` (the default) it answers nothing: the tree is gone, or `destroy()` rejects.
 */
export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOptions & {
    readonly onExit: "keep-if-dirty";
}): Promise<{
    env: ExecutionEnv & {
        destroy(): Promise<ReleasedTree>;
    };
    worktreeDir: string;
    name: string;
    branch: string;
    baseSha?: string;
}>;
export declare function addWorktree(baseEnv: ExecutionEnv, opts: AddWorktreeOptions & {
    readonly onExit?: "discard";
}): Promise<{
    env: ExecutionEnv & {
        destroy(): Promise<void>;
    };
    worktreeDir: string;
    name: string;
    branch: string;
    baseSha?: string;
}>;
/**
 * THE managed-tree mint with no environment attached: judges the name, anchors the managed parent at the repository root,
 * refuses a symlinked level, runs `git worktree add` (a name whose directory or branch exists is refused) and registers the
 * parent in the repository-local ignore file. {@link addWorktree} wraps it with a tree-rooted env whose destroy removes the
 * tree; a session checkout keeps the tree past every env and removes it only on release.
 */
export declare function mintManagedWorktree(baseEnv: ExecutionEnv, opts: Pick<AddWorktreeOptions, "repoRoot" | "sessionId" | "name" | "commit" | "readFloor">): Promise<{
    worktreeDir: string;
    name: string;
    branch: string;
    anchor: string;
    baseSha?: string;
}>;
/**
 * Resolve the commit a new tree starts from, by the base words EnterWorktree and the session declaration share: `"head"` =
 * the current local HEAD; `"fresh"` = the default branch tip (origin's HEAD symbolic ref → local main → local master → HEAD,
 * the fallback named in `note`). Run where the mint is asked (`repoRoot`).
 */
export declare function resolveBaseCommit(env: ExecutionEnv, repoRoot: string, baseRef: "fresh" | "head", readFloor: ReadFloor | undefined): Promise<{
    sha: string;
    label: string;
    note?: string;
} | {
    error: string;
}>;
/** Reap orphaned worktrees (after a crash removed their dirs) — `git worktree prune` deregisters them. A userland
 *  reaper calls this periodically against the base repo; core ships no post-kill Runner hook.
 *
 *  HRD-PTL-11: the exec Result used to be discarded, so every caller had to ASSUME the prune landed — and
 *  ExitWorktree's "already gone externally" leg told the model "stale git worktree metadata was pruned"
 *  on a claim it could not have checked. Same fail-loud treatment {@link removeManagedWorktree} already got
 *  Report the outcome, let the caller decide what to say. Never throws (a throwing env
 *  lands on the same `{ok:false}`), so a caller that ignores the value behaves exactly as before. A failure whose outcome is
 *  unknown says so as the fact (`outcomeUnknown: true`), never as the sentence: the caller that shows it places that once. */
export declare function pruneWorktrees(baseEnv: ExecutionEnv, repoRoot: string, readFloor?: ReadFloor): Promise<{
    ok: true;
} | ({
    ok: false;
    detail: string;
} & OutcomeFact)>;
