@rafter-security/cli 0.11.6 → 0.12.0

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 (52) hide show
  1. package/dist/commands/agent/auto-update.js +171 -0
  2. package/dist/commands/agent/components.js +50 -176
  3. package/dist/commands/agent/enable.js +11 -1
  4. package/dist/commands/agent/index.js +2 -0
  5. package/dist/commands/agent/init.js +654 -764
  6. package/dist/commands/agent/install-files.js +689 -0
  7. package/dist/commands/agent/instruction-block.js +82 -40
  8. package/dist/commands/agent/scan.js +70 -21
  9. package/dist/commands/agent/status.js +11 -0
  10. package/dist/commands/agent/update.js +179 -0
  11. package/dist/commands/agent/verify.js +11 -0
  12. package/dist/commands/backend/get.js +5 -10
  13. package/dist/commands/backend/run.js +10 -20
  14. package/dist/commands/backend/scan-status.js +16 -3
  15. package/dist/commands/backend/usage.js +3 -6
  16. package/dist/commands/brief.js +6 -12
  17. package/dist/commands/counters.js +146 -0
  18. package/dist/commands/gates.js +36 -0
  19. package/dist/commands/hook/pretool.js +22 -9
  20. package/dist/commands/mcp/server.js +1 -1
  21. package/dist/commands/skill/registry.js +48 -0
  22. package/dist/core/risk-rules.js +240 -34
  23. package/dist/core/usage-counters.js +439 -0
  24. package/dist/index.js +36 -0
  25. package/dist/scanners/gate-scanner.js +721 -0
  26. package/dist/scanners/regex-scanner.js +26 -25
  27. package/dist/utils/skill-manager.js +8 -338
  28. package/package.json +1 -1
  29. package/resources/continue-rules/rafter-code-review.md +6 -6
  30. package/resources/continue-rules/rafter-secure-design.md +3 -4
  31. package/resources/continue-rules/rafter-skill-review.md +4 -4
  32. package/resources/continue-rules/rafter.md +2 -2
  33. package/resources/cursor-rules/rafter-code-review.mdc +6 -6
  34. package/resources/cursor-rules/rafter-secure-design.mdc +3 -4
  35. package/resources/cursor-rules/rafter-skill-review.mdc +4 -4
  36. package/resources/cursor-rules/rafter.mdc +2 -2
  37. package/resources/rafter-security-skill.md +1 -1
  38. package/resources/shipped-hashes.json +332 -0
  39. package/resources/skills/rafter/SKILL.md +7 -7
  40. package/resources/skills/rafter/docs/cli-reference.md +37 -10
  41. package/resources/skills/rafter/docs/finding-triage.md +1 -1
  42. package/resources/skills/rafter/docs/guardrails.md +2 -2
  43. package/resources/skills/rafter/docs/shift-left.md +4 -4
  44. package/resources/skills/rafter-code-review/SKILL.md +43 -14
  45. package/resources/skills/rafter-code-review/docs/llm.md +2 -2
  46. package/resources/skills/rafter-code-review/docs/security-gates.md +53 -0
  47. package/resources/skills/rafter-secure-design/SKILL.md +1 -0
  48. package/resources/skills/rafter-skill-review/SKILL.md +1 -0
  49. package/resources/windsurf-rules/rafter-code-review.md +6 -6
  50. package/resources/windsurf-rules/rafter-secure-design.md +3 -4
  51. package/resources/windsurf-rules/rafter-skill-review.md +4 -4
  52. package/resources/windsurf-rules/rafter.md +2 -2
@@ -4,55 +4,51 @@ export const RAFTER_MARKER_START = "<!-- rafter:start -->";
4
4
  export const RAFTER_MARKER_END = "<!-- rafter:end -->";
5
5
  /** Rafter security context block for agent instruction files (CLAUDE.md, AGENTS.md, etc.) */
