@agenticcli/shipguard 0.1.2 → 0.2.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.
package/README.md CHANGED
@@ -4,24 +4,52 @@ CLI-first release gate for AI-built apps.
4
4
 
5
5
  Catches secrets leaks, auth gaps, payment webhook risks, destructive migrations, and deployment misconfigurations — before your code ships.
6
6
 
7
- ## Install
7
+ ## 30-second quickstart
8
8
 
9
9
  ```bash
10
+ # Zero install — scan right now
11
+ npx @agenticcli/shipguard scan
12
+
13
+ # Or install globally
10
14
  npm install -g @agenticcli/shipguard
15
+
16
+ # Then run from any project directory
17
+ shipguard scan
11
18
  ```
12
19
 
20
+ > **PATH gotcha:** `npm install` (without `-g`) does NOT put `shipguard` on your PATH.
21
+ > Use `npx @agenticcli/shipguard scan` or install with `npm install -g @agenticcli/shipguard`.
22
+
13
23
  ## Usage
14
24
 
15
25
  ```bash
16
- shipguard init # Initialize policy file
17
- shipguard scan # Run all checks
18
- shipguard scan --strict # Fail on high-risk issues (for CI)
19
- shipguard scan --json # Machine-readable output
26
+ shipguard scan # Scan current project (rich output)
27
+ shipguard scan --strict # CI mode: exit 1 on blocking findings
28
+ shipguard scan --json # Machine-readable output for agents/CI
29
+ shipguard scan --quiet # One-line verdict only
30
+ shipguard scan --pro # Pro rules — requires login
31
+ shipguard login # Authenticate for Pro rules
32
+ shipguard init # Generate .shipguard.yml policy file
20
33
  ```
21
34
 
