feat(guardrails): block destructive git commands (bash_destructive_git) #116

Merged
alee merged 7 commits from feat/guardrails-destructive-git into main 2026-10-18 01:26:53 +00:00
8 changed files with 837 additions and 5 deletions

View File

@@ -14,7 +14,7 @@ import { Guardrails } from "./guardrails.js";
*/ */
/** Rule IDs that go in the "Always-Scope" table (always fire regardless of boulder). */ /** Rule IDs that go in the "Always-Scope" table (always fire regardless of boulder). */
const ALWAYS_RULES = new Set(["bash_banned", "bash_protected_port"]); const ALWAYS_RULES = new Set(["bash_banned", "bash_protected_port", "bash_destructive_git"]);
/** Flush a file path to ensure disk sync. */ /** Flush a file path to ensure disk sync. */
function _fsync(path) { function _fsync(path) {
@@ -75,6 +75,7 @@ async function main() {
write_outside_worktree: "block", write_outside_worktree: "block",
bash_main_checkout: "block", bash_main_checkout: "block",
bash_banned: "block", bash_banned: "block",
bash_destructive_git: "block",
bash_protected_port: "block", bash_protected_port: "block",
plan_tick_gate: "block", plan_tick_gate: "block",
}, },

View File

@@ -372,6 +372,7 @@ describe("guardrails-replay R19 tests", () => {
const alwaysBlock = firstSectionEnd > 0 ? alwaysSection.slice(0, firstSectionEnd) : alwaysSection; const alwaysBlock = firstSectionEnd > 0 ? alwaysSection.slice(0, firstSectionEnd) : alwaysSection;
assert.ok(alwaysBlock.includes("bash_banned"), "Always table should contain bash_banned"); assert.ok(alwaysBlock.includes("bash_banned"), "Always table should contain bash_banned");
assert.ok(alwaysBlock.includes("bash_protected_port"), "Always table should contain bash_protected_port"); assert.ok(alwaysBlock.includes("bash_protected_port"), "Always table should contain bash_protected_port");
assert.ok(alwaysBlock.includes("bash_destructive_git"), "Always table should contain bash_destructive_git");
// (B) table: scoped rules that fire from the fixture. // (B) table: scoped rules that fire from the fixture.
// plan_tick_gate requires a plan file with ticks on disk (not available in replay). // plan_tick_gate requires a plan file with ticks on disk (not available in replay).

View File

@@ -45,6 +45,7 @@ const EXAMPLE_CONFIG = {
write_outside_worktree: "block", write_outside_worktree: "block",
bash_main_checkout: "block", bash_main_checkout: "block",
bash_banned: "block", bash_banned: "block",
bash_destructive_git: "block",
bash_protected_port: "block", bash_protected_port: "block",
plan_tick_gate: "block", plan_tick_gate: "block",
}, },
@@ -240,7 +241,7 @@ describe("Acceptance probes (every rule at default, real hook shape)", () => {
writeConfig(dir, EXAMPLE_CONFIG); writeConfig(dir, EXAMPLE_CONFIG);
const hooks = await Guardrails({ client: realClient(), directory: dir }); const hooks = await Guardrails({ client: realClient(), directory: dir });
await hookDrive(hooks, "bash", SESSION, { command: "ls" }); await hookDrive(hooks, "bash", SESSION, { command: "ls" });
// No throw → ALLOW // No throw -> ALLOW
}); });
it("task with category:quick and correct WORKTREE line → ALLOW", async () => { it("task with category:quick and correct WORKTREE line → ALLOW", async () => {
@@ -697,6 +698,71 @@ describe("bash_protected_port (R5c)", () => {
}); });
}); });
describe("bash_destructive_git -- hook-level (always-scope)", () => {
const SESSION = "ses_bdg";
it("positive: git reset --hard origin/main -> BLOCK (no boulder needed)", async () => {
const dir = newDir();
writeConfig(dir, EXAMPLE_CONFIG);
const hooks = await Guardrails({ client: realClient(), directory: dir });
await assert.rejects(
hookDrive(hooks, "bash", SESSION, {
command: "git reset --hard origin/main",
}),
(err) => {
assert.equal(err.ruleId, "bash_destructive_git");
return true;
},
);
});
it("warn mode: git reset --hard origin/main -> ALLOW and LOG", async () => {
const dir = newDir();
writeConfig(dir, {
...EXAMPLE_CONFIG,
rules: { ...EXAMPLE_CONFIG.rules, bash_destructive_git: "warn" },
});
const hooks = await Guardrails({ client: realClient(), directory: dir });
await hookDrive(hooks, "bash", SESSION, {
command: "git reset --hard origin/main",
});
const logContent = readFileSync(join(dir, ".omo/guardrails.log"), "utf-8");
assert.ok(
logContent.includes("bash_destructive_git"),
"log should contain bash_destructive_git",
);
});
it("off mode: git reset --hard origin/main -> ALLOW (no throw)", async () => {
const dir = newDir();
writeConfig(dir, {
...EXAMPLE_CONFIG,
rules: { ...EXAMPLE_CONFIG.rules, bash_destructive_git: "off" },
});
const hooks = await Guardrails({ client: realClient(), directory: dir });
await hookDrive(hooks, "bash", SESSION, {
command: "git reset --hard origin/main",
});
// No throw -> ALLOW
});
it("fires with NO boulder (always-scope, no boulder needed)", async () => {
const dir = newDir();
writeConfig(dir, EXAMPLE_CONFIG);
// No boulder written - always-scope rule fires regardless
const hooks = await Guardrails({ client: realClient(), directory: dir });
await assert.rejects(
hookDrive(hooks, "bash", SESSION, {
command: "git reset --hard origin/main",
}),
(err) => {
assert.equal(err.ruleId, "bash_destructive_git");
return true;
},
);
});
});
// =========================================================================== // ===========================================================================
// Tick gate — real scripts/verify_commit.py (only test that may use it) // Tick gate — real scripts/verify_commit.py (only test that may use it)
// =========================================================================== // ===========================================================================
@@ -770,7 +836,7 @@ describe("plan_tick_gate with real verify_commit.py", () => {
oldString: "- [ ] 1. do it", oldString: "- [ ] 1. do it",
newString: "- [x] 1. do it", newString: "- [x] 1. do it",
}); });
// No throw → ALLOW // No throw -> ALLOW
}); });
it("blocks tick when verify_commit fails (dirty tree)", async () => { it("blocks tick when verify_commit fails (dirty tree)", async () => {

View File

@@ -7,7 +7,8 @@
"bash_main_checkout": "block", "bash_main_checkout": "block",
"bash_banned": "block", "bash_banned": "block",
"bash_protected_port": "block", "bash_protected_port": "block",
"plan_tick_gate": "block" "plan_tick_gate": "block",
"bash_destructive_git": "block"
}, },
"log": ".omo/guardrails.log", "log": ".omo/guardrails.log",
"protected_ports": [8080], "protected_ports": [8080],

View File

@@ -48,6 +48,9 @@
* - bash_protected_port -- block curl/wget targeting protected ports * - bash_protected_port -- block curl/wget targeting protected ports
* regardless of boulder (always-scope, no boulder gate). * regardless of boulder (always-scope, no boulder gate).
* - plan_tick_gate -- refuse to tick a todo while verify_commit fails. * - plan_tick_gate -- refuse to tick a todo while verify_commit fails.
* - bash_destructive_git -- block destructive git commands (reset --hard,
* clean -f, checkout --force, branch -D, etc.)
* regardless of boulder (always-scope, no boulder gate).
* *
* Boulder v2 fields used: boulder.status, boulder.session_ids, * Boulder v2 fields used: boulder.status, boulder.session_ids,
* boulder.worktree_path. * boulder.worktree_path.
@@ -833,6 +836,252 @@ function _checkBashBanned(command) {
return null; return null;
} }
/**
* Check a command for destructive git commands.
*
* Returns {matched, desc} on violation, null if clean.
*
* Pipeline: split on delimiters => UNQUOTE (remove quotes, keep content) =>
* strip prefixes => match destructive git patterns.
*/
function _checkBashDestructiveGit(command) {
const segments = _splitSegments(command);
for (const seg of segments) {
const unquoted = _unquoteSegment(seg);
const bare = _stripPrefixes(unquoted);
if (bare) {
const result = _matchesDestructiveGit(bare);
if (result) return result;
}
}
return null;
}
/**
* Remove all quote characters and replace quoted content with the content
* itself (unquote). Unlike _stripQuotedStrings which replaces with spaces,
* this keeps the content visible so that quoted argument values (e.g.
* commit messages) participate in token-based matching.
*
* Preserves backslash-escaped quotes.
*/
function _unquoteSegment(s) {
return s.replace(/'[\s\S]*?'/g, (m) => m.replace(/'/g, ""))
.replace(/"[\s\S]*?"/g, (m) => m.replace(/"/g, ""))
.replace(/`[\s\S]*?`/g, (m) => m.replace(/`/g, ""));
}
/**
* Check if a short-flag cluster token contains a given letter.
* Short-flag clusters match /^-[A-Za-z]+$/ (e.g. "-fdx").
*/
function _hasShort(rest, letter) {
for (const t of rest) {
if (/^-[A-Za-z]+$/.test(t) && t.includes(letter)) return true;
}
return false;
}
/**
* Check if a token exactly matches --<name>.
*/
function _hasLong(rest, name) {
for (const t of rest) {
if (t === "--" + name) return true;
}
return false;
}
/**
* Token-based matcher for destructive git subcommand flags.
*
* Receives a segment that has already been prefix-stripped (no VAR=, env,
* sudo, command). Tokenises on whitespace, skips git global options
* (-C, -c, --git-dir, --work-tree, --namespace, --exec-path and other
* leading -x flags), identifies the subcommand, then scans the remaining
* tokens for destructive flag patterns per subcommand:
*
* reset --hard / --keep / --merge
* clean force (NOT dry-run)
* checkout force OR pathspec is "."
* switch force OR --discard-changes OR -C
* restore "." pathspec (UNLESS --staged+NOT--worktree) OR --staged+--worktree
* branch -D OR (--delete+--force) OR --force alone
* update-ref -d
* reflog expire / delete subcommand
* gc --prune=now
*
* Returns {matched, desc} or null.
*/
function _matchesDestructiveGit(bareSegment) {
if (!/^git\b/i.test(bareSegment.trim())) return null;
const tokens = bareSegment.trim().split(/\s+/);
let subcmd = null;
let subcmdIdx = -1;
// Skip git global options (-c, -C, --git-dir, --work-tree, --namespace,
// --exec-path, and any other leading -x flags)
for (let i = 1; i < tokens.length; i++) {
const t = tokens[i];
if (/^-/.test(t)) {
if (
(t.toLowerCase() === "-c") && i + 1 < tokens.length ||
t === "--git-dir" && i + 1 < tokens.length ||
t === "--work-tree" && i + 1 < tokens.length ||
t === "--namespace" && i + 1 < tokens.length ||
t === "--exec-path" && i + 1 < tokens.length ||
/^--\w+=/.test(t)
) {
i++;
}
continue;
}
subcmd = t;
subcmdIdx = i;
break;
}
if (!subcmd) return null;
// tokens after subcmd - used for rest
const rest = tokens.slice(subcmdIdx + 1);
// --- reset ---
if (subcmd.toLowerCase() === "reset") {
for (const t of rest) {
if (t === "--hard" || t === "--keep" || t === "--merge") {
return { matched: "reset", desc: "git reset --hard/--keep/--merge" };
}
}
}
// --- clean ---
if (subcmd.toLowerCase() === "clean") {
let hasForce = _hasShort(rest, "f") || _hasLong(rest, "force");
let hasDryRun = _hasShort(rest, "n") || _hasLong(rest, "dry-run");
if (hasForce && !hasDryRun) {
return { matched: "clean", desc: "git clean -f/--force" };
}
}
// --- checkout ---
if (subcmd.toLowerCase() === "checkout") {
let hasForce = _hasShort(rest, "f") || _hasShort(rest, "B") || _hasLong(rest, "force");
let dotPathspec = false;
let afterDashDash = false;
for (const t of rest) {
if (t === "--") { afterDashDash = true; continue; }
if (afterDashDash && t === ".") dotPathspec = true;
if (!afterDashDash && t === "." && rest.slice(rest.indexOf(t) + 1).length === 0) dotPathspec = true;
}
if (hasForce || dotPathspec) {
return { matched: "checkout", desc: "git checkout --force or pathspec \".\"" };
}
}
// --- switch ---
if (subcmd.toLowerCase() === "switch") {
let hasForce = _hasShort(rest, "f") || _hasLong(rest, "force") || _hasShort(rest, "C") || _hasLong(rest, "discard-changes");
if (hasForce) {
return { matched: "switch", desc: "git switch --force/--discard-changes/-C" };
}
}
// --- restore ---
if (subcmd.toLowerCase() === "restore") {
let hasStaged = false;
let hasWorktree = false;
let dotPathspec = false;
let afterDashDash = false;
for (const t of rest) {
if (t === "--") { afterDashDash = true; continue; }
if (t === "--staged") hasStaged = true;
if (t === "--worktree") hasWorktree = true;
if (afterDashDash && t === ".") dotPathspec = true;
if (!afterDashDash && t === "." && rest.slice(rest.indexOf(t) + 1).length === 0) dotPathspec = true;
}
// "." after -- or as only positional is destructive UNLESS --staged+NOT--worktree
if (dotPathspec && !(hasStaged && !hasWorktree)) {
return { matched: "restore", desc: "git restore --worktree (pathspec \".\")" };
}
// --staged + --worktree together is always destructive
if (hasStaged && hasWorktree) {
return { matched: "restore", desc: "git restore --staged --worktree" };
}
}
// --- branch ---
if (subcmd.toLowerCase() === "branch") {
if (_hasShort(rest, "D")) {
return { matched: "branch", desc: "git branch -D" };
}
let hasDelete = _hasShort(rest, "d") || _hasLong(rest, "delete");
let hasForce = _hasShort(rest, "f") || _hasLong(rest, "force");
if (hasDelete && hasForce) {
return { matched: "branch", desc: "git branch -d/-D --force" };
}
if (hasForce) {
return { matched: "branch", desc: "git branch --force" };
}
}
// --- update-ref ---
if (subcmd.toLowerCase() === "update-ref") {
for (const t of rest) {
if (t === "-d") {
return { matched: "update-ref", desc: "git update-ref -d" };
}
}
}
// --- reflog ---
if (subcmd.toLowerCase() === "reflog") {
for (const t of rest) {
if (t === "expire" || t === "delete") {
return { matched: "reflog", desc: "git reflog " + t };
}
}
}
// --- gc ---
if (subcmd.toLowerCase() === "gc") {
for (const t of rest) {
if (t === "--prune=now") {
return { matched: "gc", desc: "git gc --prune=now" };
}
}
}
return null;
}
/**
* Check bash_destructive_git rule.
*
* Block (or warn) destructive git commands: reset --hard, clean -f,
* checkout --force, branch -D, etc. Always-scope - fires regardless of
* boulder state.
*
* Throws Error on block; logs and returns on warn; no-op on off/absent.
*/
function checkBashDestructiveGit(mode, command) {
if (mode === MODE_OFF) return null;
const result = _checkBashDestructiveGit(command);
if (!result) return null;
if (mode === MODE_WARN) {
logEvent(null, "_guardrails", "bash_destructive_git", "bash", result.desc);
return null;
}
// block mode
const err = new Error(`bash/destructive_git: blocked -- ${result.desc}. Stop and report to the operator. Do not retry, do not work around it with another command, do not wrap it in bash -c. To restore one file use git checkout <ref> -- <path>. To undo a commit use git revert.`);
err.ruleId = "bash_destructive_git";
throw err;
}
/** /**
* Check a command for protected-port access. * Check a command for protected-port access.
* *
@@ -1394,6 +1643,9 @@ export const Guardrails = async ({ client, directory, omoDir }) => {
const bbMode = getRuleMode(config, "bash_banned"); const bbMode = getRuleMode(config, "bash_banned");
checkBashBanned(bbMode, command); checkBashBanned(bbMode, command);
const bdMode = getRuleMode(config, "bash_destructive_git");
checkBashDestructiveGit(bdMode, command);
const bpMode = getRuleMode(config, "bash_protected_port"); const bpMode = getRuleMode(config, "bash_protected_port");
checkBashProtectedPort(bpMode, command, config); checkBashProtectedPort(bpMode, command, config);
} }
@@ -1415,6 +1667,9 @@ Guardrails.splitSegments = _splitSegments;
Guardrails.stripPrefixes = _stripPrefixes; Guardrails.stripPrefixes = _stripPrefixes;
Guardrails.checkBashBanned = checkBashBanned; Guardrails.checkBashBanned = checkBashBanned;
Guardrails.checkBashProtectedPort = checkBashProtectedPort; Guardrails.checkBashProtectedPort = checkBashProtectedPort;
Guardrails.checkBashDestructiveGit = checkBashDestructiveGit;
Guardrails._checkBashBanned = _checkBashBanned; Guardrails._checkBashBanned = _checkBashBanned;
Guardrails._checkBashProtectedPort = _checkBashProtectedPort; Guardrails._checkBashProtectedPort = _checkBashProtectedPort;
Guardrails._checkBashDestructiveGit = _checkBashDestructiveGit;
Guardrails._unquoteSegment = _unquoteSegment;
Guardrails.countTicked = countTicked; Guardrails.countTicked = countTicked;

View File

@@ -3320,3 +3320,501 @@ describe("R5 -- absent rules default to block (Design C)", () => {
}); });
}); });
}); });
// ---------------------------------------------------------------------------
// bash_destructive_git -- direct function tests for _checkBashDestructiveGit
// ---------------------------------------------------------------------------
describe("bash_destructive_git", () => {
// --- BLOCKED: reset ---
describe("BLOCKED: reset", () => {
it("blocks git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reset --hard"));
});
it("blocks git reset --keep", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reset --keep"));
});
it("blocks git reset --merge", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reset --merge"));
});
it("blocks git reset --hard origin/main", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reset --hard origin/main"));
});
});
// --- BLOCKED: clean ---
describe("BLOCKED: clean", () => {
it("blocks git clean -f", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git clean -f"));
});
it("blocks git clean -fd", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git clean -fd"));
});
it("blocks git clean -xdf", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git clean -xdf"));
});
it("blocks git clean --force", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git clean --force"));
});
});
// --- BLOCKED: checkout ---
describe("BLOCKED: checkout", () => {
it("blocks git checkout -f", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout -f"));
});
it("blocks git checkout .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout ."));
});
it("blocks git checkout -- .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout -- ."));
});
it("blocks git checkout origin/main -- .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout origin/main -- ."));
});
it("blocks git checkout -B feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout -B feature"));
});
it("blocks git checkout --force", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout --force"));
});
});
// --- BLOCKED: restore ---
describe("BLOCKED: restore", () => {
it("blocks git restore .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git restore ."));
});
it("blocks git restore --staged --worktree .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git restore --staged --worktree ."));
});
it("blocks git restore --worktree .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git restore --worktree ."));
});
});
// --- BLOCKED: branch ---
describe("BLOCKED: branch", () => {
it("blocks git branch -D feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git branch -D feature"));
});
it("blocks git branch --delete --force feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git branch --delete --force feature"));
});
it("blocks git branch -f feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git branch -f feature"));
});
it("blocks git branch --force feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git branch --force feature"));
});
});
// --- BLOCKED: update-ref ---
describe("BLOCKED: update-ref", () => {
it("blocks git update-ref -d refs/heads/feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git update-ref -d refs/heads/feature"));
});
});
// --- BLOCKED: reflog ---
describe("BLOCKED: reflog", () => {
it("blocks git reflog expire", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reflog expire"));
});
it("blocks git reflog delete", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reflog delete"));
});
});
// --- BLOCKED: gc ---
describe("BLOCKED: gc", () => {
it("blocks git gc --prune=now", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git gc --prune=now"));
});
});
// --- BLOCKED: switch ---
describe("BLOCKED: switch", () => {
it("blocks git switch -f feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git switch -f feature"));
});
it("blocks git switch --force feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git switch --force feature"));
});
it("blocks git switch --discard-changes feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git switch --discard-changes feature"));
});
it("blocks git switch -C feature", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git switch -C feature"));
});
});
// --- BLOCKED: global option skipping ---
describe("BLOCKED: global option skipping", () => {
it("blocks git -C /wt reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git -C /wt reset --hard"));
});
it("blocks git --git-dir=/x/.git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git --git-dir=/x/.git reset --hard"));
});
it("blocks git --git-dir /x/.git --work-tree /x reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git --git-dir /x/.git --work-tree /x reset --hard"));
});
it("blocks git -c a=b reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git -c a=b reset --hard"));
});
it("blocks git -C /wt clean -fd", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git -C /wt clean -fd"));
});
it("blocks git -C /wt checkout .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git -C /wt checkout ."));
});
});
// --- BLOCKED: complex shells ---
describe("BLOCKED: complex shells", () => {
it("blocks cd x && git reset --hard origin/main", () => {
assert.ok(Guardrails._checkBashDestructiveGit("cd x && git reset --hard origin/main"));
});
it("blocks env GIT_X=1 git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("env GIT_X=1 git reset --hard"));
});
it("blocks sudo git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("sudo git reset --hard"));
});
it("blocks command git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("command git reset --hard"));
});
it("blocks env -u X git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("env -u X git reset --hard"));
});
it("blocks GIT_X=1 git reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("GIT_X=1 git reset --hard"));
});
it("blocks false || git clean -fd", () => {
assert.ok(Guardrails._checkBashDestructiveGit("false || git clean -fd"));
});
it("blocks ls; git checkout .", () => {
assert.ok(Guardrails._checkBashDestructiveGit("ls; git checkout ."));
});
it("blocks git reset --hard as second segment after ;", () => {
assert.ok(Guardrails._checkBashDestructiveGit("echo ok; git reset --hard"));
});
it("blocks git reset --hard as second segment after |", () => {
assert.ok(Guardrails._checkBashDestructiveGit("echo ok | git reset --hard"));
});
});
// --- BLOCKED: specific incident ---
describe("BLOCKED: specific incident", () => {
it("blocks cd /home/alee/Sources/6krrt-worktrees/classifier-reliability && git reset --hard origin/main", () => {
assert.ok(Guardrails._checkBashDestructiveGit(
"cd /home/alee/Sources/6krrt-worktrees/classifier-reliability && git reset --hard origin/main",
));
});
});
// --- ALLOWED: checkout with pathspec ---
describe("ALLOWED: checkout with pathspec", () => {
it("allows git checkout origin/main -- src/metrics.py", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git checkout origin/main -- src/metrics.py"), null);
});
it("allows git checkout feature", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git checkout feature"), null);
});
it("allows git checkout -b new-branch", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git checkout -b new-branch"), null);
});
it("allows git checkout -- src/file.py (pathspec, not dot)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git checkout -- src/file.py"), null);
});
});
// --- ALLOWED: restore with pathspec ---
describe("ALLOWED: restore with pathspec", () => {
it("allows git restore --source=HEAD -- src/file.py", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git restore --source=HEAD -- src/file.py"), null);
});
it("allows git restore file.py", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git restore file.py"), null);
});
it("allows git restore --staged file.py", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git restore --staged file.py"), null);
});
it("allows git restore --staged . (unstage only)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git restore --staged ."), null);
});
});
// --- ALLOWED: revert / reset (non-destructive) ---
describe("ALLOWED: revert / reset (non-destructive)", () => {
it("allows git revert HEAD", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git revert HEAD"), null);
});
it("allows git reset src/file.py (pathspec, no --hard)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git reset src/file.py"), null);
});
it("allows git reset --soft HEAD~1", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git reset --soft HEAD~1"), null);
});
it("allows git commit --amend", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git commit --amend"), null);
});
it("allows git reset HEAD file.py", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git reset HEAD file.py"), null);
});
});
// --- ALLOWED: switch / branch (non-destructive) ---
describe("ALLOWED: switch / branch (non-destructive)", () => {
it("allows git switch feature", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git switch feature"), null);
});
it("allows git branch -d feature (delete without force)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git branch -d feature"), null);
});
});
// --- ALLOWED: reflog / gc / update-ref (non-destructive) ---
describe("ALLOWED: reflog / gc / update-ref (non-destructive)", () => {
it("allows git reflog", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git reflog"), null);
});
it("allows git reflog show", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git reflog show"), null);
});
it("allows git gc", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git gc"), null);
});
it("allows git update-ref refs/heads/x HEAD", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git update-ref refs/heads/x HEAD"), null);
});
});
// --- ALLOWED: clean without force ---
describe("ALLOWED: clean without force", () => {
it("allows git clean (no flags)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git clean"), null);
});
it("allows git clean -n (dry-run)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git clean -n"), null);
});
it("allows git clean -nfd (dry-run with force flag but also dry-run)", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git clean -nfd"), null);
});
});
// --- ALLOWED: multi-segment ---
describe("ALLOWED: multi-segment", () => {
it("allows git status && git diff", () => {
assert.equal(Guardrails._checkBashDestructiveGit("git status && git diff"), null);
});
});
// --- ALLOWED: non-git commands ---
describe("ALLOWED: non-git commands", () => {
it("allows echo hello", () => {
assert.equal(Guardrails._checkBashDestructiveGit("echo hello"), null);
});
it("allows python3 -c 'print(1)'", () => {
assert.equal(Guardrails._checkBashDestructiveGit("python3 -c 'print(1)'"), null);
});
});
// --- F5: bypass cases ---
describe("F5: bypass cases", () => {
describe("BLOCKED: global-option bypass", () => {
it("blocks git -p reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git -p reset --hard"));
});
it("blocks git -P reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git -P reset --hard"));
});
it("blocks git --no-pager reset --hard", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git --no-pager reset --hard"));
});
});
describe("BLOCKED: short-flag cluster bypass", () => {
it("blocks git clean -fdx --exclude=node_modules", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git clean -fdx --exclude=node_modules"));
});
it("blocks git clean -fd -e node_modules", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git clean -fd -e node_modules"));
});
it("blocks git checkout -fq main", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git checkout -fq main"));
});
it("blocks git switch -fq main", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git switch -fq main"));
});
it("blocks git branch -fD x", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git branch -fD x"));
});
it("blocks git branch -Df x", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git branch -Df x"));
});
});
describe("ALLOWED: edge cases that stay allowed", () => {
it("allows git clean -fd --dry-run", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git clean -fd --dry-run"), null);
});
it("allows git clean -nfd", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git clean -nfd"), null);
});
it("allows git clean -n", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git clean -n"), null);
});
it("allows git checkout -b x", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git checkout -b x"), null);
});
it("allows git switch -c x", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git switch -c x"), null);
});
it("allows git branch -d x", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git branch -d x"), null);
});
it("allows git restore --staged .", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git restore --staged ."), null);
});
it("allows git checkout origin/main -- src/metrics.py", () => {
assert.strictEqual(Guardrails._checkBashDestructiveGit("git checkout origin/main -- src/metrics.py"), null);
});
});
});
// --- MODES: warn ---
describe("MODES: warn", () => {
it("warn mode logs and allows git reset --hard", async () => {
const dir = newDir();
const { cfgDir, logPath } = writeConfig(dir, { rules: { bash_destructive_git: "warn" } });
writeBoulder(dir, { status: "active", session_ids: [] });
const hooks = await Guardrails({ client: stubClient(() => {}), directory: dir });
await callHook(hooks, "ses_dg_warn", "bash", { command: "git reset --hard" }, {});
const logContent = readFileSync(logPath, "utf-8");
const lines = logContent.trim().split("\n");
const warnEntry = JSON.parse(lines[lines.length - 1]);
assert.equal(warnEntry.rule, "bash_destructive_git");
});
});
// --- MODES: off ---
describe("MODES: off", () => {
it("off mode allows silently git reset --hard", async () => {
const dir = newDir();
writeConfig(dir, { rules: { bash_destructive_git: "off" } });
writeBoulder(dir, { status: "active", session_ids: [] });
const hooks = await Guardrails({ client: stubClient(() => {}), directory: dir });
await callHook(hooks, "ses_dg_off", "bash", { command: "git reset --hard" }, {});
});
});
// --- MESSAGE ---
describe("MESSAGE", () => {
it("thrown Error for git reset --hard contains 'reset --hard' and 'Stop and report to the operator'", () => {
assert.throws(
() => Guardrails.checkBashDestructiveGit("block", "git reset --hard"),
(err) => {
assert.ok(err.message.includes("reset --hard"), `message should contain 'reset --hard': ${err.message}`);
assert.ok(err.message.includes("Stop and report to the operator"), `message should contain 'Stop and report to the operator': ${err.message}`);
return true;
},
);
});
it("thrown Error for git clean -f contains 'clean' and 'Stop and report to the operator'", () => {
assert.throws(
() => Guardrails.checkBashDestructiveGit("block", "git clean -f"),
(err) => {
assert.ok(err.message.includes("clean"), `message should contain 'clean': ${err.message}`);
assert.ok(err.message.includes("Stop and report to the operator"), `message should contain 'Stop and report to the operator': ${err.message}`);
return true;
},
);
});
it("thrown Error has ruleId set to bash_destructive_git", () => {
assert.throws(
() => Guardrails.checkBashDestructiveGit("block", "git reset --hard"),
(err) => {
assert.equal(err.ruleId, "bash_destructive_git");
return true;
},
);
});
});
// --- F2: block message content ---
describe("F2: block message content", () => {
it("block message contains 'Do not retry'", () => {
try {
Guardrails.checkBashDestructiveGit("block", "git reset --hard");
assert.fail("should have thrown");
} catch (err) {
assert.ok(err.message.includes("Do not retry"), `message missing 'Do not retry': ${err.message}`);
}
});
it("block message contains 'git revert'", () => {
try {
Guardrails.checkBashDestructiveGit("block", "git reset --hard");
assert.fail("should have thrown");
} catch (err) {
assert.ok(err.message.includes("git revert"), `message missing 'git revert': ${err.message}`);
}
});
});
// --- PIPELINE: Quote/Unquote ---
describe("PIPELINE: Quote/Unquote", () => {
it("allows git commit -m 'docs: never run git reset --hard' (token-based matching prevents false positive)", () => {
assert.equal(
Guardrails._checkBashDestructiveGit('git commit -m "docs: never run git reset --hard"'),
null,
);
});
it("allows git commit -m 'reset --hard is dangerous' (quoted content not matched as tokens)", () => {
assert.equal(
Guardrails._checkBashDestructiveGit("git commit -m 'reset --hard is dangerous'"),
null,
);
});
it("allows git commit -m 'clean -f happened' (quoted content not matched as tokens)", () => {
assert.equal(
Guardrails._checkBashDestructiveGit("git commit -m 'clean -f happened'"),
null,
);
});
it("blocks git reset --hard when not in quotes", () => {
assert.ok(Guardrails._checkBashDestructiveGit("git reset --hard"));
});
});
// --- _unquoteSegment helper ---
describe("_unquoteSegment", () => {
it("removes single quotes but keeps content", () => {
assert.equal(Guardrails._unquoteSegment("echo 'hello world'"), "echo hello world");
});
it("removes double quotes but keeps content", () => {
assert.equal(Guardrails._unquoteSegment('echo "hello world"'), "echo hello world");
});
it("removes backticks but keeps content", () => {
assert.equal(Guardrails._unquoteSegment("echo `whoami`"), "echo whoami");
});
it("handles mixed quotes", () => {
assert.equal(
Guardrails._unquoteSegment('echo "a" \'b\' `c`'),
"echo a b c",
);
});
it("preserves unquoted content", () => {
assert.equal(Guardrails._unquoteSegment("git add src/a.py"), "git add src/a.py");
});
});
});

View File

@@ -42,6 +42,14 @@
"command": "curl -s localhost:8080/health" "command": "curl -s localhost:8080/health"
} }
}, },
{
"sessionID": "ses_r19_006",
"callID": "call_r19_006",
"tool": "bash",
"args": {
"command": "git clean -f"
}
},
{ {
"sessionID": "ses_r19_007", "sessionID": "ses_r19_007",
"callID": "call_r19_007", "callID": "call_r19_007",

View File

@@ -34,6 +34,7 @@ call), or `"off"` (no check). Edit in `.omo/guardrails.json`.
| `write_outside_worktree` | writes to files outside the worktree scope | same 2026-09-28 incident | | `write_outside_worktree` | writes to files outside the worktree scope | same 2026-09-28 incident |
| `bash_main_checkout` | git/redirect ops targeting the main checkout from a worktree task | same class as 2026-09-28 main-checkout rewrite | | `bash_main_checkout` | git/redirect ops targeting the main checkout from a worktree task | same class as 2026-09-28 main-checkout rewrite |
| `bash_banned` | `pkill`, `git stash`, `kill`, `systemctl` | 2026-09-26: unasked PR; 2026-09-29: git stash in wrong checkout | | `bash_banned` | `pkill`, `git stash`, `kill`, `systemctl` | 2026-09-26: unasked PR; 2026-09-29: git stash in wrong checkout |
| `bash_destructive_git` | `reset --hard`, `clean -f`, `checkout .`, `restore .`, `branch -D`, reflog and ref destruction | 2026-10-10: a worker asked to restore one file ran `git reset --hard origin/main` in the classifier-reliability worktree and moved the branch off 8 commits; recovered from the reflog by the parent agent, no rule objected |
| `bash_protected_port` | bash commands containing `localhost`, `127.0.0.1` or `0.0.0.0` followed by `:8080` (list: `protected_ports`) | 8080 is the production router and opencode's own model traffic runs through it (CLAUDE.md); 2026-08-29 incident #1: an agent `pkill`ed it to free the port for a throwaway, which belongs on 8081 | | `bash_protected_port` | bash commands containing `localhost`, `127.0.0.1` or `0.0.0.0` followed by `:8080` (list: `protected_ports`) | 8080 is the production router and opencode's own model traffic runs through it (CLAUDE.md); 2026-08-29 incident #1: an agent `pkill`ed it to free the port for a throwaway, which belongs on 8081 |
| `plan_tick_gate` | tick gate blocks a todo tick while verify_commit fails | 2026-09-28: todo committed 3 failing tests and was reported done | | `plan_tick_gate` | tick gate blocks a todo tick while verify_commit fails | 2026-09-28: todo committed 3 failing tests and was reported done |
@@ -55,10 +56,11 @@ is seen doing real damage through one of them, not before.
...) and heredoc bodies are skipped unless fed to an interpreter. It does see ...) and heredoc bodies are skipped unless fed to an interpreter. It does see
inside `bash -c '...'` and `python3 -c '...'`, because it reads the raw string. inside `bash -c '...'` and `python3 -c '...'`, because it reads the raw string.
- **`bash -c '...'` and `sh -c '...'` wrappers are not inspected by - **`bash -c '...'` and `sh -c '...'` wrappers are not inspected by
`bash_banned` or `bash_main_checkout`.** `bash -c 'pkill -f foo'` and `bash_banned` or `bash_main_checkout`, or `bash_destructive_git`.** `bash -c 'pkill -f foo'` and
`bash -c 'git stash'` both pass. `bash -c 'git stash'` both pass.
- **`bash_main_checkout` can mis-anchor a relative `cd` chain that follows an - **`bash_main_checkout` can mis-anchor a relative `cd` chain that follows an
absolute one** (one block in the replay report). absolute one** (one block in the replay report).
- A parent agent's own recovery with `reset --hard` is blocked too, on purpose; the log line is the signal that the operator must decide.
## Log ## Log