6
6
  export const RAFTER_INSTRUCTION_BLOCK = `${RAFTER_MARKER_START}
7
- ## Security: Rafter (surface-driven review gate)
7
+ ## Security: Rafter
8
8
 
9
- Rafter is this project's security review gate — driven by the change's **security
10
- surface**, not by the task label. When a diff touches a real surface (below), it is
11
- **not complete** until a rafter skill (or \`rafter run\`) has reviewed it: don't mark
12
- done, don't hand off, don't open a PR without that pass. When it touches **none** of
13
- that surface — research / experimental / local-only / throwaway code (training
14
- scripts, data analysis, plotting, model eval, notebooks, pure computation over
15
- trusted local data) — a quick surface check is enough; proceed without the full
16
- gate. Judge by the diff's actual surface, not the "research" label: research code
17
- that reads a secret, shells out, hits the network, parses untrusted input, or bumps
18
- a dependency still gets the full gate.
9
+ Security-relevant code is not done until you have reviewed it yourself. Rafter
10
+ gives you the map and the questions; the review is yours. Code is
11
+ security-relevant when it decides who may do what, or touches untrusted input,
12
+ queries, shell, file paths, parsing or (de)serialization, crypto or TLS,
13
+ credentials or tokens, outbound requests, data deletion, or dependencies.
14
+ Analysis scripts, plots and pure computation over trusted local data need only
15
+ a quick look for those.
19
16
 
20
- **Stop and invoke when the change touches that surface:**
21
-
22
- - Designing auth, payments, credentials, tokens, sessions, file upload,
23
- user/untrusted data, deserialization, network endpoints, or data deletion
24
- → **\`rafter-secure-design\`** (before writing code).
25
- - Diff touches user/untrusted input, SQL/query building, shell/exec, auth,
26
- credentials, file paths, (de)serialization, crypto, network endpoints/outbound
27
- fetchers (SSRF), data deletion, or dependencies → **\`rafter-code-review\`** +
28
- \`rafter run\` (before declaring done).
29
- - About to install or forward a third-party SKILL.md, MCP manifest, Cursor
30
- rule, or agent config → **\`rafter-skill-review\`** (before copying anywhere).
31
- - Security-adjacent but the angle isn't clear → **\`rafter\`** (the router skill,
32
- powerful toolkit to help you write more secure code).
33
-
34
- **CLI:**
35
-
36
- - \`rafter run\` — remote SAST + SCA + secrets (real code analysis, needs \`RAFTER_API_KEY\`)
37
- - \`rafter secrets .\` — local secrets only (offline; NOT a code-security scan)
38
- - \`rafter run --mode plus\` — everything in default (\`--mode fast\`) plus
39
- powerful agentic deep-dives (needs \`RAFTER_API_KEY\`). **Plus is a PAID tier
40
- and consumes the user's credits — ask the user before running it.** Enforced
41
- when \`scan.plus_requires_approval\` is set (then pass \`--yes\` to confirm).
17
+ - Designing such a feature → **\`rafter-secure-design\`**, before writing code.
18
+ - Reviewing a diff or auditing code → **\`rafter-code-review\`**. Start with
19
+ \`rafter gates <path>\`: it lists the functions that make security decisions.
20
+ - Installing a third-party skill, MCP server or agent config →
21
+ **\`rafter-skill-review\`**, before copying it anywhere.
22
+ - \`rafter secrets <paths>\` finds hardcoded credentials only. A clean result is
23
+ not a code review.
24
+ - \`rafter run\` adds remote SAST + SCA on the pushed commit (needs
25
+ \`RAFTER_API_KEY\`). \`--mode plus\` is paid: ask the user first.
42
26
  ${RAFTER_MARKER_END}`;
43
27
  /**
44
- * Write a Rafter instruction block into an instruction file.
45
- * Uses marker comments for idempotent updates — existing rafter blocks are replaced,
46
- * non-rafter content is preserved.
28
+ * Aider has no skill-loading mechanism — `rafter-secure-design`,
29
+ * `rafter-code-review`, and `rafter-skill-review` above are names, not files
30
+ * it can load, unlike Claude Code / Codex / Gemini where each one is a real
31
+ * skill directory. This note tells an Aider session what's actually runnable
32
+ * instead of leaving those names as dead pointers.
47
33
  */
