@agenticcli/shipguard 0.8.1 → 0.10.0-rc.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.
package/dist/cli.js CHANGED
@@ -15,7 +15,6 @@ import {
15
15
  isTokenExpired,
16
16
  loadChecksumManifest,
17
17
  loadCredentials,
18
- logger,
19
18
  payments,
20
19
  redactFindingsEvidence,
21
20
  runProRules,
@@ -24,19 +23,40 @@ import {
24
23
  secretsCheck,
25
24
  validateBundleCompile,
26
25
  writeSecureFileSync
27
- } from "./chunk-BGWAAJ5S.js";
26
+ } from "./chunk-6XMYOF3N.js";
28
27
  import {
28
+ DEFAULT_HISTORY_PATH,
29
29
  DEFAULT_MAX_FILES,
30
30
  DEFAULT_MAX_FILE_SIZE_BYTES,
31
31
  DEFAULT_MAX_TOTAL_BYTES,
32
+ DEFAULT_POLICY_PATH,
33
+ DEFAULT_REPORT_DIR,
34
+ DEFAULT_REPORT_FILE,
35
+ DEFAULT_REPO_ID_FALLBACK_PATH,
36
+ DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES,
37
+ EXIT_CODES,
38
+ HISTORY_PATH_ENV_VAR,
39
+ MAX_SKIPPED_NAMES,
40
+ SCAN_ID_REUSE_WINDOW_ENV_VAR,
41
+ SEVERITY_WEIGHTS,
42
+ applyVerdict,
43
+ buildIgnoreRules,
44
+ capReached,
45
+ classifyIgnored,
32
46
  compareScanPaths,
47
+ computeVerdict,
48
+ createReadState,
49
+ effectiveRecommendation,
50
+ generateReport,
51
+ isShipguardArtifactPath,
52
+ readCandidate,
33
53
  readFiles
34
- } from "./chunk-MVYY4QWT.js";
54
+ } from "./chunk-E4Z2MZ5J.js";
35
55
  import {
36
- decodeUtf8Strict,
37
- detectBinary,
38
- normalizeNewlines,
39
- stripBom
56
+ logger
57
+ } from "./chunk-NC5RELTG.js";
58
+ import {
59
+ decodeUtf8Strict
40
60
  } from "./chunk-KGIK7XNK.js";
41
61
 
42
62
  // src/cli.ts
@@ -50,29 +70,6 @@ import { readFile, writeFile, mkdir } from "fs/promises";
50
70
  import { join, resolve as resolve2 } from "path";
51
71
  import YAML from "yaml";
52
72
 
53
- // ../shared/dist/constants.js
54
- var SEVERITY_WEIGHTS = {
55
- info: 1,
56
- low: 5,
57
- medium: 15,
58
- high: 30,
59
- critical: 50
60
- };
61
- var EXIT_CODES = {
62
- SAFE: 0,
63
- BLOCKED: 1,
64
- CONFIG_ERROR: 2,
65
- RUNTIME_ERROR: 3
66
- };
67
- var DEFAULT_POLICY_PATH = "shipguard.policy.yml";
68
- var DEFAULT_REPORT_DIR = ".shipguard/reports";
69
- var DEFAULT_REPORT_FILE = ".shipguard/reports/latest.md";
70
- var DEFAULT_HISTORY_PATH = ".shipguard/history.db";
71
- var HISTORY_PATH_ENV_VAR = "SHIPGUARD_HISTORY_PATH";
72
- var DEFAULT_REPO_ID_FALLBACK_PATH = ".shipguard/repo-id";
73
- var DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES = 30;
74
- var SCAN_ID_REUSE_WINDOW_ENV_VAR = "SHIPGUARD_SCAN_ID_REUSE_WINDOW_MINUTES";
75
-
76
73
  // src/utils/paths.ts
77
74
  import { resolve } from "path";
78
75
  import { existsSync } from "fs";
@@ -187,30 +184,9 @@ import { existsSync as existsSync7, statSync as statSync2 } from "fs";
187
184
  import { join as join7, resolve as resolve4 } from "path";
188
185
 
189
186
  // src/core/scanner.ts
190
- import { readFile as readFile2, stat, realpath } from "fs/promises";
187
+ import { lstat, realpath } from "fs/promises";
191
188
  import { sha256 } from "@noble/hashes/sha2.js";
192
- import { dirname as dirname2, join as join3 } from "path";
193
-
194
- // src/core/verdict.ts
195
- function computeVerdict(input) {
196
- if (input.degraded === true) return "DO_NOT_SHIP";
197
- const score = input.riskScore.score;
198
- if (score <= 20) return "SAFE_TO_SHIP";
199
- if (score < 50) return "REVIEW_BEFORE_SHIP";
200
- return "DO_NOT_SHIP";
201
- }
202
- function applyVerdict(result) {
203
- const verdict = computeVerdict({
204
- riskScore: result.riskScore,
205
- degraded: result.degraded
206
- });
207
- result.recommendation = verdict;
208
- result.riskScore.recommendation = verdict;
209
- return result;
210
- }
211
- function effectiveRecommendation(result) {
212
- return result.recommendation ?? result.riskScore.recommendation;
213
- }
189
+ import { join as join3 } from "path";
214
190
 
215
191
  // src/core/risk-score.ts
216
192
  function computeRiskScore(findings) {
@@ -261,179 +237,15 @@ function computeRiskScore(findings) {
261
237
  };
262
238
  }
263
239
 
264
- // src/core/report.ts
265
- import { mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
266
- import { dirname, basename, join as join2 } from "path";
267
- import { randomUUID } from "crypto";
268
- function severitySection(title, findings) {
269
- if (findings.length === 0) {
270
- return `## ${title}
271
-
272
- None
273
- `;
274
- }
275
- const entries = findings.map((f) => {
276
- const lines = [`### ${f.title}`];
277
- lines.push(`- **File:** ${f.file}${f.line != null ? `:${f.line}` : ""}`);
278
- lines.push(`- **Severity:** ${f.severity}`);
279
- if (f.evidence != null) lines.push(`- **Evidence:** \`${f.evidence}\``);
280
- lines.push(`- **Explanation:** ${f.explanation}`);
281
- lines.push(`- **Recommendation:** ${f.recommendation}`);
282
- return lines.join("\n");
283
- });
284
- return `## ${title}
285
-
286
- ${entries.join("\n\n")}
287
- `;
288
- }
289
- function buildFixOrder(findings) {
290
- const blocking = findings.filter((f) => f.blocking);
291
- const nonBlocking = findings.filter((f) => !f.blocking);
292
- const severityOrder = ["critical", "high", "medium", "low", "info"];
293
- const sorted = [
294
- ...blocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity)),
295
- ...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
296
- ];
297
- if (sorted.length === 0) return "No findings to address.\n";
298
- 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");
299
- }
300
- function attitudeLine(recommendation, degraded) {
301
- if (degraded) return "INCOMPLETE \u2014 parts of this scan did not run, so it cannot say this is safe.";
302
- if (recommendation === "SAFE_TO_SHIP") return "SHIP IT \u2014 nothing blocking. Go make something people want.";
303
- if (recommendation === "DO_NOT_SHIP") return "BLOCKED \u2014 shipping this would hurt. Fix the criticals first.";
304
- return `HOLD UP \u2014 findings need eyes before this ships.`;
305
- }
306
- function topThreeFindings(findings) {
307
- const severityOrder = ["critical", "high", "medium", "low", "info"];
308
- const sorted = [...findings].sort((a, b) => {
309
- if (a.blocking !== b.blocking) return a.blocking ? -1 : 1;
310
- return severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity);
311
- });
312
- const top = sorted.slice(0, 3);
313
- if (top.length === 0) return "None \u2014 clean scan.\n";
314
- return top.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}`).join("\n");
315
- }
316
- function severityBreakdownTable(riskScore) {
317
- const rows = [
318
- ["Critical", riskScore.criticalCount],
319
- ["High", riskScore.highCount],
320
- ["Medium", riskScore.mediumCount],
321
- ["Low", riskScore.lowCount],
322
- ["Info", riskScore.infoCount]
323
- ];
324
- const lines = ["| Severity | Count |", "|----------|-------|"];
325
- for (const [label, count] of rows) {
326
- lines.push(`| ${label} | ${count} |`);
327
- }
328
- return lines.join("\n");
329
- }
330
- function buildUserMarkdown(result, elapsedMs) {
331
- const { riskScore, findings, filesScanned, timestamp } = result;
332
- const rec = effectiveRecommendation(result);
333
- const degraded = result.degraded === true;
334
- const elapsedStr = elapsedMs != null ? elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s` : "N/A";
335
- const critical = findings.filter((f) => f.severity === "critical");
336
- const high = findings.filter((f) => f.severity === "high");
337
- const medium = findings.filter((f) => f.severity === "medium");
338
- const low = findings.filter((f) => f.severity === "low");
339
- const sections = [
340
- "# ShipGuard Release Report",
341
- "",
342
- "## SUMMARY",
343
- "",
344
- `**Verdict:** ${rec} \u2014 ${attitudeLine(rec, degraded)}`,
345
- "",
346
- `**Files scanned:** ${filesScanned} | **Elapsed:** ${elapsedStr} | **Generated:** ${timestamp}`,
347
- "",
348
- ...degraded ? [
349
- "### Why this scan is incomplete",
350
- "",
351
- ...(result.degradedReasons ?? []).length > 0 ? (result.degradedReasons ?? []).map((r) => `- \`${r.code}\`${r.detail ? ` \u2014 ${r.detail}` : ""}`) : ["- Reason not recorded \u2014 see `degraded` in the JSON report."],
352
- ""
353
- ] : [],
354
- "### Severity Breakdown",
355
- "",
356
- severityBreakdownTable(riskScore),
357
- "",
358
- `**Risk Score:** ${riskScore.score}/100 | **Total Findings:** ${riskScore.totalFindings}`,
359
- "",
360
- "### Top 3 Things to Fix",
361
- "",
362
- topThreeFindings(findings),
363
- "",
364
- "---",
365
- "",
366
- severitySection("Critical Findings", critical),
367
- severitySection("High Findings", high),
368
- severitySection("Medium Findings", medium),
369
- severitySection("Low Findings", low),
370
- "## Suggested Fix Order",
371
- "",
372
- buildFixOrder(findings),
373
- "",
374
- "## Final Recommendation",
375
- "",
376
- `**${rec}**`,
377
- ""
378
- ];
379
- return sections.join("\n");
380
- }
381
- function buildAgentJson(result) {
382
- const publicResult = { ...result };
383
- delete publicResult._skippedTooLarge;
384
- delete publicResult._skippedBinary;
385
- delete publicResult._truncated;
386
- return JSON.stringify(publicResult, null, 2);
387
- }
388
- var RUNS_SUBDIR = "runs";
389
- async function writeAtomic(path, content) {
390
- const tmp = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
391
- await writeFile2(tmp, content, "utf-8");
392
- await rename(tmp, path);
393
- }
394
- async function generateReport(result, outputPath, elapsedMs) {
395
- const dir = dirname(outputPath);
396
- const base = basename(outputPath, ".md");
397
- const jsonPath = join2(dir, `${base}.json`);
398
- const runId = sanitizeRunId(result.runId) ?? `run-${Date.now()}`;
399
- const runMdName = join2(RUNS_SUBDIR, `${runId}.md`);
400
- const runJsonName = join2(RUNS_SUBDIR, `${runId}.json`);
401
- const runMdPath = join2(dir, runMdName);
402
- const runJsonPath = join2(dir, runJsonName);
403
- const mdContent = buildUserMarkdown(result, elapsedMs);
404
- const jsonContent = buildAgentJson(result);
405
- const pointer = {
406
- pointer: true,
407
- pointerVersion: 1,
408
- runId,
409
- timestamp: result.timestamp,
410
- recommendation: effectiveRecommendation(result),
411
- runJson: runJsonName,
412
- runMarkdown: runMdName
413
- };
414
- await mkdir2(dir, { recursive: true });
415
- await mkdir2(join2(dir, RUNS_SUBDIR), { recursive: true });
416
- await Promise.all([
417
- writeAtomic(runMdPath, mdContent),
418
- writeAtomic(runJsonPath, jsonContent)
419
- ]);
420
- await Promise.all([
421
- writeAtomic(outputPath, mdContent),
422
- writeAtomic(jsonPath, JSON.stringify(pointer, null, 2) + "\n")
423
- ]);
424
- return { mdPath: outputPath, jsonPath, runMdPath, runJsonPath };
425
- }
426
- function sanitizeRunId(runId) {
427
- if (!runId) return void 0;
428
- const safe = runId.replace(/[^A-Za-z0-9._-]/g, "");
429
- return safe.length > 0 && safe !== "." && safe !== ".." ? safe.slice(0, 96) : void 0;
430
- }
431
-
432
240
  // src/core/git.ts
