Skip to content

fix(hooks): close the PowerShell destructive-command gate bypass - #2721

Closed
noliverbked wants to merge 5 commits into
affaan-m:mainfrom
noliverbked:fix/powershell-destructive-gate
Closed

noliverbked wants to merge 5 commits into
affaan-m:mainfrom
noliverbked:fix/powershell-destructive-gate

Conversation

@noliverbked

Copy link
Copy Markdown
Contributor

The hole

settings.json can set CLAUDE_CODE_USE_POWERSHELL_TOOL=1, which makes PowerShell a second arbitrary-command shell alongside Bash. Every destructive-command gate in this repo is scoped to Bash alone, so identical destructive intent through the two tools produced opposite outcomes.

Reproduced through the real run-with-flags invocation path, before the fix:

Bash       + recursive force delete  -> {"permissionDecision":"deny", ... "Destructive command detected"}
PowerShell + Remove-Item -Recurse -Force <path>
                                     -> {"tool_name":"PowerShell", ...}   <- passthrough, exit 0, no gate

Why widening the matcher alone is not enough

It fails at two independent levels:

  1. gateguard-fact-force.js — TOOL_MAP had no powershell key, and if (toolName === 'Bash') was the only branch reaching isDestructiveBash(). Unrecognised tool names fall through to the bare allow at the end of run().
  2. governance-capture.js — SECURITY_RELEVANT_TOOLS held only 'Bash', and a second Bash-only branch guarded APPROVAL_COMMANDS. So a command that bypassed the gate was also invisible to the audit trail. The two failures compound.

Approach

PowerShell delete verbs share no syntax with POSIX rm, so reuse of the Bash tokenizer is not possible: the PowerShell recursive-delete form reaches isDestructiveRm() as tokens whose -Force fails its case-sensitive /f/ test. Hence a dedicated isDestructivePowerShell().

It does reuse this file's existing quote-aware segmenter (quoteAwareSegments) rather than a naive String.split. That is deliberate — the naive split reintroduces exactly the evasion class documented in GHSA-4v57-ph3x-gf55, and reusing the hardened splitter also resolves the & call operator and quoted command words with no extra code.

Coverage beyond the base case:

Evasion Handling
Quoted separator in a path ("C:/evil;dir/*") quote-aware segmentation
& 'Remove-Item' ... (call operator) & is already a segment separator
Get-ChildItem -Recurse | Remove-Item statement-level pass keeps pipelines intact so upstream -Recurse stays visible
Backtick obfuscation escape normalisation
powershell -Command / pwsh -c / cmd /c nested-shell unwrap, mirroring the existing sh -c handling
-EncodedCommand <base64> UTF-16LE decode, then re-scan
cmd /c rd /s /q cmd.exe recursive-removal pattern
[System.IO.Directory]::Delete($p,$true) .NET delete pattern
Remove-Item @params (splatting) opaque parameters are gated rather than assumed safe

Parameter matching uses prefixes, because PowerShell accepts any unambiguous abbreviation: -Recurse, -Rec and -r must all match.

One deliberate departure from the rm analogy

-Force is gated even without -Recurse. Unlike rm -f, PowerShell's Remove-Item -Force <directory> removes the whole tree, and a static string cannot distinguish a file target from a directory target. A plain Remove-Item <path> with neither flag stays ungated.

Bash behaviour is unchanged

The PowerShell detector runs only for the PowerShell tool. isDestructiveBash() still runs for PowerShell input so shell-agnostic phrases (force push, hard reset, DROP TABLE, dd) stay covered. Verified by differential testing of the pre- and post-fix modules across 15 representative Bash commands: 0 differences.

The routine first-command gate intentionally shares ROUTINE_BASH_SESSION_KEY across both tools, so an operator sees one fact-forcing prompt per session rather than two. Its message is now tool-neutral ("first shell command").

Verification

The two-arm test that originally proved the bug — both now deny:

$ echo '{"tool_name":"Bash","tool_input":{"command":"<recursive force delete>"},"session_id":"verify-bash-arm"}' \
    | node scripts/hooks/run-with-flags.js pre:bash:gateguard-fact-force \
      scripts/hooks/gateguard-fact-force.js standard,strict
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny",
 "permissionDecisionReason":"[Fact-Forcing Gate]\n\nDestructive command detected. ..."}}

$ echo '{"tool_name":"PowerShell","tool_input":{"command":"Remove-Item -Recurse -Force C:/tmp/demo"},"session_id":"verify-ps-arm"}' \
    | node scripts/hooks/run-with-flags.js pre:bash:gateguard-fact-force \
      scripts/hooks/gateguard-fact-force.js standard,strict
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny",
 "permissionDecisionReason":"[Fact-Forcing Gate]\n\nDestructive command detected. ..."}}

Note when reproducing: the destructive gate denies only on the first attempt per session per command-hash, so use a distinct session_id per arm or the second run will look like a false "allow".

Test suites:

node tests/hooks/gateguard-fact-force.test.js   -> 164 passed, 0 failed   (20 new PowerShell cases; 144 pre-existing unaffected)
node tests/hooks/governance-capture.test.js     ->  30 passed, 0 failed
node tests/hooks/posttooluse-dispatcher.test.js ->  13 passed, 0 failed

governance-capture.js's new rules were additionally verified by direct invocation: Remove-Item -Recurse, -Rec, rd -Recurse, Clear-Content, Format-Volume and force-push all raise approval_requested; Get-ChildItem does not; and Start-Process -Verb RunAs now raises security_finding: elevated_privilege_command, which was unreachable before because PowerShell was absent from SECURITY_RELEVANT_TOOLS.

Review

Reviewed by two independent reviewers (security and code-quality), both of which initially returned BLOCK on the first draft with live-verified bypasses. Every bypass they demonstrated — quoted-separator evasion, pipe-to-delete, call operator, bare -Force on a directory, nested shell, cmd /c, backtick obfuscation, splatting, .NET delete — is now a named regression test in this PR.

Known residual risk (not addressed here)

Static command inspection has a ceiling, and PowerShell's unrestricted .NET access raises it. These remain undetected and are not claimed as covered:

  • Invoke-Expression / iex over a runtime-constructed string
  • Parameters or paths supplied through variables ($r='-Recurse'; Remove-Item $r $p)
  • Arbitrary .NET beyond the IO.Directory/IO.File delete pattern matched here
  • Reflection or dynamically resolved cmdlet names

These are the same limits the Bash path has. The gate is a fact-forcing speed bump, not a sandbox, and it should not be described as one.

Suggested follow-up (not in this PR)

tests/hooks/governance-capture.test.js has no PowerShell cases; the new rules there are verified by manual invocation (above) but not by the suite. Worth adding alongside.

CLAUDE_CODE_USE_POWERSHELL_TOOL=1 makes PowerShell a second
arbitrary-command shell, but every destructive-command gate was scoped to
Bash alone. Identical destructive intent through the two tools produced
opposite outcomes: the Bash recursive-delete form was denied, while the
PowerShell equivalent passed through with exit 0 and no gate at all.

The gate failed at two independent levels, so widening either alone was
insufficient:

- gateguard-fact-force.js: TOOL_MAP had no `powershell` key, and
  `if (toolName === 'Bash')` was the only branch reaching
  isDestructiveBash(). Unrecognised tool names fell through to the bare
  allow at the end of run().
