Commit Graph

78 Commits

  • fix(hooks): avoid escaped quotes in plugin bootstrap
    Generate the inline hook root resolver with single-quoted JavaScript literals so Windows Git Bash does not choke on nested escaped double quotes before Node starts. Refresh hooks.json and add regression coverage for parsed hook commands and installed hook manifests.
  • feat: add ECC statusline observability hooks
    Salvages the useful statusline/context monitor work from stale PR #1504 while preserving the current continuous-learning hook runner wiring.
    
    Adds the metrics bridge, context monitor, statusline script, shared cost/session bridge utilities, and tests. Fixes the reviewed false loop-detection hash collision for non-file tools, avoids default-session cost inflation, sanitizes statusline task lookup, and records hook payload session IDs in cost-tracker.
  • Merge pull request #1367 from ozoz5/feat/gateguard
    feat(hooks,skills): add gateguard fact-forcing pre-action gate
  • fix: address PR review comments on block-no-verify hook
    - Add `minimal` profile so the security hook runs in all profiles
    - Scope -n/--no-verify flag check to the detected subcommand region,
      preventing false positives on chained commands (e.g. `git log -n 10`)
    - Guard stdin listeners with `require.main === module` so require()
      from run-with-flags.js does not register unnecessary listeners
    - Verify subcommand token is preceded only by flags/flag-args after
      "git", preventing misclassification of argument values as subcommands
    - Add integration tests for block-no-verify hook
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
  • fix: route block-no-verify hook through run-with-flags.js
    Replace inline `npx block-no-verify@1.1.2` with a standalone Node.js
    script routed through `run-with-flags.js`, matching every other hook.
    
    Fixes two bugs:
    1. npx inherits the project cwd and triggers EBADDEVENGINES in
       pnpm-only projects that set devEngines.packageManager.onFail=error.
    2. The hook bypassed run-with-flags.js so ECC_DISABLED_HOOKS had no
       effect — the isHookEnabled() check never ran.
    
    The new script replicates the full block-no-verify@1.1.2 detection
    logic (--no-verify, -n shorthand for commit, core.hooksPath override)
    with zero external dependencies.
    
    Closes #1378
  • fix: gate MultiEdit tool alongside Edit/Write
    MultiEdit was bypassing the fact-forcing gate because only Edit and
    Write were checked. Now MultiEdit triggers the same edit gate (list
    importers, public API, data schemas) before allowing file modifications.
    
    Updated both the hook logic and hooks.json matcher pattern.
    
    Addresses coderabbit/greptile/cubic-dev: "MultiEdit bypasses gate"
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • fix: address P1 review feedback from greptile bot
    1. Use run-with-flags.js wrapper (supports ECC_HOOK_PROFILE, ECC_DISABLED_HOOKS)
    2. Add session timeout (30min inactivity = state reset, fixes "once ever" bug)
    3. Add 9 integration tests (deny/allow/timeout/sanitize/disable)
    
    Refactored hook to module.exports.run() pattern for direct require() by
    run-with-flags.js (~50-100ms faster per invocation).
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • feat(hooks,skills): add gateguard fact-forcing pre-action gate
    A PreToolUse hook that forces Claude to investigate before editing.
    Instead of self-evaluation ("are you sure?"), it demands concrete facts:
    importers, public API, data schemas, user instruction.
    
    A/B tested: +2.25 quality points (9.0 vs 6.75) across two independent tasks.
    
    - scripts/hooks/gateguard-fact-force.js — standalone Node.js hook
    - skills/gateguard/SKILL.md — skill documentation
    - hooks/hooks.json — PreToolUse entries for Edit|Write and Bash
    
    Full package with config: pip install gateguard-ai
    Repo: https://github.com/zunoworks/gateguard
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • perf(hooks): batch format+typecheck at Stop instead of per Edit (#746)
    * perf(hooks): batch format+typecheck at Stop instead of per Edit
    
    Fixes #735. The per-edit post:edit:format and post:edit:typecheck hooks
    ran synchronously after every Edit call, adding 15-30s of latency per
    file — up to 7.5 minutes for a 10-file refactor.
    
    New approach:
    - post-edit-accumulator.js (PostToolUse/Edit): lightweight hook that
      records each edited JS/TS path to a session-scoped temp file in
      os.tmpdir(). No formatters, no tsc — exits in microseconds.
    - stop-format-typecheck.js (Stop): reads the accumulator once per
      response, groups files by project root and runs the formatter in
      one batched invocation per root, then groups .ts/.tsx files by
      tsconfig dir and runs tsc once per tsconfig. Clears the accumulator
      immediately on read so repeated Stop calls don't double-process.
    
    For a 10-file refactor: was 10 × (15s + 30s) = 7.5 min overhead,
    now 1 × (batch format + batch tsc) = ~5-30s total.
    
    * fix(hooks): address race condition, spawn timeout, and Windows path guard
    
    Three issues raised in code review:
    
    1. Race condition: switched accumulator from non-atomic JSON
       read-modify-write to appendFileSync (one path per line). Concurrent
       Edit hook processes each append independently without clobbering each
       other. Deduplication moved to the Stop hook at read time.
    
    2. Effective timeout: added run() export to stop-format-typecheck.js so
       run-with-flags.js uses the direct require() path instead of falling
       through to spawnSync (which has a hardcoded 30s cap). The 120s
       timeout in hooks.json now governs the full batch as intended.
    
    3. Windows path guard: added spaces and parentheses to UNSAFE_PATH_CHARS
       so paths like "C:\Users\John Doe\project\file.ts" are caught before
       being passed to cmd.exe with shell: true.
    
    * fix(hooks): fix session fallback, stale comment, trim verbose comments
    
    - Replace 'default' session ID fallback with a cwd-based sha1 hash so
      concurrent sessions in different projects don't share the same
      accumulator file when CLAUDE_SESSION_ID is unset
    - Remove stale "JSON file" reference in accumulator header (format is
      now newline-delimited plain text)
    - Remove redundant/verbose inline comments throughout both files
    
    * fix(hooks): sanitize session ID, fix Windows tsc, proportional timeouts
    
    - Sanitize CLAUDE_SESSION_ID with /[^a-zA-Z0-9_-]/g before embedding in
      the temp filename so crafted separators or '..' sequences cannot escape
      os.tmpdir() (cubic P1)
    - Fix typecheckBatch on Windows: npx.cmd requires shell:true like
      formatBatch already does; use spawnSync and extract stdout/stderr from
      the result object (coderabbit P1)
    - Proportional per-batch timeouts: divide 270s budget across all format
      and typecheck batches so sequential runs in monorepos stay within the
      Stop hook wall-clock limit (greptile P2)
    - Raise Stop hook timeout from 120s to 300s to give large monorepos
      adequate headroom (cubic P2)
    
    * fix(hooks): extend accumulator to Write|MultiEdit, fix tests
    
    - Extend matcher from Edit to Edit|Write|MultiEdit so files created with
      Write and all files in a MultiEdit batch are included in the Stop-time
      format+typecheck pass (cubic P1)
    - Handle tool_input.edits[] array in accumulator for MultiEdit support
    - Rename misleading 'concurrent writes' test to clarify it tests append
      preservation, not true concurrency (cubic P2)
    - Add Stop hook dedup test: writes duplicate paths to accumulator and
      verifies the hook clears it cleanly (cubic P2)
    - Add Write and MultiEdit accumulation tests
    
    * fix(hooks): move timeout to command level, add dedup unit tests
    
    - Move timeout: 300 from the matcher object to the hook command object
      where it is actually enforced; the previous position was a no-op
      (cubic P2)
    - Extract parseAccumulator() and export it so tests can assert dedup
      behavior directly without relying only on side effects (cubic P2)
    - Add two unit tests for parseAccumulator: deduplication and blank-line
      handling; rename the integration test to match its scope
    
    * fix(hooks): replace removed format/typecheck hooks with accumulator in cursor adapter
  • fix(hooks): collapse multi-line commands in bash audit logs (#741)
    * fix(hooks): collapse multi-line commands in bash audit logs
    
    Add gsub("\\n"; " ") to jq filters in bash audit log and cost-tracker
    hooks so multi-line commands produce single-line log entries, preventing
    breakage in downstream line-based parsing.
    
    Fixes #734
    
    * fix: forward stdin to downstream hooks using echo pattern
    
    Addresses review feedback: PostToolUse hooks now preserve stdin
    for subsequent hooks by echoing $INPUT back to stdout after
    processing. Changed ; to && for proper error propagation.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
    
    * fix: make stdin passthrough unconditional and broaden secret redaction
    
    - Use semicolons instead of && so printf passthrough always runs
      even if jq fails
    - Add || true after jq to prevent non-zero exit on parse errors
    - Use printf '%s\n' instead of echo for safe binary passthrough
    - Fix Authorization pattern to handle 'Bearer <token>' with space
    - Add ASIA (STS temp credentials) alongside AKIA redaction
    - Add GitHub token patterns (ghp_, gho_, ghs_, github_pat_)
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
    
    * fix: use [: ]* instead of s* for Authorization whitespace matching
    
    jq's ONIG regex engine interprets s* as literal 's' zero-or-more,
    not \s* (whitespace). This caused 'Authorization: Bearer <token>'
    to only redact 'Authorization:' and leak the actual token.
    
    Using [: ]* avoids the JSON/jq double-escape issue entirely and
    correctly matches both 'Authorization: Bearer xyz' and
    'Authorization:xyz' patterns.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
  • fix: extract inline SessionStart bootstrap to separate file (#1035)
    Inline `node -e "..."` in hooks.json contained `!` characters (e.g.
    `!org.isDirectory()`) that bash history expansion in certain shell
    environments would misinterpret, producing syntax errors and the
    "SessionStart:startup hook error" banner in the Claude Code CLI header.
    
    Extract the bootstrap logic to `scripts/hooks/session-start-bootstrap.js`
    so the shell never sees the JS source. Behaviour is identical: the script
    reads stdin, resolves the ECC plugin root via CLAUDE_PLUGIN_ROOT or a set
    of well-known fallback paths, then delegates to run-with-flags.js.
    
    Update the test that asserted the old inline pattern to verify the new
    file-based approach instead.
    
    Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
  • feat(hooks): add WSL desktop notification support via PowerShell + BurntToast (#1019)
    * fix(hooks): add WSL desktop notification support via PowerShell + BurntToast
    
    Adds WSL (Windows Subsystem for Linux) desktop notification support to the
    existing desktop-notify hook. The hook now detects WSL, finds available
    PowerShell (7 or Windows PowerShell), checks for BurntToast module, and
    sends Windows toast notifications.
    
    New functions:
    - isWSL(): detects WSL environment
    - findPowerShell(): finds PowerShell 7 or Windows PowerShell on WSL
    - isBurntToastAvailable(): checks if BurntToast module is installed
    - notifyWindows(): sends Windows toast notification via BurntToast
    
    If BurntToast is not installed, logs helpful tip for installation.
    Falls back silently on non-WSL/non-macOS platforms.
    
    * docs(hooks): update desktop-notify description to include WSL
    
    Updates the hook description in hooks.json to reflect the newly
    added WSL notification support alongside macOS.
    
    * fix(hooks): capture stderr properly in notifyWindows
    
    Change stdio to ['ignore', 'pipe', 'pipe'] so stderr is captured
    and can be logged on errors. Without this, result.stderr is null
    and error logs show 'undefined' instead of the actual error.
    
    * fix(hooks): quote PowerShell path in install tip for shell safety
    
    The PowerShell path contains spaces and needs to be quoted
    when displayed as a copy-pasteable command.
    
    * fix(hooks): remove external repo URL from tip message
    
    BurntToast module is a well-known Microsoft module but per project
    policy avoiding unvetted external links in user-facing output.
    
    * fix(hooks): probe WSL interop PATH before hardcoded paths
    
    Adds 'pwsh.exe' and 'powershell.exe' as candidates to leverage
    WSL's Windows interop PATH resolution, making the hook work with
    non-default WSL mount prefixes or Windows drives.
    
    * perf(hooks): memoize isWSL detection at module load
    
    Avoids reading /proc/version twice (once in run(), once in findPowerShell())
    by computing the result once when the module loads.
    
    * perf(hooks): reduce PowerShell spawns from 3 to 1 per notification
    
    Merge findPowerShell version check and isBurntToastAvailable check
    into a single notifyWindows call. Now just tries to send directly;
    if it fails, tries next PowerShell path. Version field was unused.
    
    Net effect: up to 3 spawns reduced to 1 in the happy path.
    
    * fix(hooks): remove duplicate notifyWindows declaration
    
    There were two notifyWindows function declarations due to incomplete
    refactoring. Keeps only the version that returns true/false for the
    call site. Node.js would throw SyntaxError with 'use strict'.
    
    * fix(hooks): improve error handling and detection robustness
    
    - Increase PowerShell detection timeout from 1s to 3s to avoid false
      negatives on slower/cold WSL interop startup
    - Return error reason from notifyWindows to distinguish BurntToast
      module not found vs other PowerShell errors
    - Log actionable error details instead of always showing install tip
    
    ---------
    
    Co-authored-by: boss <boss@example.com>
  • feat(hooks): add pre-commit quality check hook
    - Add pre-bash-commit-quality.js hook script
    - Runs quality checks before git commit commands:
      - Lints staged files (ESLint, Pylint, golint)
      - Validates commit message format (conventional commits)
      - Detects console.log/debugger statements
      - Warns about TODO/FIXME without issue references
      - Detects potential hardcoded secrets
    - Updates hooks.json with new hook configuration
    - Updates README.md with hook documentation
    
    Cross-platform (Windows, macOS, Linux)
  • Merge pull request #846 from pythonstrup/feat/desktop-notify-hook
    feat: add macOS desktop notification Stop hook
  • fix: add spawnSync error logging and restore 5s timeout
    - Check spawnSync result and log warning on failure via stderr
    - Restore osascript timeout to 5000ms, increase hook deadline to 10s
      for sufficient headroom
  • feat: add macOS desktop notification Stop hook
    Add a new Stop hook that sends a native macOS notification with the
    task summary (first line of last_assistant_message) when Claude finishes
    responding. Uses osascript via spawnSync for shell injection safety.
    Supports run-with-flags fast require() path. Only active on standard
    and strict profiles; silently skips on non-macOS platforms.
  • perf(hooks): move post-edit-format and post-edit-typecheck to strict-only (#757)
    * perf(hooks): move post-edit-format and post-edit-typecheck to strict-only
    
    These hooks fire synchronously on every Edit call with 15-30s timeouts
    each. During multi-file refactors this adds 5-10 minutes of overhead.
    
    Moving them from standard,strict to strict-only means they won't fire
    in the default profile but are still available for users who want the
    extra validation.
    
    Fixes #735
    
    * Also update OpenCode plugin to strict-only for format/typecheck
    
    The OpenCode plugin had the same standard,strict profile for
    post:edit:format and post:edit:typecheck, so OpenCode users on the
    default profile would still get the per-edit overhead.
  • feat(hooks): add config protection hook to block linter config manipulation (#758)
    * feat(hooks): add config protection hook to block linter config manipulation
    
    Agents frequently modify linter/formatter configs (.eslintrc, biome.json,
    .prettierrc, .ruff.toml, etc.) to make checks pass instead of fixing
    the actual code.
    
    This PreToolUse hook intercepts Write/Edit/MultiEdit calls targeting
    known config files and blocks them with a steering message that directs
    the agent to fix the source code instead.
    
    Covers: ESLint, Prettier, Biome, Ruff, ShellCheck, Stylelint, and
    Markdownlint configs.
    
    Fixes #733
    
    * Address review: fix dead code, add missing configs, export run()
    
    - Removed pyproject.toml from PROTECTED_FILES (was dead code since
      it was also in PARTIAL_CONFIG_FILES). Added comment explaining why
      it's intentionally excluded.
    - Removed PARTIAL_CONFIG_FILES entirely (no longer needed).
    - Added missing ESLint v9 TypeScript flat configs: eslint.config.ts,
      eslint.config.mts, eslint.config.cts
    - Added missing Prettier ESM config: prettier.config.mjs
    - Exported run() function for in-process execution via run-with-flags,
      avoiding the spawnSync overhead (~50-100ms per call).
    
    * Handle stdin truncation gracefully, log warning instead of fail-open
    
    If stdin exceeds 1MB, the JSON would be malformed and the catch
    block would silently pass through. Now we detect truncation and
    log a warning. The in-process run() path is not affected.
  • feat: add block-no-verify hook for Claude Code and Cursor (#649)
    Adds npx block-no-verify@1.1.2 as a PreToolUse Bash hook in hooks/hooks.json
    and a beforeShellExecution hook in .cursor/hooks.json to prevent AI agents
    from bypassing git hooks via the hook-bypass flag.
    
    This closes the last enforcement gap in the ECC security stack — the bypass
    flag silently skips pre-commit, commit-msg, and pre-push hooks.
    
    Closes #648
    
    Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
  • feat: agent compression, inspection logic, governance hooks (#491, #485, #482) (#688)
    Implements three roadmap features:
    
    - Agent description compression (#491): New `agent-compress` module with
      catalog/summary/full compression modes and lazy-loading. Reduces ~26k
      token agent descriptions to ~2-3k catalog entries for context efficiency.
    
    - Inspection logic (#485): New `inspection` module that detects recurring
      failure patterns in skill_runs. Groups by skill + normalized failure
      reason, generates structured reports with suggested remediation actions.
      Configurable threshold (default: 3 failures).
    
    - Governance event capture hook (#482): PreToolUse/PostToolUse hook that
      detects secrets, policy violations, approval-required commands, and
      elevated privilege usage. Gated behind ECC_GOVERNANCE_CAPTURE=1 flag.
      Writes to governance_events table via JSON-line stderr output.
    
    59 new tests (16 + 16 + 27), all passing.
  • fix: address cubic-dev-ai review — 3 issues
    P1: Log non-ENOENT spawn errors (timeout, signal kill) to stderr
    instead of silently exiting 0. Separate handling for result.error
    and null result.status so users know when the security monitor
    failed to run.
    
    P1: Remove "async": true from hooks.json — async hooks run in the
    background and cannot block tool execution. The security hook needs
    to be synchronous so exit(2) actually prevents credential exposure
    and other critical findings from proceeding.
    
    P2: Remove dead tool_response/tool_result code from extract_content.
    In a PreToolUse hook the tool hasn't executed yet, so tool_response
    is never populated. Removed the variable and the unreachable branch
    that appended its content.
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • fix: address CodeRabbit review — convert to PreToolUse, add type annotations, logging
    Critical fixes:
    - Convert hook from PostToolUse to PreToolUse so exit(2) blocking works
    - Change all python references to python3 for cross-platform compat
    - Add insaits-security-wrapper.js to bridge run-with-flags.js to Python
    
    Standard fixes:
    - Wrap hook with run-with-flags.js so users can disable via
      ECC_DISABLED_HOOKS="pre:insaits-security"
    - Add "async": true to hooks.json entry
    - Add type annotations to all function signatures (Dict, List, Tuple, Any)
    - Replace all print() statements with logging module (stderr)
    - Fix silent OSError swallow in write_audit — now logs warning
    - Remove os.environ.setdefault('INSAITS_DEV_MODE') — pass dev_mode=True
      through monitor constructor instead
    - Update hooks/README.md: moved to PreToolUse table, "detects" not
      "catches", clarify blocking vs non-blocking behavior
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • feat: add InsAIts PostToolUse security monitoring hook
    - Add insaits-security-monitor.py: real-time AI security monitoring
      hook that catches credential exposure, prompt injection,
      hallucinations, and 20+ other anomaly types
    - Update hooks.json with InsAIts PostToolUse entry
    - Update hooks/README.md with InsAIts in PostToolUse table
    - Add InsAIts MCP server entry to mcp-configs/mcp-servers.json
    
    InsAIts (https://github.com/Nomadu27/InsAIts) is an open-source
    runtime security layer for multi-agent AI. It runs 100% locally
    and writes tamper-evident audit logs to .insaits_audit_session.jsonl.
    
    Install: pip install insa-its
    
    Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
  • fix: auto-start dev servers in tmux instead of blocking (#344)
    * fix: auto-start development servers in tmux instead of blocking
    
    Replace blocking PreToolUse hook that used process.exit(2) with an auto-transform hook that:
    - Detects development server commands
    - Wraps them in tmux with directory-based session names
    - Runs server detached so Claude Code is not blocked
    - Provides confirmation message with log viewing instructions
    
    Benefits:
    - Development servers no longer block Claude Code execution
    - Each project gets its own tmux session (allows multiple projects)
    - Logs remain accessible via 'tmux capture-pane -t <session>'
    - Non-blocking: if tmux unavailable, command still runs (graceful fallback)
    
    Implementation:
    - Created scripts/hooks/auto-tmux-dev.js with transform logic
    - Updated hooks.json to reference the script instead of inline node command
    - Applied same fix to cached plugin version (1.4.1) for immediate effect
    
    * fix: resolve PR #344 code review issues in auto-tmux-dev.js
    
    Critical fixes:
    - Fix variable scope: declare 'input' before try block, not inside
    - Fix shell injection: sanitize sessionName and escape cmd for shell
    - Replace unused execFileSync import with spawnSync
    
    Improvements:
    - Add real Windows support using cmd /k window launcher
    - Add tmux availability check with graceful fallback
    - Update header comment to accurately describe platform support
    
    Test coverage:
    - Valid JSON input: transforms command for respective platform
    - Invalid JSON: passes through raw data unchanged
    - Unsupported tools: gracefully falls back to original command
    - Shell metacharacters: sanitized in sessionName, escaped in cmd
    
    * fix: correct cmd.exe escape sequence for double quotes on Windows
    
    Use double-quote doubling ('""') instead of backslash-escape ('\\\") for cmd.exe syntax.
    Backslash escaping is Unix convention and not recognized by cmd.exe. This fixes quoted
    arguments in dev server commands on Windows (e.g., 'npm run dev --filter="my-app"').