@agenticcli/shipguard 0.4.1 → 0.5.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
@@ -6,30 +6,32 @@ import {
6
6
  clearCredentials,
7
7
  databaseCheck,
8
8
  deploymentCheck,
9
+ deriveBlocking,
9
10
  getAuthToken,
10
11
  isTokenExpired,
11
12
  loadChecksumManifest,
12
13
  loadCredentials,
14
+ logger,
13
15
  payments,
14
16
  runProRulesWithDispatch,
15
17
  saveCredentials,
16
18
  secretsCheck
17
- } from "./chunk-5UMQEPDN.js";
19
+ } from "./chunk-LD3EQSPU.js";
18
20
  import {
19
21
  DEFAULT_MAX_FILES,
20
22
  DEFAULT_MAX_FILE_SIZE_BYTES,
21
23
  DEFAULT_MAX_TOTAL_BYTES,
22
24
  readFiles
23
- } from "./chunk-ALFVS2BH.js";
25
+ } from "./chunk-QUBEIHTH.js";
24
26
  import {
25
27
  decodeUtf8Strict,
26
28
  detectBinary,
27
29
  normalizeNewlines,
28
30
  stripBom
29
- } from "./chunk-ANTCYKRO.js";
31
+ } from "./chunk-5T42QTNT.js";
30
32
 
31
33
  // src/cli.ts
32
- import { Command as Command7, CommanderError } from "commander";
34
+ import { Command as Command8, CommanderError } from "commander";
33
35
 
34
36
  // src/commands/init.ts
35
37
  import { Command } from "commander";