- governance-capture.js: SECURITY_RELEVANT_TOOLS held only 'Bash', and a
  second Bash-only branch guarded APPROVAL_COMMANDS, so a bypassing
  command was also invisible to the audit trail.

PowerShell delete verbs share no syntax with POSIX rm, so a dedicated
isDestructivePowerShell() is required rather than reuse: the PowerShell
recursive-delete form reaches isDestructiveRm() as tokens whose -Force
fails its case-sensitive /f/ test. PowerShell also accepts any
unambiguous parameter prefix, so -Recurse, -Rec and -r must all match.

Detection reuses the file's existing quote-aware segmenter
(quoteAwareSegments) rather than a naive split, which is what closes the
quoted-separator evasion class described in GHSA-4v57-ph3x-gf55; the same
choice resolves the `&` call operator and quoted command words for free.
Covered in addition: pipelines that carry -Recurse on an upstream
enumerator, backtick obfuscation, nested powershell/pwsh/cmd
reinvocation including base64 -EncodedCommand, .NET
[System.IO.Directory]::Delete, and splatted (opaque) parameters.

-Force is gated even without -Recurse. This deliberately departs from the
rm -f analogy: PowerShell's Remove-Item -Force on a directory removes the
tree, and a static string cannot distinguish a file target from a
directory target.

isDestructiveBash() still runs for PowerShell input so the shell-agnostic
phrases (force push, hard reset, DROP TABLE, dd) stay covered. The
PowerShell detector runs only for the PowerShell tool, so Bash gating
behaviour is unchanged - verified by differential testing of both
versions across 15 representative Bash commands, 0 differences.

The routine first-command gate intentionally shares
ROUTINE_BASH_SESSION_KEY across both tools, so an operator sees one
fact-forcing prompt per session rather than two; its message is now
tool-neutral.

Tests: 164 passed / 0 failed in gateguard-fact-force (20 new PowerShell
cases, 144 pre-existing unaffected), 30/0 governance-capture, 13/0
posttooluse-dispatcher.
@noliverbked
noliverbked requested a review from affaan-m as a code owner August 8, 2026 00:51
@ecc-tools

ecc-tools Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added safety checks for destructive PowerShell commands, including recursive deletion, encoded commands, nested shells, pipelines, aliases, and .NET-based deletion.
    • PowerShell commands now follow the same security review and approval process as other supported shells.
    • Added detection for PowerShell elevation attempts and changes to access permissions or ownership.
    • Added dedicated PowerShell safety and governance checks for tool activity.
  • Bug Fixes

    • Improved recognition of obfuscated and parameterized destructive commands while preserving safe read-only operations.

Walkthrough

PowerShell now uses destructive-command detection, governance approval checks, elevated-privilege checks, and dedicated hook routing. Detection covers aliases, nested shells, encoded commands, pipelines, parameter variants, and alternate deletion APIs. Tests cover denial, allowed commands, governance events, and shared session gating.

Changes

PowerShell security enforcement

Layer / File(s) Summary
PowerShell command detection
scripts/hooks/gateguard-fact-force.js
Adds PowerShell normalization and destructive-command detection for nested, encoded, piped, aliased, obfuscated, and API-based deletion commands. Routine-gate messaging and recovery routing now distinguish PowerShell from Bash.
Governance approval and hook routing
scripts/hooks/governance-capture.js, hooks/hooks.json, scripts/hooks/posttooluse-dispatcher.js
Treats PowerShell as security-relevant. Approval checks cover removal, content clearing, and volume formatting. Elevated checks cover RunAs, ACL changes, and ownership changes. Hook configuration and post-tool dispatch include PowerShell.
Integration and regression coverage
tests/hooks/gateguard-fact-force.test.js, tests/hooks/governance-capture.test.js, tests/hooks/hooks.test.js, tests/hooks/posttooluse-dispatcher.test.js
Adds coverage for destructive variants, read-only commands, Git checks, nested execution, encoding, .NET, cmd.exe, splatting, shared session gating, approval events, elevated findings, configured routes, and dispatcher behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PowerShell
  participant GateguardFactForce
  participant GovernanceCapture
  participant PostToolDispatcher
  PowerShell->>GateguardFactForce: submit command
  GateguardFactForce->>GateguardFactForce: inspect destructive syntax
  GateguardFactForce-->>PowerShell: allow or deny command
  PowerShell->>PostToolDispatcher: emit tool event
  PostToolDispatcher->>GovernanceCapture: dispatch PowerShell event
  GovernanceCapture->>GovernanceCapture: analyze approval and elevation patterns
  GovernanceCapture-->>PowerShell: record governance result
Loading

