shield-llm 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -75,7 +75,7 @@ import {
75
75
  sha256Hex,
76
76
  summarizeAttackErrors,
77
77
  version
78
- } from "./chunk-VJXUREGO.js";
78
+ } from "./chunk-L2AVTIZW.js";
79
79
 
80
80
  // src/load-env.ts
81
81
  try {
@@ -1139,23 +1139,251 @@ async function presetsCommand(opts) {
1139
1139
  }
1140
1140
 
1141
1141
  // src/commands/report.ts
1142
- import { writeFileSync as writeFileSync4 } from "fs";
1142
+ import { writeFileSync as writeFileSync5 } from "fs";
1143
1143
  import { resolve as resolve2 } from "path";
1144
- function verificationLabel(v) {
1145
- if (v.verificationStatus === "fixed") {
1146
- return `\u2713 Fixed & verified${v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : ""}`;
1144
+
1145
+ // src/fix/claim-store.ts
1146
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
1147
+ import { dirname, join as join2 } from "path";
1148
+ var DEFAULT_CLAIM_FILE = ".shield-llm/claims.json";
1149
+ var ClaimStore = class _ClaimStore {
1150
+ constructor(path) {
1151
+ this.path = path;
1152
+ }
1153
+ static at(root, file = DEFAULT_CLAIM_FILE) {
1154
+ return new _ClaimStore(join2(root, file));
1155
+ }
1156
+ load() {
1157
+ if (!existsSync3(this.path)) return null;
1158
+ return JSON.parse(readFileSync3(this.path, "utf8"));
1159
+ }
1160
+ list() {
1161
+ return this.load()?.claims ?? [];
1162
+ }
1163
+ /** The claims of `targetUrl`; none when the store belongs to another target.
1164
+ * Read-only callers (`report`, `retest`) only use them to qualify a retest,
1165
+ * so a store that does not parse reads as no store rather than a crash. */
1166
+ forTarget(targetUrl) {
1167
+ let file;
1168
+ try {
1169
+ file = this.load();
1170
+ } catch {
1171
+ return [];
1172
+ }
1173
+ return file?.targetId === normalizeTargetUrl(targetUrl) ? file.claims : [];
1174
+ }
1175
+ /**
1176
+ * Claims a verification run should look at.
1177
+ *
1178
+ * `refuted_or_not_deployed` is included ON PURPOSE. That status means exactly
1179
+ * "still vulnerable, and we cannot tell whether the patch failed or was
1180
+ * simply not live yet" — so treating it as terminal would make the normal
1181
+ * sequence (patch → verify → deploy → verify again) impossible: the second
1182
+ * verification would find nothing to check. `inconclusive` is included for
1183
+ * the same reason: the family was not executed, so nothing was decided.
1184
+ *
1185
+ * Terminal, and therefore excluded: `confirmed`, `confirmed_overfit`,
1186
+ * `expired`.
1187
+ */
1188
+ openForVerification() {
1189
+ return this.list().filter(
1190
+ (c2) => c2.status === "pending" || c2.status === "refuted_or_not_deployed" || c2.status === "inconclusive"
1191
+ );
1192
+ }
1193
+ pending() {
1194
+ return this.list().filter((c2) => c2.status === "pending");
1195
+ }
1196
+ /** Upsert by fingerprint+recipe: re-running `fix` refreshes, never duplicates. */
1197
+ upsert(targetId, claim) {
1198
+ const current = this.load() ?? {
1199
+ version: 1,
1200
+ targetId,
1201
+ claims: []
1202
+ };
1203
+ const idx = current.claims.findIndex(
1204
+ (c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
1205
+ );
1206
+ if (idx === -1) current.claims.push(claim);
1207
+ else current.claims[idx] = claim;
1208
+ this.write({ ...current, targetId });
1209
+ }
1210
+ replace(claim) {
1211
+ const current = this.load();
1212
+ if (!current) return;
1213
+ const idx = current.claims.findIndex(
1214
+ (c2) => c2.findingFingerprint === claim.findingFingerprint && c2.recipeId === claim.recipeId
1215
+ );
1216
+ if (idx !== -1) current.claims[idx] = claim;
1217
+ this.write(current);
1218
+ }
1219
+ write(file) {
1220
+ mkdirSync2(dirname(this.path), { recursive: true });
1221
+ writeFileSync4(this.path, `${JSON.stringify(file, null, 2)}
1222
+ `, "utf8");
1223
+ }
1224
+ };
1225
+
1226
+ // src/lib/format.ts
1227
+ function truncate(str, max) {
1228
+ const oneLine = str.replace(/\n/g, " ").trim();
1229
+ return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
1230
+ }
1231
+ function excerpt(str, max) {
1232
+ const text = str.trim();
1233
+ return text.length <= max ? text : text.slice(0, max - 3) + "...";
1234
+ }
1235
+
1236
+ // src/retest-core.ts
1237
+ function selectRetestableFindings(vulns, filter, targetUrl) {
1238
+ const seen = /* @__PURE__ */ new Set();
1239
+ const findings = [];
1240
+ const targetId = targetUrl ? normalizeTargetUrl(targetUrl) : void 0;
1241
+ for (const v of vulns) {
1242
+ if (v.status !== "DETECTED") continue;
1243
+ if (v.captureStatus === "pending" || v.captureStatus === "rate_limited") {
1244
+ continue;
1245
+ }
1246
+ const fingerprint = targetId ? retestDedupKey(targetId, v) : v.vulnerabilityType ?? v.name;
1247
+ if (seen.has(fingerprint)) continue;
1248
+ seen.add(fingerprint);
1249
+ findings.push({
1250
+ attackId: v.vulnerabilityType ?? null,
1251
+ name: v.name,
1252
+ severity: v.severity,
1253
+ fingerprint,
1254
+ evaluationMethod: v.evaluationMethod ?? null,
1255
+ confidence: v.confidence ?? null
1256
+ });
1257
+ }
1258
+ if (!filter || filter.length === 0) return findings;
1259
+ const wanted = new Set(filter);
1260
+ return findings.filter(
1261
+ (f) => f.attackId && wanted.has(f.attackId) || wanted.has(f.name)
1262
+ );
1263
+ }
1264
+ var CUSTOM_PREFIX = "custom_";
1265
+ function buildRetestPlan(findings, catalogue) {
1266
+ const plan = {
1267
+ singles: [],
1268
+ multiTurn: [],
1269
+ customs: [],
1270
+ unavailable: [],
1271
+ findingByResultId: /* @__PURE__ */ new Map()
1272
+ };
1273
+ for (const finding of findings) {
1274
+ if (finding.attackId?.startsWith(CUSTOM_PREFIX)) {
1275
+ const customName = finding.attackId.slice(CUSTOM_PREFIX.length);
1276
+ const test = catalogue.customTests.find((t) => t.name === customName);
1277
+ if (test) {
1278
+ plan.customs.push({ finding, test });
1279
+ plan.findingByResultId.set(`${CUSTOM_PREFIX}${test.name}`, finding);
1280
+ } else {
1281
+ plan.unavailable.push(finding);
1282
+ }
1283
+ continue;
1284
+ }
1285
+ const single = catalogue.attacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.attacks.find((a) => a.name === finding.name));
1286
+ if (single) {
1287
+ plan.singles.push({ finding, attack: single });
1288
+ plan.findingByResultId.set(single.id, finding);
1289
+ continue;
1290
+ }
1291
+ const multi = catalogue.multiTurnAttacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.multiTurnAttacks.find((a) => a.name === finding.name));
1292
+ if (multi) {
1293
+ plan.multiTurn.push({ finding, attack: multi });
1294
+ plan.findingByResultId.set(multi.id, finding);
1295
+ continue;
1296
+ }
1297
+ plan.unavailable.push(finding);
1147
1298
  }
1148
- if (v.verificationStatus === "still_vulnerable") {
1149
- return `\u2717 Still vulnerable${v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : ""}`;
1299
+ return plan;
1300
+ }
1301
+ var EVIDENCE_PROMPT_CAP = 6e3;
1302
+ var EVIDENCE_RESPONSE_CAP = 2500;
1303
+ var REASONING_CAP = 4500;
1304
+ function buildRetestOutcome(results, findingByResultId) {
1305
+ const outcome = { verifications: [], failed: [] };
1306
+ for (const result of results) {
1307
+ const finding = findingByResultId.get(result.id);
1308
+ if (!finding) continue;
1309
+ if (result.error || result.rateLimited) {
1310
+ outcome.failed.push({
1311
+ finding,
1312
+ error: result.error ?? "rate limited"
1313
+ });
1314
+ continue;
1315
+ }
1316
+ outcome.verifications.push({
1317
+ // For legacy findings attackId is the catalogue id we matched by name;
1318
+ // the server falls back to name-matching rows with null vulnerabilityType.
1319
+ attackId: finding.attackId ?? result.id,
1320
+ name: finding.name,
1321
+ vulnerable: result.vulnerable,
1322
+ evidence: JSON.stringify({
1323
+ prompt: excerpt(result.prompt, EVIDENCE_PROMPT_CAP),
1324
+ response: excerpt(result.response, EVIDENCE_RESPONSE_CAP)
1325
+ }),
1326
+ evaluationMethod: result.llmEvaluation?.evaluationMethod,
1327
+ confidence: result.llmEvaluation?.confidence,
1328
+ reasoning: result.llmEvaluation?.reasoning ? excerpt(result.llmEvaluation.reasoning, REASONING_CAP) : void 0
1329
+ });
1150
1330
  }
1331
+ return outcome;
1332
+ }
1333
+ function decideExitCode(summary) {
1334
+ if (summary.stillVulnerable > 0) return 1;
1335
+ if (summary.fixed > 0) return 0;
1336
+ return 3;
1337
+ }
1338
+ function claimContradiction(attackId, targetUrl, claims, scanCreatedAt) {
1339
+ const fingerprint = fingerprintFromScan(targetUrl, attackId);
1340
+ const since = scanCreatedAt ? Date.parse(scanCreatedAt) : -Infinity;
1341
+ const newest = claims.filter(
1342
+ (c2) => c2.findingFingerprint === fingerprint && Date.parse(c2.createdAt) >= since
1343
+ ).sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))[0];
1344
+ return newest?.status === "confirmed_overfit" || newest?.status === "refuted_or_not_deployed" ? newest.status : void 0;
1345
+ }
1346
+
1347
+ // src/commands/report.ts
1348
+ function contradiction(scan, v, claims) {
1349
+ if (v.verificationStatus !== "fixed" || !v.vulnerabilityType)
1350
+ return void 0;
1351
+ return claimContradiction(
1352
+ v.vulnerabilityType,
1353
+ scan.targetUrl,
1354
+ claims,
1355
+ scan.createdAt
1356
+ );
1357
+ }
1358
+ function verificationLabel(v, open) {
1359
+ const on = v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : "";
1360
+ if (open) {
1361
+ return `~ Exploit closed${on}, fix not confirmed: ` + (open === "confirmed_overfit" ? "variants still open (confirmed_overfit)" : "target still vulnerable (refuted_or_not_deployed)");
1362
+ }
1363
+ if (v.verificationStatus === "fixed") return `\u2713 Fixed & verified${on}`;
1364
+ if (v.verificationStatus === "still_vulnerable")
1365
+ return `\u2717 Still vulnerable${on}`;
1151
1366
  return "\u2014";
1152
1367
  }
1153
- function renderScanMarkdown(scan) {
1368
+ function withClaimStatus(scan, claims = []) {
1369
+ return {
1370
+ ...scan,
1371
+ vulns: scan.vulns.map((v) => {
1372
+ const claimStatus = contradiction(scan, v, claims);
1373
+ return claimStatus ? { ...v, claimStatus } : v;
1374
+ })
1375
+ };
1376
+ }
1377
+ function renderScanMarkdown(scan, claims = []) {
1154
1378
  const detected = scan.vulns.filter((v) => v.status === "DETECTED");
1155
1379
  const passed = scan.vulns.length - detected.length;
1156
- const verifiedFixed = detected.filter(
1380
+ const retestedFixed = detected.filter(
1157
1381
  (v) => v.verificationStatus === "fixed"
1382
+ );
1383
+ const notConfirmed = retestedFixed.filter(
1384
+ (v) => contradiction(scan, v, claims)
1158
1385
  ).length;
1386
+ const verifiedFixed = retestedFixed.length - notConfirmed;
1159
1387
  const lines = [
1160
1388
  `# Shield LLM scan ${scan.id}`,
1161
1389
  "",
@@ -1163,8 +1391,8 @@ function renderScanMarkdown(scan) {
1163
1391
  `- Score: **${scan.score}** (${scan.grade})`,
1164
1392
  `- Date: ${scan.createdAt}`,
1165
1393
  `- Tests: ${scan.testsRun}/${scan.testsTotal} run, ${detected.length} vulnerable, ${passed} secure`,
1166
- ...verifiedFixed > 0 ? [
1167
- `- Verified fixes: ${verifiedFixed}/${detected.length} (shield-llm retest)`
1394
+ ...retestedFixed.length > 0 ? [
1395
+ `- Verified fixes: ${verifiedFixed}/${detected.length} (shield-llm retest)` + (notConfirmed ? `; ${notConfirmed} exploit(s) closed but their fix not confirmed` : "")
1168
1396
  ] : [],
1169
1397
  "",
1170
1398
  "## Vulnerabilities detected",
@@ -1177,7 +1405,7 @@ function renderScanMarkdown(scan) {
1177
1405
  lines.push("|---|---|---|---|");
1178
1406
  for (const v of detected) {
1179
1407
  lines.push(
1180
- `| ${v.severity} | ${v.name} | ${verificationLabel(v)} | ${(v.description ?? "").slice(0, 80)} |`
1408
+ `| ${v.severity} | ${v.name} | ${verificationLabel(v, contradiction(scan, v, claims))} | ${(v.description ?? "").slice(0, 80)} |`
1181
1409
  );
1182
1410
  }
1183
1411
  }
@@ -1226,14 +1454,15 @@ async function reportCommand(scanId, opts) {
1226
1454
  return;
1227
1455
  }
1228
1456
  const scan = await res.json();
1457
+ const claims = ClaimStore.at(process.cwd()).forTarget(scan.targetUrl);
1229
1458
  let content;
1230
1459
  if (opts.output === "markdown") {
1231
- content = renderScanMarkdown(scan);
1460
+ content = renderScanMarkdown(scan, claims);
1232
1461
  } else {
1233
- content = JSON.stringify(scan, null, 2);
1462
+ content = JSON.stringify(withClaimStatus(scan, claims), null, 2);
1234
1463
  }
1235
1464
  if (opts.outputFile) {
1236
- writeFileSync4(resolve2(opts.outputFile), content, "utf-8");
1465
+ writeFileSync5(resolve2(opts.outputFile), content, "utf-8");
1237
1466
  console.error(`Report written to ${opts.outputFile}`);
1238
1467
  } else {
1239
1468
  console.log(content);
@@ -1577,7 +1806,7 @@ function printAttackComplete(event) {
1577
1806
  spinner.start();
1578
1807
  }
1579
1808
  }
1580
- function printSummary(report, thresholds) {
1809
+ function printSummary(report, thresholds, gate) {
1581
1810
  console.log("");
1582
1811
  console.log(c.bold("\u2550\u2550\u2550 Shield LLM Scan Results \u2550\u2550\u2550"));
1583
1812
  console.log("");
@@ -1636,7 +1865,13 @@ function printSummary(report, thresholds) {
1636
1865
  );
1637
1866
  }
1638
1867
  console.log("");
1639
- if (thresholds.passed) {
1868
+ if (!gate.thresholdsConfigured) {
1869
+ console.log(
1870
+ c.yellow(
1871
+ " No threshold set: this run gates nothing (add --min-score or --fail-on-critical to fail CI on it)."
1872
+ )
1873
+ );
1874
+ } else if (thresholds.passed) {
1640
1875
  console.log(c.greenBold(" \u2713 PASSED \u2014 all thresholds met"));
1641
1876
  } else {
1642
1877
  console.log(c.redBold(" \u2717 FAILED \u2014 threshold violations:"));
@@ -1682,115 +1917,6 @@ function gradeColor(grade) {
1682
1917
  }
1683
1918
  }
1684
1919
 
1685
- // src/lib/format.ts
1686
- function truncate(str, max) {
1687
- const oneLine = str.replace(/\n/g, " ").trim();
1688
- return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
1689
- }
1690
-
1691
- // src/retest-core.ts
1692
- function selectRetestableFindings(vulns, filter, targetUrl) {
1693
- const seen = /* @__PURE__ */ new Set();
1694
- const findings = [];
1695
- const targetId = targetUrl ? normalizeTargetUrl(targetUrl) : void 0;
1696
- for (const v of vulns) {
1697
- if (v.status !== "DETECTED") continue;
1698
- if (v.captureStatus === "pending" || v.captureStatus === "rate_limited") {
1699
- continue;
1700
- }
1701
- const fingerprint = targetId ? retestDedupKey(targetId, v) : v.vulnerabilityType ?? v.name;
1702
- if (seen.has(fingerprint)) continue;
1703
- seen.add(fingerprint);
1704
- findings.push({
1705
- attackId: v.vulnerabilityType ?? null,
1706
- name: v.name,
1707
- severity: v.severity,
1708
- fingerprint,
1709
- evaluationMethod: v.evaluationMethod ?? null,
1710
- confidence: v.confidence ?? null
1711
- });
1712
- }
1713
- if (!filter || filter.length === 0) return findings;
1714
- const wanted = new Set(filter);
1715
- return findings.filter(
1716
- (f) => f.attackId && wanted.has(f.attackId) || wanted.has(f.name)
1717
- );
1718
- }
1719
- var CUSTOM_PREFIX = "custom_";
1720
- function buildRetestPlan(findings, catalogue) {
1721
- const plan = {
1722
- singles: [],
1723
- multiTurn: [],
1724
- customs: [],
1725
- unavailable: [],
1726
- findingByResultId: /* @__PURE__ */ new Map()
1727
- };
1728
- for (const finding of findings) {
1729
- if (finding.attackId?.startsWith(CUSTOM_PREFIX)) {
1730
- const customName = finding.attackId.slice(CUSTOM_PREFIX.length);
1731
- const test = catalogue.customTests.find((t) => t.name === customName);
1732
- if (test) {
1733
- plan.customs.push({ finding, test });
1734
- plan.findingByResultId.set(`${CUSTOM_PREFIX}${test.name}`, finding);
1735
- } else {
1736
- plan.unavailable.push(finding);
1737
- }
1738
- continue;
1739
- }
1740
- const single = catalogue.attacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.attacks.find((a) => a.name === finding.name));
1741
- if (single) {
1742
- plan.singles.push({ finding, attack: single });
1743
- plan.findingByResultId.set(single.id, finding);
1744
- continue;
1745
- }
1746
- const multi = catalogue.multiTurnAttacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.multiTurnAttacks.find((a) => a.name === finding.name));
1747
- if (multi) {
1748
- plan.multiTurn.push({ finding, attack: multi });
1749
- plan.findingByResultId.set(multi.id, finding);
1750
- continue;
1751
- }
1752
- plan.unavailable.push(finding);
1753
- }
1754
- return plan;
1755
- }
1756
- var EVIDENCE_PROMPT_CAP = 6e3;
1757
- var EVIDENCE_RESPONSE_CAP = 2500;
1758
- var REASONING_CAP = 4500;
1759
- function buildRetestOutcome(results, findingByResultId) {
1760
- const outcome = { verifications: [], failed: [] };
1761
- for (const result of results) {
1762
- const finding = findingByResultId.get(result.id);
1763
- if (!finding) continue;
1764
- if (result.error || result.rateLimited) {
1765
- outcome.failed.push({
1766
- finding,
1767
- error: result.error ?? "rate limited"
1768
- });
1769
- continue;
1770
- }
1771
- outcome.verifications.push({
1772
- // For legacy findings attackId is the catalogue id we matched by name;
1773
- // the server falls back to name-matching rows with null vulnerabilityType.
1774
- attackId: finding.attackId ?? result.id,
1775
- name: finding.name,
1776
- vulnerable: result.vulnerable,
1777
- evidence: JSON.stringify({
1778
- prompt: truncate(result.prompt, EVIDENCE_PROMPT_CAP),
1779
- response: truncate(result.response, EVIDENCE_RESPONSE_CAP)
1780
- }),
1781
- evaluationMethod: result.llmEvaluation?.evaluationMethod,
1782
- confidence: result.llmEvaluation?.confidence,
1783
- reasoning: result.llmEvaluation?.reasoning ? truncate(result.llmEvaluation.reasoning, REASONING_CAP) : void 0
1784
- });
1785
- }
1786
- return outcome;
1787
- }
1788
- function decideExitCode(summary) {
1789
- if (summary.stillVulnerable > 0) return 1;
1790
- if (summary.fixed > 0) return 0;
1791
- return 3;
1792
- }
1793
-
1794
1920
  // src/commands/retest.ts
1795
1921
  function findingLabel(finding) {
1796
1922
  return `${finding.name} (${finding.severity})`;
@@ -1995,6 +2121,9 @@ async function retestCommand(scanId, opts) {
1995
2121
  }
1996
2122
  const fixed = outcome.verifications.filter((v) => !v.vulnerable);
1997
2123
  const stillVulnerable = outcome.verifications.filter((v) => v.vulnerable);
2124
+ const localClaims = ClaimStore.at(process.cwd()).forTarget(scan.targetUrl);
2125
+ const openClaim = (attackId) => claimContradiction(attackId, scan.targetUrl, localClaims, scan.createdAt);
2126
+ const variantsOpen = fixed.filter((v) => openClaim(v.attackId));
1998
2127
  if (opts.ci) {
1999
2128
  console.log(
2000
2129
  JSON.stringify(
@@ -2008,7 +2137,8 @@ async function retestCommand(scanId, opts) {
2008
2137
  results: outcome.verifications.map((v) => ({
2009
2138
  attackId: v.attackId,
2010
2139
  name: v.name,
2011
- outcome: v.vulnerable ? "still_vulnerable" : "fixed"
2140
+ outcome: v.vulnerable ? "still_vulnerable" : "fixed",
2141
+ ...!v.vulnerable && openClaim(v.attackId) ? { claimStatus: openClaim(v.attackId) } : {}
2012
2142
  })),
2013
2143
  failed: outcome.failed.map((f) => ({
2014
2144
  attackId: f.finding.attackId,
@@ -2029,7 +2159,10 @@ async function retestCommand(scanId, opts) {
2029
2159
  } else {
2030
2160
  console.log("");
2031
2161
  for (const v of fixed) {
2032
- console.log(` \u2713 FIXED & VERIFIED ${v.name}`);
2162
+ const open = openClaim(v.attackId);
2163
+ console.log(
2164
+ 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}`
2165
+ );
2033
2166
  }
2034
2167
  for (const v of stillVulnerable) {
2035
2168
  console.log(` \u2717 STILL VULNERABLE ${v.name}`);
@@ -2044,7 +2177,7 @@ async function retestCommand(scanId, opts) {
2044
2177
  }
2045
2178
  console.log("");
2046
2179
  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` : "") + "."
2180
+ `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
2181
  );
2049
2182
  if (verify2) {
2050
2183
  console.log(
@@ -2095,8 +2228,7 @@ function safeHostname(url) {
2095
2228
  }
2096
2229
 
2097
2230
  // src/commands/scan.ts
2098
- import { writeFileSync as writeFileSync7 } from "fs";
2099
- import { resolve as resolve4 } from "path";
2231
+ import { resolve as resolve5 } from "path";
2100
2232
 
2101
2233
  // src/reporters/evidence.ts
2102
2234
  import { writeFileSync as writeFileSync6 } from "fs";
@@ -2106,6 +2238,24 @@ import { resolve as resolve3 } from "path";
2106
2238
  import { createHash } from "crypto";
2107
2239
 
2108
2240
  // ../../packages/shared/src/compliance/remediation-validation.ts
2241
+ function claimScopeForScan(scan) {
2242
+ return {
2243
+ scanStartedAt: scan.startedAt,
2244
+ detectedFingerprints: new Set(
2245
+ Array.from(
2246
+ scan.detectedAttackIds,
2247
+ (id) => fingerprintFromScan(scan.targetUrl, id)
2248
+ )
2249
+ )
2250
+ };
2251
+ }
2252
+ function claimScanRelation(claim, scope) {
2253
+ const detected = scope.detectedFingerprints.has(claim.findingFingerprint);
2254
+ if (Date.parse(claim.createdAt) >= Date.parse(scope.scanStartedAt)) {
2255
+ return detected ? "this_scan" : "unrelated";
2256
+ }
2257
+ return detected ? "earlier_detected_again" : "earlier_not_detected";
2258
+ }
2109
2259
  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
2260
  function toClaim(c2) {
2111
2261
  const live = c2.liveVerification;
@@ -2143,9 +2293,23 @@ function toClaim(c2) {
2143
2293
  }))
2144
2294
  };
2145
2295
  }
2146
- function buildRemediationValidation(claims) {
2147
- const paragraph = DORA_PARAGRAPHS["Art. 24(5)"];
2296
+ function summarize(claims) {
2148
2297
  const count = (s) => claims.filter((c2) => c2.status === s).length;
2298
+ return {
2299
+ total: claims.length,
2300
+ confirmed: count("confirmed"),
2301
+ confirmedOverfit: count("confirmed_overfit"),
2302
+ refutedOrNotDeployed: count("refuted_or_not_deployed"),
2303
+ pending: count("pending"),
2304
+ inconclusive: count("inconclusive"),
2305
+ expired: count("expired"),
2306
+ withVerificationEvidence: claims.filter(
2307
+ (c2) => (c2.verifications ?? []).length > 0
2308
+ ).length
2309
+ };
2310
+ }
2311
+ function buildRemediationValidation(claims, scope) {
2312
+ const paragraph = DORA_PARAGRAPHS["Art. 24(5)"];
2149
2313
  return {
2150
2314
  informative: INFORMATIVE,
2151
2315
  regulation: {
@@ -2155,19 +2319,16 @@ function buildRemediationValidation(claims) {
2155
2319
  verifiedOn: DORA_PARAGRAPHS_VERIFIED_ON,
2156
2320
  source: "http://publications.europa.eu/resource/celex/32022R2554"
2157
2321
  },
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
- }
2322
+ claims: claims.map((c2) => {
2323
+ const claim = toClaim(c2);
2324
+ return scope ? { ...claim, scanRelation: claimScanRelation(c2, scope) } : claim;
2325
+ }),
2326
+ summary: summarize(claims),
2327
+ ...scope ? {
2328
+ thisScanSummary: summarize(
2329
+ claims.filter((c2) => claimScanRelation(c2, scope) === "this_scan")
2330
+ )
2331
+ } : {}
2171
2332
  };
2172
2333
  }
2173
2334
 
@@ -2351,7 +2512,7 @@ function buildEvidenceBundle(input2) {
2351
2512
  },
2352
2513
  crosswalk: buildCrosswalkBlock(),
2353
2514
  structuralAssessment: input2.assessment ?? null,
2354
- remediationValidation: input2.claims ? buildRemediationValidation(input2.claims) : null,
2515
+ remediationValidation: input2.claims ? buildRemediationValidation(input2.claims, input2.claimScope) : null,
2355
2516
  tests: budgetedTests(input2.tests),
2356
2517
  limitations: [
2357
2518
  ...bundleLimitations(
@@ -2398,71 +2559,6 @@ function toComplianceOutcomes(attacks) {
2398
2559
  }));
2399
2560
  }
2400
2561
 
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
2562
  // src/reporters/evidence.ts
2467
2563
  function claimsForTarget(target, cwd) {
2468
2564
  const file = ClaimStore.at(cwd).load();
@@ -2487,11 +2583,12 @@ function writeEvidenceBundle(input2) {
2487
2583
  responseExcerpt: a.response
2488
2584
  }));
2489
2585
  const claims = claimsForTarget(input2.report.target, input2.cwd ?? process.cwd());
2586
+ const startedAt = new Date(input2.report.timestamp).toISOString();
2490
2587
  const bundle = buildEvidenceBundle({
2491
2588
  scan: {
2492
2589
  scanId: input2.report.id,
2493
2590
  target: input2.report.target,
2494
- startedAt: new Date(input2.report.timestamp).toISOString(),
2591
+ startedAt,
2495
2592
  preset: input2.report.config.preset,
2496
2593
  attackPackVersion: ATTACK_PACK_VERSION,
2497
2594
  testsRun: executed.length,
@@ -2502,6 +2599,13 @@ function writeEvidenceBundle(input2) {
2502
2599
  compliance: input2.compliance,
2503
2600
  tests,
2504
2601
  claims,
2602
+ // Same scoping as the web bundle: a claim of an earlier run of this
2603
+ // target is context, not this scan's remediation.
2604
+ claimScope: claimScopeForScan({
2605
+ targetUrl: input2.report.target,
2606
+ startedAt,
2607
+ detectedAttackIds: input2.report.attacks.filter((a) => a.vulnerable).map((a) => baseAttackId(a.id))
2608
+ }),
2505
2609
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
2506
2610
  });
2507
2611
  const outPath = resolve3(input2.path);
@@ -2556,6 +2660,18 @@ function sanitizeReportForDisk(report, opts = {}) {
2556
2660
  }
2557
2661
 
2558
2662
  // src/lib/output-path.ts
2663
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync7 } from "fs";
2664
+ import { dirname as dirname2, resolve as resolve4 } from "path";
2665
+ function writeOutputFile(path, content) {
2666
+ const full = resolve4(path);
2667
+ mkdirSync3(dirname2(full), { recursive: true });
2668
+ writeFileSync7(
2669
+ full,
2670
+ content,
2671
+ typeof content === "string" ? "utf-8" : void 0
2672
+ );
2673
+ return full;
2674
+ }
2559
2675
  var FORMAT_EXTENSIONS = {
2560
2676
  json: ".json",
2561
2677
  markdown: ".md",
@@ -2632,10 +2748,10 @@ function buildUploadVulnerabilities(attacks) {
2632
2748
  description: a.name,
2633
2749
  evidence: a.prompt && a.response ? JSON.stringify({
2634
2750
  prompt: a.prompt,
2635
- response: truncate(a.response, 2e3)
2751
+ response: excerpt(a.response, 2e3)
2636
2752
  }) : a.response ? JSON.stringify({
2637
2753
  prompt: "",
2638
- response: truncate(a.response, 2e3)
2754
+ response: excerpt(a.response, 2e3)
2639
2755
  }) : void 0,
2640
2756
  status: a.vulnerable ? "DETECTED" : "PASSED",
2641
2757
  evaluationMethod: a.llmEvaluation?.evaluationMethod,
@@ -2711,7 +2827,9 @@ async function uploadReportToBackend(report, credentials, scanId, attackPackVers
2711
2827
  if (incomplete) throw new IncompleteRejection(incomplete);
2712
2828
  const notStored = notStoredRejection(res.status, body);
2713
2829
  if (notStored) throw new NotStoredRejection(notStored);
2714
- throw new Error(`HTTP ${res.status}: ${printableServerText(body.slice(0, 200))}`);
2830
+ throw new Error(
2831
+ `HTTP ${res.status}: ${printableServerText(body.slice(0, 200))}`
2832
+ );
2715
2833
  }
2716
2834
  const data = await res.json().catch(() => ({}));
2717
2835
  return {
@@ -2975,9 +3093,9 @@ async function scanCommand(opts) {
2975
3093
  systemPromptHash: systemPrompt,
2976
3094
  catalogHash
2977
3095
  });
2978
- const checkpointDir = opts.checkpointDir ?? resolve4(process.cwd(), ".shield-llm", "checkpoints");
3096
+ const checkpointDir = opts.checkpointDir ?? resolve5(process.cwd(), ".shield-llm", "checkpoints");
2979
3097
  const checkpointStore = new FileCheckpointStore(
2980
- resolve4(checkpointDir, `scan-${scanKey}.jsonl`)
3098
+ resolve5(checkpointDir, `scan-${scanKey}.jsonl`)
2981
3099
  );
2982
3100
  if (opts.resume === false) {
2983
3101
  await checkpointStore.finalize();
@@ -3151,11 +3269,17 @@ async function scanCommand(opts) {
3151
3269
  }
3152
3270
  }
3153
3271
  if (!opts.ci) {
3154
- printSummary(report, thresholdResult);
3272
+ printSummary(report, thresholdResult, { thresholdsConfigured });
3155
3273
  if (complianceResult) {
3156
3274
  console.log(formatComplianceTerminal(complianceResult, report.target));
3157
3275
  }
3158
3276
  if (evidenceBundleNote) console.log(evidenceBundleNote);
3277
+ if (uploadedScanId) {
3278
+ console.log(
3279
+ ` Dashboard: ${credentials.apiUrl}/scans/${uploadedScanId}
3280
+ `
3281
+ );
3282
+ }
3159
3283
  }
3160
3284
  const format = config.output?.format ?? opts.output;
3161
3285
  let outputFile = config.output?.file ?? opts.outputFile;
@@ -3172,7 +3296,7 @@ async function scanCommand(opts) {
3172
3296
  if (format === "pdf") {
3173
3297
  const pdfPath = outputFile ?? `shield-report-${report.id.slice(0, 8)}.pdf`;
3174
3298
  const pdfBuffer = await generatePdf(report);
3175
- writeFileSync7(resolve4(pdfPath), pdfBuffer);
3299
+ writeOutputFile(pdfPath, pdfBuffer);
3176
3300
  info(`PDF report written to ${pdfPath}`);
3177
3301
  } else {
3178
3302
  let content;
@@ -3194,7 +3318,7 @@ async function scanCommand(opts) {
3194
3318
  break;
3195
3319
  }
3196
3320
  if (outputFile) {
3197
- writeFileSync7(resolve4(outputFile), content, "utf-8");
3321
+ writeOutputFile(outputFile, content);
3198
3322
  info(`Report written to ${outputFile}`);
3199
3323
  } else {
3200
3324
  console.log(content);
@@ -3202,7 +3326,7 @@ async function scanCommand(opts) {
3202
3326
  }
3203
3327
  }
3204
3328
  if (opts.writeJson) {
3205
- const jsonPath = resolve4(opts.writeJson);
3329
+ const jsonPath = resolve5(opts.writeJson);
3206
3330
  const reportForDisk = opts.includeFullPayloads ? report : sanitizeReportForDisk(report);
3207
3331
  const jsonContent = formatJson({
3208
3332
  report: reportForDisk,
@@ -3210,7 +3334,7 @@ async function scanCommand(opts) {
3210
3334
  thresholdsConfigured,
3211
3335
  compliance: complianceResult
3212
3336
  });
3213
- writeFileSync7(jsonPath, jsonContent, "utf-8");
3337
+ writeOutputFile(jsonPath, jsonContent);
3214
3338
  info(
3215
3339
  `JSON copy written to ${jsonPath}${opts.includeFullPayloads ? " (full payloads)" : " (sanitized)"}`
3216
3340
  );
@@ -3539,11 +3663,11 @@ function validateCommand(opts) {
3539
3663
  // src/commands/fix.ts
3540
3664
  import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync } from "fs";
3541
3665
  import { execFileSync as execFileSync3 } from "child_process";
3542
- import { resolve as resolve6 } from "path";
3666
+ import { resolve as resolve7 } from "path";
3543
3667
 
3544
3668
  // src/fix/anchor-resolver.ts
3545
3669
  import { existsSync as existsSync4, readFileSync as readFileSync4, statSync } from "fs";
3546
- import { isAbsolute, relative, resolve as resolve5, sep } from "path";
3670
+ import { isAbsolute, relative, resolve as resolve6, sep } from "path";
3547
3671
  var AnchorError = class extends Error {
3548
3672
  constructor(message, kind, status) {
3549
3673
  super(message);
@@ -3556,8 +3680,8 @@ function safeResolve(root, relPath) {
3556
3680
  if (isAbsolute(relPath)) {
3557
3681
  throw new Error(`path must be repo-relative, got absolute: ${relPath}`);
3558
3682
  }
3559
- const rootAbs = resolve5(root);
3560
- const abs = resolve5(rootAbs, relPath);
3683
+ const rootAbs = resolve6(root);
3684
+ const abs = resolve6(rootAbs, relPath);
3561
3685
  const rel = relative(rootAbs, abs);
3562
3686
  if (rel === "" || rel.startsWith("..") || rel.startsWith(`..${sep}`)) {
3563
3687
  throw new Error(`path escapes the codebase root: ${relPath}`);
@@ -3621,7 +3745,7 @@ function resolveAll(codebase, rootDir) {
3621
3745
  return out;
3622
3746
  }
3623
3747
  function safeResolveRoot(cwd, root) {
3624
- if (root === "." || root === "./") return resolve5(cwd);
3748
+ if (root === "." || root === "./") return resolve6(cwd);
3625
3749
  return safeResolve(cwd, root);
3626
3750
  }
3627
3751
 
@@ -3688,6 +3812,21 @@ function evaluateVerdict(input2, options = {}) {
3688
3812
  }
3689
3813
 
3690
3814
  // src/fix/plan.ts
3815
+ 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`;
3816
+ function groupSkipped(skipped) {
3817
+ const groups = /* @__PURE__ */ new Map();
3818
+ for (const s of skipped) {
3819
+ const key = `${s.reason}|${s.detail}`;
3820
+ const group = groups.get(key) ?? {
3821
+ reason: s.reason,
3822
+ detail: s.detail,
3823
+ attackIds: []
3824
+ };
3825
+ group.attackIds.push(s.attackId);
3826
+ groups.set(key, group);
3827
+ }
3828
+ return Array.from(groups.values());
3829
+ }
3691
3830
  function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
3692
3831
  const targetId = normalizeTargetUrl(targetUrl);
3693
3832
  const anchors = resolveAll(codebase, cwd);
@@ -3720,10 +3859,7 @@ function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
3720
3859
  (r) => r.appliesTo.includes(f.attackId)
3721
3860
  );
3722
3861
  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
- );
3862
+ push("no_recipe_for_attack", NO_RECIPE_DETAIL);
3727
3863
  continue;
3728
3864
  }
3729
3865
  const stackOk = candidates.filter(
@@ -3789,8 +3925,8 @@ function blockedByAnchor(anchors) {
3789
3925
  }
3790
3926
 
3791
3927
  // 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";
3928
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync, writeFileSync as writeFileSync8 } from "fs";
3929
+ import { dirname as dirname3, relative as relative2 } from "path";
3794
3930
 
3795
3931
  // src/fix/marker-block.ts
3796
3932
  var EXT_STYLE = {
@@ -3980,7 +4116,7 @@ var WorkingSet = class {
3980
4116
  if (existsSync5(abs)) rmSync(abs);
3981
4117
  continue;
3982
4118
  }
3983
- mkdirSync3(dirname2(abs), { recursive: true });
4119
+ mkdirSync4(dirname3(abs), { recursive: true });
3984
4120
  writeFileSync8(abs, current, "utf8");
3985
4121
  }
3986
4122
  }
@@ -4204,13 +4340,21 @@ function revertRecipe(recipe, ctx) {
4204
4340
  // src/fix/pr-body.ts
4205
4341
  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
4342
  function proseFor(recipe) {
4207
- const prose = getStructuredRemediation(recipe.remediationRef.vulnerabilityType);
4208
- const layer = prose.layers.find((l) => l.layer === recipe.remediationRef.layer);
4343
+ const prose = getStructuredRemediation(
4344
+ recipe.remediationRef.vulnerabilityType
4345
+ );
4346
+ const layer = prose.layers.find(
4347
+ (l) => l.layer === recipe.remediationRef.layer
4348
+ );
4209
4349
  if (!layer) return [];
4210
4350
  return recipe.remediationRef.stepIndexes.map((i) => layer.steps[i]).filter(Boolean).map((s) => `> ${s.text}${s.owaspRef ? ` _(${s.owaspRef})_` : ""}`);
4211
4351
  }
4212
4352
  function liveSection(v) {
4213
- const lines = ["", "**Verified live before this PR opened**", ""];
4353
+ const lines = [
4354
+ "",
4355
+ v.passed ? "**Verified live before this PR opened**" : "**Refused by the live verification**",
4356
+ ""
4357
+ ];
4214
4358
  lines.push(
4215
4359
  `- Redeployed with \`${v.redeployCommand}\`, then the attack family was replayed against the running target (${v.verifiedAt}).`
4216
4360
  );
@@ -4218,8 +4362,13 @@ function liveSection(v) {
4218
4362
  `- Design attacks closed: ${v.designClearedIds.length}/${v.designAttackIds.length}` + (v.designClearedIds.length ? ` (${v.designClearedIds.join(", ")})` : "")
4219
4363
  );
4220
4364
  if (v.holdoutAttackIds.length) {
4365
+ const open = v.holdoutAttackIds.filter(
4366
+ (a) => !v.holdoutClearedIds.includes(a)
4367
+ );
4368
+ const exploitClosed = v.designClearedIds.length === v.designAttackIds.length;
4369
+ const verdict = !exploitClosed ? "." : open.length === 0 ? " \u2014 the patch generalised beyond the exploit it was written for." : " \u2014 the patch is overfitted to the exploit it was written for.";
4221
4370
  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."
4371
+ `- Holdout attacks closed: ${v.holdoutClearedIds.length}/${v.holdoutAttackIds.length}` + (v.holdoutClearedIds.length ? ` (${v.holdoutClearedIds.join(", ")})` : "") + (open.length ? `, still open: ${open.join(", ")}` : "") + verdict
4223
4372
  );
4224
4373
  }
4225
4374
  lines.push(
@@ -4230,11 +4379,20 @@ function liveSection(v) {
4230
4379
  '- \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
4380
  );
4232
4381
  }
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
- );
4382
+ lines.push(v.passed ? PASSED_LINE : refusalLine(v));
4236
4383
  return lines;
4237
4384
  }
4385
+ 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.";
4386
+ function refusalLine(v) {
4387
+ const attacksOpen = v.designClearedIds.length < v.designAttackIds.length || v.holdoutClearedIds.length < v.holdoutAttackIds.length;
4388
+ if (attacksOpen) {
4389
+ return "- The patch did **not** close every attack: the finding stays open. Fix it at the layer the remediation guidance names, then verify again.";
4390
+ }
4391
+ if (!v.benign.green) {
4392
+ 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.";
4393
+ }
4394
+ return "- The verification could **not** conclude (a degraded judge or an attack with no verdict): the finding stays open. Run it again.";
4395
+ }
4238
4396
  function recipeSection(p, live) {
4239
4397
  const { recipe } = p;
4240
4398
  const reliability = LAYER_META[recipe.remediationRef.layer].reliability;
@@ -4305,7 +4463,8 @@ function withheldSection(withheld, live) {
4305
4463
  out.push(
4306
4464
  `- \`${p.attackId}\` \u2014 \`${p.recipe.id}\`` + (open.length ? `: still vulnerable to ${open.join(", ")} after the patch.` : "")
4307
4465
  );
4308
- if (v && !v.benign.green) out.push(` - Benign regression gate: ${v.benign.detail}`);
4466
+ if (v && !v.benign.green)
4467
+ out.push(` - Benign regression gate: ${v.benign.detail}`);
4309
4468
  if (v && v.notExecutedAttackIds.length) {
4310
4469
  out.push(` - No verdict for ${v.notExecutedAttackIds.join(", ")}.`);
4311
4470
  }
@@ -4348,8 +4507,10 @@ function renderPrBody(plan, live, withheld = [], rescan = []) {
4348
4507
  if (plan.skipped.length) {
4349
4508
  out.push("### Findings this PR does NOT address");
4350
4509
  out.push("");
4351
- for (const s of plan.skipped) {
4352
- out.push(`- \`${s.attackId}\` \u2014 ${s.reason}: ${s.detail}`);
4510
+ for (const g of groupSkipped(plan.skipped)) {
4511
+ out.push(
4512
+ `- ${g.attackIds.map((a) => `\`${a}\``).join(", ")} \u2014 ${g.reason}: ${g.detail}`
4513
+ );
4353
4514
  }
4354
4515
  out.push("");
4355
4516
  }
@@ -4470,6 +4631,19 @@ function describeClaimSync(result) {
4470
4631
  return `Remediation claims not copied to the dashboard: ${result.reason}. The local store is unaffected.`;
4471
4632
  }
4472
4633
 
4634
+ // src/lib/progress-line.ts
4635
+ function phaseProgress(label, write = (line) => console.error(line)) {
4636
+ let shown = 0;
4637
+ return (done, total) => {
4638
+ if (total <= 0) return;
4639
+ const step = Math.max(1, Math.ceil(total / 4));
4640
+ if (done === total || done - shown >= step) {
4641
+ shown = done;
4642
+ write(` ${label}: ${done}/${total}`);
4643
+ }
4644
+ };
4645
+ }
4646
+
4473
4647
  // src/benign/runner.ts
4474
4648
  var RATE_LIMIT_RETRIES = 4;
4475
4649
  var MAX_RATE_LIMIT_WAIT_S = 60;
@@ -4503,6 +4677,7 @@ async function captureBenign(target, cases, opts = {}) {
4503
4677
  hash: sha256Hex(response),
4504
4678
  ...opts.keepResponses ? { response } : {}
4505
4679
  });
4680
+ opts.onProgress?.(out.length, cases.length);
4506
4681
  if (opts.delayMs) await new Promise((r) => setTimeout(r, opts.delayMs));
4507
4682
  }
4508
4683
  return out;
@@ -4595,10 +4770,15 @@ async function judgeBenign(captures, cases, evaluator, opts = {}) {
4595
4770
  ...verdict.split ? { split: true } : {}
4596
4771
  };
4597
4772
  };
4773
+ let judged = 0;
4598
4774
  return mapInOrder(
4599
4775
  captures,
4600
4776
  opts.concurrency ?? BENIGN_JUDGE_CONCURRENCY,
4601
- judgeOne
4777
+ async (cap) => {
4778
+ const result = await judgeOne(cap);
4779
+ opts.onProgress?.(++judged, captures.length);
4780
+ return result;
4781
+ }
4602
4782
  );
4603
4783
  }
4604
4784
  async function mapInOrder(items, limit, fn) {
@@ -4625,10 +4805,12 @@ async function mapInOrder(items, limit, fn) {
4625
4805
  async function captureBenignBaseline(target, scope, judge) {
4626
4806
  const judged = scope === "model-behaviour" && judge !== void 0;
4627
4807
  const run1 = await captureBenign(target, BENIGN_CORE_V1, {
4628
- keepResponses: judged
4808
+ keepResponses: judged,
4809
+ onProgress: phaseProgress("Legitimate questions before the patch, run 1/2")
4629
4810
  });
4630
4811
  const run2 = await captureBenign(target, BENIGN_CORE_V1, {
4631
- keepResponses: judged
4812
+ keepResponses: judged,
4813
+ onProgress: phaseProgress("Legitimate questions before the patch, run 2/2")
4632
4814
  });
4633
4815
  const strip = (run, verdicts) => run.map((c2, i) => {
4634
4816
  const v = verdicts?.[i];
@@ -4653,8 +4835,14 @@ async function captureBenignBaseline(target, scope, judge) {
4653
4835
  let verdicts1;
4654
4836
  let verdicts2;
4655
4837
  try {
4656
- verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, opts);
4657
- verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, opts);
4838
+ verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, {
4839
+ ...opts,
4840
+ onProgress: phaseProgress("Judging the answers before the patch, run 1/2")
4841
+ });
4842
+ verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, {
4843
+ ...opts,
4844
+ onProgress: phaseProgress("Judging the answers before the patch, run 2/2")
4845
+ });
4658
4846
  } catch (e) {
4659
4847
  console.warn(
4660
4848
  `\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.`
@@ -4712,7 +4900,9 @@ async function runBenignGate(input2) {
4712
4900
  (c2) => baseline.run1.some((b) => b.name === c2.name)
4713
4901
  );
4714
4902
  if (scope === "rendering") {
4715
- const after = await captureBenign(target, cases);
4903
+ const after = await captureBenign(target, cases, {
4904
+ onProgress: phaseProgress("Legitimate questions after the patch")
4905
+ });
4716
4906
  const report = evaluateBenign({
4717
4907
  suiteId: baseline.suiteId,
4718
4908
  cases,
@@ -4738,13 +4928,19 @@ async function runBenignGate(input2) {
4738
4928
  return judgePatchedAnswers(baseline, cases, contract, target, judge);
4739
4929
  }
4740
4930
  async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
4741
- const after = await captureBenign(target, cases, { keepResponses: true });
4931
+ const after = await captureBenign(target, cases, {
4932
+ keepResponses: true,
4933
+ onProgress: phaseProgress("Legitimate questions after the patch")
4934
+ });
4742
4935
  const unchanged = unchangedVerdicts(baseline, after);
4743
4936
  const judged = await judgeBenign(
4744
4937
  after.filter((a) => !unchanged.has(a.name)),
4745
4938
  cases,
4746
4939
  judge,
4747
- { votes: BENIGN_VOTES }
4940
+ {
4941
+ votes: BENIGN_VOTES,
4942
+ onProgress: phaseProgress("Judging the answers that changed")
4943
+ }
4748
4944
  );
4749
4945
  const judgedByName = new Map(judged.map((r) => [r.name, r]));
4750
4946
  const afterRun = after.map(
@@ -5347,6 +5543,80 @@ ${manualPrInstructions(branch, base)}`
5347
5543
  };
5348
5544
  }
5349
5545
 
5546
+ // src/fix/verify-outcome.ts
5547
+ function refusedPatches(plan, live) {
5548
+ if (live.size === 0) return [];
5549
+ return plan.planned.filter((p) => live.get(p.fingerprint)?.passed !== true).map((p) => p.attackId);
5550
+ }
5551
+
5552
+ // src/fix/dashboard-scan.ts
5553
+ var FETCH_TIMEOUT_MS = 3e4;
5554
+ function findingsFromStoredScan(scan) {
5555
+ const vulns = scan.vulns ?? [];
5556
+ const findings = selectRetestableFindings(
5557
+ vulns,
5558
+ void 0,
5559
+ scan.targetUrl
5560
+ ).flatMap(
5561
+ (f) => f.attackId === null ? [] : [
5562
+ {
5563
+ attackId: f.attackId,
5564
+ name: f.name,
5565
+ severity: f.severity,
5566
+ evaluationMethod: f.evaluationMethod ?? null,
5567
+ confidence: f.confidence ?? null,
5568
+ judgeErrorCategory: null,
5569
+ disagreementResolution: null
5570
+ }
5571
+ ]
5572
+ );
5573
+ const seen = /* @__PURE__ */ new Set();
5574
+ const allAttacks = [];
5575
+ for (const v of vulns) {
5576
+ if (!v.vulnerabilityType || seen.has(v.vulnerabilityType)) continue;
5577
+ seen.add(v.vulnerabilityType);
5578
+ allAttacks.push({
5579
+ id: v.vulnerabilityType,
5580
+ severity: v.severity,
5581
+ vulnerable: v.status === "DETECTED",
5582
+ ...v.captureStatus ? { captureStatus: v.captureStatus } : {}
5583
+ });
5584
+ }
5585
+ return { targetUrl: scan.targetUrl, findings, allAttacks };
5586
+ }
5587
+ async function fetchStoredScan(apiUrl, apiKey, scanId) {
5588
+ let res;
5589
+ try {
5590
+ res = await fetch(
5591
+ `${apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}`,
5592
+ {
5593
+ headers: { Authorization: `Bearer ${apiKey}` },
5594
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
5595
+ }
5596
+ );
5597
+ } catch (err) {
5598
+ const msg = err instanceof Error ? err.message : String(err);
5599
+ throw new Error(`Failed to reach the dashboard (${apiUrl}): ${msg}`);
5600
+ }
5601
+ if (!res.ok) {
5602
+ await res.text().catch(() => void 0);
5603
+ if (res.status === 401) {
5604
+ throw new Error(
5605
+ "API key invalid or revoked. Run `shield-llm login` to re-authenticate."
5606
+ );
5607
+ }
5608
+ if (res.status === 404) throw new Error(`Scan "${scanId}" not found.`);
5609
+ throw new Error(`The dashboard returned HTTP ${res.status} for the scan.`);
5610
+ }
5611
+ const scan = await res.json();
5612
+ if (scan.status && scan.status !== "completed") {
5613
+ throw new Error(
5614
+ `Scan "${scanId}" is ${scan.status}: only a completed scan has findings to fix.`
5615
+ );
5616
+ }
5617
+ return scan;
5618
+ }
5619
+
5350
5620
  // src/commands/fix.ts
5351
5621
  var resolvedEvaluators = /* @__PURE__ */ new WeakMap();
5352
5622
  function resolveEvaluator(opts) {
@@ -5465,8 +5735,9 @@ function printPlan(plan) {
5465
5735
  console.log(
5466
5736
  `Not patchable (${plan.skipped.length}) \u2014 these become issues, not PRs:`
5467
5737
  );
5468
- for (const s of plan.skipped) {
5469
- console.log(` \xB7 ${s.attackId.padEnd(24)} ${s.reason}: ${s.detail}`);
5738
+ for (const g of groupSkipped(plan.skipped)) {
5739
+ console.log(` \xB7 ${g.reason}: ${g.detail}`);
5740
+ console.log(` ${g.attackIds.join(", ")}`);
5470
5741
  }
5471
5742
  console.log();
5472
5743
  }
@@ -5521,18 +5792,35 @@ async function fixCommand(opts) {
5521
5792
  let findings;
5522
5793
  let beforeAttacks = [];
5523
5794
  try {
5795
+ let source;
5524
5796
  if (opts.report) {
5525
- const local = findingsFromLocalReport(resolve6(cwd, opts.report));
5526
- targetUrl = local.targetUrl;
5527
- findings = local.findings;
5528
- beforeAttacks = local.allAttacks;
5797
+ source = findingsFromLocalReport(resolve7(cwd, opts.report));
5798
+ } else if (opts.scan) {
5799
+ const stored = loadCredentials();
5800
+ if (!stored) {
5801
+ console.error(
5802
+ "Not logged in: `shield-llm fix <scanId>` reads the scan from your dashboard. Run `shield-llm login`, or pass --report <shield-report.json>."
5803
+ );
5804
+ setExitCode(2);
5805
+ return;
5806
+ }
5807
+ source = findingsFromStoredScan(
5808
+ await fetchStoredScan(
5809
+ resolveApiUrl(stored.apiUrl, opts.apiUrl),
5810
+ stored.apiKey,
5811
+ opts.scan
5812
+ )
5813
+ );
5529
5814
  } else {
5530
5815
  console.error(
5531
- "Provide --report <shield-report.json>. (Dashboard mode via --scan lands with the claim API.)"
5816
+ "Name the scan to fix: `shield-llm fix <scanId>` (from the dashboard) or `shield-llm fix --report <shield-report.json>` (from `scan --write-json`)."
5532
5817
  );
5533
5818
  setExitCode(2);
5534
5819
  return;
5535
5820
  }
5821
+ targetUrl = source.targetUrl;
5822
+ findings = source.findings;
5823
+ beforeAttacks = source.allAttacks;
5536
5824
  } catch (e) {
5537
5825
  console.error(e instanceof Error ? e.message : String(e));
5538
5826
  setExitCode(2);
@@ -5738,6 +6026,14 @@ Re-scanning the ${beforeAttacks.length} attack(s) of the original scan\u2026`
5738
6026
  }
5739
6027
  console.log("\n\u2500\u2500\u2500 PR body \u2500\u2500\u2500\n");
5740
6028
  console.log(renderPrBody(plan, live, [], rescanLines));
6029
+ const refused = refusedPatches(plan, live);
6030
+ if (refused.length) {
6031
+ console.error(
6032
+ `
6033
+ ${refused.length} of ${plan.planned.length} patch(es) did not pass the live verification (${refused.join(", ")}): the finding(s) stay open. Exit code 1.`
6034
+ );
6035
+ setExitCode(1);
6036
+ }
5741
6037
  }
5742
6038
  async function liveVerificationPhase(plan, config, codebase, cwd, opts, baseline) {
5743
6039
  const evidence = /* @__PURE__ */ new Map();
@@ -5993,11 +6289,11 @@ Could not open the PR: ${res.detail}`);
5993
6289
  if (holding.length) setExitCode(1);
5994
6290
  }
5995
6291
  function closurePathConfigured(root) {
5996
- const dir = resolve6(root, ".github/workflows");
6292
+ const dir = resolve7(root, ".github/workflows");
5997
6293
  if (!existsSync6(dir)) return false;
5998
6294
  try {
5999
6295
  return readdirSync(dir).some(
6000
- (f) => readFileSync6(resolve6(dir, f), "utf8").includes("verify-claims")
6296
+ (f) => readFileSync6(resolve7(dir, f), "utf8").includes("verify-claims")
6001
6297
  );
6002
6298
  } catch {
6003
6299
  return false;
@@ -6092,6 +6388,9 @@ async function verifyClaimsCommand(opts) {
6092
6388
  continue;
6093
6389
  }
6094
6390
  const { catalogue } = resolved;
6391
+ console.error(
6392
+ `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`
6393
+ );
6095
6394
  const { verdicts, judgeDegraded } = await replayFamily(
6096
6395
  claim.contract,
6097
6396
  target,
@@ -6348,9 +6647,9 @@ program.command("tests").description("List custom tests (local config and/or rem
6348
6647
  "--api-url <url>",
6349
6648
  "Backend API URL (overrides SHIELD_API_URL env var)"
6350
6649
  ).action(testsCommand);
6351
- program.command("fix").description(
6352
- "Patch findings from a scan report using declarative remediation recipes"
6353
- ).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(
6650
+ program.command("fix [scanId]").description(
6651
+ "Patch the findings of a scan (a dashboard scan id, or --report) using declarative remediation recipes"
6652
+ ).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(
6354
6653
  "--explain",
6355
6654
  "Show which recipes apply and which anchors would unlock more"
6356
6655
  ).option("--revert", "Remove every shield-llm block this recipe set owns").option(
@@ -6381,7 +6680,19 @@ program.command("fix").description(
6381
6680
  ).option(
6382
6681
  "--yes",
6383
6682
  "Skip the confirmation prompt before running the configured redeploy command"
6384
- ).action(fixCommand);
6683
+ ).action(async (scanId, o) => {
6684
+ if (scanId && o.scan && scanId !== o.scan) {
6685
+ console.error(`Two scan ids given (${scanId} and --scan ${o.scan}).`);
6686
+ setExitCode(2);
6687
+ return;
6688
+ }
6689
+ if ((scanId || o.scan) && o.report) {
6690
+ console.error("Pass a scan id or --report, not both.");
6691
+ setExitCode(2);
6692
+ return;
6693
+ }
6694
+ await fixCommand({ ...o, scan: o.scan ?? scanId });
6695
+ });
6385
6696
  program.command("verify-claims").description(
6386
6697
  "Replay the attack family of every pending remediation claim and close (or refuse to close) it"
6387
6698
  ).option("-c, --config <path>", "Path to config file").option(