73 Commits
Author SHA1 Message Date
01e15490f0 fix(skill-evolution): wire Skill PostToolUse tracker so skill-health shows real runs (#2490)
* fix(skill-evolution): wire Skill PostToolUse tracker so skill-health shows real runs (#2463)

recordSkillExecution() had no production callers, so
~/.claude/state/skill-runs.jsonl was never written and
`scripts/skills-health.js --dashboard` always reported 0 runs.

Adds scripts/hooks/skill-run-tracker.js and registers it as an async
PostToolUse hook (matcher: Skill) in posttooluse-dispatcher.js, which is now
the single PostToolUse entrypoint on main.

Addresses the privacy and bounds review on #2555's sibling PR:

- No prompt text is persisted. task_description is synthesized as
  "Skill invocation: <skill_id>"; tool_input.task_description/description/
  prompt are never read.
- Every persisted string is bounded and charset-restricted. A skill id is an
  identifier, so free text, newlines, or an over-long value are dropped rather
  than truncated and written through.
- The JSONL sink is created 0600 and re-tightened on each append, repairing
  files written before this bound existed.
- The sink is capped at MAX_RUN_RECORDS (5000), trimmed oldest-first, so the
  append-only file can no longer grow without limit.

Tests cover the privacy guarantee (no prompt text reaches a record), the
identifier bounds, the file mode on POSIX, and the retention cap.

* fix(skill-evolution): re-register the tracker for PostToolUseFailure

The rebase onto current main dropped the hooks.json entry, which silently
resurrected the P1 from the earlier review round: deriveOutcome() still
branches on hook_event_name === 'PostToolUseFailure', but the PostToolUse
dispatcher does not fan that event out, so the branch was unreachable in
production. Hard Skill failures were dropped from telemetry entirely, which
inflates the dashboard success rate — the opposite of what #2463 asks for.

Restores the dedicated PostToolUseFailure entry (matcher Skill, id
post:skill:track, same run-with-flags wrapper and standard,strict gating as
the dispatcher registration). Verified end-to-end: a PostToolUseFailure
payload piped through run-with-flags now records outcome "failure".

Adds a regression test asserting the registration so a future rebase cannot
quietly drop it again.

---------

Co-authored-by: haelyra <49814733+haelyra@users.noreply.github.com>
2026-08-12 18:12:49 -04:00
ae303fb6c1 fix(plan-canvas): deliver browser chat to the agent every time (#2739)
Feedback sent from the canvas only reached an agent through a live
/api/await long poll. When a turn ended with no await parked,
queueFeedback wrote the message to sessions.json and nothing ever
consumed it, so sending appeared to do nothing at all. The presence pill
made it worse: workingKeys had no expiry and the feedback handler never
broadcast presence, so it froze on "agent working" while nobody was
listening.

Delivery:
- Add the stop:plan-canvas-pending hook. It drains undelivered feedback
  and blocks the Stop, handing the messages to the agent, so a canvas
  message lands even when no await is running. Scoped to sessions under
  cwd so parallel agents cannot swallow each other's feedback; set
  ECC_PLAN_CANVAS_STOP_SCOPE=all to widen. Honors stop_hook_active and
  fails open on every error path.
- run-with-flags.js did not await a hook's run(), so any async hook
  silently degraded to pass-through. Fixed; plan-canvas-pending is the
  only async hook today.

Presence and indicators:
- Presence is now ended/typing/thinking/listening/queued/waiting.
  thinking and typing self-expire (90s/30s) and a 5s sweep pushes the
  decay to an idle browser, so the pill can no longer stick.
- Broadcast presence when feedback is queued, and clear the activity
  state when an agent reply lands.
- Add POST /api/session/:key/typing so agents can drive the indicator.
- Chat shows an animated dots bubble for thinking and typing, plus an
  explicit note when a message is queued with nobody listening.
  Respects prefers-reduced-motion.
- Send status reports what actually happened instead of always claiming
  the agent will pick it up.

CLI and skill:
- Add `ecc-plan-canvas pending` and `typing <file> --state ...`.
- SKILL.md documents background await as the primary pattern and makes
  replying in the canvas mandatory.

Tests: 6 new server cases covering queued presence, the typing endpoint,
state expiry and the sweep, plus a new hook suite covering delivery,
drain-once, stop_hook_active, cwd scoping and fail-open.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-09 18:15:25 -04:00
JongHyeok ParkandGitHub 28b922dee3 fix(hooks): preserve Stop output through lifecycle wrappers (#2493)
Preserve complete Stop-hook stdout through lifecycle wrappers, wait for queued output to flush before exiting, bound child output with a larger explicit buffer, and add end-to-end regressions for large, multibyte, dry-run, and failure cases.
2026-07-26 00:01:57 -07:00
JongHyeok ParkandGitHub 0071fa5c3c refactor(hooks): consolidate PostToolUse hooks into sync/async dispatchers (#2494)
* refactor(hooks): consolidate PostToolUse hooks into sync/async dispatchers

Replace 10 individual PostToolUse entries in hooks.json with two
consolidated dispatcher entries (post:dispatcher:sync /
post:dispatcher:async). The dispatcher's internal registry preserves
every hook ID, matcher, and profile, so ECC_DISABLED_HOOKS and
ECC_HOOK_PROFILE gating behave exactly as before.

Performance (Edit event, actual hooks.json commands spawned in
parallel like the harness does, median of 7 runs):
- Blocking hook latency: 81ms -> 49ms (~40% faster; 7 blocking
  processes -> 1 sync dispatcher)
- Node processes per tool call: 10 -> 2 (7 blocking + 3 async
  -> 1 sync + 1 async)
- observe-runner now runs in-process (~370ms) inside the async
  dispatcher, which stays backgrounded (async: true, timeout 45s),
  so it adds no user-facing latency.

Also:
- dashboard-web lists dispatcher-managed child hooks so the hook
  inventory stays complete
- post-edit-console-warn refactored to export run() for in-process
  dispatch while keeping standalone stdin behavior
- dispatcher stdin reading is multi-byte safe (StringDecoder) and
  child hook exit codes propagate to the dispatcher exit code

* test(hooks): replace emoji literal with unicode escape for CI unicode safety check

* fix(hooks): adopt explicit cli() entrypoint and merge multi-hook stdout

Address Greptile review on #2494:

- Replace the non-standard 'require.main === undefined' guard with an
  explicit exported cli(). The hooks.json bootstraps now call
  require(s).cli(), so merely requiring the module (dashboard-web,
  test runners, Jest, worker threads) can never trigger dispatch,
  attach stdin listeners, or set process.exitCode.
- Replace last-writer-wins stdout with mergeHookStdout(): when several
  hooks emit additionalContext envelopes they merge into a single
  PostToolUse envelope; non-mergeable raw stdout keeps the last hook's
  output and emits a stderr warning naming the dropped hook IDs, so
  nothing is lost silently.

Also includes local formatter reformatting of the dispatcher and its
test file (no behavioral changes beyond the above).

* fix(hooks): keep post:bash:dispatcher phase reachable in minimal profile

The Greptile P1 premise was partially incorrect: sub-hooks without
explicit profiles default to standard,strict via parseProfiles()
(scripts/lib/hook-flags.js), so audit/cost logs never ran under the
minimal profile on main either — there is no user-visible regression.

However, main did spawn the bash dispatcher phase unconditionally and
let each sub-hook gate itself. Restore that semantic by opening the
outer registry gate to minimal,standard,strict so a future sub-hook
that opts into minimal is not silently blocked at the phase level.
Adds the previously missing minimal-profile async dry-run test.

* test(hooks): assert failing hook exit code propagates to real process status

Spawns the actual dispatcher subprocess with an injected failing hook
and asserts the OS-level exit status, stderr diagnostic, and suppressed
pass-through — closing the E2E gap CodeRabbit flagged on #2494.

* chore: retrigger CI (flaky windows powershell bootstrap test)
2026-07-19 15:47:10 -04:00
a511395613 feat: Plan Canvas, a browser review canvas for plans (#2467)
* feat: add Plan Canvas - browser annotate-and-approve review for plan artifacts

- scripts/plan-canvas.js CLI (open/await/end/stop/server; bin ecc-plan-canvas)
- loopback server + ECC-styled chrome + annotation SDK + zero-dep markdown renderer
- Approve/Request-changes verdicts wired to the /plan confirmation gate
- plan-canvas skill, /plan-canvas command, SessionStart hook surfacing open reviews
- shared scripts/lib/loopback-guard.js extracted from control-pane (API re-exported)
- 121 new tests incl. full-workflow E2E; registered in manifests, catalog, registry

Inspired by lavish-axi (https://github.com/kunchenguid/lavish-axi) by @kunchenguid;
original ECC-native implementation, not a port.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(plan-canvas): invoke via ecc-plan-canvas bin so the skill works from any project

Skill/command referenced a cwd-relative `node scripts/plan-canvas.js`, unusable
outside the ECC root. Switch to the ecc-plan-canvas bin (and $CLAUDE_PLUGIN_ROOT
fallback) and align CLI next_step hints so an agent can run it as a skill in any repo.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(plan-canvas): render Mermaid diagrams + ship Codex cross-harness surface

- markdown renderer emits <pre class="mermaid"> for ```mermaid blocks (source
  entity-escaped so the browser decodes it for the renderer while blocking injection)
- artifact template loads a pinned Mermaid build only when a diagram is present,
  themed to ECC dark, securityLevel strict, graceful offline fallback to source
  (ECC_PLAN_CANVAS_MERMAID_URL overrides for a local mirror)
- skill teaches Mermaid-for-diagrams and states the CLI+JSON loop is harness-agnostic
- add .agents/skills/plan-canvas (Codex) with agents/openai.yaml interface manifest
- register in install-modules workflow-quality paths; docs updated

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(plan-canvas): add demo screenshot

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(ci): sync yarn.lock with new bin; add contributor checklist

- yarn.lock records the ecc-plan-canvas bin so Yarn hardened-mode install no
  longer wants to modify the lockfile on public PRs
- PR template + CONTRIBUTING gain a pre-push checklist covering the lockfile
  trap and the full skill/command/CLI registration surfaces

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Haley Chen <2022hachen@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 17:12:48 -04:00
devin-ai-integration[bot]GitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>affaanDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
3af4676e99 refactor: consolidate duplicated hook-root resolver into shared resolveEccRoot() (#2368) (#2410)
* fix(ci): resync lockfiles with package.json (eslint 10) + migrate yarn.lock to Yarn 4 format

package.json requires eslint@^10.6.0 but the committed locks pinned 9.39.2, so
npm ci aborted and Yarn 4 hardened mode rejected the stale v1-classic yarn.lock
(YN0028). Regenerate package-lock.json and rewrite yarn.lock in Yarn 4 (berry)
format so npm ci and immutable yarn installs both pass.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(ci): require clean probe exit for Windows shell/bash detection; add pyyaml dev dep

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor: consolidate duplicated hook-root resolver into shared resolveEccRoot() (#2368)

The inline node -e resolver blob was duplicated ~60x across hooks.json,
command docs, and translations. Each copy inlined the full ~700-char
plugin-root search using a spread over nested array literals
(p.join(d,'plugins',...s) over [['ecc'],...]), which breaks Windows hook
execution due to shell quoting (#2368).

Collapse every copy to a 250-char locator that loads the committed
resolve-ecc-root module and delegates to resolveEccRoot() — no spread, no
nested array literals, no escaped double quotes. The real search logic now
lives in one tested module. Also route session-start-bootstrap.js through
resolveEccRoot() instead of its own duplicated reimplementation, and fix
the auto-update.md 'marketplace' (singular) typo along the way.

Guard tests updated: discovery behavior is asserted against resolveEccRoot();
the inline is asserted to delegate and to contain no Windows-fragile
constructs.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix(resolve-ecc-root): restore full env-unset discovery in inline resolver

Address Greptile review on #2410: when CLAUDE_PLUGIN_ROOT is unset the
delegating inline could only load the resolver module from ~/.claude,
returning ~/.claude without ever reaching the plugin/cache search. Restore
the old inline's discovery breadth (exact plugin roots + versioned cache)
Windows-safely (no spread, nested arrays, or escaped quotes), then delegate
the authoritative decision to resolveEccRoot(). Add regression tests for
plugin-subdir and versioned-cache bootstrap with env unset.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: affaan <affaan@itomarkets.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-07-03 20:01:17 -07:00
Affaan MustafaandAffaan Mustafa 6cb194a3c6 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.
2026-05-19 05:15:42 -04:00
Affaan MustafaandAffaan Mustafa 940135ea47 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.
2026-05-11 23:44:06 -04:00
Affaan MustafaandGitHub c45aeee57f fix: salvage remaining stale queue fixes (#1754) 2026-05-11 16:41:08 -04:00
Affaan MustafaandAffaan Mustafa 3fadc37802 fix: route continuous learning observe hooks through node 2026-04-29 21:28:59 -04:00
Affaan Mustafa ccecb0b9f4 fix: restore string hook commands for Claude Code schema 2026-04-15 17:25:33 -07:00
Affaan Mustafa 1fabf4d2cf fix: consolidate bash hooks without fork storms 2026-04-14 21:23:57 -07:00
Affaan Mustafa 1b7c5789fc fix: bootstrap plugin-installed hook commands safely 2026-04-14 20:24:21 -07:00
Affaan MustafaandGitHub e0ddb331f6 Merge pull request #1367 from ozoz5/feat/gateguard
feat(hooks,skills): add gateguard fact-forcing pre-action gate
2026-04-13 01:05:20 -07:00
Ke WangandClaude Opus 4.6 809e0fa0a9 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>
2026-04-12 20:29:01 -05:00
Ke Wang dae663d856 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
2026-04-12 19:53:15 -05:00
setoandClaude Opus 4.6 9a64e0d271 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>
2026-04-12 18:18:16 +09:00
setoandClaude Opus 4.6 8a2d13187c 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>
2026-04-12 17:42:32 +09:00
setoandClaude Opus 4.6 5a03922934 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>
2026-04-12 11:41:33 +09:00
Affaan Mustafa 48fd68115e feat(ecc2): sync hook activity into session metrics 2026-04-09 07:02:24 -07:00
Affaan Mustafa 8488811b80 chore: remove legacy insaits integration 2026-04-05 20:19:21 -07:00
Affaan Mustafa 1346f83b08 fix: shorten plugin slug to ecc 2026-04-05 14:31:30 -07:00
Affaan Mustafa 31c9f7c33e feat: add web frontend rules and design quality hook 2026-04-02 17:33:17 -07:00
Affaan Mustafa 6833454778 fix: dedupe managed hooks by semantic identity 2026-04-01 02:16:32 -07:00
Affaan Mustafa a273c62f35 fix: restore ci lockfile and hook validation 2026-03-31 18:00:07 -07:00
Yuval DinodiaandGitHub 95e606fb81 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
2026-03-31 14:12:12 -07:00
eacf3a9fb4 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>
2026-03-31 14:12:09 -07:00
30ab9e2cd7 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>
2026-03-31 14:05:23 -07:00
118e57e14b 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>
2026-03-30 03:14:49 -04:00
Affaan Mustafa c39aa22c5a fix: harden lifecycle hook launchers and mcp schema 2026-03-29 21:26:56 -04:00
xingzihai b44ba7096f 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)
2026-03-26 00:28:26 +00:00
Affaan MustafaandGitHub 678fb6f0d3 Merge pull request #846 from pythonstrup/feat/desktop-notify-hook
feat: add macOS desktop notification Stop hook
2026-03-25 03:19:13 -07:00
Affaan Mustafa 7b510c886e fix: harden session hook guards and session ID handling 2026-03-25 03:36:36 -04:00
Jonghyeok Park f6b10481f3 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
2026-03-25 16:03:21 +09:00
Jonghyeok Park 445ae5099d 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.
2026-03-25 16:03:21 +09:00
Affaan Mustafa 00bc7f30be fix: resolve blocker PR validation regressions 2026-03-25 01:34:29 -04:00
Affaan Mustafa 1d0aa5ac2a fix: fold session manager blockers into one candidate 2026-03-24 23:08:27 -04:00
Charlie TonneslanandGitHub 0c7deb26a3 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.
2026-03-22 15:39:56 -07:00
Charlie TonneslanandGitHub fdb10ba116 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.
2026-03-22 15:39:54 -07:00
Affaan MustafaandGitHub e8495aa3fc feat: add MCP health-check hook (#711) 2026-03-20 05:56:21 -07:00
c8f631b046 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>
2026-03-20 01:50:31 -07:00
Affaan MustafaandGitHub 0b0b66c02f 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.
2026-03-20 01:38:13 -07:00
Affaan MustafaandGitHub 8878c6d6b0 fix: harden observer hooks and test discovery (#513) 2026-03-15 21:47:15 -07:00
Affaan Mustafa 9c1e8dd1e4 fix: make insaits hook opt-in 2026-03-10 20:47:09 -07:00
Nomadu27andClaude Opus 4.6 6c56e541dd 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>
2026-03-10 18:08:19 +01:00
Nomadu27andClaude Opus 4.6 44dc96d2c6 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>
2026-03-10 17:52:44 +01:00
Nomadu27andClaude Opus 4.6 540f738cc7 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>
2026-03-10 01:02:58 +01:00
HelbeticaandGitHub 7bed751db0 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"').
2026-03-07 14:47:46 -08:00
Affaan Mustafa 48b883d741 feat: deliver v1.8.0 harness reliability and parity updates 2026-03-04 14:48:06 -08:00
Affaan Mustafa 1df0a53f22 fix: resolve CI failures on main — lint, hooks validator, and test alignment
- Fix MD012 trailing blank lines in commands/projects.md and commands/promote.md
- Fix MD050 strong-style in continuous-learning-v2 (escape __tests__ as inline code)
- Extract doc-file-warning hook to standalone script to fix hooks validator regex parsing
- Update session-end test to match #317 behavior (always update summary content)
- Allow shell script hooks in integration test format validation

All 992 tests passing.
2026-03-02 22:15:46 -08:00