Suggested reviewers: affaan-m, gaurav0107

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: closing the PowerShell destructive-command gate bypass.
Description check ✅ Passed The description directly explains the PowerShell bypass, implementation approach, coverage, verification, and residual risks.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/hooks/gateguard-fact-force.js`:
- Around line 759-765: Update the destructive PowerShell detection logic near
the token loop in the relevant function to gate non-parameter target tokens
containing wildcards such as “*”, while preserving existing handling for
-Recurse, -Force, and splats. Add or update coverage for Remove-Item with a
wildcard target and no destructive parameter, ensuring it is classified as gated
and single-file -Force behavior remains unchanged.
- Around line 770-771: Update isDestructivePowerShell so reaching the recursion
limit at depth greater than 4 returns true instead of false, ensuring deeply
nested or unanalyzable PowerShell commands are treated as destructive candidates
while preserving existing behavior below the limit.

In `@scripts/hooks/governance-capture.js`:
- Around line 49-51: Add the PowerShell alias rm to the command alternatives in
the governance-capture regex, alongside Remove-Item and the existing aliases.
Ensure rm -Recurse is matched by the PowerShell-specific pattern while
preserving the current POSIX rm handling and other alias behavior.

In `@tests/hooks/gateguard-fact-force.test.js`:
- Around line 2484-2493: Update expectPsAllow in
tests/hooks/gateguard-fact-force.test.js#L2484-L2493 to assert that parseOutput
returns output before checking hookSpecificOutput, and add the pass-through
tool_name assertion in the else branch matching expectAllow. Also update the
shared-routine-gate test at tests/hooks/gateguard-fact-force.test.js#L2668-L2684
to assert output exists before its conditional check.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 92573461-e9e5-475b-b61b-378fb4abbcc3

📥 Commits

Reviewing files that changed from the base of the PR and between 59a99d6 and 3178868.

📒 Files selected for processing (3)
  • scripts/hooks/gateguard-fact-force.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
📜 Review details
🧰 Additional context used
📓 Path-based instructions (17)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
{package.json,*.config.js,scripts/**/*.js}

📄 CodeRabbit inference engine (CLAUDE.md)

Package manager detection should support npm, pnpm, yarn, and bun, with configuration via CLAUDE_PACKAGE_MANAGER environment variable or project config.

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
scripts/**/*.js

📄 CodeRabbit inference engine (CLAUDE.md)

Ensure cross-platform support for Windows, macOS, and Linux via Node.js scripts in the scripts/ directory.

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Delegate complex features to a planner agent, architectural decisions to an architect agent, modified code to a code-reviewer agent, and security-sensitive work to a security-reviewer agent; use parallel agents for independent operations.
Never compromise security; validate all inputs and prevent hardcoded secrets, injection, XSS, CSRF, authentication or authorization failures, sensitive error leakage, and missing rate limits.
Never hardcode secrets; use environment variables or a secret manager, validate required secrets at startup, and rotate exposed secrets immediately.
Always create new objects and never mutate existing ones.
Plan complex features before implementation, identifying dependencies, risks, and phases.
Prefer many small, focused files; keep functions under 50 lines, files under 800 lines where practical, avoid nesting deeper than four levels, and use readable, well-named identifiers.
Handle errors at every level, provide user-friendly UI messages, log detailed server-side context, and never silently swallow errors.
Validate all user input at system boundaries using schema-based validation; fail fast with clear messages and never trust external data.
Required tests include unit tests, integration tests for APIs and database operations, and end-to-end tests for critical user flows.
Follow the mandatory TDD cycle: write a failing test, implement the minimum passing solution, then refactor and verify coverage.
Use a consistent API response envelope containing a success indicator, data payload, error message, and pagination metadata.
Encapsulate data access behind a repository interface with operations such as findAll, findById, create, update, and delete; business logic must depend on the abstraction rather than storage details.

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
  • tests/hooks/gateguard-fact-force.test.js
{scripts,bin}/**

⚙️ CodeRabbit configuration file

{scripts,bin}/**: Focus on command injection, unsafe subprocess usage, path traversal, SSRF, secret exposure, and missing tests for new CLI behavior.

Files:

  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/hooks/gateguard-fact-force.test.js
🧠 Learnings (2)
📚 Learning: 2026-06-27T23:49:19.839Z
Learnt from: gaurav0107
Repo: affaan-m/ECC PR: 2373
File: tests/hooks/observe-signal-timeout.test.js:0-0
Timestamp: 2026-06-27T23:49:19.839Z
Learning: In tests under tests/hooks that require a Python runtime to run, the test should fail fast when Python isn’t available (or prerequisites aren’t met). Do not treat a missing Python runtime as test.skip, as an expected/allowed condition, or as a passing state; instead, explicitly fail (e.g., throw/return a rejected promise or use a test runner fail/expect that marks the test as failed) so reviewers can’t accidentally mask environment issues.

Applied to files:

  • tests/hooks/gateguard-fact-force.test.js
📚 Learning: 2026-07-14T03:26:12.530Z
Learnt from: thejesh23
Repo: affaan-m/ECC PR: 2517
File: tests/hooks/pre-bash-tmux-reminder.test.js:21-25
Timestamp: 2026-07-14T03:26:12.530Z
Learning: In this repository, do not flag `console.log` usage as a guideline violation in hook test files under `tests/hooks/*.test.js`. These tests intentionally use `console.log` for pass/fail output because the repo’s console-based runner (`tests/run-all.js`) is used and there is no Jest/Mocha dependency. Outside this specific hook-test path, follow the normal logging guidelines.

Applied to files:

  • tests/hooks/gateguard-fact-force.test.js
🔇 Additional comments (7)
scripts/hooks/gateguard-fact-force.js (6)

744-757: LGTM!


829-866: LGTM!


868-918: LGTM!


1323-1323: LGTM!

Also applies to: 1391-1391


728-742: 🔒 Security & Privacy

No change needed.

commandBasename() already removes a trailing .exe after stripping the path, so powershell.exe, pwsh.exe, and cmd.exe are normalized to the bare names used by PS_NESTED_SHELLS and the delete-verb checks.


1442-1454: 🔒 Security & Privacy

No change needed.

PowerShell gating is reachable through the existing Bash PreToolUse hook registration.

			> Likely an incorrect or invalid review comment.
scripts/hooks/governance-capture.js (1)

185-186: LGTM!

Also applies to: 231-237

Comment thread scripts/hooks/gateguard-fact-force.js Resolved
Comment thread scripts/hooks/governance-capture.js Resolved
The PowerShell entries in APPROVAL_COMMANDS and the extended
elevated-privilege check had no suite coverage; they were verified only by
direct invocation. Adds 5 cases: recursive-delete detection including
abbreviated parameter prefixes, Clear-Content/Format-Volume, a benign
control, approval_requested parity with Bash, and elevated-privilege
security_finding for RunAs/Set-Acl/takeown.

All 6 assertions verified red-green against the pre-fix module (pre=none,
post=flag); the benign control is 0 in both. Suite: 35 passed, 0 failed.
@ecc-tools

ecc-tools Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/hooks/governance-capture.test.js`:
- Around line 362-367: Strengthen the assertions in the detectApprovalRequired
PowerShell test so the abbreviated -Rec input and the rd -Recurse input each
verify the expected PowerShell finding.pattern, rather than only checking that
findings exist. Keep the existing full-parameter coverage and ensure the
assertions specifically prove abbreviated-parameter support.
- Around line 379-397: Split the combined elevated-privilege loop in the
PowerShell governance tests into independently reported, descriptively named
test cases for Start-Process, Set-Acl, and takeown. Give each case explicit
Arrange, Act, and Assert steps while preserving the existing security_finding
event type and elevated_privilege_command reason checks.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 40417207-0d88-4fb2-84f6-d1f9b3e7254d

📥 Commits

Reviewing files that changed from the base of the PR and between 3178868 and 308f390.

📒 Files selected for processing (1)
  • tests/hooks/governance-capture.test.js
📜 Review details
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • tests/hooks/governance-capture.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/hooks/governance-capture.test.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • tests/hooks/governance-capture.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • tests/hooks/governance-capture.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • tests/hooks/governance-capture.test.js
**/*

📄 CodeRabbit inference engine (AGENTS.md)

