A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI] Guard destructive git discards behind a dirty-tree check in the bash tool (#2275)
Seth Kartenec56defc1c9d
diff --git a/packages/coding-agent/.changes/destructive-git-dirty-tree-guard.md b/packages/coding-agent/.changes/destructive-git-dirty-tree-guard.mdnew file mode 100644index 0000000000..88a81a2b79--- /dev/null+++ b/packages/coding-agent/.changes/destructive-git-dirty-tree-guard.md@@ -0,0 +1 @@+- Added a dirty-tree guard to the bash tool: destructive git discard commands (`git checkout -- .`, `git checkout .`, `git clean -f...`, `git reset --hard`, `git restore .`) are refused while uncommitted changes exist, listing the dirty paths and the explicit bypasses (`allowDestructiveGit: true` or `PI_BASH_ALLOW_DESTRUCTIVE_GIT=1`). The guard probes the repository the command targets (following `cd` chains and `git -C`), refuses relocations it cannot replay safely, and fails open when dirtiness cannot be determined.diff --git a/packages/coding-agent/src/core/tools/bash.ts b/packages/coding-agent/src/core/tools/bash.tsindex 6143e6f98c..601c5b70cf 100644--- a/packages/coding-agent/src/core/tools/bash.ts+++ b/packages/coding-agent/src/core/tools/bash.ts@@ -23,6 +23,12 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResultconst bashSchema = Type.Object({command: Type.String({ description: "Bash command to execute" }),timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),+ allowDestructiveGit: Type.Optional(+ Type.Boolean({+ description:+ "Skip the dirty-tree guard for destructive git discard commands. Only set when discarding uncommitted work is intentional.",+ }),+ ),});export type BashToolInput = Static<typeof bashSchema>;@@ -147,6 +153,369 @@ export interface BashToolOptions {spawnHook?: BashSpawnHook;}+/** Bypass env var for the destructive-git dirty-tree guard. */+export const BASH_DESTRUCTIVE_GIT_BYPASS_ENV = "PI_BASH_ALLOW_DESTRUCTIVE_GIT";++const GIT_STATUS_PORCELAIN_COMMAND = "git status --porcelain --untracked-files=all";++/** How many dirty paths the refusal lists before eliding the rest. */+const MAX_DIRTY_PATHS_LISTED = 10;++/**+ * Detection for git commands that discard uncommitted working-tree changes+ * (the "clean the worktree" discard idiom).+ *+ * Conservative by design: a false positive costs one `git status` probe and+ * an explicit-bypass retry; a false negative silently loses work. Matching is+ * best-effort shell-text heuristics, not a parse.+ */++/**+ * Optional git global options between `git` and the subcommand, for example+ * `git -C dir reset --hard`, `git -c key=value checkout -- .`, or+ * `git --git-dir=dir/.git reset --hard`. Kept within one shell segment+ * (no ;&|) so it cannot swallow the rest of a chained command.+ */+const GIT_GLOBAL_OPTIONS = "(?:-{1,2}[^\\s;&|]+(?:\\s+(?:\"[^\"]*\"|'[^']*'|[^\\s;&|]+))?\\s+)*";++const DISCARD_CHECKOUT_PATTERN = new RegExp(+ `\\bgit\\s+${GIT_GLOBAL_OPTIONS}checkout\\s+(?:(?:(?:-[fm]|--ours|--theirs|--conflict=\\S+)\\s+)*(?:--\\s+)?(?:\\.\\/?|:\\/)|[^\\s;&|()]+\\s+(?:--\\s+)?(?:\\.\\/?|:\\/)|(?:-f|--force)\\s+[^\\s;&|()]+)(?=\\s|$|[;&|)])`,+ "g",+);+const DISCARD_RESTORE_PATTERN = new RegExp(+ `\\bgit\\s+${GIT_GLOBAL_OPTIONS}restore\\s+(?:(?:--source|--worktree)(?:=\\S+)?\\s+|-s(?:\\s+\\S+|[^\\s]+)\\s+|-W\\s+|--\\s+)?(?:\\.\\/?|:\\/)(?=\\s|$|[;&|)])`,+ "g",+);+const DISCARD_RESET_PATTERN = new RegExp(+ `\\bgit\\s+${GIT_GLOBAL_OPTIONS}reset\\s+(?:(?:-[^\\s;&|]+)\\s+)*--hard\\b`,+ "g",+);+const DISCARD_CLEAN_PATTERN = new RegExp(`\\bgit\\s+${GIT_GLOBAL_OPTIONS}clean\\s+([^;&|]*)`, "g");++function isForcedCleanSegment(args: string): boolean {+ const tokens = args.split(/\s+/).filter(Boolean);+ // Everything after -- is a pathspec, not options (git clean -f -- -n is forced).+ const optionEnd = tokens.indexOf("--");+ const optionTokens = optionEnd === -1 ? tokens : tokens.slice(0, optionEnd);+ const forces = optionTokens.filter((arg) =>+ arg.startsWith("--") ? arg.startsWith("--force") : arg.startsWith("-") && arg.includes("f"),+ );+ if (forces.length === 0) return false;+ return !optionTokens.some(+ (arg) => arg === "--dry-run" || (arg.startsWith("-") && !arg.startsWith("--") && arg.includes("n")),+ );+}++/**+ * Find every destructive git discard command in `command`, returning the+ * character index where each `git` token starts (empty when none match).+ */+/**+ * Replace characters inside single- or double-quoted spans with spaces so the+ * discard matcher cannot match quoted data (for example `echo 'git reset --hard'`).+ * Character positions stay identical to the original string, so match indices+ * remain valid. Command substitution (`$(...)`, backticks) is left live because+ * it executes.+ */+function maskQuotedSpans(command: string): string {+ const chars = command.split("");+ let quote: '"' | "'" | null = null;+ for (let i = 0; i < chars.length; i++) {+ const ch = chars[i];+ if (quote === null) {+ // An unquoted # at a word boundary starts a comment; mask to end of line.+ const prev = i > 0 ? chars[i - 1] : undefined;+ if (ch === "#" && (i === 0 || prev === undefined || /[\s;&|(){}]/.test(prev))) {+ for (let j = i; j < chars.length && chars[j] !== "\n"; j++) chars[j] = " ";+ continue;+ }+ if (ch === '"' || ch === "'") quote = ch;+ } else if (quote === "'") {+ // No expansion happens inside single quotes; mask it all.+ if (ch === "'") quote = null;+ else chars[i] = " ";+ } else if (ch === '"') {+ quote = null;+ } else if (ch === "\\" && i + 1 < chars.length) {+ chars[i] = " ";+ chars[i + 1] = " ";+ i++;+ } else if (ch === "$" && chars[i + 1] === "(") {+ // Command substitution inside double quotes still executes; keep it live.+ let depth = 0;+ let j = i;+ for (; j < chars.length; j++) {+ if (chars[j] === "(") depth++;+ else if (chars[j] === ")") {+ depth--;+ if (depth === 0) break;+ }+ }+ i = j - 1;+ } else if (ch === "`") {+ // Backtick substitution inside double quotes still executes; keep it live.+ let j = i + 1;+ while (j < chars.length && chars[j] !== "`") j++;+ i = j - 1;+ } else {+ chars[i] = " ";+ }+ }+ return chars.join("");+}++export function findDestructiveGitDiscardCommands(command: string): number[] {+ const masked = maskQuotedSpans(command);+ const indices: number[] = [];+ for (const pattern of [DISCARD_CHECKOUT_PATTERN, DISCARD_RESTORE_PATTERN, DISCARD_RESET_PATTERN]) {+ for (const match of masked.matchAll(pattern)) indices.push(match.index);+ }+ for (const match of masked.matchAll(DISCARD_CLEAN_PATTERN)) {+ if (isForcedCleanSegment(match[1])) indices.push(match.index);+ }+ return indices.sort((a, b) => a - b);+}++export function isDestructiveGitDiscardCommand(command: string): boolean {+ return findDestructiveGitDiscardCommands(command).length > 0;+}++/**+ * Where a discard command's probe must run: `cd` chains earlier in the command+ * and `git -C <dir>` on the discard invocation itself both relocate the+ * repository being discarded, so the probe follows them instead of assuming+ * the tool cwd.+ */+export interface DiscardProbeTarget {+ /** Shell prefix relocating the probe, for example `cd sub && `. */+ relocationPrefix?: string;+ /**+ * git status command for this discard: honors a `git -C` on the discard+ * invocation and includes ignored files when the discard deletes them+ * (git clean -x/-X).+ */+ gitStatusCommand: string;+}++/** The probe cannot safely determine the repository the discard targets. */+export const UNRESOLVABLE_DISCARD_TARGET = "unresolvable";++export function resolveDiscardProbeTarget(+ command: string,+ discardIndex: number,+ userCommandStart = 0,+): DiscardProbeTarget | typeof UNRESOLVABLE_DISCARD_TARGET | null {+ const prefix = command.slice(0, discardIndex);+ const invocation = command.slice(discardIndex);+ // A discard inside the configured command prefix would be replayed by the+ // probe itself; refuse instead of executing it during probing.+ if (userCommandStart > 0 && discardIndex < userCommandStart) return UNRESOLVABLE_DISCARD_TARGET;+ const tokens = invocation.split(/\s+/);++ // git -C <dir> (or repository-relocating global options) on the discard invocation itself.+ let dashCDir: string | undefined;+ let subcommandIndex = -1;+ for (const [index, token] of tokens.entries()) {+ if (index === 0) continue; // "git"+ if (token === "reset" || token === "checkout" || token === "clean" || token === "restore") {+ subcommandIndex = index;+ break;+ }+ if (token === "-C") {+ const dir = tokens[index + 1];+ // A quoted, escaped, or substituted path cannot be replayed as a single+ // token; refuse rather than probe a truncated or unset directory.+ if (!dir || /["'\\$`]/.test(dir)) return UNRESOLVABLE_DISCARD_TARGET;+ // Repeated -C paths are relative to the preceding one, so replay the+ // whole sequence instead of keeping only the last directory.+ dashCDir = dashCDir ? `${dashCDir} -C ${dir}` : dir;+ } else if (token.startsWith("--git-dir") || token.startsWith("--work-tree") || token.startsWith("--prefix")) {+ return UNRESOLVABLE_DISCARD_TARGET;+ } else if (token === "-c") {+ const config = tokens[index + 1];+ // core.worktree/core.bare relocate the repository the discard targets.+ if (config && /^core\.(worktree|bare)(=|$)/.test(config)) return UNRESOLVABLE_DISCARD_TARGET;+ }+ // Other flags do not relocate.+ }++ // git clean -x/-X also deletes ignored files, so its probe must include them.+ let cleanRemovesIgnored = false;+ if (subcommandIndex !== -1 && tokens[subcommandIndex] === "clean") {+ for (const token of tokens.slice(subcommandIndex + 1)) {+ if (token === "--") break; // everything after -- is a pathspec+ if (token.startsWith("--")) continue;+ if (token.startsWith("-") && /[xX]/.test(token.slice(1))) {+ cleanRemovesIgnored = true;+ break;+ }+ }+ }++ // Inline env assignments directly before the git invocation (for example+ // GIT_DIR=.../GIT_WORK_TREE=... git reset --hard) relocate the target+ // repository; replay them in the probe, or refuse when they cannot be.+ let envPrefix = "";+ const lastSegment = prefix.split(/&&|\|\||;|\||\n/).pop() ?? "";+ const leadingTokens = lastSegment.trim().split(/\s+/).filter(Boolean);+ for (const token of leadingTokens) {+ if (/^[A-Za-z_][A-Za-z0-9_]*=[^\s$`;&|()<>"]+$/.test(token)) continue; // replayable assignment+ // Wrappers that cannot change directory or select another repository.+ if (token === "sudo" || token === "env" || token === "command" || token === "builtin" || token.endsWith("/")) {+ continue;+ }+ return UNRESOLVABLE_DISCARD_TARGET;+ }+ const assignments = leadingTokens.filter((token) => token.includes("="));+ if (assignments.length > 0) envPrefix = `${assignments.join(" ")} `;++ // cd relocations earlier in the command. cds inside grouping parentheses or+ // command substitutions do not persist: they only matter when the discard+ // itself runs inside the still-open group, tracked via paren depth. Segments+ // before userCommandStart belong to the configured command prefix, which the+ // probe already replays verbatim, so their cds are not re-applied.+ const persistentCdArgs: string[] = [];+ const groupedCdArgs: string[] = [];+ let sawCd = false;+ let parenDepth = 0;+ let cdPendingSeparator = false;+ if (/\b(cd|pushd)\b/.test(prefix) || prefix.includes("(")) {+ let offset = 0;+ for (const part of prefix.split(/(&&|\|\||;|\||\n)/)) {+ const start = offset;+ offset += part.length;+ if (start < userCommandStart) continue; // command-prefix region: replayed as-is+ const separator = part === "&&" || part === "||" || part === ";" || part === "|" || part === "\n";+ if (separator) {+ if (cdPendingSeparator && (part === ";" || part === "\n")) {+ // The discard's directory depends on the cd succeeding; refuse+ // instead of probing only one of the two outcomes.+ return UNRESOLVABLE_DISCARD_TARGET;+ }+ if (part === "||" || part === "|") {+ if (sawCd) return UNRESOLVABLE_DISCARD_TARGET; // cd success no longer guaranteed+ continue;+ }+ cdPendingSeparator = false;+ continue;+ }+ const trimmed = part.trim();+ const opens = part.match(/\(/g)?.length ?? 0;+ const closes = part.match(/\)/g)?.length ?? 0;+ const insideGroup = parenDepth > 0 || opens > 0;+ parenDepth = Math.max(0, parenDepth + opens - closes);+ if (insideGroup) {+ const groupCd = /^cd\s*(.*)$/.exec(trimmed.replace(/^[(\s]+/, "").replace(/[)\s]+$/, ""));+ if (groupCd) {+ const arg = groupCd[1].trim();+ if (!arg || /[$`;&|()<>#"]/.test(arg)) return UNRESOLVABLE_DISCARD_TARGET;+ sawCd = true;+ cdPendingSeparator = true;+ groupedCdArgs.push(arg);+ } else if (/\b(cd|pushd)\b/.test(trimmed)) {+ return UNRESOLVABLE_DISCARD_TARGET; // group content we cannot replay+ }+ // A closed group's cds do not persist and must not leak into a+ // later still-open group's chain.+ if (parenDepth === 0) groupedCdArgs.length = 0;+ continue;+ }+ if (trimmed === "pushd" || trimmed.startsWith("pushd ")) return UNRESOLVABLE_DISCARD_TARGET;+ const cdMatch = /^cd\s*(.*)$/.exec(trimmed);+ if (!cdMatch) {+ cdPendingSeparator = false;+ continue; // not a cd: cannot change cwd+ }+ const arg = cdMatch[1].trim();+ // An arg we cannot replay safely (substitution, redirection, backgrounding,+ // comments, or quotes split by segmenting) leaves the target repository+ // unknown; refuse rather than probe blindly.+ const balanced = (arg.match(/"/g)?.length ?? 0) % 2 === 0 && (arg.match(/'/g)?.length ?? 0) % 2 === 0;+ if (!balanced || (arg && /[$`;&|()<>#]/.test(arg))) return UNRESOLVABLE_DISCARD_TARGET;+ sawCd = true;+ cdPendingSeparator = true;+ persistentCdArgs.push(arg);+ }+ }+ // When the discard runs inside a still-open group, its directory is the+ // persistent cd chain inherited by the group plus the group's own cds;+ // otherwise only persistent cds apply.+ const cdArgs = parenDepth > 0 ? [...persistentCdArgs, ...groupedCdArgs] : persistentCdArgs;++ if (cdArgs.length === 0 && dashCDir === undefined && !cleanRemovesIgnored && !envPrefix) return null;+ const ignored = cleanRemovesIgnored ? " --ignored=matching" : "";+ const cdPrefix = cdArgs.length > 0 ? `${cdArgs.map((arg) => (arg ? `cd ${arg}` : "cd")).join(" && ")} && ` : "";+ return {+ relocationPrefix: `${cdPrefix}${envPrefix}` || undefined,+ gitStatusCommand: `${dashCDir ? `git -C ${dashCDir} ` : "git "}status --porcelain --untracked-files=all${ignored}`,+ };+}++function isTruthyEnvValue(value: string | undefined): boolean {+ return value !== undefined && value !== "" && value !== "0";+}++/**+ * Probe for at-risk files via `git status --porcelain --untracked-files=all`+ * (plus `--ignored=matching` when the discard deletes ignored files) in the+ * command's cwd. Returns null when dirtiness cannot be determined (not a+ * repo, git missing, probe failure) so the guard fails open instead of+ * blocking on a guess.+ */+async function probeUncommittedChanges(+ ops: BashOperations,+ probeCommand: string,+ cwd: string,+ env: NodeJS.ProcessEnv,+ signal: AbortSignal | undefined,+ timeout: number | undefined,+): Promise<string[] | null> {+ let output = "";+ try {+ const result = await ops.exec(probeCommand, cwd, {+ onData: (data) => {+ output += data.toString("utf8");+ },+ signal,+ timeout,+ env,+ });+ if (result.exitCode !== 0) return null;+ } catch (err) {+ if (err instanceof Error && err.message === "aborted") throw err;+ return null;+ }+ return output+ .split("\n")+ .filter((line) => line.trim().length > 0)+ .map((line) => line.replace(/\r$/, ""));+}++function formatDirtyTreeRefusal(dirtyPaths: string[], includesIgnoredFiles = false): string {+ const listed = dirtyPaths.slice(0, MAX_DIRTY_PATHS_LISTED);+ const elided = dirtyPaths.length - listed.length;+ const noun = includesIgnoredFiles ? "uncommitted or ignored file(s)" : "uncommitted change(s)";+ const lines = [+ `Refusing to run this destructive git command: the working tree has ${dirtyPaths.length} ${noun}.`,+ ...listed.map((line) => ` ${line}`),+ ];+ if (elided > 0) lines.push(` ... and ${elided} more`);+ lines.push("");+ lines.push("Commit, stash, or stage your work first.");+ lines.push(+ `To discard these changes intentionally, retry with allowDestructiveGit: true, or set ${BASH_DESTRUCTIVE_GIT_BYPASS_ENV}=1.`,+ );+ return lines.join("\n");+}++function formatRelocationRefusal(): string {+ return [+ "Refusing to run this destructive git command: it changes directory (or repository) first, and the uncommitted changes of the repository it targets cannot be checked safely.",+ "",+ `Run the discard as its own command from the target directory, or retry with allowDestructiveGit: true, or set ${BASH_DESTRUCTIVE_GIT_BYPASS_ENV}=1.`,+ ].join("\n");+}+const BASH_PREVIEW_LINES = 5;const BASH_UPDATE_THROTTLE_MS = 100;@@ -279,18 +648,78 @@ export function createBashToolDefinition(const definition: ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> = {name: "bash",label: "bash",- description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,+ description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. Destructive git discard commands (git checkout -- ., git checkout ., git clean -f..., git reset --hard, git restore .) are refused while uncommitted changes exist; retry with allowDestructiveGit: true only when the discard is intentional.`,promptSnippet: "Execute bash commands (ls, grep, find, etc.)",parameters: bashSchema,async execute(_toolCallId,- { command, timeout }: { command: string; timeout?: number },+ {+ command,+ timeout,+ allowDestructiveGit,+ }: { command: string; timeout?: number; allowDestructiveGit?: boolean },signal?: AbortSignal,onUpdate?,_ctx?,) {const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;const spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook);+ // Refuse destructive git discard commands while the tree is dirty;+ // bypass with allowDestructiveGit or the PI_BASH_ALLOW_DESTRUCTIVE_GIT+ // env var. The pattern check is string-only and the probe runs only+ // on a match, so clean runs pay nothing.+ // Match and resolve the pre-hook command so probe construction stays+ // aligned with the command prefix; the probe itself goes through the+ // spawn hook like the guarded command does.+ const discardIndices = findDestructiveGitDiscardCommands(resolvedCommand);+ if (+ discardIndices.length > 0 &&+ allowDestructiveGit !== true &&+ !isTruthyEnvValue(spawnContext.env[BASH_DESTRUCTIVE_GIT_BYPASS_ENV])+ ) {+ // Probe the repository each discard actually targets: follow cd+ // chains and git -C, refuse when the target cannot be resolved+ // safely, and run the probe through the same spawn hook as the+ // discard so hook-provided shell setup applies to both.+ const probes: Array<{ context: BashSpawnContext; includesIgnoredFiles: boolean }> = [];+ const seenProbes = new Set<string>();+ const userCommandStart = commandPrefix ? commandPrefix.length + 1 : 0;+ for (const index of discardIndices) {+ const target = resolveDiscardProbeTarget(resolvedCommand, index, userCommandStart);+ if (target === UNRESOLVABLE_DISCARD_TARGET) {+ throw new Error(formatRelocationRefusal());+ }+ const relocationPrefix = target?.relocationPrefix ?? "";+ const gitStatus = target?.gitStatusCommand ?? GIT_STATUS_PORCELAIN_COMMAND;+ const rawProbe = commandPrefix+ ? `${commandPrefix}\n${relocationPrefix}${gitStatus}`+ : `${relocationPrefix}${gitStatus}`;+ // Resolve the probe from the original cwd so hook transforms (for+ // example a sandbox cwd remap) apply once, not to the already+ // remapped context of the guarded command.+ const context = resolveSpawnContext(rawProbe, cwd, spawnHook);+ const key = `${context.command}\u0000${context.cwd}`;+ if (seenProbes.has(key)) continue;+ seenProbes.add(key);+ probes.push({+ context,+ includesIgnoredFiles: gitStatus.includes("--ignored=matching"),+ });+ }+ for (const probe of probes) {+ const dirtyPaths = await probeUncommittedChanges(+ ops,+ probe.context.command,+ probe.context.cwd,+ probe.context.env,+ signal,+ timeout,+ );+ if (dirtyPaths && dirtyPaths.length > 0) {+ throw new Error(formatDirtyTreeRefusal(dirtyPaths, probe.includesIgnoredFiles));+ }+ }+ }const output = new OutputAccumulator({ tempFilePrefix: "pi-bash" });let updateTimer: NodeJS.Timeout | undefined;let updateDirty = false;diff --git a/packages/coding-agent/test/bash-destructive-git-guard.test.ts b/packages/coding-agent/test/bash-destructive-git-guard.test.tsnew file mode 100644index 0000000000..72035d5fa2--- /dev/null+++ b/packages/coding-agent/test/bash-destructive-git-guard.test.ts@@ -0,0 +1,813 @@+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ BASH_DESTRUCTIVE_GIT_BYPASS_ENV,+ type BashOperations,+ createBashTool,+ isDestructiveGitDiscardCommand,+} from "../src/core/tools/bash.js";++function runGit(cwd: string, ...args: string[]): void {+ execFileSync("git", args, { cwd, stdio: ["ignore", "ignore", "pipe"] });+}++/** Create a git repository with one committed file plus two uncommitted changes. */+function initDirtyGitRepo(root: string): void {+ runGit(root, "init");+ runGit(root, "config", "user.email", "[email protected]");+ runGit(root, "config", "user.name", "Test");+ runGit(root, "config", "commit.gpgsign", "false");+ writeFileSync(join(root, "tracked.txt"), "committed\n");+ runGit(root, "add", "tracked.txt");+ runGit(root, "commit", "-m", "init");+ writeFileSync(join(root, "tracked.txt"), "modified\n");+ writeFileSync(join(root, "untracked.txt"), "uncommitted\n");+}++describe("isDestructiveGitDiscardCommand", () => {+ it.each([+ "git checkout -- .",+ "git checkout .",+ "git checkout HEAD -- .",+ "git restore .",+ "git restore --source=HEAD~1 .",+ "git clean -f",+ "git clean -fd",+ "git clean -fdx",+ "git clean --force",+ "git reset --hard",+ "git reset --hard HEAD~1",+ "git checkout -b tmp 2>/dev/null; git checkout -- .",+ "git checkout main && git reset --hard",+ "echo start\ngit clean -fd",+ "npm test & git clean -fd &",+ "git checkout :/",+ "git checkout -- :/",+ "git checkout HEAD -- :/",+ "git restore :/",+ "git restore -s@ .",+ "git restore -s@ :/",+ "git restore --source=HEAD :/",+ "git restore -s HEAD~1 :/",+ "git restore -- .",+ "git checkout -- ./",+ "git checkout ./",+ "git restore ./",+ "git -C sub reset --hard",+ "git --git-dir=sub/.git reset --hard",+ "git reset -q --hard",+ "git reset --no-refresh --hard",+ "git -C repo -C nested reset --hard",+ "GIT_DIR=sub/.git git reset --hard",+ "GIT_DIR=sub/.git GIT_WORK_TREE=sub git reset --hard",+ "git checkout -f -- .",+ "git checkout --theirs -- .",+ "git checkout -m .",+ "git checkout --conflict=diff3 .",+ "git checkout HEAD .",+ "git checkout HEAD~1 -- .",+ "git checkout origin/main .",+ "git checkout -f main",+ "git checkout --force main",+ "git clean -f -- -n",+ ])("matches %s", (command) => {+ expect(isDestructiveGitDiscardCommand(command)).toBe(true);+ });++ it.each([+ "git status",+ "git log --oneline",+ "git checkout -b new-branch",+ "git checkout main",+ "git checkout -m main",+ "git checkout -b newbranch .",+ "git checkout -- single-file.txt",+ "echo 'git reset --hard'",+ 'git commit -m "git reset --hard"',+ 'echo "git clean -fd"',+ "echo preparing # git reset --hard",+ "git checkout ./nested",+ "git restore --staged .",+ "git restore --staged :/",+ "git restore single-file.txt",+ "git clean -n",+ "git clean -n -f .",+ "git clean --dry-run",+ "git clean -d",+ "git reset",+ "git reset --soft HEAD~1",+ "git stash",+ "git add .",+ "echo hello world",+ "npm run check",+ ])("does not match %s", (command) => {+ expect(isDestructiveGitDiscardCommand(command)).toBe(false);+ });+});++describe("bash tool destructive-git dirty-tree guard", () => {+ let testDir: string;++ beforeEach(() => {+ testDir = join(tmpdir(), `bash-git-guard-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ mkdirSync(testDir, { recursive: true });+ });++ afterEach(() => {+ delete process.env[BASH_DESTRUCTIVE_GIT_BYPASS_ENV];+ rmSync(testDir, { recursive: true, force: true });+ });++ it.each(["git checkout -- .", "git checkout .", "git clean -fd", "git reset --hard", "git restore ."])(+ "refuses %s on a dirty tree and preserves the work",+ async (command) => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ await expect(bash.execute(`guard-${command}`, { command })).rejects.toThrow(+ /Refusing to run this destructive git command/,+ );++ expect(readModifiedTracked()).toBe("modified\n");+ expect(existsSync(join(testDir, "untracked.txt"))).toBe(true);+ },+ );++ it("lists the dirty paths and both bypasses in the refusal", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-refusal-text", { command: "git checkout -- ." })+ .catch((err: Error) => err);++ expect(error).toBeInstanceOf(Error);+ const message = (error as Error).message;+ expect(message).toContain("2 uncommitted change(s)");+ expect(message).toContain("tracked.txt");+ expect(message).toContain("untracked.txt");+ expect(message).toContain("allowDestructiveGit: true");+ expect(message).toContain(BASH_DESTRUCTIVE_GIT_BYPASS_ENV);+ });++ it("elides long dirty path lists", async () => {+ initDirtyGitRepo(testDir);+ for (let i = 0; i < 12; i++) writeFileSync(join(testDir, `extra-${i}.txt`), "x\n");+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-elide", { command: "git checkout -- ." }).catch((err: Error) => err);+ const message = (error as Error).message;++ expect(message).toContain("... and 4 more");+ });++ it("runs the discard without a probe when the tree is clean", async () => {+ initDirtyGitRepo(testDir);+ runGit(testDir, "add", "-A");+ runGit(testDir, "commit", "-m", "second");+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-clean", { command: "git checkout -- ." })).resolves.toBeDefined();+ });++ it("bypasses the guard with allowDestructiveGit: true and discards", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ await expect(+ bash.execute("guard-bypass-arg", { command: "git reset --hard", allowDestructiveGit: true }),+ ).resolves.toBeDefined();++ expect(readModifiedTracked()).toBe("committed\n");+ });++ it(`bypasses the guard with ${BASH_DESTRUCTIVE_GIT_BYPASS_ENV}=1`, async () => {+ initDirtyGitRepo(testDir);+ process.env[BASH_DESTRUCTIVE_GIT_BYPASS_ENV] = "1";+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-bypass-env", { command: "git reset --hard" })).resolves.toBeDefined();++ expect(readModifiedTracked()).toBe("committed\n");+ });++ it("fails open outside a git repository", async () => {+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-no-repo", { command: "git checkout -- ." }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).not.toMatch(/Refusing to run/);+ });++ it("runs no probe for non-discard commands", async () => {+ initDirtyGitRepo(testDir);+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ await bash.execute("guard-no-probe", { command: "echo hi" });++ expect(calls).toEqual(["echo hi"]);+ });++ it("fails open when the probe itself fails", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, { onData }) => {+ calls.push(command);+ if (command === "git status --porcelain --untracked-files=all") {+ onData(Buffer.from("fatal: not a git repository\n", "utf8"));+ return { exitCode: 128 };+ }+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ await expect(bash.execute("guard-probe-fail", { command: "git checkout -- ." })).resolves.toBeDefined();+ expect(calls).toEqual(["git status --porcelain --untracked-files=all", "git checkout -- ."]);+ });++ it("prepends the command prefix to the probe for shell-setup parity", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { commandPrefix: "export GUARD_TEST_VAR=1", operations });++ await expect(bash.execute("guard-prefix", { command: "git checkout -- ." })).resolves.toBeDefined();++ expect(calls).toEqual([+ "export GUARD_TEST_VAR=1\ngit status --porcelain --untracked-files=all",+ "export GUARD_TEST_VAR=1\ngit checkout -- .",+ ]);+ });++ it("follows cd relocations: refuses a discard in a dirty nested repository", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-cd-dirty", { command: "cd sub && git reset --hard" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ const message = (error as Error).message;+ expect(message).toMatch(/Refusing to run this destructive git command/);+ expect(message).toContain("tracked.txt");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("follows git -C relocations: refuses a discard in a dirty nested repository", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-git-c-dirty", { command: "git -C sub reset --hard" })).rejects.toThrow(+ /tracked\.txt/,+ );+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("allows a relocated discard when the target repository is clean", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ runGit(sub, "add", "-A");+ runGit(sub, "commit", "-m", "second");+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-cd-clean", { command: "cd sub && git reset --hard" })).resolves.toBeDefined();+ });++ it("probes every discarded repository in multi-discard commands", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ await expect(+ bash.execute("guard-multi-discard", { command: "git checkout -- . && cd sub && git reset --hard" }),+ ).rejects.toThrow(/Refusing to run this destructive git command/);+ });++ it("conservatively refuses relocations it cannot replay safely", async () => {+ const bash = createBashTool(testDir);++ for (const command of [+ "cd $(pwd)/sub && git reset --hard",+ "git --git-dir=sub/.git reset --hard",+ "cd sub || git reset --hard",+ "pushd sub && git reset --hard",+ ]) {+ const error = await bash.execute(`guard-unresolvable`, { command }).then(+ () => undefined,+ (err: Error) => err,+ );+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("changes directory (or repository) first");+ }+ });++ it("replays cd chains in the probe", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ await bash.execute("guard-cd-chain", { command: "cd a && cd b && git checkout -- ." });++ expect(calls).toEqual([+ "cd a && cd b && git status --porcelain --untracked-files=all",+ "cd a && cd b && git checkout -- .",+ ]);+ });++ it("replays git -C in the probe", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ await bash.execute("guard-git-c-probe", { command: "git -C sub reset --hard" });++ expect(calls).toEqual(["git -C sub status --porcelain --untracked-files=all", "git -C sub reset --hard"]);+ });++ it("runs the probe through the spawn hook like the discard itself", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, {+ operations,+ spawnHook: (ctx) => ({ ...ctx, command: `source ~/.profile\n${ctx.command}` }),+ });++ await bash.execute("guard-hook", { command: "git checkout -- ." });++ expect(calls).toEqual([+ "source ~/.profile\ngit status --porcelain --untracked-files=all",+ "source ~/.profile\ngit checkout -- .",+ ]);+ });++ it("refuses git reset -q --hard on a dirty tree", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-reset-q", { command: "git reset -q --hard" })).rejects.toThrow(+ /Refusing to run this destructive git command/,+ );+ });++ it("refuses git clean -fx when ignored files would be deleted, and lists them", async () => {+ initDirtyGitRepo(testDir);+ runGit(testDir, "add", "-A");+ runGit(testDir, "commit", "-m", "second");+ writeFileSync(join(testDir, ".gitignore"), "ignored.txt\n");+ runGit(testDir, "add", ".gitignore");+ runGit(testDir, "commit", "-m", "gitignore");+ writeFileSync(join(testDir, "ignored.txt"), "generated\n");+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-clean-x", { command: "git clean -fx" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ const message = (error as Error).message;+ expect(message).toContain("uncommitted or ignored file(s)");+ expect(message).toContain("ignored.txt");+ expect(existsSync(join(testDir, "ignored.txt"))).toBe(true);+ });++ it("allows git clean -f when only ignored files exist", async () => {+ initDirtyGitRepo(testDir);+ runGit(testDir, "add", "-A");+ runGit(testDir, "commit", "-m", "second");+ writeFileSync(join(testDir, ".gitignore"), "ignored.txt\n");+ runGit(testDir, "add", ".gitignore");+ runGit(testDir, "commit", "-m", "gitignore");+ writeFileSync(join(testDir, "ignored.txt"), "generated\n");+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-clean-f", { command: "git clean -f" })).resolves.toBeDefined();+ });++ it("detects untracked files even when status.showUntrackedFiles=no is configured", async () => {+ initDirtyGitRepo(testDir);+ runGit(testDir, "add", "-A");+ runGit(testDir, "commit", "-m", "second");+ writeFileSync(join(testDir, "fresh-untracked.txt"), "new\n");+ runGit(testDir, "config", "status.showUntrackedFiles", "no");+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-untracked-config", { command: "git clean -fd" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("fresh-untracked.txt");+ expect(existsSync(join(testDir, "fresh-untracked.txt"))).toBe(true);+ });++ it("replays repeated git -C options against the chained target repository", async () => {+ const nested = join(testDir, "repo", "nested");+ mkdirSync(nested, { recursive: true });+ initDirtyGitRepo(nested);+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-git-c-chain", { command: "git -C repo -C nested reset --hard" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect(readFileSync(join(nested, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("replays inline GIT_DIR/GIT_WORK_TREE assignments against the targeted repository", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-git-dir", { command: "GIT_DIR=sub/.git GIT_WORK_TREE=sub git reset --hard" })+ .then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("conservatively refuses assignments it cannot replay safely", async () => {+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-git-dir-subst", { command: "GIT_DIR=$(pwd)/sub/.git git reset --hard" })+ .then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("changes directory (or repository) first");+ });++ it("refuses git checkout -f -- . on a dirty tree", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-checkout-f", { command: "git checkout -f -- ." })).rejects.toThrow(+ /Refusing to run this destructive git command/,+ );+ expect(readModifiedTracked()).toBe("modified\n");+ });++ it("refuses git clean -f -- -n, where -n is a pathspec, not a dry run", async () => {+ initDirtyGitRepo(testDir);+ writeFileSync(join(testDir, "-n"), "pathspec\n");+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-clean-pathspec", { command: "git clean -f -- -n" })).rejects.toThrow(+ /Refusing to run this destructive git command/,+ );+ expect(existsSync(join(testDir, "-n"))).toBe(true);+ });++ it("conservatively refuses quoted git -C directories", async () => {+ const sub = join(testDir, "dirty repo");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-git-c-quoted", { command: 'git -C "dirty repo" reset --hard' }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("changes directory (or repository) first");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("conservatively refuses substituted git -C directories", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-git-c-var", { command: "repo=sub && git -C $repo reset --hard" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("changes directory (or repository) first");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("guards path-qualified and sudo git discards without treating them as relocations", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ for (const command of ["/usr/bin/git reset --hard", "sudo git reset --hard"]) {+ const error = await bash+ .execute(`guard-wrapper-${command.startsWith("/") ? "path" : "sudo"}`, { command })+ .then(+ () => undefined,+ (err: Error) => err,+ );+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toMatch(/uncommitted change\(s\)/);+ }+ expect(readModifiedTracked()).toBe("modified\n");+ });++ it("probes cd relocations followed by unrelated grouped segments", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-cd-then-group", { command: "cd sub && (echo hi) && git reset --hard" })+ .then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("ignores cds in groups that close before the discard and probes the real directory", async () => {+ initDirtyGitRepo(testDir);+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ runGit(sub, "add", "-A");+ runGit(sub, "commit", "-m", "second");+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-closed-group", { command: "(echo hi && cd sub && echo done) && git reset --hard" })+ .then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect((error as Error).message).toContain("uncommitted change(s)");+ expect(readModifiedTracked()).toBe("modified\n");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("replays in-group cds when the discard runs inside the group", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir);++ const error = await bash.execute("guard-open-group", { command: "(cd sub && git reset --hard)" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("inherits persistent cds into open groups for the probe", async () => {+ const nested = join(testDir, "sub", "nested");+ mkdirSync(nested, { recursive: true });+ initDirtyGitRepo(nested);+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-inherited-group", { command: "cd sub && (cd nested && git reset --hard)" })+ .then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect(readFileSync(join(nested, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("applies cwd remapping hooks once to the probe", async () => {+ const calls: Array<{ command: string; cwd: string }> = [];+ const operations: BashOperations = {+ exec: async (command, cwd, _options) => {+ calls.push({ command, cwd });+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, {+ operations,+ spawnHook: (ctx) => ({ ...ctx, cwd: `${ctx.cwd}/remapped` }),+ });++ await bash.execute("guard-hook-cwd", { command: "git checkout -- ." });++ expect(calls.map((call) => call.cwd)).toEqual([`${testDir}/remapped`, `${testDir}/remapped`]);+ });++ it("executes harmless commands that merely quote a discard command", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ const result = await bash.execute("guard-quoted-echo", { command: "echo 'git reset --hard'" });+ expect((result.content?.[0] as { text?: string } | undefined)?.text).toContain("git reset --hard");+ expect(readModifiedTracked()).toBe("modified\n");+ });++ it("passes the tool timeout to the probe and fails open on probe timeouts", async () => {+ const calls: Array<{ command: string; timeout?: number }> = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, options) => {+ calls.push({ command, timeout: options.timeout });+ if (command.startsWith("git status")) throw new Error("timeout:5");+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ const result = await bash.execute("guard-probe-timeout", { command: "git checkout -- .", timeout: 5 });++ expect(result).toBeDefined();+ expect(calls[0]).toEqual({ command: "git status --porcelain --untracked-files=all", timeout: 5 });+ });++ it("refuses forced branch checkouts on a dirty tree", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-checkout-f-branch", { command: "git checkout -f main" })).rejects.toThrow(+ /Refusing to run this destructive git command/,+ );+ expect(readModifiedTracked()).toBe("modified\n");+ });++ it("guards discards executed through command substitution inside double quotes", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ await expect(bash.execute("guard-substitution-echo", { command: 'echo "$(git reset --hard)"' })).rejects.toThrow(+ /Refusing to run this destructive git command/,+ );+ expect(readModifiedTracked()).toBe("modified\n");+ });++ it("conservatively refuses cds joined to the discard by ; or a newline", async () => {+ const bash = createBashTool(testDir);++ for (const command of ["cd /does/not/exist; git reset --hard", "cd sub\ngit reset --hard"]) {+ const error = await bash.execute("guard-conditional-cd", { command }).then(+ () => undefined,+ (err: Error) => err,+ );+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("changes directory (or repository) first");+ }+ });++ it("applies prefix cds once in the probe and probes the prefix directory", async () => {+ const sub = join(testDir, "sub");+ mkdirSync(sub);+ initDirtyGitRepo(sub);+ const bash = createBashTool(testDir, { commandPrefix: "cd sub" });++ const error = await bash.execute("guard-prefix-cd", { command: "git reset --hard" }).then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("tracked.txt");+ expect(readFileSync(join(sub, "tracked.txt"), "utf-8")).toBe("modified\n");+ });++ it("records the prefix cd probe without duplication", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { commandPrefix: "cd sub", operations });++ await bash.execute("guard-prefix-cd-record", { command: "git checkout -- ." });++ expect(calls).toEqual(["cd sub\ngit status --porcelain --untracked-files=all", "cd sub\ngit checkout -- ."]);+ });++ it("conservatively refuses relocating git -c config keys", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ const error = await bash+ .execute("guard-c-core-worktree", { command: "git -c core.worktree=/other/tree reset --hard" })+ .then(+ () => undefined,+ (err: Error) => err,+ );++ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain("changes directory (or repository) first");+ });++ it("executes commands whose discard text sits in a comment", async () => {+ initDirtyGitRepo(testDir);+ const bash = createBashTool(testDir);++ const result = await bash.execute("guard-comment", { command: "echo preparing # git reset --hard" });+ expect((result.content?.[0] as { text?: string } | undefined)?.text).toContain("preparing");+ expect(readModifiedTracked()).toBe("modified\n");+ });++ it("refuses destructive command prefixes instead of probing them", async () => {+ const bash = createBashTool(testDir, { commandPrefix: "git clean -fd" });++ await expect(bash.execute("guard-prefix-discard", { command: "echo hi" })).rejects.toThrow(+ /changes directory \(or repository\) first/,+ );+ });++ it("drops closed-group cds from later open groups' probe chains", async () => {+ const calls: string[] = [];+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ calls.push(command);+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ await bash.execute("guard-group-leak", { command: "(cd a) && (cd b && git reset --hard)" });++ expect(calls).toEqual([+ "cd b && git status --porcelain --untracked-files=all",+ "(cd a) && (cd b && git reset --hard)",+ ]);+ });++ it("propagates aborts raised while probing", async () => {+ const operations: BashOperations = {+ exec: async (command, _cwd, _options) => {+ if (command === "git status --porcelain --untracked-files=all") throw new Error("aborted");+ return { exitCode: 0 };+ },+ };+ const bash = createBashTool(testDir, { operations });++ await expect(bash.execute("guard-abort", { command: "git checkout -- ." })).rejects.toThrow("aborted");+ });++ function readModifiedTracked(): string {+ return readFileSync(join(testDir, "tracked.txt"), "utf-8");+ }+});