35
+ ## Exit codes
36
+
37
+ | Code | Meaning |
38
+ |------|---------|
39
+ | `0` | Safe — no blocking findings |
40
+ | `1` | Blocked — `--strict` mode + blocking findings |
41
+ | `2` | Config error / degraded scan |
42
+ | `3` | Runtime error |
43
+
44
+ ## Telemetry
45
+
46
+ ShipGuard sends an anonymous usage ping on each scan (verdict bucket, duration, CLI version, CI flag — never file contents, paths, or user identity). Opt out: `SHIPGUARD_TELEMETRY=0` or `DO_NOT_TRACK=1`.
47
+
48
+ Details: [agenticcli.dev/docs#telemetry](https://agenticcli.dev/docs#telemetry)
49
+
22
50
  ## Documentation
23
51
 
24
- See [full docs](https://agenticcli.dev/shipguard) for policy configuration, CI setup, and agent integration.
52
+ See [full docs](https://agenticcli.dev/docs) for policy configuration, CI setup, and agent integration.
25
53
 
26
54
  ## License
27
55
 
@@ -1,13 +1,36 @@
1
1
  // src/core/auth.ts
2
- import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from "fs";
2
+ import {
3
+ readFileSync,
4
+ writeFileSync,
5
+ mkdirSync,
6
+ rmSync,
7
+ existsSync,
8
+ statSync,
9
+ chmodSync
10
+ } from "fs";
3
11
  import { join, dirname } from "path";
4
12
  import { homedir } from "os";
13
+ var DIR_MODE = 448;
14
+ var FILE_MODE = 384;
15
+ var UNSAFE_PERM_MASK = 63;
16
+ var isPosix = process.platform !== "win32";
5
17
  function getCredentialsPath() {
6
18
  return join(homedir(), ".config", "shipguard", "credentials.json");
7
19
  }
20
+ function hasUnsafePermissions(path) {
21
+ if (!isPosix) return false;
22
+ const mode = statSync(path).mode & 511;
23
+ return (mode & UNSAFE_PERM_MASK) !== 0;
24
+ }
8
25
  function loadCredentials() {
9
26
  const p = getCredentialsPath();
10
27
  if (!existsSync(p)) return null;
28
+ if (hasUnsafePermissions(p)) {
29
+ console.warn(
30
+ "[shipguard] credentials file has unsafe permissions (group/other-readable or writable) \u2014 refusing to use it. Run `shipguard login` again to re-create it with 0600 perms."
31
+ );
32
+ return null;
33
+ }
11
34
  try {
12
35
  return JSON.parse(readFileSync(p, "utf-8"));
13
36
  } catch {
@@ -17,12 +40,21 @@ function loadCredentials() {
17
40
  }
18
41
  async function saveCredentials(creds) {
19
42
  const p = getCredentialsPath();
20
- mkdirSync(dirname(p), { recursive: true });
21
- writeFileSync(p, JSON.stringify(creds, null, 2), { mode: 384 });
43
+ const dir = dirname(p);
44
+ mkdirSync(dir, { recursive: true, mode: DIR_MODE });
45
+ if (isPosix) chmodSync(dir, DIR_MODE);
46
+ writeFileSync(p, JSON.stringify(creds, null, 2), { mode: FILE_MODE });
47
+ if (isPosix) chmodSync(p, FILE_MODE);
22
48
  }
23
49
  function clearCredentials() {
24
50
  const p = getCredentialsPath();
25
- if (existsSync(p)) rmSync(p);
51
+ if (!existsSync(p)) return;
52
+ try {
53
+ const size = statSync(p).size;
54
+ if (size > 0) writeFileSync(p, Buffer.alloc(size, 0), { mode: FILE_MODE });
55
+ } catch {
56
+ }
57
+ rmSync(p, { force: true });
26
58
  }
27
59
  function isTokenExpired(creds) {
28
60
  return creds.expiresAt < Date.now();
@@ -58,9 +90,15 @@ async function getAuthToken() {
58
90
  // src/core/crypto.ts
59
91
  import { hkdf } from "@noble/hashes/hkdf.js";
60
92
  import { sha256 } from "@noble/hashes/sha2.js";
61
- var FALLBACK_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
93
+ var PINNED_KEYS = {
94
+ "k1-2026": `-----BEGIN PUBLIC KEY-----
62
95
  MCowBQYDK2VwAyEAkpeX0A3zIOttGn8t+jagJHLRTv5Q809vqIZU37lE6xQ=
63
- -----END PUBLIC KEY-----`;
96
+ -----END PUBLIC KEY-----`,
97
+ "k2-2026": `-----BEGIN PUBLIC KEY-----
98
+ MCowBQYDK2VwAyEA1DXW6sA9dllAbfXMa/G+50Sw00svQF2X5bcU+YcP6M8=
99
+ -----END PUBLIC KEY-----`
100
+ };
101
+ var DEFAULT_KID = "k1-2026";
64
102
  var HKDF_INFO = "shipguard-rules-v1";
65
103
  function pemToArrayBuffer(pem) {
66
104
  const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s/g, "");
@@ -70,7 +108,14 @@ function pemToArrayBuffer(pem) {
70
108
  async function verifyAndDecryptBundle(bundleB64, accessToken) {
71
109
  const bundleJson = Buffer.from(bundleB64, "base64").toString("utf-8");
72
110
  const bundle = JSON.parse(bundleJson);
73
- const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? FALLBACK_PUBLIC_KEY;
111
+ const kid = bundle.payload.kid ?? DEFAULT_KID;
112
+ const resolvedPem = PINNED_KEYS[kid];
113
+ if (!resolvedPem && !process.env.SHIPGUARD_PUBLIC_KEY) {
114
+ throw new Error(
115
+ `Unknown signing key "${kid}" \u2014 rule bundle rejected (fail closed). Upgrade shipguard to a version that supports this key id.`
116
+ );
117
+ }
118
+ const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? resolvedPem;
74
119
  const cryptoKey = await globalThis.crypto.subtle.importKey(
75
120
  "spki",
76
121
  pemToArrayBuffer(pem),
@@ -115,7 +160,7 @@ async function verifyAndDecryptBundle(bundleB64, accessToken) {
115
160
  }
116
161
  async function verifyRuleBundle(token) {
117
162
  const { importSPKI: importKey, jwtVerify } = await import("jose");
118
- const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? FALLBACK_PUBLIC_KEY;
163
+ const pem = process.env.SHIPGUARD_PUBLIC_KEY ?? PINNED_KEYS[DEFAULT_KID];
119
164
  const publicKey = await importKey(pem, "EdDSA");
120
165
  const { payload } = await jwtVerify(token, publicKey);
121
166
  return payload;
@@ -1346,6 +1391,49 @@ try {
1346
1391
  CLI_VERSION = "0.0.0";
1347
1392
  }
1348
1393
 
1394
+ // src/core/suppression.ts
1395
+ var SUPPRESS_RE = /\/\/\s*shipguard-ignore:\s*([\w.-]+)\s*--\s*(.+)/;
1396
+ function isLineSuppressed(lines, lineIndex, ruleId) {
1397
+ const sameLine = lines[lineIndex];
1398
+ if (sameLine !== void 0) {
1399
+ const sameMatch = SUPPRESS_RE.exec(sameLine);
1400
+ if (sameMatch && sameMatch[1] === ruleId) return true;
1401
+ }
1402
+ if (lineIndex > 0) {
1403
+ const aboveLine = lines[lineIndex - 1];
1404
+ if (aboveLine !== void 0) {
1405
+ const aboveMatch = SUPPRESS_RE.exec(aboveLine);
1406
+ if (aboveMatch && aboveMatch[1] === ruleId) return true;
1407
+ }
1408
+ }
1409
+ return false;
1410
+ }
1411
+ function applySuppressions(findings, files) {
1412
+ if (findings.length === 0) return findings;
1413
+ const linesByPath = /* @__PURE__ */ new Map();
1414
+ const linesFor = (relativePath) => {
1415
+ if (linesByPath.has(relativePath)) return linesByPath.get(relativePath);
1416
+ const file = files.find((f) => f.relativePath === relativePath);
1417
+ if (!file) {
1418
+ linesByPath.set(relativePath, []);
1419
+ return void 0;
1420
+ }
1421
+ const split = file.content.split("\n");
1422
+ linesByPath.set(relativePath, split);
1423
+ return split;
1424
+ };
1425
+ for (const finding of findings) {
1426
+ if (finding.line === void 0) continue;
1427
+ const lines = linesFor(finding.file);
1428
+ if (!lines || lines.length === 0) continue;
1429
+ if (isLineSuppressed(lines, finding.line - 1, finding.id)) {
1430
+ finding.suppressed = true;
1431
+ finding.blocking = false;
1432
+ }
1433
+ }
1434
+ return findings;
1435
+ }
1436
+
1349
1437
  // src/core/pro-scanner.ts
1350
1438
  async function fetchProRules(frameworks, categories, apiUrl) {
1351
1439
  const token = await getAuthToken();
@@ -1401,18 +1489,6 @@ function compileRules(rules) {
1401
1489
  }
1402
1490
  return compiled;
1403
1491
  }
1404
- var SUPPRESS_RE = /\/\/\s*shipguard-ignore:\s*([\w.-]+)\s*--\s*(.+)/;
1405
- function isLineSuppressed(lines, lineIndex, ruleId) {
1406
- const sameLine = lines[lineIndex];
1407
- const sameMatch = SUPPRESS_RE.exec(sameLine);
1408
- if (sameMatch && sameMatch[1] === ruleId) return true;
1409
- if (lineIndex > 0) {
1410
- const aboveLine = lines[lineIndex - 1];
1411
- const aboveMatch = SUPPRESS_RE.exec(aboveLine);
1412
- if (aboveMatch && aboveMatch[1] === ruleId) return true;
1413
- }
1414
- return false;
1415
- }
1416
1492
  function deriveBlocking(rule) {
1417
1493
  if (rule.action === "block") return true;
1418
1494
  if (rule.action === "warn" || rule.action === "monitor") return false;
@@ -1491,6 +1567,7 @@ export {
1491
1567
  clearCredentials,
1492
1568
  isTokenExpired,
1493
1569
  getAuthToken,
1570
+ applySuppressions,
1494
1571
  fetchProRules,
1495
1572
  runProRules,
1496
1573
  runProRulesWithDispatch
@@ -46,6 +46,7 @@ var DEFAULT_IGNORE = [
46
46
  // ShipGuard's own report output — never scan the tool's own artifacts
47
47
  ".shipguard/**"
48
48
  ];
49
+ var MAX_SKIPPED_NAMES = 50;
49
50
  async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = [], options = {}) {
50
51
  const maxFileSizeBytes = options.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES;
51
52
  const maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES;
@@ -57,11 +58,20 @@ async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = [], opti
57
58
  ignore: allIgnore,
58
59
  dot: true,
59
60
  absolute: false,
60
- onlyFiles: true
61
+ onlyFiles: true,
62
+ // Privacy moat (incident 3063d8a9): NEVER follow symlinks. A symlink inside
63
+ // the project pointing out of the root (e.g. `ln -s /home escape`) would
64
+ // otherwise cause the scan to descend out-of-tree, reading and reporting
65
+ // files the user never intended to scan (and risking a hang on huge external
66
+ // trees). The user's code must never leave their machine; out-of-tree files
67
+ // must never enter the scan. fast-glob defaults this to true, so it is
68
+ // load-bearing that we set it false explicitly.
69
+ followSymbolicLinks: false
61
70
  });
62
71
  const total = filePaths.length;
63
72
  const files = [];
64
73
  let skippedTooLarge = 0;
74
+ const skippedTooLargeFiles = [];
65
75
  let skippedBinary = 0;
66
76
  let truncated = false;
67
77
  let totalBytes = 0;
@@ -76,6 +86,9 @@ async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = [], opti
76
86
  const fileStat = await stat(fullPath);
77
87
  if (fileStat.size > maxFileSizeBytes) {
78
88
  skippedTooLarge++;
89
+ if (skippedTooLargeFiles.length < MAX_SKIPPED_NAMES) {
90
+ skippedTooLargeFiles.push(fp);
91
+ }
79
92
  onProgress?.(++processed, total, fp);
80
93
  continue;
81
94
  }
@@ -104,7 +117,7 @@ async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = [], opti
104
117
  }
105
118
  onProgress?.(++processed, total, fp);
106
119
  }
107
- return { files, skippedTooLarge, skippedBinary, truncated };
120
+ return { files, skippedTooLarge, skippedTooLargeFiles, skippedBinary, truncated };
108
121
  }
109
122
 
110
123
  export {
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ applySuppressions,
3
4
  authCheck,
4
5
  clearCredentials,
5
6
  databaseCheck,
@@ -11,16 +12,16 @@ import {
11
12
  runProRulesWithDispatch,
12
13
  saveCredentials,
13
14
  secretsCheck
14
- } from "./chunk-IK7VIKXY.js";
15
+ } from "./chunk-2N3P2DUE.js";
15
16
  import {
16
17
  DEFAULT_MAX_FILES,
17
18
  DEFAULT_MAX_FILE_SIZE_BYTES,
18
19
  DEFAULT_MAX_TOTAL_BYTES,
19
20
  readFiles
20
- } from "./chunk-7HMLDAMC.js";
21
+ } from "./chunk-BZWSFLBO.js";
21
22
 
22
23
  // src/cli.ts
23
- import { Command as Command7 } from "commander";
24
+ import { Command as Command7, CommanderError } from "commander";
24
25
 
25
26
  // src/commands/init.ts
26
27
  import { Command } from "commander";
@@ -138,9 +139,9 @@ async function createShipguardDir(dir) {
138
139
  // src/utils/logger.ts
139
140
  import chalk from "chalk";
140
141
  var logger = {
141
- info: (msg) => console.log(chalk.blue("\u2139"), msg),
142
- success: (msg) => console.log(chalk.green("\u2713"), msg),
143
- warn: (msg) => console.log(chalk.yellow("\u26A0"), msg),
142
+ info: (msg) => console.error(chalk.blue("\u2139"), msg),
143
+ success: (msg) => console.error(chalk.green("\u2713"), msg),
144
+ warn: (msg) => console.error(chalk.yellow("\u26A0"), msg),
144
145
  error: (msg) => console.error(chalk.red("\u2717"), msg),
145
146
  finding: (severity, msg) => {
146
147
  const colors = {
@@ -152,17 +153,17 @@ var logger = {
152
153
  };
153
154
  const colorFn = colors[severity] || chalk.white;
154
155
  const label = severity.toUpperCase().padEnd(8);
155
- console.log(` ${colorFn(label)} ${msg}`);
156
+ console.error(` ${colorFn(label)} ${msg}`);
156
157
  },
157
158
  score: (score, recommendation) => {
158
159
  const color = score <= 20 ? chalk.green : score <= 50 ? chalk.yellow : chalk.red;
159
160
  const icon = score <= 20 ? "\u2713" : score <= 50 ? "\u26A0" : "\u2717";
160
- console.log("");
161
- console.log(chalk.bold("ShipGuard Scan Result"));
162
- console.log(`Risk Score: ${color(`${score}/100`)}`);
163
- console.log(`Status: ${color(`${icon} ${recommendation.replace(/_/g, " ")}`)}`);
161
+ console.error("");
162
+ console.error(chalk.bold("ShipGuard Scan Result"));
163
+ console.error(`Risk Score: ${color(`${score}/100`)}`);
164
+ console.error(`Status: ${color(`${icon} ${recommendation.replace(/_/g, " ")}`)}`);
164
165
  },
165
- divider: () => console.log(chalk.gray("\u2500".repeat(50)))
166
+ divider: () => console.error(chalk.gray("\u2500".repeat(50)))
166
167
  };
167
168
 
168
169
  // src/commands/init.ts
@@ -190,7 +191,7 @@ function initCommand() {
190
191
  import { Command as Command2 } from "commander";
191
192
  import { randomUUID } from "crypto";
192
193
  import { existsSync as existsSync3 } from "fs";
193
- import { join as join4, resolve as resolve3 } from "path";
194
+ import { join as join5, resolve as resolve3 } from "path";
194
195
 
195
196
  // src/core/scanner.ts
196
197
  import { readFile as readFile2, stat } from "fs/promises";
@@ -309,6 +310,7 @@ async function scan(options, proRules, onProgress) {
309
310
  };
310
311
  let files;
311
312
  let skippedTooLarge = 0;
313
+ const skippedTooLargeFiles = [];
312
314
  let skippedBinary = 0;
313
315
  let truncated = false;
314
316
  if (options.changedOnly && isGitRepo(cwd)) {
@@ -333,6 +335,9 @@ async function scan(options, proRules, onProgress) {
333
335
  const fileStat = await stat(fullPath);
334
336
  if (fileStat.size > limits.maxFileSizeBytes) {
335
337
  skippedTooLarge++;
338
+ if (skippedTooLargeFiles.length < 50) {
339
+ skippedTooLargeFiles.push(relPath);
340
+ }
336
341
  onProgress?.(++changedProcessed, changedTotal, relPath);
337
342
  continue;
338
343
  }
@@ -369,10 +374,14 @@ async function scan(options, proRules, onProgress) {
369
374
  });
370
375
  files = readResult.files;
371
376
  skippedTooLarge = readResult.skippedTooLarge;
377
+ skippedTooLargeFiles.push(...readResult.skippedTooLargeFiles);
372
378
  skippedBinary = readResult.skippedBinary;
373
379
  truncated = readResult.truncated;
374
380
  }
375
- let allFindings = CHECK_MODULES.flatMap((mod) => mod.run(files, policy));
381
+ let allFindings = applySuppressions(
382
+ CHECK_MODULES.flatMap((mod) => mod.run(files, policy)),
383
+ files
384
+ );
376
385
  let coderefDegraded = false;
377
386
  if (proRules?.length) {
378
387
  const { findings: proFindings, degraded, warnings } = runProRulesWithDispatch(proRules, files, policy);
@@ -383,17 +392,47 @@ async function scan(options, proRules, onProgress) {
383
392
  }
384
393
  }
385
394
  const riskScore = computeRiskScore(allFindings);
395
+ const degradedReasons = [];
396
+ if (skippedTooLarge > 0) {
397
+ const named = skippedTooLargeFiles.slice(0, 10).join(", ");
398
+ const extra = skippedTooLarge > skippedTooLargeFiles.length || skippedTooLargeFiles.length > 10 ? ` (and others)` : "";
399
+ degradedReasons.push({
400
+ code: "FILE_TOO_LARGE",
401
+ detail: `${skippedTooLarge} file(s) exceeded the per-file size cap and were not scanned: ${named}${extra}`
402
+ });
403
+ }
404
+ if (truncated) {
405
+ degradedReasons.push({
406
+ code: "OUTPUT_TRUNCATED",
407
+ detail: "File count or total size ceiling was reached; collection stopped early \u2014 results are incomplete."
408
+ });
409
+ }
410
+ if (coderefDegraded) {
411
+ degradedReasons.push({
412
+ code: "CODEREF_SKIPPED",
413
+ detail: "One or more pro coderef rules were skipped because they require a newer CLI version."
414
+ });
415
+ }
416
+ const isDegraded = degradedReasons.length > 0 || void 0;
386
417
  const result = {
387
418
  findings: allFindings,
388
419
  riskScore,
389
420
  filesScanned: files.length,
390
421
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
391
422
  policyUsed: policy.project.name,
392
- // Propagate coderef version-skip degradation — scan.ts:145 will OR-merge with
393
- // its own degraded flag so this is not clobbered.
394
- degraded: coderefDegraded || truncated || void 0,
423
+ // Degraded when ANY of: coderef version-skip, collection truncation, OR a
424
+ // file was skipped for being too large. The oversized-skip case (incident
425
+ // f8fdaa6c/18e93b67) means a file was NOT scanned — the scan is incomplete,
426
+ // so it must NOT be reported SAFE. Binary skips (skippedBinary) are NORMAL
427
+ // and intentionally EXCLUDED — a binary file legitimately has no source to
428
+ // scan. scan.ts OR-merges this with its own pro-fetch-failure flag.
429
+ degraded: isDegraded,
430
+ // Machine-readable WHY for each degrade source — safe to key on in agent logic.
431
+ // scan.ts OR-merges its own PRO_RULES_UNAVAILABLE entry after pro-fetch failure.
432
+ degradedReasons: degradedReasons.length > 0 ? degradedReasons : void 0,
395
433
  // Internal metadata for the human-output path — NOT included in --json output
396
434
  _skippedTooLarge: skippedTooLarge,
435
+ _skippedTooLargeFiles: skippedTooLargeFiles,
397
436
  _skippedBinary: skippedBinary,
398
437
  _truncated: truncated
399
438
  };
@@ -402,7 +441,7 @@ async function scan(options, proRules, onProgress) {
402
441
 
403
442
  // src/core/report.ts
404
443
  import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
405
- import { dirname } from "path";
444
+ import { dirname, basename, join as join3 } from "path";
406
445
  function severitySection(title, findings) {
407
446
  if (findings.length === 0) {
408
447
  return `## ${title}
@@ -433,10 +472,41 @@ function buildFixOrder(findings) {
433
472
  ...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
434
473
  ];
435
474
  if (sorted.length === 0) return "No findings to address.\n";
436
- return sorted.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}${f.blocking ? " \u26D4 blocking" : ""}`).join("\n");
475
+ return sorted.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}${f.blocking ? " \u{1F6D1} blocking" : ""}`).join("\n");
476
+ }
477
+ function attitudeLine(recommendation) {
478
+ if (recommendation === "SAFE_TO_SHIP") return "SHIP IT \u2014 nothing blocking. Go make something people want.";
479
+ if (recommendation === "DO_NOT_SHIP") return "BLOCKED \u2014 shipping this would hurt. Fix the criticals first.";
480
+ return `HOLD UP \u2014 findings need eyes before this ships.`;
481
+ }
482
+ function topThreeFindings(findings) {
483
+ const severityOrder = ["critical", "high", "medium", "low", "info"];
484
+ const sorted = [...findings].sort((a, b) => {
485
+ if (a.blocking !== b.blocking) return a.blocking ? -1 : 1;
486
+ return severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity);
487
+ });
488
+ const top = sorted.slice(0, 3);
489
+ if (top.length === 0) return "None \u2014 clean scan.\n";
490
+ return top.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}`).join("\n");
491
+ }
492
+ function severityBreakdownTable(riskScore) {
493
+ const rows = [
494
+ ["Critical", riskScore.criticalCount],
495
+ ["High", riskScore.highCount],
496
+ ["Medium", riskScore.mediumCount],
497
+ ["Low", riskScore.lowCount],
498
+ ["Info", riskScore.infoCount]
499
+ ];
500
+ const lines = ["| Severity | Count |", "|----------|-------|"];
501
+ for (const [label, count] of rows) {
502
+ lines.push(`| ${label} | ${count} |`);
503
+ }
504
+ return lines.join("\n");
437
505
  }
438
- async function generateReport(result, outputPath) {
439
- const { riskScore, findings, filesScanned, timestamp } = result;
506
+ function buildUserMarkdown(result, elapsedMs) {
507
+ const { riskScore, findings, filesScanned, timestamp, recommendation } = result;
508
+ const rec = recommendation ?? riskScore.recommendation;
509
+ const elapsedStr = elapsedMs != null ? elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s` : "N/A";
440
510
  const critical = findings.filter((f) => f.severity === "critical");
441
511
  const high = findings.filter((f) => f.severity === "high");
442
512
  const medium = findings.filter((f) => f.severity === "medium");
@@ -444,12 +514,23 @@ async function generateReport(result, outputPath) {
444
514
  const sections = [
445
515
  "# ShipGuard Release Report",
446
516
  "",
447
- "## Summary",
448
- `- **Status:** ${riskScore.recommendation}`,
449
- `- **Risk Score:** ${riskScore.score}/100`,
450
- `- **Files Scanned:** ${filesScanned}`,
451
- `- **Total Findings:** ${riskScore.totalFindings}`,
452
- `- **Generated:** ${timestamp}`,
517
+ "## SUMMARY",
518
+ "",
519
+ `**Verdict:** ${rec} \u2014 ${attitudeLine(rec)}`,
520
+ "",
521
+ `**Files scanned:** ${filesScanned} | **Elapsed:** ${elapsedStr} | **Generated:** ${timestamp}`,
522
+ "",
523
+ "### Severity Breakdown",
524
+ "",
525
+ severityBreakdownTable(riskScore),
526
+ "",
527
+ `**Risk Score:** ${riskScore.score}/100 | **Total Findings:** ${riskScore.totalFindings}`,
528
+ "",
529
+ "### Top 3 Things to Fix",
530
+ "",
531
+ topThreeFindings(findings),
532
+ "",
533
+ "---",
453
534
  "",
454
535
  severitySection("Critical Findings", critical),
455
536
  severitySection("High Findings", high),
@@ -461,12 +542,30 @@ async function generateReport(result, outputPath) {
461
542
  "",
462
543
  "## Final Recommendation",
463
544
  "",
464
- `**${riskScore.recommendation}**`,
545
+ `**${rec}**`,
465
546
  ""
466
547
  ];
467
- const content = sections.join("\n");
468
- await mkdir2(dirname(outputPath), { recursive: true });
469
- await writeFile2(outputPath, content, "utf-8");
548
+ return sections.join("\n");
549
+ }
550
+ function buildAgentJson(result) {
551
+ const publicResult = { ...result };
552
+ delete publicResult._skippedTooLarge;
553
+ delete publicResult._skippedBinary;
554
+ delete publicResult._truncated;
555
+ return JSON.stringify(publicResult, null, 2);
556
+ }
557
+ async function generateReport(result, outputPath, elapsedMs) {
558
+ const dir = dirname(outputPath);
559
+ const base = basename(outputPath, ".md");
560
+ const jsonPath = join3(dir, `${base}.json`);
561
+ const mdContent = buildUserMarkdown(result, elapsedMs);
562
+ const jsonContent = buildAgentJson(result);
563
+ await mkdir2(dir, { recursive: true });
564
+ await Promise.all([
565
+ writeFile2(outputPath, mdContent, "utf-8"),
566
+ writeFile2(jsonPath, jsonContent, "utf-8")
567
+ ]);
568
+ return { mdPath: outputPath, jsonPath };
470
569
  }
471
570
 
472
571
  // src/core/sarif.ts
@@ -555,11 +654,12 @@ function toSarif(result) {
555
654
  // src/core/render.ts
556
655
  import chalk2 from "chalk";
557
656
  import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
558
- import { join as join3 } from "path";
657
+ import { join as join4, basename as basename2 } from "path";
559
658
  import { homedir } from "os";
560
659
  var DOCS_URL = "https://agenticcli.dev/docs";
561
660
  var SITE_URL = "https://agenticcli.dev";
562
661
  var PRICING_URL = "https://agenticcli.dev/pricing";
662
+ var ISSUES_URL = "https://github.com/ramxH3421/agentic-cli/issues";
563
663
  var SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
564
664
  var BOX_WIDTH = 78;
565
665
  var H = "\u2500";
@@ -571,6 +671,79 @@ var BR = "\u256F";
571
671
  var SECTION = "\u251C" + H.repeat(BOX_WIDTH - 2) + "\u2524";
572
672
  var BAR_FULL = "\u2588";
573
673
  var BAR_EMPTY = "\u2591";
674
+ var SEVERITY_ICONS = {
675
+ critical: "\u{1F6D1}",
676
+ high: "\u26D4",
677
+ medium: "\u26A0\uFE0F",
678
+ low: "\u{1F41B}",
679
+ info: "\u2139\uFE0F"
680
+ };
681
+ function quickstartHelp(isTTY) {
682
+ const lines = [];
683
+ if (isTTY) {
684
+ lines.push("");
685
+ lines.push(chalk2.bold.cyan(" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"));
686
+ lines.push(chalk2.bold.cyan(" \u2502") + chalk2.bold(" \u{1F6E1} ShipGuard \u2014 CLI-first release gate for AI-built apps ") + chalk2.bold.cyan(" \u2502"));
687
+ lines.push(chalk2.bold.cyan(" \u2502") + " Catches secrets, auth gaps, and deployment issues before you ship " + chalk2.bold.cyan(" \u2502"));
688
+ lines.push(chalk2.bold.cyan(" \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"));
689
+ lines.push("");
690
+ lines.push(chalk2.bold(" Get started in 2 commands:"));
691
+ lines.push("");
692
+ lines.push(` ${chalk2.green("npx @agenticcli/shipguard scan")} ${chalk2.dim("# zero install \u2014 scan right now")}`);
693
+ lines.push(` ${chalk2.green("shipguard scan --strict")} ${chalk2.dim("# CI mode: exit 1 on blocking issues")}`);
694
+ lines.push("");
695
+ lines.push(chalk2.bold(" Commands:"));
696
+ lines.push("");
697
+ lines.push(` ${chalk2.cyan("scan")} ${chalk2.dim("[path]")} Scan a project for high-risk issues`);
698
+ lines.push(` ${chalk2.cyan("init")} Generate a .shipguard.yml policy file`);
699
+ lines.push(` ${chalk2.cyan("login")} Authenticate to unlock Pro rules`);
700
+ lines.push(` ${chalk2.cyan("logout")} Remove saved credentials`);
701
+ lines.push(` ${chalk2.cyan("status")} Show auth status and credits`);
702
+ lines.push(` ${chalk2.cyan("feedback")} ${chalk2.dim("<text>")} Send feedback on your last scan`);
703
+ lines.push(` ${chalk2.cyan("rate")} ${chalk2.dim("<id> up|down")} Rate a rule finding`);
704
+ lines.push(` ${chalk2.cyan("help")} ${chalk2.dim("/ ?")} Show this screen`);
705
+ lines.push("");
706
+ lines.push(chalk2.bold(" Exit codes:"));
707
+ lines.push(` ${chalk2.green("0")} Safe \u2014 no blocking findings`);
708
+ lines.push(` ${chalk2.yellow("1")} Blocked \u2014 strict mode + blocking findings`);
709
+ lines.push(` ${chalk2.red("2")} Config error / degraded scan`);
710
+ lines.push(` ${chalk2.red("3")} Runtime error`);
711
+ lines.push("");
712
+ lines.push(` ${chalk2.dim("Docs")} ${chalk2.underline(DOCS_URL)}`);
713
+ lines.push(` ${chalk2.dim("Site")} ${chalk2.underline(SITE_URL)}`);
714
+ lines.push(` ${chalk2.dim("Pricing")} ${chalk2.underline(PRICING_URL)}`);
715
+ lines.push(` ${chalk2.dim("Issues")} ${chalk2.underline(ISSUES_URL)}`);
716
+ lines.push("");
717
+ } else {
718
+ lines.push("");
719
+ lines.push(" ShipGuard \u2014 CLI-first release gate for AI-built apps");
720
+ lines.push(" Catches secrets, auth gaps, and deployment issues before you ship");
721
+ lines.push("");
722
+ lines.push(" Get started in 2 commands:");
723
+ lines.push("");
724
+ lines.push(" npx @agenticcli/shipguard scan # zero install");
725
+ lines.push(" shipguard scan --strict # CI mode");
726
+ lines.push("");
727
+ lines.push(" Commands:");
728
+ lines.push(" scan [path] Scan a project");
729
+ lines.push(" init Generate policy file");
730
+ lines.push(" login Authenticate");
731
+ lines.push(" logout Remove credentials");
732
+ lines.push(" status Auth status + credits");
733
+ lines.push(" feedback <text> Send feedback");
734
+ lines.push(" rate <id> up|down Rate a finding");
735
+ lines.push(" help / ? Show this screen");
736
+ lines.push("");
737
+ lines.push(" Exit codes: 0=safe 1=blocked 2=config-error 3=runtime-error");
738
+ lines.push("");
739
+ lines.push(` Docs: ${DOCS_URL}`);
740
+ lines.push(` Site: ${SITE_URL}`);
741
+ lines.push(` Pricing: ${PRICING_URL}`);
742
+ lines.push(` Issues: ${ISSUES_URL}`);
743
+ lines.push("");
744
+ }
745
+ return lines.join("\n");
746
+ }
574
747
  function findingFpLabel(confidence) {
575
748
  switch (confidence) {
576
749
  case "HIGH":
@@ -589,8 +762,8 @@ function renderProgressBar(current, total, width = 20, currentFile) {
589
762
  const empty = width - filled;
590
763
  const bar = chalk2.cyan(BAR_FULL.repeat(filled)) + chalk2.gray(BAR_EMPTY.repeat(empty));
591
764
  const counter = `${current}/${total}`;
592
- const fileHint = currentFile ? ` ${chalk2.dim(truncatePath(currentFile, 35))}` : "";
593
- return `${chalk2.cyan("\u283F")} scanning [${bar}] ${chalk2.bold(counter)}${fileHint}`;
765
+ const fileHint = currentFile ? ` ${chalk2.dim(basename2(currentFile) || truncatePath(currentFile, 30))}` : "";
766
+ return `${chalk2.cyan("\u{1F50D}")} scanning [${bar}] ${chalk2.bold(counter)}${fileHint}`;
594
767
  }
595
768
  function shouldShowProgress(gates) {
596
769
  return gates.isTTY && !gates.quiet && !gates.machineOutput;
@@ -602,13 +775,6 @@ var SEVERITY_COLORS = {
602
775
  low: chalk2.blue,
603
776
  info: chalk2.gray
604
777
  };
605
- var SEVERITY_ICONS = {
606
- critical: "\u26D4",
607
- high: "\u{1F534}",
608
- medium: "\u{1F7E1}",
609
- low: "\u{1F535}",
610
- info: "\u26AA"
611
- };
612
778
  function renderFindingsSummary(findings) {
613
779
  if (findings.length === 0) {
614
780
  return chalk2.green(" \u2713 No findings detected \u2014 clean scan.");
@@ -624,7 +790,7 @@ function renderFindingsSummary(findings) {
624
790
  const group = findings.filter((f) => f.severity === sev);
625
791
  if (group.length === 0) continue;
626
792
  const colorFn = SEVERITY_COLORS[sev] || chalk2.white;
627
- const icon = SEVERITY_ICONS[sev] || "";
793
+ const icon = SEVERITY_ICONS[sev] ?? "";
628
794
  lines.push(` ${colorFn(` ${sev.toUpperCase().padEnd(8)} `)} ${icon} ${group.length} finding${group.length !== 1 ? "s" : ""}`);
629
795
  for (const f of group) {
630
796
  const location = f.line != null ? `${f.file}:${f.line}` : f.file;
@@ -666,18 +832,22 @@ var VERDICT_CONFIG = {
666
832
  icon: "\u2705",
667
833
  color: chalk2.greenBright,
668
834
  label: "SAFE TO SHIP",
835
+ // Deterministic verdict message — no RNG so tests are stable
836
+ attitudeLine: () => chalk2.green(" SHIP IT \u2014 nothing blocking. Go make something people want."),
669
837
  helpLine: (blockingCount) => blockingCount > 0 ? chalk2.green(` No blocking issues \u2014 ${blockingCount} informational finding(s) noted.`) : chalk2.green(" Clean \u2014 safe to ship. No issues found.")
670
838
  },
671
839
  REVIEW_BEFORE_SHIP: {
672
840
  icon: "\u26A0\uFE0F",
673
841
  color: chalk2.yellowBright,
674
842
  label: "REVIEW BEFORE SHIP",
843
+ attitudeLine: (blockingCount) => chalk2.yellow(` HOLD UP \u2014 ${blockingCount} finding${blockingCount !== 1 ? "s" : ""} want eyes before this ships.`),
675
844
  helpLine: (blockingCount) => chalk2.yellow(` ${blockingCount} finding(s) need attention before shipping.`)
676
845
  },
677
846
  DO_NOT_SHIP: {
678
- icon: "\u26D4",
847
+ icon: "\u{1F6D1}",
679
848
  color: chalk2.redBright,
680
849
  label: "DO NOT SHIP",
850
+ attitudeLine: () => chalk2.red(" BLOCKED \u2014 shipping this would hurt. Fix the criticals first."),
681
851
  helpLine: (blockingCount) => chalk2.red(` Blocked: ${blockingCount} critical/blocking issue(s) must be fixed first.`)
682
852
  }
683
853
  };
@@ -699,7 +869,33 @@ function boxBottom() {
699
869
  function boxSection() {
700
870
  return chalk2.dim(SECTION);
701
871
  }
702
- function verdictPanel(result, elapsedMs, skippedCount) {
872
+ function severityBar(riskScore, barWidth = 30) {
873
+ const total = riskScore.totalFindings;
874
+ if (total === 0) return chalk2.green(" " + BAR_FULL.repeat(barWidth) + " all clear");
875
+ const counts = [
876
+ { sev: "critical", count: riskScore.criticalCount, color: chalk2.bgRed.white },
877
+ { sev: "high", count: riskScore.highCount, color: chalk2.red },
878
+ { sev: "medium", count: riskScore.mediumCount, color: chalk2.yellow },
879
+ { sev: "low", count: riskScore.lowCount, color: chalk2.blue },
880
+ { sev: "info", count: riskScore.infoCount, color: chalk2.gray }
881
+ ].filter((c) => c.count > 0);
882
+ let assigned = 0;
883
+ const segments = [];
884
+ for (let i = 0; i < counts.length; i++) {
885
+ const c = counts[i];
886
+ const w = i === counts.length - 1 ? barWidth - assigned : Math.max(1, Math.round(c.count / total * barWidth));
887
+ segments.push({ color: c.color, width: Math.min(w, barWidth - assigned), sev: c.sev });
888
+ assigned += segments[segments.length - 1].width;
889
+ if (assigned >= barWidth) break;
890
+ }
891
+ const bar = segments.map((s) => s.color(BAR_FULL.repeat(s.width))).join("");
892
+ const legend = counts.map((c) => {
893
+ const icon = SEVERITY_ICONS[c.sev] ?? "";
894
+ return `${icon}${c.count}`;
895
+ }).join(" ");
896
+ return ` ${bar} ${legend}`;
897
+ }
898
+ function verdictPanel(result, elapsedMs, skippedCount, topFindings) {
703
899
  const { riskScore, filesScanned } = result;
704
900
  const recommendation = riskScore.recommendation;
705
901
  const cfg = VERDICT_CONFIG[recommendation];
@@ -711,6 +907,12 @@ function verdictPanel(result, elapsedMs, skippedCount) {
711
907
  const verdictLabel = cfg.color(chalk2.bold(`${cfg.icon} ${cfg.label}`));
712
908
  lines.push(boxLine(` ${verdictLabel}`));
713
909
  lines.push(boxEmpty());
910
+ const attitudeLine2 = recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
911
+ lines.push(boxLine(attitudeLine2));
912
+ lines.push(boxEmpty());
913
+ lines.push(boxSection());
914
+ lines.push(boxLine(chalk2.bold(" Severity breakdown")));
915
+ lines.push(boxLine(severityBar(riskScore)));
714
916
  lines.push(boxSection());
715
917
  lines.push(boxLine(chalk2.bold(" Run summary")));
716
918
  const skippedSuffix = skippedCount && skippedCount > 0 ? chalk2.dim(` (${skippedCount} skipped)`) : "";
@@ -718,13 +920,13 @@ function verdictPanel(result, elapsedMs, skippedCount) {
718
920
  lines.push(boxLine(` Elapsed time: ${chalk2.cyan(elapsedStr)}`));
719
921
  lines.push(boxLine(` Total findings: ${chalk2.cyan(riskScore.totalFindings)}`));
720
922
  const sevLines = [];
721
- if (riskScore.criticalCount > 0) sevLines.push(chalk2.red(`critical: ${riskScore.criticalCount}`));
722
- if (riskScore.highCount > 0) sevLines.push(chalk2.red(`high: ${riskScore.highCount}`));
723
- if (riskScore.mediumCount > 0) sevLines.push(chalk2.yellow(`medium: ${riskScore.mediumCount}`));
724
- if (riskScore.lowCount > 0) sevLines.push(chalk2.blue(`low: ${riskScore.lowCount}`));
725
- if (riskScore.infoCount > 0) sevLines.push(chalk2.gray(`info: ${riskScore.infoCount}`));
923
+ if (riskScore.criticalCount > 0) sevLines.push(chalk2.red(`\u{1F6D1} ${riskScore.criticalCount} critical`));
924
+ if (riskScore.highCount > 0) sevLines.push(chalk2.red(`\u26D4 ${riskScore.highCount} high`));
925
+ if (riskScore.mediumCount > 0) sevLines.push(chalk2.yellow(`\u26A0\uFE0F ${riskScore.mediumCount} medium`));
926
+ if (riskScore.lowCount > 0) sevLines.push(chalk2.blue(`\u{1F41B} ${riskScore.lowCount} low`));
927
+ if (riskScore.infoCount > 0) sevLines.push(chalk2.gray(`\u2139\uFE0F ${riskScore.infoCount} info`));
726
928
  if (sevLines.length > 0) {
727
- lines.push(boxLine(` Severity: ${sevLines.join(" ")}`));
929
+ lines.push(boxLine(` ${sevLines.join(" ")}`));
728
930
  }
729
931
  lines.push(boxSection());
730
932
  lines.push(boxLine(chalk2.bold(" How ShipGuard helped")));
@@ -739,12 +941,35 @@ function verdictPanel(result, elapsedMs, skippedCount) {
739
941
  lines.push("");
740
942
  return lines.join("\n");
741
943
  }
944
+ function actionFooter(opts) {
945
+ const { hasFindings, topRuleId, isLoggedIn } = opts;
946
+ const lines = [""];
947
+ lines.push(chalk2.bold(" \u2500\u2500 What now? \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
948
+ lines.push("");
949
+ lines.push(` ${chalk2.cyan("shipguard report")} ${chalk2.dim("# open the full report")}`);
950
+ if (hasFindings && topRuleId) {
951
+ lines.push(` ${chalk2.cyan(`shipguard rate ${topRuleId} up`)} ${chalk2.dim("# was this finding helpful?")}`);
952
+ lines.push(` ${chalk2.cyan(`shipguard rate ${topRuleId} down`)} ${chalk2.dim("# false positive?")}`);
953
+ } else if (hasFindings) {
954
+ lines.push(` ${chalk2.cyan("shipguard rate <ruleId> up")} ${chalk2.dim("# rate a finding")}`);
955
+ }
956
+ lines.push(` ${chalk2.cyan('shipguard feedback "<thoughts>"')} ${chalk2.dim("# what do you think?")}`);
957
+ if (!isLoggedIn) {
958
+ lines.push("");
959
+ lines.push(` ${chalk2.yellow("shipguard login")} ${chalk2.dim("# unlock Pro rules")}`);
960
+ lines.push(` ${chalk2.yellow("shipguard scan --pro")} ${chalk2.dim("# deeper checks after login")}`);
961
+ }
962
+ lines.push("");
963
+ lines.push(` ${chalk2.dim("Full docs: " + DOCS_URL)}`);
964
+ lines.push("");
965
+ return lines.join("\n");
966
+ }
742
967
  function getShipguardConfigDir() {
743
- return join3(homedir(), ".config", "shipguard");
968
+ return join4(homedir(), ".config", "shipguard");
744
969
  }
745
970
  function welcomeBanner(configDir) {
746
971
  const dir = configDir ?? getShipguardConfigDir();
747
- const marker = join3(dir, ".welcomed");
972
+ const marker = join4(dir, ".welcomed");
748
973
  if (existsSync2(marker)) {
749
974
  return "";
750
975
  }
@@ -776,6 +1001,9 @@ function welcomeBanner(configDir) {
776
1001
  bannerLine(` ${chalk2.green("shipguard scan --json")} Machine-readable output for CI/agents`),
777
1002
  empty,
778
1003
  bannerLine(`Docs: ${chalk2.underline(DOCS_URL)}`),
1004
+ empty,
1005
+ bannerLine(chalk2.dim("Anonymous usage ping enabled \u2014 opt out: SHIPGUARD_TELEMETRY=0")),
1006
+ bannerLine(chalk2.dim(`Details: ${chalk2.underline("agenticcli.dev/docs#telemetry")}`)),
779
1007
  bottom,
780
1008
  ""
781
1009
  ].join("\n");
@@ -857,8 +1085,39 @@ function displayWidth(str) {
857
1085
  return width;
858
1086
  }
859
1087
 
1088
+ // src/core/telemetry.ts
1089
+ function shouldSendTelemetry() {
1090
+ if (process.env.SHIPGUARD_TELEMETRY === "0") return false;
1091
+ if (process.env.DO_NOT_TRACK === "1") return false;
1092
+ return true;
1093
+ }
1094
+ function buildPayload(input) {
1095
+ const { cliVersion, verdict, durationMs, ci, rulePackCount } = input;
1096
+ return { cliVersion, verdict, durationMs, ci, rulePackCount };
1097
+ }
1098
+ function sendTelemetry(payload) {
1099
+ if (!shouldSendTelemetry()) return;
1100
+ const endpoint = process.env.SHIPGUARD_TELEMETRY_URL ?? "https://cheery-toucan-348.convex.site/cli-telemetry";
1101
+ const body = JSON.stringify(buildPayload(payload));
1102
+ const controller = new AbortController();
1103
+ const timeout = setTimeout(() => controller.abort(), 1e3);
1104
+ fetch(endpoint, {
1105
+ method: "POST",
1106
+ headers: { "Content-Type": "application/json" },
1107
+ body,
1108
+ signal: controller.signal
1109
+ }).catch(() => {
1110
+ if (process.env.SHIPGUARD_DEBUG) {
1111
+ console.debug("[shipguard:telemetry] ping failed (silent)");
1112
+ }
1113
+ }).finally(() => {
1114
+ clearTimeout(timeout);
1115
+ });
1116
+ }
1117
+
860
1118
  // src/commands/scan.ts
861
1119
  var LEARN_MORE = "Docs https://agenticcli.dev/docs \xB7 Site https://agenticcli.dev \xB7 Pricing https://agenticcli.dev/pricing \xB7 Issues https://github.com/ramxH3421/agentic-cli/issues";
1120
+ var CLI_VERSION = true ? "0.2.1" : process.env.npm_package_version ?? "0.0.0-dev";
862
1121
  function resolveExitCode(opts) {
863
1122
  if (opts.strict && opts.blockingCount > 0) {
864
1123
  return EXIT_CODES.BLOCKED;
@@ -869,7 +1128,7 @@ function resolveExitCode(opts) {
869
1128
  return EXIT_CODES.SAFE;
870
1129
  }
871
1130
  function isProjectRoot(dir) {
872
- return existsSync3(join4(dir, "package.json")) || existsSync3(join4(dir, ".git"));
1131
+ return existsSync3(join5(dir, "package.json")) || existsSync3(join5(dir, ".git"));
873
1132
  }
874
1133
  function scanCommand() {
875
1134
  return new Command2("scan").description("Scan your project for high-risk issues (verbose by default; use --quiet for one-line verdict)").argument("[path]", "Path to project root to scan (defaults to current directory)").option("--changed", "Only scan changed files from git diff").option("--report", "Generate a detailed Markdown report").option("--strict", "Exit with code 1 if blocking issues found").option("--json", "Output results as JSON (machine-readable; suppresses all decoration)").option("--sarif", "Output results as SARIF 2.1.0 (for GitHub Code Scanning)").option("-q, --quiet", "One-line verdict only (suppresses progress, panel, and tips)").option("--pro", "Include pro quality gate rules (requires authentication)").option("--api-url <url>", "API server URL", "https://agenticcli.dev").option("--category <categories>", "Comma-separated category filter for pro rules").option("--beta", "Include beta-stage rules").option("--all", "Scan any directory, even without package.json or .git").addHelpText("after", `
@@ -958,14 +1217,15 @@ async function runScan(ctx) {
958
1217
  let creditsRemaining;
959
1218
  let rulesVersion;
960
1219
  let degraded = false;
1220
+ let proFetchDegradeReason;
961
1221
  if (opts.pro) {
962
1222
  if (!machineOutput && !quiet) {
963
1223
  logger.info("Detecting stack...");
964
1224
  }
965
1225
  try {
966
1226
  const { detectFrameworks } = await import("./framework-PA6RVE7G.js");
967
- const { fetchProRules } = await import("./pro-scanner-ZBGRHNFD.js");
968
- const { hasConfig, generateConfig } = await import("./config-generator-YSWNA53I.js");
1227
+ const { fetchProRules } = await import("./pro-scanner-ER2RYPI5.js");
1228
+ const { hasConfig, generateConfig } = await import("./config-generator-Q2YTMBZ5.js");
969
1229
  const detectedResult = detectFrameworks(cwd);
970
1230
  const { frameworks } = detectedResult;
971
1231
  if (!hasConfig(cwd)) {
@@ -999,9 +1259,14 @@ async function runScan(ctx) {
999
1259
  logger.info(" + Encrypted | Signed | Memory-only");
1000
1260
  }
1001
1261
  } catch (err) {
1002
- logger.warn(`Pro rules unavailable: ${err instanceof Error ? err.message : String(err)}`);
1262
+ const errMsg = err instanceof Error ? err.message : String(err);
1263
+ logger.warn(`Pro rules unavailable: ${errMsg}`);
1003
1264
  logger.warn("Degrading to free scan \u2014 pro rules will not be applied");
1004
1265
  degraded = true;
1266
+ proFetchDegradeReason = {
1267
+ code: "PRO_RULES_UNAVAILABLE",
1268
+ detail: `Pro rules could not be fetched: ${errMsg}`
1269
+ };
1005
1270
  }
1006
1271
  }
1007
1272
  const showProgress = shouldShowProgress({
@@ -1038,11 +1303,17 @@ async function runScan(ctx) {
1038
1303
  process.stderr.write("\r\x1B[K");
1039
1304
  }
1040
1305
  const skippedTooLarge = result._skippedTooLarge ?? 0;
1306
+ const skippedTooLargeFiles = result._skippedTooLargeFiles ?? [];
1041
1307
  const skippedBinary = result._skippedBinary ?? 0;
1042
1308
  const truncatedByBounds = result._truncated ?? false;
1043
1309
  result.recommendation = result.riskScore.recommendation;
1044
1310
  result.schemaVersion = "2";
1045
1311
  result.degraded = degraded || Boolean(result.degraded);
1312
+ if (result.degraded) {
1313
+ const existingReasons = result.degradedReasons ?? [];
1314
+ const commandReasons = proFetchDegradeReason ? [proFetchDegradeReason] : [];
1315
+ result.degradedReasons = [...existingReasons, ...commandReasons];
1316
+ }
1046
1317
  result.creditsWarning = creditsRemaining !== void 0 && creditsRemaining < 10;
1047
1318
  result.rulesVersion = rulesVersion;
1048
1319
  if (proRules?.length) {
@@ -1056,6 +1327,7 @@ async function runScan(ctx) {
1056
1327
  }
1057
1328
  const publicResult = { ...result };
1058
1329
  delete publicResult._skippedTooLarge;
1330
+ delete publicResult._skippedTooLargeFiles;
1059
1331
  delete publicResult._skippedBinary;
1060
1332
  delete publicResult._truncated;
1061
1333
  if (opts.sarif) {
@@ -1076,11 +1348,19 @@ async function runScan(ctx) {
1076
1348
  console.log(findingsByCategoryTable(result.findings));
1077
1349
  console.log("");
1078
1350
  }
1079
- if (skippedTooLarge > 0 || skippedBinary > 0) {
1080
- logger.info(
1081
- `Files skipped: ${skippedTooLarge + skippedBinary}` + (skippedTooLarge > 0 ? ` (too large: ${skippedTooLarge})` : "") + (skippedBinary > 0 ? ` (binary: ${skippedBinary})` : "")
1351
+ if (skippedTooLarge > 0) {
1352
+ const named = skippedTooLargeFiles.slice(0, 10).join(", ");
1353
+ const more = skippedTooLarge > skippedTooLargeFiles.length || skippedTooLargeFiles.length > 10 ? ` (and others)` : "";
1354
+ logger.warn(
1355
+ `Scan INCOMPLETE: ${skippedTooLarge} file(s) skipped for exceeding the size limit \u2014 NOT scanned: ${named}${more}`
1356
+ );
1357
+ logger.warn(
1358
+ `These files were not checked. Split/minify-exclude them, or raise \`limits.maxFileSizeBytes\` in shipguard.policy.yml. Verdict is degraded (exit 2).`
1082
1359
  );
1083
1360
  }
1361
+ if (skippedBinary > 0) {
1362
+ logger.info(`Files skipped (binary, normal): ${skippedBinary}`);
1363
+ }
1084
1364
  if (creditsRemaining !== void 0) {
1085
1365
  logger.info(`Credits remaining: ${creditsRemaining}`);
1086
1366
  }
@@ -1095,15 +1375,23 @@ async function runScan(ctx) {
1095
1375
  }
1096
1376
  console.log(coverageLine());
1097
1377
  console.log("");
1098
- console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary));
1378
+ console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary, result.findings));
1379
+ const topRuleId = result.findings.length > 0 ? result.findings[0].id : void 0;
1380
+ const isLoggedIn = Boolean(opts.pro && !degraded);
1381
+ console.log(actionFooter({
1382
+ hasFindings: result.findings.length > 0,
1383
+ topRuleId,
1384
+ isLoggedIn
1385
+ }));
1099
1386
  }
1100
1387
  const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
1101
1388
  if (shouldReport) {
1102
1389
  const reportPath = scanOptions.reportPath;
1390
+ const reportElapsedMs = Date.now() - startTime;
1103
1391
  try {
1104
- await generateReport(result, reportPath);
1392
+ const paths = await generateReport(result, reportPath, reportElapsedMs);
1105
1393
  if (!machineOutput && !quiet) {
1106
- logger.success(`Report written to ${reportPath}`);
1394
+ logger.success(`Report: ${paths.mdPath} \xB7 agent view: ${paths.jsonPath}`);
1107
1395
  }
1108
1396
  } catch (error) {
1109
1397
  logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
@@ -1131,6 +1419,28 @@ async function runScan(ctx) {
1131
1419
  }).catch(() => {
1132
1420
  });
1133
1421
  }
1422
+ try {
1423
+ const elapsedMs = Date.now() - startTime;
1424
+ const exitCode2 = resolveExitCode({
1425
+ strict: scanOptions.strict,
1426
+ blockingCount: result.riskScore.blockingCount,
1427
+ degraded: Boolean(result.degraded)
1428
+ });
1429
+ const verdictMap = {
1430
+ [EXIT_CODES.SAFE]: "safe",
1431
+ [EXIT_CODES.BLOCKED]: "blocked",
1432
+ [EXIT_CODES.CONFIG_ERROR]: "review",
1433
+ [EXIT_CODES.RUNTIME_ERROR]: "error"
1434
+ };
1435
+ sendTelemetry({
1436
+ cliVersion: CLI_VERSION,
1437
+ verdict: verdictMap[exitCode2] ?? "error",
1438
+ durationMs: elapsedMs,
1439
+ ci: Boolean(process.env.CI),
1440
+ rulePackCount: proRules ? 1 : 0
1441
+ });
1442
+ } catch {
1443
+ }
1134
1444
  const exitCode = resolveExitCode({
1135
1445
  strict: scanOptions.strict,
1136
1446
  blockingCount: result.riskScore.blockingCount,
@@ -1321,9 +1631,9 @@ function rateCommand() {
1321
1631
  }
1322
1632
 
1323
1633
  // src/handlers.ts
1324
- var ISSUES_URL = "https://github.com/ramxH3421/agentic-cli/issues";
1634
+ var ISSUES_URL2 = "https://github.com/ramxH3421/agentic-cli/issues";
1325
1635
  var DOCS_URL2 = "https://agenticcli.dev/docs";
1326
- var REPORT_LINE = `Report this: ${ISSUES_URL} \xB7 Docs: ${DOCS_URL2}`;
1636
+ var REPORT_LINE = `Report this: ${ISSUES_URL2} \xB7 Docs: ${DOCS_URL2}`;
1327
1637
  function handleUncaughtException(error) {
1328
1638
  const message = error instanceof Error ? error.message : String(error);
1329
1639
  console.error(`\x1B[31m\u2717\x1B[0m Unexpected error: ${message}`);
@@ -1352,22 +1662,110 @@ process.on("uncaughtException", handleUncaughtException);
1352
1662
  process.on("unhandledRejection", handleUnhandledRejection);
1353
1663
  process.on("SIGINT", handleSignal);
1354
1664
  process.on("SIGTERM", handleSignal);
1355
- var ISSUES_URL2 = "https://github.com/ramxH3421/agentic-cli/issues";
1665
+ var ISSUES_URL3 = "https://github.com/ramxH3421/agentic-cli/issues";
1356
1666
  var program = new Command7();
1357
- program.name("shipguard").description("CLI-first release gate for AI-built apps").version("0.1.2").addHelpText("after", `
1667
+ var rawArgs = process.argv.slice(2);
1668
+ if (rawArgs[0] === "?") {
1669
+ process.argv = [process.argv[0], process.argv[1], "help"];
1670
+ }
1671
+ program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
1672
+ true ? "0.2.1" : process.env.npm_package_version ?? "0.0.0-dev"
1673
+ ).helpCommand(false).addHelpText("after", `
1358
1674
  Learn more:
1359
1675
  Docs https://agenticcli.dev/docs
1360
1676
  Site https://agenticcli.dev
1361
1677
  Pricing https://agenticcli.dev/pricing
1362
- Issues ${ISSUES_URL2}`);
1363
- program.addCommand(initCommand());
1364
- program.addCommand(scanCommand());
1365
- program.addCommand(loginCommand());
1366
- program.addCommand(logoutCommand());
1367
- program.addCommand(statusCommand());
1368
- program.addCommand(feedbackCommand());
1369
- program.addCommand(rateCommand());
1370
- program.parseAsync(process.argv);
1678
+ Issues ${ISSUES_URL3}`);
1679
+ program.exitOverride();
1680
+ function addSubcommand(cmd) {
1681
+ cmd.exitOverride();
1682
+ program.addCommand(cmd);
1683
+ }
1684
+ addSubcommand(initCommand());
1685
+ addSubcommand(scanCommand());
1686
+ addSubcommand(loginCommand());
1687
+ addSubcommand(logoutCommand());
1688
+ addSubcommand(statusCommand());
1689
+ addSubcommand(feedbackCommand());
1690
+ addSubcommand(rateCommand());
1691
+ program.addCommand(
1692
+ new Command7("help").description("Show the quickstart guide").action(() => {
1693
+ const isTTY = Boolean(process.stdout.isTTY);
1694
+ process.stdout.write(quickstartHelp(isTTY) + "\n");
1695
+ })
1696
+ );
1697
+ program.allowExcessArguments(true);
1698
+ program.action(() => {
1699
+ const isTTY = Boolean(process.stdout.isTTY);
1700
+ process.stdout.write(quickstartHelp(isTTY) + "\n");
1701
+ });
1702
+ function levenshtein(a, b) {
1703
+ const m = a.length;
1704
+ const n = b.length;
1705
+ const dp = Array.from(
1706
+ { length: m + 1 },
1707
+ (_, i) => Array.from({ length: n + 1 }, (_2, j) => i === 0 ? j : j === 0 ? i : 0)
1708
+ );
1709
+ for (let i = 1; i <= m; i++) {
1710
+ for (let j = 1; j <= n; j++) {
1711
+ dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
1712
+ }
1713
+ }
1714
+ return dp[m][n];
1715
+ }
1716
+ function closestCommand(input) {
1717
+ const names = ["scan", "init", "login", "logout", "status", "feedback", "rate", "help"];
1718
+ let best;
1719
+ let bestDist = Infinity;
1720
+ for (const name of names) {
1721
+ const d = levenshtein(input.toLowerCase(), name);
1722
+ if (d < bestDist) {
1723
+ bestDist = d;
1724
+ best = name;
1725
+ }
1726
+ }
1727
+ return bestDist <= 3 ? best : void 0;
1728
+ }
1729
+ (async () => {
1730
+ const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "feedback", "rate", "help"]);
1731
+ const firstNonFlag = process.argv.slice(2).find((a) => !a.startsWith("-"));
1732
+ if (firstNonFlag && firstNonFlag !== "?" && !KNOWN_COMMANDS.has(firstNonFlag)) {
1733
+ const suggestion = closestCommand(firstNonFlag);
1734
+ const hint = suggestion ? `
1735
+ Did you mean \`shipguard ${suggestion}\`?` : "";
1736
+ process.stderr.write(
1737
+ `shipguard: unknown command "${firstNonFlag}"${hint}
1738
+ Run \`shipguard help\` to see available commands.
1739
+ `
1740
+ );
1741
+ process.exit(2);
1742
+ }
1743
+ try {
1744
+ await program.parseAsync(process.argv);
1745
+ } catch (err) {
1746
+ if (err instanceof CommanderError) {
1747
+ if (err.code === "commander.unknownCommand") {
1748
+ const unknownToken = process.argv.slice(2).find((a) => !a.startsWith("-")) ?? "?";
1749
+ const suggestion = closestCommand(unknownToken);
1750
+ const hint = suggestion ? `
1751
+ Did you mean \`shipguard ${suggestion}\`?` : "";
1752
+ process.stderr.write(
1753
+ `shipguard: unknown command "${unknownToken}"${hint}
1754
+ Run \`shipguard help\` to see available commands.
1755
+ `
1756
+ );
1757
+ process.exit(2);
1758
+ }
1759
+ if (err.exitCode === 0) {
1760
+ process.exit(0);
1761
+ }
1762
+ process.stderr.write(`shipguard: ${err.message}
1763
+ `);
1764
+ process.exit(2);
1765
+ }
1766
+ throw err;
1767
+ }
1768
+ })();
1371
1769
  export {
1372
1770
  handleSignal,
1373
1771
  handleUncaughtException,
@@ -2,7 +2,7 @@ import {
2
2
  DEFAULT_MAX_FILES,
3
3
  DEFAULT_MAX_FILE_SIZE_BYTES,
4
4
  DEFAULT_MAX_TOTAL_BYTES
5
- } from "./chunk-7HMLDAMC.js";
5
+ } from "./chunk-BZWSFLBO.js";
6
6
 
7
7
  // src/core/config-generator.ts
8
8
  import { writeFileSync, existsSync } from "fs";
@@ -2,7 +2,7 @@ import {
2
2
  fetchProRules,
3
3
  runProRules,
4
4
  runProRulesWithDispatch
5
- } from "./chunk-IK7VIKXY.js";
5
+ } from "./chunk-2N3P2DUE.js";
6
6
  export {
7
7
  fetchProRules,
8
8
  runProRules,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agenticcli/shipguard",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "description": "CLI-first release gate for AI-built apps",
5
5
  "type": "module",
6
6
  "main": "./dist/cli.js",