**/*: Delegate complex features to a planner agent, architectural decisions to an architect agent, modified code to a code-reviewer agent, and security-sensitive work to a security-reviewer agent; use parallel agents for independent operations.
Never compromise security; validate all inputs and prevent hardcoded secrets, injection, XSS, CSRF, authentication or authorization failures, sensitive error leakage, and missing rate limits.
Never hardcode secrets; use environment variables or a secret manager, validate required secrets at startup, and rotate exposed secrets immediately.
Always create new objects and never mutate existing ones.
Plan complex features before implementation, identifying dependencies, risks, and phases.
Prefer many small, focused files; keep functions under 50 lines, files under 800 lines where practical, avoid nesting deeper than four levels, and use readable, well-named identifiers.
Handle errors at every level, provide user-friendly UI messages, log detailed server-side context, and never silently swallow errors.
Validate all user input at system boundaries using schema-based validation; fail fast with clear messages and never trust external data.
Required tests include unit tests, integration tests for APIs and database operations, and end-to-end tests for critical user flows.
Follow the mandatory TDD cycle: write a failing test, implement the minimum passing solution, then refactor and verify coverage.
Use a consistent API response envelope containing a success indicator, data payload, error message, and pagination metadata.
Encapsulate data access behind a repository interface with operations such as findAll, findById, create, update, and delete; business logic must depend on the abstraction rather than storage details.

Files:

  • tests/hooks/governance-capture.test.js
🧠 Learnings (2)
📚 Learning: 2026-06-27T23:49:19.839Z
Learnt from: gaurav0107
Repo: affaan-m/ECC PR: 2373
File: tests/hooks/observe-signal-timeout.test.js:0-0
Timestamp: 2026-06-27T23:49:19.839Z
Learning: In tests under tests/hooks that require a Python runtime to run, the test should fail fast when Python isn’t available (or prerequisites aren’t met). Do not treat a missing Python runtime as test.skip, as an expected/allowed condition, or as a passing state; instead, explicitly fail (e.g., throw/return a rejected promise or use a test runner fail/expect that marks the test as failed) so reviewers can’t accidentally mask environment issues.

Applied to files:

  • tests/hooks/governance-capture.test.js
📚 Learning: 2026-07-14T03:26:12.530Z
Learnt from: thejesh23
Repo: affaan-m/ECC PR: 2517
File: tests/hooks/pre-bash-tmux-reminder.test.js:21-25
Timestamp: 2026-07-14T03:26:12.530Z
Learning: In this repository, do not flag `console.log` usage as a guideline violation in hook test files under `tests/hooks/*.test.js`. These tests intentionally use `console.log` for pass/fail output because the repo’s console-based runner (`tests/run-all.js`) is used and there is no Jest/Mocha dependency. Outside this specific hook-test path, follow the normal logging guidelines.

Applied to files:

  • tests/hooks/governance-capture.test.js

Comment on lines +362 to +367
if (await test('detectApprovalRequired flags PowerShell recursive deletes', async () => {
assert.ok(detectApprovalRequired('Remove-Item -Recurse -Force C:/tmp/demo').length > 0);
// PowerShell accepts any unambiguous parameter prefix.
assert.ok(detectApprovalRequired('Remove-Item -Rec C:/tmp/demo').length > 0);
assert.ok(detectApprovalRequired('rd -Recurse C:/tmp/demo').length > 0);
})) passed += 1; else failed += 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the PowerShell-specific finding for abbreviated parameters.

The length > 0 assertions do not prove that -Rec or rd -Recurse matched the intended PowerShell rule. A broader rule could satisfy these assertions while abbreviated-parameter detection is broken. Assert the expected finding.pattern, or add a boundary case that only the abbreviated PowerShell rule can match.

The PR objective explicitly requires abbreviated parameter support.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/hooks/governance-capture.test.js` around lines 362 - 367, Strengthen
the assertions in the detectApprovalRequired PowerShell test so the abbreviated
-Rec input and the rd -Recurse input each verify the expected PowerShell
finding.pattern, rather than only checking that findings exist. Keep the
existing full-parameter coverage and ensure the assertions specifically prove
abbreviated-parameter support.

Comment on lines +379 to +397
if (await test('PowerShell tool raises approval_requested like Bash', async () => {
const events = analyzeForGovernanceEvents({
tool_name: 'PowerShell',
tool_input: { command: 'Remove-Item -Recurse -Force C:/tmp/demo' },
});
assert.ok(events.map(e => e.eventType).includes('approval_requested'));
})) passed += 1; else failed += 1;

if (await test('PowerShell elevated-privilege commands raise a security_finding', async () => {
for (const command of ['Start-Process -Verb RunAs cmd', 'Set-Acl -Path C:/x -AclObject $a', 'takeown /f C:/x']) {
const events = analyzeForGovernanceEvents(
{ tool_name: 'PowerShell', tool_input: { command } },
{ hookPhase: 'post' }
);
const finding = events.find(e => e.eventType === 'security_finding');
assert.ok(finding, `${command} should raise a security_finding`);
assert.strictEqual(finding.payload.reason, 'elevated_privilege_command');
}
})) passed += 1; else failed += 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Report each elevated-command case independently.

The loop tests Start-Process, Set-Acl, and takeown under one test. If one assertion fails, later commands are not evaluated as separate cases. Use separate test cases or a table-driven helper with explicit Arrange, Act, and Assert steps.

As per coding guidelines, tests must use an Arrange / Act / Assert structure with descriptive test names.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/hooks/governance-capture.test.js` around lines 379 - 397, Split the
combined elevated-privilege loop in the PowerShell governance tests into
independently reported, descriptively named test cases for Start-Process,
Set-Acl, and takeown. Give each case explicit Arrange, Act, and Assert steps
while preserving the existing security_finding event type and
elevated_privilege_command reason checks.

Source: Coding guidelines

@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@ecc-tools

ecc-tools Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

ECC bundle files are already tracked in this repository. Skipping generation of another bundle PR.

@haelyra haelyra left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for catching the PowerShell GateGuard gap. I completed the maintainer patch with a dedicated PowerShell route, fail-closed nested-command scanning, wildcard protection, rm alias handling, and direct configured-route coverage, then refreshed it on current main. The GateGuard, governance, dispatcher, and hook suites pass. Approving this exact head for hosted CI.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/hooks/gateguard-fact-force.js`:
- Around line 729-731: Extend the PowerShell destructive-command detection
around PS_DELETE_VERBS and isDestructivePowerShell to include Clear-Content,
Clear-Disk, and Format-Volume in a separate data-destruction verb set. Gate
these verbs independently of -Recurse and -Force, while preserving existing
Remove-Item, .NET delete, and cmd recursive-delete handling.
- Around line 760-766: Update the documentation comment for the destructive
PowerShell command detector near isDestructiveRm to accurately describe the
implemented behavior: any Remove-Item -Force prefix is gated, including
single-file and directory targets. Remove the claim that Remove-Item -Force
notes.txt remains ungated, while preserving the explanation that this behavior
intentionally differs from the rm -f comparison.

In `@tests/hooks/gateguard-fact-force.test.js`:
- Around line 2691-2712: Add a regression test near the existing Bash hook-ID
assertion that exercises the PowerShell routine-gate denial path through
runBashHook with a PowerShell command, then assert the emitted denial output
references POWERSHELL_HOOK_ID rather than BASH_HOOK_ID. Keep the test focused on
the observable disable ID selected by run() for PowerShell routine denials.

In `@tests/hooks/hooks.test.js`:
- Around line 2591-2610: Update the spawnSync environment in the test around the
route command to explicitly clear ECC_GATEGUARD and GATEGUARD_DISABLED and
remove the gateguard-fact-force entry from ECC_DISABLED_HOOKS, while preserving
the isolated GATEGUARD_STATE_DIR and other inherited environment values.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: bf703639-8d35-49fc-b048-d588b2dfc1e1

📥 Commits

Reviewing files that changed from the base of the PR and between d29cf65 and 4a2e59b.

📒 Files selected for processing (8)
  • hooks/hooks.json
  • scripts/hooks/gateguard-fact-force.js
  • scripts/hooks/governance-capture.js
  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/gateguard-fact-force.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • tests/hooks/posttooluse-dispatcher.test.js
📜 Review details
⏰ Context from checks skipped due to timeout. (13)
  • GitHub Check: Test (ubuntu-latest, Node 22.x, bun)
  • GitHub Check: Test (ubuntu-latest, Node 22.x, pnpm)
  • GitHub Check: Test (ubuntu-latest, Node 22.x, npm)
  • GitHub Check: Test (ubuntu-latest, Node 20.x, yarn)
  • GitHub Check: Test (ubuntu-latest, Node 18.x, pnpm)
  • GitHub Check: Test (ubuntu-latest, Node 20.x, pnpm)
  • GitHub Check: Test (ubuntu-latest, Node 18.x, bun)
  • GitHub Check: Test (ubuntu-latest, Node 20.x, npm)
  • GitHub Check: Security Scan
  • GitHub Check: Lint
  • GitHub Check: Coverage
  • GitHub Check: Validate Components
  • GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (18)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • hooks/hooks.json
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
{package.json,*.config.js,scripts/**/*.js}

