shield-llm 0.7.4 → 0.7.6

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.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cjs_createRequire } from "module"; import { fileURLToPath as __cjs_fileURLToPath } from "url"; import { dirname as __cjs_dirname } from "path"; const __filename = __cjs_fileURLToPath(import.meta.url); const __dirname = __cjs_dirname(__filename); const require = __cjs_createRequire(import.meta.url);
2
2
 
3
3
  // package.json
4
- var version = "0.7.4";
4
+ var version = "0.7.6";
5
5
 
6
6
  // src/config/schema.ts
7
7
  import { z as z2 } from "zod";
@@ -7840,6 +7840,13 @@ function resolveClaim(input) {
7840
7840
  notExecutedAttackIds: []
7841
7841
  };
7842
7842
  }
7843
+ if (!input.benignGreen && input.benignRan === false) {
7844
+ return {
7845
+ status: "inconclusive",
7846
+ reason: `attacks closed but the benign gate could not run (${input.benignDetail ?? "no detail"}) \u2014 it says nothing either way about legitimate traffic, so the claim does not move`,
7847
+ notExecutedAttackIds: []
7848
+ };
7849
+ }
7843
7850
  if (!input.benignGreen) {
7844
7851
  return {
7845
7852
  status: "refuted_or_not_deployed",
@@ -13527,6 +13534,7 @@ export {
13527
13534
  BENIGN_SUITE_ID,
13528
13535
  BENIGN_CORE_V1,
13529
13536
  evaluateBenign,
13537
+ RateLimitError,
13530
13538
  checkConversationContext,
13531
13539
  checkSessionIsolation,
13532
13540
  createTargetClient,
package/dist/cli.js CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  LAYER_META,
19
19
  MUTATORS,
20
20
  RECIPES,
21
+ RateLimitError,
21
22
  RegexOnlyEvaluator,
22
23
  Scanner,
23
24
  analyzeJudgeHealth,
@@ -67,7 +68,7 @@ import {
67
68
  sha256Hex,
68
69
  summarizeAttackErrors,
69
70
  version
70
- } from "./chunk-WH32F52L.js";
71
+ } from "./chunk-4OIZTQGA.js";
71
72
 
72
73
  // src/load-env.ts
73
74
  try {
@@ -4249,13 +4250,30 @@ function renderPrBody(plan, live, withheld = [], rescan = []) {
4249
4250
  }
4250
4251
 
4251
4252
  // src/benign/runner.ts
4253
+ var RATE_LIMIT_RETRIES = 4;
4254
+ var MAX_RATE_LIMIT_WAIT_S = 60;
4255
+ async function sendPatiently(client, prompt) {
4256
+ for (let attempt = 0; ; attempt++) {
4257
+ try {
4258
+ return await client.sendMessage(prompt);
4259
+ } catch (e) {
4260
+ if (!(e instanceof RateLimitError) || attempt >= RATE_LIMIT_RETRIES)
4261
+ throw e;
4262
+ const waitS = Math.min(
4263
+ e.retryAfterSec ?? 5 * 2 ** attempt,
4264
+ MAX_RATE_LIMIT_WAIT_S
4265
+ );
4266
+ await new Promise((r) => setTimeout(r, waitS * 1e3));
4267
+ }
4268
+ }
4269
+ }
4252
4270
  async function captureBenign(target, cases, opts = {}) {
4253
4271
  const client = createTargetClient(target, void 0, { resolveEnv: true });
4254
4272
  const out = [];
4255
4273
  for (const c2 of cases) {
4256
4274
  let response = "";
4257
4275
  try {
4258
- response = await client.sendMessage(c2.prompt);
4276
+ response = await sendPatiently(client, c2.prompt);
4259
4277
  } catch (e) {
4260
4278
  response = `__SHIELD_CAPTURE_ERROR__:${e instanceof Error ? e.message : "unknown"}`;
4261
4279
  }
@@ -4273,7 +4291,10 @@ function isCaptureError(capture) {
4273
4291
  }
4274
4292
  function toRunResults(baseline, after) {
4275
4293
  const byName = new Map(baseline.map((b) => [b.name, b.hash]));
4276
- return after.map((a) => ({ name: a.name, passed: byName.get(a.name) === a.hash }));
4294
+ return after.map((a) => ({
4295
+ name: a.name,
4296
+ passed: byName.get(a.name) === a.hash
4297
+ }));
4277
4298
  }
4278
4299
  function baselineRunResults(run1, run2) {
4279
4300
  const r1 = new Map(run1.map((b) => [b.name, b.hash]));
@@ -4283,34 +4304,145 @@ function baselineRunResults(run1, run2) {
4283
4304
  run2.map((c2) => ({ name: c2.name, passed: stable(c2) }))
4284
4305
  ];
4285
4306
  }
4286
- async function judgeBenign(captures, cases, evaluator) {
4307
+ var BENIGN_VOTES = 3;
4308
+ function voteAttackId(caseName, vote) {
4309
+ return vote === 0 ? `benign_${caseName}` : `benign_${caseName}#${vote + 1}`;
4310
+ }
4311
+ var DEGRADED_VOTE_RETRY = { attempts: 2, waitMs: 5e3 };
4312
+ var TRANSIENT_JUDGE_ERRORS = /* @__PURE__ */ new Set([
4313
+ "rate_limit",
4314
+ "timeout",
4315
+ "network",
4316
+ "provider_error",
4317
+ "schema"
4318
+ ]);
4319
+ async function oneVote(c2, response, evaluator, vote, budget) {
4320
+ for (let attempt = 0; ; attempt++) {
4321
+ const verdict = await evaluator.evaluate({
4322
+ attackId: voteAttackId(c2.name, vote),
4323
+ attackName: c2.name,
4324
+ attackPrompt: c2.prompt,
4325
+ severity: "LOW",
4326
+ response,
4327
+ regexResult: { vulnerable: false },
4328
+ customTest: { name: c2.name, acceptanceCriteria: c2.acceptanceCriteria }
4329
+ });
4330
+ const error = verdict.llmResult?.judgeError;
4331
+ if (!error) return verdict.vulnerable;
4332
+ if (!budget.open || !TRANSIENT_JUDGE_ERRORS.has(error.category))
4333
+ return void 0;
4334
+ if (attempt >= DEGRADED_VOTE_RETRY.attempts) {
4335
+ budget.open = false;
4336
+ return void 0;
4337
+ }
4338
+ const wait = DEGRADED_VOTE_RETRY.waitMs * (attempt + 1);
4339
+ await new Promise((r) => setTimeout(r, wait));
4340
+ }
4341
+ }
4342
+ async function voteOnAnswer(c2, response, evaluator, votes, budget) {
4343
+ let letters = "";
4344
+ for (let i = 0; i < votes; i++) {
4345
+ const vulnerable = await oneVote(c2, response, evaluator, i, budget);
4346
+ if (vulnerable === void 0) return void 0;
4347
+ letters += vulnerable ? "F" : "P";
4348
+ }
4349
+ const passes = letters.split("").filter((l) => l === "P").length;
4350
+ return {
4351
+ // A tie (even vote count) is not a pass.
4352
+ passed: passes * 2 > votes,
4353
+ split: passes > 0 && passes < votes,
4354
+ votes: letters
4355
+ };
4356
+ }
4357
+ async function judgeBenign(captures, cases, evaluator, opts = {}) {
4287
4358
  const byName = new Map(cases.map((c2) => [c2.name, c2]));
4288
4359
  const out = [];
4360
+ const budget = { open: true };
4289
4361
  for (const cap of captures) {
4290
4362
  const c2 = byName.get(cap.name);
4291
- if (!c2 || cap.response === void 0) {
4292
- out.push({ name: cap.name, passed: true });
4363
+ if (!c2 || cap.response === void 0 || isCaptureError(cap)) {
4364
+ out.push({ name: cap.name, passed: true, unobserved: true });
4293
4365
  continue;
4294
4366
  }
4295
- if (isCaptureError(cap)) {
4296
- out.push({ name: cap.name, passed: true });
4367
+ const key = `${cap.name}:${cap.hash}`;
4368
+ const verdict = opts.memo?.get(key) ?? await voteOnAnswer(c2, cap.response, evaluator, opts.votes ?? 1, budget);
4369
+ if (!verdict) {
4370
+ out.push({ name: cap.name, passed: true, unjudged: true });
4297
4371
  continue;
4298
4372
  }
4299
- const verdict = await evaluator.evaluate({
4300
- attackId: `benign_${c2.name}`,
4301
- attackName: c2.name,
4302
- attackPrompt: c2.prompt,
4303
- severity: "LOW",
4304
- response: cap.response,
4305
- regexResult: { vulnerable: false },
4306
- customTest: { name: c2.name, acceptanceCriteria: c2.acceptanceCriteria }
4373
+ opts.memo?.set(key, verdict);
4374
+ out.push({
4375
+ name: cap.name,
4376
+ passed: verdict.passed,
4377
+ votes: verdict.votes,
4378
+ ...verdict.split ? { split: true } : {}
4307
4379
  });
4308
- out.push({ name: cap.name, passed: !verdict.vulnerable });
4309
4380
  }
4310
4381
  return out;
4311
4382
  }
4312
4383
 
4313
4384
  // src/fix/live-verify.ts
4385
+ async function captureBenignBaseline(target, scope, judge) {
4386
+ const judged = scope === "model-behaviour" && judge !== void 0;
4387
+ const run1 = await captureBenign(target, BENIGN_CORE_V1, {
4388
+ keepResponses: judged
4389
+ });
4390
+ const run2 = await captureBenign(target, BENIGN_CORE_V1, {
4391
+ keepResponses: judged
4392
+ });
4393
+ const strip = (run, verdicts) => run.map((c2, i) => {
4394
+ const v = verdicts?.[i];
4395
+ const hasVerdict2 = v && !v.unobserved && !v.unjudged;
4396
+ return {
4397
+ name: c2.name,
4398
+ hash: c2.hash,
4399
+ ...hasVerdict2 ? { passed: v.passed } : {},
4400
+ ...hasVerdict2 && v.split ? { split: true } : {}
4401
+ };
4402
+ });
4403
+ const unjudged = {
4404
+ suiteId: BENIGN_SUITE_ID,
4405
+ scope,
4406
+ run1: strip(run1),
4407
+ run2: strip(run2)
4408
+ };
4409
+ if (!judged) return unjudged;
4410
+ const opts = { memo: /* @__PURE__ */ new Map(), votes: BENIGN_VOTES };
4411
+ let verdicts1;
4412
+ let verdicts2;
4413
+ try {
4414
+ verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, opts);
4415
+ verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, opts);
4416
+ } catch (e) {
4417
+ console.warn(
4418
+ `\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.`
4419
+ );
4420
+ return unjudged;
4421
+ }
4422
+ const all = [...verdicts1, ...verdicts2];
4423
+ const notCaptured = all.filter((v) => v.unobserved).length;
4424
+ const notRuled = all.filter((v) => v.unjudged).length;
4425
+ if (notCaptured || notRuled) {
4426
+ console.warn(
4427
+ `\u26A0\uFE0F No verdict for ${notCaptured + notRuled} of ${all.length} baseline answers (${notCaptured} not captured, ${notRuled} the judge could not rule on). Those cases are assumed to have passed before the patch, as without a judged baseline.`
4428
+ );
4429
+ }
4430
+ return {
4431
+ suiteId: BENIGN_SUITE_ID,
4432
+ scope,
4433
+ run1: strip(run1, verdicts1),
4434
+ run2: strip(run2, verdicts2)
4435
+ };
4436
+ }
4437
+ function judgedBaselineRuns(baseline, splitPassed) {
4438
+ const entries = [...baseline.run1, ...baseline.run2];
4439
+ if (!entries.some((b) => typeof b.passed === "boolean")) return void 0;
4440
+ const toRun = (run) => run.map((b) => ({
4441
+ name: b.name,
4442
+ passed: b.split ? splitPassed : b.passed !== false
4443
+ }));
4444
+ return [toRun(baseline.run1), toRun(baseline.run2)];
4445
+ }
4314
4446
  async function runBenignGate(input2) {
4315
4447
  const { baseline, contract, target } = input2;
4316
4448
  const scope = baseline?.scope ?? contract.benignScope;
@@ -4338,18 +4470,18 @@ async function runBenignGate(input2) {
4338
4470
  (c2) => baseline.run1.some((b) => b.name === c2.name)
4339
4471
  );
4340
4472
  if (scope === "rendering") {
4341
- const after2 = await captureBenign(target, cases);
4342
- const report2 = evaluateBenign({
4473
+ const after = await captureBenign(target, cases);
4474
+ const report = evaluateBenign({
4343
4475
  suiteId: baseline.suiteId,
4344
4476
  cases,
4345
4477
  baselineRuns: baselineRunResults(baseline.run1, baseline.run2),
4346
- afterRun: toRunResults(baseline.run1, after2),
4478
+ afterRun: toRunResults(baseline.run1, after),
4347
4479
  gate: contract.benignGate
4348
4480
  });
4349
4481
  return {
4350
- green: !report2.blocked,
4482
+ green: !report.blocked,
4351
4483
  ran: true,
4352
- detail: report2.blocked ? `blocked: ${report2.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases, ${report2.flips.length} flip(s), ${report2.flakyCaseNames.length} flaky`
4484
+ 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`
4353
4485
  };
4354
4486
  }
4355
4487
  const judge = input2.evaluator;
@@ -4360,20 +4492,87 @@ async function runBenignGate(input2) {
4360
4492
  detail: "benignScope is `model-behaviour` but no judge is available \u2014 the answers legitimately changed, so only a judge could rule and the gate did not run. Configure a judge, or accept the risk explicitly with --assume-benign-green."
4361
4493
  };
4362
4494
  }
4495
+ return judgePatchedAnswers(baseline, cases, contract, target, judge);
4496
+ }
4497
+ async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
4363
4498
  const after = await captureBenign(target, cases, { keepResponses: true });
4364
- const report = evaluateBenign({
4499
+ const afterRun = await judgeBenign(after, cases, judge, {
4500
+ votes: BENIGN_VOTES
4501
+ });
4502
+ const notPassing = afterRun.flatMap(
4503
+ (r, i) => r.votes?.includes("F") ? [{ name: r.name, hash: after[i].hash, votes: r.votes }] : []
4504
+ );
4505
+ const notCaptured = afterRun.filter((r) => r.unobserved).length;
4506
+ if (notCaptured) {
4507
+ return {
4508
+ green: false,
4509
+ ran: false,
4510
+ detail: `${notCaptured} of ${cases.length} benign answers could not be captured from the target, so the gate could not run`,
4511
+ notPassing
4512
+ };
4513
+ }
4514
+ const unjudged = afterRun.filter((r) => r.unjudged).length;
4515
+ if (unjudged) {
4516
+ return {
4517
+ green: false,
4518
+ ran: false,
4519
+ detail: `the judge could not rule on ${unjudged} of ${cases.length} benign answers (degraded), so the gate could not run`,
4520
+ notPassing
4521
+ };
4522
+ }
4523
+ return { ...ruleOnVotes(baseline, cases, contract, afterRun), notPassing };
4524
+ }
4525
+ function ruleOnVotes(baseline, cases, contract, afterRun) {
4526
+ const judged = judgedBaselineRuns(baseline, true) !== void 0;
4527
+ const read = (favourable) => evaluateBenign({
4365
4528
  suiteId: baseline.suiteId,
4366
4529
  cases,
4367
- baselineRuns: baselineRunResults(baseline.run1, baseline.run2),
4368
- afterRun: await judgeBenign(after, cases, judge),
4530
+ // A judged baseline says which cases already failed before the patch;
4531
+ // an older claim has only hashes, and keeps the old reading (all passed).
4532
+ baselineRuns: judgedBaselineRuns(baseline, !favourable) ?? baselineRunResults(baseline.run1, baseline.run2),
4533
+ afterRun: afterRun.map(
4534
+ (r) => r.split ? { name: r.name, passed: favourable } : r
4535
+ ),
4369
4536
  gate: contract.benignGate
4370
4537
  });
4538
+ const best = read(true);
4539
+ const worst = read(false);
4540
+ const mark = (f) => f.name + (f.criticalPath ? "*" : "");
4541
+ const solid = new Set(best.flips.map((f) => f.name));
4542
+ const decidedBySplit = worst.flips.filter((f) => !solid.has(f.name)).map(mark);
4543
+ if (best.blocked) {
4544
+ return {
4545
+ green: false,
4546
+ ran: true,
4547
+ detail: `blocked: ${best.flips.map(mark).join(", ")}` + (decidedBySplit.length ? `; split vote, not counted: ${decidedBySplit.join(", ")}` : "")
4548
+ };
4549
+ }
4550
+ if (worst.blocked) {
4551
+ return {
4552
+ green: false,
4553
+ ran: false,
4554
+ detail: `the judge's votes split on ${decidedBySplit.join(", ")}, and they decide the gate: read against the patch it blocks, in its favour it passes, so it cannot rule`
4555
+ };
4556
+ }
4371
4557
  return {
4372
- green: !report.blocked,
4558
+ green: true,
4373
4559
  ran: true,
4374
- detail: report.blocked ? `blocked: ${report.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases judged, ${report.flips.length} flip(s)`
4560
+ detail: passDetail(baseline, cases, worst, judged, afterRun)
4375
4561
  };
4376
4562
  }
4563
+ function passDetail(baseline, cases, report, judged, afterRun) {
4564
+ const entries = [...baseline.run1, ...baseline.run2];
4565
+ const assumed = new Set(
4566
+ entries.filter((b) => typeof b.passed !== "boolean").map((b) => b.name)
4567
+ ).size;
4568
+ const split = (/* @__PURE__ */ new Set([
4569
+ ...entries.filter((b) => b.split).map((b) => b.name),
4570
+ ...afterRun.filter((r) => r.split).map((r) => r.name)
4571
+ ])).size;
4572
+ const excluded = judged ? `, ${report.flakyCaseNames.length} not passing before the patch (excluded)` + (assumed ? `, ${assumed} without a verdict before the patch (assumed passing)` : "") : "";
4573
+ const splitNote = split ? `, ${split} split vote(s) read against the patch` : "";
4574
+ return `${cases.length} cases judged, ${report.flips.length} flip(s)${excluded}${splitNote}`;
4575
+ }
4377
4576
  async function replayFamily(contract, target, catalogue, evaluator) {
4378
4577
  const attacks = attacksForContract(contract, catalogue);
4379
4578
  const report = await new Scanner({
@@ -4424,7 +4623,12 @@ async function verifyLive(input2) {
4424
4623
  holdoutAttackIds: contract.holdoutAttackIds,
4425
4624
  holdoutClearedIds,
4426
4625
  notExecutedAttackIds,
4427
- benign: { ran: benign.ran, green: benign.green, detail: benign.detail },
4626
+ benign: {
4627
+ ran: benign.ran,
4628
+ green: benign.green,
4629
+ detail: benign.detail,
4630
+ ...benign.notPassing ? { notPassing: benign.notPassing } : {}
4631
+ },
4428
4632
  judgeDegraded,
4429
4633
  sessionIsolated: checkSessionIsolation(input2.target).isolated,
4430
4634
  passed
@@ -4853,7 +5057,15 @@ ${manualPrInstructions(branch, base)}`
4853
5057
  }
4854
5058
 
4855
5059
  // src/commands/fix.ts
5060
+ var resolvedEvaluators = /* @__PURE__ */ new WeakMap();
4856
5061
  function resolveEvaluator(opts) {
5062
+ const known = resolvedEvaluators.get(opts);
5063
+ if (known) return known;
5064
+ const resolved = pickEvaluator(opts);
5065
+ resolvedEvaluators.set(opts, resolved);
5066
+ return resolved;
5067
+ }
5068
+ function pickEvaluator(opts) {
4857
5069
  if (opts.evaluator)
4858
5070
  return { evaluator: opts.evaluator, judgeAvailable: true };
4859
5071
  const creds = loadCredentials();
@@ -5111,19 +5323,14 @@ Commit or stash them first. (Non-code changes are fine and are named in the PR b
5111
5323
  const scope = plan.planned.some(
5112
5324
  (p) => p.recipe.verification.benignScope === "model-behaviour"
5113
5325
  ) ? "model-behaviour" : "rendering";
5326
+ const { evaluator, judgeAvailable } = resolveEvaluator(opts);
5327
+ const judge = scope === "model-behaviour" && judgeAvailable ? evaluator : void 0;
5114
5328
  try {
5115
5329
  const target = buildTargetConfig(config);
5116
5330
  console.log(
5117
- `Capturing the benign baseline (${BENIGN_CORE_V1.length} cases \xD7 2 runs) before patching\u2026`
5331
+ `Capturing the benign baseline (${BENIGN_CORE_V1.length} cases \xD7 2 runs${judge ? ", judged" : ""}) before patching\u2026`
5118
5332
  );
5119
- const run1 = await captureBenign(target, BENIGN_CORE_V1);
5120
- const run2 = await captureBenign(target, BENIGN_CORE_V1);
5121
- benignBaseline = {
5122
- suiteId: BENIGN_SUITE_ID,
5123
- scope,
5124
- run1: run1.map((c2) => ({ name: c2.name, hash: c2.hash })),
5125
- run2: run2.map((c2) => ({ name: c2.name, hash: c2.hash }))
5126
- };
5333
+ benignBaseline = await captureBenignBaseline(target, scope, judge);
5127
5334
  } catch (e) {
5128
5335
  console.warn(
5129
5336
  `\u26A0\uFE0F Could not capture the benign baseline (${e instanceof Error ? e.message : e}). Claims will record no baseline, and verification will refuse to confirm them.`
@@ -5612,6 +5819,9 @@ async function verifyClaimsCommand(opts) {
5612
5819
  claim,
5613
5820
  verdicts,
5614
5821
  benignGreen: opts.benignGreen ?? benign.green,
5822
+ // A gate that could not run is inconclusive, never "breaks the product".
5823
+ benignRan: opts.benignGreen === void 0 ? benign.ran : void 0,
5824
+ benignDetail: benign.detail,
5615
5825
  judgeDegraded,
5616
5826
  // Running THIS command from a deploy job is itself the deploy signal.
5617
5827
  trigger: "verify-claims",
@@ -5620,7 +5830,12 @@ async function verifyClaimsCommand(opts) {
5620
5830
  const evidenced = recordVerification(claim, {
5621
5831
  verdicts,
5622
5832
  outcome,
5623
- benign: { ran: benign.ran, green: benign.green, detail: benign.detail },
5833
+ benign: {
5834
+ ran: benign.ran,
5835
+ green: benign.green,
5836
+ detail: benign.detail,
5837
+ ...benign.notPassing ? { notPassing: benign.notPassing } : {}
5838
+ },
5624
5839
  judgeDegraded,
5625
5840
  sessionIsolated: checkSessionIsolation(target).isolated,
5626
5841
  trigger: "verify-claims",
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  generatePdf,
10
10
  loadConfig,
11
11
  loadSystemPrompt
12
- } from "./chunk-WH32F52L.js";
12
+ } from "./chunk-4OIZTQGA.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.7.4",
3
+ "version": "0.7.6",
4
4
  "description": "AI chatbot security scanner — automated red teaming for LLMs",
5
5
  "type": "module",
6
6
  "publishConfig": {