@rafter-security/cli 0.10.6 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/commands/agent/exec.js +26 -9
  2. package/dist/commands/agent/init.js +275 -220
  3. package/dist/commands/agent/install-hook.js +17 -6
  4. package/dist/commands/agent/scan.js +265 -70
  5. package/dist/commands/agent/update-skill-scanner.js +1 -1
  6. package/dist/commands/agent/verify.js +39 -15
  7. package/dist/commands/backend/get.js +6 -2
  8. package/dist/commands/backend/scan-status.js +34 -4
  9. package/dist/commands/hook/pretool.js +124 -36
  10. package/dist/commands/mcp/server.js +184 -129
  11. package/dist/commands/report.js +6 -2
  12. package/dist/core/audit-logger.js +47 -17
  13. package/dist/core/config-manager.js +46 -8
  14. package/dist/core/custom-patterns.js +28 -8
  15. package/dist/core/docs-loader.js +33 -3
  16. package/dist/core/pattern-engine.js +23 -5
  17. package/dist/core/policy-loader.js +15 -4
  18. package/dist/core/risk-rules.js +391 -9
  19. package/dist/index.js +6 -0
  20. package/dist/scanners/betterleaks.js +127 -14
  21. package/dist/scanners/git-history-scan.js +75 -0
  22. package/dist/scanners/regex-scanner.js +16 -2
  23. package/dist/scanners/secret-patterns.js +5 -1
  24. package/dist/scanners/union.js +31 -19
  25. package/dist/utils/api.js +35 -1
  26. package/dist/utils/git-diff.js +36 -20
  27. package/dist/utils/skill-manager.js +4 -3
  28. package/package.json +16 -15
  29. package/resources/continue-rules/rafter.md +1 -1
  30. package/resources/cursor-rules/rafter.mdc +1 -1
  31. package/resources/rafter-security-skill.md +3 -1
  32. package/resources/skills/rafter/SKILL.md +1 -2
  33. package/resources/skills/rafter/docs/guardrails.md +1 -1
  34. package/resources/skills/rafter-code-review/SKILL.md +0 -1
  35. package/resources/skills/rafter-secure-design/SKILL.md +0 -1
  36. package/resources/skills/rafter-skill-review/SKILL.md +0 -1
  37. package/resources/windsurf-rules/rafter.md +1 -1
