/** * The `git init` argv for a container root. Exported so the quoting guarantee * is unit-testable: a path with a space must stay ONE argument. */ export declare function containerInitArgs(separateGitDir: string | null): string[]; /** Untracked marker written at a mirror root. Never committed. */ export declare const MIRROR_MARKER_FILE = ".teamshare-mirror.json"; export interface MirrorRepo { /** '.' for the container root, else the path relative to the linked folder. */ name: string; /** The real repo whose branch receives the commits. */ mainRepo: string; /** The worktree the run works in. */ worktree: string; branch: string; base: string; } /** Per-repo outcome of a `detachIsolationMirror`, for honest progress reporting. */ export interface MirrorDetachDetail { repo: string; worktree: string; removed: boolean; /** Uncommitted work was committed before removal. */ rescued: boolean; /** The rescue commit reached the remote (undefined when nothing was rescued). */ pushed?: boolean; branch?: string; commitHash?: string; error?: string; /** Where a surviving root was parked (only when quarantined). */ quarantined?: string; } export interface MirrorMarker { folder: string; seed: string; branch: string; repos: MirrorRepo[]; /** * Nested repos deliberately LEFT OUT of the mirror because they had no * resolvable base branch (an unborn repo has no commits to isolate). * * Recorded rather than merely logged, because a repo absent from `repos` is * absent from `resolveRunRepos` too - so finalize never commits it and the * run reports success with its work uncommitted. This field is what lets the * closing report name the gap instead of implying full coverage. */ skippedRepos?: string[]; /** * The task this mirror belongs to (task-scoped runs only). Its presence is * what makes the tree ADOPTABLE: a retry finds its own path deterministically * and can carry on from the dead run's uncommitted work. */ taskId?: string; /** The branch this tree was based on when it was created (3B). */ resumedFrom?: string; /** * The branch this run's WORK IS DELIVERED ON — `/` from * `desiredBranch()` (`marker.branch` is only the ephemeral * `teamshare/auto/` worktree branch). * * Recorded because everything that has to save a dead run's uncommitted work * needs it: the stop handler, the lease sweep and `cleanup --agent` all call * `detachIsolationMirror` without knowing the task's title/project, and their * old fallback was `branchForTask()` = `tasks/` — a ref NO re-run ever * checks out, so rescued work was invisible to the very retry meant to * continue it. Read it in preference to that fallback. */ deliverableBranch?: string; /** * The base this tree was UPDATED FROM at creation (2026-11-18). The tree is * put on `deliverableBranch` and then merged with the branch the task started * from, so the run works against current state. */ syncedFrom?: string; /** Per-repo one-liners about the branch/update step (operator surface). */ branchNotes?: string[]; /** * Merge conflicts LEFT IN THE TREE for the agent to resolve, per repo. * `brief.ts` turns this into an explicit "resolve these first" section; the * bridge never resolves them itself (that needs judgement). */ mergeConflicts?: Array<{ repo: string; files: string[]; }>; } export interface IsolationMirror { path: string; branch: string; repos: MirrorRepo[]; /** * True when this run adopted a previous run's tree instead of creating a new * one (the previous attempt died before committing; its files are intact). */ adopted?: boolean; /** Branch the tree was based on, when it resumed an existing task branch. */ resumedFrom?: string; /** Uncommitted files carried over by an adoption. */ dirtyFiles?: number; /** * Worktrees the marker listed that were NOT on disk at adoption time. * * Non-empty means the tree had already been partly torn down when this run * took it over - so `dirtyFiles: 0` alongside it means "nothing survived in * the repos that are still there", not "the tree was intact". */ missingRepos?: string[]; /** The base the tree was updated from at creation (2026-11-18). */ syncedFrom?: string; /** Per-repo notes about the branch/update step (operator surface). */ branchNotes?: string[]; /** Merge conflicts left in the tree for the agent to resolve. */ mergeConflicts?: Array<{ repo: string; files: string[]; }>; /** * The decision this tree was built from, so the report can answer "why did * this run start here" without re-deriving it. */ plan?: { branch: string; base: string | null; baseSource: string; branchSource: string; }; } /** Why a mirror could not be produced. */ export type MirrorFailure = 'blocked' | 'unavailable'; export type MirrorOutcome = { ok: true; mirror: IsolationMirror; } | { ok: false; reason: MirrorFailure; detail?: string; }; /** Task-scoped mirrors: one stable path per task, so a retry can find it. */ export declare const TASK_MIRROR_PREFIX = "taskrun-"; /** * Does this path have the SHAPE of a mirror, ignoring whether it is still one? * * `isMirrorDir` answers "is this a working mirror right now", which is false for * a mirror that was torn down: the marker is deleted along with the container * root's `.git`, so the survivors look like an ordinary folder. That is exactly * the state a run wakes up in after its tree was deleted underneath it, and the * generic "no git repository found" path then reported it as the LINKED FOLDER * not being a repo - a statement about the human's folder that was simply false, * and which sent the agent looking at the one thing that was not broken. * * The name is the part that survives: `taskrun-` / `run--` are * minted here and nowhere else, and they never collide with an orchestrator tree * (`task-`), which is backend-owned. */ export declare function looksLikeMirrorPath(dir: string): boolean; /** * Ephemeral mirrors (wakes with no task id - `build.trigger`, a bare document * mention): never adopted, always disposable. A distinct prefix keeps the * sweeper's task-mirror logic unambiguous. */ export declare const EPHEMERAL_MIRROR_PREFIX = "run-"; /** Mirror directory for a task-scoped run - deterministic, no random suffix. */ export declare function mirrorDirForTask(folder: string, taskId: string): string; /** Mirror directory for a wake with no task id - unique, never adopted. */ export declare function mirrorDirForEphemeral(folder: string, eventType: string): string; /** The task id a mirror path belongs to, or null for ephemeral/orphan trees. */ export declare function taskIdForMirrorDir(dir: string): string | null; export declare function isGitRepoDir(dir: string): boolean; /** Read a mirror marker from a directory (null when absent/invalid). */ export declare function readMirrorMarker(dir: string): MirrorMarker | null; export declare function isMirrorDir(dir: string): boolean; /** * True when `dir` is a PRIVATE tree the bridge built for one session: an * isolation mirror (container root + nested repo worktrees) or any linked * worktree. * * This is the gate for the whole stash lifecycle (`lib/git/git-runner.ts`). Two * facts make the gate mandatory rather than cosmetic: * * 1. A linked worktree has its own directory and index, so a stash pushed * inside it can only ever see ITS OWN files - never the user's working * files in the main checkout. So a stash on an isolated run was never * protecting anything of the user's; it was stashing the agent's own tree. * 2. `refs/stash` is NOT per-worktree. A linked worktree SHARES the stash * stack with its main repo, so every stash an isolated run pushed landed on * the user's own stash stack (shifting their refs) and every * `checkOrphanedStashes` scan read the user's entries back as if they were * orphaned agent work. * * On an ADOPTED mirror (a retry continuing a dead run's tree) the stash was * worse than useless: it removed the previous attempt's uncommitted files - * the only copy of them - while `brief.ts` went on telling the agent to run * `git diff` first and not re-implement the task. * * The linked folder itself is NOT isolated, so the stash still runs there: that * is what protects a human's uncommitted work from `git checkout ` * on the `autoWorktree: false` and resume-wake paths. */ export declare function isIsolatedTree(dir: string): boolean; /** * The repos a run must commit to. Inside a mirror this is the marker's * worktrees (container root + nested repos) — the essential fix: a container * root `.git` must never collapse the set to just itself. Outside a mirror * the legacy discovery is preserved. */ export declare function resolveRunRepos(cwd: string): string[]; /** * All pre-existing git repos strictly UNDER `folder` (never initializes any). * Stops descending at each repo boundary and skips dot/node_modules dirs. * * ── WHY maxDepth IS NOT A SILENT CLIFF ─────────────────────────────────────── * * This walker is used by FOUR callers that each call it with no argument: * `ensureContainerRoot` (via `healUnbornNestedRepos` and * `seedContainerExcludes`), and `createIsolationMirror`. They must agree * exactly, because they are complements - the excludes list says "do not track * this nested repo", and the mirror says "here is its worktree". * * A repo deeper than the limit broke that agreement in the worst direction: it * was in NEITHER. Not excluded, so it appeared as untracked noise in the mirror * root; not in the mirror, so its work was never committed. Raising the default * makes real layouts (`container/pkg/service/repo`) fit, and the truncation log * means hitting the ceiling is visible instead of silent. * * Cost stays bounded: dot-directories and `node_modules` are skipped, and the * walk stops at every repo boundary. */ export declare function discoverNestedRepos(folder: string, maxDepth?: number): string[]; /** * Ensure the linked folder is a usable CONTAINER ROOT repo: * - `git init` when there is no repo (NEVER a nested repo), * - seed `.git/info/exclude` with safety entries + every nested repo path, * - create a baseline commit when the repo has no commits yet. * * Serialized under the per-folder workspace lock so two agents starting at * the same instant on a not-yet-initialized folder cannot race the init / * baseline commit (the loser would otherwise fail and queue once). The lock * is released before worktree creation (which takes the same lock) so there * is no re-entrancy. Never throws. */ export declare function ensureContainerRoot(folder: string, agentId?: string): Promise<{ ok: boolean; initialized: boolean; error?: string; }>; /** * Align an EXISTING tree with the branch this run is supposed to be on * (2026-11-18). * * The failure this prevents, in order: * 1. a tree is built from the WRONG base (the repair did this, because it had * no task branch to pass); * 2. the next run adopts it; * 3. `prepare`'s `git checkout ` is refused over local changes; * 4. the run commits on a detached HEAD called `HEAD` and cannot push. * * New trees are created ON the branch, so this is the self-healing half: any * tree that predates that (or was built by an older bridge) is put right before * the agent starts. It never discards anything: a repo with uncommitted files * or unmerged paths is left exactly as it is and reported, because those bytes * may be a dead run's only copy. */ export interface TreeAlignment { ok: boolean; /** Repos that were attached to the branch by this call. */ aligned: string[]; /** Repos left alone, with why. */ skipped: Array<{ repo: string; reason: string; }>; } export declare function alignTreeToBranch(opts: { cwd: string; branch: string; log?: (text: string) => void; }): TreeAlignment; /** * Create a full isolation mirror for a run. Returns null (and rolls back any * partially-created worktrees) when isolation cannot be achieved — the caller * must then queue rather than run un-isolated. */ export declare function createIsolationMirror(folder: string, seed: string, agentId?: string, projectId?: string | null, opts?: { /** The task this run works on (task-scoped runs only). */ taskId?: string; /** * Branch to base the tree on when it exists (the task's own branch). This * is what makes a RETRY continue instead of re-implementing: a previous * attempt that committed its work left it on this branch, and a mirror * created from the default branch cannot see it - the agent lands on a * clean tree and does the job twice. */ baseBranch?: string | null; /** * Project-wide base branch from TeamShare settings (2026-12). Used only * when the task's own branch does not exist yet, and BEFORE the branch the * linked folder happens to be on. Null = no explicit setting. */ configuredBase?: string | null; /** * The branch this run's work is DELIVERED on (`/` from * `desiredBranch()`), recorded on the marker + lease. It is NOT the * worktree branch, and it is what a stop / sweep / cleanup must rescue a * killed run's uncommitted work onto. */ deliverableBranch?: string | null; /** * The branch this task already DELIVERED on (2026-12), from the hub's * `Task.deliveryBranch`. Outranks the local task-base record: after a * guarded rename the record still names the pre-rename branch. */ deliveryBranch?: string | null; /** Project name, for deriving the task's branch (see `planTaskBase`). */ projectSlug?: string | null; /** Task title, for deriving the task's branch (see `planTaskBase`). */ taskTitle?: string | null; /** * Merge this ref into the tree's branch before the agent starts (updated * state). Defaults to the task's recorded base; pass null to opt out. */ syncFrom?: string | null; /** * Put the tree ON the task's branch instead of leaving it detached. * Default true for task-scoped mirrors (2026-11-18) — a detached tree is * what let a run commit under the name `HEAD`. */ attachBranch?: boolean; }): Promise; /** * Rebuild-on-arrival (2026-10): a session dispatched into a mirror that no * longer exists gets a WORKING tree, not a downgrade and not a run in the * linked folder. * * The observed case: the daemon builds `taskrun-`, the CLI waits on * the agent lock behind a live session, and by the time it starts the tree is * gone (swept, cleaned, or deleted by hand) - an empty shell with a mirror's * name, no marker, no git repo. `git-prepare` used to downgrade that to * `mirror-destroyed` and the harness ran anyway, escaping via absolute paths * into the human's branch. * * Rules: * - marker present -> nothing to do (the live path, zero cost); * - corpse triage: a MISSING or EMPTY shell is removed; a NON-EMPTY shell of * unknown provenance is QUARANTINED (`.abandoned-`), never * deleted - its bytes may be a dead run's only copy; * - rebuild is attempted EXACTLY ONCE via `createIsolationMirror` with the * same task id/branches, so the path stays deterministic and a retry still * adopts it; any failure is terminal for the caller (abort, don't degrade); * - the previous tree's uncommitted remainder is declared unrecoverable * out loud when the lease says there was one - a rebuild continues from * the task branch, it never pretends the files survived. */ export interface MirrorRecovery { ok: boolean; rebuilt: boolean; /** Where unknown corpse content was parked (only when quarantined). */ quarantined?: string; /** Why the rebuild was refused/failed (only when `ok` is false). */ detail?: string; } export declare function ensureLiveMirror(opts: { /** The dispatched working directory (must be the task's own mirror path). */ cwd: string; /** Mirror seed (task id for task-scoped runs). */ seed: string; agentId?: string; projectId?: string | null; taskId?: string; /** Branch to base the rebuilt tree on (the task's own branch for retries). */ baseBranch?: string | null; /** Project-wide base branch (TeamShare setting) - see createIsolationMirror. */ configuredBase?: string | null; /** Branch the rebuilt run delivers on. */ deliverableBranch?: string | null; /** The branch this task already delivered on (hub-recorded rename). */ deliveryBranch?: string | null; /** Project name, so the rebuilt tree derives the task's branch (2026-11-18). */ projectSlug?: string | null; /** Task title, so the rebuilt tree derives the task's branch (2026-11-18). */ taskTitle?: string | null; log?: (text: string) => void; }): Promise; /** * Base ref for a new worktree, resolved through THE base-branch ladder * (2026-12): * * 1. the task's own branch, when it exists (retry continues the last attempt) * 2. the project-wide base branch, when a human set one * 3. the branch checked out in THIS repo of the linked folder <- the default * 4. the repo default (`detectDefaultBranch`) * * Step 3 is the fix: the mirror used to be based on `detectDefaultBranch`, * which resolves `origin/HEAD` first, so a folder sitting on `staging` got a * tree cut from `master` and a PR opened against `master`. * * For steps 2/3 a remote-tracking ref (`origin/`) is preferred when it * exists - the PR base is the REMOTE branch, so the tree should start at the * commit that branch points at. Step 1 prefers the LOCAL task branch, because * a previous attempt may have committed without pushing. * * The mirror is still created DETACHED, so nothing is checked out in the main * repo. * * Exported for the isolation REPAIR path (`workspace/isolation-repair.ts`), * which reports which base a run would start from - the same ladder the real * mirror uses, so a repair can never claim a branch the next run would not pick. */ export declare function resolveBaseBranch(repo: string, opts?: { continueFrom?: string | null; configuredBase?: string | null; }): string | null; /** * Claim a mirror for THIS session (called by the spawned CLI on start). * Records the pid in the lease so a second wake can tell "someone is working * here" from "a previous run died here". Returns the task id, or null when the * session is not in a task-keyed mirror. */ export declare function claimMirrorForSession(cwd: string, kind: string): string | null; /** * Settle the lease when a session ends. * * `success` — the tree is being removed, so the lease goes with it. * `failure` — the tree is KEPT (2026-09). A failed run's finalize still * commits to the task branch, but the uncommitted remainder only exists in this * tree, and a retry adopts it in place. The 6h sweeper reclaims it if no retry * ever arrives, so keeping it cannot leak indefinitely. */ export declare function settleMirrorLease(cwd: string, outcome: 'success' | 'failure'): void; /** * Is a session genuinely USING this mirror right now? * * This is the check that was missing where it mattered. Both sweepers decided * liveness OUTSIDE this module and then called in to delete, and the delete * takes minutes - it walks every repo, and each `removeWorktreeSafeAsync` awaits * a workspace lock. A retry could adopt the tree and start working in it inside * that window, and nothing re-read the evidence. So the decision has to be * re-taken HERE, next to the destruction, not only by the caller. * * Two signals, either sufficient, and an unreadable registry reads as BUSY: * - a live presence row (written by the CLI that owns the session) * - a live `handedTo` pid in the lease * * `ignorePids` exempts the caller itself, for the paths that legitimately * detach a tree they are sitting in (`cleanup --agent` clears its own row and * kills its own lock holder before detaching, and both would otherwise look * like an occupant forever). */ export declare function mirrorSessionIsLive(cwd: string, marker: MirrorMarker, ignorePids?: number[]): { live: boolean; reason: string; }; /** * May this teardown clean the mirror ROOT? * * Yes only when every NESTED repo is gone. A nested worktree that was kept * lives INSIDE the root, so deleting or quarantining the root would take it * with it. The ROOT being kept is NOT a blocker: that is exactly the state a * successful teardown leaves behind when OpenCode's shared service holds the * empty shell open, and the old `kept.length === 0` gate skipped the root's * registry prune entirely because of it (2026-10-27). * * Pure and exported so the rule is pinned by a test without a filesystem. */ export declare function allNonRootReposRemoved(repos: ReadonlyArray>, kept: ReadonlyArray): boolean; /** * Detach a mirror after a run — ALWAYS, success or failure: the run's work is * already committed to the task branch, so the mirror is leftover. Rescue-first * removal keeps any tree whose uncommitted work cannot be pushed, and * `rescueBranch` points that rescue at the task branch so the next run * continues from it. Returns what was removed and what was kept for inspection. * * The rescue branch DEFAULTS to the marker's own task branch. Callers used to * pass it explicitly on the finish path but NOT on the sweeper path, so a tree * cleaned up automatically landed on a nameless `teamshare/rescue/` * branch that no retry would ever look at - work that was technically saved * and practically lost. * * `guardLiveSession` is for the SWEEPERS, and is the whole point of this * function's re-check (see `mirrorSessionIsLive`). It is OFF by default because * the four CLI commands are the OWNER: `run` still holds its presence row at * this point (`unregisterPresence` runs after the detach), so a blanket check * would refuse the owner cleaning up its own tree and leak every mirror. A * sweeper sets it, and then the tree is re-checked before EACH repo and again * before the root delete, because the gap between "decided" and "acted" is * measured in minutes here. */ export declare function detachIsolationMirror(cwd: string, agentId?: string, opts?: { rescueBranch?: string; reason?: string; guardLiveSession?: boolean; ignorePids?: number[]; log?: (text: string) => void; }): Promise<{ removed: string[]; kept: string[]; details: MirrorDetachDetail[]; rescueBranch?: string; /** Set when `guardLiveSession` aborted the detach. */ aborted?: string; /** * The root could not be deleted but is EMPTY - a byte-less shell held open by * OpenCode's shared service. Nothing is kept in it, so a caller reporting the * outcome must not read it as "the rescue failed" (2026-11-05): the stop * comment told the human their work could not be saved when there had been * nothing to save and the next run reuses the shell in place. */ emptiedRoot?: boolean; }>;