48
- export function injectInstructionFile(filePath) {
34
+ export const AIDER_NOTE_MARKER_START = "<!-- rafter:aider-note:start -->";
35
+ export const AIDER_NOTE_MARKER_END = "<!-- rafter:aider-note:end -->";
36
+ export const AIDER_SKILL_NOTE = `${AIDER_NOTE_MARKER_START}
37
+ **Note for Aider**: the skill names above (\`rafter\`, \`rafter-secure-design\`,
38
+ \`rafter-code-review\`, \`rafter-skill-review\`) are not separate files here —
39
+ Aider has no skill-loading mechanism, only this one file. For the fuller
40
+ walkthroughs those skills provide on other platforms, run these in a terminal:
41
+ \`rafter brief shift-left\` (design & review routing), \`rafter brief scanning\`
42
+ (full CLI + guardrails), or \`rafter skill review <path>\` (the real pre-install
43
+ check).
44
+ ${AIDER_NOTE_MARKER_END}`;
45
+ /** Shared idempotent marker-block injector: replace the block between the given
46
+ * markers if present, otherwise append it. */
47
+ function injectMarkedBlock(filePath, block, startMarker, endMarker) {
49
48
  const dir = path.dirname(filePath);
50
49
  if (!fs.existsSync(dir)) {
51
50
  fs.mkdirSync(dir, { recursive: true });
52
51
  }
53
- const block = RAFTER_INSTRUCTION_BLOCK;
54
- const startMarker = RAFTER_MARKER_START;
55
- const endMarker = RAFTER_MARKER_END;
56
52
  let content = "";
57
53
  if (fs.existsSync(filePath)) {
58
54
  content = fs.readFileSync(filePath, "utf-8");
@@ -72,3 +68,49 @@ export function injectInstructionFile(filePath) {
72
68
  fs.writeFileSync(filePath, content, "utf-8");
73
69
  return true;
74
70
  }
71
+ /**
72
+ * Write a Rafter instruction block into an instruction file.
73
+ * Uses marker comments for idempotent updates — existing rafter blocks are replaced,
74
+ * non-rafter content is preserved.
75
+ */
76
+ export function injectInstructionFile(filePath) {
77
+ return injectMarkedBlock(filePath, RAFTER_INSTRUCTION_BLOCK, RAFTER_MARKER_START, RAFTER_MARKER_END);
78
+ }
79
+ /**
80
+ * Append (or idempotently update) the Aider-specific skill note. Separate
81
+ * marker pair from the main block, so this can live alongside it in the same
82
+ * file (RAFTER.md) without disturbing the shared instruction block.
83
+ */
84
+ export function injectAiderNote(filePath) {
85
+ return injectMarkedBlock(filePath, AIDER_SKILL_NOTE, AIDER_NOTE_MARKER_START, AIDER_NOTE_MARKER_END);
86
+ }
87
+ /** Strip the rafter marker block from a text file, writing only if the file actually changed. */
88
+ export function stripMarkerBlock(filePath, startMarker = RAFTER_MARKER_START, endMarker = RAFTER_MARKER_END) {
89
+ if (!fs.existsSync(filePath))
90
+ return false;
91
+ const content = fs.readFileSync(filePath, "utf-8");
92
+ const startIdx = content.indexOf(startMarker);
93
+ const endIdx = content.indexOf(endMarker);
94
+ if (startIdx === -1 || endIdx === -1)
95
+ return false;
96
+ const before = content.slice(0, startIdx).trimEnd();
97
+ const after = content.slice(endIdx + endMarker.length);
98
+ const trailing = after.replace(/^\s*\n+/, "");
99
+ const next = (before ? before + "\n" : "") + trailing;
100
+ fs.writeFileSync(filePath, next, "utf-8");
101
+ return true;
102
+ }
103
+ /**
104
+ * Take rafter's block out of an instruction file rafter no longer writes
105
+ * (e.g. the consolidated .cursor/rules/rafter-security.mdc). The file is
106
+ * deleted only when nothing else is left in it; a file without the block is
107
+ * not rafter's and is left alone.
108
+ */
109
+ export function retireInstructionFile(filePath) {
110
+ if (!stripMarkerBlock(filePath))
111
+ return null;
112
+ if (fs.readFileSync(filePath, "utf-8").trim())
113
+ return "stripped";
114
+ fs.unlinkSync(filePath);
115
+ return "removed";
116
+ }
@@ -17,6 +17,7 @@ import path from "path";
17
17
  import { fmt } from "../../utils/formatter.js";
18
18
  import { createRequire } from "module";
19
19
  import { minimatch } from "minimatch";
20
+ import { countScan } from "../../core/usage-counters.js";
20
21
  const _require = createRequire(import.meta.url);
21
22
  const { version: CLI_VERSION } = _require("../../../package.json");
22
23
  function loadBaselineEntries() {
@@ -114,10 +115,11 @@ function applyBaseline(results, entries) {
114
115
  export function createScanCommand() {
115
116
  return new Command("scan")
116
117
  .description("Scan files or directories for secrets")
117
- .argument("[path]", "File or directory to scan", ".")
118
+ .argument("[paths...]", "File(s) or directory(ies) to scan", ["."])
118
119
  .option("-q, --quiet", "Only output if secrets found")
119
120
  .option("--json", "Output as JSON")
120
121
  .option("--format <format>", "Output format: text, json, sarif", "text")
122
+ .option("--out <file>", "Write the --json/--format output to this file instead of stdout (status lines still go to stderr)")
121
123
  .option("--staged", "Scan only git staged files")
122
124
  .option("--diff <ref>", "Scan files changed since a git ref")
123
125
  .option("--range <range>", "Scan only files changed in a git commit range, e.g. main..HEAD")
@@ -127,7 +129,7 @@ export function createScanCommand() {
127
129
  .option("--history", "Scan every commit on every ref instead of the working tree")
128
130
  .option("--no-gitignore", "Scan files even if .gitignore would exclude them (default: respect .gitignore)")
129
131
  .option("--no-auto-update", "Do not auto-update a stale managed betterleaks binary; fall back to the patterns engine instead")
130
- .action(async (scanPath, opts) => {
132
+ .action(async (scanPaths, opts) => {
131
133
  // Validate flags before doing any work.
132
134
  const validEngines = ["auto", "betterleaks", "patterns"];
133
135
  const engineValue = opts.engine || "auto";
@@ -148,6 +150,12 @@ export function createScanCommand() {
148
150
  if (isAgentScan) {
149
151
  process.stderr.write("Warning: rafter agent scan is deprecated and will be removed in a future major version. Use rafter secrets instead.\n");
150
152
  }
153
+ // Multiple paths (`rafter secrets app/a.py app/b.py infra/c.tf`): scan
154
+ // each and merge into one report below. --diff/--range/--staged/--watch
155
+ // scope to the repo (or a single watch root), not a file list, so they
156
+ // use the first path only — the same thing they did before this command
157
+ // could take more than one path at all.
158
+ const scanPath = scanPaths[0];
151
159
  // Load policy-merged config for excludePaths/customPatterns/ignore.
152
160
  // Discover and anchor the policy from the scan TARGET, not the process
153
161
  // cwd (sable-lu0j), so an ambient `.rafter.yml` in cwd cannot suppress
@@ -189,29 +197,42 @@ export function createScanCommand() {
189
197
  await watchAndScan(resolvedPath, opts, scanCfg, suppressions);
190
198
  return;
191
199
  }
192
- // Determine scan engine
200
+ // Determine scan engine (once for every path, so the engine report in
201
+ // the merged output describes the whole run, not just the last path).
193
202
  const requestedEngine = opts.engine || "auto";
203
+ const scanStart = Date.now();
194
204
  const selected = await selectEngine(requestedEngine, opts.quiet || false, autoUpdateEnabled(opts, scanCfg));
195
205
  const engine = selected.engine;
196
206
  // Threaded through the scan so a scan-time fall-back (e.g. a betterleaks
197
207
  // timeout) updates it before the output reports the engine actually used.
198
208
  const report = buildEngineReport(requestedEngine, engine, selected.reason);
199
- // Determine if path is file or directory
200
- const stats = fs.statSync(resolvedPath);
201
- let results;
202
- if (stats.isDirectory()) {
203
- if (!opts.quiet) {
204
- console.error(`Scanning directory: ${resolvedPath} (${engineLabel(engine)})`);
209
+ // Resolve and validate every path up front — same error, same exit code
210
+ // as the single-path check above, just repeated per path.
211
+ const resolvedPaths = scanPaths.map((p) => path.resolve(p));
212
+ for (const p of resolvedPaths) {
213
+ if (!fs.existsSync(p)) {
214
+ console.error(`Error: Path not found: ${p}`);
215
+ process.exit(2);
205
216
  }
206
- results = await scanDirectory(resolvedPath, engine, scanCfg, opts.history, opts.gitignore, report);
207
217
  }
208
- else {
209
- if (!opts.quiet) {
210
- console.error(`Scanning file: ${resolvedPath} (${engineLabel(engine)})`);
218
+ const allResults = [];
219
+ for (const p of resolvedPaths) {
220
+ const stats = fs.statSync(p);
221
+ if (stats.isDirectory()) {
222
+ if (!opts.quiet) {
223
+ console.error(`Scanning directory: ${p} (${engineLabel(engine)})`);
224
+ }
225
+ allResults.push(...(await scanDirectory(p, engine, scanCfg, opts.history, opts.gitignore, report)));
226
+ }
227
+ else {
228
+ if (!opts.quiet) {
229
+ console.error(`Scanning file: ${p} (${engineLabel(engine)})`);
230
+ }
231
+ allResults.push(...(await scanFile(p, engine, scanCfg, report)));
211
232
  }
212
- results = await scanFile(resolvedPath, engine, scanCfg, report);
213
233
  }
214
- outputScanResults(applyBaseline(results, baselineEntries), opts, undefined, true, suppressions, report);
234
+ countScan(report, Date.now() - scanStart);
235
+ outputScanResults(applyBaseline(allResults, baselineEntries), opts, undefined, true, suppressions, report);
215
236
  });
216
237
  }
217
238
  /**
@@ -239,10 +260,25 @@ export function collectSuppressions(policyIgnore, policyBaseDir, rafterignoreDir
239
260
  ...loadSuppressions(rafterignoreDir),
240
261
  ];
241
262
  }
263
+ /**
264
+ * Write a JSON/SARIF payload to `--out <file>` instead of stdout, so an agent
265
+ * in a sandbox without shell redirects can still get the result onto disk.
266
+ * Status lines keep going to stderr regardless. Returns true when it wrote
267
+ * the file (caller then skips its normal stdout `console.log`).
268
+ */
269
+ function writeJsonOutput(text, outPath, quiet) {
270
+ if (!outPath)
271
+ return false;
272
+ fs.writeFileSync(outPath, text.endsWith("\n") ? text : `${text}\n`);
273
+ if (!quiet) {
274
+ console.error(fmt.info(`Results written to ${outPath}`));
275
+ }
276
+ return true;
277
+ }
242
278
  /**
243
279
  * Emit SARIF 2.1.0 JSON for GitHub/GitLab security tab integration
244
280
  */
245
- function outputSarif(results, emptyExitCode = 0) {
281
+ function outputSarif(results, emptyExitCode = 0, outPath, quiet) {
246
282
  const rules = new Map();
247
283
  const sarifResults = [];
248
284
  for (const r of results) {
@@ -287,7 +323,10 @@ function outputSarif(results, emptyExitCode = 0) {
287
323
  },
288
324
  ],
289
325
  };
290
- console.log(JSON.stringify(sarif, null, 2));
326
+ const sarifText = JSON.stringify(sarif, null, 2);
327
+ if (!writeJsonOutput(sarifText, outPath, quiet)) {
328
+ console.log(sarifText);
329
+ }
291
330
  // A read error (sable-ilbx) makes an otherwise-empty scan non-clean; the
292
331
  // caller passes that exit code in.
293
332
  process.exit(results.length > 0 ? 1 : emptyExitCode);
@@ -331,7 +370,7 @@ function outputScanResults(results, opts, context, exitOnFindings = true, suppre
331
370
  // is what a postmortem needs.
332
371
  logScanToAudit(keptResults, context);
333
372
  if (format === "sarif") {
334
- outputSarif(keptResults, scanExitCode);
373
+ outputSarif(keptResults, scanExitCode, opts.out, opts.quiet);
335
374
  return;
336
375
  }
337
376
  if (format === "json" || opts.json) {
@@ -373,7 +412,10 @@ function outputScanResults(results, opts, context, exitOnFindings = true, suppre
373
412
  if (readErrors.length > 0) {
374
413
  out.unreadable = readErrors;
375
414
  }
376
- console.log(JSON.stringify(out, null, 2));
415
+ const jsonText = JSON.stringify(out, null, 2);
416
+ if (!writeJsonOutput(jsonText, opts.out, opts.quiet)) {
417
+ console.log(jsonText);
418
+ }
377
419
  if (exitOnFindings)
378
420
  process.exit(scanExitCode);
379
421
  return;
@@ -394,7 +436,8 @@ function outputScanResults(results, opts, context, exitOnFindings = true, suppre
394
436
  }
395
437
  else if (!opts.quiet) {
396
438
  const msg = context ? `No secrets detected in ${context}` : "No secrets detected";
397
- console.log(`\n${fmt.success(msg)}\n`);
439
+ console.log(`\n${fmt.success(msg)}`);
440
+ console.log("This covers secrets only — it is not a code security review.\n");
398
441
  }
399
442
  if (exitOnFindings)
400
443
  process.exit(scanExitCode);
@@ -516,7 +559,13 @@ async function runGitAddedLineScan(gitArgs, opts, scanCfg, baselineEntries, scan
516
559
  outputScanResults(applyBaseline(filtered, baselineEntries), opts, contextLabel, true, suppressions, diffReport);
517
560
  }
518
561
  catch (error) {
519
- if (error.status === 128) {
562
+ // 128 is git's own "fatal: not a repository / bad ref". 129 is git's
563
+ // usage-error code, which is what `git diff --cached`/`--diff-filter`
564
+ // actually exits with outside a work tree (git falls back to its
565
+ // two-file `--no-index` mode, where those flags are invalid) — without
566
+ // it, a plain "cwd is not a git repo" run fell through to the generic
567
+ // "could not run" branch below and printed git's raw usage text.
568
+ if (error.status === 128 || error.status === 129) {
520
569
  console.error(errorOpts?.notRepoMessage ?? "Error: Not in a git repository or invalid ref");
521
570
  process.exit(2);
522
571
  }
@@ -7,6 +7,7 @@ import { fileURLToPath } from "url";
7
7
  import { getRafterDir, getAuditLogPath, getBinDir } from "../../core/config-defaults.js";
8
8
  import { AuditLogger } from "../../core/audit-logger.js";
9
9
  import { ConfigManager } from "../../core/config-manager.js";
10
+ import { installStaleness, reconcileLines, stalenessLine } from "./update.js";
10
11
  import { resolveHookControl } from "../../core/hook-control.js";
11
12
  import { BinaryManager } from "../../utils/binary-manager.js";
12
13
  import { SkillManager } from "../../utils/skill-manager.js";
@@ -25,6 +26,12 @@ export function createStatusCommand() {
25
26
  }
26
27
  console.log("Rafter Agent Status");
27
28
  console.log("=".repeat(50));
29
+ const staleness = installStaleness(home, "user");
30
+ if (staleness.stale)
31
+ console.log(`\n${stalenessLine(staleness)}`);
32
+ const reconcile = reconcileLines(staleness);
33
+ if (reconcile.length > 0)
34
+ console.log(`\n${reconcile.join("\n")}`);
28
35
  // --- Config ---
29
36
  if (fs.existsSync(configPath)) {
30
37
  try {
@@ -221,6 +228,10 @@ function buildStatusJson(home, configPath, auditPath) {
221
228
  return {
222
229
  installed: fs.existsSync(configPath),
223
230
  version: getPkgVersion(),
231
+ ...(() => {
232
+ const s = installStaleness(home, "user");
233
+ return { stale: s.stale, installed_version: s.installedVersion, needs_reconcile: s.needsReconcile };
234
+ })(),
224
235
  agents_detected: detectAgents(home),
225
236
  hooks_installed: detectGitHooks(home),
226
237
  betterleaks_available: isBetterleaksAvailable(),
@@ -0,0 +1,179 @@
1
+ import { Command } from "commander";
2
+ import fs from "fs";
3
+ import os from "os";
4
+ import path from "path";
5
+ import { fmt } from "../../utils/formatter.js";
6
+ import { RAFTER_MARKER_START } from "./instruction-block.js";
7
+ import { InstallSession, RULE_SKILLS, WHOLE_FILE_PLATFORMS, cliVersion, manifestPath, NEW_VERSION_SUFFIX, platformArtifacts, reconcileInstruction, } from "./install-files.js";
8
+ import { KNOWN_SKILL_NAMES } from "../skill/registry.js";
9
+ /** init's --with-<platform> option, as commander names it. */
10
+ const INIT_FLAG = {
11
+ "claude-code": "withClaudeCode",
12
+ codex: "withCodex",
13
+ gemini: "withGemini",
14
+ cursor: "withCursor",
15
+ windsurf: "withWindsurf",
16
+ continue: "withContinue",
17
+ aider: "withAider",
18
+ hermes: "withHermes",
19
+ opencode: "withOpencode",
20
+ openclaw: "withOpenclaw",
21
+ };
22
+ const USER_ONLY = ["hermes", "opencode", "openclaw"];
23
+ function contains(file, needle) {
24
+ try {
25
+ return fs.readFileSync(file, "utf-8").includes(needle);
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ function readManifestPlatforms(root) {
32
+ try {
33
+ const doc = JSON.parse(fs.readFileSync(manifestPath(root), "utf-8"));
34
+ return new Set(Object.values(doc?.files ?? {}).map((e) => String(e?.platform ?? "")));
35
+ }
36
+ catch {
37
+ return new Set();
38
+ }
39
+ }
40
+ /**
41
+ * Platforms rafter is installed for under `root`. A platform counts when the
42
+ * manifest lists a file for it or rafter's own entries are on disk: its
43
+ * skills, rules or sub-agent, its marker block, or a rafter hook / MCP entry
44
+ * in its config (the same signals `agent list` and `agent verify` read).
45
+ */
46
+ export function detectInstalledPlatforms(root, scope) {
47
+ const p = (...parts) => path.join(root, ...parts);
48
+ const anyExists = (paths) => paths.some((f) => fs.existsSync(f));
49
+ const marker = (f) => contains(f, RAFTER_MARKER_START);
50
+ const skillFiles = (dir) => KNOWN_SKILL_NAMES.map((n) => p(dir, "skills", n, "SKILL.md"));
51
+ const rules = (dir, ext) => RULE_SKILLS.map((n) => p(dir, "rules", `${n}${ext}`));
52
+ const user = scope === "user";
53
+ const recorded = readManifestPlatforms(root);
54
+ const signals = {
55
+ "claude-code": () => contains(p(".claude", "settings.json"), "hook pretool") ||
56
+ anyExists([...skillFiles(".claude"), p(".claude", "agents", "rafter.md")]) ||
57
+ marker(p(".claude", "CLAUDE.md")),
58
+ codex: () => contains(p(".codex", "hooks.json"), "hook pretool") ||
59
+ (user && marker(p(".codex", "AGENTS.md"))),
60
+ gemini: () => contains(p(".gemini", "settings.json"), "rafter") ||
61
+ marker(user ? p(".gemini", "GEMINI.md") : p("GEMINI.md")),
62
+ cursor: () => anyExists([...rules(".cursor", ".mdc"), p(".cursor", "agents", "rafter.md")]) ||
63
+ contains(p(".cursor", "hooks.json"), "hook pretool") ||
64
+ contains(p(".cursor", "mcp.json"), '"rafter"'),
65
+ windsurf: () => anyExists(rules(".windsurf", ".md")) ||
66
+ (user && contains(p(".codeium", "windsurf", "mcp_config.json"), '"rafter"')),
67
+ continue: () => anyExists(rules(".continue", ".md")) ||
68
+ (user && contains(p(".continue", "config.json"), '"rafter"')),
69
+ aider: () => marker(p("RAFTER.md")) || contains(p(".aider.conf.yml"), "RAFTER.md"),
70
+ hermes: () => contains(p(".hermes", "config.yaml"), "rafter"),
71
+ opencode: () => contains(p(".config", "opencode", "opencode.json"), '"rafter"'),
72
+ openclaw: () => fs.existsSync(p(".openclaw", "workspace", "skills", "rafter-security", "SKILL.md")),
73
+ };
74
+ return Object.keys(signals).filter((name) => !(scope === "project" && USER_ONLY.includes(name)) && (recorded.has(name) || signals[name]()));
75
+ }
76
+ export function versionOlder(a, b) {
77
+ const parse = (v) => v.match(/^(\d+)\.(\d+)\.(\d+)/)?.slice(1).map(Number);
78
+ const x = parse(a);
79
+ const y = parse(b);
80
+ if (!x || !y)
81
+ return false;
82
+ for (let i = 0; i < 3; i++)
83
+ if (x[i] !== y[i])
84
+ return x[i] < y[i];
85
+ return false;
86
+ }
87
+ /**
88
+ * Whether what is installed under `root` is older than what this CLI ships.
89
+ * Stale when the manifest names an older CLI version, when any installed
90
+ * rafter file would be updated (an unmodified older copy, by manifest or
91
+ * shipped hash), or when rafter's files are present with no manifest at all
92
+ * (they predate install records). Files the user modified do not count. No
93
+ * network, no writes.
94
+ */
95
+ export function installStaleness(root, scope) {
96
+ const version = cliVersion();
97
+ const platforms = detectInstalledPlatforms(root, scope);
98
+ const silent = { info: () => { }, warn: () => { } };
99
+ const session = new InstallSession({ root, out: silent, dryRun: true, version });
100
+ let installedVersion = null;
101
+ let hasRecord = false;
102
+ try {
103
+ const doc = JSON.parse(fs.readFileSync(manifestPath(root), "utf-8"));
104
+ // A manifest with no cliVersion was written only by the hook's
105
+ // auto-update: the files are recorded, the install as a whole is not.
106
+ if (doc && typeof doc.files === "object" && typeof doc.cliVersion === "string") {
107
+ hasRecord = true;
108
+ installedVersion = doc.cliVersion;
109
+ }
110
+ }
111
+ catch {
112
+ /* no usable record */
113
+ }
114
+ let outdatedFiles = 0;
115
+ let presentFiles = 0;
116
+ for (const platform of WHOLE_FILE_PLATFORMS) {
117
+ if (!platforms.includes(platform))
118
+ continue;
119
+ for (const a of platformArtifacts(platform, root)) {
120
+ if (fs.existsSync(a.dest))
121
+ presentFiles++;
122
+ if (session.apply(a) === "updated")
123
+ outdatedFiles++;
124
+ }
125
+ }
126
+ const stale = outdatedFiles > 0 ||
127
+ (installedVersion !== null && versionOlder(installedVersion, version)) ||
128
+ (!hasRecord && presentFiles > 0);
129
+ return { stale, installedVersion, cliVersion: version, outdatedFiles, needsReconcile: session.keptFiles(), platforms };
130
+ }
131
+ /** The one line verify / status print when the install is stale. */
132
+ export function stalenessLine(s) {
133
+ const from = s.installedVersion ? `installed by rafter ${s.installedVersion}` : "installed before rafter kept an install record";
134
+ const files = s.outdatedFiles > 0 ? `, ${s.outdatedFiles} file${s.outdatedFiles === 1 ? "" : "s"} older than this CLI ships` : "";
135
+ return `Rafter integrations are out of date (${from}; this CLI is ${s.cliVersion}${files}). Run: rafter agent update`;
136
+ }
137
+ /** The lines verify / status print for modified files waiting on the user: each file, then how to reconcile. */
138
+ export function reconcileLines(s, updateCommand = "rafter agent update") {
139
+ if (s.needsReconcile.length === 0)
140
+ return [];
141
+ const n = s.needsReconcile.length;
142
+ return [
143
+ `${n} rafter file${n === 1 ? "" : "s"} you modified ${n === 1 ? "has" : "have"} a newer version waiting:`,
144
+ ...s.needsReconcile.map((f) => ` ${f} (new: ${f}${NEW_VERSION_SUFFIX})`),
145
+ reconcileInstruction(updateCommand),
146
+ ];
147
+ }
148
+ export function createUpdateCommand() {
149
+ return new Command("update")
150
+ .description("Re-apply every installed rafter integration (skills, rules, instructions, hooks, MCP) with this version")
151
+ .option("--local", "Update the project-local install in the current directory instead of the user-global one")
152
+ .option("--dry-run", "Print what would change, per file, without writing anything")
153
+ .option("--force", "Replace installed skill, rule and sub-agent files even if you modified them (the old file is saved as <file>.bak)", false)
154
+ .option("--quiet", "Suppress informational and success output (warnings and errors still go to stderr)", false)
155
+ .action(async (opts) => {
156
+ const root = opts.local ? process.cwd() : os.homedir();
157
+ const scope = opts.local ? "project" : "user";
158
+ const platforms = detectInstalledPlatforms(root, scope);
159
+ if (platforms.length === 0) {
160
+ if (!opts.quiet) {
161
+ console.log(fmt.info(`No rafter integrations found under ${root}; nothing to update.`));
162
+ console.log(fmt.info(`To install, run: rafter agent init${opts.local ? " --local" : ""} --with-<platform>`));
163
+ }
164
+ return;
165
+ }
166
+ const flags = Object.fromEntries(platforms.map((p) => [INIT_FLAG[p], true]));
167
+ // Loaded here, not at the top: the pretool hook imports this module for
168
+ // detectInstalledPlatforms and must not pay for init's dependencies.
169
+ const { runAgentInit } = await import("./init.js");
170
+ await runAgentInit({
171
+ ...flags,
172
+ local: opts.local,
173
+ dryRun: opts.dryRun,
174
+ force: opts.force,
175
+ quiet: opts.quiet,
176
+ mode: "update",
177
+ });
178
+ });
179
+ }
@@ -8,6 +8,7 @@ import path from "path";
8
8
  import os from "os";
9
9
  import yaml from "js-yaml";
10
10
  import { fmt } from "../../utils/formatter.js";
11
+ import { installStaleness, reconcileLines, stalenessLine } from "./update.js";
11
12
  /**
12
13
  * Run a configured PreToolUse hook command EXACTLY as Claude Code would — through
13
14
  * `sh -c "<command as written in settings.json>"`, with a synthetic payload on
@@ -542,6 +543,8 @@ export function createVerifyCommand() {
542
543
  // hook payloads can be added in follow-ups.
543
544
  results.push(probeClaudeCode());
544
545
  }
546
+ // Informational only: an out-of-date install never fails verify.
547
+ const staleness = installStaleness(os.homedir(), "user");
545
548
  const hardFailed = results.filter((r) => !r.passed && !r.optional);
546
549
  const warned = results.filter((r) => !r.passed && r.optional);
547
550
  const passed = results.filter((r) => r.passed);
@@ -559,6 +562,9 @@ export function createVerifyCommand() {
559
562
  total: results.length,
560
563
  probe: !!opts.probe,
561
564
  },
565
+ stale: staleness.stale,
566
+ installed_version: staleness.installedVersion,
567
+ needs_reconcile: staleness.needsReconcile,
562
568
  };
563
569
  process.stdout.write(JSON.stringify(payload) + "\n");
564
570
  }
@@ -599,6 +605,11 @@ export function createVerifyCommand() {
599
605
  else {
600
606
  console.log(fmt.error(`${passed.length}/${coreResults.length} checks passed — ${hardFailed.length} failed`));
601
607
  }
608
+ if (staleness.stale)
609
+ console.log(fmt.warning(stalenessLine(staleness)));
610
+ const reconcile = reconcileLines(staleness);
611
+ if (reconcile.length > 0)
612
+ console.log(fmt.warning(reconcile.join("\n")));
602
613
  console.log();
603
614
  }
604
615
  if (hardFailed.length > 0) {
@@ -1,6 +1,7 @@
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, reportFailedScan, warnIfPartial } from "./scan-status.js";
3
+ import { fmt } from "../../utils/formatter.js";
4
+ import { handleScanStatus, fetchScanWithRetry, PollGaveUpError, reportFailedScan, warnIfPartial, describeHttpError } from "./scan-status.js";
4
5
  export function createGetCommand() {
5
6
  return new Command("get")
6
7
  .argument("<scan_id>")
@@ -25,20 +26,14 @@ export function createGetCommand() {
25
26
  }
26
27
  catch (e) {
27
28
  if (e.response?.status === 404) {
28
- console.error(`Scan '${scan_id}' not found`);
29
+ console.error(fmt.error(`Scan '${scan_id}' not found`));
29
30
  process.exit(EXIT_SCAN_NOT_FOUND);
30
31
  }
31
32
  else if (e instanceof PollGaveUpError) {
32
- console.error(e.message);
33
- }
34
- else if (e.response?.data) {
35
- console.error(e.response.data);
36
- }
37
- else if (e instanceof Error) {
38
- console.error(e.message);
33
+ console.error(fmt.error(e.message));
39
34
  }
40
35
  else {
41
- console.error(e);
36
+ console.error(fmt.error(describeHttpError(e)));
42
37
  }
43
38
  process.exit(EXIT_GENERAL_ERROR);
44
39
  }