shield-llm 0.7.3 → 0.7.5

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/README.md CHANGED
@@ -195,8 +195,8 @@ All five are flagged for human review. Nothing auto-merges.
195
195
  "root": ".",
196
196
  "language": "ts",
197
197
  "anchors": {
198
- "system_prompt": { "file": "src/prompt.ts", "export": "SYSTEM_PROMPT" },
199
- "output_render": { "file": "src/render.ts", "export": "renderReply" }
198
+ "system_prompt": { "file": "src/ai/system-prompt.ts", "export": "SYSTEM_PROMPT_EFFECTIVE" },
199
+ "output_render": { "file": "src/render/message.ts", "export": "renderMessage" }
200
200
  },
201
201
  "redeploy": {
202
202
  "command": "pnpm build && pnpm deploy:staging",
@@ -211,6 +211,20 @@ An anchor you have not declared is a soft skip: the recipe does not run, and the
211
211
  output names the exact config key to add. An anchor pointing at a file or export
212
212
  that does not exist is a hard error, because a stale config fakes coverage.
213
213
 
214
+ The two anchors need a precise shape, because the recipes edit them:
215
+
216
+ - **`system_prompt`** names the value your code actually sends to the model,
217
+ written as a composition line: `export const SYSTEM_PROMPT_EFFECTIVE = SYSTEM_PROMPT;`
218
+ (no type annotation, ending with `;`). Your prompt itself stays in its own
219
+ constant, in any form; the recipes never touch it. They add guardrail
220
+ constants above that line and rewrite it to
221
+ `[SYSTEM_PROMPT, SHIELD_GUARDRAIL_…].join("\n\n")`.
222
+ - **`output_render`** is a function declaration named exactly `renderMessage`
223
+ (`export function renderMessage(text) { … }`, not an arrow function), in a
224
+ file one level below `src/`. The output recipes rename it, wrap it, and import
225
+ their helper from `src/shield/`. Two output recipes cannot both wrap it in the
226
+ same run: the second one is skipped as a conflict.
227
+
214
228
  ### What "verified" actually means
215
229
 
216
230
  `fix --verify` redeploys your target with `codebase.redeploy`, then replays each
@@ -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.3";
4
+ var version = "0.7.5";
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-XMFALD5J.js";
71
+ } from "./chunk-7UJ4S6CE.js";
71
72
 
72
73
  // src/load-env.ts
73
74
  try {
@@ -4249,13 +4250,26 @@ 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) throw e;
4261
+ const waitS = Math.min(e.retryAfterSec ?? 5 * 2 ** attempt, MAX_RATE_LIMIT_WAIT_S);
4262
+ await new Promise((r) => setTimeout(r, waitS * 1e3));
4263
+ }
4264
+ }
4265
+ }
4252
4266
  async function captureBenign(target, cases, opts = {}) {
4253
4267
  const client = createTargetClient(target, void 0, { resolveEnv: true });
4254
4268
  const out = [];
4255
4269
  for (const c2 of cases) {
4256
4270
  let response = "";
4257
4271
  try {
4258
- response = await client.sendMessage(c2.prompt);
4272
+ response = await sendPatiently(client, c2.prompt);
4259
4273
  } catch (e) {
4260
4274
  response = `__SHIELD_CAPTURE_ERROR__:${e instanceof Error ? e.message : "unknown"}`;
4261
4275
  }
@@ -4273,7 +4287,10 @@ function isCaptureError(capture) {
4273
4287
  }
4274
4288
  function toRunResults(baseline, after) {
4275
4289
  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 }));
4290
+ return after.map((a) => ({
4291
+ name: a.name,
4292
+ passed: byName.get(a.name) === a.hash
4293
+ }));
4277
4294
  }
4278
4295
  function baselineRunResults(run1, run2) {
4279
4296
  const r1 = new Map(run1.map((b) => [b.name, b.hash]));
@@ -4283,17 +4300,19 @@ function baselineRunResults(run1, run2) {
4283
4300
  run2.map((c2) => ({ name: c2.name, passed: stable(c2) }))
4284
4301
  ];
4285
4302
  }