📄 CodeRabbit inference engine (CLAUDE.md)

Package manager detection should support npm, pnpm, yarn, and bun, with configuration via CLAUDE_PACKAGE_MANAGER environment variable or project config.

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
scripts/**/*.js

📄 CodeRabbit inference engine (CLAUDE.md)

Ensure cross-platform support for Windows, macOS, and Linux via Node.js scripts in the scripts/ directory.

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • hooks/hooks.json
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • scripts/hooks/governance-capture.js
  • tests/hooks/gateguard-fact-force.test.js
  • scripts/hooks/gateguard-fact-force.js
{scripts,bin}/**

⚙️ CodeRabbit configuration file

{scripts,bin}/**: Focus on command injection, unsafe subprocess usage, path traversal, SSRF, secret exposure, and missing tests for new CLI behavior.

Files:

  • scripts/hooks/posttooluse-dispatcher.js
  • scripts/hooks/governance-capture.js
  • scripts/hooks/gateguard-fact-force.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • tests/hooks/gateguard-fact-force.test.js
tests/**

📄 CodeRabbit inference engine (AGENTS.md)

Maintain the project's test suite under the tests/ directory.

Files:

  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • tests/hooks/gateguard-fact-force.test.js
hooks/**/*.json

📄 CodeRabbit inference engine (CLAUDE.md)

Hooks should be formatted as JSON with matcher conditions and hooks array.

Files:

  • hooks/hooks.json
🧠 Learnings (2)
📚 Learning: 2026-06-27T23:49:19.839Z
Learnt from: gaurav0107
Repo: affaan-m/ECC PR: 2373
File: tests/hooks/observe-signal-timeout.test.js:0-0
Timestamp: 2026-06-27T23:49:19.839Z
Learning: In tests under tests/hooks that require a Python runtime to run, the test should fail fast when Python isn’t available (or prerequisites aren’t met). Do not treat a missing Python runtime as test.skip, as an expected/allowed condition, or as a passing state; instead, explicitly fail (e.g., throw/return a rejected promise or use a test runner fail/expect that marks the test as failed) so reviewers can’t accidentally mask environment issues.

Applied to files:

  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • tests/hooks/gateguard-fact-force.test.js
📚 Learning: 2026-07-14T03:26:12.530Z
Learnt from: thejesh23
Repo: affaan-m/ECC PR: 2517
File: tests/hooks/pre-bash-tmux-reminder.test.js:21-25
Timestamp: 2026-07-14T03:26:12.530Z
Learning: In this repository, do not flag `console.log` usage as a guideline violation in hook test files under `tests/hooks/*.test.js`. These tests intentionally use `console.log` for pass/fail output because the repo’s console-based runner (`tests/run-all.js`) is used and there is no Jest/Mocha dependency. Outside this specific hook-test path, follow the normal logging guidelines.

Applied to files:

  • tests/hooks/posttooluse-dispatcher.test.js
  • tests/hooks/governance-capture.test.js
  • tests/hooks/hooks.test.js
  • tests/hooks/gateguard-fact-force.test.js
🪛 ast-grep (0.45.1)
tests/hooks/hooks.test.js

[warning] 2586-2586: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.readFileSync(hooksPath, 'utf8')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

🔇 Additional comments (19)
tests/hooks/gateguard-fact-force.test.js (3)

2516-2535: 📐 Maintainability & Code Quality | 💤 Low value

Grouped expectPsDeny calls stop at the first failure.

Lines 2518-2521 and 2528-2531 assert several independent commands in one test case. If -Rec fails, -r is never evaluated, and the alias sweep reports one failure instead of four. The same pattern repeats at Lines 2546-2549 and 2564-2567.

The label argument keeps the failing case identifiable, so this is diagnosability, not correctness. Consider a table-driven loop that reports each command as its own case.

As per coding guidelines, tests must "use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test".

Source: Coding guidelines


2459-2496: LGTM!


2592-2682: LGTM!

tests/hooks/governance-capture.test.js (3)

362-368: 🎯 Functional Correctness | ⚡ Quick win

The assertions still do not prove which rule matched.

Lines 363-367 assert only length > 0. A future broader entry in APPROVAL_COMMANDS would satisfy these assertions while the abbreviated-parameter rule at scripts/hooks/governance-capture.js Line 51 is broken. Assert the expected finding.pattern instead.

The PR objectives list abbreviated parameter support as an explicit requirement.

💚 Proposed fix
+  const PS_RECURSE_PATTERN_FRAGMENT = 'Remove-ItemProperty';
+
   if (await test('detectApprovalRequired flags PowerShell recursive deletes', async () => {
-    assert.ok(detectApprovalRequired('Remove-Item -Recurse -Force C:/tmp/demo').length > 0);
-    // PowerShell accepts any unambiguous parameter prefix.
-    assert.ok(detectApprovalRequired('Remove-Item -Rec C:/tmp/demo').length > 0);
-    assert.ok(detectApprovalRequired('rd -Recurse C:/tmp/demo').length > 0);
-    assert.ok(detectApprovalRequired('rm -Recurse C:/tmp/demo').length > 0);
+    // PowerShell accepts any unambiguous parameter prefix, so each spelling must
+    // match the dedicated PowerShell rule, not merely "some" rule.
+    for (const command of [
+      'Remove-Item -Recurse -Force C:/tmp/demo',
+      'Remove-Item -Rec C:/tmp/demo',
+      'rd -Recurse C:/tmp/demo',
+      'rm -Recurse C:/tmp/demo',
+    ]) {
+      const findings = detectApprovalRequired(command);
+      assert.ok(
+        findings.some(f => f.pattern.includes(PS_RECURSE_PATTERN_FRAGMENT)),
+        `${command} should match the PowerShell delete rule, got: ${JSON.stringify(findings)}`
+      );
+    }
   })) passed += 1; else failed += 1;

388-398: 📐 Maintainability & Code Quality | 💤 Low value

The elevated-privilege cases still share one test.

Start-Process -Verb RunAs, Set-Acl, and takeown run in one loop. A failure on the first command stops the other two. Line 396 also omits an assertion message, so a wrong reason would not name the offending command.

At minimum, add the command to the Line 396 message.

As per coding guidelines, tests must "use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test".

Source: Coding guidelines


370-386: LGTM!

scripts/hooks/gateguard-fact-force.js (4)

44-44: LGTM!

Also applies to: 718-758


838-875: LGTM!


877-928: LGTM!


1332-1332: LGTM!

Also applies to: 1400-1400, 1451-1463, 1487-1488

scripts/hooks/governance-capture.js (3)

37-53: LGTM!


185-186: LGTM!


231-237: LGTM!

hooks/hooks.json (2)

16-27: LGTM!


64-64: LGTM!

scripts/hooks/posttooluse-dispatcher.js (1)

29-29: LGTM!

tests/hooks/hooks.test.js (1)

2544-2563: LGTM!

tests/hooks/posttooluse-dispatcher.test.js (2)

33-35: LGTM!


131-135: LGTM!

