nulladrift 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { parseArgs } from "util";
5
- import { resolve as resolve5 } from "path";
5
+ import { resolve as resolve6 } from "path";
6
6
 
7
7
  // ../core/src/changes.ts
8
8
  var CHANGE_KINDS = [
@@ -312,6 +312,19 @@ function redactFormats(value) {
312
312
  for (const format of ISSUER_FORMATS) out = out.replace(format, REDACTED);
313
313
  return out;
314
314
  }
315
+ var CODE_HOSTS = /* @__PURE__ */ new Set([
316
+ "github.com",
317
+ "raw.githubusercontent.com",
318
+ "codeload.github.com",
319
+ "gist.github.com",
320
+ "gist.githubusercontent.com",
321
+ "api.github.com",
322
+ "gitlab.com",
323
+ "bitbucket.org",
324
+ "cdn.jsdelivr.net",
325
+ "esm.sh",
326
+ "deno.land"
327
+ ]);
315
328
  function redactUrl(value) {
316
329
  if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return value;
317
330
  let url;
@@ -331,7 +344,7 @@ function redactUrl(value) {
331
344
  changed = true;
332
345
  }
333
346
  }
334
- const path = redactPath(url.pathname);
347
+ const path = redactPath(url.pathname, { contentAddressed: CODE_HOSTS.has(url.hostname.toLowerCase()) });
335
348
  if (path !== url.pathname) {
336
349
  url.pathname = path;
337
350
  changed = true;
@@ -433,11 +446,12 @@ function redactArgs(args) {
433
446
  function looksLikeAnOperand(value) {
434
447
  return value.startsWith("@") || value.includes("/") || /\.(m?[jt]s|cjs|py|json|ya?ml|toml|sh|exe)$/i.test(value);
435
448
  }
436
- function redactPath(pathname) {
449
+ function redactPath(pathname, options = {}) {
437
450
  return pathname.split("/").map((segment) => {
438
451
  if (segment === "" || PLACEHOLDER.test(decoded(segment))) return segment;
439
452
  if (looksRandom(segment)) return REDACTED;
440
- if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || /^[0-9a-f]{32,}$/i.test(segment)) return REDACTED;
453
+ if (!options.contentAddressed && (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || /^[0-9a-f]{32,}$/i.test(segment)))
454
+ return REDACTED;
441
455
  return redactFormats(segment);
442
456
  }).join("/");
443
457
  }
@@ -450,6 +464,17 @@ function countRedacted(transport2) {
450
464
  var MAX_REF_DEPTH = 32;
451
465
  var MAX_VISIT_DEPTH = 12;
452
466
  var MAX_FACTS = 5e3;
467
+ var MAX_RESOLUTIONS = 1e5;
468
+ var states = /* @__PURE__ */ new WeakMap();
469
+ function stateOf(root) {
470
+ if (root === null || typeof root !== "object") return { refs: /* @__PURE__ */ new Map(), spent: 0 };
471
+ let state = states.get(root);
472
+ if (!state) {
473
+ state = { refs: /* @__PURE__ */ new Map(), spent: 0 };
474
+ states.set(root, state);
475
+ }
476
+ return state;
477
+ }
453
478
  function asObject(value) {
454
479
  return value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value) ? value : void 0;
455
480
  }
@@ -477,6 +502,9 @@ function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth
477
502
  const object = asObject(node);
478
503
  if (object === void 0) return void 0;
479
504
  if (depth > MAX_REF_DEPTH) return object;
505
+ const state = stateOf(root);
506
+ if (depth === 0) state.spent = 0;
507
+ if (++state.spent > MAX_RESOLUTIONS) return object;
480
508
  const out = /* @__PURE__ */ Object.create(null);
481
509
  const merge = (source) => {
482
510
  for (const [key, value] of Object.entries(source)) {
@@ -498,7 +526,12 @@ function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth
498
526
  merge(object);
499
527
  const ref = object["$ref"];
500
528
  if (typeof ref === "string" && !seenRefs.has(ref)) {
501
- const resolved = effectiveSchema(resolvePointer(root, ref), root, /* @__PURE__ */ new Set([...seenRefs, ref]), depth + 1);
529
+ let resolved;
530
+ if (state.refs.has(ref)) resolved = state.refs.get(ref);
531
+ else {
532
+ resolved = effectiveSchema(resolvePointer(root, ref), root, /* @__PURE__ */ new Set([...seenRefs, ref]), depth + 1);
533
+ state.refs.set(ref, resolved);
534
+ }
502
535
  if (resolved) merge(resolved);
503
536
  }
504
537
  const allOf = object["allOf"];
@@ -536,16 +569,29 @@ function resolveBehavior(annotations2) {
536
569
  function isEscalation(previous, next) {
537
570
  return previous.readOnly && !next.readOnly || !previous.destructive && next.destructive || previous.idempotent && !next.idempotent || !previous.openWorld && next.openWorld;
538
571
  }
572
+ var DATA_KEYWORDS = /* @__PURE__ */ new Set(["const", "default", "enum", "examples", "example"]);
573
+ var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
539
574
  function normalizeSchema(value) {
540
- if (Array.isArray(value)) return value.map(normalizeSchema);
575
+ return normalizeNode(value, false);
576
+ }
577
+ function normalizeNode(value, namesOnly) {
578
+ if (Array.isArray(value)) return value.map((member) => normalizeNode(member, false));
541
579
  if (value === null || typeof value !== "object") return value;
542
580
  const out = /* @__PURE__ */ Object.create(null);
543
581
  for (const [key, member] of Object.entries(value)) {
582
+ if (namesOnly) {
583
+ out[key] = normalizeNode(member, false);
584
+ continue;
585
+ }
544
586
  if (key === "required" && Array.isArray(member) && member.every((entry) => typeof entry === "string")) {
545
587
  out[key] = [...member].sort();
546
588
  continue;
547
589
  }
548
- out[key] = normalizeSchema(member);
590
+ if (DATA_KEYWORDS.has(key)) {
591
+ out[key] = member;
592
+ continue;
593
+ }
594
+ out[key] = normalizeNode(member, NAMED_SCHEMAS.has(key));
549
595
  }
550
596
  return out;
551
597
  }
@@ -849,8 +895,15 @@ function change(kind, server2, summary, extra) {
849
895
  function same(a, b) {
850
896
  return stableKey(a ?? null) === stableKey(b ?? null);
851
897
  }
852
- function indexBy(members, key) {
853
- return new Map((members ?? []).map((member) => [key(member), member]));
898
+ function groupBy(members, key) {
899
+ const groups = /* @__PURE__ */ new Map();
900
+ for (const member of members ?? []) {
901
+ const k = key(member);
902
+ const group = groups.get(k);
903
+ if (group) group.push(member);
904
+ else groups.set(k, [member]);
905
+ }
906
+ return groups;
854
907
  }
855
908
  function declaredNames(capabilities) {
856
909
  const names = [];
@@ -884,12 +937,12 @@ var CAPABILITY_SEVERITY = {
884
937
  low: "low"
885
938
  };
886
939
  function compareToolCapabilities(server2, before, after) {
887
- const previous = indexBy(before, (tool2) => tool2.name);
940
+ const previous = groupBy(before, (tool2) => tool2.name);
888
941
  const changes = [];
889
942
  for (const tool2 of after ?? []) {
890
943
  const existing = previous.get(tool2.name);
891
944
  if (!existing) continue;
892
- const had = new Set(toolCapabilities(existing).map((capability) => capability.kind));
945
+ const had = new Set(existing.flatMap((copy) => toolCapabilities(copy).map((capability) => capability.kind)));
893
946
  for (const capability of toolCapabilities(tool2)) {
894
947
  if (had.has(capability.kind)) continue;
895
948
  changes.push(
@@ -941,10 +994,20 @@ function compareTool(name, before, after) {
941
994
  );
942
995
  }
943
996
  if (changes.length === 0) {
944
- changes.push(change("tool.changed", name, "tool definition changed (title, icons or _meta)", { ...at, before, after }));
997
+ const moved = [
998
+ !same(before.title, after.title) ? "title" : "",
999
+ !same(before.icons, after.icons) ? "icons" : "",
1000
+ !same(before.execution, after.execution) ? `how it may be run (${describeExecution(before.execution)} \u2192 ${describeExecution(after.execution)})` : "",
1001
+ !same(before.meta, after.meta) ? "_meta" : ""
1002
+ ].filter(Boolean);
1003
+ changes.push(change("tool.changed", name, `tool definition changed: ${moved.length > 0 ? moved.join(", ") : "a field this report has no finding for"}`, { ...at, before, after }));
945
1004
  }
946
1005
  return changes;
947
1006
  }
1007
+ function describeExecution(execution) {
1008
+ const support = execution?.["taskSupport"];
1009
+ return typeof support === "string" ? `task support ${support}` : "unstated";
1010
+ }
948
1011
  function describeEscalation(before, after) {
949
1012
  const gained = [];
950
1013
  if (before.behavior.readOnly && !after.behavior.readOnly) gained.push("may now modify");
@@ -955,25 +1018,61 @@ function describeEscalation(before, after) {
955
1018
  }
956
1019
  function compareMembers(name, before, after, spec, deep) {
957
1020
  const changes = [];
958
- const previous = indexBy(before, spec.key);
959
- const next = indexBy(after, spec.key);
960
- for (const [key, member] of next) {
1021
+ const previous = groupBy(before, spec.key);
1022
+ const next = groupBy(after, spec.key);
1023
+ for (const [key, members] of next) {
961
1024
  const existing = previous.get(key);
962
1025
  if (!existing) {
963
- const extra = spec.arriving?.(member);
1026
+ for (const member of members) {
1027
+ const extra = spec.arriving?.(member);
1028
+ changes.push(
1029
+ change(spec.added, name, `new ${spec.noun} ${spec.label(member)}${extra ? ` \xB7 ${extra}` : ""}`, { member: spec.label(member), after: member })
1030
+ );
1031
+ }
1032
+ continue;
1033
+ }
1034
+ const unpairedBefore = [...existing];
1035
+ const unpairedAfter = [];
1036
+ for (const member of members) {
1037
+ const twin = unpairedBefore.findIndex((candidate) => candidate.digest === member.digest);
1038
+ if (twin === -1) unpairedAfter.push(member);
1039
+ else unpairedBefore.splice(twin, 1);
1040
+ }
1041
+ for (const [index, member] of unpairedAfter.entries()) {
1042
+ const counterpart = unpairedBefore[index] ?? existing[0];
1043
+ if (counterpart.digest === member.digest) {
1044
+ changes.push(
1045
+ change(spec.changed, name, `${spec.noun} ${spec.label(member)} is now declared ${members.length} times`, { member: spec.label(member), before: existing, after: members })
1046
+ );
1047
+ continue;
1048
+ }
964
1049
  changes.push(
965
- change(spec.added, name, `new ${spec.noun} ${spec.label(member)}${extra ? ` \xB7 ${extra}` : ""}`, { member: spec.label(member), after: member })
1050
+ ...deep ? deep(key, counterpart, member) : [change(spec.changed, name, `${spec.noun} ${spec.label(member)} changed`, { member: spec.label(member), before: counterpart, after: member })]
966
1051
  );
967
- continue;
968
1052
  }
969
- if (existing.digest === member.digest) continue;
970
- changes.push(...deep ? deep(key, existing, member) : [change(spec.changed, name, `${spec.noun} ${spec.label(member)} changed`, { member: spec.label(member), before: existing, after: member })]);
1053
+ for (const member of unpairedBefore.slice(unpairedAfter.length)) {
1054
+ changes.push(change(spec.removed, name, `one of the ${spec.noun}s declared as ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
1055
+ }
971
1056
  }
972
- for (const [key, member] of previous) {
973
- if (!next.has(key)) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
1057
+ for (const [key, members] of previous) {
1058
+ if (next.has(key)) continue;
1059
+ for (const member of members) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
974
1060
  }
975
1061
  return changes;
976
1062
  }
1063
+ function filesMoved(was, now) {
1064
+ if (was === void 0 || now === void 0) return void 0;
1065
+ const added = Object.keys(now).filter((file) => !Object.hasOwn(was, file));
1066
+ const removed = Object.keys(was).filter((file) => !Object.hasOwn(now, file));
1067
+ const changed = Object.keys(now).filter((file) => Object.hasOwn(was, file) && was[file] !== now[file]);
1068
+ if (added.length + removed.length + changed.length === 0) return void 0;
1069
+ const list = (files) => `${files.slice(0, 3).join(", ")}${files.length > 3 ? ` +${files.length - 3}` : ""}`;
1070
+ return [
1071
+ added.length > 0 ? `added ${list(added)}` : "",
1072
+ removed.length > 0 ? `removed ${list(removed)}` : "",
1073
+ changed.length > 0 ? `different contents for ${list(changed)}` : ""
1074
+ ].filter(Boolean).join("; ");
1075
+ }
977
1076
  function compareProvenance(name, before, after) {
978
1077
  const was = before.provenance;
979
1078
  const now = after.provenance;
@@ -983,7 +1082,16 @@ function compareProvenance(name, before, after) {
983
1082
  const unexplained = surfaceHeld ? ", and the declared surface did not change: nothing else in this report describes what the new code does" : "";
984
1083
  const integrityMoved = was.integrity !== void 0 && now.integrity !== void 0 && was.integrity !== now.integrity;
985
1084
  if (was.version !== void 0 && was.version === now.version) {
986
- if (!integrityMoved) return [];
1085
+ if (!integrityMoved) {
1086
+ const files = filesMoved(was.files, now.files);
1087
+ if (files) {
1088
+ return [change("server.artifact.changed", name, `the files published for ${was.name}@${was.version} are not the ones that were pinned (${files})${unexplained}`, { before: was, after: now })];
1089
+ }
1090
+ if (was.integrity !== void 0 && now.integrity === void 0) {
1091
+ return [change("server.artifact.changed", name, `the file pinned for ${was.name}@${was.version} is no longer published, so something else is installed in its place${unexplained}`, { before: was, after: now })];
1092
+ }
1093
+ return [];
1094
+ }
987
1095
  if (was.ecosystem === "npm") {
988
1096
  return [
989
1097
  change(
@@ -1004,6 +1112,17 @@ function compareProvenance(name, before, after) {
1004
1112
  const what = was.ecosystem === "oci" ? `the image ${was.name}:${was.requested ?? "latest"} now resolves to a different digest` : "the file this server runs from has different contents than when it was pinned";
1005
1113
  return [change("server.artifact.changed", name, `${what}${unexplained}`, { before: was, after: now })];
1006
1114
  }
1115
+ function orderless(entry) {
1116
+ const { kind: _kind, source: _source, digest: _digest, provenance: _provenance, coverage: _coverage, tools, resources, resourceTemplates, prompts, ...rest } = entry;
1117
+ const digests = (members) => (members ?? []).map((member) => member.digest).sort();
1118
+ return stableKey({
1119
+ ...rest,
1120
+ tools: digests(tools),
1121
+ resources: digests(resources),
1122
+ resourceTemplates: digests(resourceTemplates),
1123
+ prompts: digests(prompts)
1124
+ });
1125
+ }
1007
1126
  function compareServer(name, before, after) {
1008
1127
  const provenance2 = compareProvenance(name, before, after);
1009
1128
  if (before.digest === after.digest) return provenance2;
@@ -1086,6 +1205,14 @@ function compareServer(name, before, after) {
1086
1205
  noun: "prompt"
1087
1206
  })
1088
1207
  );
1208
+ if (changes.length === 0 && orderless(before) !== orderless(after)) {
1209
+ changes.push(
1210
+ change("server.capabilities.changed", name, "the server's pinned definition changed in a way no other finding describes; compare the lock entries", {
1211
+ before: before.digest,
1212
+ after: after.digest
1213
+ })
1214
+ );
1215
+ }
1089
1216
  return changes;
1090
1217
  }
1091
1218
  function detectRenames(before, after, removed, added) {
@@ -1134,6 +1261,9 @@ function diffLockfiles(before, after) {
1134
1261
  }
1135
1262
 
1136
1263
  // ../core/src/risk/steering.ts
1264
+ var INVISIBLE_CHARACTERS = "\\u00AD\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u2066-\\u2069\\uFE00-\\uFE0D\\uFEFF\\u{E0000}-\\u{E007F}\\u{E0100}-\\u{E01EF}";
1265
+ var INVISIBLE_RUN = new RegExp(`[${INVISIBLE_CHARACTERS}]+`, "gu");
1266
+ var ONLY_INVISIBLE = new RegExp(`^[${INVISIBLE_CHARACTERS}]+$`, "u");
1137
1267
  var PATTERNS = [
1138
1268
  // Imperatives aimed at the reader of the prompt, not at a person reading documentation.
1139
1269
  { kind: "model-directive", pattern: /\b(ignore|disregard|override)\s+(all\s+)?(previous|prior|earlier|above)\b[^.]{0,80}/gi },
@@ -1152,7 +1282,7 @@ var PATTERNS = [
1152
1282
  // Paths that only appear in a description when something wants their contents.
1153
1283
  { kind: "credential-path", pattern: /(~|\$HOME|\/home\/[\w.-]+|\/Users\/[\w.-]+)?[/\\]?\.(aws\/credentials|ssh\/id_[\w]+|npmrc|netrc|git-credentials|kube\/config|env)\b/gi },
1154
1284
  { kind: "credential-path", pattern: /\b(id_rsa|id_ed25519|authorized_keys|\.pem|service-account\.json)\b/gi },
1155
- { kind: "exfiltration", pattern: /\b(send|post|upload|transmit|forward|exfiltrate)\s+[^.]{0,40}\bto\s+(https?:\/\/|[\w.-]+\.[a-z]{2,})/gi },
1285
+ { kind: "exfiltration", pattern: /\b(send|post|upload|transmit|forward|exfiltrate)\s+[^.]{0,40}\bto\s+(https?:\/\/|[\w.-]{1,253}\.[a-z]{2,24})/gi },
1156
1286
  { kind: "exfiltration", pattern: /\b(include|append|attach)\s+(its|the|their)\s+contents?\b[^.]{0,60}/gi },
1157
1287
  /*
1158
1288
  * The MCP-native form of a credential path. A server's own resource URIs are the secrets it
@@ -1160,16 +1290,16 @@ var PATTERNS = [
1160
1290
  * `~/.aws/credentials`. Only when something is being told to go and read it: a description that
1161
1291
  * merely names its own resource is documentation.
1162
1292
  */
1163
- { kind: "credential-path", pattern: /\b(read|fetch|load|access|retrieve|call)\b[^.]{0,40}?\b[a-z][\w+.-]*:\/\/[\w./-]*(secret|token|credential|key|auth|passwd|password|config)[\w./-]*/gi },
1293
+ { kind: "credential-path", pattern: /\b(read|fetch|load|access|retrieve|call)\b[^.]{0,40}?\b[a-z][\w+.-]{0,31}:\/\/[\w./-]{0,200}?(secret|token|credential|key|auth|passwd|password|config)[\w./-]{0,200}/gi },
1164
1294
  // Characters that make text render as something other than what it is.
1165
- { kind: "hidden-text", pattern: /[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]+/g },
1295
+ { kind: "hidden-text", pattern: INVISIBLE_RUN },
1166
1296
  /*
1167
1297
  * Markup inside a tool description, which is the convention every published tool-poisoning
1168
1298
  * sample follows: a pseudo-tag or an HTML comment is invisible wherever the description is
1169
1299
  * rendered and plain text to the model that is given it. A description is documentation for a
1170
1300
  * person; a section of it addressed to a reader who is not that person is the whole technique.
1171
1301
  */
1172
- { kind: "hidden-text", pattern: /<\/?\s*(important|system[\w\s-]*|instructions?|secret|hidden|directive)\s*>/gi },
1302
+ { kind: "hidden-text", pattern: /<\/?[ \t]{0,8}(important|system(?:[\w-]{0,24}(?:[ \t]{1,8}[\w-]{1,24}){0,3})?|instructions?|secret|hidden|directive)[ \t]{0,8}>/gi },
1173
1303
  { kind: "hidden-text", pattern: /<!--[\s\S]{0,200}?-->/g }
1174
1304
  ];
1175
1305
  var CONFUSABLES2 = {
@@ -1200,7 +1330,7 @@ function steeringSignals(text, field) {
1200
1330
  const at = match.index ?? 0;
1201
1331
  const raw = text.slice(at, at + match[0].length).trim();
1202
1332
  if (raw.length === 0) continue;
1203
- const quote = /^[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]+$/.test(raw) ? `${raw.length} invisible character(s)` : raw.length > 120 ? `${raw.slice(0, 119)}\u2026` : raw;
1333
+ const quote = ONLY_INVISIBLE.test(raw) ? `${[...raw].length} invisible character(s)` : raw.length > 120 ? `${[...raw].slice(0, 119).join("")}\u2026` : raw;
1204
1334
  const key = `${kind}\0${quote}`;
1205
1335
  if (seen.has(key)) continue;
1206
1336
  seen.add(key);
@@ -1312,18 +1442,22 @@ var red = wrap(31);
1312
1442
  var green = wrap(32);
1313
1443
  var yellow = wrap(33);
1314
1444
  var blue = wrap(34);
1315
- function visibleControls(text) {
1316
- return text.replace(
1317
- // C0 and C1 controls and DEL, plus the bidirectional overrides and zero-width characters
1318
- // that change what a line appears to say without changing what it is.
1319
- // eslint-disable-next-line no-control-regex
1320
- /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g,
1321
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
1322
- );
1445
+ function visibleControls(text, options = {}) {
1446
+ return text.replace(options.multiline ? CONTROLS_EXCEPT_LINES : CONTROLS, (character) => {
1447
+ const code2 = character.codePointAt(0) ?? 0;
1448
+ return code2 > 65535 ? `\\u{${code2.toString(16)}}` : `\\u${code2.toString(16).padStart(4, "0")}`;
1449
+ });
1450
+ }
1451
+ var CONTROLS = new RegExp(`[\\u0000-\\u001F\\u007F-\\u009F${INVISIBLE_CHARACTERS}]`, "gu");
1452
+ var CONTROLS_EXCEPT_LINES = new RegExp(`[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F${INVISIBLE_CHARACTERS}]`, "gu");
1453
+ function visibleLines(text, indent) {
1454
+ return text.split(/\r?\n/).map((line) => visibleControls(line)).join(`
1455
+ ${indent}`);
1323
1456
  }
1324
1457
  function truncate(text, limit = 160) {
1325
- const collapsed = visibleControls(text).replace(/\s+/g, " ").trim();
1326
- return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}\u2026`;
1458
+ const collapsed = visibleControls(text, { multiline: true }).replace(/\s+/g, " ").trim();
1459
+ const points = [...collapsed];
1460
+ return points.length <= limit ? collapsed : `${points.slice(0, limit - 1).join("")}\u2026`;
1327
1461
  }
1328
1462
  function elideMiddle(raw, limit) {
1329
1463
  const path = visibleControls(raw);
@@ -1667,6 +1801,7 @@ async function discoverServers(projectRoot, extraFiles = [], options = {}) {
1667
1801
  const skipped = [];
1668
1802
  const filesRead = [];
1669
1803
  const shadowed = [];
1804
+ const conflicting = /* @__PURE__ */ new Map();
1670
1805
  const problems = [];
1671
1806
  const requested = new Set(files.filter((file) => file.client === "generic").map((file) => file.path));
1672
1807
  for (const file of files) {
@@ -1695,9 +1830,19 @@ async function discoverServers(projectRoot, extraFiles = [], options = {}) {
1695
1830
  const parsed = file.client === "claude-code" && file.scope === "user" ? await parseClaudeJson(raw, projectRoot, source, context) : await parseServerMap(raw, mapKey, { ...source, scope: file.scope }, context);
1696
1831
  skipped.push(...parsed.skipped);
1697
1832
  for (const server2 of parsed.servers.map((entry) => anchorCwd(entry, projectRoot))) {
1833
+ const contested = conflicting.get(server2.name);
1834
+ if (contested) {
1835
+ contested.push({ file: source.file, server: server2 });
1836
+ continue;
1837
+ }
1698
1838
  const existing = byName2.get(server2.name);
1699
1839
  if (existing) {
1700
- shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
1840
+ if (sameDefinition(existing.server, server2)) {
1841
+ shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
1842
+ continue;
1843
+ }
1844
+ byName2.delete(server2.name);
1845
+ conflicting.set(server2.name, [{ file: existing.from, server: existing.server }, { file: source.file, server: server2 }]);
1701
1846
  continue;
1702
1847
  }
1703
1848
  byName2.set(server2.name, { server: server2, from: source.file });
@@ -1712,9 +1857,20 @@ async function discoverServers(projectRoot, extraFiles = [], options = {}) {
1712
1857
  (path) => path !== void 0
1713
1858
  ),
1714
1859
  shadowed,
1860
+ conflicts: [...conflicting].map(([name, definitions]) => ({ name, definitions })).sort((a, b) => a.name.localeCompare(b.name)),
1715
1861
  problems
1716
1862
  };
1717
1863
  }
1864
+ function sameDefinition(a, b) {
1865
+ const essence = ({ transport: transport2 }) => transport2.type === "stdio" ? { type: "stdio", command: transport2.command, args: transport2.args, env: sorted(transport2.env), cwd: transport2.cwd ?? null } : { type: transport2.type, url: transport2.url, headers: sorted(lowercased(transport2.headers)), oauth: transport2.oauth ? sorted({ ...transport2.oauth }) : null };
1866
+ return JSON.stringify(essence(a)) === JSON.stringify(essence(b));
1867
+ }
1868
+ function sorted(record) {
1869
+ return Object.entries(record).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1870
+ }
1871
+ function lowercased(headers) {
1872
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));
1873
+ }
1718
1874
 
1719
1875
  // src/lock/build.ts
1720
1876
  function byName(members) {
@@ -1766,6 +1922,7 @@ function lockTool(tool2, ignoredMeta) {
1766
1922
  behavior: resolveBehavior(annotations2),
1767
1923
  headerParams: headerParams.length > 0 ? headerParams : void 0,
1768
1924
  icons: lockIcons(tool2.icons),
1925
+ execution: tool2.execution ? toJson(tool2.execution) : void 0,
1769
1926
  meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
1770
1927
  });
1771
1928
  }
@@ -1839,7 +1996,7 @@ function buildLockedServer(server2, surface, policy) {
1839
1996
  resourceTemplates: resourceTemplates.map((template) => template.digest),
1840
1997
  prompts: prompts.map((prompt2) => prompt2.digest)
1841
1998
  };
1842
- return { kind: "mcp-server", ...entry, digest: digest(toJson(covered)) };
1999
+ return { kind: "mcp-server", ...entry, ...surface.coverage ? { coverage: surface.coverage } : {}, digest: digest(toJson(covered)) };
1843
2000
  }
1844
2001
 
1845
2002
  // src/lock/provenance.ts
@@ -1848,7 +2005,7 @@ import { readFile as readFile3 } from "fs/promises";
1848
2005
  import { isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
1849
2006
 
1850
2007
  // src/lib/version.ts
1851
- var VERSION = "0.7.1";
2008
+ var VERSION = "0.9.0";
1852
2009
  var USER_AGENT = `nulladrift/${VERSION} (+https://github.com/Nulladrift/nulladrift)`;
1853
2010
 
1854
2011
  // src/lock/provenance.ts
@@ -2040,7 +2197,7 @@ function firstPositional(args, valueFlags, explicitFlags, shortValues) {
2040
2197
  let explicit;
2041
2198
  for (let index = 0; index < args.length; index += 1) {
2042
2199
  const arg = args[index];
2043
- if (arg === "--") return { positional: args[index + 1], explicit };
2200
+ if (arg === "--") return { positional: args[index + 1], explicit, index: index + 1 };
2044
2201
  const equals = arg.indexOf("=");
2045
2202
  if (arg.startsWith("--") && equals > 0) {
2046
2203
  if (explicitFlags.includes(arg.slice(0, equals))) explicit = arg.slice(equals + 1);
@@ -2056,7 +2213,7 @@ function firstPositional(args, valueFlags, explicitFlags, shortValues) {
2056
2213
  else if (shortValues && !arg.startsWith("--") && arg.length > 2 && shortValues.has(arg.at(-1))) index += 1;
2057
2214
  continue;
2058
2215
  }
2059
- return { positional: arg, explicit };
2216
+ return { positional: arg, explicit, index };
2060
2217
  }
2061
2218
  return { explicit };
2062
2219
  }
@@ -2166,14 +2323,30 @@ async function resolvePypi(reference, options) {
2166
2323
  const files = (body.urls ?? []).filter((file) => typeof file.filename === "string");
2167
2324
  const chosen = files.find((file) => file.packagetype === "sdist") ?? files.filter((file) => /-none-any\.whl$/.test(file.filename)).sort((a, b) => a.filename.localeCompare(b.filename))[0];
2168
2325
  const sha = chosen?.digests?.sha256;
2326
+ const published = Object.fromEntries(
2327
+ files.filter((file) => typeof file.digests?.sha256 === "string" && /^[a-f0-9]{64}$/.test(file.digests.sha256)).map((file) => [file.filename, `sha256:${file.digests.sha256}`]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
2328
+ );
2169
2329
  return {
2170
2330
  ecosystem: "pypi",
2171
2331
  name: reference.name,
2172
2332
  version: body.info.version,
2173
2333
  ...typeof sha === "string" && /^[a-f0-9]{64}$/.test(sha) ? { integrity: `sha256:${sha}` } : {},
2174
- ...requestedOf(reference)
2334
+ ...requestedOf(reference),
2335
+ ...Object.keys(published).length > 0 ? { files: published } : {}
2175
2336
  };
2176
2337
  }
2338
+ function launchPinned(transport2, provenance2) {
2339
+ if (provenance2?.ecosystem !== "oci" || provenance2.integrity === void 0 || !/^sha256:[a-f0-9]{64}$/.test(provenance2.integrity)) return void 0;
2340
+ const name = commandName(transport2.command);
2341
+ if (name !== "docker" && name !== "podman" || transport2.args[0] !== "run") return void 0;
2342
+ const { positional, index } = firstPositional(transport2.args.slice(1), DOCKER_VALUE_FLAGS, [], DOCKER_VALUE_SHORT);
2343
+ if (positional === void 0 || index === void 0) return void 0;
2344
+ const image = splitImage(positional);
2345
+ if (!image || image.digest) return void 0;
2346
+ const args = [...transport2.args];
2347
+ args[index + 1] = `${positional}@${provenance2.integrity}`;
2348
+ return { ...transport2, args };
2349
+ }
2177
2350
  function imageLocation(name) {
2178
2351
  const parts = name.split("/");
2179
2352
  const first = parts[0];
@@ -2272,8 +2445,8 @@ function canonicalRegistry(url) {
2272
2445
  }
2273
2446
  function readSmall(path) {
2274
2447
  try {
2275
- const stat = statSync(path);
2276
- if (!stat.isFile() || stat.size > 1e6) return void 0;
2448
+ const stat2 = statSync(path);
2449
+ if (!stat2.isFile() || stat2.size > 1e6) return void 0;
2277
2450
  return readFileSync(path, "utf8");
2278
2451
  } catch {
2279
2452
  return void 0;
@@ -2446,9 +2619,9 @@ import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotoc
2446
2619
 
2447
2620
  // src/mcp/oauth.ts
2448
2621
  import { spawn } from "child_process";
2449
- import { createHash as createHash3, randomUUID } from "crypto";
2622
+ import { createHash as createHash3, randomBytes, randomUUID } from "crypto";
2450
2623
  import { readFileSync as readFileSync2 } from "fs";
2451
- import { mkdir, readFile as readFile4, rm, writeFile } from "fs/promises";
2624
+ import { chmod, lstat, mkdir, readFile as readFile4, rename, rm, writeFile } from "fs/promises";
2452
2625
  import { homedir as homedir4, platform as platform2 } from "os";
2453
2626
  import { dirname as dirname2, join as join3 } from "path";
2454
2627
  import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
@@ -2468,6 +2641,23 @@ var InteractiveAuthRequiredError = class extends Error {
2468
2641
  }
2469
2642
  serverName;
2470
2643
  };
2644
+ async function writeOwnerOnly(path, contents) {
2645
+ const directory = dirname2(path);
2646
+ await mkdir(directory, { recursive: true, mode: 448 });
2647
+ const found = await lstat(directory);
2648
+ if (found.isSymbolicLink() || !found.isDirectory()) throw new Error(`refusing to store credentials in ${directory}: it is not a plain directory`);
2649
+ await chmod(directory, 448);
2650
+ const temporary = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
2651
+ try {
2652
+ await writeFile(temporary, contents, { encoding: "utf8", mode: 384, flag: "wx" });
2653
+ await chmod(temporary, 384);
2654
+ await rename(temporary, path);
2655
+ } catch (error) {
2656
+ await rm(temporary, { force: true }).catch(() => {
2657
+ });
2658
+ throw error;
2659
+ }
2660
+ }
2471
2661
  var FileTokenProvider = class {
2472
2662
  constructor(serverName, serverUrl, options = { interactive: false }) {
2473
2663
  this.serverName = serverName;
@@ -2510,10 +2700,8 @@ var FileTokenProvider = class {
2510
2700
  async write(patch) {
2511
2701
  const next = { ...await this.read(), ...patch, serverUrl: this.serverUrl };
2512
2702
  this.cache = next;
2513
- const path = credentialPath(this.serverUrl);
2514
- await mkdir(dirname2(path), { recursive: true, mode: 448 });
2515
- await writeFile(path, `${JSON.stringify(next, null, 2)}
2516
- `, { encoding: "utf8", mode: 384 });
2703
+ await writeOwnerOnly(credentialPath(this.serverUrl), `${JSON.stringify(next, null, 2)}
2704
+ `);
2517
2705
  }
2518
2706
  async clientInformation() {
2519
2707
  return (await this.read()).clientInformation;
@@ -2654,13 +2842,140 @@ function isAuthFailure(error) {
2654
2842
  }
2655
2843
  const outer = `${error instanceof Error ? error.message : String(error)}`;
2656
2844
  const inner = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message : "";
2657
- const text = `${outer} ${inner}`.toLowerCase();
2658
- return /\b(401|403)\b|unauthorized|forbidden|invalid or missing.*token|authentication required|invalid_client|dynamic client registration/.test(text);
2845
+ const text = `${outer.slice(0, 4096)} ${inner.slice(0, 4096)}`.toLowerCase();
2846
+ return /\b(401|403)\b|unauthorized|forbidden|invalid or missing[^\n]{0,80}?token|authentication required|invalid_client|dynamic client registration/.test(text);
2659
2847
  }
2660
2848
 
2661
2849
  // src/mcp/connect.ts
2662
2850
  var DEFAULT_TIMEOUT_MS2 = 3e4;
2663
2851
  var STDERR_KEEP_BYTES = 2e3;
2852
+ var MAX_SURFACE_BYTES = 32 * 1024 * 1024;
2853
+ var SurfaceGuard = class {
2854
+ constructor(stop) {
2855
+ this.stop = stop;
2856
+ }
2857
+ stop;
2858
+ messageBytes = 0;
2859
+ wireBytes = 0;
2860
+ refusal;
2861
+ refuse(reason) {
2862
+ if (this.refusal !== void 0) return;
2863
+ this.refusal = reason;
2864
+ this.stop();
2865
+ }
2866
+ /** Bytes as they arrive over HTTP, before anything is parsed. */
2867
+ received(bytes) {
2868
+ this.wireBytes += bytes;
2869
+ if (this.wireBytes <= MAX_SURFACE_BYTES) return true;
2870
+ this.refuse(tooLarge());
2871
+ return false;
2872
+ }
2873
+ /** A parsed message, before the client library sees it. False when it must not be passed on. */
2874
+ admit(message) {
2875
+ if (this.refusal !== void 0) return false;
2876
+ const { bytes, prototypeKey } = inspectMessage(message);
2877
+ if (prototypeKey) {
2878
+ this.refuse("the server's reply contains a key named `__proto__`, which the MCP client library drops before it can be read; a surface that cannot be read as it was sent cannot be pinned");
2879
+ return false;
2880
+ }
2881
+ this.messageBytes += bytes;
2882
+ if (this.messageBytes > MAX_SURFACE_BYTES) {
2883
+ this.refuse(tooLarge());
2884
+ return false;
2885
+ }
2886
+ return true;
2887
+ }
2888
+ };
2889
+ function tooLarge() {
2890
+ return `the server sent more than ${MAX_SURFACE_BYTES / 1024 / 1024} MB while being audited, so it was stopped there; nothing was pinned`;
2891
+ }
2892
+ function inspectMessage(message) {
2893
+ let bytes = 0;
2894
+ let prototypeKey = false;
2895
+ const pending = [message];
2896
+ while (pending.length > 0) {
2897
+ const node = pending.pop();
2898
+ if (typeof node === "string") bytes += node.length + 2;
2899
+ else if (Array.isArray(node)) {
2900
+ bytes += 2;
2901
+ for (const member of node) pending.push(member);
2902
+ } else if (node !== null && typeof node === "object") {
2903
+ bytes += 2;
2904
+ if (Object.hasOwn(node, "__proto__")) prototypeKey = true;
2905
+ for (const key of Object.keys(node)) {
2906
+ bytes += key.length + 3;
2907
+ pending.push(node[key]);
2908
+ }
2909
+ } else bytes += 5;
2910
+ }
2911
+ return { bytes, prototypeKey };
2912
+ }
2913
+ var INSPECTED = /* @__PURE__ */ Symbol("nulladrift.inspected");
2914
+ function guardMessages(transport2, guard) {
2915
+ let current;
2916
+ Object.defineProperty(transport2, "onmessage", {
2917
+ configurable: true,
2918
+ enumerable: true,
2919
+ get: () => current,
2920
+ set: (handler) => {
2921
+ if (handler === void 0 || handler[INSPECTED]) {
2922
+ current = handler;
2923
+ return;
2924
+ }
2925
+ const wrapped = ((message, extra) => {
2926
+ if (guard.admit(message)) handler(message, extra);
2927
+ });
2928
+ wrapped[INSPECTED] = true;
2929
+ current = wrapped;
2930
+ }
2931
+ });
2932
+ }
2933
+ function guardedFetch(guard) {
2934
+ return (async (input, init) => {
2935
+ const response = await fetch(input, init);
2936
+ if (!response.body) return response;
2937
+ const reader = response.body.getReader();
2938
+ const body = new ReadableStream({
2939
+ async pull(controller) {
2940
+ const { done, value } = await reader.read();
2941
+ if (done) {
2942
+ controller.close();
2943
+ return;
2944
+ }
2945
+ if (!guard.received(value.byteLength)) {
2946
+ await reader.cancel().catch(() => {
2947
+ });
2948
+ controller.error(new Error(guard.refusal));
2949
+ return;
2950
+ }
2951
+ controller.enqueue(value);
2952
+ },
2953
+ cancel: (reason) => reader.cancel(reason)
2954
+ });
2955
+ return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
2956
+ });
2957
+ }
2958
+ var UNSENDABLE = /[\r\n\0]/;
2959
+ function refuseUnsendable(server2) {
2960
+ const { transport: transport2 } = server2;
2961
+ if (transport2.type === "stdio") {
2962
+ for (const [name, value] of Object.entries(transport2.env)) {
2963
+ if (value.includes("\0")) throw new UnreachableServerError(server2.name, `the environment variable ${name} contains a NUL character, which a process cannot be given; check where its value comes from`);
2964
+ }
2965
+ transport2.args.forEach((arg, index) => {
2966
+ if (arg.includes("\0")) throw new UnreachableServerError(server2.name, `argument ${index + 1} contains a NUL character, which a process cannot be given`);
2967
+ });
2968
+ return;
2969
+ }
2970
+ for (const [name, value] of Object.entries(transport2.headers)) {
2971
+ if (UNSENDABLE.test(value)) {
2972
+ throw new UnreachableServerError(
2973
+ server2.name,
2974
+ `the value of the ${name} header contains a line break or NUL, which HTTP does not allow; check the variable it is read from (a secret saved with a trailing newline is the usual cause)`
2975
+ );
2976
+ }
2977
+ }
2978
+ }
2664
2979
  function buildTransport(server2, captureStderr = () => {
2665
2980
  }, options = {}) {
2666
2981
  const { transport: transport2 } = server2;
@@ -2681,8 +2996,9 @@ function buildTransport(server2, captureStderr = () => {
2681
2996
  const headers = { "user-agent": USER_AGENT, ...transport2.headers };
2682
2997
  const url = new URL(transport2.url);
2683
2998
  const authProvider = createAuthProvider(server2, options);
2684
- if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider });
2685
- return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider });
2999
+ const custom = options.fetch ? { fetch: options.fetch } : {};
3000
+ if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider, ...custom });
3001
+ return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider, ...custom });
2686
3002
  }
2687
3003
  function diagnosticLines(stderr, limit = 3) {
2688
3004
  const lines = stderr.split("\n").map((line) => line.trimEnd()).filter((line) => line.trim().length > 0).filter((line) => !/^\s*(at\s|\^+$|[}\])]+$|Node\.js v[\d.]+$)/.test(line));
@@ -2706,17 +3022,34 @@ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS2, options = {}) {
2706
3022
  versionNegotiation: { mode: "auto", probe: { timeoutMs } }
2707
3023
  }
2708
3024
  );
3025
+ refuseUnsendable(server2);
3026
+ const changes = /* @__PURE__ */ new Set();
3027
+ for (const [list, method] of [
3028
+ ["tools", "notifications/tools/list_changed"],
3029
+ ["resources", "notifications/resources/list_changed"],
3030
+ ["prompts", "notifications/prompts/list_changed"]
3031
+ ]) {
3032
+ client.setNotificationHandler(method, () => {
3033
+ changes.add(list);
3034
+ });
3035
+ }
2709
3036
  let transport2;
3037
+ const guard = new SurfaceGuard(() => {
3038
+ void transport2?.close().catch(() => {
3039
+ });
3040
+ });
2710
3041
  try {
2711
- transport2 = buildTransport(server2, captureStderr, options);
3042
+ transport2 = buildTransport(server2, captureStderr, { ...options, fetch: guardedFetch(guard) });
2712
3043
  } catch (error) {
2713
3044
  throw new UnreachableServerError(server2.name, `could not prepare transport: ${error.message}`, error);
2714
3045
  }
3046
+ guardMessages(transport2, guard);
2715
3047
  try {
2716
3048
  await client.connect(transport2, { timeout: timeoutMs });
2717
3049
  } catch (error) {
2718
3050
  await client.close().catch(() => {
2719
3051
  });
3052
+ if (guard.refusal !== void 0) throw new UnreachableServerError(server2.name, guard.refusal, error);
2720
3053
  const detail = stderrBuffer.trim();
2721
3054
  throw new UnreachableServerError(
2722
3055
  server2.name,
@@ -2728,6 +3061,9 @@ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS2, options = {}) {
2728
3061
  return {
2729
3062
  client,
2730
3063
  stderr: () => stderrBuffer,
3064
+ refused: () => guard.refusal,
3065
+ watchChanges: () => changes.clear(),
3066
+ changed: () => [...changes].sort(),
2731
3067
  close: async () => {
2732
3068
  await client.close().catch(() => {
2733
3069
  });
@@ -2778,13 +3114,13 @@ async function listAllTools(client, timeoutMs) {
2778
3114
  let cursor;
2779
3115
  for (let page = 0; page < MAX_LIST_PAGES; page += 1) {
2780
3116
  const result = await client.request({ method: "tools/list", params: cursor === void 0 ? {} : { cursor } }, { timeout: timeoutMs });
2781
- tools.push(...result.tools);
3117
+ for (const tool2 of result.tools) tools.push(tool2);
2782
3118
  cursor = result.nextCursor;
2783
- if (cursor === void 0) return tools;
2784
- if (cursors.has(cursor)) throw new Error("tools/list: the server repeated a page cursor, so the listing would never end");
3119
+ if (cursor === void 0) return { tools };
3120
+ if (cursors.has(cursor)) return { tools, partial: `tools/list repeated a page cursor after ${page + 1} page(s), so its listing never ends; the pages before the repeat were read` };
2785
3121
  cursors.add(cursor);
2786
3122
  }
2787
- throw new Error(`tools/list: more than ${MAX_LIST_PAGES} pages; the server's pagination did not end`);
3123
+ return { tools, partial: `tools/list did not end within ${MAX_LIST_PAGES} pages; the first ${MAX_LIST_PAGES} were read` };
2788
3124
  }
2789
3125
  async function listOrEmpty(label, serverName, fetchList) {
2790
3126
  try {
@@ -2811,7 +3147,8 @@ function readServerInfo(client) {
2811
3147
  title: info.title,
2812
3148
  version: info.version,
2813
3149
  description: info.description,
2814
- websiteUrl: info.websiteUrl
3150
+ websiteUrl: info.websiteUrl,
3151
+ icons: lockIcons(info.icons)
2815
3152
  };
2816
3153
  }
2817
3154
  async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS2) {
@@ -2835,7 +3172,11 @@ async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS2) {
2835
3172
  }
2836
3173
  connection = opened;
2837
3174
  try {
2838
- return await readSurface(opened.client, server2, timeoutMs);
3175
+ return await readSurface(opened, server2, timeoutMs);
3176
+ } catch (error) {
3177
+ const refused = opened.refused();
3178
+ if (refused !== void 0) throw new UnreachableServerError(server2.name, refused, error);
3179
+ throw error;
2839
3180
  } finally {
2840
3181
  await opened.close();
2841
3182
  }
@@ -2847,10 +3188,31 @@ async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS2) {
2847
3188
  clearTimeout(timer);
2848
3189
  }
2849
3190
  }
2850
- async function readSurface(client, server2, timeoutMs) {
3191
+ var LIST_PASSES = 2;
3192
+ async function readSurface(connection, server2, timeoutMs) {
3193
+ for (let pass = 1; ; pass += 1) {
3194
+ connection.watchChanges();
3195
+ const surface = await readLists(connection.client, server2, timeoutMs);
3196
+ const moved = connection.changed();
3197
+ if (moved.length === 0) return surface;
3198
+ if (pass >= LIST_PASSES) {
3199
+ const reasons = [
3200
+ ...surface.coverage?.reasons ?? [],
3201
+ `the server said its ${moved.join(" and ")} changed while being read, on ${LIST_PASSES} passes running, so no read is known to be current`
3202
+ ];
3203
+ return { ...surface, coverage: { complete: false, reasons } };
3204
+ }
3205
+ }
3206
+ }
3207
+ async function readLists(client, server2, timeoutMs) {
2851
3208
  const capabilities = client.getServerCapabilities();
3209
+ let toolsPartial;
2852
3210
  const [tools, resources, resourceTemplates, prompts] = await Promise.all([
2853
- capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => listAllTools(client, timeoutMs)) : [],
3211
+ capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => {
3212
+ const listed = await listAllTools(client, timeoutMs);
3213
+ toolsPartial = listed.partial;
3214
+ return listed.tools;
3215
+ }) : [],
2854
3216
  // Each list call is bounded by the server's timeout too. With none, the SDK's default
2855
3217
  // applied per page (60s, up to 64 pages), so one slow server could hold a run for an hour.
2856
3218
  capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, { ...FRESH, timeout: timeoutMs })).resources) : [],
@@ -2866,7 +3228,8 @@ async function readSurface(client, server2, timeoutMs) {
2866
3228
  tools,
2867
3229
  resources,
2868
3230
  resourceTemplates,
2869
- prompts
3231
+ prompts,
3232
+ ...toolsPartial ? { coverage: { complete: false, reasons: [toolsPartial] } } : {}
2870
3233
  };
2871
3234
  }
2872
3235
 
@@ -2875,8 +3238,9 @@ async function provenanceOf(server2, options) {
2875
3238
  if (server2.transport.type !== "stdio") return { unverified: false };
2876
3239
  const reference = referenceOf(server2.transport, options.projectRoot);
2877
3240
  if (!reference) return { unverified: false };
2878
- if (fetchedElsewhere(server2.transport, reference, { projectRoot: options.projectRoot })) return { unverified: true };
2879
3241
  const previous = options.previous?.subjects[server2.name]?.provenance;
3242
+ const elsewhere = fetchedElsewhere(server2.transport, reference, { projectRoot: options.projectRoot });
3243
+ if (elsewhere) return { unverified: true, ...previous ? { displaced: { previous, why: elsewhere } } : {} };
2880
3244
  if (options.provenance === false) {
2881
3245
  const kept2 = carriedForward(previous, reference);
2882
3246
  return { ...kept2 ? { provenance: kept2 } : {}, unverified: true };
@@ -2904,14 +3268,15 @@ async function captureAll(options) {
2904
3268
  const discovery = await discoverServers(options.projectRoot, options.configFiles, { userConfigs: options.userConfigs === true });
2905
3269
  const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
2906
3270
  try {
2907
- const { provenance: provenance2, unverified: unverified2 } = await provenanceOf(server2, options);
2908
- const surface = await captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
3271
+ const { provenance: provenance2, unverified: unverified2, displaced: displaced2 } = await provenanceOf(server2, options);
3272
+ const pinned = server2.transport.type === "stdio" ? launchPinned(server2.transport, provenance2) : void 0;
3273
+ const surface = await captureSurface(pinned ? { ...server2, transport: pinned } : server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
2909
3274
  const entry = buildLockedServer(server2, surface, options.policy);
2910
3275
  options.onServerDone?.(server2.name, "captured");
2911
- return { name: server2.name, entry: provenance2 ? { ...entry, provenance: provenance2 } : entry, unverified: unverified2 };
3276
+ return { name: server2.name, entry: provenance2 ? { ...entry, provenance: provenance2 } : entry, unverified: unverified2, displaced: displaced2 };
2912
3277
  } catch (error) {
2913
3278
  options.onServerDone?.(server2.name, "failed");
2914
- const reason = error instanceof UnreachableServerError ? error.message : error.message;
3279
+ const reason = withoutSecrets(error instanceof UnreachableServerError ? error.message : error.message, server2);
2915
3280
  const kind = authFailureKind(error) ?? "unreachable";
2916
3281
  return { name: server2.name, failure: { server: server2.name, reason, kind } };
2917
3282
  }
@@ -2919,14 +3284,30 @@ async function captureAll(options) {
2919
3284
  const subjects = {};
2920
3285
  const unreachable = [];
2921
3286
  const unverified = [];
3287
+ const displaced = [];
3288
+ const unaudited = {};
3289
+ const configured = new Map(discovery.servers.map((server2) => [server2.name, server2]));
2922
3290
  for (const result of captured) {
2923
3291
  if ("entry" in result && result.entry) {
2924
3292
  subjects[result.name] = result.entry;
2925
3293
  if (result.unverified) unverified.push(result.name);
2926
- } else if ("failure" in result && result.failure) unreachable.push(result.failure);
3294
+ if (result.displaced) displaced.push({ server: result.name, ...result.displaced });
3295
+ } else if ("failure" in result && result.failure) {
3296
+ unreachable.push(result.failure);
3297
+ const server2 = configured.get(result.name);
3298
+ unaudited[result.name] = server2 ? { transport: lockTransport(server2) } : {};
3299
+ }
2927
3300
  }
2928
3301
  for (const skipped of discovery.skipped) {
2929
3302
  unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
3303
+ unaudited[skipped.serverName] = {};
3304
+ }
3305
+ for (const conflict of discovery.conflicts) {
3306
+ unreachable.push({
3307
+ server: conflict.name,
3308
+ reason: `defined differently in ${conflict.definitions.map((definition) => definition.file).join(" and ")}. Each client runs the one in its own file, so auditing one of them would vouch for the others. Give them different names, or make them the same.`,
3309
+ kind: "unreachable"
3310
+ });
2930
3311
  }
2931
3312
  for (const problem of discovery.problems) {
2932
3313
  unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
@@ -2940,13 +3321,75 @@ async function captureAll(options) {
2940
3321
  },
2941
3322
  unreachable,
2942
3323
  discovery,
2943
- unverified: unverified.sort()
3324
+ unverified: unverified.sort(),
3325
+ displaced,
3326
+ unaudited,
3327
+ conflicted: discovery.conflicts.map((conflict) => conflict.name),
3328
+ partial: Object.entries(subjects).filter(([, entry]) => entry.coverage !== void 0).map(([server2, entry]) => ({ server: server2, reasons: entry.coverage.reasons })).sort((a, b) => a.server.localeCompare(b.server))
2944
3329
  };
2945
3330
  }
3331
+ function acknowledged(committed, name, now) {
3332
+ const agreed = committed.unaudited?.[name];
3333
+ return agreed !== void 0 && JSON.stringify(agreed.transport ?? null) === JSON.stringify(now.transport ?? null);
3334
+ }
3335
+ function compareWithLock(committed, result) {
3336
+ const changes = diffLockfiles(committed, result.lock);
3337
+ for (const moved of result.displaced) {
3338
+ const was = `${moved.previous.name}${moved.previous.version ? `@${moved.previous.version}` : ""}`;
3339
+ changes.push({
3340
+ kind: "server.artifact.changed",
3341
+ severity: SEVERITY["server.artifact.changed"],
3342
+ server: moved.server,
3343
+ summary: `${was} was pinned from its registry, and now ${moved.why}: what runs is not what was pinned, and nothing here can check it`,
3344
+ before: moved.previous
3345
+ });
3346
+ }
3347
+ const failed = new Map(result.unreachable.map((failure) => [failure.server, failure.reason]));
3348
+ for (const [name, now] of Object.entries(result.unaudited)) {
3349
+ if (committed.subjects[name] !== void 0 || acknowledged(committed, name, now)) continue;
3350
+ changes.push({
3351
+ kind: "server.added",
3352
+ severity: SEVERITY["server.added"],
3353
+ server: name,
3354
+ summary: `${committed.unaudited?.[name] ? "a server left unaudited is now reached differently, and" : "new server, which"} could not be audited: ${failed.get(name) ?? "it did not answer"}`
3355
+ });
3356
+ }
3357
+ for (const name of result.conflicted) {
3358
+ if (committed.subjects[name] !== void 0) continue;
3359
+ changes.push({
3360
+ kind: "server.added",
3361
+ severity: SEVERITY["server.added"],
3362
+ server: name,
3363
+ summary: `new server, defined differently in two config files: ${failed.get(name) ?? ""}`
3364
+ });
3365
+ }
3366
+ return sortChanges(changes);
3367
+ }
3368
+ function unauditedToRecord(result, keep = () => true) {
3369
+ const entries = Object.entries(result.unaudited).filter(([name]) => keep(name));
3370
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
3371
+ }
3372
+ function withoutSecrets(reason, server2) {
3373
+ const { transport: transport2 } = server2;
3374
+ const secrets = [];
3375
+ if (transport2.type === "stdio") {
3376
+ for (const [name, value] of Object.entries(transport2.env)) {
3377
+ if (isCredentialName(name) || value.length >= 16 && !/[\s/\\]/.test(value)) secrets.push(value);
3378
+ }
3379
+ } else {
3380
+ for (const value of Object.values(transport2.headers)) secrets.push(value, ...value.split(/\s+/));
3381
+ if (transport2.oauth?.clientSecret) secrets.push(transport2.oauth.clientSecret);
3382
+ }
3383
+ let out = reason;
3384
+ for (const secret of [...new Set(secrets)].filter((value) => value.length >= 8).sort((a, b) => b.length - a.length)) {
3385
+ out = out.split(secret).join("[redacted]");
3386
+ }
3387
+ return out;
3388
+ }
2946
3389
 
2947
3390
  // src/lock/io.ts
2948
3391
  import { randomUUID as randomUUID2 } from "crypto";
2949
- import { lstat, readFile as readFile5, rename, rm as rm2, writeFile as writeFile2 } from "fs/promises";
3392
+ import { lstat as lstat2, readFile as readFile5, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
2950
3393
 
2951
3394
  // src/lock/schema.ts
2952
3395
  import { z as z2 } from "zod";
@@ -2994,6 +3437,7 @@ var tool = z2.object({
2994
3437
  behavior,
2995
3438
  headerParams: z2.array(z2.string()).optional(),
2996
3439
  icons: z2.array(icon).optional(),
3440
+ execution: jsonObject.optional(),
2997
3441
  meta: jsonObject.optional(),
2998
3442
  digest: digestString
2999
3443
  });
@@ -3044,7 +3488,8 @@ var provenance = z2.object({
3044
3488
  name: z2.string(),
3045
3489
  version: z2.string().optional(),
3046
3490
  integrity: z2.string().optional(),
3047
- requested: z2.string().optional()
3491
+ requested: z2.string().optional(),
3492
+ files: z2.record(z2.string(), z2.string()).optional()
3048
3493
  });
3049
3494
  var server = z2.object({
3050
3495
  kind: z2.literal("mcp-server"),
@@ -3055,6 +3500,7 @@ var server = z2.object({
3055
3500
  }),
3056
3501
  transport,
3057
3502
  provenance: provenance.optional(),
3503
+ coverage: z2.object({ complete: z2.literal(false), reasons: z2.array(z2.string()) }).optional(),
3058
3504
  protocol: z2.object({
3059
3505
  era: z2.enum(["modern", "legacy"]),
3060
3506
  version: z2.string(),
@@ -3065,7 +3511,8 @@ var server = z2.object({
3065
3511
  title: z2.string().optional(),
3066
3512
  version: z2.string().optional(),
3067
3513
  description: z2.string().optional(),
3068
- websiteUrl: z2.string().optional()
3514
+ websiteUrl: z2.string().optional(),
3515
+ icons: z2.array(icon).optional()
3069
3516
  }).optional(),
3070
3517
  capabilities: jsonObject.optional(),
3071
3518
  instructions: z2.string().optional(),
@@ -3085,6 +3532,7 @@ var lockfileSchema = z2.object({
3085
3532
  policy: z2.object({
3086
3533
  ignoreMetaPrefixes: z2.array(z2.string()).optional(),
3087
3534
  allowUnreachable: z2.boolean().optional(),
3535
+ allowPartial: z2.boolean().optional(),
3088
3536
  /*
3089
3537
  * Validated against the real list rather than accepted as free strings: a policy with
3090
3538
  * `process_exec` in it would otherwise parse, forbid nothing, and read in the diff of
@@ -3097,20 +3545,22 @@ var lockfileSchema = z2.object({
3097
3545
  * union of one looks odd now and is the point: a second kind is a new member here, and every
3098
3546
  * switch over the result stops compiling until it handles it.
3099
3547
  */
3100
- subjects: z2.record(z2.string(), z2.discriminatedUnion("kind", [server]))
3548
+ subjects: z2.record(z2.string(), z2.discriminatedUnion("kind", [server])),
3549
+ // Listed here or lost, like provenance: an acknowledgement stripped on read is one `check` ignores.
3550
+ unaudited: z2.record(z2.string(), z2.object({ transport: transport.optional() })).optional()
3101
3551
  });
3102
3552
 
3103
3553
  // src/lock/io.ts
3104
3554
  var DEFAULT_LOCK_FILENAME = "mcp.lock";
3105
3555
  var KEY_ORDER = {
3106
- root: ["lockfileVersion", "generatedBy", "policy", "subjects"],
3107
- policy: ["ignoreMetaPrefixes", "allowUnreachable", "deniedCapabilities"],
3556
+ root: ["lockfileVersion", "generatedBy", "policy", "subjects", "unaudited"],
3557
+ policy: ["ignoreMetaPrefixes", "allowUnreachable", "allowPartial", "deniedCapabilities"],
3108
3558
  server: ["kind", "source", "transport", "protocol", "serverInfo", "capabilities", "instructions", "tools", "resources", "resourceTemplates", "prompts", "digest"],
3109
3559
  source: ["client", "file", "scope"],
3110
3560
  transport: ["type", "command", "args", "envKeys", "cwd", "url", "headerKeys"],
3111
3561
  protocol: ["era", "version", "supportedVersions"],
3112
- serverInfo: ["name", "title", "version", "description", "websiteUrl"],
3113
- tool: ["name", "title", "description", "inputSchema", "outputSchema", "annotations", "behavior", "headerParams", "icons", "meta", "digest"],
3562
+ serverInfo: ["name", "title", "version", "description", "websiteUrl", "icons"],
3563
+ tool: ["name", "title", "description", "inputSchema", "outputSchema", "annotations", "behavior", "headerParams", "icons", "execution", "meta", "digest"],
3114
3564
  resource: ["uri", "name", "title", "description", "mimeType", "annotations", "icons", "meta", "digest"],
3115
3565
  resourceTemplate: ["uriTemplate", "name", "title", "description", "mimeType", "annotations", "icons", "meta", "digest"],
3116
3566
  prompt: ["name", "title", "description", "arguments", "icons", "meta", "digest"],
@@ -3173,7 +3623,10 @@ function serializeLockfile(lock) {
3173
3623
  // Names sorted so that adding one produces a localized diff.
3174
3624
  subjects: Object.fromEntries(
3175
3625
  Object.keys(lock.subjects).sort().map((name) => [name, lock.subjects[name]])
3176
- )
3626
+ ),
3627
+ unaudited: lock.unaudited && Object.keys(lock.unaudited).length > 0 ? Object.fromEntries(
3628
+ Object.keys(lock.unaudited).sort().map((name) => [name, lock.unaudited[name]])
3629
+ ) : void 0
3177
3630
  };
3178
3631
  const pad = INDENT;
3179
3632
  const parts = [];
@@ -3244,7 +3697,7 @@ async function readLockfile(path) {
3244
3697
  }
3245
3698
  async function writeLockfile(path, lock) {
3246
3699
  try {
3247
- const link = await lstat(path).catch(() => void 0);
3700
+ const link = await lstat2(path).catch(() => void 0);
3248
3701
  if (link?.isSymbolicLink()) {
3249
3702
  throw new LockfileError(`refusing to write ${path}: it is a symbolic link. A lockfile is a real file in the project, and following the link would write somewhere else.`);
3250
3703
  }
@@ -3255,7 +3708,7 @@ async function writeLockfile(path, lock) {
3255
3708
  const temporary = `${path}.${randomUUID2()}.tmp`;
3256
3709
  await writeFile2(temporary, serializeLockfile(lock), { encoding: "utf8", flag: "wx" });
3257
3710
  try {
3258
- await rename(temporary, path);
3711
+ await rename2(temporary, path);
3259
3712
  } catch (error) {
3260
3713
  await rm2(temporary, { force: true }).catch(() => {
3261
3714
  });
@@ -3328,7 +3781,8 @@ function renderViolations(report) {
3328
3781
  for (const violation of found) {
3329
3782
  lines.push(
3330
3783
  ` ${red("denied")} ${bold(visibleControls(`${violation.server} \u203A ${violation.tool}`))} ${dim(violation.kind)}`,
3331
- ` ${violation.severity} \xB7 ${violation.evidence}`
3784
+ // The evidence is an argument name, which the server chose.
3785
+ ` ${violation.severity} \xB7 ${visibleControls(violation.evidence)}`
3332
3786
  );
3333
3787
  }
3334
3788
  lines.push(
@@ -3360,7 +3814,7 @@ function renderHumanReport(report) {
3360
3814
  lines.push(bold(`Could not audit ${report.unreachable.length} server(s):`), "");
3361
3815
  for (const failure of report.unreachable) {
3362
3816
  const label = failure.kind === "auth" ? yellow("needs creds") : failure.kind === "forbidden" ? yellow("not permitted") : red("unreachable");
3363
- lines.push(` ${label} ${bold(visibleControls(failure.server))}`, ` ${visibleControls(failure.reason)}`, "");
3817
+ lines.push(` ${label} ${bold(visibleControls(failure.server))}`, ` ${visibleLines(failure.reason, " ")}`, "");
3364
3818
  }
3365
3819
  }
3366
3820
  const unverified = report.unverified ?? [];
@@ -3372,8 +3826,17 @@ function renderHumanReport(report) {
3372
3826
  ""
3373
3827
  );
3374
3828
  }
3829
+ const partial = report.partial ?? [];
3830
+ if (partial.length > 0) {
3831
+ lines.push(yellow(`Could not read ${partial.length} server(s) in full:`));
3832
+ for (const entry of partial) {
3833
+ lines.push(` ${bold(visibleControls(entry.server))}`);
3834
+ for (const reason of entry.reasons) lines.push(` ${visibleLines(reason, " ")}`);
3835
+ }
3836
+ lines.push(dim(" Compared as far as they were read. This fails the audit; --allow-partial makes it a warning."), "");
3837
+ }
3375
3838
  lines.push(...renderSteering(report));
3376
- if (report.changes.length === 0 && report.unreachable.length === 0 && (report.violations ?? []).length === 0) {
3839
+ if (report.changes.length === 0 && report.unreachable.length === 0 && (report.violations ?? []).length === 0 && partial.length === 0) {
3377
3840
  lines.push(green(`\u2713 ${report.serversChecked} server(s) match ${report.lockPath}`));
3378
3841
  return `${lines.join("\n")}
3379
3842
  `;
@@ -3437,7 +3900,11 @@ function renderJsonReport(report, exitCode) {
3437
3900
  */
3438
3901
  steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0),
3439
3902
  /** Unlike steering, these DO decide the exit code. */
3440
- violations: (report.violations ?? []).length
3903
+ violations: (report.violations ?? []).length,
3904
+ /** Answered, but what they run could not be established. Never part of the verdict. */
3905
+ unverified: (report.unverified ?? []).length,
3906
+ /** Read, but not in full. Part of the verdict (exit 2) unless --allow-partial. */
3907
+ partial: (report.partial ?? []).length
3441
3908
  },
3442
3909
  changes: report.changes.map((change2) => ({
3443
3910
  kind: change2.kind,
@@ -3451,7 +3918,9 @@ function renderJsonReport(report, exitCode) {
3451
3918
  unreachable: report.unreachable,
3452
3919
  /** Text that began addressing the model since the lock was approved. Reported, never gated. */
3453
3920
  steering: report.steering ?? [],
3454
- violations: report.violations ?? []
3921
+ violations: report.violations ?? [],
3922
+ unverified: report.unverified ?? [],
3923
+ partial: report.partial ?? []
3455
3924
  },
3456
3925
  null,
3457
3926
  2
@@ -3487,6 +3956,8 @@ var LEVEL = {
3487
3956
  };
3488
3957
  var DENIED_RULE = "policy.capability.denied";
3489
3958
  var STEERING_RULE = "steering.passage.arrived";
3959
+ var UNVERIFIED_RULE = "server.artifact.unverified";
3960
+ var PARTIAL_RULE = "server.surface.partial";
3490
3961
  var RULE_HELP = {
3491
3962
  "tool.capability.gained": "A tool gained a capability it did not declare before, derived from its name, its argument names and the shape of its schema. The severity is the capability's, not the schema change's: gaining a `command` argument is not the same finding as gaining an optional string.",
3492
3963
  "tool.description.changed": "A tool description is injected into the model's context. A change here can carry instructions to the agent and should be read in full, not skimmed.",
@@ -3512,6 +3983,8 @@ function renderSarifReport(report, options = {}) {
3512
3983
  const used = [...new Set(report.changes.map((change2) => change2.kind))].sort();
3513
3984
  const violations = report.violations ?? [];
3514
3985
  const steering = options.steering ? report.steering ?? [] : [];
3986
+ const unverified = report.unverified ?? [];
3987
+ const partial = report.partial ?? [];
3515
3988
  const at = (name, qualified) => [
3516
3989
  {
3517
3990
  physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
@@ -3532,6 +4005,20 @@ function renderSarifReport(report, options = {}) {
3532
4005
  shortDescription: { text: "Text that began addressing the model" },
3533
4006
  fullDescription: { text: "A passage a model is shown started reading as an instruction since this lock was approved. A signal to read, not a verdict: legitimate servers trip the same shape. It does not affect the exit code." },
3534
4007
  defaultConfiguration: { level: "note" }
4008
+ }] : [],
4009
+ ...partial.length > 0 ? [{
4010
+ id: PARTIAL_RULE,
4011
+ name: "ServerSurfacePartial",
4012
+ shortDescription: { text: "A server's surface could not be read in full" },
4013
+ fullDescription: { text: "The listing did not end within the page limit, or the server said it changed while being read on every pass. Compared as far as it was read; the audit did not finish." },
4014
+ defaultConfiguration: { level: "warning" }
4015
+ }] : [],
4016
+ ...unverified.length > 0 ? [{
4017
+ id: UNVERIFIED_RULE,
4018
+ name: "ServerArtifactUnverified",
4019
+ shortDescription: { text: "What a server runs could not be checked" },
4020
+ fullDescription: { text: "The server answered and its declared surface was compared, but the artifact behind it could not be established on this run: a registry that did not answer, or a launcher configured to fetch from somewhere the pin does not describe. It does not affect the exit code." },
4021
+ defaultConfiguration: { level: "note" }
3535
4022
  }] : []
3536
4023
  ];
3537
4024
  const document = {
@@ -3580,7 +4067,21 @@ function renderSarifReport(report, options = {}) {
3580
4067
  locations: at(signal.field, `${server2}/${signal.field}`),
3581
4068
  partialFingerprints: { "mcpAuditChange/v1": `${server2}/${signal.field}/${signal.kind}` }
3582
4069
  }))
3583
- )
4070
+ ),
4071
+ ...partial.map((entry) => ({
4072
+ ruleId: PARTIAL_RULE,
4073
+ level: "warning",
4074
+ message: { text: `${entry.server}: could not be read in full. ${entry.reasons.join("; ")}` },
4075
+ locations: at(entry.server, entry.server),
4076
+ partialFingerprints: { "mcpAuditChange/v1": `${entry.server}/partial` }
4077
+ })),
4078
+ ...unverified.map((server2) => ({
4079
+ ruleId: UNVERIFIED_RULE,
4080
+ level: "note",
4081
+ message: { text: `${server2}: what this server runs could not be checked on this run` },
4082
+ locations: at(server2, server2),
4083
+ partialFingerprints: { "mcpAuditChange/v1": `${server2}/unverified` }
4084
+ }))
3584
4085
  ]
3585
4086
  }
3586
4087
  ]
@@ -3597,10 +4098,10 @@ var AUDIT_FAILURE_LABEL = {
3597
4098
  };
3598
4099
  var MARK2 = { high: "\u{1F534}", medium: "\u{1F7E0}", low: "\u26AA" };
3599
4100
  function plain(text) {
3600
- return visibleControls(text).replace(/\r?\n/g, " ").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/([\\`*_{}[\]()#+!|~])/g, "\\$1").replace(/@/g, "&#64;").replace(/:\/\//g, "&#58;//").trim();
4101
+ return visibleControls(text, { multiline: true }).replace(/\r?\n/g, " ").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/([\\`*_{}[\]()#+!|~])/g, "\\$1").replace(/@/g, "@\u200B").replace(/\bwww\./gi, (prefix) => `${prefix.slice(0, 3)}\u200B.`).replace(/:\/\//g, "&#58;//").trim();
3601
4102
  }
3602
4103
  function code(text) {
3603
- const body = visibleControls(text).replace(/\r?\n/g, " ").replace(/\|/g, "\\|").trim();
4104
+ const body = visibleControls(text, { multiline: true }).replace(/\r?\n/g, " ").replace(/\|/g, "\\|").trim();
3604
4105
  const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((run) => run.length));
3605
4106
  const fence = "`".repeat(longest + 1);
3606
4107
  const pad = body.startsWith("`") || body.endsWith("`") ? " " : "";
@@ -3611,16 +4112,22 @@ function row(change2) {
3611
4112
  return `| ${MARK2[change2.severity]} ${change2.severity} | ${code(where)} | ${plain(change2.kind)} | ${plain(change2.summary)} |`;
3612
4113
  }
3613
4114
  function renderMarkdownReport(report, options = {}) {
3614
- if (report.changes.length === 0 && report.unreachable.length === 0) return null;
4115
+ const violations = report.violations ?? [];
4116
+ const partial = report.partial ?? [];
4117
+ if (report.changes.length === 0 && report.unreachable.length === 0 && violations.length === 0 && partial.length === 0) return null;
3615
4118
  const lines = [];
3616
4119
  const high = report.changes.filter((change2) => change2.severity === "high").length;
3617
- lines.push(
3618
- high > 0 ? `### ${report.changes.length} change${report.changes.length === 1 ? "" : "s"} to what your agents can reach, ${high} high` : `### ${report.changes.length} change${report.changes.length === 1 ? "" : "s"} to what your agents can reach`,
3619
- "",
3620
- "A server changed what it declares. Same version, same package: the comparison is against the",
3621
- "surface you approved, not the version string.",
3622
- ""
3623
- );
4120
+ if (report.changes.length === 0 && violations.length > 0) {
4121
+ lines.push(`### ${violations.length} capabilit${violations.length === 1 ? "y" : "ies"} this project does not permit`, "");
4122
+ } else {
4123
+ lines.push(
4124
+ high > 0 ? `### ${report.changes.length} change${report.changes.length === 1 ? "" : "s"} to what your agents can reach, ${high} high` : `### ${report.changes.length} change${report.changes.length === 1 ? "" : "s"} to what your agents can reach`,
4125
+ "",
4126
+ "A server changed what it declares. Same version, same package: the comparison is against the",
4127
+ "surface you approved, not the version string.",
4128
+ ""
4129
+ );
4130
+ }
3624
4131
  if (report.changes.length > 0) {
3625
4132
  lines.push("| | Where | What | Detail |", "| --- | --- | --- | --- |", ...report.changes.map(row), "");
3626
4133
  const quiet = serversThatShippedNothing(report.changes);
@@ -3633,6 +4140,16 @@ function renderMarkdownReport(report, options = {}) {
3633
4140
  );
3634
4141
  }
3635
4142
  }
4143
+ if (violations.length > 0) {
4144
+ lines.push(
4145
+ `**${violations.length} capabilit${violations.length === 1 ? "y" : "ies"} this project does not permit.** Set by \`policy.deniedCapabilities\` in the lockfile; accepting the change does not clear it.`,
4146
+ "",
4147
+ "| Where | Capability | Evidence |",
4148
+ "| --- | --- | --- |",
4149
+ ...violations.map((violation) => `| ${code(`${violation.server}/${violation.tool}`)} | ${plain(violation.kind)} | ${code(violation.evidence)} |`),
4150
+ ""
4151
+ );
4152
+ }
3636
4153
  const steering = report.steering ?? [];
3637
4154
  if (steering.length > 0) {
3638
4155
  const total = steering.reduce((sum, server2) => sum + server2.signals.length, 0);
@@ -3665,6 +4182,31 @@ function renderMarkdownReport(report, options = {}) {
3665
4182
  ""
3666
4183
  );
3667
4184
  }
4185
+ if (partial.length > 0) {
4186
+ lines.push(
4187
+ `<details><summary>${partial.length} server${partial.length === 1 ? "" : "s"} could not be read in full</summary>`,
4188
+ "",
4189
+ "Compared as far as they were read. A clean comparison against part of a surface says nothing about the rest, so this fails the audit unless `--allow-partial` is set.",
4190
+ "",
4191
+ ...partial.map((entry) => `- ${code(entry.server)}: ${plain(entry.reasons.join("; "))}`),
4192
+ "",
4193
+ "</details>",
4194
+ ""
4195
+ );
4196
+ }
4197
+ const unverified = report.unverified ?? [];
4198
+ if (unverified.length > 0) {
4199
+ lines.push(
4200
+ `<details><summary>${unverified.length} server${unverified.length === 1 ? "" : "s"} whose code could not be checked</summary>`,
4201
+ "",
4202
+ "These answered and their declarations were compared, but what they run could not be established on this run.",
4203
+ "",
4204
+ ...unverified.map((server2) => `- ${code(server2)}`),
4205
+ "",
4206
+ "</details>",
4207
+ ""
4208
+ );
4209
+ }
3668
4210
  lines.push(
3669
4211
  options.url ? `Read the full diff and rule on it: ${options.url}` : "Run `nulladrift review` to read the full diff, or `nulladrift review --accept-all` to accept every change."
3670
4212
  );
@@ -3706,12 +4248,29 @@ ${body}`;
3706
4248
  const existing = await call(target, `/issues/${target.issue}/comments?per_page=100`);
3707
4249
  if (existing.status === 403) return "forbidden";
3708
4250
  if (!existing.ok) throw new Error(`could not read the comments (${existing.status})`);
4251
+ const self = await identity2(target);
3709
4252
  const comments = await existing.json();
3710
- const mine = comments.find((comment2) => comment2.body?.startsWith(MARKER));
3711
- const written = mine ? await call(target, `/issues/comments/${mine.id}`, { method: "PATCH", body: JSON.stringify({ body: marked }) }) : await call(target, `/issues/${target.issue}/comments`, { method: "POST", body: JSON.stringify({ body: marked }) });
3712
- if (written.status === 403) return "forbidden";
3713
- if (!written.ok) throw new Error(`could not post the comment (${written.status})`);
3714
- return mine ? "updated" : "created";
4253
+ const mine = comments.find((comment2) => comment2.body?.startsWith(MARKER) && comment2.user?.login === self);
4254
+ if (mine) {
4255
+ const updated = await call(target, `/issues/comments/${mine.id}`, { method: "PATCH", body: JSON.stringify({ body: marked }) });
4256
+ if (updated.ok) return "updated";
4257
+ if (updated.status !== 403 && updated.status !== 404) throw new Error(`could not update the comment (${updated.status})`);
4258
+ }
4259
+ const created = await call(target, `/issues/${target.issue}/comments`, { method: "POST", body: JSON.stringify({ body: marked }) });
4260
+ if (created.status === 403) return "forbidden";
4261
+ if (!created.ok) throw new Error(`could not post the comment (${created.status})`);
4262
+ return "created";
4263
+ }
4264
+ async function identity2(target) {
4265
+ const response = await fetch(`${target.api}/user`, {
4266
+ headers: { accept: "application/vnd.github+json", authorization: `Bearer ${target.token}`, "x-github-api-version": "2022-11-28" },
4267
+ signal: AbortSignal.timeout(1e4)
4268
+ }).catch(() => void 0);
4269
+ if (response?.ok) {
4270
+ const body = await response.json().catch(() => ({}));
4271
+ if (typeof body.login === "string" && body.login.length > 0) return body.login;
4272
+ }
4273
+ return "github-actions[bot]";
3715
4274
  }
3716
4275
 
3717
4276
  // src/telemetry/index.ts
@@ -3825,8 +4384,9 @@ async function buildReport(options) {
3825
4384
  });
3826
4385
  for (const note of redactedNotes(result.lock)) process.stderr.write(`${yellow("note:")} ${note}
3827
4386
  `);
3828
- const changes = diffLockfiles(committed, result.lock);
4387
+ const changes = compareWithLock(committed, result);
3829
4388
  const allowUnreachable = options.allowUnreachable || committed.policy?.allowUnreachable === true;
4389
+ const allowPartial = options.allowPartial === true || committed.policy?.allowPartial === true;
3830
4390
  const report = {
3831
4391
  changes,
3832
4392
  /*
@@ -3843,6 +4403,7 @@ async function buildReport(options) {
3843
4403
  unreachable: result.unreachable,
3844
4404
  // Reported beside the verdict and never part of it; see `AuditReport.unverified`.
3845
4405
  unverified: result.unverified,
4406
+ partial: result.partial,
3846
4407
  serversChecked: Object.keys(result.lock.subjects).length,
3847
4408
  lockPath: options.lockPath,
3848
4409
  projectRoot: options.projectRoot
@@ -3856,7 +4417,11 @@ async function buildReport(options) {
3856
4417
  * able to make it pass: policy is the thing acceptance cannot overrule.
3857
4418
  */
3858
4419
  driftCount: changes.length + (report.violations?.length ?? 0),
3859
- incompleteCount: allowUnreachable ? 0 : result.unreachable.length
4420
+ /*
4421
+ * A surface only partly read is neither drift nor clean: the audit did not finish, which is
4422
+ * what an unreachable server already means, for the same reason.
4423
+ */
4424
+ incompleteCount: (allowUnreachable ? 0 : result.unreachable.length) + (allowPartial ? 0 : result.partial.length)
3860
4425
  })
3861
4426
  };
3862
4427
  }
@@ -3896,7 +4461,7 @@ async function comment(report) {
3896
4461
  }
3897
4462
 
3898
4463
  // src/commands/init.ts
3899
- import { lstat as lstat2 } from "fs/promises";
4464
+ import { lstat as lstat3 } from "fs/promises";
3900
4465
 
3901
4466
  // src/commands/telemetry.ts
3902
4467
  import { createInterface } from "readline/promises";
@@ -3991,7 +4556,7 @@ ${dim(" No collector is configured in this build, so nothing will be sent until
3991
4556
  // src/commands/init.ts
3992
4557
  async function exists(path) {
3993
4558
  try {
3994
- await lstat2(path);
4559
+ await lstat3(path);
3995
4560
  return true;
3996
4561
  } catch {
3997
4562
  return false;
@@ -4034,7 +4599,8 @@ async function runInit(options) {
4034
4599
  return EXIT_CLEAN;
4035
4600
  }
4036
4601
  const pinnedSomething = names.length > 0;
4037
- if (pinnedSomething) await writeLockfile(options.lockPath, result.lock);
4602
+ const unaudited = options.allowUnreachable ? unauditedToRecord(result) : void 0;
4603
+ if (pinnedSomething) await writeLockfile(options.lockPath, unaudited ? { ...result.lock, unaudited } : result.lock);
4038
4604
  const lines = pinnedSomething ? ["", bold(`Pinned ${names.length} server(s) to ${options.lockPath}:`), ""] : ["", bold("Pinned nothing: no server answered."), ""];
4039
4605
  for (const name of names) {
4040
4606
  const entry = result.lock.subjects[name];
@@ -4077,8 +4643,12 @@ async function runInit(options) {
4077
4643
  lines.push(` ${dim("A signal to read, not a verdict. It never fails a build.")}`);
4078
4644
  }
4079
4645
  }
4646
+ for (const partial of result.partial) {
4647
+ lines.push(` ${yellow("\u25D0")} ${bold(visibleControls(partial.server))} ${dim("pinned as far as it could be read")}`);
4648
+ for (const reason of partial.reasons) lines.push(` ${visibleLines(reason, " ")}`);
4649
+ }
4080
4650
  for (const failure of result.unreachable) {
4081
- lines.push(` ${red("\u2717")} ${bold(failure.server)} ${dim("not pinned")}`, ` ${failure.reason}`);
4651
+ lines.push(` ${red("\u2717")} ${bold(visibleControls(failure.server))} ${dim("not pinned")}`, ` ${visibleLines(failure.reason, " ")}`);
4082
4652
  }
4083
4653
  if (result.discovery.userConfigsSkipped.length > 0) {
4084
4654
  lines.push(
@@ -4097,13 +4667,15 @@ async function runInit(options) {
4097
4667
  process.stdout.write(lines.join("\n"));
4098
4668
  await maybeOfferTelemetry();
4099
4669
  if (result.unreachable.length > 0 && !options.allowUnreachable) return EXIT_INCOMPLETE;
4670
+ if (result.partial.length > 0 && !options.allowPartial) return EXIT_INCOMPLETE;
4100
4671
  return EXIT_CLEAN;
4101
4672
  }
4102
4673
 
4103
4674
  // src/commands/login.ts
4104
4675
  import { createServer } from "http";
4105
4676
  import { auth } from "@modelcontextprotocol/client";
4106
- import { rm as rm4 } from "fs/promises";
4677
+ import { rm as rm4, stat } from "fs/promises";
4678
+ import { resolve as resolve5 } from "path";
4107
4679
  var CALLBACK_TIMEOUT_MS = 5 * 60 * 1e3;
4108
4680
  async function awaitCallback(expectedState) {
4109
4681
  let settle;
@@ -4140,8 +4712,8 @@ async function awaitCallback(expectedState) {
4140
4712
  server2.listen(0, "127.0.0.1", ready);
4141
4713
  });
4142
4714
  const { port } = server2.address();
4143
- const received = new Promise((resolve6, reject) => {
4144
- settle = resolve6;
4715
+ const received = new Promise((resolve7, reject) => {
4716
+ settle = resolve7;
4145
4717
  fail = reject;
4146
4718
  setTimeout(() => reject(new Error(`no callback within ${CALLBACK_TIMEOUT_MS / 1e3}s`)), CALLBACK_TIMEOUT_MS).unref();
4147
4719
  });
@@ -4153,6 +4725,16 @@ async function awaitCallback(expectedState) {
4153
4725
  }
4154
4726
  async function findServer(projectRoot, configFiles, name) {
4155
4727
  const discovery = await discoverServers(projectRoot, configFiles, { userConfigs: true });
4728
+ const conflict = discovery.conflicts.find((candidate) => candidate.name === name);
4729
+ if (conflict) {
4730
+ const named = new Set(configFiles.map((file) => portablePath(resolve5(projectRoot, file), projectRoot)));
4731
+ const chosen = conflict.definitions.filter((definition) => named.has(definition.file));
4732
+ if (chosen.length === 1) return chosen[0].server;
4733
+ const where = conflict.definitions.map((definition) => ` ${definition.file}: ${describeTarget(definition.server)}`).join("\n");
4734
+ return { error: `"${name}" is defined differently in more than one config:
4735
+ ${where}
4736
+ Name the one you mean with --config <file>.` };
4737
+ }
4156
4738
  const server2 = discovery.servers.find((candidate) => candidate.name === name);
4157
4739
  if (!server2) {
4158
4740
  const known = discovery.servers.map((candidate) => candidate.name);
@@ -4161,6 +4743,10 @@ async function findServer(projectRoot, configFiles, name) {
4161
4743
  if (server2.transport.type === "stdio") return { error: `"${name}" is a stdio server; it is launched locally and has nothing to log in to` };
4162
4744
  return server2;
4163
4745
  }
4746
+ function describeTarget(server2) {
4747
+ const { transport: transport2 } = server2;
4748
+ return transport2.type === "stdio" ? `runs ${transport2.command}` : sanitizeUrl(transport2.url);
4749
+ }
4164
4750
  async function runLogin(options) {
4165
4751
  if (options.serverName === void 0) {
4166
4752
  process.stderr.write(`${red("which server?")} ${dim("Usage: nulladrift login <server>")}
@@ -4220,9 +4806,16 @@ async function runLogout(options) {
4220
4806
  return EXIT_INCOMPLETE;
4221
4807
  }
4222
4808
  const url = found.transport.type === "stdio" ? "" : found.transport.url;
4223
- await rm4(credentialPath(url), { force: true });
4224
- process.stdout.write(`${dim(`stored credentials for ${found.name} deleted`)}
4225
- `);
4809
+ const path = credentialPath(url);
4810
+ const existed = await stat(path).then(
4811
+ () => true,
4812
+ () => false
4813
+ );
4814
+ await rm4(path, { force: true });
4815
+ process.stdout.write(
4816
+ `${dim(existed ? `stored credentials for ${found.name} (${sanitizeUrl(url)}) deleted` : `no credentials were stored for ${found.name} (${sanitizeUrl(url)})`)}
4817
+ `
4818
+ );
4226
4819
  return EXIT_CLEAN;
4227
4820
  }
4228
4821
 
@@ -4285,7 +4878,7 @@ async function acquireBuildToken(options = {}) {
4285
4878
  const explicit = env["NULLADRIFT_ID_TOKEN"];
4286
4879
  if (explicit) return { token: explicit, source: "environment" };
4287
4880
  if (env["GITHUB_ACTIONS"] !== "true") return void 0;
4288
- return fromGithubActions(env["NULLADRIFT_BUILD_AUDIENCE"] ?? DEFAULT_AUDIENCE, env, options);
4881
+ return fromGithubActions(env["NULLADRIFT_BUILD_AUDIENCE"] || DEFAULT_AUDIENCE, env, options);
4289
4882
  }
4290
4883
  async function acquireReadingToken(audience, options = {}) {
4291
4884
  const env = options.env ?? process.env;
@@ -4315,14 +4908,15 @@ async function fromGithubActions(audience, env, options) {
4315
4908
  }
4316
4909
 
4317
4910
  // src/commands/push.ts
4318
- function describeIdentity(identity2, hint) {
4319
- const where = `${identity2?.repository ?? ""}${identity2?.ref ? ` @ ${identity2.ref}` : ""}`;
4320
- const contents = identity2?.boundToReading ? " \xB7 contents signed" : identity2?.bindingRefused ? ` \xB7 contents not signed: ${identity2.bindingRefused}` : "";
4321
- if (identity2?.trust === "trusted") return `${green("signed")} ${dim(`${where} \xB7 a trusted build${contents}`)}`;
4322
- if (identity2?.trust === "verified") {
4911
+ function describeIdentity(identity3, hint) {
4912
+ const shown = (text) => visibleControls(text);
4913
+ const where = shown(`${identity3?.repository ?? ""}${identity3?.ref ? ` @ ${identity3.ref}` : ""}`);
4914
+ const contents = identity3?.boundToReading ? " \xB7 contents signed" : identity3?.bindingRefused ? ` \xB7 contents not signed: ${shown(identity3.bindingRefused)}` : "";
4915
+ if (identity3?.trust === "trusted") return `${green("signed")} ${dim(`${where} \xB7 a trusted build${contents}`)}`;
4916
+ if (identity3?.trust === "verified") {
4323
4917
  return `${yellow("signed")} ${dim(`${where} \xB7 not a build this organization lists as trusted${contents}`)}`;
4324
4918
  }
4325
- if (identity2?.rejected) return `${red("build token refused")} ${dim(identity2.rejected)}`;
4919
+ if (identity3?.rejected) return `${red("build token refused")} ${dim(shown(identity3.rejected))}`;
4326
4920
  return hint ? dim(`unsigned: ${hint}`) : void 0;
4327
4921
  }
4328
4922
  function inferProject(projectRoot) {
@@ -4348,6 +4942,7 @@ function refuseApiUrl(apiUrl) {
4348
4942
  if (url.protocol === "https:" || url.protocol === "http:" && loopback) return void 0;
4349
4943
  return `the control plane has to be reached over https (http only on this machine), not ${url.protocol}`;
4350
4944
  }
4945
+ var UNSENDABLE2 = /[\r\n\0]/;
4351
4946
  async function runPush(options) {
4352
4947
  const apiUrl = (options.apiUrl ?? process.env["NULLADRIFT_API_URL"] ?? "").replace(/\/+$/, "");
4353
4948
  const token = options.token ?? process.env["NULLADRIFT_TOKEN"] ?? "";
@@ -4369,6 +4964,17 @@ async function runPush(options) {
4369
4964
  `);
4370
4965
  return EXIT_INCOMPLETE;
4371
4966
  }
4967
+ if (UNSENDABLE2.test(token)) {
4968
+ process.stderr.write(
4969
+ `${red("push refused:")} the collector token (${options.token !== void 0 ? "--token" : "NULLADRIFT_TOKEN"}) contains a line break or NUL; a secret saved with a trailing newline is the usual cause
4970
+ `
4971
+ );
4972
+ return EXIT_INCOMPLETE;
4973
+ }
4974
+ if (options.token !== void 0) {
4975
+ process.stderr.write(`${yellow("note:")} --token is visible to other processes on this machine; prefer NULLADRIFT_TOKEN.
4976
+ `);
4977
+ }
4372
4978
  const result = await captureAll({
4373
4979
  projectRoot: options.projectRoot,
4374
4980
  configFiles: options.configFiles,
@@ -4416,8 +5022,14 @@ ${dim(`Looked in: ${looked}`)}
4416
5022
  acquireBuildToken(),
4417
5023
  acquireReadingToken(readingAudience(readingAudienceBase(apiUrl), digest2))
4418
5024
  ]);
4419
- const buildToken = build && "token" in build ? build.token : void 0;
4420
- const readingToken = reading && "token" in reading ? reading.token : void 0;
5025
+ const sendable = (candidate, what) => {
5026
+ if (candidate === void 0 || !UNSENDABLE2.test(candidate)) return candidate;
5027
+ process.stderr.write(`${yellow("note:")} ${what} contains a line break or NUL, so it was left out; the reading goes unsigned.
5028
+ `);
5029
+ return void 0;
5030
+ };
5031
+ const buildToken = sendable(build && "token" in build ? build.token : void 0, "the identity token (NULLADRIFT_ID_TOKEN)");
5032
+ const readingToken = sendable(reading && "token" in reading ? reading.token : void 0, "the reading token");
4421
5033
  let response;
4422
5034
  try {
4423
5035
  response = await fetch(`${apiUrl}/api/v1/ingest`, {
@@ -4434,7 +5046,9 @@ ${dim(`Looked in: ${looked}`)}
4434
5046
  signal: AbortSignal.timeout(options.timeoutMs)
4435
5047
  });
4436
5048
  } catch (error) {
4437
- process.stderr.write(`${red("could not reach the control plane:")} ${error.message}
5049
+ let message = error.message;
5050
+ for (const secret of [token, buildToken, readingToken]) if (secret) message = message.split(secret).join("[redacted]");
5051
+ process.stderr.write(`${red("could not reach the control plane:")} ${message}
4438
5052
  `);
4439
5053
  return EXIT_INCOMPLETE;
4440
5054
  }
@@ -4447,18 +5061,26 @@ ${dim(`Looked in: ${looked}`)}
4447
5061
  const verdict = await response.json();
4448
5062
  const lines = [""];
4449
5063
  const mark = verdict.verdict === "clean" ? green("\u2713") : verdict.verdict === "drift" ? yellow("!") : red("\u2717");
4450
- lines.push(`${mark} ${bold(verdict.verdict)} ${dim(`\xB7 ${servers.length} server(s) \xB7 reading ${verdict.readingId.slice(0, 8)}`)}`);
4451
- const identity2 = describeIdentity(verdict.identity, build && "hint" in build ? build.hint : void 0);
4452
- if (identity2) lines.push(` ${identity2}`);
5064
+ const shown = (text) => visibleControls(String(text ?? ""));
5065
+ lines.push(`${mark} ${bold(shown(verdict.verdict))} ${dim(`\xB7 ${servers.length} server(s) \xB7 reading ${shown(verdict.readingId).slice(0, 8)}`)}`);
5066
+ const identity3 = describeIdentity(verdict.identity, build && "hint" in build ? build.hint : void 0);
5067
+ if (identity3) lines.push(` ${identity3}`);
4453
5068
  for (const change2 of verdict.changes) {
4454
- lines.push(` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${bold(change2.server)}${change2.member ? dim(`/${change2.member}`) : ""} ${change2.summary}`);
5069
+ lines.push(` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${bold(shown(change2.server))}${change2.member ? dim(`/${shown(change2.member)}`) : ""} ${shown(change2.summary)}`);
4455
5070
  }
4456
5071
  for (const reason of verdict.decision.reasons) {
4457
- lines.push(` ${red("blocked")} ${dim(reason.code)} ${reason.message}`);
5072
+ lines.push(` ${red("blocked")} ${dim(shown(reason.code))} ${shown(reason.message)}`);
4458
5073
  }
4459
- if (verdict.verdict !== "clean") lines.push("", dim(`Review it at ${verdict.url}`));
5074
+ if (verdict.verdict !== "clean") lines.push("", dim(`Review it at ${shown(verdict.url)}`));
4460
5075
  lines.push("");
4461
5076
  process.stdout.write(lines.join("\n"));
5077
+ if (result.partial.length > 0 && options.allowPartial !== true) {
5078
+ process.stderr.write(
5079
+ `${yellow("incomplete:")} ${result.partial.map((entry) => visibleControls(entry.server)).join(", ")} could not be read in full. Pass --allow-partial to accept that.
5080
+ `
5081
+ );
5082
+ return EXIT_INCOMPLETE;
5083
+ }
4462
5084
  return verdict.exitCode === 0 ? EXIT_CLEAN : verdict.exitCode === 1 ? EXIT_DRIFT : EXIT_INCOMPLETE;
4463
5085
  }
4464
5086
 
@@ -4513,11 +5135,11 @@ async function runReview(options) {
4513
5135
  provenance: options.provenance,
4514
5136
  userConfigs: options.userConfigs
4515
5137
  });
4516
- const changes = diffLockfiles(committed, result.lock);
5138
+ const changes = compareWithLock(committed, result);
4517
5139
  if (changes.length === 0) {
4518
5140
  process.stdout.write(`${green(`\u2713 nothing to review; ${options.lockPath} is up to date`)}
4519
5141
  `);
4520
- return result.unreachable.length > 0 && !options.allowUnreachable ? EXIT_INCOMPLETE : EXIT_CLEAN;
5142
+ return result.unreachable.length > 0 && !options.allowUnreachable || result.partial.length > 0 && !options.allowPartial ? EXIT_INCOMPLETE : EXIT_CLEAN;
4521
5143
  }
4522
5144
  const grouped = /* @__PURE__ */ new Map();
4523
5145
  for (const change2 of changes) {
@@ -4558,9 +5180,18 @@ ${context.length > 0 ? `${context.join("\n")}
4558
5180
  continue;
4559
5181
  }
4560
5182
  accepted += 1;
4561
- const fresh = result.lock.subjects[serverName];
5183
+ let fresh = result.lock.subjects[serverName];
5184
+ const pin = committed.subjects[serverName]?.provenance;
5185
+ const displaced = result.displaced.some((moved) => moved.server === serverName);
5186
+ if (fresh && fresh.provenance === void 0 && pin !== void 0 && result.unverified.includes(serverName) && !displaced) {
5187
+ fresh = { ...fresh, provenance: pin };
5188
+ }
4562
5189
  if (fresh) next.subjects[serverName] = fresh;
4563
5190
  else delete next.subjects[serverName];
5191
+ const unaudited = { ...next.unaudited };
5192
+ if (!fresh && result.unaudited[serverName] !== void 0) unaudited[serverName] = result.unaudited[serverName];
5193
+ else delete unaudited[serverName];
5194
+ next.unaudited = Object.keys(unaudited).length > 0 ? unaudited : void 0;
4564
5195
  for (const change2 of serverChanges) {
4565
5196
  if (change2.kind === "server.renamed" && typeof change2.before === "string") delete next.subjects[change2.before];
4566
5197
  }
@@ -4577,6 +5208,7 @@ ${green(`\u2713 accepted ${accepted} server(s) into ${options.lockPath}`)}
4577
5208
  if (declined > 0) process.stdout.write(`${yellow(`${declined} server(s) left unaccepted; \`check\` will still fail on them.`)}
4578
5209
  `);
4579
5210
  if (result.unreachable.length > 0 && !options.allowUnreachable) return EXIT_INCOMPLETE;
5211
+ if (result.partial.length > 0 && !options.allowPartial) return EXIT_INCOMPLETE;
4580
5212
  return declined > 0 ? EXIT_DRIFT : EXIT_CLEAN;
4581
5213
  }
4582
5214
 
@@ -4598,6 +5230,7 @@ ${bold("Options")}
4598
5230
  --config <path> audit this config file too; repeatable
4599
5231
  --timeout <ms> per-server timeout (default: ${DEFAULT_TIMEOUT_MS2})
4600
5232
  --allow-unreachable a server that cannot be reached warns instead of failing
5233
+ --allow-partial a server whose tool list could not be read in full warns instead of failing
4601
5234
  --no-provenance do not look up what each stdio server runs (air-gapped runs)
4602
5235
  --user-configs also pin servers from your own configs (~/.claude.json, Claude Desktop, ...)
4603
5236
  --json machine-readable output (check)
@@ -4629,6 +5262,7 @@ async function main() {
4629
5262
  config: { type: "string", multiple: true },
4630
5263
  timeout: { type: "string" },
4631
5264
  "allow-unreachable": { type: "boolean", default: false },
5265
+ "allow-partial": { type: "boolean", default: false },
4632
5266
  "no-provenance": { type: "boolean", default: false },
4633
5267
  "user-configs": { type: "boolean", default: false },
4634
5268
  json: { type: "boolean", default: false },
@@ -4667,13 +5301,14 @@ async function main() {
4667
5301
  `);
4668
5302
  return EXIT_INCOMPLETE;
4669
5303
  }
4670
- const projectRoot = resolve5(values.cwd ?? process.cwd());
5304
+ const projectRoot = resolve6(values.cwd ?? process.cwd());
4671
5305
  const options = {
4672
5306
  projectRoot,
4673
- lockPath: resolve5(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
5307
+ lockPath: resolve6(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
4674
5308
  configFiles: values.config ?? [],
4675
5309
  timeoutMs,
4676
5310
  allowUnreachable: values["allow-unreachable"],
5311
+ allowPartial: values["allow-partial"],
4677
5312
  format: values.sarif ? "sarif" : values.json ? "json" : "human",
4678
5313
  sarifSteering: values["sarif-steering"] === true,
4679
5314
  comment: values.comment,