4286
- async function judgeBenign(captures, cases, evaluator) {
4303
+ async function judgeBenign(captures, cases, evaluator, opts = {}) {
4287
4304
  const byName = new Map(cases.map((c2) => [c2.name, c2]));
4288
4305
  const out = [];
4289
4306
  for (const cap of captures) {
4290
4307
  const c2 = byName.get(cap.name);
4291
- if (!c2 || cap.response === void 0) {
4292
- out.push({ name: cap.name, passed: true });
4308
+ if (!c2 || cap.response === void 0 || isCaptureError(cap)) {
4309
+ out.push({ name: cap.name, passed: true, unobserved: true });
4293
4310
  continue;
4294
4311
  }
4295
- if (isCaptureError(cap)) {
4296
- out.push({ name: cap.name, passed: true });
4312
+ const key = `${cap.name}:${cap.hash}`;
4313
+ const known = opts.memo?.get(key);
4314
+ if (known !== void 0) {
4315
+ out.push({ name: cap.name, passed: known });
4297
4316
  continue;
4298
4317
  }
4299
4318
  const verdict = await evaluator.evaluate({
@@ -4305,12 +4324,74 @@ async function judgeBenign(captures, cases, evaluator) {
4305
4324
  regexResult: { vulnerable: false },
4306
4325
  customTest: { name: c2.name, acceptanceCriteria: c2.acceptanceCriteria }
4307
4326
  });
4327
+ if (verdict.llmResult?.judgeError) {
4328
+ out.push({ name: cap.name, passed: true, unjudged: true });
4329
+ continue;
4330
+ }
4331
+ opts.memo?.set(key, !verdict.vulnerable);
4308
4332
  out.push({ name: cap.name, passed: !verdict.vulnerable });
4309
4333
  }
4310
4334
  return out;
4311
4335
  }
4312
4336
 
4313
4337
  // src/fix/live-verify.ts
4338
+ async function captureBenignBaseline(target, scope, judge) {
4339
+ const judged = scope === "model-behaviour" && judge !== void 0;
4340
+ const run1 = await captureBenign(target, BENIGN_CORE_V1, {
4341
+ keepResponses: judged
4342
+ });
4343
+ const run2 = await captureBenign(target, BENIGN_CORE_V1, {
4344
+ keepResponses: judged
4345
+ });
4346
+ const strip = (run, verdicts) => run.map((c2, i) => {
4347
+ const v = verdicts?.[i];
4348
+ const hasVerdict2 = v && !v.unobserved && !v.unjudged;
4349
+ return {
4350
+ name: c2.name,
4351
+ hash: c2.hash,
4352
+ ...hasVerdict2 ? { passed: v.passed } : {}
4353
+ };
4354
+ });
4355
+ const unjudged = {
4356
+ suiteId: BENIGN_SUITE_ID,
4357
+ scope,
4358
+ run1: strip(run1),
4359
+ run2: strip(run2)
4360
+ };
4361
+ if (!judged) return unjudged;
4362
+ const opts = { memo: /* @__PURE__ */ new Map() };
4363
+ let verdicts1;
4364
+ let verdicts2;
4365
+ try {
4366
+ verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, opts);
4367
+ verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, opts);
4368
+ } catch (e) {
4369
+ console.warn(
4370
+ `\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.`
4371
+ );
4372
+ return unjudged;
4373
+ }
4374
+ const all = [...verdicts1, ...verdicts2];
4375
+ const notCaptured = all.filter((v) => v.unobserved).length;
4376
+ const notRuled = all.filter((v) => v.unjudged).length;
4377
+ if (notCaptured || notRuled) {
4378
+ console.warn(
4379
+ `\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.`
4380
+ );
4381
+ }
4382
+ return {
4383
+ suiteId: BENIGN_SUITE_ID,
4384
+ scope,
4385
+ run1: strip(run1, verdicts1),
4386
+ run2: strip(run2, verdicts2)
4387
+ };
4388
+ }
4389
+ function judgedBaselineRuns(baseline) {
4390
+ const entries = [...baseline.run1, ...baseline.run2];
4391
+ if (!entries.some((b) => typeof b.passed === "boolean")) return void 0;
4392
+ const toRun = (run) => run.map((b) => ({ name: b.name, passed: b.passed !== false }));
4393
+ return [toRun(baseline.run1), toRun(baseline.run2)];
4394
+ }
4314
4395
  async function runBenignGate(input2) {
4315
4396
  const { baseline, contract, target } = input2;
4316
4397
  const scope = baseline?.scope ?? contract.benignScope;
@@ -4338,18 +4419,18 @@ async function runBenignGate(input2) {
4338
4419
  (c2) => baseline.run1.some((b) => b.name === c2.name)
4339
4420
  );
4340
4421
  if (scope === "rendering") {
4341
- const after2 = await captureBenign(target, cases);
4342
- const report2 = evaluateBenign({
4422
+ const after = await captureBenign(target, cases);
4423
+ const report = evaluateBenign({
4343
4424
  suiteId: baseline.suiteId,
4344
4425
  cases,
4345
4426
  baselineRuns: baselineRunResults(baseline.run1, baseline.run2),
4346
- afterRun: toRunResults(baseline.run1, after2),
4427
+ afterRun: toRunResults(baseline.run1, after),
4347
4428
  gate: contract.benignGate
4348
4429
  });
4349
4430
  return {
4350
- green: !report2.blocked,
4431
+ green: !report.blocked,
4351
4432
  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`
4433
+ 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
4434
  };
4354
4435
  }
4355
4436
  const judge = input2.evaluator;
@@ -4360,18 +4441,43 @@ async function runBenignGate(input2) {
4360
4441
  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
4442
  };
4362
4443
  }
4444
+ return judgePatchedAnswers(baseline, cases, contract, target, judge);
4445
+ }
4446
+ async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
4363
4447
  const after = await captureBenign(target, cases, { keepResponses: true });
4448
+ const afterRun = await judgeBenign(after, cases, judge);
4449
+ const notCaptured = afterRun.filter((r) => r.unobserved).length;
4450
+ if (notCaptured) {
4451
+ return {
4452
+ green: false,
4453
+ ran: false,
4454
+ detail: `${notCaptured} of ${cases.length} benign answers could not be captured from the target, so the gate could not run`
4455
+ };
4456
+ }
4457
+ const unjudged = afterRun.filter((r) => r.unjudged).length;
4458
+ if (unjudged) {
4459
+ return {
4460
+ green: false,
4461
+ ran: false,
4462
+ detail: `the judge could not rule on ${unjudged} of ${cases.length} benign answers (degraded), so the gate could not run`
4463
+ };
4464
+ }
4465
+ const judgedBefore = judgedBaselineRuns(baseline);
4364
4466
  const report = evaluateBenign({
4365
4467
  suiteId: baseline.suiteId,
4366
4468
  cases,
4367
- baselineRuns: baselineRunResults(baseline.run1, baseline.run2),
4368
- afterRun: await judgeBenign(after, cases, judge),
4469
+ baselineRuns: judgedBefore ?? baselineRunResults(baseline.run1, baseline.run2),
4470
+ afterRun,
4369
4471
  gate: contract.benignGate
4370
4472
  });
4473
+ const assumed = new Set(
4474
+ [...baseline.run1, ...baseline.run2].filter((b) => typeof b.passed !== "boolean").map((b) => b.name)
4475
+ ).size;
4476
+ const excluded = judgedBefore ? `, ${report.flakyCaseNames.length} not passing before the patch (excluded)` + (assumed ? `, ${assumed} without a verdict before the patch (assumed passing)` : "") : "";
4371
4477
  return {
4372
4478
  green: !report.blocked,
4373
4479
  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)`
4480
+ detail: report.blocked ? `blocked: ${report.flips.map((f) => f.name + (f.criticalPath ? "*" : "")).join(", ")}` : `${cases.length} cases judged, ${report.flips.length} flip(s)${excluded}`
4375
4481
  };
4376
4482
  }
4377
4483
  async function replayFamily(contract, target, catalogue, evaluator) {
@@ -4853,7 +4959,15 @@ ${manualPrInstructions(branch, base)}`
4853
4959
  }
4854
4960
 
4855
4961
  // src/commands/fix.ts
4962
+ var resolvedEvaluators = /* @__PURE__ */ new WeakMap();
4856
4963
  function resolveEvaluator(opts) {
4964
+ const known = resolvedEvaluators.get(opts);
4965
+ if (known) return known;
4966
+ const resolved = pickEvaluator(opts);
4967
+ resolvedEvaluators.set(opts, resolved);
4968
+ return resolved;
4969
+ }
4970
+ function pickEvaluator(opts) {
4857
4971
  if (opts.evaluator)
4858
4972
  return { evaluator: opts.evaluator, judgeAvailable: true };
4859
4973
  const creds = loadCredentials();
@@ -5111,19 +5225,14 @@ Commit or stash them first. (Non-code changes are fine and are named in the PR b
5111
5225
  const scope = plan.planned.some(
5112
5226
  (p) => p.recipe.verification.benignScope === "model-behaviour"
5113
5227
  ) ? "model-behaviour" : "rendering";
5228
+ const { evaluator, judgeAvailable } = resolveEvaluator(opts);
5229
+ const judge = scope === "model-behaviour" && judgeAvailable ? evaluator : void 0;
5114
5230
  try {
5115
5231
  const target = buildTargetConfig(config);
5116
5232
  console.log(
5117
- `Capturing the benign baseline (${BENIGN_CORE_V1.length} cases \xD7 2 runs) before patching\u2026`
5233
+ `Capturing the benign baseline (${BENIGN_CORE_V1.length} cases \xD7 2 runs${judge ? ", judged" : ""}) before patching\u2026`
5118
5234
  );
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
- };
5235
+ benignBaseline = await captureBenignBaseline(target, scope, judge);
5127
5236
  } catch (e) {
5128
5237
  console.warn(
5129
5238
  `\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.`
@@ -5600,13 +5709,21 @@ async function verifyClaimsCommand(opts) {
5600
5709
  baseline: claim.benignBaseline,
5601
5710
  contract: claim.contract,
5602
5711
  target,
5603
- evaluator: opts.evaluator,
5712
+ // The same judge the replay used, as `fix --verify` does. This passed
5713
+ // `opts.evaluator`, which only tests set: for a logged-in user the gate
5714
+ // always found "no judge", so a prompt-level claim could close only with
5715
+ // --assume-benign-green. A regex evaluator cannot judge benign answers,
5716
+ // hence `backed`.
5717
+ evaluator: backed ? evaluator : void 0,
5604
5718
  assumeGreen: opts.assumeBenignGreen
5605
5719
  });
5606
5720
  const outcome = resolveClaim({
5607
5721
  claim,
5608
5722
  verdicts,
5609
5723
  benignGreen: opts.benignGreen ?? benign.green,
5724
+ // A gate that could not run is inconclusive, never "breaks the product".
5725
+ benignRan: opts.benignGreen === void 0 ? benign.ran : void 0,
5726
+ benignDetail: benign.detail,
5610
5727
  judgeDegraded,
5611
5728
  // Running THIS command from a deploy job is itself the deploy signal.
5612
5729
  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-XMFALD5J.js";
12
+ } from "./chunk-7UJ4S6CE.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.3",
3
+ "version": "0.7.5",
4
4
  "description": "AI chatbot security scanner — automated red teaming for LLMs",
5
5
  "type": "module",
6
6
  "publishConfig": {