433
241
  import { execFileSync } from "child_process";
242
+ import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from "fs";
243
+ import { tmpdir } from "os";
244
+ import { join as join2 } from "path";
245
+ var GIT_ENV = { ...process.env, LC_ALL: "C", LANGUAGE: "C" };
434
246
  function isGitRepo(dir) {
435
247
  try {
436
- execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: dir, stdio: "pipe" });
248
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: dir, stdio: "pipe", env: GIT_ENV });
437
249
  return true;
438
250
  } catch {
439
251
  return false;
@@ -449,38 +261,100 @@ var GitCommandError = class extends Error {
449
261
  command;
450
262
  stderr;
451
263
  };
452
- function runGit(dir, args) {
264
+ function runGit(dir, args, warnings) {
453
265
  const command = `git ${args.join(" ")}`;
266
+ let errDir;
267
+ let errFd;
268
+ if (warnings) {
269
+ try {
270
+ errDir = mkdtempSync(join2(tmpdir(), "sg-git-err-"));
271
+ errFd = openSync(join2(errDir, "stderr"), "w");
272
+ } catch (err) {
273
+ throw new GitCommandError(command, `cannot capture git warnings: ${err instanceof Error ? err.message : String(err)}`);
274
+ }
275
+ }
454
276
  try {
455
- return execFileSync("git", args, {
277
+ const out = execFileSync("git", args, {
456
278
  cwd: dir,
457
- encoding: "utf-8",
458
- stdio: ["pipe", "pipe", "pipe"]
279
+ stdio: ["pipe", "pipe", errFd ?? "pipe"],
280
+ env: GIT_ENV
459
281
  });
282
+ if (warnings && errDir) {
283
+ closeSync(errFd);
284
+ errFd = void 0;
285
+ const text = readFileSync(join2(errDir, "stderr"), "utf8");
286
+ for (const line of text.split("\n")) if (line.trim()) warnings.push(line.trim());
287
+ }
288
+ return out;
460
289
  } catch (err) {
461
- const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : err instanceof Error ? err.message : String(err);
290
+ let stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : err instanceof Error ? err.message : String(err);
291
+ if (!stderr && errDir) {
292
+ try {
293
+ stderr = readFileSync(join2(errDir, "stderr"), "utf8");
294
+ } catch (readErr) {
295
+ stderr = `git stderr unreadable: ${readErr instanceof Error ? readErr.message : String(readErr)}`;
296
+ }
297
+ }
462
298
  throw new GitCommandError(command, stderr);
299
+ } finally {
300
+ if (errFd !== void 0) {
301
+ try {
302
+ closeSync(errFd);
303
+ } catch (e) {
304
+ void e;
305
+ }
306
+ }
307
+ if (errDir) rmSync(errDir, { recursive: true, force: true });
463
308
  }
464
309
  }
465
- function getChangedFiles(dir) {
310
+ function splitNul(out) {
311
+ const entries = [];
312
+ let start = 0;
313
+ for (let i = 0; i < out.length; i++) {
314
+ if (out[i] === 0) {
315
+ if (i > start) entries.push(out.subarray(start, i));
316
+ start = i + 1;
317
+ }
318
+ }
319
+ if (start < out.length) entries.push(out.subarray(start));
320
+ return entries;
321
+ }
322
+ function getChangedFilesDetailed(dir) {
466
323
  let diffOutput;
467
324
  try {
468
- diffOutput = runGit(dir, ["diff", "--name-only", "HEAD"]);
325
+ diffOutput = runGit(dir, ["-c", "diff.relative=false", "diff", "--name-only", "-z", "HEAD"]);
469
326
  } catch (err) {
470
327
  if (err instanceof GitCommandError && /unknown revision|ambiguous argument|bad revision/i.test(err.stderr)) {
471
- diffOutput = "";
328
+ diffOutput = Buffer.alloc(0);
472
329
  } else {
473
330
  throw err;
474
331
  }
475
332
  }
476
- const stagedOutput = runGit(dir, ["diff", "--cached", "--name-only"]);
477
- const untrackedOutput = runGit(dir, ["ls-files", "--others", "--exclude-standard"]);
478
- const allFiles = /* @__PURE__ */ new Set();
479
- const outputs = [diffOutput, stagedOutput, untrackedOutput];
480
- for (const output of outputs) {
481
- output.split("\n").map((f) => f.trim()).filter(Boolean).forEach((f) => allFiles.add(f));
333
+ const stagedOutput = runGit(dir, ["-c", "diff.relative=false", "diff", "--cached", "--name-only", "-z"]);
334
+ const gitWarnings = [];
335
+ const untrackedOutput = runGit(dir, ["ls-files", "--others", "--exclude-standard", "--full-name", "-z"], gitWarnings);
336
+ const unreadable = gitWarnings.map((w) => w.match(/'([^']+)'/)?.[1] ?? w);
337
+ const prefix = Buffer.from(runGit(dir, ["rev-parse", "--show-prefix"]).toString("latin1").replace(/\r?\n$/, ""), "latin1");
338
+ const seen = /* @__PURE__ */ new Set();
339
+ const paths = [];
340
+ const unaddressable = [];
341
+ let outsideScope = 0;
342
+ for (const output of [diffOutput, stagedOutput, untrackedOutput]) {
343
+ for (const raw2 of splitNul(output)) {
344
+ const key = raw2.toString("latin1");
345
+ if (seen.has(key)) continue;
346
+ seen.add(key);
347
+ if (prefix.length > 0 && !(raw2.length > prefix.length && raw2.subarray(0, prefix.length).equals(prefix))) {
348
+ outsideScope++;
349
+ continue;
350
+ }
351
+ const rel = raw2.subarray(prefix.length);
352
+ const decoded = decodeUtf8Strict(rel);
353
+ if (decoded.ok) paths.push(decoded.text);
354
+ else unaddressable.push(rel.toString("utf8"));
355
+ }
482
356
  }
483
- return [...allFiles];
357
+ return { paths, unaddressable, outsideScope, unreadable };
484
358
  }
485
359
 
486
360
  // rules/free-bundle.json
@@ -2132,36 +2006,6 @@ function collapseSameIssueFindings(findings) {
2132
2006
 
2133
2007
  // src/core/scanner.ts
2134
2008
  var CHECK_MODULES = [secretsCheck, authCheck, databaseCheck, payments, deploymentCheck];
2135
- var DEFAULT_IGNORE = [
2136
- "node_modules/**",
2137
- "dist/**",
2138
- "build/**",
2139
- ".next/**",
2140
- "coverage/**",
2141
- ".git/**",
2142
- // ShipGuard's own report output — never scan the tool's own artifacts
2143
- ".shipguard/**"
2144
- ];
2145
- function selfArtifactIgnorePatterns(policy) {
2146
- const patterns = [];
2147
- const add = (p) => {
2148
- if (!p) return;
2149
- if (p.startsWith("/")) return;
2150
- const rel = p.replace(/^\.\//, "");
2151
- if (!rel) return;
2152
- patterns.push(rel);
2153
- };
2154
- const reportOutput = policy.report?.output;
2155
- add(reportOutput);
2156
- if (reportOutput) {
2157
- add(reportOutput.replace(/\.md$/, ".json"));
2158
- const reportDir = dirname2(reportOutput);
2159
- add(join3(reportDir === "." ? "" : reportDir, RUNS_SUBDIR, "**"));
2160
- }
2161
- add(policy.history?.path);
2162
- add(process.env[HISTORY_PATH_ENV_VAR]);
2163
- return patterns;
2164
- }
2165
2009
  function computeTreeDigest(files) {
2166
2010
  if (files.length === 0) return void 0;
2167
2011
  const encoder = new TextEncoder();
@@ -2172,125 +2016,173 @@ function computeTreeDigest(files) {
2172
2016
  function toHex(bytes) {
2173
2017
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2174
2018
  }
2019
+ function dedupeAcrossReadings(findings, files) {
2020
+ const counts = /* @__PURE__ */ new Map();
2021
+ for (const f of files) counts.set(f.relativePath, (counts.get(f.relativePath) ?? 0) + 1);
2022
+ const multi = new Set([...counts].filter(([, n]) => n > 1).map(([p]) => p));
2023
+ if (multi.size === 0) return findings;
2024
+ const seen = /* @__PURE__ */ new Set();
2025
+ return findings.filter((f) => {
2026
+ if (!f.file || !multi.has(f.file)) return true;
2027
+ const key = `${f.id}\0${f.file}\0${f.line ?? ""}\0${f.line === void 0 ? `${f.title}\0${f.evidence ?? ""}` : ""}`;
2028
+ if (seen.has(key)) return false;
2029
+ seen.add(key);
2030
+ return true;
2031
+ });
2032
+ }
2033
+ var sortedCapped = (names) => [...names].sort(compareScanPaths).slice(0, MAX_SKIPPED_NAMES);
2034
+ function buildCoverage(state, mode, changed) {
2035
+ return {
2036
+ discovered: state.discovered,
2037
+ scanned: state.acceptedPaths,
2038
+ skipped: {
2039
+ binary: state.skippedBinary,
2040
+ tooLarge: state.skippedTooLarge,
2041
+ symlink: state.skippedSymlinks,
2042
+ unknownBinary: state.skippedUnknownBinary,
2043
+ invalidUtf8: state.invalidUtf8Files.length,
2044
+ unreadable: state.unreadableFiles.length,
2045
+ special: state.skippedSpecial,
2046
+ binaryHeadOnly: state.skippedBinaryHeadOnly
2047
+ },
2048
+ decoded: {
2049
+ utf16: state.utf16Decoded,
2050
+ nulSubstituted: state.nulSubstituted,
2051
+ multiReading: state.multiReading,
2052
+ asciiStrings: state.asciiStrings,
2053
+ binaryStringsScanned: state.binaryStringsScanned
2054
+ },
2055
+ truncated: state.truncated && state.truncatedBy ? { by: state.truncatedBy, notReached: state.notReached } : false,
2056
+ ignoredByDefault: state.ignoredByDefault,
2057
+ ignoredByUser: state.ignoredByUser,
2058
+ selfArtifacts: state.selfArtifacts,
2059
+ mode,
2060
+ ...changed ? { changed } : {},
2061
+ files: {
2062
+ binary: sortedCapped(state.skippedBinaryFiles),
2063
+ tooLarge: sortedCapped(state.skippedTooLargeFiles),
2064
+ symlink: sortedCapped(state.skippedSymlinkFiles),
2065
+ unknownBinary: sortedCapped(state.skippedUnknownBinaryFiles),
2066
+ special: sortedCapped(state.skippedSpecialFiles),
2067
+ nulSubstituted: sortedCapped(state.nulSubstitutedFiles),
2068
+ selfArtifacts: sortedCapped(state.selfArtifactFiles)
2069
+ }
2070
+ };
2071
+ }
2175
2072
  async function scan(options, proRules, onProgress) {
2176
2073
  const cwd = process.cwd();
2177
2074
  const policy = await loadPolicy(cwd);
2178
- const ignorePatterns = [
2179
- ...DEFAULT_IGNORE,
2180
- // Rec #6 — ShipGuard's own artifacts, wherever the policy put them.
2181
- ...selfArtifactIgnorePatterns(policy),
2182
- ...policy.ignore.paths
2183
- ];
2075
+ const ignoreRules = buildIgnoreRules(policy);
2184
2076
  const limits = {
2185
2077
  maxFileSizeBytes: policy.limits?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES,
2186
2078
  maxTotalBytes: policy.limits?.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
2187
2079
  maxFiles: policy.limits?.maxFiles ?? DEFAULT_MAX_FILES
2188
2080
  };
2189
- let files;
2190
- let skippedTooLarge = 0;
2191
- const skippedTooLargeFiles = [];
2192
- let skippedBinary = 0;
2193
- const skippedBinaryFiles = [];
2194
- let skippedSymlinks = 0;
2195
- const skippedSymlinkFiles = [];
2196
- let truncated = false;
2197
- const changedInvalidUtf8 = [];
2198
- const changedUnreadable = [];
2081
+ let state;
2082
+ let mode = "full";
2083
+ let changedInfo;
2199
2084
  if (options.changedOnly && isGitRepo(cwd)) {
2200
- const changedRelPaths = getChangedFiles(cwd);
2201
- if (changedRelPaths.length === 0) {
2202
- logger.info("--changed: git ran successfully \u2014 0 changed files to scan.");
2203
- }
2204
- const changedIgnore = [...DEFAULT_IGNORE, ...selfArtifactIgnorePatterns(policy)];
2205
- const filteredPaths = changedRelPaths.filter(
2206
- (rp) => !changedIgnore.some((pat) => {
2207
- const prefix = pat.replace("/**", "");
2208
- return rp.startsWith(prefix + "/") || rp === prefix;
2209
- })
2210
- ).sort(compareScanPaths);
2211
- files = [];
2212
- let totalBytes = 0;
2213
- const changedTotal = filteredPaths.length;
2214
- let changedProcessed = 0;
2215
- for (const relPath of filteredPaths) {
2216
- if (files.length >= limits.maxFiles || totalBytes >= limits.maxTotalBytes) {
2217
- truncated = true;
2085
+ mode = "changed";
2086
+ state = createReadState();
2087
+ const changed = getChangedFilesDetailed(cwd);
2088
+ const listed = changed.paths.length + changed.unaddressable.length + changed.outsideScope;
2089
+ changedInfo = { listed, outsideScope: changed.outsideScope };
2090
+ const defaultCounts = /* @__PURE__ */ new Map();
2091
+ const candidates = [];
2092
+ for (const rp of changed.paths) {
2093
+ const rule = classifyIgnored(rp, ignoreRules);
2094
+ if (!rule && isShipguardArtifactPath(rp)) {
2095
+ state.selfArtifacts++;
2096
+ if (state.selfArtifactFiles.length < MAX_SKIPPED_NAMES) state.selfArtifactFiles.push(rp);
2097
+ } else if (!rule) candidates.push(rp);
2098
+ else if (rule.by === "user") state.ignoredByUser++;
2099
+ else defaultCounts.set(rule.pattern, (defaultCounts.get(rule.pattern) ?? 0) + 1);
2100
+ }
2101
+ state.ignoredByDefault = [...defaultCounts].map(([pattern, files2]) => ({ pattern, files: files2 }));
2102
+ candidates.sort(compareScanPaths);
2103
+ for (const display of changed.unaddressable) {
2104
+ logger.warn(`[shipguard] Changed file name is not valid UTF-8 and cannot be addressed safely: ${display}`);
2105
+ state.unreadableFiles.push(display);
2106
+ state.unaddressableCount++;
2107
+ }
2108
+ for (const display of changed.unreadable ?? []) {
2109
+ logger.warn(`[shipguard] git could not read ${display}; files under it are NOT scanned`);
2110
+ state.unreadableFiles.push(display);
2111
+ }
2112
+ state.discovered = candidates.length + changed.unaddressable.length + (changed.unreadable ?? []).length;
2113
+ if (listed === 0) {
2114
+ logger.info("--changed: git ran successfully - 0 changed files to scan.");
2115
+ }
2116
+ if (candidates.length === 0 && !options.json) {
2117
+ logger.warn(
2118
+ "`--changed` scans only files that differ from git; on a clean checkout it scans nothing. Run `shipguard scan` for the whole tree."
2119
+ );
2120
+ }
2121
+ const canonicalCwd = await realpath(cwd).catch(() => cwd);
2122
+ const cwdWithSep = canonicalCwd.endsWith("/") ? canonicalCwd : canonicalCwd + "/";
2123
+ let processed = 0;
2124
+ for (let i = 0; i < candidates.length; i++) {
2125
+ const hit = capReached(state, limits);
2126
+ if (hit) {
2127
+ state.truncated = true;
2128
+ state.truncatedBy = hit;
2129
+ state.notReached = candidates.length - i;
2218
2130
  break;
2219
2131
  }
2132
+ const relPath = candidates[i];
2220
2133
  const fullPath = join3(cwd, relPath);
2134
+ let isLink = false;
2221
2135
  try {
2222
- let resolvedPath;
2223
- try {
2224
- resolvedPath = await realpath(fullPath);
2225
- } catch (realpathErr) {
2226
- const detail = realpathErr instanceof Error ? realpathErr.message : String(realpathErr);
2227
- logger.warn(`[shipguard] Could not resolve path for changed file ${relPath}: ${detail}`);
2228
- changedUnreadable.push(relPath);
2229
- onProgress?.(++changedProcessed, changedTotal, relPath);
2230
- continue;
2231
- }
2232
- const canonicalCwd = await realpath(cwd).catch(() => cwd);
2233
- const cwdWithSep = canonicalCwd.endsWith("/") ? canonicalCwd : canonicalCwd + "/";
2136
+ isLink = (await lstat(fullPath)).isSymbolicLink();
2137
+ } catch {
2138
+ isLink = false;
2139
+ }
2140
+ if (isLink) {
2141
+ state.skippedSymlinks++;
2142
+ if (state.skippedSymlinkFiles.length < MAX_SKIPPED_NAMES) state.skippedSymlinkFiles.push(relPath);
2143
+ onProgress?.(++processed, candidates.length, relPath);
2144
+ continue;
2145
+ }
2146
+ let resolvedPath;
2147
+ try {
2148
+ resolvedPath = await realpath(fullPath);
2149
+ } catch (realpathErr) {
2150
+ const detail = realpathErr instanceof Error ? realpathErr.message : String(realpathErr);
2151
+ logger.warn(`[shipguard] Could not resolve path for changed file ${relPath}: ${detail}`);
2152
+ state.unreadableFiles.push(relPath);
2153
+ }
2154
+ if (resolvedPath !== void 0) {
2234
2155
  if (!resolvedPath.startsWith(cwdWithSep) && resolvedPath !== canonicalCwd) {
2235
2156
  logger.warn(
2236
2157
  `[shipguard] Refusing out-of-root path for changed file ${relPath}: resolved to ${resolvedPath} which is outside ${canonicalCwd}`
2237
2158
  );
2238
- changedUnreadable.push(relPath);
2239
- onProgress?.(++changedProcessed, changedTotal, relPath);
2240
- continue;
2241
- }
2242
- const fileStat = await stat(resolvedPath);
2243
- if (fileStat.size > limits.maxFileSizeBytes) {
2244
- skippedTooLarge++;
2245
- if (skippedTooLargeFiles.length < 50) {
2246
- skippedTooLargeFiles.push(relPath);
2247
- }
2248
- onProgress?.(++changedProcessed, changedTotal, relPath);
2249
- continue;
2250
- }
2251
- const buffer = await readFile2(resolvedPath);
2252
- if (detectBinary(new Uint8Array(buffer))) {
2253
- skippedBinary++;
2254
- onProgress?.(++changedProcessed, changedTotal, relPath);
2255
- continue;
2256
- }
2257
- const decoded = decodeUtf8Strict(new Uint8Array(buffer));
2258
- if (!decoded.ok) {
2259
- changedInvalidUtf8.push({ relativePath: relPath, reason: decoded.reason });
2260
- onProgress?.(++changedProcessed, changedTotal, relPath);
2261
- continue;
2159
+ state.unreadableFiles.push(relPath);
2160
+ } else {
2161
+ await readCandidate(state, { readPath: resolvedPath, path: fullPath, rel: relPath }, limits.maxFileSizeBytes);
2262
2162
  }
2263
- const content = normalizeNewlines(stripBom(decoded.text));
2264
- totalBytes += buffer.length;
2265
- files.push({ path: fullPath, content, relativePath: relPath });
2266
- } catch (err) {
2267
- const detail = err instanceof Error ? err.message : String(err);
2268
- logger.warn(`[shipguard] Could not read changed file ${relPath}: ${detail}`);
2269
- changedUnreadable.push(relPath);
2270
2163
  }
2271
- onProgress?.(++changedProcessed, changedTotal, relPath);
2164
+ onProgress?.(++processed, candidates.length, relPath);
2272
2165
  }
2273
2166
  } else {
2274
2167
  if (options.changedOnly && !isGitRepo(cwd)) {
2275
- logger.warn("--changed flag set but not a git repository \u2014 scanning all files");
2168
+ logger.warn("--changed flag set but not a git repository - scanning all files");
2276
2169
  }
2277
- const readResult = await readFiles(cwd, ["**/*"], ignorePatterns, {
2170
+ state = await readFiles(cwd, ["**/*"], [], {
2278
2171
  maxFileSizeBytes: limits.maxFileSizeBytes,
2279
2172
  maxTotalBytes: limits.maxTotalBytes,
2280
2173
  maxFiles: limits.maxFiles,
2281
- onProgress
2174
+ onProgress,
2175
+ ignoreRules
2282
2176
  });
2283
- files = readResult.files;
2284
- skippedTooLarge = readResult.skippedTooLarge;
2285
- skippedTooLargeFiles.push(...readResult.skippedTooLargeFiles);
2286
- skippedBinary = readResult.skippedBinary;
2287
- skippedBinaryFiles.push(...readResult.skippedBinaryFiles);
2288
- skippedSymlinks = readResult.skippedSymlinks;
2289
- skippedSymlinkFiles.push(...readResult.skippedSymlinkFiles);
2290
- truncated = readResult.truncated;
2291
- changedInvalidUtf8.push(...readResult.invalidUtf8Files);
2292
- changedUnreadable.push(...readResult.unreadableFiles);
2293
2177
  }
2178
+ const files = state.files;
2179
+ const skippedTooLarge = state.skippedTooLarge;
2180
+ const skippedTooLargeFiles = state.skippedTooLargeFiles;
2181
+ const skippedSymlinks = state.skippedSymlinks;
2182
+ const skippedSymlinkFiles = state.skippedSymlinkFiles;
2183
+ const truncated = state.truncated;
2184
+ const changedInvalidUtf8 = state.invalidUtf8Files;
2185
+ const changedUnreadable = state.unreadableFiles;
2294
2186
  const sourceRedacted = /* @__PURE__ */ new Set();
2295
2187
  const legacyFindings = applySuppressions(
2296
2188
  CHECK_MODULES.flatMap((mod) => {
@@ -2336,6 +2228,7 @@ async function scan(options, proRules, onProgress) {
2336
2228
  logger.warn(w);
2337
2229
  }
2338
2230
  }
2231
+ allFindings = dedupeAcrossReadings(allFindings, files);
2339
2232
  const collapsed = collapseSameIssueFindings(allFindings);
2340
2233
  for (const n of collapsed.notes) {
2341
2234
  logger.debug(
@@ -2355,10 +2248,11 @@ async function scan(options, proRules, onProgress) {
2355
2248
  detail: `${skippedTooLarge} file(s) exceeded the per-file size cap and were not scanned: ${named}${extra}`
2356
2249
  });
2357
2250
  }
2358
- if (truncated) {
2251
+ if (truncated && state.truncatedBy) {
2252
+ const capName = state.truncatedBy === "maxFiles" ? `limits.maxFiles (${limits.maxFiles})` : `limits.maxTotalBytes (${limits.maxTotalBytes})`;
2359
2253
  degradedReasons.push({
2360
2254
  code: "OUTPUT_TRUNCATED",
2361
- detail: "File count or total size ceiling was reached; collection stopped early \u2014 results are incomplete."
2255
+ detail: `Collection stopped at ${capName}: ${state.notReached} file(s) were never reached. Results are incomplete. Raise the limit in shipguard.policy.yml or narrow the scan with ignore.paths.`
2362
2256
  });
2363
2257
  }
2364
2258
  if (skippedSymlinks > 0) {
@@ -2380,44 +2274,62 @@ async function scan(options, proRules, onProgress) {
2380
2274
  const extra = changedInvalidUtf8.length > 10 ? ` (and ${changedInvalidUtf8.length - 10} more)` : "";
2381
2275
  degradedReasons.push({
2382
2276
  code: "INVALID_UTF8",
2383
- detail: `${changedInvalidUtf8.length} file(s) contained invalid UTF-8 and were not scanned: ${named}${extra}`
2277
+ detail: `${changedInvalidUtf8.length} file(s) contained invalid UTF-8 (or UTF-16 with a BOM that does not decode) and were not scanned: ${named}${extra}`
2384
2278
  });
2385
2279
  }
2386
2280
  if (changedUnreadable.length > 0) {
2387
2281
  const named = changedUnreadable.slice(0, 10).join(", ");
2388
2282
  const extra = changedUnreadable.length > 10 ? ` (and ${changedUnreadable.length - 10} more)` : "";
2283
+ const badNames = state.unaddressableCount > 0 ? ` ${state.unaddressableCount} of them have a file name that is not valid UTF-8, cannot be addressed safely and were never read.` : "";
2389
2284
  degradedReasons.push({
2390
2285
  code: "UNREADABLE_FILE",
2391
- detail: `${changedUnreadable.length} file(s) could not be read and were not scanned: ${named}${extra}`
2286
+ detail: `${changedUnreadable.length} file(s) could not be read and were not scanned: ${named}${extra}.${badNames}`
2287
+ });
2288
+ }
2289
+ if (state.skippedUnknownBinary > 0) {
2290
+ const named = state.skippedUnknownBinaryFiles.slice(0, 10).join(", ");
2291
+ const extra = state.skippedUnknownBinary > Math.min(10, state.skippedUnknownBinaryFiles.length) ? " (and others)" : "";
2292
+ degradedReasons.push({
2293
+ code: "UNSCANNED_UNKNOWN_BINARY",
2294
+ detail: `${state.skippedUnknownBinary} file(s) contain NUL or control data that no text reading explains and show no sign of a known binary format, so they were not scanned: ${named}${extra}. If they are safe, add their paths to ignore.paths in shipguard.policy.yml.`
2295
+ });
2296
+ }
2297
+ if (state.acceptedPaths === 0) {
2298
+ const parts = [];
2299
+ const add = (n, label) => {
2300
+ if (n > 0) parts.push(`${n} ${label}`);
2301
+ };
2302
+ add(state.skippedBinary, "binary");
2303
+ add(skippedTooLarge, "too large");
2304
+ add(skippedSymlinks, "symlink");
2305
+ add(state.skippedUnknownBinary, "unknown binary");
2306
+ add(changedInvalidUtf8.length, "invalid UTF-8");
2307
+ add(changedUnreadable.length, "unreadable");
2308
+ add(state.skippedSpecial, "special");
2309
+ add(state.notReached, "not reached");
2310
+ degradedReasons.push({
2311
+ code: "NO_FILES_SCANNED",
2312
+ detail: `0 files were scanned (${state.discovered} candidate file(s)${parts.length > 0 ? `: ${parts.join(", ")}` : ""}, 0 readable). A scan that read nothing cannot report that shipping is safe.`
2392
2313
  });
2393
2314
  }
2394
2315
  const isDegraded = degradedReasons.length > 0 || void 0;
2316
+ const coverage = buildCoverage(state, mode, changedInfo);
2395
2317
  const result = {
2396
2318
  findings: allFindings,
2397
2319
  riskScore,
2398
- filesScanned: files.length,
2320
+ filesScanned: state.acceptedPaths,
2399
2321
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2400
2322
  policyUsed: policy.project.name,
2401
- // Degraded when ANY of: coderef version-skip, collection truncation, a file
2402
- // skipped for being too large, OR a symlink not followed (symlink reporting).
2403
- // The oversized-skip case and the symlink-skip
2404
- // case both mean content was NOT scanned — the scan is incomplete, so it must
2405
- // NOT be reported SAFE. Binary skips (skippedBinary) are NORMAL and
2406
- // intentionally EXCLUDED — a binary file legitimately has no source to scan.
2323
+ // Degraded when ANY of: coderef version-skip, truncation, an oversized file, a symlink not
2324
+ // followed, an unreadable/invalid/unknown-binary file, OR nothing scanned at all. Real binaries
2325
+ // (skipped.binary) are NORMAL and intentionally EXCLUDED: a real image has no source to scan.
2407
2326
  // scan.ts OR-merges this with its own pro-fetch-failure flag.
2408
2327
  treeDigest,
2409
2328
  degraded: isDegraded,
2410
- // Machine-readable WHY for each degrade source — safe to key on in agent logic.
2329
+ // Machine-readable WHY for each degrade source - safe to key on in agent logic.
2411
2330
  // scan.ts OR-merges its own PRO_RULES_UNAVAILABLE entry after pro-fetch failure.
2412
2331
  degradedReasons: degradedReasons.length > 0 ? degradedReasons : void 0,
2413
- // Internal metadata for the human-output path — NOT included in --json output
2414
- _skippedTooLarge: skippedTooLarge,
2415
- _skippedTooLargeFiles: skippedTooLargeFiles,
2416
- _skippedBinary: skippedBinary,
2417
- _skippedBinaryFiles: skippedBinaryFiles,
2418
- _skippedSymlinks: skippedSymlinks,
2419
- _skippedSymlinkFiles: skippedSymlinkFiles,
2420
- _truncated: truncated
2332
+ coverage
2421
2333
  };
2422
2334
  applyVerdict(result);
2423
2335
  return result;
@@ -2509,7 +2421,7 @@ function toSarif(result) {
2509
2421
  // src/core/render.ts
2510
2422
  import chalk from "chalk";
2511
2423
  import { existsSync as existsSync2 } from "fs";
2512
- import { join as join4, basename as basename2 } from "path";
2424
+ import { join as join4, basename } from "path";
2513
2425
  import { homedir } from "os";
2514
2426
  var DOCS_URL = goLink("docs");
2515
2427
  var SITE_URL = goLink("site");
@@ -2623,7 +2535,7 @@ function renderProgressBar(current, total, width = 20, currentFile) {
2623
2535
  const empty = width - filled;
2624
2536
  const bar = chalk.cyan(BAR_FULL.repeat(filled)) + chalk.gray(BAR_EMPTY.repeat(empty));
2625
2537
  const counter = `${current}/${total}`;
2626
- const fileHint = currentFile ? ` ${chalk.dim(basename2(currentFile) || truncatePath(currentFile, 30))}` : "";
2538
+ const fileHint = currentFile ? ` ${chalk.dim(basename(currentFile) || truncatePath(currentFile, 30))}` : "";
2627
2539
  return `${chalk.cyan("\u{1F50D}")} scanning [${bar}] ${chalk.bold(counter)}${fileHint}`;
2628
2540
  }
2629
2541
  function shouldShowProgress(gates) {
@@ -2690,6 +2602,30 @@ function coverageLine() {
2690
2602
  Plans: ${chalk.underline(PRICING_URL)}`
2691
2603
  );
2692
2604
  }
2605
+ function coverageSummaryLine(c) {
2606
+ const skipped = [];
2607
+ const add = (list, n, label) => {
2608
+ if (n > 0) list.push(`${label} ${n}`);
2609
+ };
2610
+ add(skipped, c.skipped.binary, "binary");
2611
+ add(skipped, c.skipped.tooLarge, "too large");
2612
+ add(skipped, c.skipped.symlink, "symlink");
2613
+ add(skipped, c.skipped.unknownBinary, "unknown");
2614
+ add(skipped, c.skipped.invalidUtf8, "invalid UTF-8");
2615
+ add(skipped, c.skipped.unreadable, "unreadable");
2616
+ add(skipped, c.skipped.special, "special");
2617
+ const decoded = [];
2618
+ add(decoded, c.decoded.utf16, "UTF-16");
2619
+ add(decoded, c.decoded.nulSubstituted, "NUL-substituted");
2620
+ add(decoded, c.decoded.asciiStrings, "strings-only");
2621
+ add(decoded, c.decoded.binaryStringsScanned, "binary strings");
2622
+ const ignored = c.ignoredByUser + c.ignoredByDefault.reduce((n, e) => n + (e.files ?? 0), 0);
2623
+ const parts = [`scanned ${c.scanned} of ${c.discovered} files`];
2624
+ if (skipped.length > 0) parts.push(`skipped: ${skipped.join(", ")}`);
2625
+ if (decoded.length > 0) parts.push(`decoded: ${decoded.join(", ")}`);
2626
+ if (ignored > 0) parts.push(`ignored: ${ignored}`);
2627
+ return chalk.dim(` Coverage: ${parts.join("; ")}`);
2628
+ }
2693
2629
  var VERDICT_CONFIG = {
2694
2630
  SAFE_TO_SHIP: {
2695
2631
  icon: "\u2705",
@@ -2815,8 +2751,8 @@ function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict, repo
2815
2751
  if ((riskScore.blockingCount > 0 || degraded) && !strict) {
2816
2752
  lines.push(boxLine(chalk.dim(" (informational \u2014 exit 0; use --strict to enforce as exit 1)")));
2817
2753
  }
2818
- const attitudeLine2 = degraded ? chalk.red(" INCOMPLETE \u2014 parts of this scan did not run, so it cannot say this is safe.") : recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
2819
- lines.push(boxLine(attitudeLine2));
2754
+ const attitudeLine = degraded ? chalk.red(" INCOMPLETE \u2014 parts of this scan did not run, so it cannot say this is safe.") : recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
2755
+ lines.push(boxLine(attitudeLine));
2820
2756
  lines.push(boxEmpty());
2821
2757
  lines.push(boxBottom());
2822
2758
  lines.push("");
@@ -2972,7 +2908,7 @@ function displayWidth(str) {
2972
2908
 
2973
2909
  // src/core/history/finding-key.ts
2974
2910
  import { createHmac, randomBytes } from "crypto";
2975
- import { chmodSync, existsSync as existsSync3, linkSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
2911
+ import { chmodSync, existsSync as existsSync3, linkSync, readFileSync as readFileSync2, statSync, unlinkSync, writeFileSync } from "fs";
2976
2912
  var SALT_BYTES = 32;
2977
2913
  var SALT_HEX = /^[0-9a-f]{64}$/;
2978
2914
  function saltPathFor(dbPath) {
@@ -2984,7 +2920,7 @@ function keyFindingIdentity(salt, identityDigest) {
2984
2920
  function readSalt(path) {
2985
2921
  let text;
2986
2922
  try {
2987
- text = readFileSync(path, "utf-8").trim();
2923
+ text = readFileSync2(path, "utf-8").trim();
2988
2924
  } catch (err) {
2989
2925
  return { ok: false, reason: `Could not read the history salt file ${path}: ${err instanceof Error ? err.message : err}` };
2990
2926
  }
@@ -3128,9 +3064,9 @@ function resolveHistoryPath(cwd, policy) {
3128
3064
 
3129
3065
  // src/core/history/identity.ts
3130
3066
  import { execFileSync as execFileSync2 } from "child_process";
3131
- import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
3132
- import { existsSync as existsSync4, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
3133
- import { dirname as dirname3, join as join5 } from "path";
3067
+ import { createHash as createHash2, randomUUID } from "crypto";
3068
+ import { existsSync as existsSync4, mkdirSync, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
3069
+ import { dirname, join as join5 } from "path";
3134
3070
  function tryGit(cwd, args) {
3135
3071
  try {
3136
3072
  return execFileSync2("git", args, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
@@ -3141,7 +3077,7 @@ function tryGit(cwd, args) {
3141
3077
  function ensureGitignored(cwd, entry) {
3142
3078
  try {
3143
3079
  const gitignorePath = join5(cwd, ".gitignore");
3144
- const existing = existsSync4(gitignorePath) ? readFileSync2(gitignorePath, "utf-8") : "";
3080
+ const existing = existsSync4(gitignorePath) ? readFileSync3(gitignorePath, "utf-8") : "";
3145
3081
  const alreadyPresent = existing.split("\n").map((l) => l.trim()).some((l) => l === entry || l === entry.replace(/\/$/, ""));
3146
3082
  if (alreadyPresent) return;
3147
3083
  const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
@@ -3163,20 +3099,20 @@ function resolveRepoIdentity(cwd) {
3163
3099
  const fallbackPath = join5(cwd, DEFAULT_REPO_ID_FALLBACK_PATH);
3164
3100
  try {
3165
3101
  if (existsSync4(fallbackPath)) {
3166
- const existing = readFileSync2(fallbackPath, "utf-8").trim();
3102
+ const existing = readFileSync3(fallbackPath, "utf-8").trim();
3167
3103
  if (existing) {
3168
3104
  return { repoId: existing, repoIdKind: "fallback-uuid", remoteLabel };
3169
3105
  }
3170
3106
  }
3171
- const id = randomUUID2();
3172
- mkdirSync(dirname3(fallbackPath), { recursive: true });
3107
+ const id = randomUUID();
3108
+ mkdirSync(dirname(fallbackPath), { recursive: true });
3173
3109
  writeFileSync2(fallbackPath, `${id}
3174
3110
  `, "utf-8");
3175
3111
  ensureGitignored(cwd, ".shipguard/");
3176
3112
  return { repoId: id, repoIdKind: "fallback-uuid", remoteLabel };
3177
3113
  } catch (err) {
3178
3114
  logger.warn(`Could not persist fallback repo identity: ${err instanceof Error ? err.message : err}`);
3179
- return { repoId: randomUUID2(), repoIdKind: "fallback-uuid", remoteLabel };
3115
+ return { repoId: randomUUID(), repoIdKind: "fallback-uuid", remoteLabel };
3180
3116
  }
3181
3117
  }
3182
3118
  function resolveContentIdentity(cwd, excludePrefixes = []) {
@@ -3208,9 +3144,9 @@ function computeScopeFingerprint(input) {
3208
3144
  }
3209
3145
 
3210
3146
  // src/core/history/store.ts
3211
- import { randomUUID as randomUUID3 } from "crypto";
3147
+ import { randomUUID as randomUUID2 } from "crypto";
3212
3148
  import { existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
3213
- import { dirname as dirname4 } from "path";
3149
+ import { dirname as dirname2 } from "path";
3214
3150
  var sqliteModulePromise;
3215
3151
  var warningFilterInstalled = false;
3216
3152
  function installSqliteWarningFilter() {
@@ -3267,7 +3203,7 @@ var HistoryStore = class _HistoryStore {
3267
3203
  }
3268
3204
  const preExisted = existsSync5(dbPath);
3269
3205
  try {
3270
- mkdirSync2(dirname4(dbPath), { recursive: true });
3206
+ mkdirSync2(dirname2(dbPath), { recursive: true });
3271
3207
  } catch (err) {
3272
3208
  return {
3273
3209
  ok: false,
@@ -3516,7 +3452,7 @@ var HistoryStore = class _HistoryStore {
3516
3452
  return { ok: true, scanId: row.scan_id, reused: true };
3517
3453
  }
3518
3454
  }
3519
- const scanId = randomUUID3();
3455
+ const scanId = randomUUID2();
3520
3456
  this.db.prepare(
3521
3457
  `INSERT INTO scan_id_reservations (repo_id, reuse_key, scan_id, created_at) VALUES (?, ?, ?, ?)
3522
3458
  ON CONFLICT(repo_id, reuse_key) DO UPDATE SET scan_id = excluded.scan_id, created_at = excluded.created_at`
@@ -3640,7 +3576,7 @@ function computeRegressionResult(current, baseline) {
3640
3576
  }
3641
3577
 
3642
3578
  // src/core/history/scan-id.ts
3643
- import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
3579
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
3644
3580
  import { relative } from "path";
3645
3581
  function computeScanIdReuseKey(input) {
3646
3582
  const normalized = {
@@ -3675,7 +3611,7 @@ async function resolveScanId(input) {
3675
3611
  const excludePrefixes = [".shipguard/", historyRelPath];
3676
3612
  const contentIdentity = resolveContentIdentity(cwd, excludePrefixes);
3677
3613
  if (!contentIdentity) {
3678
- return { scanId: randomUUID4(), scanIdReused: false };
3614
+ return { scanId: randomUUID3(), scanIdReused: false };
3679
3615
  }
3680
3616
  const identity = resolveRepoIdentity(cwd);
3681
3617
  const reuseKey = computeScanIdReuseKey({
@@ -3690,14 +3626,14 @@ async function resolveScanId(input) {
3690
3626
  const openResult = await HistoryStore.open(historyPath, cliVersion);
3691
3627
  if (!openResult.ok) {
3692
3628
  logger.warn(`ShipGuard scanId persistence unavailable (${openResult.status}) \u2014 minting a fresh scanId: ${openResult.reason}`);
3693
- return { scanId: randomUUID4(), scanIdReused: false };
3629
+ return { scanId: randomUUID3(), scanIdReused: false };
3694
3630
  }
3695
3631
  const store = openResult.store;
3696
3632
  try {
3697
3633
  const result = store.reserveScanId(identity.repoId, reuseKey, reuseWindowMs);
3698
3634
  if (!result.ok) {
3699
3635
  logger.warn(`ShipGuard scanId persistence failed \u2014 minting a fresh scanId: ${result.reason}`);
3700
- return { scanId: randomUUID4(), scanIdReused: false };
3636
+ return { scanId: randomUUID3(), scanIdReused: false };
3701
3637
  }
3702
3638
  return { scanId: result.scanId, scanIdReused: result.reused };
3703
3639
  } finally {
@@ -3707,7 +3643,7 @@ async function resolveScanId(input) {
3707
3643
  logger.warn(
3708
3644
  `ShipGuard scanId persistence failed unexpectedly \u2014 minting a fresh scanId: ${err instanceof Error ? err.message : err}`
3709
3645
  );
3710
- return { scanId: randomUUID4(), scanIdReused: false };
3646
+ return { scanId: randomUUID3(), scanIdReused: false };
3711
3647
  }
3712
3648
  }
3713
3649
 
@@ -3837,16 +3773,17 @@ async function recordScanHistory(input) {
3837
3773
  }
3838
3774
 
3839
3775
  // src/core/telemetry.ts
3840
- import { randomUUID as randomUUID6 } from "crypto";
3776
+ import { randomUUID as randomUUID5 } from "crypto";
3841
3777
 
3842
3778
  // src/core/telemetry-config.ts
3843
- import { randomUUID as randomUUID5 } from "crypto";
3844
- import { existsSync as existsSync6, readFileSync as readFileSync3 } from "fs";
3779
+ import { randomUUID as randomUUID4 } from "crypto";
3780
+ import { existsSync as existsSync6, readFileSync as readFileSync4 } from "fs";
3845
3781
  import { homedir as homedir2 } from "os";
3846
3782
  import { join as join6 } from "path";
3847
3783
  import YAML2 from "yaml";
3848
3784
  var CONFIG_FILE = "telemetry.json";
3849
3785
  var NOTICE_MARKER = "telemetry-notice-shown";
3786
+ var FIRST_RUN_MARKER = "telemetry-first-run-sent";
3850
3787
  function getConfigDir() {
3851
3788
  return join6(homedir2(), ".config", "shipguard");
3852
3789
  }
@@ -3857,7 +3794,7 @@ function readUserConfig(dir = getConfigDir()) {
3857
3794
  const file = configFilePath(dir);
3858
3795
  try {
3859
3796
  if (!existsSync6(file)) return {};
3860
- const parsed = JSON.parse(readFileSync3(file, "utf-8"));
3797
+ const parsed = JSON.parse(readFileSync4(file, "utf-8"));
3861
3798
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
3862
3799
  } catch (err) {
3863
3800
  logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
@@ -3868,7 +3805,7 @@ function userConfigUnreadable(dir = getConfigDir()) {
3868
3805
  const file = configFilePath(dir);
3869
3806
  try {
3870
3807
  if (!existsSync6(file)) return false;
3871
- const parsed = JSON.parse(readFileSync3(file, "utf-8"));
3808
+ const parsed = JSON.parse(readFileSync4(file, "utf-8"));
3872
3809
  return !(parsed && typeof parsed === "object" && !Array.isArray(parsed));
3873
3810
  } catch {
3874
3811
  return true;
@@ -3889,7 +3826,7 @@ function getOrCreateInstallId(dir = getConfigDir()) {
3889
3826
  const existing = readInstallId(dir);
3890
3827
  if (existing) return existing;
3891
3828
  try {
3892
- const installId = randomUUID5();
3829
+ const installId = randomUUID4();
3893
3830
  writeConfig(dir, { ...readUserConfig(dir), installId });
3894
3831
  return installId;
3895
3832
  } catch (err) {
@@ -3921,6 +3858,19 @@ function markNoticeShown(dir = getConfigDir()) {
3921
3858
  logger.debug(`telemetry: could not persist the notice marker: ${err instanceof Error ? err.message : String(err)}`);
3922
3859
  }
3923
3860
  }
3861
+ function firstRunHandled(dir = getConfigDir()) {
3862
+ return existsSync6(join6(dir, FIRST_RUN_MARKER));
3863
+ }
3864
+ function markFirstRunHandled(dir = getConfigDir()) {
3865
+ try {
3866
+ ensureSecureDir(dir);
3867
+ writeSecureFileSync(join6(dir, FIRST_RUN_MARKER), "1\n");
3868
+ return true;
3869
+ } catch (err) {
3870
+ logger.debug(`telemetry: could not persist the first-run marker: ${err instanceof Error ? err.message : String(err)}`);
3871
+ return false;
3872
+ }
3873
+ }
3924
3874
  var FALSE_LIKE = /* @__PURE__ */ new Set(["false", "off", "no", "0"]);
3925
3875
  var GENERATED_CONFIG_FILE = ".shipguard.yml";
3926
3876
  function policyTelemetryEnabled(policy) {
@@ -3936,7 +3886,7 @@ function policyTelemetryEnabled(policy) {
3936
3886
  function readYamlToggle(file) {
3937
3887
  try {
3938
3888
  if (!existsSync6(file)) return void 0;
3939
- return policyTelemetryEnabled(YAML2.parse(readFileSync3(file, "utf-8")));
3889
+ return policyTelemetryEnabled(YAML2.parse(readFileSync4(file, "utf-8")));
3940
3890
  } catch (err) {
3941
3891
  logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
3942
3892
  return void 0;
@@ -3973,6 +3923,11 @@ function resolveEndpoint(published = IS_PUBLISHED_BUILD, env = process.env) {
3973
3923
  if (published) return override || PROD_TELEMETRY_ENDPOINT;
3974
3924
  return isLoopbackUrl(override) ? override : null;
3975
3925
  }
3926
+ function resolveTraffic(env, published) {
3927
+ const v = env.SHIPGUARD_TRAFFIC;
3928
+ if (v === "test" || v === "internal") return v;
3929
+ return published ? void 0 : "test";
3930
+ }
3976
3931
  var ALLOWED_KEYS = [
3977
3932
  "schema",
3978
3933
  "eventId",
@@ -4027,14 +3982,20 @@ function envOptOut(env) {
4027
3982
  return null;
4028
3983
  }
4029
3984
  function buildPayload(input) {
4030
- const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci } = input;
4031
- return { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci };
3985
+ const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, traffic } = input;
3986
+ const out = { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci };
3987
+ if (traffic === "test" || traffic === "internal") out.traffic = traffic;
3988
+ return out;
3989
+ }
3990
+ function isTrafficOk(obj, count, expected) {
3991
+ if ("traffic" in obj) return count === expected + 1 && (obj.traffic === "test" || obj.traffic === "internal");
3992
+ return count === expected;
4032
3993
  }
4033
3994
  function validatePayload(payload) {
4034
3995
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
4035
3996
  const obj = payload;
4036
3997
  const keys = Object.keys(obj);
4037
- if (keys.length !== ALLOWED_KEYS.length) return false;
3998
+ if (!isTrafficOk(obj, keys.length, ALLOWED_KEYS.length)) return false;
4038
3999
  for (const k of ALLOWED_KEYS) if (!(k in obj)) return false;
4039
4000
  if (obj.schema !== 2) return false;
4040
4001
  if (typeof obj.eventId !== "string" || !UUID_V4.test(obj.eventId)) return false;
@@ -4061,7 +4022,7 @@ function decideTelemetry(input = {}) {
4061
4022
  if (projectTelemetryEnabled({ policy: input.policy, projectDir: input.projectDir }) === false) return { enabled: false, source: "project-policy" };
4062
4023
  return { enabled: true, source: "default" };
4063
4024
  }
4064
- var NOTICE_TEXT = "shipguard: sends a pseudonymous usage ping after each scan (version, verdict, duration bucket, a random install id outside CI; never code, paths or your account). Turn it off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`. " + goLink("telemetry");
4025
+ var NOTICE_TEXT = "shipguard: sends a pseudonymous usage ping after each scan, once on first run and after login (version, verdict, duration bucket, a random install id outside CI; never code, paths or your account). Turn it off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`. " + goLink("telemetry");
4065
4026
  var PING_WAIT_MS = 1500;
4066
4027
  var FETCH_TIMEOUT_MS = 1e3;
4067
4028
  function debugEnabled(env) {
@@ -4084,16 +4045,17 @@ function sendTelemetry(input, opts = {}) {
4084
4045
  const ci = detectCi(env);
4085
4046
  const base = {
4086
4047
  schema: 2,
4087
- eventId: randomUUID6(),
4048
+ eventId: randomUUID5(),
4088
4049
  cliVersion: input.cliVersion,
4089
4050
  provenance: getProvenance(published),
4090
4051
  verdict: input.verdict,
4091
4052
  durationBucket: durationBucket(input.durationMs),
4092
- ci
4053
+ ci,
4054
+ traffic: resolveTraffic(env, published)
4093
4055
  };
4094
4056
  if (debug) {
4095
4057
  const stored = ci ? null : readInstallId(configDir);
4096
- const installId2 = ci ? null : stored ?? randomUUID6();
4058
+ const installId2 = ci ? null : stored ?? randomUUID5();
4097
4059
  const note = !ci && !stored ? " (installId is a preview: none saved yet, one is created on the first real ping)" : "";
4098
4060
  process.stderr.write(
4099
4061
  `[shipguard:telemetry] SHIPGUARD_TELEMETRY_DEBUG=1: not sending. provenance=${base.provenance} endpoint=${endpoint ?? "(none: dev build without a loopback SHIPGUARD_TELEMETRY_URL)"} payload=${JSON.stringify(buildPayload({ ...base, installId: installId2 }))}${note}
@@ -4120,36 +4082,157 @@ function sendTelemetry(input, opts = {}) {
4120
4082
  return Promise.resolve();
4121
4083
  }
4122
4084
  const body = JSON.stringify(payload);
4123
- const controller = new AbortController();
4124
- const abortTimer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
4125
- const request = fetch(endpoint, {
4126
- method: "POST",
4127
- headers: { "Content-Type": "application/json" },
4128
- body,
4129
- signal: controller.signal
4130
- }).then(
4131
- () => void 0,
4132
- (err) => {
4133
- logger.debug(`telemetry: ping failed (ignored): ${err instanceof Error ? err.message : String(err)}`);
4134
- }
4135
- ).finally(() => clearTimeout(abortTimer));
4136
- return new Promise((resolve7) => {
4137
- const cap = setTimeout(resolve7, PING_WAIT_MS);
4138
- cap.unref();
4139
- void request.then(() => {
4140
- clearTimeout(cap);
4141
- resolve7();
4142
- });
4085
+ return postBounded(endpoint, body);
4086
+ } catch (err) {
4087
+ logger.debug(`telemetry: skipped after error (ignored): ${err instanceof Error ? err.message : String(err)}`);
4088
+ return Promise.resolve();
4089
+ }
4090
+ }
4091
+ function postBounded(endpoint, body) {
4092
+ const controller = new AbortController();
4093
+ const abortTimer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
4094
+ const request = fetch(endpoint, {
4095
+ method: "POST",
4096
+ headers: { "Content-Type": "application/json" },
4097
+ body,
4098
+ signal: controller.signal
4099
+ }).then(
4100
+ () => void 0,
4101
+ (err) => {
4102
+ logger.debug(`telemetry: ping failed (ignored): ${err instanceof Error ? err.message : String(err)}`);
4103
+ }
4104
+ ).finally(() => clearTimeout(abortTimer));
4105
+ return new Promise((resolve7) => {
4106
+ const cap = setTimeout(resolve7, PING_WAIT_MS);
4107
+ cap.unref();
4108
+ void request.then(() => {
4109
+ clearTimeout(cap);
4110
+ resolve7();
4143
4111
  });
4112
+ });
4113
+ }
4114
+ var CLI_VERSION = true ? "0.10.0-rc.0" : process.env.npm_package_version ?? "0.0.0-dev";
4115
+ var LIFECYCLE_KEYS = ["schema", "event", "eventId", "installId", "cliVersion", "provenance", "ci"];
4116
+ function validateLifecyclePayload(payload) {
4117
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
4118
+ const o = payload;
4119
+ const keys = Object.keys(o);
4120
+ if (!isTrafficOk(o, keys.length, LIFECYCLE_KEYS.length) || !LIFECYCLE_KEYS.every((k) => k in o)) return false;
4121
+ if (o.schema !== 3) return false;
4122
+ if (o.event !== "cli_first_run" && o.event !== "cli_login") return false;
4123
+ if (typeof o.eventId !== "string" || !UUID_V4.test(o.eventId)) return false;
4124
+ if (typeof o.ci !== "boolean") return false;
4125
+ if (o.ci) {
4126
+ if (o.installId !== null || o.event === "cli_first_run") return false;
4127
+ } else if (typeof o.installId !== "string" || !UUID_V4.test(o.installId)) {
4128
+ return false;
4129
+ }
4130
+ if (typeof o.cliVersion !== "string" || o.cliVersion.length > 40 || !VERSION_RE.test(o.cliVersion)) return false;
4131
+ return o.provenance === "published" || o.provenance === "dev";
4132
+ }
4133
+ function sendLifecycleEvent(event, input, opts = {}) {
4134
+ try {
4135
+ const env = opts.env ?? process.env;
4136
+ const configDir = opts.configDir ?? getConfigDir();
4137
+ const published = opts.published ?? IS_PUBLISHED_BUILD;
4138
+ const debug = debugEnabled(env);
4139
+ const ci = detectCi(env);
4140
+ if (event === "cli_first_run" && ci) return Promise.resolve();
4141
+ const decision = decideTelemetry({ env, configDir, policy: opts.policy, projectDir: opts.projectDir });
4142
+ if (!decision.enabled) {
4143
+ if (debug) process.stderr.write(`[shipguard:telemetry] disabled (${decision.source}); nothing would be sent
4144
+ `);
4145
+ return Promise.resolve();
4146
+ }
4147
+ const endpoint = resolveEndpoint(published, env);
4148
+ const base = {
4149
+ schema: 3,
4150
+ event,
4151
+ eventId: randomUUID5(),
4152
+ cliVersion: input.cliVersion,
4153
+ provenance: getProvenance(published),
4154
+ ci
4155
+ };
4156
+ const traffic = resolveTraffic(env, published);
4157
+ if (debug) {
4158
+ const installId2 = ci ? null : readInstallId(configDir) ?? randomUUID5();
4159
+ process.stderr.write(
4160
+ `[shipguard:telemetry] SHIPGUARD_TELEMETRY_DEBUG=1: not sending. endpoint=${endpoint ?? "(none)"} payload=${JSON.stringify({ ...base, installId: installId2, ...traffic ? { traffic } : {} })}
4161
+ `
4162
+ );
4163
+ return Promise.resolve();
4164
+ }
4165
+ if (endpoint === null) {
4166
+ logger.debug("telemetry: dev build, not sending (set a loopback SHIPGUARD_TELEMETRY_URL to capture)");
4167
+ return Promise.resolve();
4168
+ }
4169
+ if (event === "cli_first_run") {
4170
+ if (firstRunHandled(configDir)) return Promise.resolve();
4171
+ if (readInstallId(configDir)) {
4172
+ markFirstRunHandled(configDir);
4173
+ return Promise.resolve();
4174
+ }
4175
+ }
4176
+ if (!noticeShown(configDir)) {
4177
+ process.stderr.write(NOTICE_TEXT + "\n");
4178
+ markNoticeShown(configDir);
4179
+ }
4180
+ const installId = ci ? null : getOrCreateInstallId(configDir) ?? void 0;
4181
+ if (installId === void 0) {
4182
+ logger.debug("telemetry: no install id could be saved; not sending");
4183
+ return Promise.resolve();
4184
+ }
4185
+ if (event === "cli_first_run" && !markFirstRunHandled(configDir)) return Promise.resolve();
4186
+ const payload = { ...base, installId, ...traffic ? { traffic } : {} };
4187
+ if (!validateLifecyclePayload(payload)) {
4188
+ logger.debug("telemetry: lifecycle payload failed validation; not sending");
4189
+ return Promise.resolve();
4190
+ }
4191
+ return postBounded(endpoint, JSON.stringify(payload));
4144
4192
  } catch (err) {
4145
4193
  logger.debug(`telemetry: skipped after error (ignored): ${err instanceof Error ? err.message : String(err)}`);
4146
4194
  return Promise.resolve();
4147
4195
  }
4148
4196
  }
4149
4197
 
4198
+ // src/utils/exit.ts
4199
+ function setExitCode(code) {
4200
+ process.exitCode = code;
4201
+ }
4202
+ var installed = false;
4203
+ function installStreamErrorHandlers() {
4204
+ if (installed) return;
4205
+ installed = true;
4206
+ for (const [name, stream] of [["stdout", process.stdout], ["stderr", process.stderr]]) {
4207
+ stream.on("error", (err) => {
4208
+ if (name === "stderr") return;
4209
+ if (err?.code === "EPIPE") {
4210
+ logger.debug(`${name}: reader closed the pipe (EPIPE); keeping the computed exit code`);
4211
+ return;
4212
+ }
4213
+ logger.warn(`${name} stream error (${err?.code ?? "unknown"}): ${err?.message ?? String(err)}`);
4214
+ });
4215
+ }
4216
+ }
4217
+ function exitWhenDrained() {
4218
+ const code = process.exitCode;
4219
+ if (code === void 0 || code === 0) return;
4220
+ let pending = 2;
4221
+ const done = (err) => {
4222
+ if (err) logger.debug(`exit: stream write callback reported ${err.message}; nothing more can be delivered`);
4223
+ pending--;
4224
+ if (pending > 0) return;
4225
+ if (process.stdout.writableLength === 0 && process.stderr.writableLength === 0) {
4226
+ process.exit(Number(code));
4227
+ }
4228
+ };
4229
+ process.stdout.write("", done);
4230
+ process.stderr.write("", done);
4231
+ }
4232
+
4150
4233
  // src/commands/scan.ts
4151
4234
  var LEARN_MORE = `Docs ${goLink("docs")} \xB7 Site ${goLink("site")} \xB7 Pricing ${goLink("pricing")} \xB7 Issues https://github.com/agenticcli/shipguard/issues`;
4152
- var CLI_VERSION = true ? "0.8.1" : process.env.npm_package_version ?? "0.0.0-dev";
4235
+ var CLI_VERSION2 = true ? "0.10.0-rc.0" : process.env.npm_package_version ?? "0.0.0-dev";
4153
4236
  function resolveExitCode(opts) {
4154
4237
  if (opts.strict && (opts.blockingCount > 0 || opts.degraded === true || opts.recommendation === "DO_NOT_SHIP")) {
4155
4238
  return EXIT_CODES.BLOCKED;
@@ -4215,7 +4298,8 @@ Exit codes (verdict-neutral by default \u2014 ShipGuard informs, you choose the
4215
4298
  partial (see \`degraded\`/\`degradedReasons\` in --json output).
4216
4299
  1 Blocked \u2014 with --strict AND at least one of: a blocking finding, a scan
4217
4300
  that did not finish (\`degraded:true\` \u2014 an unfinished scan cannot clear
4218
- a hard gate), or an effective \`recommendation\` of DO_NOT_SHIP (suppressed
4301
+ a hard gate: an oversized file, a symlink, an unreadable file, a truncated
4302
+ scan, a file with unexplained binary data, or a scan that read NOTHING), or an effective \`recommendation\` of DO_NOT_SHIP (suppressed
4219
4303
  findings still count toward the risk score, so a scan can cross the
4220
4304
  DO_NOT_SHIP threshold with zero blocking findings \u2014 the exit code always
4221
4305
  agrees with the printed verdict). OR with --check-regressions AND at
@@ -4252,7 +4336,7 @@ ${LEARN_MORE}`).action(async (scanPath, opts) => {
4252
4336
  if (machineOutput) {
4253
4337
  console.log(JSON.stringify({ error: pathProblem.message, code: pathProblem.code }));
4254
4338
  }
4255
- await exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4339
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4256
4340
  }
4257
4341
  }
4258
4342
  if (!scanPath && !opts.all && !isProjectRoot(cwd)) {
@@ -4263,7 +4347,7 @@ ${LEARN_MORE}`).action(async (scanPath, opts) => {
4263
4347
  console.log(`
4264
4348
  ${LEARN_MORE}`);
4265
4349
  }
4266
- await exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4350
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4267
4351
  }
4268
4352
  const originalCwd = process.cwd();
4269
4353
  if (scanPath) {
@@ -4281,13 +4365,13 @@ ${LEARN_MORE}`);
4281
4365
  async function exitWithError(exitCode, startTime, projectDir, policy) {
4282
4366
  try {
4283
4367
  await sendTelemetry(
4284
- { cliVersion: CLI_VERSION, verdict: "error", durationMs: Date.now() - startTime },
4368
+ { cliVersion: CLI_VERSION2, verdict: "error", durationMs: Date.now() - startTime },
4285
4369
  { policy, projectDir }
4286
4370
  );
4287
4371
  } catch (err) {
4288
4372
  logger.debug(`telemetry: error ping skipped (ignored): ${err instanceof Error ? err.message : String(err)}`);
4289
4373
  }
4290
- return process.exit(exitCode);
4374
+ setExitCode(exitCode);
4291
4375
  }
4292
4376
  function checkScanPath(absPath) {
4293
4377
  let isDir;
@@ -4309,8 +4393,7 @@ async function runScan(ctx) {
4309
4393
  policy = await loadPolicy(cwd);
4310
4394
  } catch (error) {
4311
4395
  logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
4312
- await exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, cwd);
4313
- return;
4396
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, cwd);
4314
4397
  }
4315
4398
  const changedOnly = Boolean(opts.changed);
4316
4399
  const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : [];
@@ -4325,7 +4408,7 @@ async function runScan(ctx) {
4325
4408
  const { scanId, scanIdReused } = await resolveScanId({
4326
4409
  cwd,
4327
4410
  policy,
4328
- cliVersion: CLI_VERSION,
4411
+ cliVersion: CLI_VERSION2,
4329
4412
  changedOnly,
4330
4413
  categories,
4331
4414
  proRequested: Boolean(opts.pro),
@@ -4360,8 +4443,8 @@ async function runScan(ctx) {
4360
4443
  logger.info("Detecting stack...");
4361
4444
  }
4362
4445
  try {
4363
- const { fetchProRules } = await import("./pro-scanner-ZKL6L5L6.js");
4364
- const { hasConfig, generateConfig } = await import("./config-generator-4MK6PGY5.js");
4446
+ const { fetchProRules } = await import("./pro-scanner-TPNDJ6L6.js");
4447
+ const { hasConfig, generateConfig } = await import("./config-generator-S5KFHKGQ.js");
4365
4448
  const frameworks = detectedFrameworks;
4366
4449
  if (!hasConfig(cwd)) {
4367
4450
  const configPath = generateConfig(cwd, frameworks);
@@ -4403,7 +4486,7 @@ async function runScan(ctx) {
4403
4486
  } else {
4404
4487
  console.log(JSON.stringify({ error: errMsg, code: "NO_RULES_APPLIED" }));
4405
4488
  }
4406
- await exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4489
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4407
4490
  }
4408
4491
  const rawErrCode = err?.code;
4409
4492
  const KNOWN_PRO_FETCH_ERROR_CODES = [
@@ -4442,7 +4525,7 @@ async function runScan(ctx) {
4442
4525
  ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
4443
4526
  }));
4444
4527
  }
4445
- await exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4528
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4446
4529
  }
4447
4530
  }
4448
4531
  }
@@ -4479,14 +4562,17 @@ async function runScan(ctx) {
4479
4562
  if (showProgress) {
4480
4563
  process.stderr.write("\r\x1B[K");
4481
4564
  }
4482
- const skippedTooLarge = result._skippedTooLarge ?? 0;
4483
- const skippedTooLargeFiles = result._skippedTooLargeFiles ?? [];
4484
- const skippedBinary = result._skippedBinary ?? 0;
4485
- const skippedBinaryFiles = result._skippedBinaryFiles ?? [];
4486
- const skippedSymlinks = result._skippedSymlinks ?? 0;
4487
- const skippedSymlinkFiles = result._skippedSymlinkFiles ?? [];
4488
- const truncatedByBounds = result._truncated ?? false;
4489
- result.schemaVersion = "5";
4565
+ const coverage = result.coverage;
4566
+ const skippedTooLarge = coverage?.skipped.tooLarge ?? 0;
4567
+ const skippedTooLargeFiles = coverage?.files.tooLarge ?? [];
4568
+ const skippedBinary = coverage?.skipped.binary ?? 0;
4569
+ const skippedBinaryFiles = coverage?.files.binary ?? [];
4570
+ const skippedSymlinks = coverage?.skipped.symlink ?? 0;
4571
+ const skippedSymlinkFiles = coverage?.files.symlink ?? [];
4572
+ const skippedUnknownBinary = coverage?.skipped.unknownBinary ?? 0;
4573
+ const skippedUnknownBinaryFiles = coverage?.files.unknownBinary ?? [];
4574
+ const truncatedBy = coverage?.truncated || void 0;
4575
+ result.schemaVersion = "6";
4490
4576
  result.scanIdReused = scanIdReused;
4491
4577
  result.degraded = degraded || Boolean(result.degraded);
4492
4578
  if (result.degraded) {
@@ -4497,7 +4583,7 @@ async function runScan(ctx) {
4497
4583
  result.creditsWarning = creditsRemaining !== void 0 && creditsRemaining < 10;
4498
4584
  result.rulesVersion = rulesVersion;
4499
4585
  result.runId = scanId;
4500
- result.cliVersion = CLI_VERSION;
4586
+ result.cliVersion = CLI_VERSION2;
4501
4587
  applyVerdict(result);
4502
4588
  if (proRules?.length) {
4503
4589
  const breakdown = {};
@@ -4512,7 +4598,7 @@ async function runScan(ctx) {
4512
4598
  const historyOutcome = await recordScanHistory({
4513
4599
  cwd,
4514
4600
  scanId,
4515
- cliVersion: CLI_VERSION,
4601
+ cliVersion: CLI_VERSION2,
4516
4602
  policy,
4517
4603
  changedOnly: scanOptions.changedOnly,
4518
4604
  categories,
@@ -4530,13 +4616,6 @@ async function runScan(ctx) {
4530
4616
  result.coverageChanged = historyOutcome.coverageChanged;
4531
4617
  }
4532
4618
  const publicResult = { ...result };
4533
- delete publicResult._skippedTooLarge;
4534
- delete publicResult._skippedTooLargeFiles;
4535
- delete publicResult._skippedBinary;
4536
- delete publicResult._skippedBinaryFiles;
4537
- delete publicResult._skippedSymlinks;
4538
- delete publicResult._skippedSymlinkFiles;
4539
- delete publicResult._truncated;
4540
4619
  const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
4541
4620
  let reportPaths;
4542
4621
  if (shouldReport) {
@@ -4585,6 +4664,21 @@ async function runScan(ctx) {
4585
4664
  `ShipGuard never follows symlinks (privacy moat \u2014 a symlink could point outside your project). If this path holds real source, replace the symlink with the real directory/file to have it scanned. Verdict is degraded \u2014 see \`degraded\`/\`degradedReasons\` in --json output (does not change the exit code).`
4586
4665
  );
4587
4666
  }
4667
+ if (skippedUnknownBinary > 0) {
4668
+ const named = skippedUnknownBinaryFiles.slice(0, 10).join(", ");
4669
+ const more = skippedUnknownBinary > Math.min(10, skippedUnknownBinaryFiles.length) ? " (and others)" : "";
4670
+ logger.warn(
4671
+ `Scan INCOMPLETE: ${skippedUnknownBinary} file(s) with unexplained binary data (unknown binary) were NOT scanned: ${named}${more}`
4672
+ );
4673
+ logger.warn(
4674
+ `If these files are safe, add their paths to \`ignore.paths\` in shipguard.policy.yml. Verdict is degraded \u2014 see \`degradedReasons\` in --json output.`
4675
+ );
4676
+ }
4677
+ if (coverage && coverage.scanned === 0) {
4678
+ logger.warn(
4679
+ `Nothing was scanned (0 of ${coverage.discovered} candidate file(s) could be read). A scan that read nothing is DO_NOT_SHIP, never safe.`
4680
+ );
4681
+ }
4588
4682
  if (skippedBinary > 0) {
4589
4683
  const named = skippedBinaryFiles.slice(0, 10).join(", ");
4590
4684
  const more = skippedBinary > skippedBinaryFiles.length || skippedBinaryFiles.length > 10 ? ` (and others)` : "";
@@ -4599,12 +4693,13 @@ async function runScan(ctx) {
4599
4693
  if (degraded) {
4600
4694
  logger.warn("Scan ran in degraded mode \u2014 pro rules were unavailable");
4601
4695
  }
4602
- if (truncatedByBounds) {
4696
+ if (truncatedBy) {
4603
4697
  logger.warn(
4604
- `Scan was truncated: file count or total size limit was reached. Results are INCOMPLETE \u2014 add a \`.shipguardignore\` or edit \`shipguard.policy.yml\` limits.`
4698
+ `Scan was truncated at ${truncatedBy.by}: ${truncatedBy.notReached} file(s) were never reached. Results are INCOMPLETE \u2014 raise the limit or narrow the scan with \`ignore.paths\` in \`shipguard.policy.yml\`.`
4605
4699
  );
4606
4700
  logger.warn(`Docs: ${goLink("docs")}`);
4607
4701
  }
4702
+ if (coverage) console.log(coverageSummaryLine(coverage));
4608
4703
  console.log(coverageLine());
4609
4704
  console.log("");
4610
4705
  const topRuleId = result.findings.length > 0 ? result.findings[0].id : void 0;
@@ -4617,7 +4712,7 @@ async function runScan(ctx) {
4617
4712
  console.log(verdictPanel(
4618
4713
  result,
4619
4714
  elapsedMs,
4620
- skippedTooLarge + skippedBinary + skippedSymlinks,
4715
+ skippedTooLarge + skippedBinary + skippedSymlinks + skippedUnknownBinary,
4621
4716
  result.findings,
4622
4717
  scanOptions.strict,
4623
4718
  reportPaths
@@ -4629,7 +4724,7 @@ async function runScan(ctx) {
4629
4724
  const verdictBucket = result.degraded ? "review" : result.riskScore.blockingCount > 0 ? "blocked" : result.riskScore.recommendation === "REVIEW_BEFORE_SHIP" ? "review" : "safe";
4630
4725
  telemetryDone = sendTelemetry(
4631
4726
  {
4632
- cliVersion: CLI_VERSION,
4727
+ cliVersion: CLI_VERSION2,
4633
4728
  verdict: verdictBucket,
4634
4729
  durationMs: elapsedMs
4635
4730
  },
@@ -4671,7 +4766,7 @@ async function runScan(ctx) {
4671
4766
  }
4672
4767
  await telemetryDone;
4673
4768
  if (exitCode !== EXIT_CODES.SAFE) {
4674
- process.exit(exitCode);
4769
+ setExitCode(exitCode);
4675
4770
  }
4676
4771
  }
4677
4772
 
@@ -4768,6 +4863,7 @@ Visit: ${safeUrl.href}`);
4768
4863
  apiUrl
4769
4864
  });
4770
4865
  logger.success("Authenticated successfully!");
4866
+ await sendLifecycleEvent("cli_login", { cliVersion: CLI_VERSION }, { projectDir: process.cwd() });
4771
4867
  return;
4772
4868
  }
4773
4869
  const { error } = tokenBody;
@@ -4831,7 +4927,7 @@ function statusCommand() {
4831
4927
  // src/commands/history.ts
4832
4928
  import { Command as Command6 } from "commander";
4833
4929
  import { resolve as resolve5 } from "path";
4834
- var CLI_VERSION2 = true ? "0.8.1" : process.env.npm_package_version ?? "0.0.0-dev";
4930
+ var CLI_VERSION3 = true ? "0.10.0-rc.0" : process.env.npm_package_version ?? "0.0.0-dev";
4835
4931
  function historyCommand() {
4836
4932
  return new Command6("history").description("Show recent local scan history for this repo (read-only; --json for machine output)").argument("[path]", "Path to project root (defaults to current directory)").option("--json", "Output as JSON").option("--limit <n>", "Number of recent scans to show", (v) => Number.parseInt(v, 10) || 10, 10).action(async (scanPath, opts) => {
4837
4933
  const cwd = scanPath ? resolve5(scanPath) : process.cwd();
@@ -4846,7 +4942,7 @@ function historyCommand() {
4846
4942
  }
4847
4943
  const identity = resolveRepoIdentity(cwd);
4848
4944
  const historyPath = resolveHistoryPath(cwd, policy);
4849
- const openResult = await HistoryStore.open(historyPath, CLI_VERSION2);
4945
+ const openResult = await HistoryStore.open(historyPath, CLI_VERSION3);
4850
4946
  if (!openResult.ok) {
4851
4947
  if (machineOutput) {
4852
4948
  console.log(JSON.stringify({ version: 1, available: false, status: openResult.status, reason: openResult.reason }));
@@ -4897,8 +4993,8 @@ function historyCommand() {
4897
4993
  // src/commands/hook.ts
4898
4994
  import { Command as Command7 } from "commander";
4899
4995
  import { execFileSync as execFileSync3 } from "child_process";
4900
- import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
4901
- import { dirname as dirname5, isAbsolute, join as join8, relative as relative2, resolve as resolve6 } from "path";
4996
+ import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
4997
+ import { dirname as dirname3, isAbsolute, join as join8, relative as relative2, resolve as resolve6 } from "path";
4902
4998
 
4903
4999
  // src/core/hook-templates.ts
4904
5000
  var HOOK_BLOCK_VERSION = 1;
@@ -4991,12 +5087,12 @@ function isManaged(content) {
4991
5087
  // src/commands/hook.ts
4992
5088
  function writeManaged(path, whole, block, executable) {
4993
5089
  if (!existsSync8(path)) {
4994
- mkdirSync3(dirname5(path), { recursive: true });
5090
+ mkdirSync3(dirname3(path), { recursive: true });
4995
5091
  writeFileSync3(path, whole, "utf-8");
4996
5092
  if (executable) chmodSync2(path, 493);
4997
5093
  return { path, status: "created" };
4998
5094
  }
4999
- const current = readFileSync4(path, "utf-8");
5095
+ const current = readFileSync5(path, "utf-8");
5000
5096
  if (!isManaged(current)) {
5001
5097
  return {
5002
5098
  path,
@@ -5028,11 +5124,11 @@ function installClaude(cwd) {
5028
5124
  const path = join8(cwd, ".claude", "settings.json");
5029
5125
  const entry = { matcher: "Bash", hooks: [{ type: "command", command: CLAUDE_HOOK_COMMAND }] };
5030
5126
  if (!existsSync8(path)) {
5031
- mkdirSync3(dirname5(path), { recursive: true });
5127
+ mkdirSync3(dirname3(path), { recursive: true });
5032
5128
  writeFileSync3(path, JSON.stringify({ hooks: { PreToolUse: [entry] } }, null, 2) + "\n", "utf-8");
5033
5129
  return [{ path, status: "created" }];
5034
5130
  }
5035
- const raw2 = readFileSync4(path, "utf-8");
5131
+ const raw2 = readFileSync5(path, "utf-8");
5036
5132
  let settings;
5037
5133
  try {
5038
5134
  settings = JSON.parse(raw2);
@@ -5153,13 +5249,13 @@ Exit codes:
5153
5249
 
5154
5250
  // src/commands/schema.ts
5155
5251
  import { Command as Command8 } from "commander";
5156
- var CLI_VERSION3 = true ? "0.8.1" : process.env.npm_package_version ?? "0.0.0-dev";
5157
- var CURRENT_SCHEMA_VERSION2 = "5";
5252
+ var CLI_VERSION4 = true ? "0.10.0-rc.0" : process.env.npm_package_version ?? "0.0.0-dev";
5253
+ var CURRENT_SCHEMA_VERSION2 = "6";
5158
5254
  function buildSchemaContract(limits) {
5159
5255
  const src = (value, fallback) => value === fallback ? "default" : "policy";
5160
5256
  return {
5161
5257
  schemaVersion: CURRENT_SCHEMA_VERSION2,
5162
- cliVersion: CLI_VERSION3,
5258
+ cliVersion: CLI_VERSION4,
5163
5259
  contract: "shipguard-scan-result",
5164
5260
  recommendation: {
5165
5261
  field: "recommendation",
@@ -5198,7 +5294,10 @@ function buildSchemaContract(limits) {
5198
5294
  { code: "PRO_RULES_UNAVAILABLE", meaning: "Pro rules could not be fetched (auth, credits, rate limit, network)." },
5199
5295
  { code: "INVALID_UTF8", meaning: "One or more files were not valid UTF-8 and were skipped rather than mangled." },
5200
5296
  { code: "UNREADABLE_FILE", meaning: "One or more files could not be read from disk." },
5201
- { code: "COMPILE_FAILURE", meaning: "A Pro rule bundle failed to compile; the whole bundle was refused rather than partly run." }
5297
+ { code: "COMPILE_FAILURE", meaning: "A Pro rule bundle failed to compile; the whole bundle was refused rather than partly run." },
5298
+ { code: "SYMLINK_SKIPPED", meaning: "One or more symlinks were not followed (privacy) and were not scanned." },
5299
+ { code: "UNSCANNED_UNKNOWN_BINARY", meaning: "One or more files hold NUL or control data that no text reading explains and show no sign of a known binary format; they were not scanned. Add their paths to ignore.paths if they are safe." },
5300
+ { code: "NO_FILES_SCANNED", meaning: "Zero files were scanned (empty tree, everything ignored or binary, or --changed on a clean checkout). A scan that read nothing is never SAFE_TO_SHIP." }
5202
5301
  ],
5203
5302
  limits: {
5204
5303
  maxFiles: {
@@ -5228,9 +5327,33 @@ function buildSchemaContract(limits) {
5228
5327
  unanalyzableTypes: [
5229
5328
  {
5230
5329
  type: "binary",
5231
- behavior: "Skipped. A binary file has no source to scan.",
5232
- // Deliberately no degrade signal: a binary skip is normal, not incomplete coverage.
5233
- machineSignal: null,
5330
+ behavior: "Real binaries (known format AND mostly non-printable content) are skipped and counted. The file name and extension are never used. SQLite and TAR files are scanned through their ASCII strings.",
5331
+ // Counted, not degraded, except when nothing at all was scanned (NO_FILES_SCANNED).
5332
+ machineSignal: 'coverage.skipped.binary (no degrade); degradedReasons[].code === "NO_FILES_SCANNED" when nothing was scanned',
5333
+ verifiedBy: null
5334
+ },
5335
+ {
5336
+ type: "utf16",
5337
+ behavior: "Decoded and scanned (BOM, and BOM-less when the bytes fit UTF-16). Findings use code-unit columns of the decoded text.",
5338
+ machineSignal: "coverage.decoded.utf16",
5339
+ verifiedBy: null
5340
+ },
5341
+ {
5342
+ type: "nul-in-text",
5343
+ behavior: "A text file with a few stray NUL bytes is scanned with each NUL read as one space (lines and columns unchanged). A key split by a NUL byte is not matched.",
5344
+ machineSignal: "coverage.decoded.nulSubstituted",
5345
+ verifiedBy: null
5346
+ },
5347
+ {
5348
+ type: "unknown-binary",
5349
+ behavior: "NUL or control data that no reading explains and with no real-binary evidence: skipped and the scan is degraded.",
5350
+ machineSignal: 'degradedReasons[].code === "UNSCANNED_UNKNOWN_BINARY"',
5351
+ verifiedBy: null
5352
+ },
5353
+ {
5354
+ type: "special",
5355
+ behavior: "FIFO, socket and device nodes hold no stored content: counted, not read, not degraded.",
5356
+ machineSignal: "coverage.skipped.special",
5234
5357
  verifiedBy: null
5235
5358
  },
5236
5359
  {
@@ -5242,7 +5365,7 @@ function buildSchemaContract(limits) {
5242
5365
  {
5243
5366
  type: "symlink",
5244
5367
  behavior: "Never followed. A symlink pointing out of the project root is refused.",
5245
- machineSignal: 'degradedReasons[].code === "UNREADABLE_FILE" when the path was reported as changed',
5368
+ machineSignal: 'degradedReasons[].code === "SYMLINK_SKIPPED" (full scan); "UNREADABLE_FILE" when a changed path resolves outside the root',
5246
5369
  verifiedBy: null
5247
5370
  },
5248
5371
  {
@@ -5253,8 +5376,8 @@ function buildSchemaContract(limits) {
5253
5376
  },
5254
5377
  {
5255
5378
  type: "ignored-by-default",
5256
- behavior: "Not collected: node_modules, dist, build, .next, coverage, .git, lockfiles, images/archives/media, and ShipGuard\u2019s own artifacts.",
5257
- machineSignal: null,
5379
+ behavior: "Not collected: node_modules, dist, build, .next, coverage, .git, vendor, tmp, out, lockfiles, *.log, *.min.js, *.map and ShipGuard\u2019s own artifacts. Images and other media are NOT ignored: they are classified by content.",
5380
+ machineSignal: "coverage.ignoredByDefault (counts per rule); coverage.ignoredByUser",
5258
5381
  verifiedBy: null
5259
5382
  }
5260
5383
  ],
@@ -5499,6 +5622,7 @@ process.on("uncaughtException", handleUncaughtException);
5499
5622
  process.on("unhandledRejection", handleUnhandledRejection);
5500
5623
  process.on("SIGINT", handleSignal);
5501
5624
  process.on("SIGTERM", handleSignal);
5625
+ installStreamErrorHandlers();
5502
5626
  var ISSUES_URL4 = "https://github.com/agenticcli/shipguard/issues";
5503
5627
  var program = new Command11();
5504
5628
  var rawArgs = process.argv.slice(2);
@@ -5506,13 +5630,17 @@ if (rawArgs[0] === "?") {
5506
5630
  process.argv = [process.argv[0], process.argv[1], "help"];
5507
5631
  }
5508
5632
  program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
5509
- true ? "0.8.1" : process.env.npm_package_version ?? "0.0.0-dev"
5633
+ true ? "0.10.0-rc.0" : process.env.npm_package_version ?? "0.0.0-dev"
5510
5634
  ).helpCommand(false).addHelpText("after", `
5511
5635
  Learn more:
5512
5636
  Docs ${goLink("docs")}
5513
5637
  Site ${goLink("site")}
5514
5638
  Pricing ${goLink("pricing")}
5515
5639
  Issues ${ISSUES_URL4}`);
5640
+ program.hook("preAction", async (_thisCommand, actionCommand) => {
5641
+ if (actionCommand.name() === "telemetry" || actionCommand.parent?.name() === "telemetry") return;
5642
+ await sendLifecycleEvent("cli_first_run", { cliVersion: CLI_VERSION }, { projectDir: process.cwd() });
5643
+ });
5516
5644
  program.exitOverride();
5517
5645
  function addSubcommand(cmd) {
5518
5646
  cmd.exitOverride();
@@ -5583,6 +5711,7 @@ function closestCommand(input) {
5583
5711
  }
5584
5712
  try {
5585
5713
  await program.parseAsync(process.argv);
5714
+ exitWhenDrained();
5586
5715
  } catch (err) {
5587
5716
  if (err instanceof CommanderError) {
5588
5717
  if (err.code === "commander.unknownCommand") {