@@ -56,6 +58,11 @@ var EXIT_CODES = {
56
58
  var DEFAULT_POLICY_PATH = "shipguard.policy.yml";
57
59
  var DEFAULT_REPORT_DIR = ".shipguard/reports";
58
60
  var DEFAULT_REPORT_FILE = ".shipguard/reports/latest.md";
61
+ var DEFAULT_HISTORY_PATH = ".shipguard/history.db";
62
+ var HISTORY_PATH_ENV_VAR = "SHIPGUARD_HISTORY_PATH";
63
+ var DEFAULT_REPO_ID_FALLBACK_PATH = ".shipguard/repo-id";
64
+ var DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES = 30;
65
+ var SCAN_ID_REUSE_WINDOW_ENV_VAR = "SHIPGUARD_SCAN_ID_REUSE_WINDOW_MINUTES";
59
66
 
60
67
  // src/utils/paths.ts
61
68
  import { resolve } from "path";
@@ -144,36 +151,6 @@ async function createShipguardDir(dir) {
144
151
  await mkdir(reportDir, { recursive: true });
145
152
  }
146
153
 
147
- // src/utils/logger.ts
148
- import chalk from "chalk";
149
- var logger = {
150
- info: (msg) => console.error(chalk.blue("\u2139"), msg),
151
- success: (msg) => console.error(chalk.green("\u2713"), msg),
152
- warn: (msg) => console.error(chalk.yellow("\u26A0"), msg),
153
- error: (msg) => console.error(chalk.red("\u2717"), msg),
154
- finding: (severity, msg) => {
155
- const colors = {
156
- critical: chalk.bgRed.white,
157
- high: chalk.red,
158
- medium: chalk.yellow,
159
- low: chalk.blue,
160
- info: chalk.gray
161
- };
162
- const colorFn = colors[severity] || chalk.white;
163
- const label = severity.toUpperCase().padEnd(8);
164
- console.error(` ${colorFn(label)} ${msg}`);
165
- },
166
- score: (score, recommendation) => {
167
- const color = score <= 20 ? chalk.green : score <= 50 ? chalk.yellow : chalk.red;
168
- const icon = score <= 20 ? "\u2713" : score <= 50 ? "\u26A0" : "\u2717";
169
- console.error("");
170
- console.error(chalk.bold("ShipGuard Scan Result"));
171
- console.error(`Risk Score: ${color(`${score}/100`)}`);
172
- console.error(`Status: ${color(`${icon} ${recommendation.replace(/_/g, " ")}`)}`);
173
- },
174
- divider: () => console.error(chalk.gray("\u2500".repeat(50)))
175
- };
176
-
177
154
  // src/commands/init.ts
178
155
  function initCommand() {
179
156
  return new Command("init").description("Initialize ShipGuard in your project").action(async () => {
@@ -197,9 +174,8 @@ function initCommand() {
197
174
 
198
175
  // src/commands/scan.ts
199
176
  import { Command as Command2 } from "commander";
200
- import { randomUUID } from "crypto";
201
- import { existsSync as existsSync3 } from "fs";
202
- import { join as join5, resolve as resolve3 } from "path";
177
+ import { existsSync as existsSync5 } from "fs";
178
+ import { join as join6, resolve as resolve4 } from "path";
203
179
 
204
180
  // src/core/scanner.ts
205
181
  import { readFile as readFile2, stat, realpath } from "fs/promises";
@@ -258,41 +234,57 @@ function computeRiskScore(findings) {
258
234
  }
259
235
 
260
236
  // src/core/git.ts
261
- import { execSync } from "child_process";
237
+ import { execFileSync } from "child_process";
262
238
  function isGitRepo(dir) {
263
239
  try {
264
- execSync("git rev-parse --is-inside-work-tree", { cwd: dir, stdio: "pipe" });
240
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd: dir, stdio: "pipe" });
265
241
  return true;
266
242
  } catch {
267
243
  return false;
268
244
  }
269
245
  }
270
- function getChangedFiles(dir) {
246
+ var GitCommandError = class extends Error {
247
+ constructor(command, stderr) {
248
+ super(`git command failed: ${command}${stderr ? ` \u2014 ${stderr.trim()}` : ""}`);
249
+ this.command = command;
250
+ this.stderr = stderr;
251
+ this.name = "GitCommandError";
252
+ }
253
+ command;
254
+ stderr;
255
+ };
256
+ function runGit(dir, args) {
257
+ const command = `git ${args.join(" ")}`;
271
258
  try {
272
- const diffOutput = execSync("git diff --name-only HEAD 2>/dev/null || git diff --name-only", {
273
- cwd: dir,
274
- encoding: "utf-8",
275
- stdio: ["pipe", "pipe", "pipe"]
276
- });
277
- const stagedOutput = execSync("git diff --cached --name-only", {
278
- cwd: dir,
279
- encoding: "utf-8",
280
- stdio: ["pipe", "pipe", "pipe"]
281
- });
282
- const untrackedOutput = execSync("git ls-files --others --exclude-standard", {
259
+ return execFileSync("git", args, {
283
260
  cwd: dir,
284
261
  encoding: "utf-8",
285
262
  stdio: ["pipe", "pipe", "pipe"]
286
263
  });
287
- const allFiles = /* @__PURE__ */ new Set();
288
- const outputs = [diffOutput, stagedOutput, untrackedOutput];
289
- for (const output of outputs) {
290
- output.split("\n").map((f) => f.trim()).filter(Boolean).forEach((f) => allFiles.add(f));
264
+ } catch (err) {
265
+ const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : err instanceof Error ? err.message : String(err);
266
+ throw new GitCommandError(command, stderr);
267
+ }
268
+ }
269
+ function getChangedFiles(dir) {
270
+ let diffOutput;
271
+ try {
272
+ diffOutput = runGit(dir, ["diff", "--name-only", "HEAD"]);
273
+ } catch (err) {
274
+ if (err instanceof GitCommandError && /unknown revision|ambiguous argument|bad revision/i.test(err.stderr)) {
275
+ diffOutput = "";
276
+ } else {
277
+ throw err;
291
278
  }
292
- return [...allFiles];
293
- } catch {
294
- return [];
295
279
  }
280
+ const stagedOutput = runGit(dir, ["diff", "--cached", "--name-only"]);
281
+ const untrackedOutput = runGit(dir, ["ls-files", "--others", "--exclude-standard"]);
282
+ const allFiles = /* @__PURE__ */ new Set();
283
+ const outputs = [diffOutput, stagedOutput, untrackedOutput];
284
+ for (const output of outputs) {
285
+ output.split("\n").map((f) => f.trim()).filter(Boolean).forEach((f) => allFiles.add(f));
286
+ }
287
+ return [...allFiles];
296
288
  }
297
289
 
298
290
  // src/core/scanner.ts
@@ -325,6 +317,9 @@ async function scan(options, proRules, onProgress) {
325
317
  const changedUnreadable = [];
326
318
  if (options.changedOnly && isGitRepo(cwd)) {
327
319
  const changedRelPaths = getChangedFiles(cwd);
320
+ if (changedRelPaths.length === 0) {
321
+ logger.info("--changed: git ran successfully \u2014 0 changed files to scan.");
322
+ }
328
323
  const filteredPaths = changedRelPaths.filter(
329
324
  (rp) => !DEFAULT_IGNORE.some((pat) => {
330
325
  const prefix = pat.replace("/**", "");
@@ -711,7 +706,7 @@ function toSarif(result) {
711
706
  }
712
707
 
713
708
  // src/core/render.ts
714
- import chalk2 from "chalk";
709
+ import chalk from "chalk";
715
710
  import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
716
711
  import { join as join4, basename as basename2 } from "path";
717
712
  import { homedir } from "os";
@@ -741,37 +736,37 @@ function quickstartHelp(isTTY) {
741
736
  const lines = [];
742
737
  if (isTTY) {
743
738
  lines.push("");
744
- 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"));
745
- lines.push(chalk2.bold.cyan(" \u2502") + chalk2.bold(" \u{1F6E1} ShipGuard \u2014 CLI-first release gate for AI-built apps ") + chalk2.bold.cyan(" \u2502"));
746
- lines.push(chalk2.bold.cyan(" \u2502") + " Catches secrets, auth gaps, and deployment issues before you ship " + chalk2.bold.cyan(" \u2502"));
747
- 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"));
739
+ lines.push(chalk.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"));
740
+ lines.push(chalk.bold.cyan(" \u2502") + chalk.bold(" \u{1F6E1} ShipGuard \u2014 CLI-first release gate for AI-built apps ") + chalk.bold.cyan(" \u2502"));
741
+ lines.push(chalk.bold.cyan(" \u2502") + " Catches secrets, auth gaps, and deployment issues before you ship " + chalk.bold.cyan(" \u2502"));
742
+ lines.push(chalk.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"));
748
743
  lines.push("");
749
- lines.push(chalk2.bold(" Get started in 2 commands:"));
744
+ lines.push(chalk.bold(" Get started in 2 commands:"));
750
745
  lines.push("");
751
- lines.push(` ${chalk2.green("npx @agenticcli/shipguard scan")} ${chalk2.dim("# zero install \u2014 scan right now")}`);
752
- lines.push(` ${chalk2.green("shipguard scan --strict")} ${chalk2.dim("# CI mode: exit 1 on blocking issues")}`);
746
+ lines.push(` ${chalk.green("npx @agenticcli/shipguard scan")} ${chalk.dim("# zero install \u2014 scan right now")}`);
747
+ lines.push(` ${chalk.green("shipguard scan --strict")} ${chalk.dim("# CI mode: exit 1 on blocking issues")}`);
753
748
  lines.push("");
754
- lines.push(chalk2.bold(" Commands:"));
749
+ lines.push(chalk.bold(" Commands:"));
755
750
  lines.push("");
756
- lines.push(` ${chalk2.cyan("scan")} ${chalk2.dim("[path]")} Scan a project for high-risk issues`);
757
- lines.push(` ${chalk2.cyan("init")} Generate a .shipguard.yml policy file`);
758
- lines.push(` ${chalk2.cyan("login")} Authenticate to unlock Pro rules`);
759
- lines.push(` ${chalk2.cyan("logout")} Remove saved credentials`);
760
- lines.push(` ${chalk2.cyan("status")} Show auth status and credits`);
761
- lines.push(` ${chalk2.cyan("feedback")} ${chalk2.dim("<text>")} Send feedback on your last scan`);
762
- lines.push(` ${chalk2.cyan("rate")} ${chalk2.dim("<id> up|down")} Rate a rule finding`);
763
- lines.push(` ${chalk2.cyan("help")} ${chalk2.dim("/ ?")} Show this screen`);
751
+ lines.push(` ${chalk.cyan("scan")} ${chalk.dim("[path]")} Scan a project for high-risk issues`);
752
+ lines.push(` ${chalk.cyan("init")} Generate a .shipguard.yml policy file`);
753
+ lines.push(` ${chalk.cyan("login")} Authenticate to unlock Pro rules`);
754
+ lines.push(` ${chalk.cyan("logout")} Remove saved credentials`);
755
+ lines.push(` ${chalk.cyan("status")} Show auth status and credits`);
756
+ lines.push(` ${chalk.cyan("feedback")} ${chalk.dim("<text>")} Send feedback on your last scan`);
757
+ lines.push(` ${chalk.cyan("rate")} ${chalk.dim("<id> up|down")} Rate a rule finding`);
758
+ lines.push(` ${chalk.cyan("help")} ${chalk.dim("/ ?")} Show this screen`);
764
759
  lines.push("");
765
- lines.push(chalk2.bold(" Exit codes:"));
766
- lines.push(` ${chalk2.green("0")} Safe \u2014 no blocking findings`);
767
- lines.push(` ${chalk2.yellow("1")} Blocked \u2014 strict mode + blocking findings`);
768
- lines.push(` ${chalk2.red("2")} Config error / degraded scan`);
769
- lines.push(` ${chalk2.red("3")} Runtime error`);
760
+ lines.push(chalk.bold(" Exit codes (verdict-neutral \u2014 read the JSON for the verdict):"));
761
+ lines.push(` ${chalk.green("0")} Scan completed \u2014 verdict is in the JSON \`recommendation\` field`);
762
+ lines.push(` ${chalk.yellow("1")} Blocked \u2014 ONLY with --strict + blocking findings`);
763
+ lines.push(` ${chalk.red("2")} Config error`);
764
+ lines.push(` ${chalk.red("3")} Runtime error \u2014 scan could not meaningfully run`);
770
765
  lines.push("");
771
- lines.push(` ${chalk2.dim("Docs")} ${chalk2.underline(DOCS_URL)}`);
772
- lines.push(` ${chalk2.dim("Site")} ${chalk2.underline(SITE_URL)}`);
773
- lines.push(` ${chalk2.dim("Pricing")} ${chalk2.underline(PRICING_URL)}`);
774
- lines.push(` ${chalk2.dim("Issues")} ${chalk2.underline(ISSUES_URL)}`);
766
+ lines.push(` ${chalk.dim("Docs")} ${chalk.underline(DOCS_URL)}`);
767
+ lines.push(` ${chalk.dim("Site")} ${chalk.underline(SITE_URL)}`);
768
+ lines.push(` ${chalk.dim("Pricing")} ${chalk.underline(PRICING_URL)}`);
769
+ lines.push(` ${chalk.dim("Issues")} ${chalk.underline(ISSUES_URL)}`);
775
770
  lines.push("");
776
771
  } else {
777
772
  lines.push("");
@@ -793,7 +788,7 @@ function quickstartHelp(isTTY) {
793
788
  lines.push(" rate <id> up|down Rate a finding");
794
789
  lines.push(" help / ? Show this screen");
795
790
  lines.push("");
796
- lines.push(" Exit codes: 0=safe 1=blocked 2=config-error 3=runtime-error");
791
+ lines.push(" Exit codes: 0=completed (verdict in JSON) 1=blocked (--strict only) 2=config-error 3=runtime-error");
797
792
  lines.push("");
798
793
  lines.push(` Docs: ${DOCS_URL}`);
799
794
  lines.push(` Site: ${SITE_URL}`);
@@ -819,28 +814,28 @@ function renderProgressBar(current, total, width = 20, currentFile) {
819
814
  const fraction = total > 0 ? Math.min(current / total, 1) : 0;
820
815
  const filled = Math.round(fraction * width);
821
816
  const empty = width - filled;
822
- const bar = chalk2.cyan(BAR_FULL.repeat(filled)) + chalk2.gray(BAR_EMPTY.repeat(empty));
817
+ const bar = chalk.cyan(BAR_FULL.repeat(filled)) + chalk.gray(BAR_EMPTY.repeat(empty));
823
818
  const counter = `${current}/${total}`;
824
- const fileHint = currentFile ? ` ${chalk2.dim(basename2(currentFile) || truncatePath(currentFile, 30))}` : "";
825
- return `${chalk2.cyan("\u{1F50D}")} scanning [${bar}] ${chalk2.bold(counter)}${fileHint}`;
819
+ const fileHint = currentFile ? ` ${chalk.dim(basename2(currentFile) || truncatePath(currentFile, 30))}` : "";
820
+ return `${chalk.cyan("\u{1F50D}")} scanning [${bar}] ${chalk.bold(counter)}${fileHint}`;
826
821
  }
827
822
  function shouldShowProgress(gates) {
828
823
  return gates.isTTY && !gates.quiet && !gates.machineOutput;
829
824
  }
830
825
  var SEVERITY_COLORS = {
831
- critical: chalk2.bgRed.white,
832
- high: chalk2.red,
833
- medium: chalk2.yellow,
834
- low: chalk2.blue,
835
- info: chalk2.gray
826
+ critical: chalk.bgRed.white,
827
+ high: chalk.red,
828
+ medium: chalk.yellow,
829
+ low: chalk.blue,
830
+ info: chalk.gray
836
831
  };
837
832
  function renderFindingsSummary(findings) {
838
833
  if (findings.length === 0) {
839
- return chalk2.green(" \u2713 No findings detected \u2014 clean scan.");
834
+ return chalk.green(" \u2713 No findings detected \u2014 clean scan.");
840
835
  }
841
836
  const lines = [];
842
837
  lines.push(
843
- chalk2.dim(
838
+ chalk.dim(
844
839
  " Confidence legend: HIGH \u2192 low false-positive chance MEDIUM \u2192 moderate \u2014 review LOW \u2192 higher false-positive"
845
840
  )
846
841
  );
@@ -848,15 +843,15 @@ function renderFindingsSummary(findings) {
848
843
  for (const sev of SEVERITY_ORDER) {
849
844
  const group = findings.filter((f) => f.severity === sev);
850
845
  if (group.length === 0) continue;
851
- const colorFn = SEVERITY_COLORS[sev] || chalk2.white;
846
+ const colorFn = SEVERITY_COLORS[sev] || chalk.white;
852
847
  const icon = SEVERITY_ICONS[sev] ?? "";
853
848
  lines.push(` ${colorFn(` ${sev.toUpperCase().padEnd(8)} `)} ${icon} ${group.length} finding${group.length !== 1 ? "s" : ""}`);
854
849
  for (const f of group) {
855
850
  const location = f.line != null ? `${f.file}:${f.line}` : f.file;
856
- const fpLabel = chalk2.dim(`[${findingFpLabel(f.confidence)}]`);
857
- lines.push(` ${chalk2.bold(f.title)} \u2014 ${chalk2.cyan(location)} ${fpLabel}`);
851
+ const fpLabel = chalk.dim(`[${findingFpLabel(f.confidence)}]`);
852
+ lines.push(` ${chalk.bold(f.title)} \u2014 ${chalk.cyan(location)} ${fpLabel}`);
858
853
  if (f.evidence) {
859
- lines.push(` Evidence: ${chalk2.yellow(truncate(f.evidence, 100))}`);
854
+ lines.push(` Evidence: ${chalk.yellow(truncate(f.evidence, 100))}`);
860
855
  }
861
856
  }
862
857
  lines.push("");
@@ -865,49 +860,49 @@ function renderFindingsSummary(findings) {
865
860
  }
866
861
  function findingsByCategoryTable(findings) {
867
862
  if (findings.length === 0) {
868
- return chalk2.dim(" No findings across any category.");
863
+ return chalk.dim(" No findings across any category.");
869
864
  }
870
865
  const catCounts = {};
871
866
  for (const f of findings) {
872
867
  catCounts[f.category] = (catCounts[f.category] ?? 0) + 1;
873
868
  }
874
869
  const lines = [];
875
- lines.push(chalk2.bold(" Category breakdown:"));
870
+ lines.push(chalk.bold(" Category breakdown:"));
876
871
  for (const [cat, count] of Object.entries(catCounts).sort()) {
877
- const bar = chalk2.cyan("\u25A0".repeat(Math.min(count, 10)));
872
+ const bar = chalk.cyan("\u25A0".repeat(Math.min(count, 10)));
878
873
  lines.push(` ${cat.padEnd(14)} ${String(count).padStart(3)} ${bar}`);
879
874
  }
880
875
  return lines.join("\n");
881
876
  }
882
877
  function coverageLine() {
883
- return chalk2.dim(
878
+ return chalk.dim(
884
879
  ` Coverage: secrets, auth, payments, database, deployment (free tier).
885
880
  Deeper agentic rules available via Pro \u2014 some issue classes may be missed on free.
886
- Upgrade: ${chalk2.underline(PRICING_URL)}`
881
+ Upgrade: ${chalk.underline(PRICING_URL)}`
887
882
  );
888
883
  }
889
884
  var VERDICT_CONFIG = {
890
885
  SAFE_TO_SHIP: {
891
886
  icon: "\u2705",
892
- color: chalk2.greenBright,
887
+ color: chalk.greenBright,
893
888
  label: "SAFE TO SHIP",
894
889
  // Deterministic verdict message — no RNG so tests are stable
895
- attitudeLine: () => chalk2.green(" SHIP IT \u2014 nothing blocking. Go make something people want."),
896
- 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.")
890
+ attitudeLine: () => chalk.green(" SHIP IT \u2014 nothing blocking. Go make something people want."),
891
+ helpLine: (blockingCount) => blockingCount > 0 ? chalk.green(` No blocking issues \u2014 ${blockingCount} informational finding(s) noted.`) : chalk.green(" Clean \u2014 safe to ship. No issues found.")
897
892
  },
898
893
  REVIEW_BEFORE_SHIP: {
899
894
  icon: "\u26A0\uFE0F",
900
- color: chalk2.yellowBright,
895
+ color: chalk.yellowBright,
901
896
  label: "REVIEW BEFORE SHIP",
902
- attitudeLine: (blockingCount) => chalk2.yellow(` HOLD UP \u2014 ${blockingCount} finding${blockingCount !== 1 ? "s" : ""} want eyes before this ships.`),
903
- helpLine: (blockingCount) => chalk2.yellow(` ${blockingCount} finding(s) need attention before shipping.`)
897
+ attitudeLine: (blockingCount) => chalk.yellow(` HOLD UP \u2014 ${blockingCount} finding${blockingCount !== 1 ? "s" : ""} want eyes before this ships.`),
898
+ helpLine: (blockingCount) => chalk.yellow(` ${blockingCount} finding(s) need attention before shipping.`)
904
899
  },
905
900
  DO_NOT_SHIP: {
906
901
  icon: "\u{1F6D1}",
907
- color: chalk2.redBright,
902
+ color: chalk.redBright,
908
903
  label: "DO NOT SHIP",
909
- attitudeLine: () => chalk2.red(" BLOCKED \u2014 shipping this would hurt. Fix the criticals first."),
910
- helpLine: (blockingCount) => chalk2.red(` Blocked: ${blockingCount} critical/blocking issue(s) must be fixed first.`)
904
+ attitudeLine: () => chalk.red(" BLOCKED \u2014 shipping this would hurt. Fix the criticals first."),
905
+ helpLine: (blockingCount) => chalk.red(` Blocked: ${blockingCount} critical/blocking issue(s) must be fixed first.`)
911
906
  }
912
907
  };
913
908
  function boxLine(content) {
@@ -920,23 +915,23 @@ function boxEmpty() {
920
915
  return `${V}${" ".repeat(BOX_WIDTH - 2)}${V}`;
921
916
  }
922
917
  function boxTop() {
923
- return chalk2.dim(TL + H.repeat(BOX_WIDTH - 2) + TR);
918
+ return chalk.dim(TL + H.repeat(BOX_WIDTH - 2) + TR);
924
919
  }
925
920
  function boxBottom() {
926
- return chalk2.dim(BL + H.repeat(BOX_WIDTH - 2) + BR);
921
+ return chalk.dim(BL + H.repeat(BOX_WIDTH - 2) + BR);
927
922
  }
928
923
  function boxSection() {
929
- return chalk2.dim(SECTION);
924
+ return chalk.dim(SECTION);
930
925
  }
931
926
  function severityBar(riskScore, barWidth = 30) {
932
927
  const total = riskScore.totalFindings;
933
- if (total === 0) return chalk2.green(" " + BAR_FULL.repeat(barWidth) + " all clear");
928
+ if (total === 0) return chalk.green(" " + BAR_FULL.repeat(barWidth) + " all clear");
934
929
  const counts = [
935
- { sev: "critical", count: riskScore.criticalCount, color: chalk2.bgRed.white },
936
- { sev: "high", count: riskScore.highCount, color: chalk2.red },
937
- { sev: "medium", count: riskScore.mediumCount, color: chalk2.yellow },
938
- { sev: "low", count: riskScore.lowCount, color: chalk2.blue },
939
- { sev: "info", count: riskScore.infoCount, color: chalk2.gray }
930
+ { sev: "critical", count: riskScore.criticalCount, color: chalk.bgRed.white },
931
+ { sev: "high", count: riskScore.highCount, color: chalk.red },
932
+ { sev: "medium", count: riskScore.mediumCount, color: chalk.yellow },
933
+ { sev: "low", count: riskScore.lowCount, color: chalk.blue },
934
+ { sev: "info", count: riskScore.infoCount, color: chalk.gray }
940
935
  ].filter((c) => c.count > 0);
941
936
  let assigned = 0;
942
937
  const segments = [];
@@ -954,47 +949,50 @@ function severityBar(riskScore, barWidth = 30) {
954
949
  }).join(" ");
955
950
  return ` ${bar} ${legend}`;
956
951
  }
957
- function verdictPanel(result, elapsedMs, skippedCount, topFindings) {
952
+ function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict) {
958
953
  const { riskScore, filesScanned } = result;
959
954
  const recommendation = riskScore.recommendation;
960
955
  const cfg = VERDICT_CONFIG[recommendation];
961
956
  const elapsedStr = elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s`;
962
957
  const lines = [""];
963
958
  lines.push(boxTop());
964
- lines.push(boxLine(chalk2.bold(" ShipGuard \u2014 Release Gate Report")));
959
+ lines.push(boxLine(chalk.bold(" ShipGuard \u2014 Release Gate Report")));
965
960
  lines.push(boxEmpty());
966
- const verdictLabel = cfg.color(chalk2.bold(`${cfg.icon} ${cfg.label}`));
961
+ const verdictLabel = cfg.color(chalk.bold(`${cfg.icon} ${cfg.label}`));
967
962
  lines.push(boxLine(` ${verdictLabel}`));
963
+ if (riskScore.blockingCount > 0 && !strict) {
964
+ lines.push(boxLine(chalk.dim(" (informational \u2014 exit 0; use --strict to enforce as exit 1)")));
965
+ }
968
966
  lines.push(boxEmpty());
969
967
  const attitudeLine2 = recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
970
968
  lines.push(boxLine(attitudeLine2));
971
969
  lines.push(boxEmpty());
972
970
  lines.push(boxSection());
973
- lines.push(boxLine(chalk2.bold(" Severity breakdown")));
971
+ lines.push(boxLine(chalk.bold(" Severity breakdown")));
974
972
  lines.push(boxLine(severityBar(riskScore)));
975
973
  lines.push(boxSection());
976
- lines.push(boxLine(chalk2.bold(" Run summary")));
977
- const skippedSuffix = skippedCount && skippedCount > 0 ? chalk2.dim(` (${skippedCount} skipped)`) : "";
978
- lines.push(boxLine(` Files scanned: ${chalk2.cyan(filesScanned)}${skippedSuffix}`));
979
- lines.push(boxLine(` Elapsed time: ${chalk2.cyan(elapsedStr)}`));
980
- lines.push(boxLine(` Total findings: ${chalk2.cyan(riskScore.totalFindings)}`));
974
+ lines.push(boxLine(chalk.bold(" Run summary")));
975
+ const skippedSuffix = skippedCount && skippedCount > 0 ? chalk.dim(` (${skippedCount} skipped)`) : "";
976
+ lines.push(boxLine(` Files scanned: ${chalk.cyan(filesScanned)}${skippedSuffix}`));
977
+ lines.push(boxLine(` Elapsed time: ${chalk.cyan(elapsedStr)}`));
978
+ lines.push(boxLine(` Total findings: ${chalk.cyan(riskScore.totalFindings)}`));
981
979
  const sevLines = [];
982
- if (riskScore.criticalCount > 0) sevLines.push(chalk2.red(`\u{1F6D1} ${riskScore.criticalCount} critical`));
983
- if (riskScore.highCount > 0) sevLines.push(chalk2.red(`\u26D4 ${riskScore.highCount} high`));
984
- if (riskScore.mediumCount > 0) sevLines.push(chalk2.yellow(`\u26A0\uFE0F ${riskScore.mediumCount} medium`));
985
- if (riskScore.lowCount > 0) sevLines.push(chalk2.blue(`\u{1F41B} ${riskScore.lowCount} low`));
986
- if (riskScore.infoCount > 0) sevLines.push(chalk2.gray(`\u2139\uFE0F ${riskScore.infoCount} info`));
980
+ if (riskScore.criticalCount > 0) sevLines.push(chalk.red(`\u{1F6D1} ${riskScore.criticalCount} critical`));
981
+ if (riskScore.highCount > 0) sevLines.push(chalk.red(`\u26D4 ${riskScore.highCount} high`));
982
+ if (riskScore.mediumCount > 0) sevLines.push(chalk.yellow(`\u26A0\uFE0F ${riskScore.mediumCount} medium`));
983
+ if (riskScore.lowCount > 0) sevLines.push(chalk.blue(`\u{1F41B} ${riskScore.lowCount} low`));
984
+ if (riskScore.infoCount > 0) sevLines.push(chalk.gray(`\u2139\uFE0F ${riskScore.infoCount} info`));
987
985
  if (sevLines.length > 0) {
988
986
  lines.push(boxLine(` ${sevLines.join(" ")}`));
989
987
  }
990
988
  lines.push(boxSection());
991
- lines.push(boxLine(chalk2.bold(" How ShipGuard helped")));
989
+ lines.push(boxLine(chalk.bold(" How ShipGuard helped")));
992
990
  lines.push(boxLine(cfg.helpLine(riskScore.blockingCount)));
993
991
  lines.push(boxSection());
994
- lines.push(boxLine(chalk2.bold(" Learn more")));
995
- lines.push(boxLine(` Docs ${chalk2.underline(DOCS_URL)}`));
996
- lines.push(boxLine(` Site ${chalk2.underline(SITE_URL)}`));
997
- lines.push(boxLine(` Pricing ${chalk2.underline(PRICING_URL)}`));
992
+ lines.push(boxLine(chalk.bold(" Learn more")));
993
+ lines.push(boxLine(` Docs ${chalk.underline(DOCS_URL)}`));
994
+ lines.push(boxLine(` Site ${chalk.underline(SITE_URL)}`));
995
+ lines.push(boxLine(` Pricing ${chalk.underline(PRICING_URL)}`));
998
996
  lines.push(boxEmpty());
999
997
  lines.push(boxBottom());
1000
998
  lines.push("");
@@ -1003,23 +1001,23 @@ function verdictPanel(result, elapsedMs, skippedCount, topFindings) {
1003
1001
  function actionFooter(opts) {
1004
1002
  const { hasFindings, topRuleId, isLoggedIn } = opts;
1005
1003
  const lines = [""];
1006
- 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"));
1004
+ lines.push(chalk.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"));
1007
1005
  lines.push("");
1008
- lines.push(` ${chalk2.cyan("shipguard report")} ${chalk2.dim("# open the full report")}`);
1006
+ lines.push(` ${chalk.cyan("shipguard report")} ${chalk.dim("# open the full report")}`);
1009
1007
  if (hasFindings && topRuleId) {
1010
- lines.push(` ${chalk2.cyan(`shipguard rate ${topRuleId} up`)} ${chalk2.dim("# was this finding helpful?")}`);
1011
- lines.push(` ${chalk2.cyan(`shipguard rate ${topRuleId} down`)} ${chalk2.dim("# false positive?")}`);
1008
+ lines.push(` ${chalk.cyan(`shipguard rate ${topRuleId} up`)} ${chalk.dim("# was this finding helpful?")}`);
1009
+ lines.push(` ${chalk.cyan(`shipguard rate ${topRuleId} down`)} ${chalk.dim("# false positive?")}`);
1012
1010
  } else if (hasFindings) {
1013
- lines.push(` ${chalk2.cyan("shipguard rate <ruleId> up")} ${chalk2.dim("# rate a finding")}`);
1011
+ lines.push(` ${chalk.cyan("shipguard rate <ruleId> up")} ${chalk.dim("# rate a finding")}`);
1014
1012
  }
1015
- lines.push(` ${chalk2.cyan('shipguard feedback "<thoughts>"')} ${chalk2.dim("# what do you think?")}`);
1013
+ lines.push(` ${chalk.cyan('shipguard feedback "<thoughts>"')} ${chalk.dim("# what do you think?")}`);
1016
1014
  if (!isLoggedIn) {
1017
1015
  lines.push("");
1018
- lines.push(` ${chalk2.yellow("shipguard login")} ${chalk2.dim("# unlock Pro rules")}`);
1019
- lines.push(` ${chalk2.yellow("shipguard scan --pro")} ${chalk2.dim("# deeper checks after login")}`);
1016
+ lines.push(` ${chalk.yellow("shipguard login")} ${chalk.dim("# unlock Pro rules")}`);
1017
+ lines.push(` ${chalk.yellow("shipguard scan --pro")} ${chalk.dim("# deeper checks after login")}`);
1020
1018
  }
1021
1019
  lines.push("");
1022
- lines.push(` ${chalk2.dim("Full docs: " + DOCS_URL)}`);
1020
+ lines.push(` ${chalk.dim("Full docs: " + DOCS_URL)}`);
1023
1021
  lines.push("");
1024
1022
  return lines.join("\n");
1025
1023
  }
@@ -1042,11 +1040,11 @@ function welcomeBanner(configDir) {
1042
1040
  const inner = ` ${content}`;
1043
1041
  const w = displayWidth(inner);
1044
1042
  const pad = Math.max(0, BANNER_INNER - w);
1045
- return chalk2.cyan(" \u2502") + inner + " ".repeat(pad) + chalk2.cyan("\u2502");
1043
+ return chalk.cyan(" \u2502") + inner + " ".repeat(pad) + chalk.cyan("\u2502");
1046
1044
  }
1047
- const top = chalk2.bold(chalk2.cyan(" \u256D" + "\u2500".repeat(BANNER_INNER) + "\u256E"));
1048
- const bottom = chalk2.bold(chalk2.cyan(" \u2570" + "\u2500".repeat(BANNER_INNER) + "\u256F"));
1049
- const empty = chalk2.cyan(" \u2502") + " ".repeat(BANNER_INNER) + chalk2.cyan("\u2502");
1045
+ const top = chalk.bold(chalk.cyan(" \u256D" + "\u2500".repeat(BANNER_INNER) + "\u256E"));
1046
+ const bottom = chalk.bold(chalk.cyan(" \u2570" + "\u2500".repeat(BANNER_INNER) + "\u256F"));
1047
+ const empty = chalk.cyan(" \u2502") + " ".repeat(BANNER_INNER) + chalk.cyan("\u2502");
1050
1048
  return [
1051
1049
  "",
1052
1050
  top,
@@ -1054,24 +1052,25 @@ function welcomeBanner(configDir) {
1054
1052
  bannerLine("It catches secrets, auth flaws, and deployment issues before"),
1055
1053
  bannerLine("they ship \u2014 deterministic, fast, privacy-preserving."),
1056
1054
  empty,
1057
- bannerLine(chalk2.bold("Quick start:")),
1058
- bannerLine(` ${chalk2.green("shipguard scan <path>")} Run a scan on your project`),
1059
- bannerLine(` ${chalk2.green("shipguard login")} Unlock Pro rules`),
1060
- bannerLine(` ${chalk2.green("shipguard scan --json")} Machine-readable output for CI/agents`),
1055
+ bannerLine(chalk.bold("Quick start:")),
1056
+ bannerLine(` ${chalk.green("shipguard scan <path>")} Run a scan on your project`),
1057
+ bannerLine(` ${chalk.green("shipguard login")} Unlock Pro rules`),
1058
+ bannerLine(` ${chalk.green("shipguard scan --json")} Machine-readable output for CI/agents`),
1061
1059
  empty,
1062
- bannerLine(`Docs: ${chalk2.underline(DOCS_URL)}`),
1060
+ bannerLine(`Docs: ${chalk.underline(DOCS_URL)}`),
1063
1061
  empty,
1064
- bannerLine(chalk2.dim("Anonymous usage ping enabled \u2014 opt out: SHIPGUARD_TELEMETRY=0")),
1065
- bannerLine(chalk2.dim(`Details: ${chalk2.underline("agenticcli.dev/docs#telemetry")}`)),
1062
+ bannerLine(chalk.dim("Anonymous usage ping enabled \u2014 opt out: SHIPGUARD_TELEMETRY=0")),
1063
+ bannerLine(chalk.dim(`Details: ${chalk.underline("agenticcli.dev/docs#telemetry")}`)),
1066
1064
  bottom,
1067
1065
  ""
1068
1066
  ].join("\n");
1069
1067
  }
1070
- function quietVerdict(result) {
1068
+ function quietVerdict(result, strict) {
1071
1069
  const { recommendation, score, totalFindings, blockingCount } = result.riskScore;
1072
1070
  const icon = recommendation === "SAFE_TO_SHIP" ? "\u2705" : recommendation === "DO_NOT_SHIP" ? "\u26D4" : "\u26A0\uFE0F";
1073
- const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk2.green : recommendation === "DO_NOT_SHIP" ? chalk2.red : chalk2.yellow;
1074
- return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}`);
1071
+ const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk.green : recommendation === "DO_NOT_SHIP" ? chalk.red : chalk.yellow;
1072
+ const suffix = blockingCount > 0 && !strict ? " (informational \u2014 exit 0; use --strict to enforce)" : "";
1073
+ return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}${suffix}`);
1075
1074
  }
1076
1075
  function truncate(str, maxLen) {
1077
1076
  return str.length <= maxLen ? str : `${str.slice(0, maxLen - 3)}...`;
@@ -1144,6 +1143,785 @@ function displayWidth(str) {
1144
1143
  return width;
1145
1144
  }
1146
1145
 
1146
+ // src/core/history/index.ts
1147
+ import { createHash as createHash5 } from "crypto";
1148
+
1149
+ // src/core/history/schema.ts
1150
+ var CURRENT_SCHEMA_VERSION = 2;
1151
+ var MIGRATION_1_INIT = `
1152
+ CREATE TABLE IF NOT EXISTS schema_meta (
1153
+ schema_version INTEGER NOT NULL,
1154
+ created_at TEXT NOT NULL,
1155
+ cli_version_created_with TEXT NOT NULL
1156
+ );
1157
+
1158
+ CREATE TABLE IF NOT EXISTS scans (
1159
+ scan_id TEXT PRIMARY KEY,
1160
+ repo_id TEXT NOT NULL,
1161
+ repo_id_kind TEXT NOT NULL,
1162
+ repo_remote_label TEXT,
1163
+ scope_fingerprint TEXT NOT NULL,
1164
+ corpus_version TEXT NOT NULL,
1165
+ release_id TEXT NOT NULL,
1166
+ cli_version TEXT NOT NULL,
1167
+ timestamp TEXT NOT NULL,
1168
+ recommendation TEXT,
1169
+ blocking_count INTEGER NOT NULL DEFAULT 0,
1170
+ critical_count INTEGER NOT NULL DEFAULT 0,
1171
+ high_count INTEGER NOT NULL DEFAULT 0,
1172
+ medium_count INTEGER NOT NULL DEFAULT 0,
1173
+ low_count INTEGER NOT NULL DEFAULT 0,
1174
+ info_count INTEGER NOT NULL DEFAULT 0,
1175
+ state_status TEXT NOT NULL
1176
+ );
1177
+
1178
+ CREATE INDEX IF NOT EXISTS idx_scans_repo_scope_ts
1179
+ ON scans (repo_id, scope_fingerprint, timestamp DESC);
1180
+
1181
+ CREATE TABLE IF NOT EXISTS rule_outcomes (
1182
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1183
+ scan_id TEXT NOT NULL REFERENCES scans(scan_id) ON DELETE CASCADE,
1184
+ rule_id TEXT NOT NULL,
1185
+ blocking INTEGER NOT NULL,
1186
+ active_finding_count INTEGER NOT NULL DEFAULT 0,
1187
+ rule_version TEXT NOT NULL
1188
+ );
1189
+
1190
+ CREATE INDEX IF NOT EXISTS idx_rule_outcomes_scan ON rule_outcomes (scan_id);
1191
+ CREATE INDEX IF NOT EXISTS idx_rule_outcomes_rule ON rule_outcomes (rule_id);
1192
+
1193
+ CREATE TABLE IF NOT EXISTS findings (
1194
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1195
+ scan_id TEXT NOT NULL REFERENCES scans(scan_id) ON DELETE CASCADE,
1196
+ rule_id TEXT NOT NULL,
1197
+ finding_key TEXT NOT NULL,
1198
+ file_path TEXT,
1199
+ severity TEXT,
1200
+ blocking INTEGER NOT NULL,
1201
+ active INTEGER NOT NULL,
1202
+ rule_version TEXT NOT NULL,
1203
+ corpus_version TEXT NOT NULL,
1204
+ release_id TEXT NOT NULL
1205
+ );
1206
+
1207
+ CREATE INDEX IF NOT EXISTS idx_findings_scan ON findings (scan_id);
1208
+ CREATE INDEX IF NOT EXISTS idx_findings_rule_key ON findings (rule_id, finding_key);
1209
+ `;
1210
+ var MIGRATION_2_SCAN_ID_RESERVATIONS = `
1211
+ CREATE TABLE IF NOT EXISTS scan_id_reservations (
1212
+ repo_id TEXT NOT NULL,
1213
+ reuse_key TEXT NOT NULL,
1214
+ scan_id TEXT NOT NULL,
1215
+ created_at TEXT NOT NULL,
1216
+ PRIMARY KEY (repo_id, reuse_key)
1217
+ );
1218
+
1219
+ CREATE INDEX IF NOT EXISTS idx_scan_id_reservations_created
1220
+ ON scan_id_reservations (created_at);
1221
+ `;
1222
+ var MIGRATIONS = [
1223
+ { version: 1, sql: MIGRATION_1_INIT },
1224
+ { version: 2, sql: MIGRATION_2_SCAN_ID_RESERVATIONS }
1225
+ ];
1226
+ var UNVERSIONED = "unversioned";
1227
+
1228
+ // src/core/history/path.ts
1229
+ import { resolve as resolve3 } from "path";
1230
+ function resolveHistoryPath(cwd, policy) {
1231
+ const envPath = process.env[HISTORY_PATH_ENV_VAR];
1232
+ if (envPath && envPath.trim().length > 0) {
1233
+ return resolve3(cwd, envPath);
1234
+ }
1235
+ const policyPath = policy.history?.path;
1236
+ if (policyPath && policyPath.trim().length > 0) {
1237
+ return resolve3(cwd, policyPath);
1238
+ }
1239
+ return resolve3(cwd, DEFAULT_HISTORY_PATH);
1240
+ }
1241
+
1242
+ // src/core/history/identity.ts
1243
+ import { execFileSync as execFileSync2 } from "child_process";
1244
+ import { createHash as createHash2, randomUUID } from "crypto";
1245
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, writeFileSync as writeFileSync2 } from "fs";
1246
+ import { dirname as dirname2, join as join5 } from "path";
1247
+ function tryGit(cwd, args) {
1248
+ try {
1249
+ return execFileSync2("git", args, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
1250
+ } catch {
1251
+ return void 0;
1252
+ }
1253
+ }
1254
+ function ensureGitignored(cwd, entry) {
1255
+ try {
1256
+ const gitignorePath = join5(cwd, ".gitignore");
1257
+ const existing = existsSync3(gitignorePath) ? readFileSync(gitignorePath, "utf-8") : "";
1258
+ const alreadyPresent = existing.split("\n").map((l) => l.trim()).some((l) => l === entry || l === entry.replace(/\/$/, ""));
1259
+ if (alreadyPresent) return;
1260
+ const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
1261
+ writeFileSync2(gitignorePath, `${existing}${prefix}${entry}
1262
+ `, "utf-8");
1263
+ } catch (err) {
1264
+ logger.warn(`Could not update .gitignore for history store: ${err instanceof Error ? err.message : err}`);
1265
+ }
1266
+ }
1267
+ function resolveRepoIdentity(cwd) {
1268
+ const rootCommits = tryGit(cwd, ["rev-list", "--max-parents=0", "HEAD"]);
1269
+ const remoteLabel = tryGit(cwd, ["remote", "get-url", "origin"]);
1270
+ if (rootCommits) {
1271
+ const roots = rootCommits.split("\n").map((l) => l.trim()).filter(Boolean).sort();
1272
+ if (roots.length > 0) {
1273
+ return { repoId: roots.join(","), repoIdKind: "root-commit", remoteLabel };
1274
+ }
1275
+ }
1276
+ const fallbackPath = join5(cwd, DEFAULT_REPO_ID_FALLBACK_PATH);
1277
+ try {
1278
+ if (existsSync3(fallbackPath)) {
1279
+ const existing = readFileSync(fallbackPath, "utf-8").trim();
1280
+ if (existing) {
1281
+ return { repoId: existing, repoIdKind: "fallback-uuid", remoteLabel };
1282
+ }
1283
+ }
1284
+ const id = randomUUID();
1285
+ mkdirSync2(dirname2(fallbackPath), { recursive: true });
1286
+ writeFileSync2(fallbackPath, `${id}
1287
+ `, "utf-8");
1288
+ ensureGitignored(cwd, ".shipguard/");
1289
+ return { repoId: id, repoIdKind: "fallback-uuid", remoteLabel };
1290
+ } catch (err) {
1291
+ logger.warn(`Could not persist fallback repo identity: ${err instanceof Error ? err.message : err}`);
1292
+ return { repoId: randomUUID(), repoIdKind: "fallback-uuid", remoteLabel };
1293
+ }
1294
+ }
1295
+ function resolveContentIdentity(cwd, excludePrefixes = []) {
1296
+ const headSha = tryGit(cwd, ["rev-parse", "HEAD"]);
1297
+ if (!headSha) return void 0;
1298
+ const raw = tryGit(cwd, ["status", "--porcelain", "-z"]) ?? "";
1299
+ const normalizedExcludes = excludePrefixes.map((p) => p.replace(/\\/g, "/").replace(/^\.\//, "")).filter(Boolean);
1300
+ const records = raw.split("\0").filter(Boolean);
1301
+ const kept = records.filter((rec) => {
1302
+ const path = rec.length > 3 ? rec.slice(3) : rec;
1303
+ return !normalizedExcludes.some((ex) => path === ex || path === ex.replace(/\/$/, "") || path.startsWith(ex));
1304
+ });
1305
+ const dirtyStatus = kept.sort().join("\n");
1306
+ return createHash2("sha256").update(`${headSha}
1307
+ ${dirtyStatus}`).digest("hex").slice(0, 16);
1308
+ }
1309
+
1310
+ // src/core/history/fingerprint.ts
1311
+ import { createHash as createHash3 } from "crypto";
1312
+ function computeScopeFingerprint(input) {
1313
+ const normalized = {
1314
+ mode: input.changedOnly ? "changed" : "full",
1315
+ categories: [...input.categories].map((c) => c.trim().toLowerCase()).filter(Boolean).sort(),
1316
+ ignorePaths: [...input.ignorePaths].map((p) => p.trim()).filter(Boolean).sort(),
1317
+ tier: input.proApplied ? "pro" : "free"
1318
+ };
1319
+ const json = JSON.stringify(normalized);
1320
+ return createHash3("sha256").update(json).digest("hex").slice(0, 16);
1321
+ }
1322
+
1323
+ // src/core/history/store.ts
1324
+ import { randomUUID as randomUUID2 } from "crypto";
1325
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
1326
+ import { dirname as dirname3 } from "path";
1327
+ var sqliteModulePromise;
1328
+ var warningFilterInstalled = false;
1329
+ function installSqliteWarningFilter() {
1330
+ if (warningFilterInstalled) return;
1331
+ warningFilterInstalled = true;
1332
+ const existingListeners = [...process.listeners("warning")];
1333
+ process.removeAllListeners("warning");
1334
+ process.on("warning", (warning) => {
1335
+ if (warning.name === "ExperimentalWarning" && /SQLite/i.test(warning.message)) return;
1336
+ if (existingListeners.length > 0) {
1337
+ for (const listener of existingListeners) listener(warning);
1338
+ } else {
1339
+ console.error(`${warning.name}: ${warning.message}`);
1340
+ }
1341
+ });
1342
+ }
1343
+ var NODE_SQLITE_SPECIFIER = ["node", "sqlite"].join(":");
1344
+ async function loadSqliteModule() {
1345
+ if (!sqliteModulePromise) {
1346
+ installSqliteWarningFilter();
1347
+ sqliteModulePromise = import(NODE_SQLITE_SPECIFIER).catch(() => void 0);
1348
+ }
1349
+ return sqliteModulePromise;
1350
+ }
1351
+ function isBusyOrLockedError(err) {
1352
+ const message = err instanceof Error ? err.message : String(err);
1353
+ return /SQLITE_BUSY|database is locked|SQLITE_LOCKED/i.test(message);
1354
+ }
1355
+ var HistoryStore = class _HistoryStore {
1356
+ constructor(db, path) {
1357
+ this.db = db;
1358
+ this.path = path;
1359
+ }
1360
+ db;
1361
+ path;
1362
+ /**
1363
+ * Open (creating if absent) + forward-only-migrate + integrity-check the history store.
1364
+ * NEVER throws — every failure mode returns a typed `{ ok: false, status, reason }` so
1365
+ * the caller can set `stateStatus` and keep the scan itself going (§1.6).
1366
+ */
1367
+ static async open(dbPath, cliVersion) {
1368
+ const sqlite = await loadSqliteModule();
1369
+ if (!sqlite) {
1370
+ return {
1371
+ ok: false,
1372
+ status: "unavailable",
1373
+ reason: "node:sqlite is not available on this Node.js runtime (requires Node >=22.5). History is disabled for this scan; the scan's own findings/verdict are unaffected."
1374
+ };
1375
+ }
1376
+ const preExisted = existsSync4(dbPath);
1377
+ try {
1378
+ mkdirSync3(dirname3(dbPath), { recursive: true });
1379
+ } catch (err) {
1380
+ return {
1381
+ ok: false,
1382
+ status: "unavailable",
1383
+ reason: `Could not create the history directory: ${err instanceof Error ? err.message : err}`
1384
+ };
1385
+ }
1386
+ let db;
1387
+ try {
1388
+ db = new sqlite.DatabaseSync(dbPath);
1389
+ } catch (err) {
1390
+ const reason = err instanceof Error ? err.message : String(err);
1391
+ return {
1392
+ ok: false,
1393
+ status: isBusyOrLockedError(err) ? "unavailable" : preExisted ? "corrupt" : "unavailable",
1394
+ reason: `Could not open history store at ${dbPath}: ${reason}`
1395
+ };
1396
+ }
1397
+ try {
1398
+ db.exec("PRAGMA journal_mode = WAL");
1399
+ db.exec("PRAGMA busy_timeout = 5000");
1400
+ db.exec("PRAGMA foreign_keys = ON");
1401
+ } catch (err) {
1402
+ const reason = err instanceof Error ? err.message : String(err);
1403
+ try {
1404
+ db.close();
1405
+ } catch {
1406
+ }
1407
+ return {
1408
+ ok: false,
1409
+ status: isBusyOrLockedError(err) ? "unavailable" : "corrupt",
1410
+ reason: `Could not configure history store at ${dbPath}: ${reason}`
1411
+ };
1412
+ }
1413
+ try {
1414
+ const row = db.prepare("PRAGMA integrity_check").get();
1415
+ if (row?.integrity_check && row.integrity_check !== "ok") {
1416
+ db.close();
1417
+ return {
1418
+ ok: false,
1419
+ status: "corrupt",
1420
+ reason: `History store failed integrity check (${row.integrity_check}). File: ${dbPath} \u2014 back it up or delete it to start fresh.`
1421
+ };
1422
+ }
1423
+ } catch (err) {
1424
+ try {
1425
+ db.close();
1426
+ } catch {
1427
+ }
1428
+ const reason = err instanceof Error ? err.message : String(err);
1429
+ return {
1430
+ ok: false,
1431
+ status: isBusyOrLockedError(err) ? "unavailable" : preExisted ? "corrupt" : "unavailable",
1432
+ reason: `History store integrity check failed: ${reason}`
1433
+ };
1434
+ }
1435
+ try {
1436
+ db.exec(
1437
+ "CREATE TABLE IF NOT EXISTS schema_meta (schema_version INTEGER NOT NULL, created_at TEXT NOT NULL, cli_version_created_with TEXT NOT NULL)"
1438
+ );
1439
+ const metaRow = db.prepare("SELECT schema_version FROM schema_meta ORDER BY schema_version DESC LIMIT 1").get();
1440
+ const existingVersion = metaRow?.schema_version ?? 0;
1441
+ if (existingVersion > CURRENT_SCHEMA_VERSION) {
1442
+ db.close();
1443
+ return {
1444
+ ok: false,
1445
+ status: "unavailable",
1446
+ reason: `History file was created by a newer ShipGuard (schema v${existingVersion}) \u2014 this CLI only knows schema v${CURRENT_SCHEMA_VERSION}. Upgrade ShipGuard to keep recording history. File: ${dbPath}`
1447
+ };
1448
+ }
1449
+ const insertMeta = db.prepare(
1450
+ "INSERT INTO schema_meta (schema_version, created_at, cli_version_created_with) VALUES (?, ?, ?)"
1451
+ );
1452
+ for (const migration of MIGRATIONS) {
1453
+ if (migration.version <= existingVersion) continue;
1454
+ try {
1455
+ db.exec("BEGIN IMMEDIATE");
1456
+ db.exec(migration.sql);
1457
+ insertMeta.run(migration.version, (/* @__PURE__ */ new Date()).toISOString(), cliVersion);
1458
+ db.exec("COMMIT");
1459
+ } catch (err) {
1460
+ try {
1461
+ db.exec("ROLLBACK");
1462
+ } catch {
1463
+ }
1464
+ db.close();
1465
+ const reason = err instanceof Error ? err.message : String(err);
1466
+ return {
1467
+ ok: false,
1468
+ status: "corrupt",
1469
+ reason: `Migration to schema v${migration.version} failed partway (the original file is left untouched, never partially applied): ${reason}. File: ${dbPath} \u2014 back it up or delete it to start fresh.`
1470
+ };
1471
+ }
1472
+ }
1473
+ } catch (err) {
1474
+ try {
1475
+ db.close();
1476
+ } catch {
1477
+ }
1478
+ const reason = err instanceof Error ? err.message : String(err);
1479
+ return { ok: false, status: "corrupt", reason: `History store migration bookkeeping failed: ${reason}` };
1480
+ }
1481
+ return { ok: true, store: new _HistoryStore(db, dbPath) };
1482
+ }
1483
+ /**
1484
+ * One transaction per scan record (§1.4): begin → insert scan row + rule-outcome rows +
1485
+ * finding rows → commit. Never throws — a write failure rolls back and returns
1486
+ * `{ ok: false }` so the caller sets `stateStatus: 'unavailable'` and keeps going.
1487
+ */
1488
+ writeScan(input) {
1489
+ try {
1490
+ this.db.exec("BEGIN IMMEDIATE");
1491
+ this.db.prepare(
1492
+ `INSERT OR REPLACE INTO scans (
1493
+ scan_id, repo_id, repo_id_kind, repo_remote_label, scope_fingerprint,
1494
+ corpus_version, release_id, cli_version, timestamp, recommendation,
1495
+ blocking_count, critical_count, high_count, medium_count, low_count, info_count,
1496
+ state_status
1497
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`
1498
+ ).run(
1499
+ input.scanId,
1500
+ input.repoId,
1501
+ input.repoIdKind,
1502
+ input.remoteLabel ?? null,
1503
+ input.scopeFingerprint,
1504
+ input.corpusVersion,
1505
+ input.releaseId,
1506
+ input.cliVersion,
1507
+ input.timestamp,
1508
+ input.recommendation ?? null,
1509
+ input.blockingCount,
1510
+ input.criticalCount,
1511
+ input.highCount,
1512
+ input.mediumCount,
1513
+ input.lowCount,
1514
+ input.infoCount,
1515
+ "complete"
1516
+ );
1517
+ const insertRuleOutcome = this.db.prepare(
1518
+ "INSERT INTO rule_outcomes (scan_id, rule_id, blocking, active_finding_count, rule_version) VALUES (?,?,?,?,?)"
1519
+ );
1520
+ for (const ro of input.ruleOutcomes) {
1521
+ insertRuleOutcome.run(input.scanId, ro.ruleId, ro.blocking ? 1 : 0, ro.activeFindingCount, ro.ruleVersion);
1522
+ }
1523
+ const insertFinding = this.db.prepare(
1524
+ `INSERT INTO findings (
1525
+ scan_id, rule_id, finding_key, file_path, severity, blocking, active,
1526
+ rule_version, corpus_version, release_id
1527
+ ) VALUES (?,?,?,?,?,?,?,?,?,?)`
1528
+ );
1529
+ for (const f of input.findings) {
1530
+ insertFinding.run(
1531
+ input.scanId,
1532
+ f.ruleId,
1533
+ f.findingKey,
1534
+ f.filePath ?? null,
1535
+ f.severity ?? null,
1536
+ f.blocking ? 1 : 0,
1537
+ f.active ? 1 : 0,
1538
+ f.ruleVersion,
1539
+ f.corpusVersion,
1540
+ f.releaseId
1541
+ );
1542
+ }
1543
+ this.db.exec("COMMIT");
1544
+ return { ok: true };
1545
+ } catch (err) {
1546
+ try {
1547
+ this.db.exec("ROLLBACK");
1548
+ } catch {
1549
+ }
1550
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
1551
+ }
1552
+ }
1553
+ /**
1554
+ * Most recent PRIOR scan for the same repo + scope fingerprint with `state_status = 'complete'`
1555
+ * (§4 step 2). Returns undefined when there is no such scan (first-ever scan for this
1556
+ * repo+scope — regressionCheckSkipped: 'no-baseline', not an error).
1557
+ */
1558
+ getBaseline(repoId, scopeFingerprint) {
1559
+ const scanRow = this.db.prepare(
1560
+ `SELECT scan_id, timestamp, corpus_version FROM scans
1561
+ WHERE repo_id = ? AND scope_fingerprint = ? AND state_status = 'complete'
1562
+ ORDER BY timestamp DESC LIMIT 1`
1563
+ ).get(repoId, scopeFingerprint);
1564
+ if (!scanRow) return void 0;
1565
+ const ruleRows = this.db.prepare("SELECT rule_id, blocking, active_finding_count, rule_version FROM rule_outcomes WHERE scan_id = ?").all(scanRow.scan_id);
1566
+ return {
1567
+ scanId: scanRow.scan_id,
1568
+ timestamp: scanRow.timestamp,
1569
+ scopeFingerprint,
1570
+ corpusVersion: scanRow.corpus_version,
1571
+ stateStatus: "complete",
1572
+ ruleOutcomes: ruleRows.map((r) => ({
1573
+ ruleId: r.rule_id,
1574
+ blocking: r.blocking === 1,
1575
+ activeFindingCount: r.active_finding_count,
1576
+ ruleVersion: r.rule_version
1577
+ }))
1578
+ };
1579
+ }
1580
+ /**
1581
+ * Task #25 (persist-scanid) — look up or mint the scanId for a PRE-scan reuse key
1582
+ * (repo_id + reuse_key, see history/scan-id.ts). Never throws — every failure (lock
1583
+ * timeout, disk full, etc.) returns `{ ok: false, reason }` so the caller falls back to a
1584
+ * fresh in-memory `randomUUID()` exactly like today (graceful degrade, §1.6's pattern).
1585
+ *
1586
+ * A row within `reuseWindowMs` of its `created_at` is reused verbatim (`reused: true`);
1587
+ * otherwise (no row, or the row aged out) a fresh UUID is minted and UPSERTed — replacing
1588
+ * any stale row for the same (repo_id, reuse_key) rather than accumulating one, so a
1589
+ * legitimately new scan of unchanged-looking content never keeps resurrecting an
1590
+ * arbitrarily old scanId once the window has passed.
1591
+ */
1592
+ reserveScanId(repoId, reuseKey, reuseWindowMs) {
1593
+ try {
1594
+ const row = this.db.prepare("SELECT scan_id, created_at FROM scan_id_reservations WHERE repo_id = ? AND reuse_key = ?").get(repoId, reuseKey);
1595
+ if (row) {
1596
+ const ageMs = Date.now() - new Date(row.created_at).getTime();
1597
+ if (ageMs >= 0 && ageMs <= reuseWindowMs) {
1598
+ return { ok: true, scanId: row.scan_id, reused: true };
1599
+ }
1600
+ }
1601
+ const scanId = randomUUID2();
1602
+ this.db.prepare(
1603
+ `INSERT INTO scan_id_reservations (repo_id, reuse_key, scan_id, created_at) VALUES (?, ?, ?, ?)
1604
+ ON CONFLICT(repo_id, reuse_key) DO UPDATE SET scan_id = excluded.scan_id, created_at = excluded.created_at`
1605
+ ).run(repoId, reuseKey, scanId, (/* @__PURE__ */ new Date()).toISOString());
1606
+ return { ok: true, scanId, reused: false };
1607
+ } catch (err) {
1608
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
1609
+ }
1610
+ }
1611
+ /** Read-only recent-scans listing for `shipguard history` — most recent first. */
1612
+ listRecentScans(repoId, limit) {
1613
+ const rows = this.db.prepare(
1614
+ `SELECT scan_id, timestamp, scope_fingerprint, corpus_version, recommendation, blocking_count, state_status
1615
+ FROM scans WHERE repo_id = ? ORDER BY timestamp DESC LIMIT ?`
1616
+ ).all(repoId, limit);
1617
+ return rows.map((r) => ({
1618
+ scanId: r.scan_id,
1619
+ timestamp: r.timestamp,
1620
+ scopeFingerprint: r.scope_fingerprint,
1621
+ corpusVersion: r.corpus_version,
1622
+ recommendation: r.recommendation,
1623
+ blockingCount: r.blocking_count,
1624
+ stateStatus: r.state_status
1625
+ }));
1626
+ }
1627
+ /**
1628
+ * User-controlled pruning only (§1.7) — default is keep-everything (retentionDays unset).
1629
+ * Never removes the most recent scan per (repo, scope fingerprint), even if it's past the
1630
+ * window, so a regression baseline can never be pruned out from under a future comparison.
1631
+ * Scoped to ONE repoId so an opt-in shared history file never lets one project's retention
1632
+ * policy delete another project's rows.
1633
+ */
1634
+ prune(repoId, retentionDays) {
1635
+ try {
1636
+ this.db.exec("BEGIN IMMEDIATE");
1637
+ const info = this.db.prepare(
1638
+ `DELETE FROM scans
1639
+ WHERE repo_id = ?
1640
+ AND (julianday('now') - julianday(timestamp)) > ?
1641
+ AND scan_id NOT IN (
1642
+ SELECT s2.scan_id FROM (
1643
+ SELECT scope_fingerprint, MAX(timestamp) AS max_ts FROM scans WHERE repo_id = ? GROUP BY scope_fingerprint
1644
+ ) latest
1645
+ JOIN scans s2 ON s2.repo_id = ? AND s2.scope_fingerprint = latest.scope_fingerprint AND s2.timestamp = latest.max_ts
1646
+ )`
1647
+ ).run(repoId, retentionDays, repoId, repoId);
1648
+ this.db.exec("COMMIT");
1649
+ return { ok: true, deleted: info.changes ?? 0 };
1650
+ } catch (err) {
1651
+ try {
1652
+ this.db.exec("ROLLBACK");
1653
+ } catch {
1654
+ }
1655
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
1656
+ }
1657
+ }
1658
+ close() {
1659
+ try {
1660
+ this.db.close();
1661
+ } catch {
1662
+ }
1663
+ }
1664
+ };
1665
+
1666
+ // src/core/history/regression.ts
1667
+ function computeRegressionResult(current, baseline) {
1668
+ const skip = (reason) => ({
1669
+ regressionCheckSkipped: true,
1670
+ regressionCheckSkippedReason: reason,
1671
+ regressions: [],
1672
+ coverageChanged: []
1673
+ });
1674
+ if (!baseline) return skip("no-baseline");
1675
+ if (current.stateStatus !== "complete" || baseline.stateStatus !== "complete") {
1676
+ return skip("state-unavailable");
1677
+ }
1678
+ if (current.scopeFingerprint !== baseline.scopeFingerprint) {
1679
+ return skip("scope-mismatch");
1680
+ }
1681
+ const regressions = [];
1682
+ const coverageChanged = [];
1683
+ const baselineByRule = new Map(baseline.ruleOutcomes.map((r) => [r.ruleId, r]));
1684
+ const currentRuleIds = new Set(current.ruleOutcomes.map((r) => r.ruleId));
1685
+ for (const cur of current.ruleOutcomes) {
1686
+ if (!cur.blocking) continue;
1687
+ const base = baselineByRule.get(cur.ruleId);
1688
+ if (!base) {
1689
+ coverageChanged.push({ ruleId: cur.ruleId, reason: "new-since-baseline" });
1690
+ continue;
1691
+ }
1692
+ if (base.ruleVersion !== cur.ruleVersion) {
1693
+ coverageChanged.push({
1694
+ ruleId: cur.ruleId,
1695
+ reason: "rule-version-changed",
1696
+ baselineRuleVersion: base.ruleVersion,
1697
+ currentRuleVersion: cur.ruleVersion
1698
+ });
1699
+ continue;
1700
+ }
1701
+ if (!base.blocking) {
1702
+ coverageChanged.push({ ruleId: cur.ruleId, reason: "rule-version-changed" });
1703
+ continue;
1704
+ }
1705
+ if (base.activeFindingCount === 0 && cur.activeFindingCount > 0) {
1706
+ regressions.push({
1707
+ ruleId: cur.ruleId,
1708
+ baselineScanId: baseline.scanId,
1709
+ baselineTimestamp: baseline.timestamp,
1710
+ currentScanId: current.scanId,
1711
+ corpusVersion: { baseline: baseline.corpusVersion, current: current.corpusVersion },
1712
+ scopeFingerprint: current.scopeFingerprint
1713
+ });
1714
+ }
1715
+ }
1716
+ for (const base of baseline.ruleOutcomes) {
1717
+ if (base.blocking && !currentRuleIds.has(base.ruleId)) {
1718
+ coverageChanged.push({ ruleId: base.ruleId, reason: "withdrawn-since-baseline" });
1719
+ }
1720
+ }
1721
+ return { regressionCheckSkipped: false, regressions, coverageChanged };
1722
+ }
1723
+
1724
+ // src/core/history/scan-id.ts
1725
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
1726
+ import { relative } from "path";
1727
+ function computeScanIdReuseKey(input) {
1728
+ const normalized = {
1729
+ mode: input.changedOnly ? "changed" : "full",
1730
+ categories: [...input.categories].map((c) => c.trim().toLowerCase()).filter(Boolean).sort(),
1731
+ ignorePaths: [...input.ignorePaths].map((p) => p.trim()).filter(Boolean).sort(),
1732
+ proRequested: input.proRequested,
1733
+ // Sorted so listing order never affects the key; a changed framework set → fresh scanId.
1734
+ frameworks: [...input.frameworks].map((f) => f.trim().toLowerCase()).filter(Boolean).sort(),
1735
+ content: input.contentIdentity
1736
+ };
1737
+ const json = JSON.stringify(normalized);
1738
+ return createHash4("sha256").update(json).digest("hex").slice(0, 16);
1739
+ }
1740
+ function resolveScanIdReuseWindowMs(policy) {
1741
+ const envMinutes = process.env[SCAN_ID_REUSE_WINDOW_ENV_VAR];
1742
+ if (envMinutes && envMinutes.trim().length > 0) {
1743
+ const parsed = Number(envMinutes);
1744
+ if (Number.isFinite(parsed) && parsed > 0) return parsed * 60 * 1e3;
1745
+ }
1746
+ const policyMinutes = policy.history?.scan_id_reuse_window_minutes;
1747
+ if (typeof policyMinutes === "number" && policyMinutes > 0) {
1748
+ return policyMinutes * 60 * 1e3;
1749
+ }
1750
+ return DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES * 60 * 1e3;
1751
+ }
1752
+ async function resolveScanId(input) {
1753
+ const { cwd, policy, cliVersion, changedOnly, categories, proRequested, frameworks } = input;
1754
+ try {
1755
+ const historyPath = resolveHistoryPath(cwd, policy);
1756
+ const historyRelPath = relative(cwd, historyPath).replace(/\\/g, "/");
1757
+ const excludePrefixes = [".shipguard/", historyRelPath];
1758
+ const contentIdentity = resolveContentIdentity(cwd, excludePrefixes);
1759
+ if (!contentIdentity) {
1760
+ return { scanId: randomUUID3(), scanIdReused: false };
1761
+ }
1762
+ const identity = resolveRepoIdentity(cwd);
1763
+ const reuseKey = computeScanIdReuseKey({
1764
+ changedOnly,
1765
+ categories,
1766
+ ignorePaths: policy.ignore.paths,
1767
+ proRequested,
1768
+ frameworks,
1769
+ contentIdentity
1770
+ });
1771
+ const reuseWindowMs = resolveScanIdReuseWindowMs(policy);
1772
+ const openResult = await HistoryStore.open(historyPath, cliVersion);
1773
+ if (!openResult.ok) {
1774
+ logger.warn(`ShipGuard scanId persistence unavailable (${openResult.status}) \u2014 minting a fresh scanId: ${openResult.reason}`);
1775
+ return { scanId: randomUUID3(), scanIdReused: false };
1776
+ }
1777
+ const store = openResult.store;
1778
+ try {
1779
+ const result = store.reserveScanId(identity.repoId, reuseKey, reuseWindowMs);
1780
+ if (!result.ok) {
1781
+ logger.warn(`ShipGuard scanId persistence failed \u2014 minting a fresh scanId: ${result.reason}`);
1782
+ return { scanId: randomUUID3(), scanIdReused: false };
1783
+ }
1784
+ return { scanId: result.scanId, scanIdReused: result.reused };
1785
+ } finally {
1786
+ store.close();
1787
+ }
1788
+ } catch (err) {
1789
+ logger.warn(
1790
+ `ShipGuard scanId persistence failed unexpectedly \u2014 minting a fresh scanId: ${err instanceof Error ? err.message : err}`
1791
+ );
1792
+ return { scanId: randomUUID3(), scanIdReused: false };
1793
+ }
1794
+ }
1795
+
1796
+ // src/core/history/index.ts
1797
+ function isActive(finding) {
1798
+ if (finding.suppressionState) return finding.suppressionState === "active";
1799
+ return !finding.suppressed;
1800
+ }
1801
+ function computeFindingKey(finding) {
1802
+ const basis = finding.evidence && finding.evidence.length > 0 ? finding.evidence : finding.title;
1803
+ return createHash5("sha256").update(basis).digest("hex").slice(0, 16);
1804
+ }
1805
+ function buildRuleOutcomes(policy, proRules, proApplied, cliVersion, corpusVersion, result) {
1806
+ const outcomes = [];
1807
+ const countActive = (ruleId) => result.findings.filter((f) => f.id === ruleId && isActive(f)).length;
1808
+ for (const ruleId of policy.block) {
1809
+ outcomes.push({ ruleId, blocking: true, activeFindingCount: countActive(ruleId), ruleVersion: cliVersion });
1810
+ }
1811
+ for (const ruleId of policy.warn) {
1812
+ outcomes.push({ ruleId, blocking: false, activeFindingCount: countActive(ruleId), ruleVersion: cliVersion });
1813
+ }
1814
+ if (proApplied && proRules) {
1815
+ for (const rule of proRules) {
1816
+ outcomes.push({
1817
+ ruleId: rule.id,
1818
+ blocking: deriveBlocking(rule),
1819
+ activeFindingCount: countActive(rule.id),
1820
+ ruleVersion: rule.version ?? corpusVersion
1821
+ });
1822
+ }
1823
+ }
1824
+ return outcomes;
1825
+ }
1826
+ async function recordScanHistory(input) {
1827
+ const { cwd, scanId, cliVersion, policy, changedOnly, categories, proRules, proApplied, rulesVersion, result } = input;
1828
+ const scopeFingerprint = computeScopeFingerprint({
1829
+ changedOnly,
1830
+ categories,
1831
+ ignorePaths: policy.ignore.paths,
1832
+ proApplied
1833
+ });
1834
+ const identity = resolveRepoIdentity(cwd);
1835
+ const corpusVersion = proApplied ? rulesVersion ?? UNVERSIONED : `free:${cliVersion}`;
1836
+ const proReleaseId = proApplied ? result.findings.find((f) => f.releaseId)?.releaseId : void 0;
1837
+ const releaseId = proReleaseId ?? UNVERSIONED;
1838
+ const historyPath = resolveHistoryPath(cwd, policy);
1839
+ const openResult = await HistoryStore.open(historyPath, cliVersion);
1840
+ if (!openResult.ok) {
1841
+ logger.warn(`ShipGuard history ${openResult.status}: ${openResult.reason}`);
1842
+ return {
1843
+ stateStatus: openResult.status,
1844
+ regressionCheckSkipped: true,
1845
+ regressionCheckSkippedReason: "state-unavailable",
1846
+ regressions: [],
1847
+ coverageChanged: []
1848
+ };
1849
+ }
1850
+ const store = openResult.store;
1851
+ try {
1852
+ const ruleOutcomes = buildRuleOutcomes(policy, proRules, proApplied, cliVersion, corpusVersion, result);
1853
+ const baseline = store.getBaseline(identity.repoId, scopeFingerprint);
1854
+ const ruleVersionById = new Map(ruleOutcomes.map((ro) => [ro.ruleId, ro.ruleVersion]));
1855
+ const findingRows = result.findings.map((f) => ({
1856
+ ruleId: f.id,
1857
+ findingKey: computeFindingKey(f),
1858
+ filePath: f.file,
1859
+ severity: f.severity,
1860
+ blocking: Boolean(f.blocking),
1861
+ active: isActive(f),
1862
+ ruleVersion: ruleVersionById.get(f.id) ?? corpusVersion,
1863
+ corpusVersion,
1864
+ releaseId: f.releaseId ?? releaseId
1865
+ }));
1866
+ const writeResult = store.writeScan({
1867
+ scanId,
1868
+ repoId: identity.repoId,
1869
+ repoIdKind: identity.repoIdKind,
1870
+ remoteLabel: identity.remoteLabel,
1871
+ scopeFingerprint,
1872
+ corpusVersion,
1873
+ releaseId,
1874
+ cliVersion,
1875
+ timestamp: result.timestamp,
1876
+ recommendation: result.recommendation,
1877
+ blockingCount: result.riskScore.blockingCount,
1878
+ criticalCount: result.riskScore.criticalCount,
1879
+ highCount: result.riskScore.highCount,
1880
+ mediumCount: result.riskScore.mediumCount,
1881
+ lowCount: result.riskScore.lowCount,
1882
+ infoCount: result.riskScore.infoCount,
1883
+ ruleOutcomes,
1884
+ findings: findingRows
1885
+ });
1886
+ const stateStatus = writeResult.ok ? "complete" : "unavailable";
1887
+ if (!writeResult.ok) {
1888
+ logger.warn(`ShipGuard history write failed \u2014 this scan's findings/verdict are unaffected: ${writeResult.reason}`);
1889
+ }
1890
+ const retentionDays = policy.history?.retention_days;
1891
+ if (writeResult.ok && retentionDays && retentionDays > 0) {
1892
+ const pruneResult = store.prune(identity.repoId, retentionDays);
1893
+ if (!pruneResult.ok) {
1894
+ logger.warn(`ShipGuard history retention pruning failed (non-fatal): ${pruneResult.reason}`);
1895
+ } else if (pruneResult.deleted > 0) {
1896
+ logger.info(`ShipGuard history: pruned ${pruneResult.deleted} scan(s) older than ${retentionDays} day(s)`);
1897
+ }
1898
+ }
1899
+ const currentSnapshot = {
1900
+ scanId,
1901
+ timestamp: result.timestamp,
1902
+ scopeFingerprint,
1903
+ corpusVersion,
1904
+ stateStatus,
1905
+ ruleOutcomes
1906
+ };
1907
+ const regressionResult = computeRegressionResult(currentSnapshot, baseline);
1908
+ return { stateStatus, ...regressionResult };
1909
+ } catch (err) {
1910
+ logger.warn(
1911
+ `ShipGuard history recording failed unexpectedly \u2014 this scan's findings/verdict are unaffected: ${err instanceof Error ? err.message : err}`
1912
+ );
1913
+ return {
1914
+ stateStatus: "unavailable",
1915
+ regressionCheckSkipped: true,
1916
+ regressionCheckSkippedReason: "state-unavailable",
1917
+ regressions: [],
1918
+ coverageChanged: []
1919
+ };
1920
+ } finally {
1921
+ store.close();
1922
+ }
1923
+ }
1924
+
1147
1925
  // src/core/telemetry.ts
1148
1926
  function shouldSendTelemetry() {
1149
1927
  if (process.env.SHIPGUARD_TELEMETRY === "0") return false;
@@ -1176,21 +1954,34 @@ function sendTelemetry(payload) {
1176
1954
 
1177
1955
  // src/commands/scan.ts
1178
1956
  var LEARN_MORE = "Docs https://agenticcli.dev/docs \xB7 Site https://agenticcli.dev \xB7 Pricing https://agenticcli.dev/pricing \xB7 Issues https://github.com/agenticcli/shipguard/issues";
1179
- var CLI_VERSION = true ? "0.4.1" : process.env.npm_package_version ?? "0.0.0-dev";
1957
+ var CLI_VERSION = true ? "0.5.0" : process.env.npm_package_version ?? "0.0.0-dev";
1180
1958
  function resolveExitCode(opts) {
1181
1959
  if (opts.strict && opts.blockingCount > 0) {
1182
1960
  return EXIT_CODES.BLOCKED;
1183
1961
  }
1184
- if (opts.degraded) {
1185
- return EXIT_CODES.CONFIG_ERROR;
1186
- }
1187
1962
  return EXIT_CODES.SAFE;
1188
1963
  }
1964
+ function proFetchActionHint(code, retryAfterSeconds) {
1965
+ switch (code) {
1966
+ case "AUTH_FAILED":
1967
+ return "Run `shipguard login` to re-authenticate, or pass --allow-degraded to run local rules only.";
1968
+ case "INSUFFICIENT_CREDITS":
1969
+ return "Buy more credits at https://agenticcli.dev/dashboard/billing, or pass --allow-degraded to run local rules only.";
1970
+ case "RATE_LIMITED":
1971
+ return retryAfterSeconds !== void 0 ? `Rate limited \u2014 retry after ${retryAfterSeconds}s, or pass --allow-degraded to run local rules only.` : "Rate limited \u2014 wait and retry, or pass --allow-degraded to run local rules only.";
1972
+ case "SERVER_ERROR":
1973
+ return "This looks like a transient server/network issue \u2014 retry the scan, or pass --allow-degraded to run local rules only.";
1974
+ case "BUNDLE_INVALID":
1975
+ return "The pro rule bundle failed validation (server-side issue) \u2014 retry, or pass --allow-degraded to run local rules only. If this persists, contact support.";
1976
+ default:
1977
+ return "Retry the scan, or pass --allow-degraded to run local rules only.";
1978
+ }
1979
+ }
1189
1980
  function isProjectRoot(dir) {
1190
- return existsSync3(join5(dir, "package.json")) || existsSync3(join5(dir, ".git"));
1981
+ return existsSync5(join6(dir, "package.json")) || existsSync5(join6(dir, ".git"));
1191
1982
  }
1192
1983
  function scanCommand() {
1193
- 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", `
1984
+ 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", "Opt-in hard gate: exit 1 if blocking findings exist (default exit is 0 \u2014 verdict is informational, read the JSON `recommendation`)").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").option("--allow-degraded", "With --pro: fall back to local-only rules if the pro rule fetch fails, instead of failing loud (opt-in; restores the pre-2026-07-14 fallback behavior \u2014 see exit code 3 below)").option("--check-regressions", "Opt-in hard gate: exit 1 if a previously-passing blocking rule now fails under the same scan scope + corpus release (informational-only in --json unless this flag is set)").addHelpText("after", `
1194
1985
  Output modes:
1195
1986
  (default) Verbose: live progress (TTY), categorized findings, gamified verdict panel
1196
1987
  --quiet / -q One-line verdict + exit code only \u2014 ideal for scripts
@@ -1206,18 +1997,38 @@ Examples:
1206
1997
  shipguard scan --changed Scan only git-diff files (faster)
1207
1998
  shipguard scan --json Machine-readable output for CI/agents
1208
1999
  shipguard scan --pro Include pro quality gate rules (requires login)
2000
+ shipguard scan --pro --allow-degraded Fall back to local rules if the pro fetch fails (opt-in)
1209
2001
  shipguard scan --all Scan any directory regardless of project markers
2002
+ shipguard scan --strict CI hard gate: exit 1 on blocking findings
2003
+ shipguard scan --check-regressions CI hard gate: exit 1 if a previously-passing rule now fails
2004
+ shipguard history Show recent local scan history for this repo
1210
2005
 
1211
- Exit codes:
1212
- 0 Safe \u2014 no blocking findings
1213
- 1 Blocked \u2014 strict mode + blocking findings
1214
- 2 Config error / degraded scan (incomplete results)
1215
- 3 Runtime error
2006
+ Exit codes (verdict-neutral by default \u2014 ShipGuard informs, you choose the gate):
2007
+ 0 Scan completed. Verdict is in the JSON \`recommendation\` field \u2014 this
2008
+ is returned EVEN IF findings are blocking, or the scan is degraded/
2009
+ partial (see \`degraded\`/\`degradedReasons\` in --json output).
2010
+ 1 Blocked \u2014 with --strict AND at least one blocking finding, OR with
2011
+ --check-regressions AND at least one regression (see \`regressions\`
2012
+ in --json output \u2014 informational-only unless this flag is set).
2013
+ 2 Config error (bad policy file, bad flags, non-project directory).
2014
+ 3 Runtime error \u2014 the scan could not meaningfully run at all. This
2015
+ INCLUDES an explicit --pro request whose rule fetch failed (auth,
2016
+ credits, rate limit, server, or an invalid bundle) \u2014 the requested
2017
+ gate did not run, so ShipGuard fails loud instead of silently
2018
+ falling back to a free scan. Pass --allow-degraded to opt back into
2019
+ the free-scan fallback (degraded:true, exit code unaffected).
2020
+
2021
+ Local history (E5): every scan is recorded to a local SQLite store
2022
+ (\`.shipguard/history.db\` by default; override via \`history.path\` in
2023
+ shipguard.policy.yml or SHIPGUARD_HISTORY_PATH). \`stateStatus\` in --json
2024
+ reports whether that recording succeeded (complete/unavailable/corrupt) \u2014
2025
+ a regression is only ever claimed when it's \`complete\` for both runs
2026
+ being compared. A corpus/rule update is reported as \`coverageChanged\`,
2027
+ never as a regression.
1216
2028
 
1217
2029
  ${LEARN_MORE}`).action(async (scanPath, opts) => {
1218
2030
  const startTime = Date.now();
1219
- const cwd = scanPath ? resolve3(scanPath) : process.cwd();
1220
- const scanId = randomUUID();
2031
+ const cwd = scanPath ? resolve4(scanPath) : process.cwd();
1221
2032
  const machineOutput = Boolean(opts.json) || Boolean(opts.sarif);
1222
2033
  const quiet = Boolean(opts.quiet);
1223
2034
  if (!scanPath && !opts.all && !isProjectRoot(cwd)) {
@@ -1235,7 +2046,7 @@ ${LEARN_MORE}`);
1235
2046
  process.chdir(cwd);
1236
2047
  }
1237
2048
  try {
1238
- await runScan({ cwd, scanId, opts, machineOutput, quiet, startTime });
2049
+ await runScan({ cwd, opts, machineOutput, quiet, startTime });
1239
2050
  } finally {
1240
2051
  if (scanPath) {
1241
2052
  process.chdir(originalCwd);
@@ -1244,7 +2055,7 @@ ${LEARN_MORE}`);
1244
2055
  });
1245
2056
  }
1246
2057
  async function runScan(ctx) {
1247
- const { cwd, scanId, opts, machineOutput, quiet, startTime } = ctx;
2058
+ const { cwd, opts, machineOutput, quiet, startTime } = ctx;
1248
2059
  let policy;
1249
2060
  try {
1250
2061
  policy = await loadPolicy(cwd);
@@ -1253,9 +2064,28 @@ async function runScan(ctx) {
1253
2064
  process.exit(EXIT_CODES.CONFIG_ERROR);
1254
2065
  return;
1255
2066
  }
2067
+ const changedOnly = Boolean(opts.changed);
2068
+ const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : [];
2069
+ let detectedFrameworks = [{ name: "generic" }];
2070
+ try {
2071
+ const { detectFrameworks } = await import("./framework-PA6RVE7G.js");
2072
+ detectedFrameworks = detectFrameworks(cwd).frameworks;
2073
+ } catch (err) {
2074
+ logger.warn(`Framework detection failed \u2014 using 'generic' for the scan scope: ${err instanceof Error ? err.message : err}`);
2075
+ }
2076
+ const frameworkNames = detectedFrameworks.map((f) => f.name);
2077
+ const { scanId, scanIdReused } = await resolveScanId({
2078
+ cwd,
2079
+ policy,
2080
+ cliVersion: CLI_VERSION,
2081
+ changedOnly,
2082
+ categories,
2083
+ proRequested: Boolean(opts.pro),
2084
+ frameworks: frameworkNames
2085
+ });
1256
2086
  const inGitRepo = isGitRepo(cwd);
1257
2087
  const scanOptions = {
1258
- changedOnly: Boolean(opts.changed),
2088
+ changedOnly,
1259
2089
  generateReport: Boolean(opts.report),
1260
2090
  strict: Boolean(opts.strict),
1261
2091
  json: Boolean(opts.json),
@@ -1282,13 +2112,11 @@ async function runScan(ctx) {
1282
2112
  logger.info("Detecting stack...");
1283
2113
  }
1284
2114
  try {
1285
- const { detectFrameworks } = await import("./framework-PA6RVE7G.js");
1286
- const { fetchProRules } = await import("./pro-scanner-HI5OGQYR.js");
1287
- const { hasConfig, generateConfig } = await import("./config-generator-RMWNQQHW.js");
1288
- const detectedResult = detectFrameworks(cwd);
1289
- const { frameworks } = detectedResult;
2115
+ const { fetchProRules } = await import("./pro-scanner-7NX6BST3.js");
2116
+ const { hasConfig, generateConfig } = await import("./config-generator-TUQCF2SD.js");
2117
+ const frameworks = detectedFrameworks;
1290
2118
  if (!hasConfig(cwd)) {
1291
- const configPath = generateConfig(cwd, detectedResult.frameworks);
2119
+ const configPath = generateConfig(cwd, frameworks);
1292
2120
  if (!machineOutput && !quiet) {
1293
2121
  logger.success(`Config saved to ${configPath}`);
1294
2122
  }
@@ -1299,11 +2127,11 @@ async function runScan(ctx) {
1299
2127
  }
1300
2128
  logger.info("Fetching pro rules...");
1301
2129
  }
1302
- const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : void 0;
1303
2130
  const fetched = await fetchProRules(
1304
2131
  frameworks.map((f) => f.name),
1305
- categories,
1306
- opts.apiUrl
2132
+ categories.length > 0 ? categories : void 0,
2133
+ opts.apiUrl,
2134
+ scanId
1307
2135
  );
1308
2136
  proRules = fetched.rules;
1309
2137
  creditsRemaining = fetched.creditsRemaining;
@@ -1329,13 +2157,39 @@ async function runScan(ctx) {
1329
2157
  }
1330
2158
  process.exit(EXIT_CODES.RUNTIME_ERROR);
1331
2159
  }
1332
- logger.warn(`Pro rules unavailable: ${errMsg}`);
1333
- logger.warn("Degrading to free scan \u2014 pro rules will not be applied");
1334
- degraded = true;
1335
- proFetchDegradeReason = {
1336
- code: "PRO_RULES_UNAVAILABLE",
1337
- detail: `Pro rules could not be fetched: ${errMsg}`
1338
- };
2160
+ const rawErrCode = err?.code;
2161
+ const KNOWN_PRO_FETCH_ERROR_CODES = [
2162
+ "AUTH_FAILED",
2163
+ "INSUFFICIENT_CREDITS",
2164
+ "RATE_LIMITED",
2165
+ "SERVER_ERROR",
2166
+ "BUNDLE_INVALID"
2167
+ ];
2168
+ const proErrorCode = typeof rawErrCode === "string" && KNOWN_PRO_FETCH_ERROR_CODES.includes(rawErrCode) ? rawErrCode : "SERVER_ERROR";
2169
+ const retryAfterSeconds = err?.retryAfterSeconds;
2170
+ if (opts.allowDegraded) {
2171
+ logger.warn("--allow-degraded set \u2014 degrading to free scan; pro rules will not be applied");
2172
+ degraded = true;
2173
+ proFetchDegradeReason = {
2174
+ code: "PRO_RULES_UNAVAILABLE",
2175
+ detail: `[${proErrorCode}] Pro rules could not be fetched: ${errMsg}`
2176
+ };
2177
+ } else {
2178
+ const action = proFetchActionHint(proErrorCode, retryAfterSeconds);
2179
+ logger.error(`Pro rules request failed [${proErrorCode}]: ${errMsg}`);
2180
+ logger.error(action);
2181
+ logger.error("Pass --allow-degraded to fall back to a free (local-rules-only) scan instead.");
2182
+ if (machineOutput) {
2183
+ console.log(JSON.stringify({
2184
+ error: errMsg,
2185
+ code: proErrorCode,
2186
+ degraded: false,
2187
+ action,
2188
+ ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
2189
+ }));
2190
+ }
2191
+ process.exit(EXIT_CODES.RUNTIME_ERROR);
2192
+ }
1339
2193
  }
1340
2194
  }
1341
2195
  const showProgress = shouldShowProgress({
@@ -1376,7 +2230,8 @@ async function runScan(ctx) {
1376
2230
  const skippedBinary = result._skippedBinary ?? 0;
1377
2231
  const truncatedByBounds = result._truncated ?? false;
1378
2232
  result.recommendation = result.riskScore.recommendation;
1379
- result.schemaVersion = "2";
2233
+ result.schemaVersion = "4";
2234
+ result.scanIdReused = scanIdReused;
1380
2235
  result.degraded = degraded || Boolean(result.degraded);
1381
2236
  if (result.degraded) {
1382
2237
  const existingReasons = result.degradedReasons ?? [];
@@ -1394,6 +2249,27 @@ async function runScan(ctx) {
1394
2249
  result.rulesBreakdown = breakdown;
1395
2250
  result.aiCodeIssues = result.findings.filter((f) => f.aiCodeTarget).length;
1396
2251
  }
2252
+ const proApplied = Boolean(proRules?.length) && !degraded;
2253
+ const historyOutcome = await recordScanHistory({
2254
+ cwd,
2255
+ scanId,
2256
+ cliVersion: CLI_VERSION,
2257
+ policy,
2258
+ changedOnly: scanOptions.changedOnly,
2259
+ categories,
2260
+ proRules,
2261
+ proApplied,
2262
+ rulesVersion,
2263
+ result
2264
+ });
2265
+ result.stateStatus = historyOutcome.stateStatus;
2266
+ result.regressionCheckSkipped = historyOutcome.regressionCheckSkipped;
2267
+ if (historyOutcome.regressionCheckSkipped) {
2268
+ result.regressionCheckSkippedReason = historyOutcome.regressionCheckSkippedReason;
2269
+ } else {
2270
+ result.regressions = historyOutcome.regressions;
2271
+ result.coverageChanged = historyOutcome.coverageChanged;
2272
+ }
1397
2273
  const publicResult = { ...result };
1398
2274
  delete publicResult._skippedTooLarge;
1399
2275
  delete publicResult._skippedTooLargeFiles;
@@ -1404,7 +2280,7 @@ async function runScan(ctx) {
1404
2280
  } else if (scanOptions.json) {
1405
2281
  console.log(JSON.stringify(publicResult, null, 2));
1406
2282
  } else if (quiet) {
1407
- console.log(quietVerdict(result));
2283
+ console.log(quietVerdict(result, scanOptions.strict));
1408
2284
  } else {
1409
2285
  const elapsedMs = Date.now() - startTime;
1410
2286
  const isTTY = Boolean(process.stdout.isTTY);
@@ -1424,7 +2300,7 @@ async function runScan(ctx) {
1424
2300
  `Scan INCOMPLETE: ${skippedTooLarge} file(s) skipped for exceeding the size limit \u2014 NOT scanned: ${named}${more}`
1425
2301
  );
1426
2302
  logger.warn(
1427
- `These files were not checked. Split/minify-exclude them, or raise \`limits.maxFileSizeBytes\` in shipguard.policy.yml. Verdict is degraded (exit 2).`
2303
+ `These files were not checked. Split/minify-exclude them, or raise \`limits.maxFileSizeBytes\` in shipguard.policy.yml. Verdict is degraded \u2014 see \`degraded\`/\`degradedReasons\` in --json output (does not change the exit code).`
1428
2304
  );
1429
2305
  }
1430
2306
  if (skippedBinary > 0) {
@@ -1433,6 +2309,9 @@ async function runScan(ctx) {
1433
2309
  if (creditsRemaining !== void 0) {
1434
2310
  logger.info(`Credits remaining: ${creditsRemaining}`);
1435
2311
  }
2312
+ if (scanIdReused) {
2313
+ logger.info("Retry detected \u2014 reused the prior scanId (no double charge for this retry)");
2314
+ }
1436
2315
  if (degraded) {
1437
2316
  logger.warn("Scan ran in degraded mode \u2014 pro rules were unavailable");
1438
2317
  }
@@ -1444,7 +2323,7 @@ async function runScan(ctx) {
1444
2323
  }
1445
2324
  console.log(coverageLine());
1446
2325
  console.log("");
1447
- console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary, result.findings));
2326
+ console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary, result.findings, scanOptions.strict));
1448
2327
  const topRuleId = result.findings.length > 0 ? result.findings[0].id : void 0;
1449
2328
  const isLoggedIn = Boolean(opts.pro && !degraded);
1450
2329
  console.log(actionFooter({
@@ -1490,34 +2369,29 @@ async function runScan(ctx) {
1490
2369
  }
1491
2370
  try {
1492
2371
  const elapsedMs = Date.now() - startTime;
1493
- const exitCode2 = resolveExitCode({
1494
- strict: scanOptions.strict,
1495
- blockingCount: result.riskScore.blockingCount,
1496
- degraded: Boolean(result.degraded)
1497
- });
1498
- const verdictMap = {
1499
- [EXIT_CODES.SAFE]: "safe",
1500
- [EXIT_CODES.BLOCKED]: "blocked",
1501
- [EXIT_CODES.CONFIG_ERROR]: "review",
1502
- [EXIT_CODES.RUNTIME_ERROR]: "error"
1503
- };
2372
+ const verdictBucket = result.degraded ? "review" : result.riskScore.blockingCount > 0 ? "blocked" : result.riskScore.recommendation === "REVIEW_BEFORE_SHIP" ? "review" : "safe";
1504
2373
  sendTelemetry({
1505
2374
  cliVersion: CLI_VERSION,
1506
- verdict: verdictMap[exitCode2] ?? "error",
2375
+ verdict: verdictBucket,
1507
2376
  durationMs: elapsedMs,
1508
2377
  ci: Boolean(process.env.CI),
1509
2378
  rulePackCount: proRules ? 1 : 0
1510
2379
  });
1511
2380
  } catch {
1512
2381
  }
1513
- const exitCode = resolveExitCode({
2382
+ let exitCode = resolveExitCode({
1514
2383
  strict: scanOptions.strict,
1515
- blockingCount: result.riskScore.blockingCount,
1516
- degraded: Boolean(result.degraded)
2384
+ blockingCount: result.riskScore.blockingCount
1517
2385
  });
1518
2386
  if (exitCode === EXIT_CODES.BLOCKED && !machineOutput && !quiet) {
1519
2387
  logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
1520
2388
  }
2389
+ if (opts.checkRegressions && exitCode === EXIT_CODES.SAFE && (result.regressions?.length ?? 0) > 0) {
2390
+ exitCode = EXIT_CODES.BLOCKED;
2391
+ if (!machineOutput && !quiet) {
2392
+ logger.warn(`--check-regressions: ${result.regressions?.length} previously-passing rule(s) now fail \u2014 exiting with code 1`);
2393
+ }
2394
+ }
1521
2395
  if (exitCode !== EXIT_CODES.SAFE) {
1522
2396
  process.exit(exitCode);
1523
2397
  }
@@ -1623,10 +2497,74 @@ function statusCommand() {
1623
2497
  });
1624
2498
  }
1625
2499
 
1626
- // src/commands/feedback.ts
2500
+ // src/commands/history.ts
1627
2501
  import { Command as Command6 } from "commander";
2502
+ import { resolve as resolve5 } from "path";
2503
+ var CLI_VERSION2 = true ? "0.5.0" : process.env.npm_package_version ?? "0.0.0-dev";
2504
+ function historyCommand() {
2505
+ 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) => {
2506
+ const cwd = scanPath ? resolve5(scanPath) : process.cwd();
2507
+ const machineOutput = Boolean(opts.json);
2508
+ const limit = opts.limit;
2509
+ let policy;
2510
+ try {
2511
+ policy = await loadPolicy(cwd);
2512
+ } catch (error) {
2513
+ logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
2514
+ return;
2515
+ }
2516
+ const identity = resolveRepoIdentity(cwd);
2517
+ const historyPath = resolveHistoryPath(cwd, policy);
2518
+ const openResult = await HistoryStore.open(historyPath, CLI_VERSION2);
2519
+ if (!openResult.ok) {
2520
+ if (machineOutput) {
2521
+ console.log(JSON.stringify({ version: 1, available: false, status: openResult.status, reason: openResult.reason }));
2522
+ } else {
2523
+ logger.warn(`History unavailable (${openResult.status}): ${openResult.reason}`);
2524
+ logger.info("No history to show. History is recorded automatically on the next successful scan.");
2525
+ }
2526
+ return;
2527
+ }
2528
+ const store = openResult.store;
2529
+ try {
2530
+ const scans = store.listRecentScans(identity.repoId, limit);
2531
+ if (machineOutput) {
2532
+ console.log(
2533
+ JSON.stringify({
2534
+ version: 1,
2535
+ available: true,
2536
+ historyPath,
2537
+ repoId: identity.repoId,
2538
+ repoIdKind: identity.repoIdKind,
2539
+ scans
2540
+ }, null, 2)
2541
+ );
2542
+ return;
2543
+ }
2544
+ if (scans.length === 0) {
2545
+ logger.info(`No scan history yet for this repo at ${historyPath}. Run \`shipguard scan\` to start recording.`);
2546
+ return;
2547
+ }
2548
+ logger.info(`Recent scans for this repo (${historyPath}):`);
2549
+ console.log("");
2550
+ for (const s of scans) {
2551
+ const ts = new Date(s.timestamp).toISOString();
2552
+ console.log(
2553
+ ` ${ts} ${(s.recommendation ?? "UNKNOWN").padEnd(18)} blocking:${s.blockingCount} state:${s.stateStatus} scope:${s.scopeFingerprint} corpus:${s.corpusVersion} (${s.scanId})`
2554
+ );
2555
+ }
2556
+ console.log("");
2557
+ logger.info("Full schema is documented and DIY-queryable: `sqlite3 " + historyPath + "`.");
2558
+ } finally {
2559
+ store.close();
2560
+ }
2561
+ });
2562
+ }
2563
+
2564
+ // src/commands/feedback.ts
2565
+ import { Command as Command7 } from "commander";
1628
2566
  function feedbackCommand() {
1629
- return new Command6("feedback").description("Send feedback about your last scan").argument("<text>", "Your feedback text").action(async (text) => {
2567
+ return new Command7("feedback").description("Send feedback about your last scan").argument("<text>", "Your feedback text").action(async (text) => {
1630
2568
  let token;
1631
2569
  try {
1632
2570
  const t = await getAuthToken();
@@ -1665,7 +2603,7 @@ function feedbackCommand() {
1665
2603
  });
1666
2604
  }
1667
2605
  function rateCommand() {
1668
- return new Command6("rate").description("Rate a finding from your last scan").argument("<findingNumber>", "Finding number from scan output").argument("<rating>", 'Rating: "helpful" or "not-helpful"').action(async (findingNumber, rating) => {
2606
+ return new Command7("rate").description("Rate a finding from your last scan").argument("<findingNumber>", "Finding number from scan output").argument("<rating>", 'Rating: "helpful" or "not-helpful"').action(async (findingNumber, rating) => {
1669
2607
  const num = parseInt(findingNumber, 10);
1670
2608
  if (isNaN(num) || num < 1) {
1671
2609
  logger.error("Finding number must be a positive integer.");
@@ -1750,13 +2688,13 @@ process.on("unhandledRejection", handleUnhandledRejection);
1750
2688
  process.on("SIGINT", handleSignal);
1751
2689
  process.on("SIGTERM", handleSignal);
1752
2690
  var ISSUES_URL3 = "https://github.com/agenticcli/shipguard/issues";
1753
- var program = new Command7();
2691
+ var program = new Command8();
1754
2692
  var rawArgs = process.argv.slice(2);
1755
2693
  if (rawArgs[0] === "?") {
1756
2694
  process.argv = [process.argv[0], process.argv[1], "help"];
1757
2695
  }
1758
2696
  program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
1759
- true ? "0.4.1" : process.env.npm_package_version ?? "0.0.0-dev"
2697
+ true ? "0.5.0" : process.env.npm_package_version ?? "0.0.0-dev"
1760
2698
  ).helpCommand(false).addHelpText("after", `
1761
2699
  Learn more:
1762
2700
  Docs https://agenticcli.dev/docs
@@ -1773,10 +2711,11 @@ addSubcommand(scanCommand());
1773
2711
  addSubcommand(loginCommand());
1774
2712
  addSubcommand(logoutCommand());
1775
2713
  addSubcommand(statusCommand());
2714
+ addSubcommand(historyCommand());
1776
2715
  addSubcommand(feedbackCommand());
1777
2716
  addSubcommand(rateCommand());
1778
2717
  program.addCommand(
1779
- new Command7("help").description("Show the quickstart guide").action(() => {
2718
+ new Command8("help").description("Show the quickstart guide").action(() => {
1780
2719
  const isTTY = Boolean(process.stdout.isTTY);
1781
2720
  process.stdout.write(quickstartHelp(isTTY) + "\n");
1782
2721
  })
@@ -1801,7 +2740,7 @@ function levenshtein(a, b) {
1801
2740
  return dp[m][n];
1802
2741
  }
1803
2742
  function closestCommand(input) {
1804
- const names = ["scan", "init", "login", "logout", "status", "feedback", "rate", "help"];
2743
+ const names = ["scan", "init", "login", "logout", "status", "history", "feedback", "rate", "help"];
1805
2744
  let best;
1806
2745
  let bestDist = Infinity;
1807
2746
  for (const name of names) {
@@ -1814,7 +2753,7 @@ function closestCommand(input) {
1814
2753
  return bestDist <= 3 ? best : void 0;
1815
2754
  }
1816
2755
  (async () => {
1817
- const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "feedback", "rate", "help"]);
2756
+ const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "history", "feedback", "rate", "help"]);
1818
2757
  const firstNonFlag = process.argv.slice(2).find((a) => !a.startsWith("-"));
1819
2758
  if (firstNonFlag && firstNonFlag !== "?" && !KNOWN_COMMANDS.has(firstNonFlag)) {
1820
2759
  const suggestion = closestCommand(firstNonFlag);