@@ -34,14 +34,21 @@ export function runConfiguredHook(command, toolCommand) {
34
34
  // is exercised the same way the editor would exercise it. Retry a transient
35
35
  // spawn failure (e.g. EAGAIN under process pressure) so a resource hiccup does
36
36
  // not get reported as an inert gate — a false alarm is worse than a slow check.
37
- let result = spawnSync("sh", ["-c", command], { input: payload, encoding: "utf-8", timeout: 10000 });
37
+ // A hook may exit without reading its payload; the stdin write then fails with
38
+ // EPIPE while status and stdout are intact. That is a hook that ran, not a
39
+ // spawn failure, so it must not be retried or reported as inert.
40
+ const run = () => {
41
+ const r = spawnSync("sh", ["-c", command], { input: payload, encoding: "utf-8", timeout: 10000 });
42
+ return r.error?.code === "EPIPE" ? { ...r, error: undefined } : r;
43
+ };
44
+ let result = run();
38
45
  // Retry a spawn-level error OR a signal kill: under the same process pressure
39
46
  // that produces EAGAIN, the OOM killer sends SIGKILL, which sets `signal` (not
40
47
  // `error`) with a null status — the identical false-alarm scenario by another
41
48
  // route (measured by achebe). A persistent failure still returns decision:null,
42
49
  // so a genuinely inert hook is still reported inert — no fail-open.
43
50
  for (let attempt = 0; attempt < 2 && (result.error || result.signal); attempt++) {
44
- result = spawnSync("sh", ["-c", command], { input: payload, encoding: "utf-8", timeout: 10000 });
51
+ result = run();
45
52
  }
46
53
  if (result.error) {
47
54
  return { status: null, decision: null, error: result.error.message, stdout: "" };
@@ -106,7 +113,7 @@ function checkClaudeCode() {
106
113
  // optional: warn if absent but don't fail exit code
107
114
  const claudeDir = path.join(homeDir, ".claude");
108
115
  if (!fs.existsSync(claudeDir)) {
109
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-claude-code' to enable` };
116
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-claude-code' to enable` };
110
117
  }
111
118
  const settingsPath = path.join(claudeDir, "settings.json");
112
119
  if (!fs.existsSync(settingsPath)) {
@@ -184,7 +191,7 @@ function checkOpenClaw() {
184
191
  const name = "OpenClaw";
185
192
  const skillManager = new SkillManager();
186
193
  if (!skillManager.isOpenClawInstalled()) {
187
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-openclaw' to enable` };
194
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-openclaw' to enable` };
188
195
  }
189
196
  if (!skillManager.isRafterSkillInstalled()) {
190
197
  // rf-zgwj: surface the legacy install path so users on rafter ≤ 0.7.7
@@ -207,7 +214,7 @@ function checkCodex() {
207
214
  const homeDir = os.homedir();
208
215
  const codexDir = path.join(homeDir, ".codex");
209
216
  if (!fs.existsSync(codexDir)) {
210
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-codex' to enable` };
217
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-codex' to enable` };
211
218
  }
212
219
  const skillPath = path.join(homeDir, ".agents", "skills", "rafter", "SKILL.md");
213
220
  if (!fs.existsSync(skillPath)) {
@@ -220,7 +227,7 @@ function checkGemini() {
220
227
  const homeDir = os.homedir();
221
228
  const geminiDir = path.join(homeDir, ".gemini");
222
229
  if (!fs.existsSync(geminiDir)) {
223
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-gemini' to enable` };
230
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-gemini' to enable` };
224
231
  }
225
232
  const settingsPath = path.join(geminiDir, "settings.json");
226
233
  if (!fs.existsSync(settingsPath)) {
@@ -243,7 +250,7 @@ function checkCursor() {
243
250
  const homeDir = os.homedir();
244
251
  const cursorDir = path.join(homeDir, ".cursor");
245
252
  if (!fs.existsSync(cursorDir)) {
246
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-cursor' to enable` };
253
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-cursor' to enable` };
247
254
  }
248
255
  const mcpPath = path.join(cursorDir, "mcp.json");
249
256
  if (!fs.existsSync(mcpPath)) {
@@ -266,7 +273,7 @@ function checkWindsurf() {
266
273
  const homeDir = os.homedir();
267
274
  const windsurfDir = path.join(homeDir, ".codeium", "windsurf");
268
275
  if (!fs.existsSync(windsurfDir)) {
269
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-windsurf' to enable` };
276
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-windsurf' to enable` };
270
277
  }
271
278
  const mcpPath = path.join(windsurfDir, "mcp_config.json");
272
279
  if (!fs.existsSync(mcpPath)) {
@@ -289,7 +296,7 @@ function checkContinueDev() {
289
296
  const homeDir = os.homedir();
290
297
  const continueDir = path.join(homeDir, ".continue");
291
298
  if (!fs.existsSync(continueDir)) {
292
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-continue' to enable` };
299
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-continue' to enable` };
293
300
  }
294
301
  const configPath = path.join(continueDir, "config.json");
295
302
  if (!fs.existsSync(configPath)) {
@@ -327,7 +334,7 @@ function checkAider() {
327
334
  : fs.existsSync(userConf) ? userConf
328
335
  : null;
329
336
  if (!conf) {
330
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-aider' to enable` };
337
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-aider' to enable` };
331
338
  }
332
339
  let raw = "";
333
340
  try {
@@ -369,7 +376,7 @@ function checkHermes() {
369
376
  const homeDir = os.homedir();
370
377
  const hermesDir = path.join(homeDir, ".hermes");
371
378
  if (!fs.existsSync(hermesDir)) {
372
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-hermes' to enable` };
379
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-hermes' to enable` };
373
380
  }
374
381
  const configPath = path.join(hermesDir, "config.yaml");
375
382
  if (!fs.existsSync(configPath)) {
@@ -397,7 +404,7 @@ function checkOpenCode() {
397
404
  const homeDir = os.homedir();
398
405
  const openCodeDir = path.join(homeDir, ".config", "opencode");
399
406
  if (!fs.existsSync(openCodeDir)) {
400
- return { name, passed: false, optional: true, detail: `Not detected — run 'rafter agent init --with-opencode' to enable` };
407
+ return { name, passed: false, optional: true, notDetected: true, detail: `Not detected — run 'rafter agent init --with-opencode' to enable` };
401
408
  }
402
409
  const configPath = path.join(openCodeDir, "opencode.json");
403
410
  if (!fs.existsSync(configPath)) {
@@ -568,12 +575,29 @@ export function createVerifyCommand() {
568
575
  }
569
576
  }
570
577
  console.log();
578
+ // "Core checks" excludes optional integrations that simply aren't
579
+ // present on this machine — those were never candidates to pass, so
580
+ // counting them in the denominator (and calling them "core" in the
581
+ // same breath as "optional") misrepresents a healthy install as a
582
+ // mostly-failing one (rafter-cli#231). An optional check that IS
583
+ // applicable here but still failed (e.g. hooks installed but
584
+ // disabled) still counts as core: it's a real, actionable warning.
585
+ const notApplicable = results.filter((r) => !r.passed && r.optional && r.notDetected);
586
+ const coreResults = results.filter((r) => !(r.optional && r.notDetected));
587
+ const coreWarned = coreResults.filter((r) => !r.passed && r.optional);
571
588
  if (hardFailed.length === 0) {
572
- const warnNote = warned.length > 0 ? ` (${warned.length} optional check${warned.length > 1 ? "s" : ""} not configured)` : "";
573
- console.log(fmt.success(`${passed.length}/${results.length} core checks passed${warnNote}`));
589
+ const notes = [];
590
+ if (coreWarned.length > 0) {
591
+ notes.push(`${coreWarned.length} optional check${coreWarned.length > 1 ? "s" : ""} not configured`);
592
+ }
593
+ if (notApplicable.length > 0) {
594
+ notes.push(`${notApplicable.length} optional integration${notApplicable.length > 1 ? "s" : ""} not detected`);
595
+ }
596
+ const warnNote = notes.length > 0 ? ` (${notes.join(", ")})` : "";
597
+ console.log(fmt.success(`${passed.length}/${coreResults.length} core checks passed${warnNote}`));
574
598
  }
575
599
  else {
576
- console.log(fmt.error(`${passed.length}/${results.length} checks passed — ${hardFailed.length} failed`));
600
+ console.log(fmt.error(`${passed.length}/${coreResults.length} checks passed — ${hardFailed.length} failed`));
577
601
  }
578
602
  console.log();
579
603
  }
@@ -1,6 +1,6 @@
1
1
  import { Command } from "commander";
2
2
  import { resolveKey, writePayload, EXIT_GENERAL_ERROR, EXIT_SCAN_NOT_FOUND } from "../../utils/api.js";
3
- import { handleScanStatus, fetchScanWithRetry, PollGaveUpError } from "./scan-status.js";
3
+ import { handleScanStatus, fetchScanWithRetry, PollGaveUpError, reportFailedScan, warnIfPartial } from "./scan-status.js";
4
4
  export function createGetCommand() {
5
5
  return new Command("get")
6
6
  .argument("<scan_id>")
@@ -16,7 +16,11 @@ export function createGetCommand() {
16
16
  // give-up message recommends. A remedy defeated by the same transient
17
17
  // failure it is recommended for is not a remedy.
18
18
  const { data } = await fetchScanWithRetry(scan_id, { "x-api-key": key }, opts.format, opts.quiet);
19
- const exitCode = writePayload(data, opts.format, opts.quiet);
19
+ if (data?.status !== "failed")
20
+ warnIfPartial(data);
21
+ const exitCode = data?.status === "failed"
22
+ ? reportFailedScan(data, opts.format)
23
+ : writePayload(data, opts.format, opts.quiet);
20
24
  process.exit(exitCode);
21
25
  }
22
26
  catch (e) {
@@ -217,11 +217,12 @@ export async function handleScanStatus(scan_id, headers, fmt, quiet) {
217
217
  status = poll.data.status;
218
218
  if (status === "completed") {
219
219
  spinner?.succeed("Scan completed");
220
+ warnIfPartial(poll.data);
220
221
  return writePayload(poll.data, fmt, quiet);
221
222
  }
222
223
  else if (status === "failed") {
223
- spinner?.fail("Scan failed");
224
- return EXIT_GENERAL_ERROR;
224
+ spinner?.stop();
225
+ return reportFailedScan(poll.data, fmt);
225
226
  }
226
227
  }
227
228
  }
@@ -238,16 +239,45 @@ export async function handleScanStatus(scan_id, headers, fmt, quiet) {
238
239
  if (!quiet) {
239
240
  console.error("Scan completed");
240
241
  }
242
+ warnIfPartial(poll.data);
241
243
  return writePayload(poll.data, fmt, quiet);
242
244
  }
243
245
  else if (status === "failed") {
244
- console.error("Scan failed");
245
- return EXIT_GENERAL_ERROR;
246
+ return reportFailedScan(poll.data, fmt);
246
247
  }
247
248
  else {
248
249
  if (!quiet) {
249
250
  console.error(`Scan status: ${status}`);
250
251
  }
251
252
  }
253
+ warnIfPartial(poll.data);
252
254
  return writePayload(poll.data, fmt, quiet);
253
255
  }
256
+ /**
257
+ * A failed scan: say why on stderr, as the API explains it, and in JSON mode
258
+ * hand the payload to stdout so an agent can read `error_code`/`retryable`.
259
+ */
260
+ export function reportFailedScan(data, fmt) {
261
+ const code = typeof data?.error_code === "string" ? ` (${data.error_code})` : "";
262
+ const reason = typeof data?.error === "string" && data.error ? `: ${data.error}` : "";
263
+ console.error(output.error(`Scan failed${code}${reason}`));
264
+ if (data?.retryable === true) {
265
+ console.error("This failure is retryable: start a new scan with `rafter run`.");
266
+ }
267
+ if (fmt === "json")
268
+ writePayload(data, fmt);
269
+ return EXIT_GENERAL_ERROR;
270
+ }
271
+ /**
272
+ * A completed scan the API marks partial (some scanners did not finish) is
273
+ * not a clean result. Say so on stderr, even with --quiet.
274
+ */
275
+ export function warnIfPartial(data) {
276
+ if (data?.partial !== true && data?.warning_code !== "SCAN_PARTIAL")
277
+ return;
278
+ const code = typeof data?.warning_code === "string" ? data.warning_code : "SCAN_PARTIAL";
279
+ const missing = Array.isArray(data?.missing_scanners) && data.missing_scanners.length
280
+ ? ` Scanners that did not finish: ${data.missing_scanners.join(", ")}.`
281
+ : "";
282
+ console.error(output.warning(`Scan completed with gaps (${code}): some scanners did not finish, so findings may be missing.${missing} Do not treat this result as clean.`));
283
+ }
@@ -9,8 +9,9 @@ import { getRafterDir } from "../../core/config-defaults.js";
9
9
  import { applySuppressions } from "../../core/custom-patterns.js";
10
10
  import { resolveHookControl } from "../../core/hook-control.js";
11
11
  import { collectSuppressions, applyExcludePaths } from "../agent/scan.js";
12
+ import { shellQuote } from "../agent/exec.js";
12
13
  import { scanAddedDiffLines } from "../../scanners/git-diff-scan.js";
13
- import { parseUnifiedDiffAddedLines } from "../../utils/git-diff.js";
14
+ import { parseUnifiedDiffAddedLines, gitDiffMaxBuffer } from "../../utils/git-diff.js";
14
15
  import { execSync } from "child_process";
15
16
  import path from "path";
16
17
  /**
@@ -68,12 +69,16 @@ function formatBlockedMessage(command, evaluation) {
68
69
  const desc = RISK_DESCRIPTIONS[evaluation.riskLevel] ?? "";
69
70
  return `\u2717 Rafter blocked: ${cmdDisplay}\n Rule: ${rule}\n Risk: ${label}\u2014${desc}`;
70
71
  }
71
- function formatApprovalMessage(command, evaluation) {
72
+ export function formatApprovalMessage(command, evaluation) {
72
73
  const cmdDisplay = command.length > 60 ? command.slice(0, 60) + "..." : command;
73
74
  const rule = evaluation.matchedPattern ?? "policy match";
74
75
  const label = RISK_LABELS[evaluation.riskLevel] ?? evaluation.riskLevel.toUpperCase();
75
76
  const desc = RISK_DESCRIPTIONS[evaluation.riskLevel] ?? "";
76
- return `\u26a0 Rafter: approval required\n Command: ${cmdDisplay}\n Rule: ${rule}\n Risk: ${label}\u2014${desc}\n\nTo approve: a person must run \`rafter agent exec "${command}"\` at an\n interactive terminal and confirm. There is no flag that\n skips the prompt.`;
77
+ // The command is echoed into a suggested shell invocation, so it must be
78
+ // quoted as data, not interpolated raw \u2014 a raw double-quoted echo lets a
79
+ // command containing `"`, `$`, or a backtick break out of the quoting or
80
+ // get shell-expanded when pasted (rf issue #231 item 5).
81
+ return `\u26a0 Rafter: approval required\n Command: ${cmdDisplay}\n Rule: ${rule}\n Risk: ${label}\u2014${desc}\n\nTo approve: a person must run \`rafter agent exec ${shellQuote(command)}\` at an\n interactive terminal and confirm. There is no flag that\n skips the prompt.`;
77
82
  }
78
83
  export function createHookPretoolCommand() {
79
84
  return new Command("pretool")
@@ -86,32 +91,48 @@ export function createHookPretoolCommand() {
86
91
  .option("--format <format>", "Output format: claude (default, also Codex/Continue), cursor, gemini, windsurf", "claude")
87
92
  .action(async (opts) => {
88
93
  const format = (opts.format || "claude");
94
+ let decision;
89
95
  try {
90
- const input = await readStdin();
91
- let raw;
92
- try {
93
- raw = JSON.parse(input);
94
- }
95
- catch {
96
- // Can't parse → fail open
97
- writeDecision({ decision: "allow" }, format);
98
- return;
99
- }
100
- // Validate payload is an object with expected shape
101
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
102
- writeDecision({ decision: "allow" }, format);
103
- return;
104
- }
105
- const payload = normalizeInput(raw, format);
106
- const decision = evaluateToolCall(payload);
107
- writeDecision(decision, format);
96
+ decision = decidePretool(await readStdin(), format);
108
97
  }
109
- catch {
110
- // Any unexpected error → fail open
111
- writeDecision({ decision: "allow" }, format);
98
+ catch (e) {
99
+ decision = denyOnError(e);
112
100
  }
101
+ writeDecision(decision, format);
113
102
  });
114
103
  }
104
+ /**
105
+ * Decide one PreToolUse call from its raw stdin text. Input that is not a JSON
106
+ * object is allowed (nothing to evaluate). Any exception thrown while
107
+ * evaluating fails CLOSED: an unexpected error is not evidence the call is
108
+ * safe. Conditions the loaders already handle (a malformed .rafter.yml warns
109
+ * and falls back to defaults) never throw, so they do not reach this.
110
+ */
111
+ export function decidePretool(input, format) {
112
+ let raw;
113
+ try {
114
+ raw = JSON.parse(input);
115
+ }
116
+ catch {
117
+ return { decision: "allow" };
118
+ }
119
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
120
+ return { decision: "allow" };
121
+ }
122
+ try {
123
+ return evaluateToolCall(normalizeInput(raw, format));
124
+ }
125
+ catch (e) {
126
+ return denyOnError(e);
127
+ }
128
+ }
129
+ function denyOnError(e) {
130
+ const type = e instanceof Error ? e.constructor.name : typeof e;
131
+ const msg = e instanceof Error ? e.message : String(e);
132
+ const reason = `rafter hook error: ${type}: ${msg}; denying to be safe`;
133
+ console.error(reason);
134
+ return { decision: "deny", reason };
135
+ }
115
136
  /**
116
137
  * Normalize platform-specific stdin JSON into a common HookInput shape.
117
138
  *
@@ -166,16 +187,46 @@ function evaluateToolCall(payload) {
166
187
  const control = resolveHookControl();
167
188
  if (!control.hookEnabled)
168
189
  return { decision: "allow" };
169
- if (tool_name === "Bash") {
190
+ if (SHELL_TOOLS.has(tool_name)) {
170
191
  return evaluateBash(tool_input?.command || "", control);
171
192
  }
172
- if (tool_name === "Write" || tool_name === "Edit") {
193
+ if (WRITE_TOOLS.has(tool_name)) {
173
194
  if (!control.secretScanEnabled)
174
195
  return { decision: "allow" };
175
- return evaluateWrite(tool_input || {});
196
+ return evaluateWrite(normalizeWriteInput(tool_name, tool_input || {}));
176
197
  }
177
198
  return { decision: "allow" };
178
199
  }
200
+ /**
201
+ * Shell and file-write tools under each platform's own name, so the same
202
+ * policy applies whatever the tool is called.
203
+ * Shell: Bash (Claude Code, Codex, Continue), Shell (Cursor preToolUse),
204
+ * run_shell_command (Gemini CLI).
205
+ * Write: Write/Edit (Claude Code, Continue, Cursor), MultiEdit (Claude Code,
206
+ * Continue), write_file/replace (Gemini CLI), apply_patch (Codex).
207
+ */
208
+ const SHELL_TOOLS = new Set(["Bash", "Shell", "run_shell_command"]);
209
+ const WRITE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "write_file", "replace", "apply_patch"]);
210
+ /**
211
+ * Map each write tool's input onto the { file_path, content } shape that
212
+ * evaluateWrite reads: Continue's Write names its path `filepath`; MultiEdit
213
+ * and Windsurf's pre_write_code carry `edits[].new_string`; Codex's
214
+ * apply_patch carries the whole patch in `command`.
215
+ */
216
+ function normalizeWriteInput(toolName, input) {
217
+ const out = { ...input };
218
+ if (out.file_path === undefined && typeof input.filepath === "string")
219
+ out.file_path = input.filepath;
220
+ if (!out.content && !out.new_string) {
221
+ if (Array.isArray(input.edits)) {
222
+ out.content = input.edits.map((e) => (typeof e?.new_string === "string" ? e.new_string : "")).join("\n");
223
+ }
224
+ else if (toolName === "apply_patch" && typeof input.command === "string") {
225
+ out.content = input.command;
226
+ }
227
+ }
228
+ return out;
229
+ }
179
230
  function evaluateBash(command, control) {
180
231
  const audit = new AuditLogger();
181
232
  // Command-risk interception — gated by commandPolicy. When disabled, skip the
@@ -206,6 +257,14 @@ function evaluateBash(command, control) {
206
257
  const trimmed = command.trim();
207
258
  if (control.secretScanEnabled && (trimmed.startsWith("git commit") || trimmed.startsWith("git push"))) {
208
259
  const scanResult = scanStagedFiles();
260
+ if (scanResult.scanError) {
261
+ audit.logCommandIntercepted(command, false, "blocked", `secret scan could not run: ${scanResult.scanError}`);
262
+ return {
263
+ decision: "deny",
264
+ reason: `Rafter: secret scan of the staged diff could not run (${scanResult.scanError}); ` +
265
+ "commit blocked rather than allowed unscanned. Run 'rafter secrets --staged' to investigate.",
266
+ };
267
+ }
209
268
  if (scanResult.secretsFound) {
210
269
  // Audit per file so the log records WHICH file + pattern, not a bare count.
211
270
  for (const r of scanResult.findings) {
@@ -310,9 +369,17 @@ export function scanStagedFiles(cwd = process.cwd()) {
310
369
  const empty = {
311
370
  secretsFound: false, count: 0, files: 0, findings: [], repoRoot: cwd,
312
371
  };
372
+ let repoRoot;
313
373
  try {
314
- const repoRoot = execSync("git rev-parse --show-toplevel", gitOpts).trim() || cwd;
315
- const patch = execSync("git diff -U0 --no-color --cached --diff-filter=ACM", gitOpts).trim();
374
+ repoRoot = execSync("git rev-parse --show-toplevel", gitOpts).trim() || cwd;
375
+ }
376
+ catch {
377
+ return empty; // Not a git repo: no staged files to scan.
378
+ }
379
+ try {
380
+ // At the default 1 MiB buffer a larger staged diff threw ENOBUFS, the catch
381
+ // below returned "no secrets", and the commit skipped the scan (#274).
382
+ const patch = execSync("git diff -U0 --no-color --cached --diff-filter=ACM", { ...gitOpts, maxBuffer: gitDiffMaxBuffer() }).trim();
316
383
  if (!patch) {
317
384
  return { ...empty, repoRoot };
318
385
  }
@@ -333,8 +400,12 @@ export function scanStagedFiles(cwd = process.cwd()) {
333
400
  repoRoot,
334
401
  };
335
402
  }
336
- catch {
337
- return empty;
403
+ catch (error) {
404
+ // Inside a repo, a scan that could not run must not read as "no secrets".
405
+ const scanError = error?.code === "ENOBUFS"
406
+ ? "staged diff too large for the scanner to read"
407
+ : (error?.message ?? String(error));
408
+ return { ...empty, repoRoot, scanError };
338
409
  }
339
410
  }
340
411
  /** Cap on individual findings listed in a deny reason before truncating. */
@@ -396,12 +467,24 @@ function readStdin() {
396
467
  process.stdin.resume();
397
468
  });
398
469
  }
470
+ /**
471
+ * Write the decision in the platform's format. The hook only ever DENIES: an
472
+ * internal "allow" means "rafter has no objection", and is written as the
473
+ * platform's no-decision form so the platform's own permission settings still
474
+ * apply. Approving would skip those settings (a Claude Code PreToolUse "allow"
475
+ * skips the permission prompt), making an agent more permissive with rafter
476
+ * installed than without it. Cursor is the one exception; see below.
477
+ */
399
478
  function writeDecision(decision, format) {
400
479
  const isDeny = decision.decision === "deny";
401
480
  const reason = decision.reason ?? "";
402
481
  switch (format) {
403
482
  case "cursor": {
404
483
  // Cursor: { permission: "allow"|"deny"|"ask", agentMessage?, userMessage? }
484
+ // Cursor has no neutral answer: its permission hooks block on an empty or
485
+ // schema-invalid response, so "allow" is the only way to let a call
486
+ // proceed. "ask" would force a prompt on every call, overriding the
487
+ // user's own allowlist in the other direction.
405
488
  const output = {
406
489
  permission: isDeny ? "deny" : "allow",
407
490
  };
@@ -413,7 +496,7 @@ function writeDecision(decision, format) {
413
496
  break;
414
497
  }
415
498
  case "gemini": {
416
- // Gemini: {} for allow, { decision: "deny", reason: "..." } for deny
499
+ // Gemini: {} for no decision, { decision: "deny", reason: "..." } for deny
417
500
  if (isDeny) {
418
501
  process.stdout.write(JSON.stringify({ decision: "deny", reason }) + "\n");
419
502
  }
@@ -423,20 +506,25 @@ function writeDecision(decision, format) {
423
506
  break;
424
507
  }
425
508
  case "windsurf": {
426
- // Windsurf: exit 0 for allow, exit 2 + stderr for deny
509
+ // Windsurf: exit 0 to proceed normally, exit 2 + stderr for deny
427
510
  if (isDeny) {
428
511
  process.stderr.write(reason + "\n");
429
512
  process.exit(2);
430
513
  }
431
- // Allow: exit 0 (no output needed)
514
+ // No decision: exit 0 (no output needed)
432
515
  break;
433
516
  }
434
517
  default: {
435
- // Claude Code / Codex / Continue.dev: hookSpecificOutput envelope
518
+ // Claude Code / Codex / Continue.dev: hookSpecificOutput envelope for a
519
+ // deny; `{}` (no permissionDecision) leaves the call to the normal flow.
520
+ if (!isDeny) {
521
+ process.stdout.write("{}\n");
522
+ break;
523
+ }
436
524
  const output = {
437
525
  hookSpecificOutput: {
438
526
  hookEventName: "PreToolUse",
439
- permissionDecision: isDeny ? "deny" : "allow",
527
+ permissionDecision: "deny",
440
528
  permissionDecisionReason: reason,
441
529
  },
442
530
  };