Comment on lines +729 to +731
const PS_DELETE_VERBS = new Set([
'remove-item', 'remove-itemproperty', 'ri', 'rm', 'rmdir', 'rd', 'del', 'erase',
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Clear-Content, Clear-Disk, and Format-Volume are gated by governance capture but not by the gate.

scripts/hooks/governance-capture.js Lines 52-53 add Clear-(?:Content|Disk) and Format-Volume to APPROVAL_COMMANDS. isDestructivePowerShell has no equivalent. PS_DELETE_VERBS at Lines 729-731 lists only Remove-Item and its aliases, and the regexes at Lines 740-743 cover only .NET delete and cmd recursive delete.

Result: Format-Volume -DriveLetter D emits an approval_requested event but passes the destructive gate once the session routine gate is satisfied. The audit record and the enforcement decision disagree — the same class of gap reported earlier for the rm alias, in the opposite direction.

Add a data-destruction verb set that is gated independently of -Recurse / -Force, since these cmdlets destroy content without either parameter.

🔒 Proposed fix: gate content-destroying cmdlets
 const PS_DELETE_VERBS = new Set([
   'remove-item', 'remove-itemproperty', 'ri', 'rm', 'rmdir', 'rd', 'del', 'erase',
 ]);
+
+// Cmdlets that destroy data without a delete verb and without -Recurse/-Force.
+// Gated on presence alone, matching the governance-capture approval patterns.
+const PS_DATA_DESTROYERS = new Set([
+  'clear-content', 'clear-disk', 'format-volume',
+]);
   for (const tokens of quoteAwareSegments(raw)) {
     if (tokens.length === 0) continue;
 
     const verb = commandBasename(tokens[0]);
     const rest = tokens.slice(1);
+
+    if (PS_DATA_DESTROYERS.has(verb)) return true;
 
     if (PS_NESTED_SHELLS.has(verb)) {

Also applies to: 784-798

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/hooks/gateguard-fact-force.js` around lines 729 - 731, Extend the
PowerShell destructive-command detection around PS_DELETE_VERBS and
isDestructivePowerShell to include Clear-Content, Clear-Disk, and Format-Volume
in a separate data-destruction verb set. Gate these verbs independently of
-Recurse and -Force, while preserving existing Remove-Item, .NET delete, and cmd
recursive-delete handling.

Comment on lines +760 to +766
/**
* Detect destructive PowerShell commands.
*
* Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not
* `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any
* delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as
* its `rm -f notes.txt` equivalent does.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

The doc comment contradicts the implemented behavior.

Lines 765-766 state that Remove-Item -Force notes.txt stays ungated. Line 829 gates any -Force prefix, and Lines 827-828 explain why. The test at tests/hooks/gateguard-fact-force.test.js Line 2577 asserts denial for Remove-Item -Force C:/tmp/some-directory.

Correct the doc so a future reader does not treat the -Force gate as a bug.

📝 Proposed doc fix
- * Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not
- * `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any
- * delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as
- * its `rm -f notes.txt` equivalent does.
+ * The hazard class is *recursive, forced, or wildcarded* deletion, not any
+ * delete. A plain `Remove-Item notes.txt` stays ungated. `-Force` is gated even
+ * without `-Recurse`, because `Remove-Item -Force <directory>` removes the tree
+ * and a static string cannot distinguish a file target from a directory target.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* Detect destructive PowerShell commands.
*
* Scoped deliberately to mirror `isDestructiveRm`, which gates `rm -rf` but not
* `rm -f`: the hazard class is *recursive or wildcarded* deletion, not any
* delete. A single-file `Remove-Item -Force notes.txt` stays ungated, exactly as
* its `rm -f notes.txt` equivalent does.
/**
* Detect destructive PowerShell commands.
*
* The hazard class is *recursive, forced, or wildcarded* deletion, not any
* delete. A plain `Remove-Item notes.txt` stays ungated. `-Force` is gated even
* without `-Recurse`, because `Remove-Item -Force <directory>` removes the tree
* and a static string cannot distinguish a file target from a directory target.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/hooks/gateguard-fact-force.js` around lines 760 - 766, Update the
documentation comment for the destructive PowerShell command detector near
isDestructiveRm to accurately describe the implemented behavior: any Remove-Item
-Force prefix is gated, including single-file and directory targets. Remove the
claim that Remove-Item -Force notes.txt remains ungated, while preserving the
explanation that this behavior intentionally differs from the rm -f comparison.

Comment on lines +2691 to +2712
// Regression guard: the routine gate is shared, so PowerShell must not get a
// second first-command gate after Bash has already satisfied it.
if (
test('shares the routine session gate with Bash', () => {
clearState();
writeState({ checked: ['__bash_session__'], last_active: Date.now() });
const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } });
const output = parseOutput(result.stdout);
assert.ok(output, 'PowerShell should produce pass-through JSON');
if (output.hookSpecificOutput) {
assert.notStrictEqual(
output.hookSpecificOutput.permissionDecision,
'deny',
'PowerShell should not re-trigger the routine gate Bash already satisfied'
);
} else {
assert.strictEqual(output.tool_name, 'PowerShell');
}
})
)
passed++;
else failed++;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No test asserts the PowerShell routine-gate hook ID.

run() at scripts/hooks/gateguard-fact-force.js Line 1487 selects POWERSHELL_HOOK_ID for PowerShell routine denials. That selection is the only observable effect of the new constant at Line 44, and no test covers it. The Bash equivalent is covered at Line 559 of this file.

A regression that reverts Line 1487 to BASH_HOOK_ID would print the wrong disable ID to the operator and pass the suite.

💚 Proposed test
+  if (
+    test('routine PowerShell denials name the PowerShell hook disable id', () => {
+      clearState();
+      const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } });
+      const output = parseOutput(result.stdout);
+      assert.ok(output, 'should produce JSON output');
+      const reason = output.hookSpecificOutput.permissionDecisionReason;
+      assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny');
+      assert.ok(reason.includes('pre:powershell:gateguard-fact-force'), 'should show the PowerShell hook ID');
+      assert.ok(!reason.includes('pre:bash:gateguard-fact-force'), 'should not show the Bash hook ID');
+    })
+  )
+    passed++;
+  else failed++;
+
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Regression guard: the routine gate is shared, so PowerShell must not get a
// second first-command gate after Bash has already satisfied it.
if (
test('shares the routine session gate with Bash', () => {
clearState();
writeState({ checked: ['__bash_session__'], last_active: Date.now() });
const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } });
const output = parseOutput(result.stdout);
assert.ok(output, 'PowerShell should produce pass-through JSON');
if (output.hookSpecificOutput) {
assert.notStrictEqual(
output.hookSpecificOutput.permissionDecision,
'deny',
'PowerShell should not re-trigger the routine gate Bash already satisfied'
);
} else {
assert.strictEqual(output.tool_name, 'PowerShell');
}
})
)
passed++;
else failed++;
if (
test('routine PowerShell denials name the PowerShell hook disable id', () => {
clearState();
const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } });
const output = parseOutput(result.stdout);
assert.ok(output, 'should produce JSON output');
const reason = output.hookSpecificOutput.permissionDecisionReason;
assert.strictEqual(output.hookSpecificOutput.permissionDecision, 'deny');
assert.ok(reason.includes('pre:powershell:gateguard-fact-force'), 'should show the PowerShell hook ID');
assert.ok(!reason.includes('pre:bash:gateguard-fact-force'), 'should not show the Bash hook ID');
})
)
passed++;
else failed++;
// Regression guard: the routine gate is shared, so PowerShell must not get a
// second first-command gate after Bash has already satisfied it.
if (
test('shares the routine session gate with Bash', () => {
clearState();
writeState({ checked: ['__bash_session__'], last_active: Date.now() });
const result = runBashHook({ tool_name: 'PowerShell', tool_input: { command: 'Get-Date' } });
const output = parseOutput(result.stdout);
assert.ok(output, 'PowerShell should produce pass-through JSON');
if (output.hookSpecificOutput) {
assert.notStrictEqual(
output.hookSpecificOutput.permissionDecision,
'deny',
'PowerShell should not re-trigger the routine gate Bash already satisfied'
);
} else {
assert.strictEqual(output.tool_name, 'PowerShell');
}
})
)
passed++;
else failed++;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/hooks/gateguard-fact-force.test.js` around lines 2691 - 2712, Add a
regression test near the existing Bash hook-ID assertion that exercises the
PowerShell routine-gate denial path through runBashHook with a PowerShell
command, then assert the emitted denial output references POWERSHELL_HOOK_ID
rather than BASH_HOOK_ID. Keep the test focused on the observable disable ID
selected by run() for PowerShell routine denials.

Comment thread tests/hooks/hooks.test.js
Comment on lines +2591 to +2610
try {
const result = spawnSync(route.hooks[0].command, {
shell: true,
cwd: repoRoot,
input: JSON.stringify({
hook_event_name: 'PreToolUse',
tool_name: 'PowerShell',
tool_input: { command: 'Remove-Item C:/build/*' },
session_id: 'configured-powershell-route'
}),
encoding: 'utf8',
env: {
...process.env,
CLAUDE_PLUGIN_ROOT: repoRoot,
ECC_PLUGIN_ROOT: repoRoot,
ECC_PROFILE: 'standard',
GATEGUARD_STATE_DIR: stateDir
},
timeout: 10000
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

The spawned route inherits GateGuard disable switches from the developer environment.

Line 2603 spreads process.env without clearing the gate opt-outs. ECC_GATEGUARD=off, GATEGUARD_DISABLED=1, or ECC_DISABLED_HOOKS=pre:powershell:gateguard-fact-force in the ambient environment makes the hook pass through, and the assertion at Line 2614 fails with a permissionDecision of undefined rather than a clear cause.

GATEGUARD_STATE_DIR is isolated correctly, so only the disable switches are unpinned.

💚 Proposed fix: pin the disable switches
           env: {
             ...process.env,
             CLAUDE_PLUGIN_ROOT: repoRoot,
             ECC_PLUGIN_ROOT: repoRoot,
             ECC_PROFILE: 'standard',
-            GATEGUARD_STATE_DIR: stateDir
+            GATEGUARD_STATE_DIR: stateDir,
+            // Pin the opt-outs: an ambient disable switch would silently turn
+            // this route into a pass-through and fail the deny assertion below.
+            ECC_GATEGUARD: '',
+            GATEGUARD_DISABLED: '',
+            GATEGUARD_BASH_ROUTINE_DISABLED: '',
+            ECC_DISABLED_HOOKS: ''
           },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const result = spawnSync(route.hooks[0].command, {
shell: true,
cwd: repoRoot,
input: JSON.stringify({
hook_event_name: 'PreToolUse',
tool_name: 'PowerShell',
tool_input: { command: 'Remove-Item C:/build/*' },
session_id: 'configured-powershell-route'
}),
encoding: 'utf8',
env: {
...process.env,
CLAUDE_PLUGIN_ROOT: repoRoot,
ECC_PLUGIN_ROOT: repoRoot,
ECC_PROFILE: 'standard',
GATEGUARD_STATE_DIR: stateDir
},
timeout: 10000
});
try {
const result = spawnSync(route.hooks[0].command, {
shell: true,
cwd: repoRoot,
input: JSON.stringify({
hook_event_name: 'PreToolUse',
tool_name: 'PowerShell',
tool_input: { command: 'Remove-Item C:/build/*' },
session_id: 'configured-powershell-route'
}),
encoding: 'utf8',
env: {
...process.env,
CLAUDE_PLUGIN_ROOT: repoRoot,
ECC_PLUGIN_ROOT: repoRoot,
ECC_PROFILE: 'standard',
GATEGUARD_STATE_DIR: stateDir,
// Pin the opt-outs: an ambient disable switch would silently turn
// this route into a pass-through and fail the deny assertion below.
ECC_GATEGUARD: '',
GATEGUARD_DISABLED: '',
GATEGUARD_BASH_ROUTINE_DISABLED: '',
ECC_DISABLED_HOOKS: ''
},
timeout: 10000
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/hooks/hooks.test.js` around lines 2591 - 2610, Update the spawnSync
environment in the test around the route command to explicitly clear
ECC_GATEGUARD and GATEGUARD_DISABLED and remove the gateguard-fact-force entry
from ECC_DISABLED_HOOKS, while preserving the isolated GATEGUARD_STATE_DIR and
other inherited environment values.

