Files
ruvnet__ruflo/scripts/audit-hook-commands.mjs
rUv f0ee0f9688 fix(#1921): plugin hooks use a resilient shim, not bare npx @alpha per fire (#1923)
* fix(#1921): plugin hooks invoke a resilient shim, not bare `npx @alpha` per fire

Every PreToolUse/PostToolUse/Stop hook ran `npx <pkg>@alpha hooks …`, which
(a) re-resolves the @alpha dist-tag from the registry on every fire and
(b) re-installs from cold cache — and when that install crashes (an arborist
`Invalid Version` on npm 10.8.x, deep in a transitive OTEL/grpc subtree) the
user sees a hook error in Claude Code after every assistant turn, plus ~7s of
wasted registry traffic per turn.

Fix: each plugin (`.claude-plugin/`, `plugin/`, `plugins/ruflo-core/`) ships
`scripts/ruflo-hook.sh` — prefers an already-installed `ruflo`/`claude-flow`
binary, falls back to `npx --prefer-offline --yes ruflo@alpha`, and ALWAYS
exits 0. hooks.json invokes `"${CLAUDE_PLUGIN_ROOT}/scripts/ruflo-hook.sh" …
|| true` (the `|| true` covers the unset-$CLAUDE_PLUGIN_ROOT case). stdin
(the hook event JSON) passes through unchanged; the stdin-jq-xargs
shell-injection-safety pattern in plugin/hooks/hooks.json is preserved.

This does NOT fix the underlying arborist crash (which needs the offending
empty-`version` package pinned via `overrides` once it's identified on
npm 10.8.2 — see the issue thread) — it makes a CLI/install failure invisible
and cheap instead of a visible error every turn.

CI guard: scripts/audit-hook-commands.mjs — fails CI if any hook `command`
uses `npx` without `--prefer-offline`, or invokes the CLI without a non-fatal
guard. Wired into v3-ci.yml as `hook-command-audit` (also bash-lints each
ruflo-hook.sh and asserts it exits 0 with no CLI on PATH) + added to
witness-verify needs[]. Path triggers updated to fire on `**/hooks/hooks.json`,
`**/scripts/ruflo-hook.sh`, and `scripts/**`. Witness markers for #1921 +

Co-Authored-By: RuFlo <ruv@ruv.net>

* fix(#1921): make test-hooks.mjs shim-aware; fix shim-lint CI step; regen witness

Rebasing #1921 onto main surfaced 3 CI failures:

- plugin-hooks-smoke (ubuntu + macos): test-hooks.mjs substituted only
  `npx ruflo@alpha` → the local CLI, but the hooks.json now invokes
  `${CLAUDE_PLUGIN_ROOT}/scripts/ruflo-hook.sh <args>`. It now also
  substitutes the shim path → `<cli> hooks <args>` (bypassing the shim, so
  the test exercises the real CLI flag wiring) and strips the shim's
  trailing `|| true` so exit codes are still asserted. 7/7 pass.
- hook-command-audit shim-lint step: `PATH="/nonexistent" bash "$sh"` set
  PATH to a dir with no `bash`, so `bash: command not found`. Now invokes
  bash by full path with `PATH=` empty: `PATH= "$BASH" "$sh"` — the shim's
  `command -v` is a builtin (works with empty PATH) and the npx fallback
  fails cleanly under `|| true` → exit 0. (resolved in v3-ci.yml during the
  rebase.)

Witness manifest regenerated; #1862's marker refreshed to match the
shim-relocated `post-edit -f "$FILE" -s true` (the documented-flag form is
preserved). `ruflo verify` 0 regressed.

Co-Authored-By: RuFlo <ruv@ruv.net>

---------

Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
2026-05-12 00:51:18 -04:00

118 lines
4.5 KiB
JavaScript

#!/usr/bin/env node
/**
* Hook-command install-safety audit — regression guard for #1921 (and #1147).
*
* Hooks fire on EVERY PreToolUse / PostToolUse / Stop / etc. A hook `command`
* that does a bare `npx <pkg>@alpha …` re-resolves the dist-tag and re-installs
* from cold cache on every fire; when that install crashes (e.g. an arborist
* `Invalid Version` on npm 10.8.x) the user sees a hook error in Claude Code
* after every turn. The fix: invoke `scripts/ruflo-hook.sh` (prefers a locally-
* installed `ruflo`/`claude-flow` binary, falls back to `npx --prefer-offline`,
* always exits 0). This guard fails CI if any hook `command` regresses.
*
* Rules, per hook `command` string:
* 1. If it invokes `npx`, it MUST also pass `--prefer-offline`.
* 2. If it invokes `npx` or `scripts/ruflo-hook.sh`, it MUST be non-fatal:
* end with `|| true` / `|| exit 0`, or the hook entry must set
* `continueOnError: true`.
*
* Usage:
* node scripts/audit-hook-commands.mjs # exit 1 on any violation
* node scripts/audit-hook-commands.mjs --json # machine-readable report
*/
import { readFileSync, readdirSync } from 'node:fs';
import { join, relative } from 'node:path';
const REPO_ROOT = process.cwd();
const JSON_OUT = process.argv.includes('--json');
function findHooksFiles(dir, out = []) {
let entries;
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return out; }
for (const e of entries) {
if (e.name === 'node_modules' || e.name === '.git') continue;
const p = join(dir, e.name);
if (e.isDirectory()) findHooksFiles(p, out);
else if (e.isFile() && /[\\/]hooks[\\/]hooks\.json$/.test(p)) out.push(p);
}
return out;
}
function collectCommands(hooksJson) {
const out = [];
const root = hooksJson && hooksJson.hooks;
if (!root || typeof root !== 'object') return out;
for (const [event, entries] of Object.entries(root)) {
if (!Array.isArray(entries)) continue;
for (const entry of entries) {
const matcher = entry && entry.matcher;
const list = entry && Array.isArray(entry.hooks) ? entry.hooks : [];
for (let idx = 0; idx < list.length; idx++) {
const h = list[idx];
if (h && h.type === 'command' && typeof h.command === 'string') {
out.push({ event, matcher, idx, command: h.command, continueOnError: h.continueOnError === true });
}
}
}
}
return out;
}
const NPX_RE = /(^|[\s;&|(])npx\b/;
const PREFER_OFFLINE_RE = /--prefer-offline\b/;
const SHIM_RE = /ruflo-hook\.sh/;
const NONFATAL_RE = /\|\|\s*(true|exit\s+0)\b/;
const files = findHooksFiles(REPO_ROOT);
const violations = [];
for (const file of files) {
const rel = relative(REPO_ROOT, file);
let parsed;
try { parsed = JSON.parse(readFileSync(file, 'utf-8')); }
catch (e) { violations.push({ file: rel, where: rel, reason: `invalid JSON: ${e.message}` }); continue; }
for (const { event, matcher, idx, command, continueOnError } of collectCommands(parsed)) {
const where = `${rel} :: ${event}${matcher ? ` [${matcher}]` : ''} #${idx}`;
const usesNpx = NPX_RE.test(command);
const usesShim = SHIM_RE.test(command);
if (usesNpx && !PREFER_OFFLINE_RE.test(command)) {
violations.push({
file: rel, where,
reason: 'invokes `npx` without `--prefer-offline` — re-resolves the dist-tag and re-installs from cold cache on every hook fire (#1921). Use scripts/ruflo-hook.sh, or add `--prefer-offline`.',
command,
});
continue;
}
if ((usesNpx || usesShim) && !NONFATAL_RE.test(command) && !continueOnError) {
violations.push({
file: rel, where,
reason: 'invokes the CLI but is not non-fatal — a CLI/install failure surfaces a hook error in Claude Code (#1921). Append `|| true` (or set `continueOnError: true`).',
command,
});
}
}
}
const report = { scannedFiles: files.length, violationCount: violations.length, violations };
if (JSON_OUT) {
console.log(JSON.stringify(report, null, 2));
} else {
console.log(`hook-command audit — scanned ${files.length} hooks.json file(s)`);
if (violations.length === 0) {
console.log(' ✓ no install-safety violations');
} else {
for (const v of violations) {
console.log(` ✗ ${v.where}`);
console.log(` ${v.reason}`);
if (v.command) console.log(` command: ${v.command.length > 200 ? v.command.slice(0, 200) + '…' : v.command}`);
}
console.log(`\n${violations.length} violation(s)`);
}
}
process.exit(violations.length > 0 ? 1 : 0);