@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
@@ -0,0 +1,439 @@
1
+ /**
2
+ * Local-only usage counters (`~/.rafter/usage/<YYYY-MM-DD>.json`).
3
+ *
4
+ * Counts are keyed by allowlisted enums, counts and duration buckets only; the
5
+ * allowlist is shared-docs/usage-counters.json, embedded below and checked
6
+ * against that file by a test. Nothing here touches the network: the counters
7
+ * stay on this machine until a person pastes `rafter counters show` output
8
+ * somewhere.
9
+ *
10
+ * Recorders only add to an in-memory buffer; the buffer is written once, when
11
+ * the process exits, by one read-modify-write of a tiny file (temp file +
12
+ * rename). Concurrent rafter processes can therefore lose each other's
13
+ * increments (last rename wins); they never leave a torn file, and an
14
+ * unreadable file is replaced. Every entry point swallows its own errors and
15
+ * none writes to stdout.
16
+ *
17
+ * Mirrors python/rafter_cli/core/usage_counters.py. Deleting this file, its
18
+ * Python twin, the two `counters` command files and their one-line call sites
19
+ * removes the feature.
20
+ */
21
+ import fs from "fs";
22
+ import path from "path";
23
+ import { getConfigPath, getRafterDir } from "./config-defaults.js";
24
+ export const USAGE_SCHEMA = 1;
25
+ /** Same values as shared-docs/usage-counters.json (minus its prose description). */
26
+ export const USAGE_ALLOWLIST = {
27
+ schema: 1,
28
+ families: {
29
+ unknown_command: ["unknown_command"],
30
+ unknown_option: ["unknown_option"],
31
+ command: ["command_path", "literal:exit", "exit"],
32
+ hook: ["hook_tool", "hook_decision", "hook_risk"],
33
+ scan_engine: ["scan_engine", "scan_engine"],
34
+ scan_fallback: ["scan_fallback"],
35
+ scan_duration: ["scan_engine", "duration_bucket"],
36
+ error_class: ["command_path", "error_class"],
37
+ },
38
+ patterns: {
39
+ unknown_command: "^[a-z][a-z-]{0,31}$",
40
+ unknown_option: "^--[a-z][a-z-]{0,31}$",
41
+ command_path: "^[a-z][a-z0-9-]{0,31}(\\.[a-z][a-z0-9-]{0,31}){0,3}$",
42
+ error_class: "^([A-Z][A-Za-z0-9]{0,29})?(Error|Exception|Exit|Interrupt)$",
43
+ },
44
+ pattern_fallback: "other",
45
+ enums: {
46
+ exit: ["0", "1", "2", "other"],
47
+ hook_tool: ["shell", "write", "other"],
48
+ hook_decision: ["allow", "deny", "defer", "ask", "error"],
49
+ hook_risk: ["low", "medium", "high", "critical", "none"],
50
+ scan_engine: ["auto", "betterleaks", "patterns", "both"],
51
+ scan_fallback: ["missing", "timeout", "error", "stale", "other"],
52
+ duration_bucket: ["lt1s", "1-5s", "5-30s", "30-120s", "gt120s"],
53
+ },
54
+ duration_bucket_edges_seconds: [1, 5, 30, 120],
55
+ retention_days: 7,
56
+ };
57
+ export const USAGE_FAMILIES = Object.keys(USAGE_ALLOWLIST.families);
58
+ export const USAGE_STORE_DISPLAY = "~/.rafter/usage";
59
+ export const USAGE_NOTICE = "Nothing leaves this machine: these counts are stored locally and rafter has no code to upload them.";
60
+ const PATTERNS = Object.fromEntries(Object.entries(USAGE_ALLOWLIST.patterns).map(([k, v]) => [k, new RegExp(v)]));
61
+ const FALLBACK = USAGE_ALLOWLIST.pattern_fallback;
62
+ /** Value for a pattern part: itself if it matches, else "other". */
63
+ function patterned(kind, value) {
64
+ return typeof value === "string" && PATTERNS[kind].test(value) ? value : FALLBACK;
65
+ }
66
+ function partAllowed(spec, part) {
67
+ if (spec.startsWith("literal:"))
68
+ return part === spec.slice("literal:".length);
69
+ if (spec in USAGE_ALLOWLIST.enums)
70
+ return USAGE_ALLOWLIST.enums[spec].includes(part);
71
+ if (spec in PATTERNS)
72
+ return part === FALLBACK || PATTERNS[spec].test(part);
73
+ return false;
74
+ }
75
+ /** True if every part of `key` is built from the allowlist. */
76
+ export function isAllowedKey(key) {
77
+ if (typeof key !== "string")
78
+ return false;
79
+ const [family, ...parts] = key.split(":");
80
+ const spec = USAGE_ALLOWLIST.families[family];
81
+ if (!spec || !Object.prototype.hasOwnProperty.call(USAGE_ALLOWLIST.families, family))
82
+ return false;
83
+ return parts.length === spec.length && spec.every((s, i) => partAllowed(s, parts[i]));
84
+ }
85
+ // ── in-memory buffer ────────────────────────────────────────────────
86
+ const pending = new Map();
87
+ let commandPath = null;
88
+ let discarded = false;
89
+ function bump(key) {
90
+ if (discarded || !isAllowedKey(key))
91
+ return;
92
+ pending.set(key, (pending.get(key) ?? 0) + 1);
93
+ }
94
+ function guard(fn) {
95
+ try {
96
+ fn();
97
+ }
98
+ catch {
99
+ // Counting must never affect the command.
100
+ }
101
+ }
102
+ /** Test hook: the keys buffered so far. */
103
+ export function pendingCounts() {
104
+ return Object.fromEntries(pending);
105
+ }
106
+ /** Test hook: forget buffered counts and the command path. */
107
+ export function resetPending() {
108
+ pending.clear();
109
+ commandPath = null;
110
+ discarded = false;
111
+ }
112
+ /** Drop everything buffered and stop counting for this process (`counters clear`). */
113
+ export function discardPending() {
114
+ pending.clear();
115
+ discarded = true;
116
+ }
117
+ export function vocabularyOf(root) {
118
+ const commands = new Set();
119
+ const options = new Set();
120
+ const visit = (cmd) => {
121
+ for (const o of cmd.options) {
122
+ if (!o.long)
123
+ continue;
124
+ options.add(o.long);
125
+ }
126
+ for (const sub of cmd.commands) {
127
+ commands.add(sub.name());
128
+ for (const a of sub.aliases())
129
+ commands.add(a);
130
+ visit(sub);
131
+ }
132
+ };
133
+ visit(root);
134
+ const words = new Set();
135
+ for (const n of [...commands, ...[...options].map((o) => o.slice(2))])
136
+ for (const w of n.split("-"))
137
+ if (w)
138
+ words.add(w);
139
+ return { commands: [...commands], options: [...options], words };
140
+ }
141
+ /** Optimal-string-alignment (restricted Damerau-Levenshtein) distance. */
142
+ export function editDistance(a, b) {
143
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
144
+ for (let j = 1; j <= b.length; j++)
145
+ d[0][j] = j;
146
+ for (let i = 1; i <= a.length; i++) {
147
+ for (let j = 1; j <= b.length; j++) {
148
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
149
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
150
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
151
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
152
+ }
153
+ }
154
+ return d[a.length][b.length];
155
+ }
156
+ /**
157
+ * Keep a token that already matched its pattern only if it is near a
158
+ * registered name (distance <= 2) or is built entirely from the CLI's own
159
+ * words. Anything else (a project or client name) becomes "other".
160
+ */
161
+ function plausible(token, candidates, words, prefix) {
162
+ if (candidates.some((c) => Math.abs(c.length - token.length) <= 2 && editDistance(token, c) <= 2))
163
+ return true;
164
+ return token.slice(prefix.length).split("-").every((p) => p !== "" && words.has(p));
165
+ }
166
+ function vetted(kind, token, vocab) {
167
+ const v = patterned(kind, token);
168
+ if (v === FALLBACK || !vocab)
169
+ return FALLBACK;
170
+ return kind === "unknown_command"
171
+ ? plausible(v, vocab.commands, vocab.words, "") ? v : FALLBACK
172
+ : plausible(v, vocab.options, vocab.words, "--") ? v : FALLBACK;
173
+ }
174
+ export function countUnknownCommand(token, vocab) {
175
+ guard(() => bump(`unknown_command:${vetted("unknown_command", token, vocab)}`));
176
+ }
177
+ export function countUnknownOption(flag, vocab) {
178
+ guard(() => {
179
+ const name = typeof flag === "string" ? flag.split("=")[0] : flag;
180
+ bump(`unknown_option:${vetted("unknown_option", name, vocab)}`);
181
+ });
182
+ }
183
+ /**
184
+ * Set the resolved command path from registered command names (not argv).
185
+ * A name that is not in the vocabulary makes the whole path "other".
186
+ */
187
+ export function setCommandPath(names, vocab) {
188
+ guard(() => {
189
+ if (names.length === 0)
190
+ commandPath = "root";
191
+ else if (!vocab || !names.every((n) => vocab.commands.includes(n)))
192
+ commandPath = FALLBACK;
193
+ else
194
+ commandPath = patterned("command_path", names.join("."));
195
+ });
196
+ }
197
+ function currentPath() {
198
+ return commandPath ?? "root";
199
+ }
200
+ export function exitBucket(code) {
201
+ return code === 0 || code === 1 || code === 2 ? String(code) : "other";
202
+ }
203
+ export function countHook(tool, decision, risk) {
204
+ guard(() => {
205
+ const e = USAGE_ALLOWLIST.enums;
206
+ const t = e.hook_tool.includes(tool) ? tool : "other";
207
+ const d = e.hook_decision.includes(decision) ? decision : "error";
208
+ const r = e.hook_risk.includes(risk) ? risk : "none";
209
+ bump(`hook:${t}:${d}:${r}`);
210
+ });
211
+ }
212
+ /** Map a free-text fall-back reason onto the enum. The text itself is never stored. */
213
+ export function classifyFallback(reason) {
214
+ const s = typeof reason === "string" ? reason.toLowerCase() : "";
215
+ if (/timed out|timeout/.test(s))
216
+ return "timeout";
217
+ if (/stale|update/.test(s))
218
+ return "stale";
219
+ if (/not available|unavailable|not found|missing|enoent/.test(s))
220
+ return "missing";
221
+ if (/fail|error|crash|exit/.test(s))
222
+ return "error";
223
+ return "other";
224
+ }
225
+ export function durationBucket(ms) {
226
+ const s = ms / 1000;
227
+ const [a, b, c, d] = USAGE_ALLOWLIST.duration_bucket_edges_seconds;
228
+ if (s < a)
229
+ return "lt1s";
230
+ if (s < b)
231
+ return "1-5s";
232
+ if (s < c)
233
+ return "5-30s";
234
+ if (s < d)
235
+ return "30-120s";
236
+ return "gt120s";
237
+ }
238
+ /** Record one local scan from its engine report and elapsed time. */
239
+ export function countScan(report, elapsedMs) {
240
+ guard(() => {
241
+ if (!report)
242
+ return;
243
+ bump(`scan_engine:${report.requested}:${report.used}`);
244
+ if (report.degraded)
245
+ bump(`scan_fallback:${classifyFallback(report.reason)}`);
246
+ bump(`scan_duration:${report.used}:${durationBucket(elapsedMs)}`);
247
+ });
248
+ }
249
+ /** Record an uncaught error by class name only. */
250
+ export function countError(err) {
251
+ guard(() => {
252
+ const name = err instanceof Error ? err.constructor?.name : typeof err;
253
+ bump(`error_class:${currentPath()}:${patterned("error_class", name)}`);
254
+ });
255
+ }
256
+ /**
257
+ * Whether counting is on, and why. Read only from the environment and the
258
+ * global ~/.rafter/config.json (`agent.usage.enabled`); a project .rafter.yml
259
+ * is never consulted.
260
+ */
261
+ export function usageStatus(env = process.env) {
262
+ const rt = (env.RAFTER_USAGE_COUNTERS ?? "").trim().toLowerCase();
263
+ if (rt === "0" || rt === "false" || rt === "off")
264
+ return { enabled: false, source: "env:RAFTER_USAGE_COUNTERS" };
265
+ const dnt = (env.DO_NOT_TRACK ?? "").trim().toLowerCase();
266
+ if (dnt !== "" && dnt !== "0" && dnt !== "false")
267
+ return { enabled: false, source: "env:DO_NOT_TRACK" };
268
+ try {
269
+ const cfg = JSON.parse(fs.readFileSync(getConfigPath(), "utf-8"));
270
+ const v = cfg?.agent?.usage?.enabled;
271
+ if (v === false)
272
+ return { enabled: false, source: "config" };
273
+ if (v === true)
274
+ return { enabled: true, source: "config" };
275
+ }
276
+ catch {
277
+ // Missing or unreadable config: the default applies.
278
+ }
279
+ return { enabled: true, source: "default" };
280
+ }
281
+ // ── store ───────────────────────────────────────────────────────────
282
+ export function usageDir() {
283
+ return path.join(getRafterDir(), "usage");
284
+ }
285
+ export function utcDay(d) {
286
+ return d.toISOString().slice(0, 10);
287
+ }
288
+ const DAY_FILE = /^(\d{4}-\d{2}-\d{2})\.json$/;
289
+ /** Allowlisted, positive-integer counts from one day file; {} if missing or corrupt. */
290
+ function readDay(file) {
291
+ const out = {};
292
+ try {
293
+ const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
294
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || raw.schema !== USAGE_SCHEMA)
295
+ return out;
296
+ for (const [k, v] of Object.entries(raw)) {
297
+ if (k !== "schema" && isAllowedKey(k) && Number.isSafeInteger(v) && v > 0)
298
+ out[k] = v;
299
+ }
300
+ }
301
+ catch {
302
+ // Missing or corrupt: treated as empty and replaced on the next write.
303
+ }
304
+ return out;
305
+ }
306
+ function prune(dir, today) {
307
+ const keep = USAGE_ALLOWLIST.retention_days;
308
+ const oldest = utcDay(new Date(Date.parse(today) - (keep - 1) * 86400000));
309
+ for (const name of fs.readdirSync(dir)) {
310
+ try {
311
+ const m = DAY_FILE.exec(name);
312
+ if (m && m[1] < oldest)
313
+ fs.unlinkSync(path.join(dir, name));
314
+ else if (name.endsWith(".tmp") && Date.now() - fs.statSync(path.join(dir, name)).mtimeMs > 60000) {
315
+ fs.unlinkSync(path.join(dir, name));
316
+ }
317
+ }
318
+ catch {
319
+ // best effort
320
+ }
321
+ }
322
+ }
323
+ /** Add `counts` to today's file. Throws on I/O failure; callers guard. */
324
+ export function writeCounts(counts, now = new Date()) {
325
+ const entries = counts instanceof Map ? [...counts] : Object.entries(counts);
326
+ if (entries.length === 0)
327
+ return;
328
+ const dir = usageDir();
329
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
330
+ const day = utcDay(now);
331
+ const file = path.join(dir, `${day}.json`);
332
+ const firstToday = !fs.existsSync(file);
333
+ const merged = readDay(file);
334
+ for (const [k, n] of entries) {
335
+ if (isAllowedKey(k) && Number.isSafeInteger(n) && n > 0)
336
+ merged[k] = (merged[k] ?? 0) + n;
337
+ }
338
+ const body = { schema: USAGE_SCHEMA };
339
+ for (const k of Object.keys(merged).sort())
340
+ body[k] = merged[k];
341
+ const tmp = path.join(dir, `.${day}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
342
+ try {
343
+ fs.writeFileSync(tmp, JSON.stringify(body, null, 2) + "\n", { mode: 0o600 });
344
+ fs.renameSync(tmp, file);
345
+ }
346
+ catch (e) {
347
+ try {
348
+ fs.unlinkSync(tmp);
349
+ }
350
+ catch { /* already gone */ }
351
+ throw e;
352
+ }
353
+ if (firstToday) {
354
+ try {
355
+ fs.chmodSync(dir, 0o700);
356
+ }
357
+ catch { /* best effort */ }
358
+ prune(dir, day);
359
+ }
360
+ }
361
+ /**
362
+ * Record the command result and write the buffer, if counting is enabled.
363
+ * Called once, at process exit.
364
+ */
365
+ export function flush(exitCode) {
366
+ guard(() => {
367
+ if (discarded)
368
+ return;
369
+ bump(`command:${currentPath()}:exit:${exitBucket(exitCode)}`);
370
+ if (!usageStatus().enabled)
371
+ return;
372
+ writeCounts(pending);
373
+ pending.clear();
374
+ });
375
+ }
376
+ /** Sum the last `days` daily files (today included), grouped by family. */
377
+ export function readCounters(days, now = new Date()) {
378
+ const counters = Object.fromEntries(USAGE_FAMILIES.map((f) => [f, {}]));
379
+ const today = Date.parse(utcDay(now));
380
+ let since = utcDay(now);
381
+ for (let i = 0; i < days; i++) {
382
+ const day = utcDay(new Date(today - i * 86400000));
383
+ since = day;
384
+ for (const [k, n] of Object.entries(readDay(path.join(usageDir(), `${day}.json`)))) {
385
+ const fam = counters[k.split(":")[0]];
386
+ fam[k] = (fam[k] ?? 0) + n;
387
+ }
388
+ }
389
+ for (const f of USAGE_FAMILIES) {
390
+ counters[f] = Object.fromEntries(Object.entries(counters[f]).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
391
+ }
392
+ return { since, counters };
393
+ }
394
+ /** Delete the usage directory. Returns whether it existed. */
395
+ export function clearStore() {
396
+ const dir = usageDir();
397
+ const existed = fs.existsSync(dir);
398
+ fs.rmSync(dir, { recursive: true, force: true });
399
+ return existed;
400
+ }
401
+ // ── commander wiring ────────────────────────────────────────────────
402
+ function registeredPath(cmd) {
403
+ const names = [];
404
+ for (let c = cmd; c && c.parent; c = c.parent)
405
+ names.unshift(c.name());
406
+ return names;
407
+ }
408
+ const QUOTED = /'([^']*)'/;
409
+ /**
410
+ * Wire the counters into a commander program: command path from the
411
+ * registered tree, unknown commands/options from commander's own errors,
412
+ * uncaught errors by class, and one flush at exit. Call once, before parse().
413
+ */
414
+ export function installUsageCounters(program) {
415
+ guard(() => {
416
+ let cached;
417
+ const vocab = () => (cached ?? (cached = vocabularyOf(program)));
418
+ const visit = (cmd) => {
419
+ cmd.hook("preAction", (_self, actionCommand) => setCommandPath(registeredPath(actionCommand), vocab()));
420
+ // A callback that returns lets commander exit exactly as it would have.
421
+ cmd.exitOverride((err) => {
422
+ guard(() => {
423
+ if (commandPath === null)
424
+ setCommandPath(registeredPath(cmd), vocab());
425
+ const token = QUOTED.exec(err.message ?? "")?.[1];
426
+ if (err.code === "commander.unknownCommand")
427
+ countUnknownCommand(token, vocab());
428
+ else if (err.code === "commander.unknownOption")
429
+ countUnknownOption(token, vocab());
430
+ });
431
+ });
432
+ for (const sub of cmd.commands)
433
+ visit(sub);
434
+ };
435
+ visit(program);
436
+ process.on("uncaughtExceptionMonitor", (err) => countError(err));
437
+ process.on("exit", (code) => flush(code));
438
+ });
439
+ }
package/dist/index.js CHANGED
@@ -19,7 +19,10 @@ import { createNotifyCommand } from "./commands/notify.js";
19
19
  import { createCompletionCommand } from "./commands/completion.js";
20
20
  import { createIssuesCommand } from "./commands/issues/index.js";
21
21
  import { createReportCommand } from "./commands/report.js";
22
+ import { createGatesCommand } from "./commands/gates.js";
22
23
  import { createSitesCommand } from "./commands/sites/index.js";
24
+ import { createCountersCommand } from "./commands/counters.js";
25
+ import { installUsageCounters } from "./core/usage-counters.js";
23
26
  import { checkForUpdate } from "./utils/update-checker.js";
24
27
  import { setAgentMode } from "./utils/formatter.js";
25
28
  import { createRequire } from "module";
@@ -76,17 +79,50 @@ program.addCommand(createBriefCommand());
76
79
  program.addCommand(createNotifyCommand());
77
80
  // HTML security report
78
81
  program.addCommand(createReportCommand());
82
+ // Gates — static map of security gates for an audit
83
+ program.addCommand(createGatesCommand());
79
84
  // Shell completions
80
85
  program.addCommand(createCompletionCommand());
86
+ // Local usage counters (nothing leaves the machine)
87
+ program.addCommand(createCountersCommand());
81
88
  // Version subcommand (also available as --version)
82
89
  program.addCommand(new Command("version")
83
90
  .description("Print version and exit")
84
91
  .action(() => {
85
92
  console.log(VERSION);
86
93
  }));
94
+ /**
95
+ * `-a`/`--agent` is declared only on the root `program`, so Commander rejects
96
+ * it as an unknown option once it appears after a subcommand name
97
+ * (`rafter secrets . -a`, `rafter scan local . -a`). The actual mode switch
98
+ * already happens above via the `process.argv` scan, which is
99
+ * position-independent — this just teaches every command in the tree to
100
+ * accept the flag syntactically instead of erroring on it.
101
+ *
102
+ * Skipped on a command that declares its own `--agent <value>` option
103
+ * (`agent audit`, `skill review` filter by agent type) and on every parent
104
+ * of one: Commander lets a parent consume its options anywhere in argv, so a
105
+ * boolean `--agent` on `skill` would swallow `skill review --agent codex` and
106
+ * leave `codex` as a stray positional. `rafter -a agent audit ...` (the flag
107
+ * before the subcommand) still works for those two.
108
+ */
109
+ function declaresAgentOption(cmd) {
110
+ return (cmd.options.some((o) => o.long === "--agent") ||
111
+ cmd.commands.some(declaresAgentOption));
112
+ }
113
+ function allowAgentFlagAtAnyDepth(cmd) {
114
+ if (!declaresAgentOption(cmd)) {
115
+ cmd.option("-a, --agent", "Plain output for AI agents (no colors/emoji)");
116
+ }
117
+ for (const sub of cmd.commands) {
118
+ allowAgentFlagAtAnyDepth(sub);
119
+ }
120
+ }
121
+ allowAgentFlagAtAnyDepth(program);
87
122
  // Non-blocking update check — runs after command, prints to stderr
88
123
  checkForUpdate(VERSION).then((notice) => {
89
124
  if (notice)
90
125
  process.stderr.write(notice);
91
126
  });
127
+ installUsageCounters(program);
92
128
  program.parse();