@greptile-apps

greptile-apps Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This change adds dedicated PowerShell GateGuard routing, broader destructive-command detection, governance capture, and hook coverage. Two reproduced failures remain: a destructive command inside a PowerShell $() subexpression bypasses the pre-execution denial, and several destructive operations that GateGuard denies are not recorded as approval requests. The change is not safe to merge until both enforcement and audit coverage are aligned.

Confidence Score: 1/5

Not safe to merge because destructive PowerShell operations can evade the intended pre-execution protection and denied operations can be missing from governance records.

Both failures were reproduced through the configured Node hook entry points with fresh GateGuard state. The subexpression behavior was repeated independently, and the audit mismatch was compared with a working recursive-delete control.

Files Needing Attention: scripts/hooks/gateguard-fact-force.js needs recursive detection of PowerShell subexpression bodies, and scripts/hooks/governance-capture.js needs approval coverage for every destructive PowerShell form that GateGuard denies.

Security Review

PowerShell $() subexpressions allow a destructive Remove-Item operation to reach execution without GateGuard denying it. In addition, force-only, wildcard, and .NET deletion forms that GateGuard denies are absent from the approval audit trail, weakening governance visibility for destructive attempts.

T-Rex T-Rex Logs

What T-Rex did

  • Ran a node hook reproduction to compare direct deletes and PowerShell subexpression deletes, and reviewed the GateGuard regression results.
  • Validated governance behavior by confirming the recursive PowerShell delete control emits an approval audit event and that GateGuard denies three destructive forms without audit events.
  • Investigated direct vs subexpression removal behavior and identified unwrap logic gaps in the PowerShell path within the gate guard code.
  • Validated governance-PowerShell audit validation script, observing four cases complete with exit code 0.
  • Compiled and cross-checked all posted P1 findings with their validation artifacts to prepare a consolidated reviewer view.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (2)

  1. General comment

    P1 PowerShell command substitution bypasses destructive-command gate

    • Bug
      • The Node PowerShell pre-tool hook lets $(Remove-Item -Recurse -Force C:/tmp/demo) pass through on a fresh session, while denying the equivalent direct destructive command. In PowerShell, $() evaluates its enclosed statement, so the delete executes when the tool executes the permitted command.
    • Cause
      • isDestructivePowerShell checks statements and quoteAwareSegments(raw), but does not recursively extract or unwrap PowerShell $() bodies. The segment begins with $( rather than a recognized deletion verb, bypassing the segment-level parameter detection at lines 803-830.
    • Fix
      • Before or alongside statement/segment detection, extract PowerShell subexpression bodies ($(...)) with quote- and nesting-aware parsing and recursively call isDestructivePowerShell on each body. Add a regression test invoking the configured Node PowerShell hook with a fresh state directory and asserting first-attempt denial for $(Remove-Item -Recurse -Force C:/tmp/demo).

    T-Rex Ran code and verified through T-Rex

  2. General comment

    P1 GateGuard-denied destructive PowerShell operations are absent from approval audit events

    • Bug
      • GateGuard denied Remove-Item -Force C:/tmp/demo, Remove-Item C:/build/*, and [System.IO.Directory]::Delete('C:/tmp/demo',$true) at its real pre-hook entry point. For the identical PowerShell tool payloads with governance capture enabled, governance-capture.js emitted zero events, including zero approval_requested events. By contrast, Remove-Item -Recurse -Force C:/tmp/demo was denied and emitted one high-severity approval_requested event.
    • Cause
      • The approval detector at scripts/hooks/governance-capture.js:51 recognizes only Remove-Item aliases followed by a -Recurse parameter prefix. It does not cover GateGuard's additional destructive classifications: -Force directory removal, wildcard targets, or .NET System.IO.Directory/File::Delete calls.
    • Fix
      • Expand APPROVAL_COMMANDS (or share a conservative PowerShell destructive-command classifier with GateGuard) so all GateGuard-denied destructive PowerShell forms generate approval_requested; add end-to-end entry-point tests for force-only, wildcard, and .NET delete forms.

    T-Rex Ran code and verified through T-Rex

Reviews (1): Last reviewed commit: "Merge commit 'd29cf651c795869f733669c33e..." | Re-trigger Greptile

Comment on lines +803 to +830
for (const tokens of quoteAwareSegments(raw)) {
if (tokens.length === 0) continue;

const verb = commandBasename(tokens[0]);
const rest = tokens.slice(1);

if (PS_NESTED_SHELLS.has(verb)) {
if (isDestructiveNestedPsShell(rest, depth)) return true;
continue;
}

if (!PS_DELETE_VERBS.has(verb)) continue;

for (const token of rest) {
// Splatted parameters (`Remove-Item @params`) are opaque to static
// inspection, so a splatted delete is gated rather than assumed safe.
if (token.startsWith('@')) return true;
if (!token.startsWith('-')) {
// PowerShell expands wildcard targets before deletion. Even without
// -Recurse or -Force, one command can therefore remove an unbounded
// number of entries.
if (token.includes('*') || token.includes('?')) return true;
continue;
}
// -Force is gated as well as -Recurse: unlike `rm -f`, PowerShell's
// `Remove-Item -Force <directory>` removes the tree.
if (isPsParamPrefixOf(token, 'recurse') || isPsParamPrefixOf(token, 'force')) {
return true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security PowerShell subexpressions bypass the destructive-command gate

The PowerShell pre-tool hook denies Remove-Item -Recurse -Force C:/tmp/demo, but passes $(Remove-Item -Recurse -Force C:/tmp/demo) through on a fresh session. PowerShell evaluates the statement inside $(), so a destructive deletion can execute without the fact-forcing denial. Recursively inspect quote- and nesting-aware $() bodies with the same destructive-command classifier, and add a regression test for this form.

Rule Used: Treat CLI inputs, URLs, file paths, and subprocess... (source)

Artifacts

Node hook reproduction source comparing direct and PowerShell subexpression deletes

  • This executed Node-only harness sends direct and `$()` PowerShell command strings to the configured hook with fresh state directories and sessions, showing the precise comparison setup.

Initial hook comparison: direct delete denied and subexpression delete passed through

  • This captured first execution shows the direct destructive command denied while the `$()` form is returned unchanged by the Node hook, confirming the bypass.

Repeated hook comparison: direct delete denied and subexpression delete passed through

  • This independently repeated execution with fresh state directories and sessions reproduces the same direct-deny versus subexpression-pass-through result, confirming it is deterministic.

Focused GateGuard regression suite passes without the missing PowerShell subexpression case

  • This captured focused regression run completed with 166 passing tests and zero failures, showing existing coverage does not catch the reproduced PowerShell `$()` bypass.

View artifacts

T-Rex Ran code and verified through T-Rex

/DELETE\s+FROM\s+\w+\s*(?:;|$)/i,
// PowerShell Remove-Item and its aliases with -Recurse. PowerShell accepts any
// unambiguous parameter prefix, so -Recurse, -Rec and -r must all match.
/(?:^|[\s;|(])(?:Remove-Item|Remove-ItemProperty|ri|rm|rmdir|rd|del|erase)\b[^;|]*\s-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?\b/i,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Destructive PowerShell denials are missing approval audit events

GateGuard denies Remove-Item -Force C:/tmp/demo, Remove-Item C:/build/*, and [System.IO.Directory]::Delete('C:/tmp/demo',$true), but governance capture emits no approval_requested event for those same payloads. The current matcher recognizes only Remove-Item-family commands using -Recurse, leaving denied destructive attempts absent from the approval trail. Expand the approval classifier—or share GateGuard's classifier—so every destructive PowerShell form GateGuard denies is recorded.

Artifacts

Node validation source for GateGuard and governance audit behavior

  • This executable Node harness sends identical safe JSON payloads to the real GateGuard and governance-capture entry points without executing PowerShell, proving the audit mismatch.

Recursive PowerShell delete control emits approval audit event

  • This direct governance-capture control run shows that the supported Remove-Item -Recurse form emits a high-severity approval_requested event.

GateGuard denies three destructive PowerShell forms without audit events

  • This executed harness output shows GateGuard denies all representative forms but governance capture emits no approval_requested event for force-only, wildcard, and .NET deletion.

View artifacts

T-Rex Ran code and verified through T-Rex

@haelyra haelyra left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for taking on the PowerShell gap, and I am sorry this has waited so long. The direction is valuable and fits the ECC 2.2 security and evidence substrate, but I cannot merge the exact head while two reproduced gaps remain: a destructive command inside a PowerShell $() subexpression bypasses the pre-execution gate, and force-only, wildcard, plus .NET deletion forms can be denied without matching approval_requested evidence. Please add quote-aware recursive subexpression parsing, align the governance classifier with every PowerShell form the gate denies, and cover those cases through the configured hook entry points. If you do not have bandwidth for that revision, no problem; I queued ECC-039 so maintainers can finish it after ECC 2.2. Thank you again for pushing this safety surface forward.

@haelyra

haelyra commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Thank you for catching the PowerShell GateGuard gap. This was a real security hole: before your PR, a destructive PowerShell command had no dedicated pre-execution route at all. I am sorry it took us this long to close the loop on this thread.

Your PR became the source for the maintainer fix in #2961 (merged September 7), which ported your route and detection inventory, then added quote-aware $() subexpression scanning and matching governance evidence for every form the gate denies. I re-checked current main today: recursive, force-only, wildcard, nested $(), pipelined Get-ChildItem | Remove-Item, and .NET Directory::Delete forms are all classified as destructive. Since main now covers this, we are closing this PR to keep the queue clear. Thank you again, and focused follow-ups on GateGuard coverage are always welcome.

@haelyra haelyra closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants