shield-llm 0.10.0 → 0.11.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.
@@ -8965,7 +8965,7 @@ function evaluateBenign(input) {
8965
8965
  }
8966
8966
 
8967
8967
  // package.json
8968
- var version = "0.10.0";
8968
+ var version = "0.11.0";
8969
8969
 
8970
8970
  // src/config/schema.ts
8971
8971
  import { z as z2 } from "zod";
@@ -9862,11 +9862,22 @@ async function fetchWithTimeout(url, init, timeoutMs, responseField, allowPrivat
9862
9862
  }
9863
9863
  const controller = new AbortController();
9864
9864
  const existingSignal = init.signal;
9865
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
9865
+ let timedOut = false;
9866
+ const timeout = setTimeout(() => {
9867
+ timedOut = true;
9868
+ controller.abort();
9869
+ }, timeoutMs);
9866
9870
  if (existingSignal) {
9867
9871
  existingSignal.addEventListener("abort", () => controller.abort());
9868
9872
  }
9869
9873
  try {
9874
+ return await sendAndRead();
9875
+ } catch (err) {
9876
+ throw describeTimeout(err, timedOut, timeoutMs, existingSignal);
9877
+ } finally {
9878
+ clearTimeout(timeout);
9879
+ }
9880
+ async function sendAndRead() {
9870
9881
  const response = await doFetch(url, {
9871
9882
  ...init,
9872
9883
  signal: controller.signal,
@@ -9928,10 +9939,23 @@ async function fetchWithTimeout(url, init, timeoutMs, responseField, allowPrivat
9928
9939
  0
9929
9940
  );
9930
9941
  }
9931
- } finally {
9932
- clearTimeout(timeout);
9933
9942
  }
9934
9943
  }
9944
+ function describeTimeout(err, timedOut, timeoutMs, callerSignal) {
9945
+ const timeoutError = (message) => Object.assign(new Error(message), { name: "TimeoutError" });
9946
+ if (timedOut) {
9947
+ return timeoutError(
9948
+ `No answer within ${timeoutMs / 1e3} s: the target timed out`
9949
+ );
9950
+ }
9951
+ const reason = callerSignal?.aborted ? callerSignal.reason : void 0;
9952
+ if (reason?.name === "TimeoutError") {
9953
+ return timeoutError(
9954
+ "No answer before the attack's time budget ran out: the target timed out"
9955
+ );
9956
+ }
9957
+ return err;
9958
+ }
9935
9959
  var ERROR_BODY_HEAD_BYTES = 8192;
9936
9960
  async function readErrorBodyHead(response) {
9937
9961
  try {
package/dist/cli.js CHANGED
@@ -75,7 +75,7 @@ import {
75
75
  sha256Hex,
76
76
  summarizeAttackErrors,
77
77
  version
78
- } from "./chunk-GJQFYKMY.js";
78
+ } from "./chunk-ZK35FYSR.js";
79
79
 
80
80
  // src/load-env.ts
81
81
  try {
@@ -1577,7 +1577,7 @@ function printAttackComplete(event) {
1577
1577
  spinner.start();
1578
1578
  }
1579
1579
  }
1580
- function printSummary(report, thresholds) {
1580
+ function printSummary(report, thresholds, gate) {
1581
1581
  console.log("");
1582
1582
  console.log(c.bold("\u2550\u2550\u2550 Shield LLM Scan Results \u2550\u2550\u2550"));
1583
1583
  console.log("");
@@ -1636,7 +1636,13 @@ function printSummary(report, thresholds) {
1636
1636
  );
1637
1637
  }
1638
1638
  console.log("");
1639
- if (thresholds.passed) {
1639
+ if (!gate.thresholdsConfigured) {
1640
+ console.log(
1641
+ c.yellow(
1642
+ " No threshold set: this run gates nothing (add --min-score or --fail-on-critical to fail CI on it)."
1643
+ )
1644
+ );
1645
+ } else if (thresholds.passed) {
1640
1646
  console.log(c.greenBold(" \u2713 PASSED \u2014 all thresholds met"));
1641
1647
  } else {
1642
1648
  console.log(c.redBold(" \u2717 FAILED \u2014 threshold violations:"));
@@ -1682,11 +1688,80 @@ function gradeColor(grade) {
1682
1688
  }
1683
1689
  }
1684
1690
 
1691
+ // src/fix/claim-store.ts
1692
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync5 } from "fs";
1693
+ import { dirname, join as join2 } from "path";
1694
+ var DEFAULT_CLAIM_FILE = ".shield-llm/claims.json";
1695
+ var ClaimStore = class _ClaimStore {
1696
+ constructor(path) {
1697
+ this.path = path;
1698
+ }
1699
+ static at(root, file = DEFAULT_CLAIM_FILE) {
1700
+ return new _ClaimStore(join2(root, file));
1701
+ }
1702
+ load() {
1703
+ if (!existsSync3(this.path)) return null;
1704
+ return JSON.parse(readFileSync3(this.path, "utf8"));
1705
+ }
1706
+ list() {
1707
+ return this.load()?.claims ?? [];
1708
+ }
1709
+ /**
1710
+ * Claims a verification run should look at.
1711
+ *
1712
+ * `refuted_or_not_deployed` is included ON PURPOSE. That status means exactly
1713
+ * "still vulnerable, and we cannot tell whether the patch failed or was
1714
+ * simply not live yet" — so treating it as terminal would make the normal
1715
+ * sequence (patch → verify → deploy → verify again) impossible: the second
1716
+ * verification would find nothing to check. `inconclusive` is included for
1717
+ * the same reason: the family was not executed, so nothing was decided.
1718
+ *
1719
+ * Terminal, and therefore excluded: `confirmed`, `confirmed_overfit`,
1720
+ * `expired`.
1721
+ */
1722
+ openForVerification() {
1723
+ return this.list().filter(
1724
+ (c2) => c2.status === "pending" || c2.status === "refuted_or_not_deployed" || c2.status === "inconclusive"
1725
+ );
1726
+ }
1727
+ pending() {
1728
+ return this.list().filter((c2) => c2.status === "pending");
1729
+ }
1730
+ /** Upsert by fingerprint+recipe: re-running `fix` refreshes, never duplicates. */
1731
+ upsert(targetId, claim) {
1732
+ const current = this.load() ?? { version: 1, targetId, claims: [] };
1733
+ const idx = current.claims.findIndex(
1734
+ (c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
1735
+ );
1736
+ if (idx === -1) current.claims.push(claim);
1737
+ else current.claims[idx] = claim;
1738
+ this.write({ ...current, targetId });
1739
+ }
1740
+ replace(claim) {
1741
+ const current = this.load();
1742
+ if (!current) return;
1743
+ const idx = current.claims.findIndex(
1744
+ (c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
1745
+ );
1746
+ if (idx !== -1) current.claims[idx] = claim;
1747
+ this.write(current);
1748
+ }
1749
+ write(file) {
1750
+ mkdirSync2(dirname(this.path), { recursive: true });
1751
+ writeFileSync5(this.path, `${JSON.stringify(file, null, 2)}
1752
+ `, "utf8");
1753
+ }
1754
+ };
1755
+
1685
1756
  // src/lib/format.ts
1686
1757
  function truncate(str, max) {
1687
1758
  const oneLine = str.replace(/\n/g, " ").trim();
1688
1759
  return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
1689
1760
  }
1761
+ function excerpt(str, max) {
1762
+ const text = str.trim();
1763
+ return text.length <= max ? text : text.slice(0, max - 3) + "...";
1764
+ }
1690
1765
 
1691
1766
  // src/retest-core.ts
1692
1767
  function selectRetestableFindings(vulns, filter, targetUrl) {
@@ -1775,12 +1850,12 @@ function buildRetestOutcome(results, findingByResultId) {
1775
1850
  name: finding.name,
1776
1851
  vulnerable: result.vulnerable,
1777
1852
  evidence: JSON.stringify({
1778
- prompt: truncate(result.prompt, EVIDENCE_PROMPT_CAP),
1779
- response: truncate(result.response, EVIDENCE_RESPONSE_CAP)
1853
+ prompt: excerpt(result.prompt, EVIDENCE_PROMPT_CAP),
1854
+ response: excerpt(result.response, EVIDENCE_RESPONSE_CAP)
1780
1855
  }),
1781
1856
  evaluationMethod: result.llmEvaluation?.evaluationMethod,
1782
1857
  confidence: result.llmEvaluation?.confidence,
1783
- reasoning: result.llmEvaluation?.reasoning ? truncate(result.llmEvaluation.reasoning, REASONING_CAP) : void 0
1858
+ reasoning: result.llmEvaluation?.reasoning ? excerpt(result.llmEvaluation.reasoning, REASONING_CAP) : void 0
1784
1859
  });
1785
1860
  }
1786
1861
  return outcome;
@@ -1790,6 +1865,14 @@ function decideExitCode(summary) {
1790
1865
  if (summary.fixed > 0) return 0;
1791
1866
  return 3;
1792
1867
  }
1868
+ function claimContradiction(attackId, targetUrl, claims, scanCreatedAt) {
1869
+ const fingerprint = fingerprintFromScan(targetUrl, attackId);
1870
+ const since = scanCreatedAt ? Date.parse(scanCreatedAt) : -Infinity;
1871
+ const newest = claims.filter(
1872
+ (c2) => c2.findingFingerprint === fingerprint && Date.parse(c2.createdAt) >= since
1873
+ ).sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))[0];
1874
+ return newest?.status === "confirmed_overfit" || newest?.status === "refuted_or_not_deployed" ? newest.status : void 0;
1875
+ }
1793
1876
 
1794
1877
  // src/commands/retest.ts
1795
1878
  function findingLabel(finding) {
@@ -1995,6 +2078,10 @@ async function retestCommand(scanId, opts) {
1995
2078
  }
1996
2079
  const fixed = outcome.verifications.filter((v) => !v.vulnerable);
1997
2080
  const stillVulnerable = outcome.verifications.filter((v) => v.vulnerable);
2081
+ const localStore = ClaimStore.at(process.cwd()).load();
2082
+ const localClaims = localStore?.targetId === normalizeTargetUrl(scan.targetUrl) ? localStore.claims : [];
2083
+ const openClaim = (attackId) => claimContradiction(attackId, scan.targetUrl, localClaims, scan.createdAt);
2084
+ const variantsOpen = fixed.filter((v) => openClaim(v.attackId));
1998
2085
  if (opts.ci) {
1999
2086
  console.log(
2000
2087
  JSON.stringify(
@@ -2008,7 +2095,8 @@ async function retestCommand(scanId, opts) {
2008
2095
  results: outcome.verifications.map((v) => ({
2009
2096
  attackId: v.attackId,
2010
2097
  name: v.name,
2011
- outcome: v.vulnerable ? "still_vulnerable" : "fixed"
2098
+ outcome: v.vulnerable ? "still_vulnerable" : "fixed",
2099
+ ...!v.vulnerable && openClaim(v.attackId) ? { claimStatus: openClaim(v.attackId) } : {}
2012
2100
  })),
2013
2101
  failed: outcome.failed.map((f) => ({
2014
2102
  attackId: f.finding.attackId,
@@ -2029,7 +2117,10 @@ async function retestCommand(scanId, opts) {
2029
2117
  } else {
2030
2118
  console.log("");
2031
2119
  for (const v of fixed) {
2032
- console.log(` \u2713 FIXED & VERIFIED ${v.name}`);
2120
+ const open = openClaim(v.attackId);
2121
+ console.log(
2122
+ open ? ` ~ EXPLOIT CLOSED ${v.name} \u2014 its fix's own verification found ` + (open === "confirmed_overfit" ? "the variants still open (confirmed_overfit)" : "the target still vulnerable (refuted_or_not_deployed)") : ` \u2713 FIXED & VERIFIED ${v.name}`
2123
+ );
2033
2124
  }
2034
2125
  for (const v of stillVulnerable) {
2035
2126
  console.log(` \u2717 STILL VULNERABLE ${v.name}`);
@@ -2044,7 +2135,7 @@ async function retestCommand(scanId, opts) {
2044
2135
  }
2045
2136
  console.log("");
2046
2137
  console.log(
2047
- `Retest complete: ${fixed.length} fixed & verified, ${stillVulnerable.length} still vulnerable` + (outcome.failed.length + plan.unavailable.length > 0 ? `, ${outcome.failed.length + plan.unavailable.length} not retested` : "") + "."
2138
+ `Retest complete: ${fixed.length - variantsOpen.length} fixed & verified, ` + (variantsOpen.length ? `${variantsOpen.length} exploit closed but its fix not confirmed, ` : "") + `${stillVulnerable.length} still vulnerable` + (outcome.failed.length + plan.unavailable.length > 0 ? `, ${outcome.failed.length + plan.unavailable.length} not retested` : "") + "."
2048
2139
  );
2049
2140
  if (verify2) {
2050
2141
  console.log(
@@ -2095,8 +2186,7 @@ function safeHostname(url) {
2095
2186
  }
2096
2187
 
2097
2188
  // src/commands/scan.ts
2098
- import { writeFileSync as writeFileSync7 } from "fs";
2099
- import { resolve as resolve4 } from "path";
2189
+ import { resolve as resolve5 } from "path";
2100
2190
 
2101
2191
  // src/reporters/evidence.ts
2102
2192
  import { writeFileSync as writeFileSync6 } from "fs";
@@ -2106,6 +2196,24 @@ import { resolve as resolve3 } from "path";
2106
2196
  import { createHash } from "crypto";
2107
2197
 
2108
2198
  // ../../packages/shared/src/compliance/remediation-validation.ts
2199
+ function claimScopeForScan(scan) {
2200
+ return {
2201
+ scanStartedAt: scan.startedAt,
2202
+ detectedFingerprints: new Set(
2203
+ Array.from(
2204
+ scan.detectedAttackIds,
2205
+ (id) => fingerprintFromScan(scan.targetUrl, id)
2206
+ )
2207
+ )
2208
+ };
2209
+ }
2210
+ function claimScanRelation(claim, scope) {
2211
+ const detected = scope.detectedFingerprints.has(claim.findingFingerprint);
2212
+ if (Date.parse(claim.createdAt) >= Date.parse(scope.scanStartedAt)) {
2213
+ return detected ? "this_scan" : "unrelated";
2214
+ }
2215
+ return detected ? "earlier_detected_again" : "earlier_not_detected";
2216
+ }
2109
2217
  var INFORMATIVE = "Records of Shield's remediation loop for the findings of this target: each fix's frozen verification contract and every post-deploy re-test with its per-attack result. Offered as evidence a financial entity's own internal validation methodology (DORA Art. 24(5)) can rely on. The obligation binds the entity; this block does not state that the entity complies.";
2110
2218
  function toClaim(c2) {
2111
2219
  const live = c2.liveVerification;
@@ -2143,9 +2251,23 @@ function toClaim(c2) {
2143
2251
  }))
2144
2252
  };
2145
2253
  }
2146
- function buildRemediationValidation(claims) {
2147
- const paragraph = DORA_PARAGRAPHS["Art. 24(5)"];
2254
+ function summarize(claims) {
2148
2255
  const count = (s) => claims.filter((c2) => c2.status === s).length;
2256
+ return {
2257
+ total: claims.length,
2258
+ confirmed: count("confirmed"),
2259
+ confirmedOverfit: count("confirmed_overfit"),
2260
+ refutedOrNotDeployed: count("refuted_or_not_deployed"),
2261
+ pending: count("pending"),
2262
+ inconclusive: count("inconclusive"),
2263
+ expired: count("expired"),
2264
+ withVerificationEvidence: claims.filter(
2265
+ (c2) => (c2.verifications ?? []).length > 0
2266
+ ).length
2267
+ };
2268
+ }
2269
+ function buildRemediationValidation(claims, scope) {
2270
+ const paragraph = DORA_PARAGRAPHS["Art. 24(5)"];
2149
2271
  return {
2150
2272
  informative: INFORMATIVE,
2151
2273
  regulation: {
@@ -2155,19 +2277,16 @@ function buildRemediationValidation(claims) {
2155
2277
  verifiedOn: DORA_PARAGRAPHS_VERIFIED_ON,
2156
2278
  source: "http://publications.europa.eu/resource/celex/32022R2554"
2157
2279
  },
2158
- claims: claims.map(toClaim),
2159
- summary: {
2160
- total: claims.length,
2161
- confirmed: count("confirmed"),
2162
- confirmedOverfit: count("confirmed_overfit"),
2163
- refutedOrNotDeployed: count("refuted_or_not_deployed"),
2164
- pending: count("pending"),
2165
- inconclusive: count("inconclusive"),
2166
- expired: count("expired"),
2167
- withVerificationEvidence: claims.filter(
2168
- (c2) => (c2.verifications ?? []).length > 0
2169
- ).length
2170
- }
2280
+ claims: claims.map((c2) => {
2281
+ const claim = toClaim(c2);
2282
+ return scope ? { ...claim, scanRelation: claimScanRelation(c2, scope) } : claim;
2283
+ }),
2284
+ summary: summarize(claims),
2285
+ ...scope ? {
2286
+ thisScanSummary: summarize(
2287
+ claims.filter((c2) => claimScanRelation(c2, scope) === "this_scan")
2288
+ )
2289
+ } : {}
2171
2290
  };
2172
2291
  }
2173
2292
 
@@ -2351,7 +2470,7 @@ function buildEvidenceBundle(input2) {
2351
2470
  },
2352
2471
  crosswalk: buildCrosswalkBlock(),
2353
2472
  structuralAssessment: input2.assessment ?? null,
2354
- remediationValidation: input2.claims ? buildRemediationValidation(input2.claims) : null,
2473
+ remediationValidation: input2.claims ? buildRemediationValidation(input2.claims, input2.claimScope) : null,
2355
2474
  tests: budgetedTests(input2.tests),
2356
2475
  limitations: [
2357
2476
  ...bundleLimitations(
@@ -2398,71 +2517,6 @@ function toComplianceOutcomes(attacks) {
2398
2517
  }));
2399
2518
  }
2400
2519
 
2401
- // src/fix/claim-store.ts
2402
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync5 } from "fs";
2403
- import { dirname, join as join2 } from "path";
2404
- var DEFAULT_CLAIM_FILE = ".shield-llm/claims.json";
2405
- var ClaimStore = class _ClaimStore {
2406
- constructor(path) {
2407
- this.path = path;
2408
- }
2409
- static at(root, file = DEFAULT_CLAIM_FILE) {
2410
- return new _ClaimStore(join2(root, file));
2411
- }
2412
- load() {
2413
- if (!existsSync3(this.path)) return null;
2414
- return JSON.parse(readFileSync3(this.path, "utf8"));
2415
- }
2416
- list() {
2417
- return this.load()?.claims ?? [];
2418
- }
2419
- /**
2420
- * Claims a verification run should look at.
2421
- *
2422
- * `refuted_or_not_deployed` is included ON PURPOSE. That status means exactly
2423
- * "still vulnerable, and we cannot tell whether the patch failed or was
2424
- * simply not live yet" — so treating it as terminal would make the normal
2425
- * sequence (patch → verify → deploy → verify again) impossible: the second
2426
- * verification would find nothing to check. `inconclusive` is included for
2427
- * the same reason: the family was not executed, so nothing was decided.
2428
- *
2429
- * Terminal, and therefore excluded: `confirmed`, `confirmed_overfit`,
2430
- * `expired`.
2431
- */
2432
- openForVerification() {
2433
- return this.list().filter(
2434
- (c2) => c2.status === "pending" || c2.status === "refuted_or_not_deployed" || c2.status === "inconclusive"
2435
- );
2436
- }
2437
- pending() {
2438
- return this.list().filter((c2) => c2.status === "pending");
2439
- }
2440
- /** Upsert by fingerprint+recipe: re-running `fix` refreshes, never duplicates. */
2441
- upsert(targetId, claim) {
2442
- const current = this.load() ?? { version: 1, targetId, claims: [] };
2443
- const idx = current.claims.findIndex(
2444
- (c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
2445
- );
2446
- if (idx === -1) current.claims.push(claim);
2447
- else current.claims[idx] = claim;
2448
- this.write({ ...current, targetId });
2449
- }
2450
- replace(claim) {
2451
- const current = this.load();
2452
- if (!current) return;
2453
- const idx = current.claims.findIndex(
2454
- (c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
2455
- );
2456
- if (idx !== -1) current.claims[idx] = claim;
2457
- this.write(current);
2458
- }
2459
- write(file) {
2460
- mkdirSync2(dirname(this.path), { recursive: true });
2461
- writeFileSync5(this.path, `${JSON.stringify(file, null, 2)}
2462
- `, "utf8");
2463
- }
2464
- };
2465
-
2466
2520
  // src/reporters/evidence.ts
2467
2521
  function claimsForTarget(target, cwd) {
2468
2522
  const file = ClaimStore.at(cwd).load();
@@ -2487,11 +2541,12 @@ function writeEvidenceBundle(input2) {
2487
2541
  responseExcerpt: a.response
2488
2542
  }));
2489
2543
  const claims = claimsForTarget(input2.report.target, input2.cwd ?? process.cwd());
2544
+ const startedAt = new Date(input2.report.timestamp).toISOString();
2490
2545
  const bundle = buildEvidenceBundle({
2491
2546
  scan: {
2492
2547
  scanId: input2.report.id,
2493
2548
  target: input2.report.target,
2494
- startedAt: new Date(input2.report.timestamp).toISOString(),
2549
+ startedAt,
2495
2550
  preset: input2.report.config.preset,
2496
2551
  attackPackVersion: ATTACK_PACK_VERSION,
2497
2552
  testsRun: executed.length,
@@ -2502,6 +2557,13 @@ function writeEvidenceBundle(input2) {
2502
2557
  compliance: input2.compliance,
2503
2558
  tests,
2504
2559
  claims,
2560
+ // Same scoping as the web bundle: a claim of an earlier run of this
2561
+ // target is context, not this scan's remediation.
2562
+ claimScope: claimScopeForScan({
2563
+ targetUrl: input2.report.target,
2564
+ startedAt,
2565
+ detectedAttackIds: input2.report.attacks.filter((a) => a.vulnerable).map((a) => baseAttackId(a.id))
2566
+ }),
2505
2567
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
2506
2568
  });
2507
2569
  const outPath = resolve3(input2.path);
@@ -2556,6 +2618,18 @@ function sanitizeReportForDisk(report, opts = {}) {
2556
2618
  }
2557
2619
 
2558
2620
  // src/lib/output-path.ts
2621
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync7 } from "fs";
2622
+ import { dirname as dirname2, resolve as resolve4 } from "path";
2623
+ function writeOutputFile(path, content) {
2624
+ const full = resolve4(path);
2625
+ mkdirSync3(dirname2(full), { recursive: true });
2626
+ writeFileSync7(
2627
+ full,
2628
+ content,
2629
+ typeof content === "string" ? "utf-8" : void 0
2630
+ );
2631
+ return full;
2632
+ }
2559
2633
  var FORMAT_EXTENSIONS = {
2560
2634
  json: ".json",
2561
2635
  markdown: ".md",
@@ -2632,10 +2706,10 @@ function buildUploadVulnerabilities(attacks) {
2632
2706
  description: a.name,
2633
2707
  evidence: a.prompt && a.response ? JSON.stringify({
2634
2708
  prompt: a.prompt,
2635
- response: truncate(a.response, 2e3)
2709
+ response: excerpt(a.response, 2e3)
2636
2710
  }) : a.response ? JSON.stringify({
2637
2711
  prompt: "",
2638
- response: truncate(a.response, 2e3)
2712
+ response: excerpt(a.response, 2e3)
2639
2713
  }) : void 0,
2640
2714
  status: a.vulnerable ? "DETECTED" : "PASSED",
2641
2715
  evaluationMethod: a.llmEvaluation?.evaluationMethod,
@@ -2711,7 +2785,9 @@ async function uploadReportToBackend(report, credentials, scanId, attackPackVers
2711
2785
  if (incomplete) throw new IncompleteRejection(incomplete);
2712
2786
  const notStored = notStoredRejection(res.status, body);
2713
2787
  if (notStored) throw new NotStoredRejection(notStored);
2714
- throw new Error(`HTTP ${res.status}: ${printableServerText(body.slice(0, 200))}`);
2788
+ throw new Error(
2789
+ `HTTP ${res.status}: ${printableServerText(body.slice(0, 200))}`
2790
+ );
2715
2791
  }
2716
2792
  const data = await res.json().catch(() => ({}));
2717
2793
  return {
@@ -2975,9 +3051,9 @@ async function scanCommand(opts) {
2975
3051
  systemPromptHash: systemPrompt,
2976
3052
  catalogHash
2977
3053
  });
2978
- const checkpointDir = opts.checkpointDir ?? resolve4(process.cwd(), ".shield-llm", "checkpoints");
3054
+ const checkpointDir = opts.checkpointDir ?? resolve5(process.cwd(), ".shield-llm", "checkpoints");
2979
3055
  const checkpointStore = new FileCheckpointStore(
2980
- resolve4(checkpointDir, `scan-${scanKey}.jsonl`)
3056
+ resolve5(checkpointDir, `scan-${scanKey}.jsonl`)
2981
3057
  );
2982
3058
  if (opts.resume === false) {
2983
3059
  await checkpointStore.finalize();
@@ -3151,11 +3227,17 @@ async function scanCommand(opts) {
3151
3227
  }
3152
3228
  }
3153
3229
  if (!opts.ci) {
3154
- printSummary(report, thresholdResult);
3230
+ printSummary(report, thresholdResult, { thresholdsConfigured });
3155
3231
  if (complianceResult) {
3156
3232
  console.log(formatComplianceTerminal(complianceResult, report.target));
3157
3233
  }
3158
3234
  if (evidenceBundleNote) console.log(evidenceBundleNote);
3235
+ if (uploadedScanId) {
3236
+ console.log(
3237
+ ` Dashboard: ${credentials.apiUrl}/scans/${uploadedScanId}
3238
+ `
3239
+ );
3240
+ }
3159
3241
  }
3160
3242
  const format = config.output?.format ?? opts.output;
3161
3243
  let outputFile = config.output?.file ?? opts.outputFile;
@@ -3172,7 +3254,7 @@ async function scanCommand(opts) {
3172
3254
  if (format === "pdf") {
3173
3255
  const pdfPath = outputFile ?? `shield-report-${report.id.slice(0, 8)}.pdf`;
3174
3256
  const pdfBuffer = await generatePdf(report);
3175
- writeFileSync7(resolve4(pdfPath), pdfBuffer);
3257
+ writeOutputFile(pdfPath, pdfBuffer);
3176
3258
  info(`PDF report written to ${pdfPath}`);
3177
3259
  } else {
3178
3260
  let content;
@@ -3194,7 +3276,7 @@ async function scanCommand(opts) {
3194
3276
  break;
3195
3277
  }
3196
3278
  if (outputFile) {
3197
- writeFileSync7(resolve4(outputFile), content, "utf-8");
3279
+ writeOutputFile(outputFile, content);
3198
3280
  info(`Report written to ${outputFile}`);
3199
3281
  } else {
3200
3282
  console.log(content);
@@ -3202,7 +3284,7 @@ async function scanCommand(opts) {
3202
3284
  }
3203
3285
  }
3204
3286
  if (opts.writeJson) {
3205
- const jsonPath = resolve4(opts.writeJson);
3287
+ const jsonPath = resolve5(opts.writeJson);
3206
3288
  const reportForDisk = opts.includeFullPayloads ? report : sanitizeReportForDisk(report);
3207
3289
  const jsonContent = formatJson({
3208
3290
  report: reportForDisk,
@@ -3210,7 +3292,7 @@ async function scanCommand(opts) {
3210
3292
  thresholdsConfigured,
3211
3293
  compliance: complianceResult
3212
3294
  });
3213
- writeFileSync7(jsonPath, jsonContent, "utf-8");
3295
+ writeOutputFile(jsonPath, jsonContent);
3214
3296
  info(
3215
3297
  `JSON copy written to ${jsonPath}${opts.includeFullPayloads ? " (full payloads)" : " (sanitized)"}`
3216
3298
  );
@@ -3539,11 +3621,11 @@ function validateCommand(opts) {
3539
3621
  // src/commands/fix.ts
3540
3622
  import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync } from "fs";
3541
3623
  import { execFileSync as execFileSync3 } from "child_process";
3542
- import { resolve as resolve6 } from "path";
3624
+ import { resolve as resolve7 } from "path";
3543
3625
 
3544
3626
  // src/fix/anchor-resolver.ts
3545
3627
  import { existsSync as existsSync4, readFileSync as readFileSync4, statSync } from "fs";
3546
- import { isAbsolute, relative, resolve as resolve5, sep } from "path";
3628
+ import { isAbsolute, relative, resolve as resolve6, sep } from "path";
3547
3629
  var AnchorError = class extends Error {
3548
3630
  constructor(message, kind, status) {
3549
3631
  super(message);
@@ -3556,8 +3638,8 @@ function safeResolve(root, relPath) {
3556
3638
  if (isAbsolute(relPath)) {
3557
3639
  throw new Error(`path must be repo-relative, got absolute: ${relPath}`);
3558
3640
  }
3559
- const rootAbs = resolve5(root);
3560
- const abs = resolve5(rootAbs, relPath);
3641
+ const rootAbs = resolve6(root);
3642
+ const abs = resolve6(rootAbs, relPath);
3561
3643
  const rel = relative(rootAbs, abs);
3562
3644
  if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) {
3563
3645
  throw new Error(`path escapes the codebase root: ${relPath}`);
@@ -3621,7 +3703,7 @@ function resolveAll(codebase, rootDir) {
3621
3703
  return out;
3622
3704
  }
3623
3705
  function safeResolveRoot(cwd, root) {
3624
- if (root === "." || root === "./") return resolve5(cwd);
3706
+ if (root === "." || root === "./") return resolve6(cwd);
3625
3707
  return safeResolve(cwd, root);
3626
3708
  }
3627
3709
 
@@ -3688,6 +3770,21 @@ function evaluateVerdict(input2, options = {}) {
3688
3770
  }
3689
3771
 
3690
3772
  // src/fix/plan.ts
3773
+ var NO_RECIPE_DETAIL = `no v1 recipe covers these attacks: v1 patches ${RECIPES.flatMap((r) => r.appliesTo).join(", ")}; the others need a code or architecture change and become issues`;
3774
+ function groupSkipped(skipped) {
3775
+ const groups = /* @__PURE__ */ new Map();
3776
+ for (const s of skipped) {
3777
+ const key = `${s.reason}|${s.detail}`;
3778
+ const group = groups.get(key) ?? {
3779
+ reason: s.reason,
3780
+ detail: s.detail,
3781
+ attackIds: []
3782
+ };
3783
+ group.attackIds.push(s.attackId);
3784
+ groups.set(key, group);
3785
+ }
3786
+ return Array.from(groups.values());
3787
+ }
3691
3788
  function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
3692
3789
  const targetId = normalizeTargetUrl(targetUrl);
3693
3790
  const anchors = resolveAll(codebase, cwd);
@@ -3720,10 +3817,7 @@ function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
3720
3817
  (r) => r.appliesTo.includes(f.attackId)
3721
3818
  );
3722
3819
  if (candidates.length === 0) {
3723
- push(
3724
- "no_recipe_for_attack",
3725
- "no v1 recipe covers this attack \u2014 architecture-layer and multi-turn findings are issue-only by design"
3726
- );
3820
+ push("no_recipe_for_attack", NO_RECIPE_DETAIL);
3727
3821
  continue;
3728
3822
  }
3729
3823
  const stackOk = candidates.filter(
@@ -3789,8 +3883,8 @@ function blockedByAnchor(anchors) {
3789
3883
  }
3790
3884
 
3791
3885
  // src/fix/operations.ts
3792
- import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync, writeFileSync as writeFileSync8 } from "fs";
3793
- import { dirname as dirname2, relative as relative2 } from "path";
3886
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync, writeFileSync as writeFileSync8 } from "fs";
3887
+ import { dirname as dirname3, relative as relative2 } from "path";
3794
3888
 
3795
3889
  // src/fix/marker-block.ts
3796
3890
  var EXT_STYLE = {
@@ -3980,7 +4074,7 @@ var WorkingSet = class {
3980
4074
  if (existsSync5(abs)) rmSync(abs);
3981
4075
  continue;
3982
4076
  }
3983
- mkdirSync3(dirname2(abs), { recursive: true });
4077
+ mkdirSync4(dirname3(abs), { recursive: true });
3984
4078
  writeFileSync8(abs, current, "utf8");
3985
4079
  }
3986
4080
  }
@@ -4204,13 +4298,21 @@ function revertRecipe(recipe, ctx) {
4204
4298
  // src/fix/pr-body.ts
4205
4299
  var DISCLAIMER = "This patch is generated from an automated security scan. It reduces exposure to the listed attacks; it does not certify the system as secure. Review it as you would any other change \u2014 you remain responsible for what you merge.";
4206
4300
  function proseFor(recipe) {
4207
- const prose = getStructuredRemediation(recipe.remediationRef.vulnerabilityType);
4208
- const layer = prose.layers.find((l) => l.layer === recipe.remediationRef.layer);
4301
+ const prose = getStructuredRemediation(
4302
+ recipe.remediationRef.vulnerabilityType
4303
+ );
4304
+ const layer = prose.layers.find(
4305
+ (l) => l.layer === recipe.remediationRef.layer
4306
+ );
4209
4307
  if (!layer) return [];
4210
4308
  return recipe.remediationRef.stepIndexes.map((i) => layer.steps[i]).filter(Boolean).map((s) => `> ${s.text}${s.owaspRef ? ` _(${s.owaspRef})_` : ""}`);
4211
4309
  }
4212
4310
  function liveSection(v) {
4213
- const lines = ["", "**Verified live before this PR opened**", ""];
4311
+ const lines = [
4312
+ "",
4313
+ v.passed ? "**Verified live before this PR opened**" : "**Refused by the live verification**",
4314
+ ""
4315
+ ];
4214
4316
  lines.push(
4215
4317
  `- Redeployed with \`${v.redeployCommand}\`, then the attack family was replayed against the running target (${v.verifiedAt}).`
4216
4318
  );
@@ -4218,8 +4320,11 @@ function liveSection(v) {
4218
4320
  `- Design attacks closed: ${v.designClearedIds.length}/${v.designAttackIds.length}` + (v.designClearedIds.length ? ` (${v.designClearedIds.join(", ")})` : "")
4219
4321
  );
4220
4322
  if (v.holdoutAttackIds.length) {
4323
+ const open = v.holdoutAttackIds.filter(
4324
+ (a) => !v.holdoutClearedIds.includes(a)
4325
+ );
4221
4326
  lines.push(
4222
- `- Holdout attacks closed: ${v.holdoutClearedIds.length}/${v.holdoutAttackIds.length}` + (v.holdoutClearedIds.length ? ` (${v.holdoutClearedIds.join(", ")})` : "") + " \u2014 the patch generalised beyond the exploit it was written for."
4327
+ `- Holdout attacks closed: ${v.holdoutClearedIds.length}/${v.holdoutAttackIds.length}` + (v.holdoutClearedIds.length ? ` (${v.holdoutClearedIds.join(", ")})` : "") + (open.length === 0 ? " \u2014 the patch generalised beyond the exploit it was written for." : `, still open: ${open.join(", ")} \u2014 the patch is overfitted to the exploit it was written for.`)
4223
4328
  );
4224
4329
  }
4225
4330
  lines.push(
@@ -4230,11 +4335,20 @@ function liveSection(v) {
4230
4335
  '- \u26A0\uFE0F The replay sent **no session identifier**. If this target keeps conversation state, every attack above ran in one shared conversation and each verdict depends on the ones before it. Add `"sessionId": "{{sessionId}}"` to your request template and re-verify before trusting these results.'
4231
4336
  );
4232
4337
  }
4233
- lines.push(
4234
- "- This proves the patch **works**. It does not prove it is live where your scans look: `verify-claims` after your real deploy is what closes the finding."
4235
- );
4338
+ lines.push(v.passed ? PASSED_LINE : refusalLine(v));
4236
4339
  return lines;
4237
4340
  }
4341
+ var PASSED_LINE = "- This proves the patch **works**. It does not prove it is live where your scans look: `verify-claims` after your real deploy is what closes the finding.";
4342
+ function refusalLine(v) {
4343
+ const attacksOpen = v.designClearedIds.length < v.designAttackIds.length || v.holdoutClearedIds.length < v.holdoutAttackIds.length;
4344
+ if (attacksOpen) {
4345
+ return "- The patch did **not** close every attack: the finding stays open. Fix it at the layer the remediation guidance names, then verify again.";
4346
+ }
4347
+ if (!v.benign.green) {
4348
+ return "- Every attack closed, but the check on legitimate questions did **not** pass (above): the patch is held and the finding stays open until it does.";
4349
+ }
4350
+ return "- The verification could **not** conclude (a degraded judge or an attack with no verdict): the finding stays open. Run it again.";
4351
+ }
4238
4352
  function recipeSection(p, live) {
4239
4353
  const { recipe } = p;
4240
4354
  const reliability = LAYER_META[recipe.remediationRef.layer].reliability;
@@ -4305,7 +4419,8 @@ function withheldSection(withheld, live) {
4305
4419
  out.push(
4306
4420
  `- \`${p.attackId}\` \u2014 \`${p.recipe.id}\`` + (open.length ? `: still vulnerable to ${open.join(", ")} after the patch.` : "")
4307
4421
  );
4308
- if (v && !v.benign.green) out.push(` - Benign regression gate: ${v.benign.detail}`);
4422
+ if (v && !v.benign.green)
4423
+ out.push(` - Benign regression gate: ${v.benign.detail}`);
4309
4424
  if (v && v.notExecutedAttackIds.length) {
4310
4425
  out.push(` - No verdict for ${v.notExecutedAttackIds.join(", ")}.`);
4311
4426
  }
@@ -4348,8 +4463,10 @@ function renderPrBody(plan, live, withheld = [], rescan = []) {
4348
4463
  if (plan.skipped.length) {
4349
4464
  out.push("### Findings this PR does NOT address");
4350
4465
  out.push("");
4351
- for (const s of plan.skipped) {
4352
- out.push(`- \`${s.attackId}\` \u2014 ${s.reason}: ${s.detail}`);
4466
+ for (const g of groupSkipped(plan.skipped)) {
4467
+ out.push(
4468
+ `- ${g.attackIds.map((a) => `\`${a}\``).join(", ")} \u2014 ${g.reason}: ${g.detail}`
4469
+ );
4353
4470
  }
4354
4471
  out.push("");
4355
4472
  }
@@ -4470,6 +4587,19 @@ function describeClaimSync(result) {
4470
4587
  return `Remediation claims not copied to the dashboard: ${result.reason}. The local store is unaffected.`;
4471
4588
  }
4472
4589
 
4590
+ // src/lib/progress-line.ts
4591
+ function phaseProgress(label, write = (line) => console.error(line)) {
4592
+ let shown = 0;
4593
+ return (done, total) => {
4594
+ if (total <= 0) return;
4595
+ const step = Math.max(1, Math.ceil(total / 4));
4596
+ if (done === total || done - shown >= step) {
4597
+ shown = done;
4598
+ write(` ${label}: ${done}/${total}`);
4599
+ }
4600
+ };
4601
+ }
4602
+
4473
4603
  // src/benign/runner.ts
4474
4604
  var RATE_LIMIT_RETRIES = 4;
4475
4605
  var MAX_RATE_LIMIT_WAIT_S = 60;
@@ -4503,6 +4633,7 @@ async function captureBenign(target, cases, opts = {}) {
4503
4633
  hash: sha256Hex(response),
4504
4634
  ...opts.keepResponses ? { response } : {}
4505
4635
  });
4636
+ opts.onProgress?.(out.length, cases.length);
4506
4637
  if (opts.delayMs) await new Promise((r) => setTimeout(r, opts.delayMs));
4507
4638
  }
4508
4639
  return out;
@@ -4526,6 +4657,7 @@ function baselineRunResults(run1, run2) {
4526
4657
  ];
4527
4658
  }
4528
4659
  var BENIGN_VOTES = 3;
4660
+ var BENIGN_JUDGE_CONCURRENCY = 3;
4529
4661
  function voteAttackId(caseName, vote) {
4530
4662
  return vote === 0 ? `benign_${caseName}` : `benign_${caseName}#${vote + 1}`;
4531
4663
  }
@@ -4577,28 +4709,51 @@ async function voteOnAnswer(c2, response, evaluator, votes, budget) {
4577
4709
  }
4578
4710
  async function judgeBenign(captures, cases, evaluator, opts = {}) {
4579
4711
  const byName = new Map(cases.map((c2) => [c2.name, c2]));
4580
- const out = [];
4581
4712
  const budget = { open: true };
4582
- for (const cap of captures) {
4713
+ const judgeOne = async (cap) => {
4583
4714
  const c2 = byName.get(cap.name);
4584
4715
  if (!c2 || cap.response === void 0 || isCaptureError(cap)) {
4585
- out.push({ name: cap.name, passed: true, unobserved: true });
4586
- continue;
4716
+ return { name: cap.name, passed: true, unobserved: true };
4587
4717
  }
4588
4718
  const key = `${cap.name}:${cap.hash}`;
4589
4719
  const verdict = opts.memo?.get(key) ?? await voteOnAnswer(c2, cap.response, evaluator, opts.votes ?? 1, budget);
4590
- if (!verdict) {
4591
- out.push({ name: cap.name, passed: true, unjudged: true });
4592
- continue;
4593
- }
4720
+ if (!verdict) return { name: cap.name, passed: true, unjudged: true };
4594
4721
  opts.memo?.set(key, verdict);
4595
- out.push({
4722
+ return {
4596
4723
  name: cap.name,
4597
4724
  passed: verdict.passed,
4598
4725
  votes: verdict.votes,
4599
4726
  ...verdict.split ? { split: true } : {}
4600
- });
4601
- }
4727
+ };
4728
+ };
4729
+ let judged = 0;
4730
+ return mapInOrder(
4731
+ captures,
4732
+ opts.concurrency ?? BENIGN_JUDGE_CONCURRENCY,
4733
+ async (cap) => {
4734
+ const result = await judgeOne(cap);
4735
+ opts.onProgress?.(++judged, captures.length);
4736
+ return result;
4737
+ }
4738
+ );
4739
+ }
4740
+ async function mapInOrder(items, limit, fn) {
4741
+ const out = new Array(items.length);
4742
+ let next = 0;
4743
+ let failed = false;
4744
+ const worker = async () => {
4745
+ while (!failed && next < items.length) {
4746
+ const i = next++;
4747
+ try {
4748
+ out[i] = await fn(items[i]);
4749
+ } catch (e) {
4750
+ failed = true;
4751
+ throw e;
4752
+ }
4753
+ }
4754
+ };
4755
+ const workers = Math.max(1, Math.min(limit, items.length));
4756
+ await Promise.all(Array.from({ length: workers }, worker));
4602
4757
  return out;
4603
4758
  }
4604
4759
 
@@ -4606,10 +4761,12 @@ async function judgeBenign(captures, cases, evaluator, opts = {}) {
4606
4761
  async function captureBenignBaseline(target, scope, judge) {
4607
4762
  const judged = scope === "model-behaviour" && judge !== void 0;
4608
4763
  const run1 = await captureBenign(target, BENIGN_CORE_V1, {
4609
- keepResponses: judged
4764
+ keepResponses: judged,
4765
+ onProgress: phaseProgress("Legitimate questions before the patch, run 1/2")
4610
4766
  });
4611
4767
  const run2 = await captureBenign(target, BENIGN_CORE_V1, {
4612
- keepResponses: judged
4768
+ keepResponses: judged,
4769
+ onProgress: phaseProgress("Legitimate questions before the patch, run 2/2")
4613
4770
  });
4614
4771
  const strip = (run, verdicts) => run.map((c2, i) => {
4615
4772
  const v = verdicts?.[i];
@@ -4618,7 +4775,9 @@ async function captureBenignBaseline(target, scope, judge) {
4618
4775
  name: c2.name,
4619
4776
  hash: c2.hash,
4620
4777
  ...hasVerdict2 ? { passed: v.passed } : {},
4621
- ...hasVerdict2 && v.split ? { split: true } : {}
4778
+ ...hasVerdict2 && v.split ? { split: true } : {},
4779
+ // Kept so an answer the patch does not change keeps this verdict.
4780
+ ...hasVerdict2 && v.votes ? { votes: v.votes } : {}
4622
4781
  };
4623
4782
  });
4624
4783
  const unjudged = {
@@ -4632,8 +4791,14 @@ async function captureBenignBaseline(target, scope, judge) {
4632
4791
  let verdicts1;
4633
4792
  let verdicts2;
4634
4793
  try {
4635
- verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, opts);
4636
- verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, opts);
4794
+ verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, {
4795
+ ...opts,
4796
+ onProgress: phaseProgress("Judging the answers before the patch, run 1/2")
4797
+ });
4798
+ verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, {
4799
+ ...opts,
4800
+ onProgress: phaseProgress("Judging the answers before the patch, run 2/2")
4801
+ });
4637
4802
  } catch (e) {
4638
4803
  console.warn(
4639
4804
  `\u26A0\uFE0F Could not judge the benign baseline (${e instanceof Error ? e.message : e}). It is recorded unjudged: every case is assumed to have passed before the patch.`
@@ -4691,7 +4856,9 @@ async function runBenignGate(input2) {
4691
4856
  (c2) => baseline.run1.some((b) => b.name === c2.name)
4692
4857
  );
4693
4858
  if (scope === "rendering") {
4694
- const after = await captureBenign(target, cases);
4859
+ const after = await captureBenign(target, cases, {
4860
+ onProgress: phaseProgress("Legitimate questions after the patch")
4861
+ });
4695
4862
  const report = evaluateBenign({
4696
4863
  suiteId: baseline.suiteId,
4697
4864
  cases,
@@ -4702,7 +4869,8 @@ async function runBenignGate(input2) {
4702
4869
  return {
4703
4870
  green: !report.blocked,
4704
4871
  ran: true,
4705
- detail: report.blocked ? `blocked: ${report.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases, ${report.flips.length} flip(s), ${report.flakyCaseNames.length} flaky`
4872
+ detail: report.blocked ? `blocked: ${report.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases, ${report.flips.length} flip(s), ${report.flakyCaseNames.length} flaky`,
4873
+ coverage: coverageOf(cases, [report])
4706
4874
  };
4707
4875
  }
4708
4876
  const judge = input2.evaluator;
@@ -4716,12 +4884,26 @@ async function runBenignGate(input2) {
4716
4884
  return judgePatchedAnswers(baseline, cases, contract, target, judge);
4717
4885
  }
4718
4886
  async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
4719
- const after = await captureBenign(target, cases, { keepResponses: true });
4720
- const afterRun = await judgeBenign(after, cases, judge, {
4721
- votes: BENIGN_VOTES
4887
+ const after = await captureBenign(target, cases, {
4888
+ keepResponses: true,
4889
+ onProgress: phaseProgress("Legitimate questions after the patch")
4722
4890
  });
4891
+ const unchanged = unchangedVerdicts(baseline, after);
4892
+ const judged = await judgeBenign(
4893
+ after.filter((a) => !unchanged.has(a.name)),
4894
+ cases,
4895
+ judge,
4896
+ {
4897
+ votes: BENIGN_VOTES,
4898
+ onProgress: phaseProgress("Judging the answers that changed")
4899
+ }
4900
+ );
4901
+ const judgedByName = new Map(judged.map((r) => [r.name, r]));
4902
+ const afterRun = after.map(
4903
+ (a) => unchanged.get(a.name) ?? judgedByName.get(a.name)
4904
+ );
4723
4905
  const notPassing = afterRun.flatMap(
4724
- (r, i) => r.votes?.includes("F") ? [{ name: r.name, hash: after[i].hash, votes: r.votes }] : []
4906
+ (r, i) => !r.unchanged && r.votes?.includes("F") ? [{ name: r.name, hash: after[i].hash, votes: r.votes }] : []
4725
4907
  );
4726
4908
  const notCaptured = afterRun.filter((r) => r.unobserved).length;
4727
4909
  if (notCaptured) {
@@ -4743,6 +4925,24 @@ async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
4743
4925
  }
4744
4926
  return { ...ruleOnVotes(baseline, cases, contract, afterRun), notPassing };
4745
4927
  }
4928
+ function unchangedVerdicts(baseline, after) {
4929
+ const out = /* @__PURE__ */ new Map();
4930
+ const before = [...baseline.run1, ...baseline.run2];
4931
+ for (const a of after) {
4932
+ const b = before.find(
4933
+ (x) => x.name === a.name && x.hash === a.hash && typeof x.passed === "boolean" && x.votes
4934
+ );
4935
+ if (!b || typeof b.passed !== "boolean") continue;
4936
+ out.set(a.name, {
4937
+ name: a.name,
4938
+ passed: b.passed,
4939
+ votes: b.votes,
4940
+ unchanged: true,
4941
+ ...b.split ? { split: true } : {}
4942
+ });
4943
+ }
4944
+ return out;
4945
+ }
4746
4946
  function ruleOnVotes(baseline, cases, contract, afterRun) {
4747
4947
  const judged = judgedBaselineRuns(baseline, true) !== void 0;
4748
4948
  const read = (favourable) => evaluateBenign({
@@ -4751,13 +4951,17 @@ function ruleOnVotes(baseline, cases, contract, afterRun) {
4751
4951
  // A judged baseline says which cases already failed before the patch;
4752
4952
  // an older claim has only hashes, and keeps the old reading (all passed).
4753
4953
  baselineRuns: judgedBaselineRuns(baseline, !favourable) ?? baselineRunResults(baseline.run1, baseline.run2),
4754
- afterRun: afterRun.map(
4755
- (r) => r.split ? { name: r.name, passed: favourable } : r
4756
- ),
4954
+ afterRun: afterRun.map((r) => {
4955
+ if (r.unchanged) {
4956
+ return { name: r.name, passed: r.split ? !favourable : r.passed };
4957
+ }
4958
+ return r.split ? { name: r.name, passed: favourable } : r;
4959
+ }),
4757
4960
  gate: contract.benignGate
4758
4961
  });
4759
4962
  const best = read(true);
4760
4963
  const worst = read(false);
4964
+ const coverage = coverageOf(cases, [best, worst]);
4761
4965
  const mark = (f) => f.name + (f.criticalPath ? "*" : "");
4762
4966
  const solid = new Set(best.flips.map((f) => f.name));
4763
4967
  const decidedBySplit = worst.flips.filter((f) => !solid.has(f.name)).map(mark);
@@ -4765,7 +4969,8 @@ function ruleOnVotes(baseline, cases, contract, afterRun) {
4765
4969
  return {
4766
4970
  green: false,
4767
4971
  ran: true,
4768
- detail: `blocked: ${best.flips.map(mark).join(", ")}` + (decidedBySplit.length ? `; split vote, not counted: ${decidedBySplit.join(", ")}` : "")
4972
+ detail: `blocked: ${best.flips.map(mark).join(", ")}` + (decidedBySplit.length ? `; split vote, not counted: ${decidedBySplit.join(", ")}` : ""),
4973
+ coverage
4769
4974
  };
4770
4975
  }
4771
4976
  if (worst.blocked) {
@@ -4778,7 +4983,18 @@ function ruleOnVotes(baseline, cases, contract, afterRun) {
4778
4983
  return {
4779
4984
  green: true,
4780
4985
  ran: true,
4781
- detail: passDetail(baseline, cases, worst, judged, afterRun)
4986
+ detail: passDetail(baseline, cases, worst, judged, afterRun),
4987
+ coverage
4988
+ };
4989
+ }
4990
+ function coverageOf(cases, reports) {
4991
+ const excluded = new Set(reports.flatMap((r) => r.flakyCaseNames));
4992
+ const checked = cases.filter((c2) => !excluded.has(c2.name));
4993
+ return {
4994
+ checked: checked.length,
4995
+ total: cases.length,
4996
+ criticalChecked: checked.filter((c2) => c2.criticalPath).length,
4997
+ criticalTotal: cases.filter((c2) => c2.criticalPath).length
4782
4998
  };
4783
4999
  }
4784
5000
  function passDetail(baseline, cases, report, judged, afterRun) {
@@ -4792,7 +5008,9 @@ function passDetail(baseline, cases, report, judged, afterRun) {
4792
5008
  ])).size;
4793
5009
  const excluded = judged ? `, ${report.flakyCaseNames.length} not passing before the patch (excluded)` + (assumed ? `, ${assumed} without a verdict before the patch (assumed passing)` : "") : "";
4794
5010
  const splitNote = split ? `, ${split} split vote(s) read against the patch` : "";
4795
- return `${cases.length} cases judged, ${report.flips.length} flip(s)${excluded}${splitNote}`;
5011
+ const kept = afterRun.filter((r) => r.unchanged).length;
5012
+ const scope = kept ? `${cases.length} cases, ${cases.length - kept} judged after the patch, ${kept} unchanged answer(s) kept their pre-patch verdict` : `${cases.length} cases judged`;
5013
+ return `${scope}, ${report.flips.length} flip(s)${excluded}${splitNote}`;
4796
5014
  }
4797
5015
  async function replayFamily(contract, target, catalogue, evaluator, judgeRetryDelayMs) {
4798
5016
  const attacks = attacksForContract(contract, catalogue);
@@ -4851,7 +5069,8 @@ async function verifyLive(input2) {
4851
5069
  ran: benign.ran,
4852
5070
  green: benign.green,
4853
5071
  detail: benign.detail,
4854
- ...benign.notPassing ? { notPassing: benign.notPassing } : {}
5072
+ ...benign.notPassing ? { notPassing: benign.notPassing } : {},
5073
+ ...benign.coverage ? { coverage: benign.coverage } : {}
4855
5074
  },
4856
5075
  judgeDegraded,
4857
5076
  sessionIsolated: checkSessionIsolation(input2.target).isolated,
@@ -5280,6 +5499,80 @@ ${manualPrInstructions(branch, base)}`
5280
5499
  };
5281
5500
  }
5282
5501
 
5502
+ // src/fix/verify-outcome.ts
5503
+ function refusedPatches(plan, live) {
5504
+ if (live.size === 0) return [];
5505
+ return plan.planned.filter((p) => live.get(p.fingerprint)?.passed !== true).map((p) => p.attackId);
5506
+ }
5507
+
5508
+ // src/fix/dashboard-scan.ts
5509
+ var FETCH_TIMEOUT_MS = 3e4;
5510
+ function findingsFromStoredScan(scan) {
5511
+ const vulns = scan.vulns ?? [];
5512
+ const findings = selectRetestableFindings(
5513
+ vulns,
5514
+ void 0,
5515
+ scan.targetUrl
5516
+ ).flatMap(
5517
+ (f) => f.attackId === null ? [] : [
5518
+ {
5519
+ attackId: f.attackId,
5520
+ name: f.name,
5521
+ severity: f.severity,
5522
+ evaluationMethod: f.evaluationMethod ?? null,
5523
+ confidence: f.confidence ?? null,
5524
+ judgeErrorCategory: null,
5525
+ disagreementResolution: null
5526
+ }
5527
+ ]
5528
+ );
5529
+ const seen = /* @__PURE__ */ new Set();
5530
+ const allAttacks = [];
5531
+ for (const v of vulns) {
5532
+ if (!v.vulnerabilityType || seen.has(v.vulnerabilityType)) continue;
5533
+ seen.add(v.vulnerabilityType);
5534
+ allAttacks.push({
5535
+ id: v.vulnerabilityType,
5536
+ severity: v.severity,
5537
+ vulnerable: v.status === "DETECTED",
5538
+ ...v.captureStatus ? { captureStatus: v.captureStatus } : {}
5539
+ });
5540
+ }
5541
+ return { targetUrl: scan.targetUrl, findings, allAttacks };
5542
+ }
5543
+ async function fetchStoredScan(apiUrl, apiKey, scanId) {
5544
+ let res;
5545
+ try {
5546
+ res = await fetch(
5547
+ `${apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}`,
5548
+ {
5549
+ headers: { Authorization: `Bearer ${apiKey}` },
5550
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
5551
+ }
5552
+ );
5553
+ } catch (err) {
5554
+ const msg = err instanceof Error ? err.message : String(err);
5555
+ throw new Error(`Failed to reach the dashboard (${apiUrl}): ${msg}`);
5556
+ }
5557
+ if (!res.ok) {
5558
+ await res.text().catch(() => void 0);
5559
+ if (res.status === 401) {
5560
+ throw new Error(
5561
+ "API key invalid or revoked. Run `shield-llm login` to re-authenticate."
5562
+ );
5563
+ }
5564
+ if (res.status === 404) throw new Error(`Scan "${scanId}" not found.`);
5565
+ throw new Error(`The dashboard returned HTTP ${res.status} for the scan.`);
5566
+ }
5567
+ const scan = await res.json();
5568
+ if (scan.status && scan.status !== "completed") {
5569
+ throw new Error(
5570
+ `Scan "${scanId}" is ${scan.status}: only a completed scan has findings to fix.`
5571
+ );
5572
+ }
5573
+ return scan;
5574
+ }
5575
+
5283
5576
  // src/commands/fix.ts
5284
5577
  var resolvedEvaluators = /* @__PURE__ */ new WeakMap();
5285
5578
  function resolveEvaluator(opts) {
@@ -5398,8 +5691,9 @@ function printPlan(plan) {
5398
5691
  console.log(
5399
5692
  `Not patchable (${plan.skipped.length}) \u2014 these become issues, not PRs:`
5400
5693
  );
5401
- for (const s of plan.skipped) {
5402
- console.log(` \xB7 ${s.attackId.padEnd(24)} ${s.reason}: ${s.detail}`);
5694
+ for (const g of groupSkipped(plan.skipped)) {
5695
+ console.log(` \xB7 ${g.reason}: ${g.detail}`);
5696
+ console.log(` ${g.attackIds.join(", ")}`);
5403
5697
  }
5404
5698
  console.log();
5405
5699
  }
@@ -5454,18 +5748,35 @@ async function fixCommand(opts) {
5454
5748
  let findings;
5455
5749
  let beforeAttacks = [];
5456
5750
  try {
5751
+ let source;
5457
5752
  if (opts.report) {
5458
- const local = findingsFromLocalReport(resolve6(cwd, opts.report));
5459
- targetUrl = local.targetUrl;
5460
- findings = local.findings;
5461
- beforeAttacks = local.allAttacks;
5753
+ source = findingsFromLocalReport(resolve7(cwd, opts.report));
5754
+ } else if (opts.scan) {
5755
+ const stored = loadCredentials();
5756
+ if (!stored) {
5757
+ console.error(
5758
+ "Not logged in: `shield-llm fix <scanId>` reads the scan from your dashboard. Run `shield-llm login`, or pass --report <shield-report.json>."
5759
+ );
5760
+ setExitCode(2);
5761
+ return;
5762
+ }
5763
+ source = findingsFromStoredScan(
5764
+ await fetchStoredScan(
5765
+ resolveApiUrl(stored.apiUrl, opts.apiUrl),
5766
+ stored.apiKey,
5767
+ opts.scan
5768
+ )
5769
+ );
5462
5770
  } else {
5463
5771
  console.error(
5464
- "Provide --report <shield-report.json>. (Dashboard mode via --scan lands with the claim API.)"
5772
+ "Name the scan to fix: `shield-llm fix <scanId>` (from the dashboard) or `shield-llm fix --report <shield-report.json>` (from `scan --write-json`)."
5465
5773
  );
5466
5774
  setExitCode(2);
5467
5775
  return;
5468
5776
  }
5777
+ targetUrl = source.targetUrl;
5778
+ findings = source.findings;
5779
+ beforeAttacks = source.allAttacks;
5469
5780
  } catch (e) {
5470
5781
  console.error(e instanceof Error ? e.message : String(e));
5471
5782
  setExitCode(2);
@@ -5671,6 +5982,14 @@ Re-scanning the ${beforeAttacks.length} attack(s) of the original scan\u2026`
5671
5982
  }
5672
5983
  console.log("\n\u2500\u2500\u2500 PR body \u2500\u2500\u2500\n");
5673
5984
  console.log(renderPrBody(plan, live, [], rescanLines));
5985
+ const refused = refusedPatches(plan, live);
5986
+ if (refused.length) {
5987
+ console.error(
5988
+ `
5989
+ ${refused.length} of ${plan.planned.length} patch(es) did not pass the live verification (${refused.join(", ")}): the finding(s) stay open. Exit code 1.`
5990
+ );
5991
+ setExitCode(1);
5992
+ }
5674
5993
  }
5675
5994
  async function liveVerificationPhase(plan, config, codebase, cwd, opts, baseline) {
5676
5995
  const evidence = /* @__PURE__ */ new Map();
@@ -5926,11 +6245,11 @@ Could not open the PR: ${res.detail}`);
5926
6245
  if (holding.length) setExitCode(1);
5927
6246
  }
5928
6247
  function closurePathConfigured(root) {
5929
- const dir = resolve6(root, ".github/workflows");
6248
+ const dir = resolve7(root, ".github/workflows");
5930
6249
  if (!existsSync6(dir)) return false;
5931
6250
  try {
5932
6251
  return readdirSync(dir).some(
5933
- (f) => readFileSync6(resolve6(dir, f), "utf8").includes("verify-claims")
6252
+ (f) => readFileSync6(resolve7(dir, f), "utf8").includes("verify-claims")
5934
6253
  );
5935
6254
  } catch {
5936
6255
  return false;
@@ -6025,6 +6344,9 @@ async function verifyClaimsCommand(opts) {
6025
6344
  continue;
6026
6345
  }
6027
6346
  const { catalogue } = resolved;
6347
+ console.error(
6348
+ `Verifying ${claim.recipeId} (${pending.indexOf(claim) + 1}/${pending.length}): replaying ${claim.contract.designAttackIds.length + claim.contract.holdoutAttackIds.length} attack(s), then the legitimate questions\u2026`
6349
+ );
6028
6350
  const { verdicts, judgeDegraded } = await replayFamily(
6029
6351
  claim.contract,
6030
6352
  target,
@@ -6062,7 +6384,8 @@ async function verifyClaimsCommand(opts) {
6062
6384
  ran: benign.ran,
6063
6385
  green: benign.green,
6064
6386
  detail: benign.detail,
6065
- ...benign.notPassing ? { notPassing: benign.notPassing } : {}
6387
+ ...benign.notPassing ? { notPassing: benign.notPassing } : {},
6388
+ ...benign.coverage ? { coverage: benign.coverage } : {}
6066
6389
  },
6067
6390
  judgeDegraded,
6068
6391
  sessionIsolated: checkSessionIsolation(target).isolated,
@@ -6280,9 +6603,9 @@ program.command("tests").description("List custom tests (local config and/or rem
6280
6603
  "--api-url <url>",
6281
6604
  "Backend API URL (overrides SHIELD_API_URL env var)"
6282
6605
  ).action(testsCommand);
6283
- program.command("fix").description(
6284
- "Patch findings from a scan report using declarative remediation recipes"
6285
- ).option("-c, --config <path>", "Path to config file").option("--report <path>", "Scan report JSON (from `scan --write-json`)").option("--dry-run", "Print the diff, write nothing").option(
6606
+ program.command("fix [scanId]").description(
6607
+ "Patch the findings of a scan (a dashboard scan id, or --report) using declarative remediation recipes"
6608
+ ).option("-c, --config <path>", "Path to config file").option("--report <path>", "Scan report JSON (from `scan --write-json`)").option("--scan <id>", "Dashboard scan id (same as the positional argument)").option("--api-url <url>", "Backend API URL override").option("--dry-run", "Print the diff, write nothing").option(
6286
6609
  "--explain",
6287
6610
  "Show which recipes apply and which anchors would unlock more"
6288
6611
  ).option("--revert", "Remove every shield-llm block this recipe set owns").option(
@@ -6313,7 +6636,19 @@ program.command("fix").description(
6313
6636
  ).option(
6314
6637
  "--yes",
6315
6638
  "Skip the confirmation prompt before running the configured redeploy command"
6316
- ).action(fixCommand);
6639
+ ).action(async (scanId, o) => {
6640
+ if (scanId && o.scan && scanId !== o.scan) {
6641
+ console.error(`Two scan ids given (${scanId} and --scan ${o.scan}).`);
6642
+ setExitCode(2);
6643
+ return;
6644
+ }
6645
+ if ((scanId || o.scan) && o.report) {
6646
+ console.error("Pass a scan id or --report, not both.");
6647
+ setExitCode(2);
6648
+ return;
6649
+ }
6650
+ await fixCommand({ ...o, scan: o.scan ?? scanId });
6651
+ });
6317
6652
  program.command("verify-claims").description(
6318
6653
  "Replay the attack family of every pending remediation claim and close (or refuse to close) it"
6319
6654
  ).option("-c, --config <path>", "Path to config file").option(
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  generatePdf,
10
10
  loadConfig,
11
11
  loadSystemPrompt
12
- } from "./chunk-GJQFYKMY.js";
12
+ } from "./chunk-ZK35FYSR.js";
13
13
  export {
14
14
  ConfigError,
15
15
  ConfigSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shield-llm",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "AI chatbot security scanner — automated red teaming for LLMs",
5
5
  "type": "module",
6
6
  "publishConfig": {