nulladrift 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { parseArgs } from "util";
5
- import { resolve as resolve6 } from "path";
5
+ import { resolve as resolve7 } from "path";
6
6
 
7
7
  // ../core/src/changes.ts
8
8
  var CHANGE_KINDS = [
@@ -99,7 +99,8 @@ function serversThatShippedNothing(changes) {
99
99
  const moved = /* @__PURE__ */ new Set();
100
100
  const versioned = /* @__PURE__ */ new Set();
101
101
  for (const change2 of changes) {
102
- moved.add(change2.server);
102
+ const uncaptured = change2.kind === "server.removed" || change2.kind === "server.added" && change2.after === void 0;
103
+ if (!uncaptured) moved.add(change2.server);
103
104
  if (change2.kind === "server.identity.changed") versioned.add(change2.server);
104
105
  }
105
106
  return [...moved].filter((server2) => !versioned.has(server2)).sort();
@@ -446,11 +447,17 @@ function redactArgs(args) {
446
447
  function looksLikeAnOperand(value) {
447
448
  return value.startsWith("@") || value.includes("/") || /\.(m?[jt]s|cjs|py|json|ya?ml|toml|sh|exe)$/i.test(value);
448
449
  }
450
+ var REVISION_WORDS = /* @__PURE__ */ new Set(["raw", "blob", "blobs", "tree", "trees", "commit", "commits", "archive", "src", "+"]);
451
+ var COMMIT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
449
452
  function redactPath(pathname, options = {}) {
453
+ let revisionPath = false;
450
454
  return pathname.split("/").map((segment) => {
455
+ const afterRevisionWord = revisionPath;
456
+ if (REVISION_WORDS.has(decoded(segment).toLowerCase())) revisionPath = true;
451
457
  if (segment === "" || PLACEHOLDER.test(decoded(segment))) return segment;
452
458
  if (looksRandom(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)))
459
+ const commit = afterRevisionWord && COMMIT_ID.test(segment);
460
+ if (!options.contentAddressed && !commit && (/^[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
461
  return REDACTED;
455
462
  return redactFormats(segment);
456
463
  }).join("/");
@@ -465,26 +472,65 @@ var MAX_REF_DEPTH = 32;
465
472
  var MAX_VISIT_DEPTH = 12;
466
473
  var MAX_FACTS = 5e3;
467
474
  var MAX_RESOLUTIONS = 1e5;
475
+ var MAX_MERGED_KEYS = 1e5;
468
476
  var states = /* @__PURE__ */ new WeakMap();
477
+ function freshState() {
478
+ return { refs: /* @__PURE__ */ new Map(), nodes: /* @__PURE__ */ new WeakMap(), spent: 0, merged: 0 };
479
+ }
480
+ function beginWalk(root) {
481
+ if (root !== null && typeof root === "object") states.delete(root);
482
+ }
469
483
  function stateOf(root) {
470
- if (root === null || typeof root !== "object") return { refs: /* @__PURE__ */ new Map(), spent: 0 };
484
+ if (root === null || typeof root !== "object") return freshState();
471
485
  let state = states.get(root);
472
486
  if (!state) {
473
- state = { refs: /* @__PURE__ */ new Map(), spent: 0 };
487
+ state = freshState();
474
488
  states.set(root, state);
475
489
  }
476
490
  return state;
477
491
  }
492
+ var LOWER_BOUNDS = /* @__PURE__ */ new Set(["minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties", "minContains"]);
493
+ var UPPER_BOUNDS = /* @__PURE__ */ new Set(["maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties", "maxContains"]);
494
+ var ANNOTATIONS = /* @__PURE__ */ new Set(["title", "description", "default", "examples", "example", "$comment", "$id", "$schema", "$anchor", "deprecated", "readOnly", "writeOnly"]);
495
+ var shadows = /* @__PURE__ */ new WeakMap();
496
+ function shadowedIn(effective) {
497
+ return shadows.get(effective);
498
+ }
499
+ function remember(into, key, value) {
500
+ const held = into.get(key);
501
+ if (held) held.push(value);
502
+ else into.set(key, [value]);
503
+ }
504
+ function canonicalOrUndefined(value) {
505
+ try {
506
+ return canonicalize(value);
507
+ } catch {
508
+ return void 0;
509
+ }
510
+ }
511
+ function intersectEnum(held, value) {
512
+ const allowed = new Set(value.map(canonicalOrUndefined));
513
+ return held.filter((member) => allowed.has(canonicalOrUndefined(member)));
514
+ }
515
+ function intersectTypes(held, value) {
516
+ const list = (types) => typeof types === "string" ? /* @__PURE__ */ new Set([types]) : Array.isArray(types) ? new Set(types.filter((entry) => typeof entry === "string")) : void 0;
517
+ const a = list(held);
518
+ const b = list(value);
519
+ if (a === void 0 || b === void 0) return held;
520
+ const both = [...a].filter((type) => b.has(type) || type === "integer" && b.has("number"));
521
+ if (a.has("number") && b.has("integer") && !both.includes("integer")) both.push("integer");
522
+ return both.length === 1 ? both[0] : both;
523
+ }
478
524
  function asObject(value) {
479
525
  return value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value) ? value : void 0;
480
526
  }
481
527
  function decodeToken(token) {
482
- let decoded2 = token;
528
+ let decoded3 = token;
483
529
  try {
484
- decoded2 = decodeURIComponent(token);
530
+ decoded3 = decodeURIComponent(token);
485
531
  } catch {
486
532
  }
487
- return decoded2.replace(/~1/g, "/").replace(/~0/g, "~");
533
+ return decoded3.replace(/~1/g, "/").replace(/~0/g, "~");
488
534
  }
489
535
  function resolvePointer(root, ref) {
490
536
  if (!ref.startsWith("#")) return void 0;
@@ -503,25 +549,68 @@ function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth
503
549
  if (object === void 0) return void 0;
504
550
  if (depth > MAX_REF_DEPTH) return object;
505
551
  const state = stateOf(root);
506
- if (depth === 0) state.spent = 0;
507
- if (++state.spent > MAX_RESOLUTIONS) return object;
552
+ if (depth === 0) {
553
+ const known = state.nodes.get(object);
554
+ if (known !== void 0) return known;
555
+ state.spent = 0;
556
+ }
557
+ if (++state.spent > MAX_RESOLUTIONS || state.merged > MAX_MERGED_KEYS) {
558
+ if (depth === 0) state.nodes.set(object, object);
559
+ return object;
560
+ }
508
561
  const out = /* @__PURE__ */ Object.create(null);
562
+ let shadow;
563
+ const shadowed = () => shadow ??= { keywords: /* @__PURE__ */ new Map(), properties: /* @__PURE__ */ new Map() };
564
+ let ownsProperties = false;
509
565
  const merge = (source) => {
510
- for (const [key, value] of Object.entries(source)) {
566
+ if (state.merged > MAX_MERGED_KEYS) return;
567
+ const entries = Object.entries(source);
568
+ state.merged += entries.length;
569
+ for (const [key, value] of entries) {
511
570
  if (key === "$ref" || key === "allOf") continue;
512
571
  if (key === "properties") {
513
- const merged = Object.assign(/* @__PURE__ */ Object.create(null), asObject(out["properties"]) ?? {});
514
- for (const [name, schema] of Object.entries(asObject(value) ?? {})) {
572
+ const incoming = asObject(value);
573
+ const held = asObject(out["properties"]);
574
+ if (held === void 0) {
575
+ out["properties"] = incoming ?? /* @__PURE__ */ Object.create(null);
576
+ continue;
577
+ }
578
+ if (incoming === void 0 || incoming === held) continue;
579
+ const names = Object.keys(incoming);
580
+ if (names.length === 0) continue;
581
+ const merged = ownsProperties ? held : Object.assign(/* @__PURE__ */ Object.create(null), held);
582
+ if (!ownsProperties) state.merged += Object.keys(held).length;
583
+ state.merged += names.length;
584
+ ownsProperties = true;
585
+ for (const name of names) {
586
+ const schema = incoming[name];
515
587
  if (!Object.hasOwn(merged, name)) Object.defineProperty(merged, name, { value: schema, enumerable: true, writable: true, configurable: true });
588
+ else if (merged[name] !== schema) remember(shadowed().properties, name, schema);
516
589
  }
517
590
  out["properties"] = merged;
518
591
  } else if (key === "required" && Array.isArray(value)) {
519
592
  const already = Array.isArray(out["required"]) ? out["required"] : [];
593
+ state.merged += already.length + value.length;
520
594
  out["required"] = [...new Set([...already, ...value].filter((entry) => typeof entry === "string"))];
521
595
  } else if (!Object.hasOwn(out, key)) {
522
596
  out[key] = value;
597
+ } else {
598
+ const held = out[key];
599
+ if (held === value) continue;
600
+ if (typeof held === "number" && typeof value === "number" && LOWER_BOUNDS.has(key)) out[key] = Math.max(held, value);
601
+ else if (typeof held === "number" && typeof value === "number" && UPPER_BOUNDS.has(key)) out[key] = Math.min(held, value);
602
+ else if (key === "enum" && Array.isArray(held) && Array.isArray(value)) {
603
+ state.merged += held.length + value.length;
604
+ out[key] = intersectEnum(held, value);
605
+ } else if (key === "type") out[key] = intersectTypes(held, value);
606
+ else if (!ANNOTATIONS.has(key)) remember(shadowed().keywords, key, value);
523
607
  }
524
608
  }
609
+ const inherited = shadows.get(source);
610
+ if (inherited) {
611
+ for (const [key, values] of inherited.keywords) for (const value of values) remember(shadowed().keywords, key, value);
612
+ for (const [name, values] of inherited.properties) for (const value of values) remember(shadowed().properties, name, value);
613
+ }
525
614
  };
526
615
  merge(object);
527
616
  const ref = object["$ref"];
@@ -541,9 +630,23 @@ function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth
541
630
  if (resolved) merge(resolved);
542
631
  }
543
632
  }
633
+ if (shadow) shadows.set(out, shadow);
634
+ if (depth === 0) state.nodes.set(object, out);
544
635
  return out;
545
636
  }
637
+ var entryLists = /* @__PURE__ */ new WeakMap();
638
+ var alternativeLists = /* @__PURE__ */ new WeakMap();
639
+ function entriesOf(object) {
640
+ let entries = entryLists.get(object);
641
+ if (!entries) {
642
+ entries = Object.entries(object);
643
+ entryLists.set(object, entries);
644
+ }
645
+ return entries;
646
+ }
546
647
  function alternatives(object) {
648
+ const known = alternativeLists.get(object);
649
+ if (known) return known;
547
650
  const branches = [];
548
651
  for (const keyword of ["anyOf", "oneOf"]) {
549
652
  const value = object[keyword];
@@ -553,6 +656,7 @@ function alternatives(object) {
553
656
  for (const keyword of ["then", "else", "not"]) {
554
657
  if (object[keyword] !== void 0) branches.push({ label: keyword, schema: object[keyword] });
555
658
  }
659
+ alternativeLists.set(object, branches);
556
660
  return branches;
557
661
  }
558
662
 
@@ -569,8 +673,25 @@ function resolveBehavior(annotations2) {
569
673
  function isEscalation(previous, next) {
570
674
  return previous.readOnly && !next.readOnly || !previous.destructive && next.destructive || previous.idempotent && !next.idempotent || !previous.openWorld && next.openWorld;
571
675
  }
572
- var DATA_KEYWORDS = /* @__PURE__ */ new Set(["const", "default", "enum", "examples", "example"]);
573
- var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
676
+ var SCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
677
+ "items",
678
+ "prefixItems",
679
+ "additionalItems",
680
+ "contains",
681
+ "allOf",
682
+ "anyOf",
683
+ "oneOf",
684
+ "not",
685
+ "if",
686
+ "then",
687
+ "else",
688
+ "additionalProperties",
689
+ "unevaluatedProperties",
690
+ "unevaluatedItems",
691
+ "propertyNames",
692
+ "contentSchema"
693
+ ]);
694
+ var NAMED_SCHEMAS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas", "dependencies"]);
574
695
  function normalizeSchema(value) {
575
696
  return normalizeNode(value, false);
576
697
  }
@@ -587,47 +708,54 @@ function normalizeNode(value, namesOnly) {
587
708
  out[key] = [...member].sort();
588
709
  continue;
589
710
  }
590
- if (DATA_KEYWORDS.has(key)) {
591
- out[key] = member;
592
- continue;
593
- }
594
- out[key] = normalizeNode(member, NAMED_SCHEMAS.has(key));
711
+ if (NAMED_SCHEMAS.has(key)) out[key] = normalizeNode(member, true);
712
+ else if (SCHEMA_KEYWORDS.has(key)) out[key] = normalizeNode(member, false);
713
+ else out[key] = member;
595
714
  }
596
715
  return out;
597
716
  }
598
717
  function extractHeaderParams(schema) {
599
718
  const found = [];
600
719
  let budget = MAX_HEADER_VISITS;
720
+ let reads = 0;
601
721
  const walk = (node, path, depth, refsOnPath) => {
602
722
  if (depth > MAX_VISIT_DEPTH) return;
603
723
  if (budget <= 0) return;
604
724
  budget -= 1;
605
725
  const object = effectiveSchema(node, schema);
606
726
  if (!object) return;
727
+ const descend = () => budget > 0 && depth + 1 <= MAX_VISIT_DEPTH;
607
728
  const properties = asObject(object["properties"]);
608
729
  if (properties) {
609
- for (const [name, child] of Object.entries(properties)) {
730
+ for (const [name, child] of entriesOf(properties)) {
731
+ if (++reads > MAX_HEADER_READS) return;
610
732
  const resolved = effectiveSchema(child, schema);
611
733
  if (!resolved) continue;
612
734
  const header = resolved["x-mcp-header"];
613
735
  if (typeof header === "string" && header.length > 0) found.push(`${[...path, name].join(".")} -> ${header}`);
614
736
  const ref = asObject(child)?.["$ref"];
615
737
  if (typeof ref === "string" && refsOnPath.has(ref)) continue;
738
+ if (!descend()) continue;
616
739
  walk(child, [...path, name], depth + 1, typeof ref === "string" ? /* @__PURE__ */ new Set([...refsOnPath, ref]) : refsOnPath);
617
740
  }
618
741
  }
619
742
  for (const branch of alternatives(object)) {
743
+ if (++reads > MAX_HEADER_READS) return;
620
744
  const ref = asObject(branch.schema)?.["$ref"];
621
745
  if (typeof ref === "string" && refsOnPath.has(ref)) continue;
746
+ if (!descend()) continue;
622
747
  walk(branch.schema, path, depth + 1, typeof ref === "string" ? /* @__PURE__ */ new Set([...refsOnPath, ref]) : refsOnPath);
623
748
  }
624
749
  };
625
750
  const rootRef = asObject(schema)?.["$ref"];
751
+ beginWalk(schema);
626
752
  walk(schema, [], 0, new Set(typeof rootRef === "string" ? [rootRef] : []));
627
753
  if (budget <= 0) found.push(`(schema too large to scan for headers past ${MAX_HEADER_VISITS} nodes)`);
754
+ if (reads > MAX_HEADER_READS) found.push(`(schema too large to scan for headers past ${MAX_HEADER_READS} reads)`);
628
755
  return [...new Set(found)].sort();
629
756
  }
630
757
  var MAX_HEADER_VISITS = 2e4;
758
+ var MAX_HEADER_READS = 50 * MAX_HEADER_VISITS;
631
759
  function stripIgnoredMeta(meta, ignoredPrefixes) {
632
760
  if (meta === null || meta === void 0 || typeof meta !== "object" || Array.isArray(meta)) return void 0;
633
761
  const out = /* @__PURE__ */ Object.create(null);
@@ -693,7 +821,6 @@ var RULES = [
693
821
  // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
694
822
  { kind: "code-eval", severity: "critical", name: /(^|_)(eval|evaluate|run_code|exec_code|interpret|compile)(_|$)/, arg: /^code$|(^|_)(source_code|code_to_run|js_code|python_code|expression|program|snippet)(_|$)/ },
695
823
  { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
696
- { kind: "file-write", severity: "high", name: /(^|_)(write|create_file|put_file|save|delete|remove|unlink|rename|move|copy|chmod|mkdir|rmdir|edit)(_|$)/, arg: /(^|_)(contents|content|data|destination|dest_path|target_path)(_|$)/ },
697
824
  { kind: "network-egress", severity: "high", name: /(^|_)(fetch|request|http|curl|download|upload|post|webhook|navigate|browse|send)(_|$)/, arg: /(^|_)(url|uri|endpoint|host|hostname|webhook|callback)(_|$)/ },
698
825
  // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
699
826
  // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
@@ -702,8 +829,29 @@ var RULES = [
702
829
  { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
703
830
  { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
704
831
  { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
705
- { kind: "file-read", severity: "low", name: /(^|_)(read|read_file|cat|open|load|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
832
+ // `read`, `open` and `load` are not here; see `fileRead` below.
833
+ { kind: "file-read", severity: "low", name: /(^|_)(read_file|cat|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
706
834
  ];
835
+ var FILE_ONLY_VERBS = /(^|_)(write|create_file|put_file|unlink|chmod|chown|mkdir|rmdir|truncate)(_|$)/;
836
+ var CHANGING_VERBS = /(^|_)(create|save|delete|remove|rename|move|copy|edit|append|put|overwrite|replace|patch)(_|$)/;
837
+ var FILE_NOUNS = /(^|_)(file|files|filename|dir|dirs|directory|directories|folder|folders|path|paths)(_|$)/;
838
+ var PATH_ARGS = /^(path|paths|file|files|filename|filepath|file_path|directory|dir|folder|source_path)$|(^|_)(path|filepath|filename)$/;
839
+ var DESTINATION_ARGS = /(^|_)(destination|dest|dest_path|target_path|output_path|out_path)(_|$)/;
840
+ var CONTENT_ARGS = /(^|_)(contents|content|data|text|body)$/;
841
+ function fileWrite(name, args) {
842
+ if (FILE_ONLY_VERBS.test(name)) return "name";
843
+ const path = args.find(([, normalized]) => PATH_ARGS.test(normalized));
844
+ if (CHANGING_VERBS.test(name) && (FILE_NOUNS.test(name) || path)) return "name";
845
+ const destination = args.find(([, normalized]) => DESTINATION_ARGS.test(normalized));
846
+ if (destination) return `arg:${destination[0]}`;
847
+ const content = args.find(([, normalized]) => CONTENT_ARGS.test(normalized));
848
+ if (content && path) return `arg:${content[0]}`;
849
+ return void 0;
850
+ }
851
+ var READING_VERBS = /(^|_)(read|open|load)(_|$)/;
852
+ function fileRead(name) {
853
+ return READING_VERBS.test(name) && FILE_NOUNS.test(name);
854
+ }
707
855
  var CONFUSABLES = {
708
856
  "\u0430": "a",
709
857
  "\u0435": "e",
@@ -730,19 +878,43 @@ var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g
730
878
  function normalize(identifier) {
731
879
  return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
732
880
  }
733
- function argumentNames(inputSchema, depth = 0) {
734
- if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
735
- const node = inputSchema;
736
- const names = [];
737
- const properties = node.properties;
738
- if (typeof properties === "object" && properties !== null) {
739
- for (const [name, child] of Object.entries(properties)) {
740
- names.push(name);
741
- names.push(...argumentNames(child, depth + 1));
881
+ var MAX_ARGUMENT_READS = 10 * MAX_FACTS;
882
+ function argumentNames(inputSchema) {
883
+ const root = inputSchema;
884
+ const names = /* @__PURE__ */ new Set();
885
+ let budget = MAX_ARGUMENT_READS;
886
+ const walk = (node, depth) => {
887
+ if (budget <= 0) return false;
888
+ budget -= 1;
889
+ const object = effectiveSchema(node, root);
890
+ if (!object) return true;
891
+ const deeper = depth < MAX_VISIT_DEPTH;
892
+ const into = (child) => deeper && child !== null && typeof child === "object" ? walk(child, depth + 1) : budget > 0;
893
+ const properties = asObject(object["properties"]);
894
+ if (properties) {
895
+ for (const [name, child] of entriesOf(properties)) {
896
+ if (--budget <= 0) return false;
897
+ names.add(name);
898
+ if (!into(child)) return false;
899
+ }
742
900
  }
743
- }
744
- if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
745
- return names;
901
+ for (const keyword of ["items", "prefixItems"]) {
902
+ const value = object[keyword];
903
+ if (Array.isArray(value)) {
904
+ for (const child of value) if (!into(child)) return false;
905
+ } else if (!into(value)) return false;
906
+ }
907
+ if (!into(object["additionalProperties"])) return false;
908
+ const patternProperties = asObject(object["patternProperties"]);
909
+ if (patternProperties) {
910
+ for (const [, child] of entriesOf(patternProperties)) if (!into(child)) return false;
911
+ }
912
+ for (const branch of alternatives(object)) if (!into(branch.schema)) return false;
913
+ return true;
914
+ };
915
+ beginWalk(root);
916
+ walk(root, 0);
917
+ return [...names];
746
918
  }
747
919
  function toolCapabilities(tool2) {
748
920
  const subject = objectOr(tool2);
@@ -758,6 +930,9 @@ function toolCapabilities(tool2) {
758
930
  const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
759
931
  if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
760
932
  }
933
+ if (!found.has("file-read") && fileRead(name)) found.set("file-read", { kind: "file-read", severity: "low", evidence: "name" });
934
+ const writes = fileWrite(name, args);
935
+ if (writes) found.set("file-write", { kind: "file-write", severity: "high", evidence: writes });
761
936
  return [...found.values()].sort(
762
937
  (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
763
938
  );
@@ -778,111 +953,297 @@ function surfaceCapabilities(tools) {
778
953
  }
779
954
 
780
955
  // ../core/src/diff/schema.ts
781
- function numberAt(node, key) {
782
- const value = node[key];
783
- return typeof value === "number" ? value : void 0;
784
- }
785
- function collectFacts(schema) {
956
+ var LOWER_BOUNDS2 = ["minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties", "minContains"];
957
+ var UPPER_BOUNDS2 = ["maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties", "maxContains"];
958
+ var OPAQUE = [
959
+ "pattern",
960
+ "format",
961
+ "multipleOf",
962
+ "uniqueItems",
963
+ "not",
964
+ "if",
965
+ "contains",
966
+ "propertyNames",
967
+ "dependentRequired",
968
+ "dependentSchemas",
969
+ "dependencies",
970
+ "unevaluatedProperties",
971
+ "unevaluatedItems",
972
+ "additionalItems"
973
+ ];
974
+ var OPEN_WHEN_EMPTY = /* @__PURE__ */ new Set(["unevaluatedProperties", "unevaluatedItems", "additionalItems", "propertyNames"]);
975
+ var SLOT_KEYWORDS = ["items", "anyOf", "oneOf", "then", "else"];
976
+ var CONSIDERED = /* @__PURE__ */ new Set([...LOWER_BOUNDS2, ...UPPER_BOUNDS2, ...OPAQUE, ...SLOT_KEYWORDS]);
977
+ var MEMBERS = /* @__PURE__ */ new Set(["properties", "patternProperties", "prefixItems"]);
978
+ function isOpen(value) {
979
+ if (value === true) return true;
980
+ const object = asObject(value);
981
+ return object !== void 0 && Object.keys(object).length === 0;
982
+ }
983
+ function isVacuous(keyword, value) {
984
+ if (value === false) return keyword === "uniqueItems" || keyword === "exclusiveMinimum" || keyword === "exclusiveMaximum";
985
+ return OPEN_WHEN_EMPTY.has(keyword) && isOpen(value);
986
+ }
987
+ function typesOf(values) {
988
+ const types = /* @__PURE__ */ new Set();
989
+ for (const value of values) {
990
+ if (value === null) types.add("null");
991
+ else if (Array.isArray(value)) types.add("array");
992
+ else if (typeof value === "number") types.add(Number.isInteger(value) ? "integer" : "number");
993
+ else types.add(typeof value);
994
+ }
995
+ return types;
996
+ }
997
+ function ownValues(object) {
998
+ let values = Array.isArray(object["enum"]) ? object["enum"] : void 0;
999
+ const consts = [...Object.hasOwn(object, "const") ? [object["const"]] : [], ...shadowedIn(object)?.keywords.get("const") ?? []];
1000
+ for (const value of consts) {
1001
+ const key = canonicalize(value);
1002
+ values = values === void 0 ? [value] : values.filter((member) => canonicalize(member) === key);
1003
+ }
1004
+ const typeValue = object["type"];
1005
+ let types = typeof typeValue === "string" ? /* @__PURE__ */ new Set([typeValue]) : Array.isArray(typeValue) ? new Set(typeValue.filter((entry) => typeof entry === "string")) : void 0;
1006
+ if (types === void 0 && values !== void 0) types = typesOf(values);
1007
+ return { types, members: values === void 0 ? void 0 : new Set(values.map((member) => canonicalize(member))) };
1008
+ }
1009
+ function unionOfBranches(branches, root) {
1010
+ let types = /* @__PURE__ */ new Set();
1011
+ let members = /* @__PURE__ */ new Set();
1012
+ let counted = 0;
1013
+ for (const branch of branches) {
1014
+ if (branch === false) continue;
1015
+ const object = effectiveSchema(branch, root);
1016
+ if (object === void 0) return {};
1017
+ const own2 = ownValues(object);
1018
+ const onlyNull = own2.members === void 0 ? own2.types?.size === 1 && own2.types.has("null") : own2.members.size === 1 && own2.members.has("null");
1019
+ if (onlyNull) continue;
1020
+ counted += 1;
1021
+ if (types) {
1022
+ if (own2.types) for (const type of own2.types) types.add(type);
1023
+ else types = void 0;
1024
+ }
1025
+ if (members) {
1026
+ if (own2.members) for (const member of own2.members) members.add(member);
1027
+ else members = void 0;
1028
+ }
1029
+ }
1030
+ return counted === 0 ? {} : { types, members };
1031
+ }
1032
+ var constraintCache = /* @__PURE__ */ new WeakMap();
1033
+ function constraintsOf(object, root) {
1034
+ const key = root !== null && typeof root === "object" ? root : constraintCache;
1035
+ let cache = constraintCache.get(key);
1036
+ if (!cache) {
1037
+ cache = /* @__PURE__ */ new WeakMap();
1038
+ constraintCache.set(key, cache);
1039
+ }
1040
+ const known = cache.get(object);
1041
+ if (known) return known;
1042
+ let { types, members } = ownValues(object);
1043
+ if (types === void 0 || members === void 0) {
1044
+ const anyOf = Array.isArray(object["anyOf"]) ? object["anyOf"] : void 0;
1045
+ const oneOf = Array.isArray(object["oneOf"]) ? object["oneOf"] : void 0;
1046
+ const branches = anyOf && !oneOf ? anyOf : oneOf && !anyOf ? oneOf : void 0;
1047
+ if (branches) {
1048
+ const union = unionOfBranches(branches, root);
1049
+ types ??= union.types;
1050
+ members ??= union.members;
1051
+ }
1052
+ }
1053
+ const lower = /* @__PURE__ */ new Map();
1054
+ const upper = /* @__PURE__ */ new Map();
1055
+ const opaque = /* @__PURE__ */ new Map();
1056
+ const constrain = (keyword, value) => {
1057
+ if (isVacuous(keyword, value)) return;
1058
+ let values = opaque.get(keyword);
1059
+ if (!values) {
1060
+ values = /* @__PURE__ */ new Set();
1061
+ opaque.set(keyword, values);
1062
+ }
1063
+ values.add(canonicalize(value));
1064
+ };
1065
+ for (const [keywords, bounds] of [[LOWER_BOUNDS2, lower], [UPPER_BOUNDS2, upper]]) {
1066
+ for (const keyword of keywords) {
1067
+ const value = object[keyword];
1068
+ if (typeof value === "number") bounds.set(keyword, value);
1069
+ else if (value !== void 0) constrain(keyword, value);
1070
+ }
1071
+ }
1072
+ for (const keyword of OPAQUE) if (object[keyword] !== void 0) constrain(keyword, object[keyword]);
1073
+ const shadow = shadowedIn(object);
1074
+ if (shadow) {
1075
+ for (const [keyword, values] of shadow.keywords) if (CONSIDERED.has(keyword)) for (const value of values) constrain(keyword, value);
1076
+ for (const [name, values] of shadow.properties) for (const value of values) constrain(`\0properties\0${name}`, value);
1077
+ }
1078
+ const slots = /* @__PURE__ */ new Set();
1079
+ const items = object["items"];
1080
+ if (items !== void 0 && !Array.isArray(items) && !isOpen(items)) slots.add("items");
1081
+ for (const keyword of ["anyOf", "oneOf"]) if (Array.isArray(object[keyword])) slots.add(keyword);
1082
+ for (const keyword of ["then", "else"]) if (object[keyword] !== void 0 && !isOpen(object[keyword])) slots.add(keyword);
1083
+ const additionalValue = object["additionalProperties"];
1084
+ const required = Array.isArray(object["required"]) ? object["required"] : [];
1085
+ const constraints = {
1086
+ additional: additionalValue === false ? 0 : asObject(additionalValue) !== void 0 && !isOpen(additionalValue) ? 1 : 2,
1087
+ enumMembers: members,
1088
+ types,
1089
+ lower,
1090
+ upper,
1091
+ opaque,
1092
+ slots,
1093
+ requiredNames: new Set(required.filter((entry) => typeof entry === "string"))
1094
+ };
1095
+ cache.set(object, constraints);
1096
+ return constraints;
1097
+ }
1098
+ var Routes = class {
1099
+ names = /* @__PURE__ */ new Map();
1100
+ ids = /* @__PURE__ */ new Map();
1101
+ child(parent, keyword, name) {
1102
+ let nameId = this.names.get(name);
1103
+ if (nameId === void 0) {
1104
+ nameId = this.names.size;
1105
+ this.names.set(name, nameId);
1106
+ }
1107
+ const key = `${parent} ${keyword} ${nameId}`;
1108
+ let id = this.ids.get(key);
1109
+ if (id === void 0) {
1110
+ id = this.ids.size + 1;
1111
+ this.ids.set(key, id);
1112
+ }
1113
+ return id;
1114
+ }
1115
+ };
1116
+ function collectFacts(schema, routes) {
786
1117
  const facts = /* @__PURE__ */ new Map();
787
- const visit = (node, path, required, depth) => {
788
- if (depth > MAX_VISIT_DEPTH || facts.size >= MAX_FACTS) return;
1118
+ let budget = MAX_FACTS;
1119
+ const visit = (node, id, parent, via, required, depth) => {
1120
+ if (depth > MAX_VISIT_DEPTH || budget <= 0) return;
1121
+ budget -= 1;
789
1122
  const object = effectiveSchema(node, schema);
790
1123
  if (!object) return;
791
- const typeValue = object["type"];
792
- const types = typeof typeValue === "string" ? [typeValue] : Array.isArray(typeValue) ? typeValue.filter((entry) => typeof entry === "string").sort() : void 0;
793
- const enumValue = object["enum"];
794
- facts.set(path, {
795
- required,
796
- additionalProperties: typeof object["additionalProperties"] === "boolean" ? object["additionalProperties"] : void 0,
797
- enumMembers: Array.isArray(enumValue) ? enumValue.map((entry) => canonicalize(entry)).sort() : void 0,
798
- types,
799
- minimum: numberAt(object, "minimum"),
800
- maximum: numberAt(object, "maximum"),
801
- minLength: numberAt(object, "minLength"),
802
- maxLength: numberAt(object, "maxLength")
803
- });
1124
+ const constraints = constraintsOf(object, schema);
1125
+ facts.set(id, { parent, via, required, node: constraints });
1126
+ if (depth >= MAX_VISIT_DEPTH) return;
1127
+ const into = (keyword, name, child, isRequired = false) => {
1128
+ if (budget <= 0) return false;
1129
+ if (child !== void 0) visit(child, routes.child(id, keyword, name), id, keyword, isRequired, depth + 1);
1130
+ return true;
1131
+ };
804
1132
  const properties = asObject(object["properties"]);
805
1133
  if (properties) {
806
- const requiredList = Array.isArray(object["required"]) ? object["required"].filter((entry) => typeof entry === "string") : [];
807
- const requiredSet = new Set(requiredList);
808
- for (const [name, child] of Object.entries(properties)) {
809
- visit(child, path === "" ? name : `${path}.${name}`, requiredSet.has(name), depth + 1);
810
- }
1134
+ for (const [name, child] of entriesOf(properties)) if (!into("properties", name, child, constraints.requiredNames.has(name))) return;
811
1135
  }
812
- const items = object["items"];
813
- if (items !== void 0) visit(items, `${path}[]`, false, depth + 1);
814
- const prefixItems = object["prefixItems"];
815
- if (Array.isArray(prefixItems)) prefixItems.forEach((entry, index) => visit(entry, `${path}[${index}]`, false, depth + 1));
816
- for (const branch of alternatives(object)) visit(branch.schema, `${path}|${branch.label}`, false, depth + 1);
1136
+ const patternProperties = asObject(object["patternProperties"]);
1137
+ if (patternProperties) {
1138
+ for (const [pattern, child] of entriesOf(patternProperties)) if (!into("patternProperties", pattern, child)) return;
1139
+ }
1140
+ for (const keyword of ["prefixItems", "items"]) {
1141
+ const tuple = object[keyword];
1142
+ if (!Array.isArray(tuple)) continue;
1143
+ for (let index = 0; index < tuple.length; index += 1) if (!into("prefixItems", String(index), tuple[index])) return;
1144
+ }
1145
+ if (constraints.slots.has("items") && !into("items", "", object["items"])) return;
1146
+ if (constraints.additional === 1 && !into("additionalProperties", "", object["additionalProperties"])) return;
1147
+ for (const keyword of ["anyOf", "oneOf"]) {
1148
+ const branches = object[keyword];
1149
+ if (!Array.isArray(branches)) continue;
1150
+ for (let index = 0; index < branches.length; index += 1) if (!into(keyword, String(index), branches[index])) return;
1151
+ }
1152
+ for (const keyword of ["then", "else"]) if (constraints.slots.has(keyword) && !into(keyword, "", object[keyword])) return;
817
1153
  };
818
- visit(schema, "", true, 0);
1154
+ beginWalk(schema);
1155
+ visit(schema, 0, void 0, "", true, 0);
819
1156
  return facts;
820
1157
  }
821
1158
  function isSuperset(next, previous) {
822
- const members = new Set(next);
823
- return previous.every((entry) => members.has(entry));
1159
+ if (previous.size > next.size) return false;
1160
+ for (const entry of previous) if (!next.has(entry)) return false;
1161
+ return true;
1162
+ }
1163
+ function covers(types, type) {
1164
+ return types.has(type) || type === "integer" && types.has("number");
1165
+ }
1166
+ function compareConstraints(a, b) {
1167
+ let widened = false;
1168
+ let narrowed = false;
1169
+ if (b.additional > a.additional) widened = true;
1170
+ else if (b.additional < a.additional) narrowed = true;
1171
+ if (a.enumMembers && b.enumMembers) {
1172
+ if (!isSuperset(b.enumMembers, a.enumMembers)) narrowed = true;
1173
+ if (!isSuperset(a.enumMembers, b.enumMembers)) widened = true;
1174
+ } else if (a.enumMembers && !b.enumMembers) widened = true;
1175
+ else if (!a.enumMembers && b.enumMembers) narrowed = true;
1176
+ if (a.types && b.types) {
1177
+ for (const type of b.types) if (!covers(a.types, type)) widened = true;
1178
+ for (const type of a.types) if (!covers(b.types, type)) narrowed = true;
1179
+ } else if (a.types && !b.types) widened = true;
1180
+ else if (!a.types && b.types) narrowed = true;
1181
+ for (const [keyword, before] of a.lower) {
1182
+ const after = b.lower.get(keyword);
1183
+ if (after === void 0 || after < before) widened = true;
1184
+ if (after !== void 0 && after > before) narrowed = true;
1185
+ }
1186
+ for (const keyword of b.lower.keys()) if (!a.lower.has(keyword)) narrowed = true;
1187
+ for (const [keyword, before] of a.upper) {
1188
+ const after = b.upper.get(keyword);
1189
+ if (after === void 0 || after > before) widened = true;
1190
+ if (after !== void 0 && after < before) narrowed = true;
1191
+ }
1192
+ for (const keyword of b.upper.keys()) if (!a.upper.has(keyword)) narrowed = true;
1193
+ for (const [keyword, before] of a.opaque) {
1194
+ const after = b.opaque.get(keyword);
1195
+ if (!after || !isSuperset(after, before)) widened = true;
1196
+ if (after && !isSuperset(before, after)) narrowed = true;
1197
+ }
1198
+ for (const keyword of b.opaque.keys()) if (!a.opaque.has(keyword)) narrowed = true;
1199
+ for (const keyword of a.slots) if (!b.slots.has(keyword)) widened = true;
1200
+ for (const keyword of b.slots) if (!a.slots.has(keyword)) narrowed = true;
1201
+ return { widened, narrowed };
824
1202
  }
825
1203
  function classifySchemaChange(before, after) {
826
1204
  if (stableKey(before) === stableKey(after)) return "same";
827
- const previous = collectFacts(before);
828
- const next = collectFacts(after);
1205
+ const routes = new Routes();
1206
+ const previous = collectFacts(before, routes);
1207
+ const next = collectFacts(after, routes);
829
1208
  let widened = false;
830
1209
  let narrowed = false;
831
- for (const path of /* @__PURE__ */ new Set([...previous.keys(), ...next.keys()])) {
832
- const a = previous.get(path);
833
- const b = next.get(path);
834
- if (!a && b) {
835
- widened = true;
836
- continue;
837
- }
838
- if (a && !b) {
839
- narrowed = true;
840
- continue;
1210
+ const compared = /* @__PURE__ */ new Map();
1211
+ const oneSided = (fact, arrived) => {
1212
+ const counterpart = fact.parent === void 0 ? void 0 : (arrived ? previous : next).get(fact.parent);
1213
+ if (counterpart === void 0) {
1214
+ if (arrived && MEMBERS.has(fact.via)) widened = true;
1215
+ return;
841
1216
  }
842
- if (!a || !b) continue;
843
- if (a.required && !b.required) widened = true;
844
- if (!a.required && b.required) narrowed = true;
845
- const beforeAdditional = a.additionalProperties ?? true;
846
- const afterAdditional = b.additionalProperties ?? true;
847
- if (!beforeAdditional && afterAdditional) widened = true;
848
- if (beforeAdditional && !afterAdditional) narrowed = true;
849
- if (a.enumMembers && b.enumMembers) {
850
- if (isSuperset(b.enumMembers, a.enumMembers) && b.enumMembers.length > a.enumMembers.length) widened = true;
851
- else if (isSuperset(a.enumMembers, b.enumMembers) && a.enumMembers.length > b.enumMembers.length) narrowed = true;
852
- else if (canonicalize(a.enumMembers) !== canonicalize(b.enumMembers)) {
853
- widened = true;
854
- narrowed = true;
855
- }
856
- } else if (a.enumMembers && !b.enumMembers) widened = true;
857
- else if (!a.enumMembers && b.enumMembers) narrowed = true;
858
- if (a.types && b.types) {
859
- if (isSuperset(b.types, a.types) && b.types.length > a.types.length) widened = true;
860
- else if (isSuperset(a.types, b.types) && a.types.length > b.types.length) narrowed = true;
861
- else if (canonicalize(a.types) !== canonicalize(b.types)) {
862
- widened = true;
863
- narrowed = true;
864
- }
865
- } else if (a.types && !b.types) widened = true;
866
- else if (!a.types && b.types) narrowed = true;
867
- const lowerBounds = [["minimum", a.minimum, b.minimum], ["minLength", a.minLength, b.minLength]];
868
- for (const [, before_, after_] of lowerBounds) {
869
- if (before_ !== void 0 && after_ === void 0) widened = true;
870
- else if (before_ === void 0 && after_ !== void 0) narrowed = true;
871
- else if (before_ !== void 0 && after_ !== void 0) {
872
- if (after_ < before_) widened = true;
873
- if (after_ > before_) narrowed = true;
874
- }
1217
+ if (MEMBERS.has(fact.via) || counterpart.node.slots.has(fact.via)) {
1218
+ if (arrived) widened = true;
1219
+ else narrowed = true;
875
1220
  }
876
- const upperBounds = [["maximum", a.maximum, b.maximum], ["maxLength", a.maxLength, b.maxLength]];
877
- for (const [, before_, after_] of upperBounds) {
878
- if (before_ !== void 0 && after_ === void 0) widened = true;
879
- else if (before_ === void 0 && after_ !== void 0) narrowed = true;
880
- else if (before_ !== void 0 && after_ !== void 0) {
881
- if (after_ > before_) widened = true;
882
- if (after_ < before_) narrowed = true;
1221
+ };
1222
+ for (const [id, a] of previous) {
1223
+ const b = next.get(id);
1224
+ if (!b) {
1225
+ oneSided(a, false);
1226
+ } else {
1227
+ if (a.required && !b.required) widened = true;
1228
+ if (!a.required && b.required) narrowed = true;
1229
+ if (a.node !== b.node) {
1230
+ let row2 = compared.get(a.node);
1231
+ if (!row2) {
1232
+ row2 = /* @__PURE__ */ new Map();
1233
+ compared.set(a.node, row2);
1234
+ }
1235
+ let direction = row2.get(b.node);
1236
+ if (!direction) {
1237
+ direction = compareConstraints(a.node, b.node);
1238
+ row2.set(b.node, direction);
1239
+ }
1240
+ if (direction.widened) widened = true;
1241
+ if (direction.narrowed) narrowed = true;
883
1242
  }
884
1243
  }
1244
+ if (widened && narrowed) return "changed";
885
1245
  }
1246
+ for (const [id, b] of next) if (!previous.has(id)) oneSided(b, true);
886
1247
  if (widened && !narrowed) return "widened";
887
1248
  if (narrowed && !widened) return "narrowed";
888
1249
  return "changed";
@@ -993,13 +1354,15 @@ function compareTool(name, before, after) {
993
1354
  change("tool.header_params.changed", name, "arguments mirrored into HTTP headers changed", { ...at, before: before.headerParams ?? [], after: after.headerParams ?? [] })
994
1355
  );
995
1356
  }
996
- if (changes.length === 0) {
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);
1357
+ const moved = [
1358
+ !same(before.title, after.title) ? "title" : "",
1359
+ // A second title a client shows in place of the name, and the same finding for the same reason.
1360
+ !same(before.annotations?.title, after.annotations?.title) ? "annotations.title" : "",
1361
+ !same(before.icons, after.icons) ? "icons" : "",
1362
+ !same(before.execution, after.execution) ? `how it may be run (${describeExecution(before.execution)} \u2192 ${describeExecution(after.execution)})` : "",
1363
+ !same(before.meta, after.meta) ? "_meta" : ""
1364
+ ].filter(Boolean);
1365
+ if (moved.length > 0 || changes.length === 0) {
1003
1366
  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 }));
1004
1367
  }
1005
1368
  return changes;
@@ -1215,15 +1578,18 @@ function compareServer(name, before, after) {
1215
1578
  }
1216
1579
  return changes;
1217
1580
  }
1581
+ function subjectNamed(lock, name) {
1582
+ return Object.hasOwn(lock.subjects, name) ? lock.subjects[name] : void 0;
1583
+ }
1218
1584
  function detectRenames(before, after, removed, added) {
1219
1585
  const changes = [];
1220
1586
  const renamed = /* @__PURE__ */ new Set();
1221
1587
  const availableAdds = [...added];
1222
1588
  for (const oldName of removed) {
1223
- const oldEntry = before.subjects[oldName];
1589
+ const oldEntry = subjectNamed(before, oldName);
1224
1590
  if (!oldEntry) continue;
1225
1591
  const match = availableAdds.find((newName) => {
1226
- const candidate = after.subjects[newName];
1592
+ const candidate = subjectNamed(after, newName);
1227
1593
  return candidate !== void 0 && candidate.digest === oldEntry.digest && same(candidate.transport, oldEntry.transport);
1228
1594
  });
1229
1595
  if (!match) continue;
@@ -1231,6 +1597,8 @@ function detectRenames(before, after, removed, added) {
1231
1597
  renamed.add(oldName);
1232
1598
  renamed.add(match);
1233
1599
  changes.push(change("server.renamed", match, `renamed from "${oldName}"; capabilities are unchanged`, { before: oldName, after: match }));
1600
+ const newEntry = subjectNamed(after, match);
1601
+ if (newEntry) changes.push(...compareProvenance(match, oldEntry, newEntry));
1234
1602
  }
1235
1603
  return { changes, renamed };
1236
1604
  }
@@ -1243,17 +1611,17 @@ function diffLockfiles(before, after) {
1243
1611
  const changes = [...renameChanges];
1244
1612
  for (const name of added) {
1245
1613
  if (renamed.has(name)) continue;
1246
- const entry = after.subjects[name];
1614
+ const entry = subjectNamed(after, name);
1247
1615
  const toolCount = entry?.tools?.length ?? 0;
1248
1616
  changes.push(change("server.added", name, `new server with ${toolCount} tool${toolCount === 1 ? "" : "s"}`, { after: entry }));
1249
1617
  }
1250
1618
  for (const name of removed) {
1251
1619
  if (renamed.has(name)) continue;
1252
- changes.push(change("server.removed", name, "server is no longer configured", { before: before.subjects[name] }));
1620
+ changes.push(change("server.removed", name, "server is no longer configured", { before: subjectNamed(before, name) }));
1253
1621
  }
1254
1622
  for (const name of afterNames) {
1255
- const a = before.subjects[name];
1256
- const b = after.subjects[name];
1623
+ const a = subjectNamed(before, name);
1624
+ const b = subjectNamed(after, name);
1257
1625
  if (!a || !b) continue;
1258
1626
  changes.push(...compareServer(name, a, b));
1259
1627
  }
@@ -1358,25 +1726,49 @@ function capabilityViolations(lock, denied) {
1358
1726
 
1359
1727
  // ../core/src/risk/surface-text.ts
1360
1728
  var MAX_NODES = 2e4;
1729
+ var SINGLE_SCHEMAS = ["items", "additionalItems", "additionalProperties", "unevaluatedItems", "unevaluatedProperties", "contains", "propertyNames", "not", "if", "then", "else", "contentSchema"];
1730
+ var SCHEMA_LISTS = ["items", "prefixItems", "allOf", "anyOf", "oneOf"];
1731
+ var NAMED_SCHEMAS2 = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"];
1732
+ var VALUES = ["enum", "const", "default", "examples"];
1361
1733
  function schemaText(root, rootPath, out) {
1362
1734
  const stack = [{ node: root, path: rootPath }];
1363
1735
  const seen = /* @__PURE__ */ new WeakSet();
1364
1736
  let budget = MAX_NODES;
1737
+ let values = MAX_NODES;
1365
1738
  while (stack.length > 0 && budget-- > 0) {
1366
1739
  const { node, path } = stack.pop();
1367
- if (typeof node !== "object" || node === null) continue;
1740
+ if (typeof node !== "object" || node === null || Array.isArray(node)) continue;
1368
1741
  if (seen.has(node)) continue;
1369
1742
  seen.add(node);
1370
1743
  const schema = node;
1371
- if (typeof schema.description === "string") out.push({ field: path, text: schema.description });
1372
- if (typeof schema.title === "string") out.push({ field: `${path}.title`, text: schema.title });
1373
- const properties = schema.properties;
1374
- if (typeof properties === "object" && properties !== null) {
1375
- for (const [name, child] of Object.entries(properties)) {
1376
- stack.push({ node: child, path: `${path}.${name}` });
1744
+ if (typeof schema["description"] === "string") out.push({ field: path, text: schema["description"] });
1745
+ if (typeof schema["title"] === "string") out.push({ field: `${path}.title`, text: schema["title"] });
1746
+ for (const keyword of VALUES) {
1747
+ const value = schema[keyword];
1748
+ const strings = Array.isArray(value) ? value : [value];
1749
+ for (const [index, entry] of strings.entries()) {
1750
+ if (values <= 0) break;
1751
+ if (typeof entry !== "string" || entry.length === 0) continue;
1752
+ values -= 1;
1753
+ out.push({ field: Array.isArray(value) ? `${path}.${keyword}[${index}]` : `${path}.${keyword}`, text: entry });
1377
1754
  }
1378
1755
  }
1379
- if (schema.items !== void 0) stack.push({ node: schema.items, path: `${path}[]` });
1756
+ for (const keyword of NAMED_SCHEMAS2) {
1757
+ const named = schema[keyword];
1758
+ if (typeof named !== "object" || named === null || Array.isArray(named)) continue;
1759
+ const prefix = keyword === "properties" ? path : `${path}.${keyword}`;
1760
+ for (const [name, child] of Object.entries(named)) stack.push({ node: child, path: `${prefix}.${name}` });
1761
+ }
1762
+ for (const keyword of SCHEMA_LISTS) {
1763
+ const list = schema[keyword];
1764
+ if (!Array.isArray(list)) continue;
1765
+ list.forEach((child, index) => stack.push({ node: child, path: `${path}.${keyword}[${index}]` }));
1766
+ }
1767
+ for (const keyword of SINGLE_SCHEMAS) {
1768
+ const child = schema[keyword];
1769
+ if (child === void 0 || Array.isArray(child)) continue;
1770
+ stack.push({ node: child, path: keyword === "items" ? `${path}[]` : `${path}.${keyword}` });
1771
+ }
1380
1772
  }
1381
1773
  }
1382
1774
  function surfaceText(subject) {
@@ -1386,36 +1778,36 @@ function surfaceText(subject) {
1386
1778
  };
1387
1779
  push("instructions", subject?.instructions);
1388
1780
  for (const tool2 of objectsIn(subject?.tools)) {
1389
- const where = stringOr(tool2.name) ?? "?";
1390
- push(`${where}.title`, tool2.title);
1391
- push(`${where}.description`, tool2.description);
1392
- schemaText(tool2.inputSchema, `${where}.inputSchema`, out);
1393
- schemaText(tool2.outputSchema, `${where}.outputSchema`, out);
1781
+ const where2 = stringOr(tool2.name) ?? "?";
1782
+ push(`${where2}.title`, tool2.title);
1783
+ push(`${where2}.description`, tool2.description);
1784
+ schemaText(tool2.inputSchema, `${where2}.inputSchema`, out);
1785
+ schemaText(tool2.outputSchema, `${where2}.outputSchema`, out);
1394
1786
  }
1395
1787
  for (const prompt2 of objectsIn(subject?.prompts)) {
1396
- const where = stringOr(prompt2.name) ?? "?";
1397
- push(`prompt:${where}.title`, prompt2.title);
1398
- push(`prompt:${where}.description`, prompt2.description);
1788
+ const where2 = stringOr(prompt2.name) ?? "?";
1789
+ push(`prompt:${where2}.title`, prompt2.title);
1790
+ push(`prompt:${where2}.description`, prompt2.description);
1399
1791
  for (const argument of objectsIn(prompt2.arguments)) {
1400
- push(`prompt:${where}.${stringOr(argument.name) ?? "?"}`, argument.description);
1792
+ push(`prompt:${where2}.${stringOr(argument.name) ?? "?"}`, argument.description);
1401
1793
  }
1402
1794
  }
1403
1795
  for (const resource2 of objectsIn(subject?.resources)) {
1404
- const where = stringOr(resource2.name) ?? stringOr(resource2.uri) ?? "?";
1405
- push(`resource:${where}.title`, resource2.title);
1406
- push(`resource:${where}.description`, resource2.description);
1796
+ const where2 = stringOr(resource2.name) ?? stringOr(resource2.uri) ?? "?";
1797
+ push(`resource:${where2}.title`, resource2.title);
1798
+ push(`resource:${where2}.description`, resource2.description);
1407
1799
  }
1408
1800
  for (const template of objectsIn(subject?.resourceTemplates)) {
1409
- const where = stringOr(template.name) ?? stringOr(template.uriTemplate) ?? "?";
1410
- push(`template:${where}.title`, template.title);
1411
- push(`template:${where}.description`, template.description);
1801
+ const where2 = stringOr(template.name) ?? stringOr(template.uriTemplate) ?? "?";
1802
+ push(`template:${where2}.title`, template.title);
1803
+ push(`template:${where2}.description`, template.description);
1412
1804
  }
1413
1805
  return out;
1414
1806
  }
1415
1807
 
1416
1808
  // ../core/src/risk/arrival.ts
1417
- function identity(signal) {
1418
- return `${signal.field}\0${signal.kind}\0${signal.quote}`;
1809
+ function identity(signal2) {
1810
+ return `${signal2.field}\0${signal2.kind}\0${signal2.quote}`;
1419
1811
  }
1420
1812
  function signalsFor(subject) {
1421
1813
  if (typeof subject !== "object" || subject === null) return [];
@@ -1426,8 +1818,9 @@ function signalsFor(subject) {
1426
1818
  function newSteering(committed, observed) {
1427
1819
  const found = [];
1428
1820
  for (const [server2, subject] of Object.entries(observed.subjects ?? {})) {
1429
- const before = new Set(signalsFor(committed.subjects?.[server2]).map(identity));
1430
- const signals = signalsFor(subject).filter((signal) => !before.has(identity(signal)));
1821
+ const approved = committed.subjects && Object.hasOwn(committed.subjects, server2) ? committed.subjects[server2] : void 0;
1822
+ const before = new Set(signalsFor(approved).map(identity));
1823
+ const signals = signalsFor(subject).filter((signal2) => !before.has(identity(signal2)));
1431
1824
  if (signals.length > 0) found.push({ server: server2, signals });
1432
1825
  }
1433
1826
  return found.sort((a, b) => a.server.localeCompare(b.server));
@@ -1476,6 +1869,133 @@ import { readFile } from "fs/promises";
1476
1869
  import { resolve } from "path";
1477
1870
  import { z } from "zod";
1478
1871
 
1872
+ // src/lock/build.ts
1873
+ function byName(members) {
1874
+ return [...members].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1875
+ }
1876
+ function lockIcons(icons) {
1877
+ if (!icons || icons.length === 0) return void 0;
1878
+ return icons.map((icon2) => ({
1879
+ src: icon2.src,
1880
+ mimeType: icon2.mimeType,
1881
+ sizes: icon2.sizes,
1882
+ theme: icon2.theme
1883
+ }));
1884
+ }
1885
+ function sealed(entry) {
1886
+ return { ...entry, digest: digest(toJson(entry)) };
1887
+ }
1888
+ function lockTransport(server2) {
1889
+ const { transport: transport2 } = server2;
1890
+ if (transport2.type === "stdio") {
1891
+ const command = transport2.asWritten?.command ?? transport2.command;
1892
+ const args = redactArgs(transport2.asWritten?.args ?? transport2.args);
1893
+ return {
1894
+ type: "stdio",
1895
+ command,
1896
+ args: args.length > 0 ? args : void 0,
1897
+ envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
1898
+ cwd: transport2.asWritten ? transport2.asWritten.cwd : transport2.cwd
1899
+ };
1900
+ }
1901
+ const headerKeys = Object.keys(transport2.headers);
1902
+ return {
1903
+ type: transport2.type,
1904
+ url: sanitizeUrl(transport2.asWritten?.url ?? transport2.url),
1905
+ headerKeys: headerKeys.length > 0 ? headerKeys.sort() : void 0
1906
+ };
1907
+ }
1908
+ function lockTool(tool2, ignoredMeta) {
1909
+ const annotations2 = tool2.annotations;
1910
+ const inputSchema = normalizeSchema(toJson(tool2.inputSchema));
1911
+ const headerParams = extractHeaderParams(inputSchema);
1912
+ return sealed({
1913
+ name: tool2.name,
1914
+ title: tool2.title,
1915
+ description: tool2.description,
1916
+ inputSchema,
1917
+ outputSchema: tool2.outputSchema ? normalizeSchema(toJson(tool2.outputSchema)) : void 0,
1918
+ annotations: annotations2 ? { ...annotations2 } : void 0,
1919
+ behavior: resolveBehavior(annotations2),
1920
+ headerParams: headerParams.length > 0 ? headerParams : void 0,
1921
+ icons: lockIcons(tool2.icons),
1922
+ execution: tool2.execution ? toJson(tool2.execution) : void 0,
1923
+ meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
1924
+ });
1925
+ }
1926
+ function lockResource(resource2, ignoredMeta) {
1927
+ return sealed({
1928
+ uri: resource2.uri,
1929
+ name: resource2.name,
1930
+ title: resource2.title,
1931
+ description: resource2.description,
1932
+ mimeType: resource2.mimeType,
1933
+ annotations: resource2.annotations ? toJson(resource2.annotations) : void 0,
1934
+ icons: lockIcons(resource2.icons),
1935
+ meta: stripIgnoredMeta(toJson(resource2._meta), ignoredMeta)
1936
+ });
1937
+ }
1938
+ function lockResourceTemplate(template, ignoredMeta) {
1939
+ return sealed({
1940
+ uriTemplate: template.uriTemplate,
1941
+ name: template.name,
1942
+ title: template.title,
1943
+ description: template.description,
1944
+ mimeType: template.mimeType,
1945
+ annotations: template.annotations ? toJson(template.annotations) : void 0,
1946
+ icons: lockIcons(template.icons),
1947
+ meta: stripIgnoredMeta(toJson(template._meta), ignoredMeta)
1948
+ });
1949
+ }
1950
+ function lockPrompt(prompt2, ignoredMeta) {
1951
+ return sealed({
1952
+ name: prompt2.name,
1953
+ title: prompt2.title,
1954
+ description: prompt2.description,
1955
+ arguments: prompt2.arguments && prompt2.arguments.length > 0 ? prompt2.arguments.map((argument) => ({
1956
+ name: argument.name,
1957
+ // The spec gives PromptArgument a `title` (it extends BaseMetadata); the SDK's type
1958
+ // has not caught up, so it is read off the wire rather than skipped.
1959
+ title: argument.title,
1960
+ description: argument.description,
1961
+ required: argument.required
1962
+ })) : void 0,
1963
+ icons: lockIcons(prompt2.icons),
1964
+ meta: stripIgnoredMeta(toJson(prompt2._meta), ignoredMeta)
1965
+ });
1966
+ }
1967
+ function buildLockedServer(server2, surface, policy) {
1968
+ const ignoredMeta = policy?.ignoreMetaPrefixes ?? [];
1969
+ const tools = byName(surface.tools).map((tool2) => lockTool(tool2, ignoredMeta));
1970
+ const resources = byName(surface.resources).map((resource2) => lockResource(resource2, ignoredMeta));
1971
+ const resourceTemplates = byName(surface.resourceTemplates).map((template) => lockResourceTemplate(template, ignoredMeta));
1972
+ const prompts = byName(surface.prompts).map((prompt2) => lockPrompt(prompt2, ignoredMeta));
1973
+ const entry = {
1974
+ source: server2.source,
1975
+ transport: lockTransport(server2),
1976
+ protocol: surface.protocol,
1977
+ serverInfo: surface.serverInfo,
1978
+ capabilities: surface.capabilities,
1979
+ instructions: surface.instructions,
1980
+ tools: tools.length > 0 ? tools : void 0,
1981
+ resources: resources.length > 0 ? resources : void 0,
1982
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
1983
+ prompts: prompts.length > 0 ? prompts : void 0
1984
+ };
1985
+ const covered = {
1986
+ transport: entry.transport,
1987
+ protocol: entry.protocol,
1988
+ serverInfo: entry.serverInfo,
1989
+ capabilities: entry.capabilities,
1990
+ instructions: entry.instructions,
1991
+ tools: tools.map((tool2) => tool2.digest),
1992
+ resources: resources.map((resource2) => resource2.digest),
1993
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
1994
+ prompts: prompts.map((prompt2) => prompt2.digest)
1995
+ };
1996
+ return { kind: "mcp-server", ...entry, ...surface.coverage ? { coverage: surface.coverage } : {}, digest: digest(toJson(covered)) };
1997
+ }
1998
+
1479
1999
  // src/config/expand.ts
1480
2000
  import { homedir } from "os";
1481
2001
  var PLACEHOLDER2 = /\$\{([^}]+)\}/g;
@@ -1496,6 +2016,7 @@ function isRunCredential(name) {
1496
2016
  function expand(input, context) {
1497
2017
  const unresolved = [];
1498
2018
  const refused = [];
2019
+ const filled = [];
1499
2020
  const value = input.replace(PLACEHOLDER2, (match, body) => {
1500
2021
  const named = body.startsWith("env:") ? body.slice(4) : body.includes(":-") ? body.slice(0, body.indexOf(":-")) : body;
1501
2022
  if (isRunCredential(named)) {
@@ -1512,21 +2033,30 @@ function expand(input, context) {
1512
2033
  if (body.startsWith("env:")) {
1513
2034
  const name = body.slice(4);
1514
2035
  const found2 = context.env[name];
1515
- if (found2 !== void 0) return found2;
2036
+ if (found2 !== void 0) {
2037
+ filled.push({ name, value: found2 });
2038
+ return found2;
2039
+ }
1516
2040
  unresolved.push(match);
1517
2041
  return match;
1518
2042
  }
1519
2043
  const defaultAt = body.indexOf(":-");
1520
2044
  if (defaultAt !== -1) {
1521
2045
  const name = body.slice(0, defaultAt);
1522
- return context.env[name] ?? body.slice(defaultAt + 2);
2046
+ const found2 = context.env[name];
2047
+ if (found2 === void 0) return body.slice(defaultAt + 2);
2048
+ filled.push({ name, value: found2 });
2049
+ return found2;
1523
2050
  }
1524
2051
  const found = context.env[body];
1525
- if (found !== void 0) return found;
2052
+ if (found !== void 0) {
2053
+ filled.push({ name: body, value: found });
2054
+ return found;
2055
+ }
1526
2056
  unresolved.push(match);
1527
2057
  return match;
1528
2058
  });
1529
- return { value, unresolved, refused };
2059
+ return { value, unresolved, refused, filled };
1530
2060
  }
1531
2061
 
1532
2062
  // src/config/parsers.ts
@@ -1555,6 +2085,16 @@ var UnsupportedServerError = class extends Error {
1555
2085
  this.name = "UnsupportedServerError";
1556
2086
  }
1557
2087
  serverName;
2088
+ /**
2089
+ * How the definition reaches its server, written down as the lock writes a pinned one, where
2090
+ * that could be read: unexpanded, with literal credentials left out. Absent for a definition
2091
+ * with no transport to read (WebSocket, no command, not a server definition at all).
2092
+ *
2093
+ * An agreement to leave the server unaudited is an agreement to this. It was `{}`, and `check`
2094
+ * compared nothing with nothing: a pull request could rewrite an agreed server to `bash -c
2095
+ * "curl ... | sh"`, keep the `${input:...}` placeholder that kept it from being run, and pass.
2096
+ */
2097
+ transport;
1558
2098
  };
1559
2099
  function scalarsToStrings(record) {
1560
2100
  const out = {};
@@ -1571,13 +2111,33 @@ function refusedCredentials(name, refused) {
1571
2111
  `configuration uses ${names.join(", ")}, which ${names.length === 1 ? "holds" : "hold"} this run's own credentials (the CI job's token or identity, or Nulladrift's). They are never given to a server under audit. Give the server a credential of its own.`
1572
2112
  );
1573
2113
  }
2114
+ function writtenTransport(entry) {
2115
+ const declared = entry.type === "streamable-http" ? "http" : entry.type;
2116
+ if (declared === "ws") return void 0;
2117
+ if (declared === "http" || declared === "sse" || declared === void 0 && entry.url !== void 0) {
2118
+ if (entry.url === void 0) return void 0;
2119
+ return { type: declared === "sse" ? "sse" : "http", url: entry.url, asWritten: { url: entry.url }, headers: scalarsToStrings(entry.headers) };
2120
+ }
2121
+ if (entry.command === void 0) return void 0;
2122
+ const args = (entry.args ?? []).map((argument) => String(argument));
2123
+ return {
2124
+ type: "stdio",
2125
+ command: entry.command,
2126
+ args,
2127
+ asWritten: { command: entry.command, args, ...entry.cwd ? { cwd: entry.cwd } : {} },
2128
+ env: scalarsToStrings(entry.env),
2129
+ cwd: entry.cwd
2130
+ };
2131
+ }
1574
2132
  function resolveTransport(name, entry, context) {
1575
2133
  const unresolved = [];
1576
2134
  const refused = [];
2135
+ const filled = [];
1577
2136
  const take = (input) => {
1578
2137
  const result = expand(input, context);
1579
2138
  unresolved.push(...result.unresolved);
1580
2139
  refused.push(...result.refused);
2140
+ filled.push(...result.filled);
1581
2141
  return result.value;
1582
2142
  };
1583
2143
  const declared = entry.type === "streamable-http" ? "http" : entry.type;
@@ -1624,6 +2184,7 @@ function resolveTransport(name, entry, context) {
1624
2184
  "oauth.clientSecret is set without oauth.issuer. Set oauth.issuer to the authorization server's issuer URL, so the secret can only be sent there and not to an authorization server the MCP server chooses."
1625
2185
  );
1626
2186
  }
2187
+ if (filled.length > 0) transport2.filled = filled;
1627
2188
  if (refused.length > 0) throw refusedCredentials(name, refused);
1628
2189
  if (unresolved.length > 0) {
1629
2190
  const names = [...new Set(unresolved)].join(", ");
@@ -1704,8 +2265,10 @@ async function parseServerMap(raw, mapKey, source, context) {
1704
2265
  }
1705
2266
  servers.push({ name, source: { ...source }, transport: transport2 });
1706
2267
  } catch (error) {
1707
- if (error instanceof UnsupportedServerError) skipped.push(error);
1708
- else throw error;
2268
+ if (!(error instanceof UnsupportedServerError)) throw error;
2269
+ const written = writtenTransport(entry.data);
2270
+ if (written) error.transport = lockTransport({ name, source: { ...source }, transport: written });
2271
+ skipped.push(error);
1709
2272
  }
1710
2273
  }
1711
2274
  return { servers, skipped };
@@ -1785,8 +2348,8 @@ function anchorCwd(server2, projectRoot) {
1785
2348
  return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
1786
2349
  }
1787
2350
  function describeSearch(searched, filesRead) {
1788
- const read = new Set(filesRead);
1789
- const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
2351
+ const read2 = new Set(filesRead);
2352
+ const lines = searched.map((path) => ` ${(read2.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
1790
2353
  return lines.join("\n");
1791
2354
  }
1792
2355
  async function discoverServers(projectRoot, extraFiles = [], options = {}) {
@@ -1805,18 +2368,18 @@ async function discoverServers(projectRoot, extraFiles = [], options = {}) {
1805
2368
  const problems = [];
1806
2369
  const requested = new Set(files.filter((file) => file.client === "generic").map((file) => file.path));
1807
2370
  for (const file of files) {
1808
- const read = await readJsonIfPresent(file.path);
1809
- if (!read.present) {
2371
+ const read2 = await readJsonIfPresent(file.path);
2372
+ if (!read2.present) {
1810
2373
  if (requested.has(file.path)) {
1811
2374
  problems.push({ file: portablePath(file.path, projectRoot), reason: "no such file; it was named with --config" });
1812
2375
  }
1813
2376
  continue;
1814
2377
  }
1815
- if (!read.ok) {
1816
- problems.push({ file: portablePath(file.path, projectRoot), reason: read.reason });
2378
+ if (!read2.ok) {
2379
+ problems.push({ file: portablePath(file.path, projectRoot), reason: read2.reason });
1817
2380
  continue;
1818
2381
  }
1819
- const raw = read.value;
2382
+ const raw = read2.value;
1820
2383
  filesRead.push(file.path);
1821
2384
  const source = { client: file.client, file: portablePath(file.path, projectRoot) };
1822
2385
  let mapKey = CLIENT_MAP_KEY[file.client];
@@ -1872,140 +2435,13 @@ function lowercased(headers) {
1872
2435
  return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]));
1873
2436
  }
1874
2437
 
1875
- // src/lock/build.ts
1876
- function byName(members) {
1877
- return [...members].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1878
- }
1879
- function lockIcons(icons) {
1880
- if (!icons || icons.length === 0) return void 0;
1881
- return icons.map((icon2) => ({
1882
- src: icon2.src,
1883
- mimeType: icon2.mimeType,
1884
- sizes: icon2.sizes,
1885
- theme: icon2.theme
1886
- }));
1887
- }
1888
- function sealed(entry) {
1889
- return { ...entry, digest: digest(toJson(entry)) };
1890
- }
1891
- function lockTransport(server2) {
1892
- const { transport: transport2 } = server2;
1893
- if (transport2.type === "stdio") {
1894
- const command = transport2.asWritten?.command ?? transport2.command;
1895
- const args = redactArgs(transport2.asWritten?.args ?? transport2.args);
1896
- return {
1897
- type: "stdio",
1898
- command,
1899
- args: args.length > 0 ? args : void 0,
1900
- envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
1901
- cwd: transport2.asWritten ? transport2.asWritten.cwd : transport2.cwd
1902
- };
1903
- }
1904
- const headerKeys = Object.keys(transport2.headers);
1905
- return {
1906
- type: transport2.type,
1907
- url: sanitizeUrl(transport2.asWritten?.url ?? transport2.url),
1908
- headerKeys: headerKeys.length > 0 ? headerKeys.sort() : void 0
1909
- };
1910
- }
1911
- function lockTool(tool2, ignoredMeta) {
1912
- const annotations2 = tool2.annotations;
1913
- const inputSchema = normalizeSchema(toJson(tool2.inputSchema));
1914
- const headerParams = extractHeaderParams(inputSchema);
1915
- return sealed({
1916
- name: tool2.name,
1917
- title: tool2.title,
1918
- description: tool2.description,
1919
- inputSchema,
1920
- outputSchema: tool2.outputSchema ? normalizeSchema(toJson(tool2.outputSchema)) : void 0,
1921
- annotations: annotations2 ? { ...annotations2 } : void 0,
1922
- behavior: resolveBehavior(annotations2),
1923
- headerParams: headerParams.length > 0 ? headerParams : void 0,
1924
- icons: lockIcons(tool2.icons),
1925
- execution: tool2.execution ? toJson(tool2.execution) : void 0,
1926
- meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
1927
- });
1928
- }
1929
- function lockResource(resource2, ignoredMeta) {
1930
- return sealed({
1931
- uri: resource2.uri,
1932
- name: resource2.name,
1933
- title: resource2.title,
1934
- description: resource2.description,
1935
- mimeType: resource2.mimeType,
1936
- annotations: resource2.annotations ? toJson(resource2.annotations) : void 0,
1937
- icons: lockIcons(resource2.icons),
1938
- meta: stripIgnoredMeta(toJson(resource2._meta), ignoredMeta)
1939
- });
1940
- }
1941
- function lockResourceTemplate(template, ignoredMeta) {
1942
- return sealed({
1943
- uriTemplate: template.uriTemplate,
1944
- name: template.name,
1945
- title: template.title,
1946
- description: template.description,
1947
- mimeType: template.mimeType,
1948
- annotations: template.annotations ? toJson(template.annotations) : void 0,
1949
- icons: lockIcons(template.icons),
1950
- meta: stripIgnoredMeta(toJson(template._meta), ignoredMeta)
1951
- });
1952
- }
1953
- function lockPrompt(prompt2, ignoredMeta) {
1954
- return sealed({
1955
- name: prompt2.name,
1956
- title: prompt2.title,
1957
- description: prompt2.description,
1958
- arguments: prompt2.arguments && prompt2.arguments.length > 0 ? prompt2.arguments.map((argument) => ({
1959
- name: argument.name,
1960
- // The spec gives PromptArgument a `title` (it extends BaseMetadata); the SDK's type
1961
- // has not caught up, so it is read off the wire rather than skipped.
1962
- title: argument.title,
1963
- description: argument.description,
1964
- required: argument.required
1965
- })) : void 0,
1966
- icons: lockIcons(prompt2.icons),
1967
- meta: stripIgnoredMeta(toJson(prompt2._meta), ignoredMeta)
1968
- });
1969
- }
1970
- function buildLockedServer(server2, surface, policy) {
1971
- const ignoredMeta = policy?.ignoreMetaPrefixes ?? [];
1972
- const tools = byName(surface.tools).map((tool2) => lockTool(tool2, ignoredMeta));
1973
- const resources = byName(surface.resources).map((resource2) => lockResource(resource2, ignoredMeta));
1974
- const resourceTemplates = byName(surface.resourceTemplates).map((template) => lockResourceTemplate(template, ignoredMeta));
1975
- const prompts = byName(surface.prompts).map((prompt2) => lockPrompt(prompt2, ignoredMeta));
1976
- const entry = {
1977
- source: server2.source,
1978
- transport: lockTransport(server2),
1979
- protocol: surface.protocol,
1980
- serverInfo: surface.serverInfo,
1981
- capabilities: surface.capabilities,
1982
- instructions: surface.instructions,
1983
- tools: tools.length > 0 ? tools : void 0,
1984
- resources: resources.length > 0 ? resources : void 0,
1985
- resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
1986
- prompts: prompts.length > 0 ? prompts : void 0
1987
- };
1988
- const covered = {
1989
- transport: entry.transport,
1990
- protocol: entry.protocol,
1991
- serverInfo: entry.serverInfo,
1992
- capabilities: entry.capabilities,
1993
- instructions: entry.instructions,
1994
- tools: tools.map((tool2) => tool2.digest),
1995
- resources: resources.map((resource2) => resource2.digest),
1996
- resourceTemplates: resourceTemplates.map((template) => template.digest),
1997
- prompts: prompts.map((prompt2) => prompt2.digest)
1998
- };
1999
- return { kind: "mcp-server", ...entry, ...surface.coverage ? { coverage: surface.coverage } : {}, digest: digest(toJson(covered)) };
2000
- }
2001
-
2002
2438
  // src/lock/provenance.ts
2003
2439
  import { createHash as createHash2 } from "crypto";
2004
2440
  import { readFile as readFile3 } from "fs/promises";
2005
2441
  import { isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
2006
2442
 
2007
2443
  // src/lib/version.ts
2008
- var VERSION = "0.9.0";
2444
+ var VERSION = "0.10.1";
2009
2445
  var USER_AGENT = `nulladrift/${VERSION} (+https://github.com/Nulladrift/nulladrift)`;
2010
2446
 
2011
2447
  // src/lock/provenance.ts
@@ -2349,9 +2785,9 @@ function launchPinned(transport2, provenance2) {
2349
2785
  }
2350
2786
  function imageLocation(name) {
2351
2787
  const parts = name.split("/");
2352
- const first = parts[0];
2353
- const hasHost = parts.length > 1 && (first.includes(".") || first.includes(":") || first === "localhost");
2354
- let host = hasHost ? first : "registry-1.docker.io";
2788
+ const first2 = parts[0];
2789
+ const hasHost = parts.length > 1 && (first2.includes(".") || first2.includes(":") || first2 === "localhost");
2790
+ let host = hasHost ? first2 : "registry-1.docker.io";
2355
2791
  if (host === "docker.io" || host === "index.docker.io") host = "registry-1.docker.io";
2356
2792
  let repository = hasHost ? parts.slice(1).join("/") : name;
2357
2793
  if (host === "registry-1.docker.io" && !repository.includes("/")) repository = `library/${repository}`;
@@ -2809,6 +3245,12 @@ function createAuthProvider(server2, options = {}) {
2809
3245
 
2810
3246
  // src/mcp/types.ts
2811
3247
  import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
3248
+ var MAX_REASON_CHARS = 2048;
3249
+ function boundReason(text, limit = MAX_REASON_CHARS) {
3250
+ if (text.length <= limit) return text;
3251
+ const kept = text.slice(0, limit).replace(/\S*$/, "").trimEnd();
3252
+ return `${kept} \u2026 (${text.length - kept.length} more characters)`;
3253
+ }
2812
3254
  var UnreachableServerError = class extends Error {
2813
3255
  constructor(serverName, message, cause) {
2814
3256
  super(message);
@@ -2846,6 +3288,61 @@ function isAuthFailure(error) {
2846
3288
  return /\b(401|403)\b|unauthorized|forbidden|invalid or missing[^\n]{0,80}?token|authentication required|invalid_client|dynamic client registration/.test(text);
2847
3289
  }
2848
3290
 
3291
+ // src/mcp/network.ts
3292
+ var MAX_DEPTH2 = 8;
3293
+ function networkError(error) {
3294
+ const pending = [{ value: error, depth: 0 }];
3295
+ while (pending.length > 0) {
3296
+ const { value, depth } = pending.shift();
3297
+ if (value === null || typeof value !== "object" || depth > MAX_DEPTH2) continue;
3298
+ const candidate = value;
3299
+ if (typeof candidate.code === "string" && /^(E[A-Z]+|UND_ERR_[A-Z_]+|CERT_[A-Z_]+|ERR_TLS_[A-Z_]+|UNABLE_TO_[A-Z_]+|[A-Z_]*SELF_SIGNED[A-Z_]*)$/.test(candidate.code)) {
3300
+ return {
3301
+ code: candidate.code,
3302
+ address: typeof candidate.address === "string" ? candidate.address : void 0,
3303
+ port: typeof candidate.port === "number" ? candidate.port : void 0,
3304
+ hostname: typeof candidate.hostname === "string" ? candidate.hostname : void 0
3305
+ };
3306
+ }
3307
+ pending.push({ value: candidate.cause, depth: depth + 1 });
3308
+ if (Array.isArray(candidate.errors)) for (const inner of candidate.errors.slice(0, 8)) pending.push({ value: inner, depth: depth + 1 });
3309
+ }
3310
+ return void 0;
3311
+ }
3312
+ function where(found) {
3313
+ const host = found.hostname ?? found.address;
3314
+ if (!host) return "";
3315
+ const shown = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
3316
+ return found.port !== void 0 ? `${shown}:${found.port}` : shown;
3317
+ }
3318
+ function describeNetworkFailure(error) {
3319
+ const found = networkError(error);
3320
+ if (!found) return void 0;
3321
+ const at = where(found);
3322
+ switch (found.code) {
3323
+ case "ECONNREFUSED":
3324
+ return `connection refused${at ? ` by ${at}` : ""}: nothing is listening there. Is the server running, and is the port right?`;
3325
+ case "ENOTFOUND":
3326
+ return `${at ? `the host name ${found.hostname ?? at}` : "the host name"} does not resolve. Check the URL for a typo, or the DNS this machine uses.`;
3327
+ case "EAI_AGAIN":
3328
+ return `looking up ${found.hostname ?? "the host name"} failed for now (EAI_AGAIN): DNS did not answer. Try again, or check this machine's network.`;
3329
+ case "ETIMEDOUT":
3330
+ case "UND_ERR_CONNECT_TIMEOUT":
3331
+ return `connecting${at ? ` to ${at}` : ""} timed out. A firewall may be dropping the traffic, or the host is down.`;
3332
+ case "ECONNRESET":
3333
+ case "UND_ERR_SOCKET":
3334
+ return `the connection${at ? ` to ${at}` : ""} was dropped before the server answered.`;
3335
+ case "EHOSTUNREACH":
3336
+ case "ENETUNREACH":
3337
+ return `there is no route to ${at || "the host"} from this machine (${found.code}).`;
3338
+ default:
3339
+ if (/CERT|TLS|SELF_SIGNED|UNABLE_TO/.test(found.code)) {
3340
+ return `the server's TLS certificate was not accepted (${found.code}). Fix the certificate, or set NODE_EXTRA_CA_CERTS to the CA that signed it.`;
3341
+ }
3342
+ return `${found.code}${at ? ` at ${at}` : ""}`;
3343
+ }
3344
+ }
3345
+
2849
3346
  // src/mcp/connect.ts
2850
3347
  var DEFAULT_TIMEOUT_MS2 = 3e4;
2851
3348
  var STDERR_KEEP_BYTES = 2e3;
@@ -2993,13 +3490,50 @@ function buildTransport(server2, captureStderr = () => {
2993
3490
  child.stderr?.on("data", (chunk) => captureStderr(chunk.toString("utf8")));
2994
3491
  return child;
2995
3492
  }
2996
- const headers = { "user-agent": USER_AGENT, ...transport2.headers };
3493
+ const ownAgent = Object.keys(transport2.headers).some((name) => name.toLowerCase() === "user-agent");
3494
+ const headers = { ...ownAgent ? {} : { "user-agent": USER_AGENT }, ...transport2.headers };
2997
3495
  const url = new URL(transport2.url);
2998
3496
  const authProvider = createAuthProvider(server2, options);
2999
3497
  const custom = options.fetch ? { fetch: options.fetch } : {};
3000
3498
  if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider, ...custom });
3001
3499
  return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider, ...custom });
3002
3500
  }
3501
+ var KILL_GRACE_MS = 1e3;
3502
+ var signalled = /* @__PURE__ */ new Set();
3503
+ var closing = /* @__PURE__ */ new Set();
3504
+ var open = /* @__PURE__ */ new Set();
3505
+ var exitHooked = false;
3506
+ function isRunning(pid) {
3507
+ try {
3508
+ process.kill(pid, 0);
3509
+ return true;
3510
+ } catch (error) {
3511
+ return error.code === "EPERM";
3512
+ }
3513
+ }
3514
+ function signal(pid, name) {
3515
+ try {
3516
+ process.kill(pid, name);
3517
+ } catch {
3518
+ }
3519
+ }
3520
+ function stopProcess(pid) {
3521
+ if (!isRunning(pid)) return;
3522
+ signalled.add(pid);
3523
+ signal(pid, "SIGTERM");
3524
+ setTimeout(() => {
3525
+ if (isRunning(pid)) signal(pid, "SIGKILL");
3526
+ signalled.delete(pid);
3527
+ }, KILL_GRACE_MS).unref();
3528
+ }
3529
+ function hookExit() {
3530
+ if (exitHooked) return;
3531
+ exitHooked = true;
3532
+ process.on("exit", () => {
3533
+ for (const pid of [...signalled, ...closing]) signal(pid, "SIGKILL");
3534
+ for (const transport2 of open) if (transport2.pid !== null) signal(transport2.pid, "SIGKILL");
3535
+ });
3536
+ }
3003
3537
  function diagnosticLines(stderr, limit = 3) {
3004
3538
  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));
3005
3539
  const named = lines.filter((line) => /\b(error|exception|cannot|failed|refused|denied|not found|enoent|eacces)\b/i.test(line));
@@ -3034,26 +3568,55 @@ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS2, options = {}) {
3034
3568
  });
3035
3569
  }
3036
3570
  let transport2;
3037
- const guard = new SurfaceGuard(() => {
3571
+ const stop = () => {
3572
+ if (transport2 instanceof StdioClientTransport) {
3573
+ open.delete(transport2);
3574
+ if (transport2.pid !== null) stopProcess(transport2.pid);
3575
+ }
3038
3576
  void transport2?.close().catch(() => {
3039
3577
  });
3040
- });
3578
+ };
3579
+ const guard = new SurfaceGuard(stop);
3041
3580
  try {
3042
3581
  transport2 = buildTransport(server2, captureStderr, { ...options, fetch: guardedFetch(guard) });
3043
3582
  } catch (error) {
3044
3583
  throw new UnreachableServerError(server2.name, `could not prepare transport: ${error.message}`, error);
3045
3584
  }
3046
3585
  guardMessages(transport2, guard);
3586
+ const built = transport2;
3587
+ if (built instanceof StdioClientTransport) {
3588
+ hookExit();
3589
+ open.add(built);
3590
+ const start = built.start.bind(built);
3591
+ built.start = async () => {
3592
+ await start();
3593
+ if (options.signal?.aborted) {
3594
+ stop();
3595
+ throw new UnreachableServerError(server2.name, "stopped: the deadline passed while it was starting");
3596
+ }
3597
+ };
3598
+ }
3599
+ options.signal?.addEventListener("abort", stop, { once: true });
3600
+ const close = async () => {
3601
+ options.signal?.removeEventListener("abort", stop);
3602
+ const pid = built instanceof StdioClientTransport ? built.pid : null;
3603
+ if (pid !== null) closing.add(pid);
3604
+ if (built instanceof StdioClientTransport) open.delete(built);
3605
+ await client.close().catch(() => {
3606
+ });
3607
+ if (pid !== null) closing.delete(pid);
3608
+ };
3047
3609
  try {
3048
3610
  await client.connect(transport2, { timeout: timeoutMs });
3049
3611
  } catch (error) {
3050
- await client.close().catch(() => {
3051
- });
3612
+ if (options.signal?.aborted) stop();
3613
+ await close();
3052
3614
  if (guard.refusal !== void 0) throw new UnreachableServerError(server2.name, guard.refusal, error);
3053
3615
  const detail = stderrBuffer.trim();
3616
+ const network = describeNetworkFailure(error);
3054
3617
  throw new UnreachableServerError(
3055
3618
  server2.name,
3056
- `${error.message}${detail ? `
3619
+ `${boundReason(error.message, MAX_REASON_CHARS / 2)}${network ? ` (${network})` : ""}${detail ? `
3057
3620
  server stderr: ${diagnosticLines(detail).join("\n ")}` : ""}`,
3058
3621
  error
3059
3622
  );
@@ -3064,10 +3627,7 @@ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS2, options = {}) {
3064
3627
  refused: () => guard.refusal,
3065
3628
  watchChanges: () => changes.clear(),
3066
3629
  changed: () => [...changes].sort(),
3067
- close: async () => {
3068
- await client.close().catch(() => {
3069
- });
3070
- }
3630
+ close
3071
3631
  };
3072
3632
  }
3073
3633
 
@@ -3083,11 +3643,11 @@ function describeValidationIssues(message) {
3083
3643
  return void 0;
3084
3644
  }
3085
3645
  if (!Array.isArray(issues) || issues.length === 0) return void 0;
3086
- const where = (issue) => (issue.path ?? []).map((part) => typeof part === "number" ? `[${part}]` : `.${String(part)}`).join("").replace(/^\./, "");
3646
+ const where2 = (issue) => (issue.path ?? []).map((part) => typeof part === "number" ? `[${part}]` : `.${String(part)}`).join("").replace(/^\./, "");
3087
3647
  const byMessage = /* @__PURE__ */ new Map();
3088
3648
  for (const issue of issues) {
3089
3649
  const text = issue.message ?? "did not validate";
3090
- byMessage.set(text, [...byMessage.get(text) ?? [], where(issue)]);
3650
+ byMessage.set(text, [...byMessage.get(text) ?? [], where2(issue)]);
3091
3651
  }
3092
3652
  const lines = [...byMessage].slice(0, 3).map(([text, paths]) => {
3093
3653
  const rest = paths.length > 1 ? ` (and ${paths.length - 1} more like it)` : "";
@@ -3156,16 +3716,18 @@ async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS2) {
3156
3716
  let expired = false;
3157
3717
  let timer;
3158
3718
  const late = () => new UnreachableServerError(server2.name, `did not finish within ${timeoutMs}ms`);
3719
+ const giveUp = new AbortController();
3159
3720
  const deadline = new Promise((_resolve, reject) => {
3160
3721
  timer = setTimeout(() => {
3161
3722
  expired = true;
3723
+ giveUp.abort();
3162
3724
  void connection?.close();
3163
3725
  reject(late());
3164
3726
  }, timeoutMs);
3165
3727
  timer.unref?.();
3166
3728
  });
3167
3729
  const work = (async () => {
3168
- const opened = await connect(server2, timeoutMs);
3730
+ const opened = await connect(server2, timeoutMs, { signal: giveUp.signal });
3169
3731
  if (expired) {
3170
3732
  await opened.close();
3171
3733
  throw late();
@@ -3233,12 +3795,20 @@ async function readLists(client, server2, timeoutMs) {
3233
3795
  };
3234
3796
  }
3235
3797
 
3798
+ // src/lib/own.ts
3799
+ function own(record, name) {
3800
+ return record !== void 0 && Object.hasOwn(record, name) ? record[name] : void 0;
3801
+ }
3802
+ function setOwn(record, name, value) {
3803
+ Object.defineProperty(record, name, { value, enumerable: true, writable: true, configurable: true });
3804
+ }
3805
+
3236
3806
  // src/audit.ts
3237
3807
  async function provenanceOf(server2, options) {
3238
3808
  if (server2.transport.type !== "stdio") return { unverified: false };
3239
3809
  const reference = referenceOf(server2.transport, options.projectRoot);
3240
3810
  if (!reference) return { unverified: false };
3241
- const previous = options.previous?.subjects[server2.name]?.provenance;
3811
+ const previous = own(options.previous?.subjects, server2.name)?.provenance;
3242
3812
  const elsewhere = fetchedElsewhere(server2.transport, reference, { projectRoot: options.projectRoot });
3243
3813
  if (elsewhere) return { unverified: true, ...previous ? { displaced: { previous, why: elsewhere } } : {} };
3244
3814
  if (options.provenance === false) {
@@ -3267,8 +3837,10 @@ async function mapWithLimit(items, limit, worker) {
3267
3837
  async function captureAll(options) {
3268
3838
  const discovery = await discoverServers(options.projectRoot, options.configFiles, { userConfigs: options.userConfigs === true });
3269
3839
  const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
3840
+ let established;
3270
3841
  try {
3271
- const { provenance: provenance2, unverified: unverified2, displaced: displaced2 } = await provenanceOf(server2, options);
3842
+ established = await provenanceOf(server2, options);
3843
+ const { provenance: provenance2, unverified: unverified2, displaced: displaced2 } = established;
3272
3844
  const pinned = server2.transport.type === "stdio" ? launchPinned(server2.transport, provenance2) : void 0;
3273
3845
  const surface = await captureSurface(pinned ? { ...server2, transport: pinned } : server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
3274
3846
  const entry = buildLockedServer(server2, surface, options.policy);
@@ -3276,9 +3848,9 @@ async function captureAll(options) {
3276
3848
  return { name: server2.name, entry: provenance2 ? { ...entry, provenance: provenance2 } : entry, unverified: unverified2, displaced: displaced2 };
3277
3849
  } catch (error) {
3278
3850
  options.onServerDone?.(server2.name, "failed");
3279
- const reason = withoutSecrets(error instanceof UnreachableServerError ? error.message : error.message, server2);
3851
+ const reason = boundReason(withoutSecrets(error instanceof UnreachableServerError ? error.message : error.message, server2));
3280
3852
  const kind = authFailureKind(error) ?? "unreachable";
3281
- return { name: server2.name, failure: { server: server2.name, reason, kind } };
3853
+ return { name: server2.name, failure: { server: server2.name, reason, kind }, provenance: established?.provenance, displaced: established?.displaced };
3282
3854
  }
3283
3855
  });
3284
3856
  const subjects = {};
@@ -3286,21 +3858,24 @@ async function captureAll(options) {
3286
3858
  const unverified = [];
3287
3859
  const displaced = [];
3288
3860
  const unaudited = {};
3861
+ const unauditedProvenance = {};
3289
3862
  const configured = new Map(discovery.servers.map((server2) => [server2.name, server2]));
3290
3863
  for (const result of captured) {
3291
3864
  if ("entry" in result && result.entry) {
3292
- subjects[result.name] = result.entry;
3865
+ setOwn(subjects, result.name, result.entry);
3293
3866
  if (result.unverified) unverified.push(result.name);
3294
3867
  if (result.displaced) displaced.push({ server: result.name, ...result.displaced });
3295
3868
  } else if ("failure" in result && result.failure) {
3296
3869
  unreachable.push(result.failure);
3297
3870
  const server2 = configured.get(result.name);
3298
- unaudited[result.name] = server2 ? { transport: lockTransport(server2) } : {};
3871
+ setOwn(unaudited, result.name, server2 ? { transport: lockTransport(server2) } : {});
3872
+ if (result.provenance) setOwn(unauditedProvenance, result.name, result.provenance);
3873
+ if (result.displaced) displaced.push({ server: result.name, ...result.displaced });
3299
3874
  }
3300
3875
  }
3301
3876
  for (const skipped of discovery.skipped) {
3302
- unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
3303
- unaudited[skipped.serverName] = {};
3877
+ unreachable.push({ server: skipped.serverName, reason: boundReason(skipped.message), kind: "unreachable" });
3878
+ setOwn(unaudited, skipped.serverName, skipped.transport ? { transport: skipped.transport } : {});
3304
3879
  }
3305
3880
  for (const conflict of discovery.conflicts) {
3306
3881
  unreachable.push({
@@ -3310,7 +3885,7 @@ async function captureAll(options) {
3310
3885
  });
3311
3886
  }
3312
3887
  for (const problem of discovery.problems) {
3313
- unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
3888
+ unreachable.push({ server: problem.file, reason: boundReason(problem.reason), kind: "unreachable" });
3314
3889
  }
3315
3890
  return {
3316
3891
  lock: {
@@ -3324,16 +3899,43 @@ async function captureAll(options) {
3324
3899
  unverified: unverified.sort(),
3325
3900
  displaced,
3326
3901
  unaudited,
3902
+ unauditedProvenance,
3327
3903
  conflicted: discovery.conflicts.map((conflict) => conflict.name),
3328
3904
  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))
3329
3905
  };
3330
3906
  }
3331
3907
  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);
3908
+ const agreed = own(committed.unaudited, name)?.transport;
3909
+ return agreed !== void 0 && now.transport !== void 0 && stableKey(agreed) === stableKey(now.transport);
3910
+ }
3911
+ function unagreed(agreed, now, reason) {
3912
+ if (now.transport === void 0) return `could not be audited, and how it is reached could not be read either, so it cannot be agreed to: ${reason}`;
3913
+ if (agreed === void 0) return `new server, which could not be audited: ${reason}`;
3914
+ if (agreed.transport === void 0) {
3915
+ return `left unaudited by an agreement that does not say how it is reached, as an older mcp.lock's does, so nothing can tell whether it changed since; accept it with \`nulladrift review\` to record how. It could not be audited: ${reason}`;
3916
+ }
3917
+ return `a server left unaudited is now reached differently, and could not be audited: ${reason}`;
3918
+ }
3919
+ function unreadPin(name, pinned, now, runs, reason) {
3920
+ const changes = [];
3921
+ if (now.transport === void 0 || stableKey(now.transport) !== stableKey(pinned.transport)) {
3922
+ changes.push({
3923
+ kind: "server.transport.changed",
3924
+ severity: SEVERITY["server.transport.changed"],
3925
+ server: name,
3926
+ summary: `the server is reached differently than when it was pinned, and could not be audited: ${reason}`,
3927
+ before: pinned.transport,
3928
+ after: now.transport
3929
+ });
3930
+ }
3931
+ if (runs !== void 0) {
3932
+ const unread = { ...pinned, provenance: runs, digest: "unread" };
3933
+ changes.push(...diffLockfiles({ lockfileVersion: LOCKFILE_VERSION, subjects: { [name]: pinned } }, { lockfileVersion: LOCKFILE_VERSION, subjects: { [name]: unread } }));
3934
+ }
3935
+ return changes;
3334
3936
  }
3335
3937
  function compareWithLock(committed, result) {
3336
- const changes = diffLockfiles(committed, result.lock);
3938
+ const changes = diffLockfiles(committed, result.lock).filter((change2) => !(change2.kind === "server.removed" && own(result.unaudited, change2.server) !== void 0));
3337
3939
  for (const moved of result.displaced) {
3338
3940
  const was = `${moved.previous.name}${moved.previous.version ? `@${moved.previous.version}` : ""}`;
3339
3941
  changes.push({
@@ -3346,16 +3948,21 @@ function compareWithLock(committed, result) {
3346
3948
  }
3347
3949
  const failed = new Map(result.unreachable.map((failure) => [failure.server, failure.reason]));
3348
3950
  for (const [name, now] of Object.entries(result.unaudited)) {
3349
- if (committed.subjects[name] !== void 0 || acknowledged(committed, name, now)) continue;
3951
+ const pinned = own(committed.subjects, name);
3952
+ if (pinned !== void 0) {
3953
+ changes.push(...unreadPin(name, pinned, now, own(result.unauditedProvenance, name), failed.get(name) ?? "it did not answer"));
3954
+ continue;
3955
+ }
3956
+ if (acknowledged(committed, name, now)) continue;
3350
3957
  changes.push({
3351
3958
  kind: "server.added",
3352
3959
  severity: SEVERITY["server.added"],
3353
3960
  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"}`
3961
+ summary: unagreed(own(committed.unaudited, name), now, failed.get(name) ?? "it did not answer")
3355
3962
  });
3356
3963
  }
3357
3964
  for (const name of result.conflicted) {
3358
- if (committed.subjects[name] !== void 0) continue;
3965
+ if (own(committed.subjects, name) !== void 0) continue;
3359
3966
  changes.push({
3360
3967
  kind: "server.added",
3361
3968
  severity: SEVERITY["server.added"],
@@ -3366,19 +3973,64 @@ function compareWithLock(committed, result) {
3366
3973
  return sortChanges(changes);
3367
3974
  }
3368
3975
  function unauditedToRecord(result, keep = () => true) {
3369
- const entries = Object.entries(result.unaudited).filter(([name]) => keep(name));
3976
+ const entries = Object.entries(result.unaudited).filter(([name, entry]) => entry.transport !== void 0 && name !== "__proto__" && keep(name));
3370
3977
  return entries.length > 0 ? Object.fromEntries(entries) : void 0;
3371
3978
  }
3979
+ function decoded2(value) {
3980
+ try {
3981
+ return decodeURIComponent(value);
3982
+ } catch {
3983
+ return value;
3984
+ }
3985
+ }
3986
+ function addressSecrets(address) {
3987
+ let url;
3988
+ try {
3989
+ url = new URL(address);
3990
+ } catch {
3991
+ return [];
3992
+ }
3993
+ const out = [url.username, url.password, decoded2(url.username), decoded2(url.password)];
3994
+ for (const [, value] of url.searchParams) out.push(value);
3995
+ for (const pair of url.search.slice(1).split("&")) out.push(pair.slice(pair.indexOf("=") + 1));
3996
+ if (url.hash.length > 1) out.push(url.hash.slice(1));
3997
+ const kept = redactPath(url.pathname).split("/");
3998
+ url.pathname.split("/").forEach((segment, index) => {
3999
+ if (kept[index] !== segment) out.push(segment, decoded2(segment));
4000
+ });
4001
+ return out;
4002
+ }
4003
+ function replacedParts(original, redacted) {
4004
+ const kept = redacted.split(REDACTED);
4005
+ const parts = [];
4006
+ let at = 0;
4007
+ for (const [index, piece] of kept.entries()) {
4008
+ const found = index === 0 ? original.startsWith(piece) ? 0 : -1 : index === kept.length - 1 ? original.endsWith(piece) && original.length - piece.length >= at ? original.length - piece.length : -1 : original.indexOf(piece, at);
4009
+ if (found < 0) return [original];
4010
+ if (index > 0) parts.push(original.slice(at, found));
4011
+ at = found + piece.length;
4012
+ }
4013
+ return parts;
4014
+ }
3372
4015
  function withoutSecrets(reason, server2) {
3373
4016
  const { transport: transport2 } = server2;
3374
4017
  const secrets = [];
4018
+ for (const { name, value } of transport2.filled ?? []) {
4019
+ if (isCredentialName(name) || !/^(?:[./~]|[A-Za-z]:\\)/.test(value)) secrets.push(value, ...addressSecrets(value));
4020
+ }
3375
4021
  if (transport2.type === "stdio") {
3376
4022
  for (const [name, value] of Object.entries(transport2.env)) {
3377
4023
  if (isCredentialName(name) || value.length >= 16 && !/[\s/\\]/.test(value)) secrets.push(value);
3378
4024
  }
4025
+ const redacted = redactArgs(transport2.args);
4026
+ transport2.args.forEach((argument, index) => {
4027
+ const kept = redacted[index];
4028
+ if (kept !== void 0 && kept !== argument) secrets.push(...replacedParts(argument, kept));
4029
+ });
3379
4030
  } else {
3380
4031
  for (const value of Object.values(transport2.headers)) secrets.push(value, ...value.split(/\s+/));
3381
4032
  if (transport2.oauth?.clientSecret) secrets.push(transport2.oauth.clientSecret);
4033
+ secrets.push(...addressSecrets(transport2.url));
3382
4034
  }
3383
4035
  let out = reason;
3384
4036
  for (const secret of [...new Set(secrets)].filter((value) => value.length >= 8).sort((a, b) => b.length - a.length)) {
@@ -3674,9 +4326,9 @@ function parseLockfile(text, path) {
3674
4326
  }
3675
4327
  const parsed = lockfileSchema.safeParse(raw);
3676
4328
  if (!parsed.success) {
3677
- const first = parsed.error.issues[0];
3678
- const where = first && first.path.length > 0 ? ` at ${first.path.join(".")}` : "";
3679
- throw new LockfileError(`${path} is not a valid lockfile${where}: ${first?.message ?? "unknown error"}`);
4329
+ const first2 = parsed.error.issues[0];
4330
+ const where2 = first2 && first2.path.length > 0 ? ` at ${first2.path.join(".")}` : "";
4331
+ throw new LockfileError(`${path} is not a valid lockfile${where2}: ${first2?.message ?? "unknown error"}`);
3680
4332
  }
3681
4333
  return parsed.data;
3682
4334
  }
@@ -3745,8 +4397,8 @@ function renderTextChange(before, after) {
3745
4397
  return lines;
3746
4398
  }
3747
4399
  function renderChange(change2) {
3748
- const where = visibleControls(change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server);
3749
- const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where)} ${dim(change2.kind)}`, ` ${visibleControls(change2.summary)}`];
4400
+ const where2 = visibleControls(change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server);
4401
+ const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where2)} ${dim(change2.kind)}`, ` ${visibleControls(change2.summary)}`];
3750
4402
  if (change2.kind === "tool.description.changed" || change2.kind === "server.instructions.changed") {
3751
4403
  lines.push(...renderTextChange(change2.before, change2.after));
3752
4404
  }
@@ -3763,7 +4415,7 @@ function renderSteering(report) {
3763
4415
  for (const { server: server2, signals } of found) {
3764
4416
  lines.push(` ${bold(visibleControls(server2))}`);
3765
4417
  const byField = /* @__PURE__ */ new Map();
3766
- for (const signal of signals) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
4418
+ for (const signal2 of signals) byField.set(signal2.field, [...byField.get(signal2.field) ?? [], signal2.quote]);
3767
4419
  const fields = [...byField];
3768
4420
  for (const [field, quotes] of fields.slice(0, 4)) {
3769
4421
  const more = quotes.length > 1 ? ` (+${quotes.length - 1} more here)` : "";
@@ -3877,7 +4529,7 @@ function redactedLine(count) {
3877
4529
  function redactedNotes(lock) {
3878
4530
  return Object.entries(lock.subjects).flatMap(([name, entry]) => {
3879
4531
  const count = countRedacted(entry.transport);
3880
- return count > 0 ? [`${name}: ${redactedLine(count)}`] : [];
4532
+ return count > 0 ? [`${visibleControls(name)}: ${redactedLine(count)}`] : [];
3881
4533
  });
3882
4534
  }
3883
4535
 
@@ -3948,6 +4600,13 @@ function helpUriFor(anchor) {
3948
4600
  return base === void 0 ? void 0 : `${base}/blob/main/docs/lockfile.md#${anchor}`;
3949
4601
  }
3950
4602
 
4603
+ // src/report/types.ts
4604
+ var AUDIT_FAILURE_LABEL = {
4605
+ auth: "refused the audit",
4606
+ forbidden: "accepted the credentials and refused",
4607
+ unreachable: "unreachable"
4608
+ };
4609
+
3951
4610
  // src/report/sarif.ts
3952
4611
  var LEVEL = {
3953
4612
  high: "error",
@@ -3958,6 +4617,7 @@ var DENIED_RULE = "policy.capability.denied";
3958
4617
  var STEERING_RULE = "steering.passage.arrived";
3959
4618
  var UNVERIFIED_RULE = "server.artifact.unverified";
3960
4619
  var PARTIAL_RULE = "server.surface.partial";
4620
+ var UNREAD_RULE = "server.surface.unread";
3961
4621
  var RULE_HELP = {
3962
4622
  "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.",
3963
4623
  "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.",
@@ -3985,6 +4645,7 @@ function renderSarifReport(report, options = {}) {
3985
4645
  const steering = options.steering ? report.steering ?? [] : [];
3986
4646
  const unverified = report.unverified ?? [];
3987
4647
  const partial = report.partial ?? [];
4648
+ const unread = report.unreachable;
3988
4649
  const at = (name, qualified) => [
3989
4650
  {
3990
4651
  physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
@@ -4013,6 +4674,13 @@ function renderSarifReport(report, options = {}) {
4013
4674
  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
4675
  defaultConfiguration: { level: "warning" }
4015
4676
  }] : [],
4677
+ ...unread.length > 0 ? [{
4678
+ id: UNREAD_RULE,
4679
+ name: "ServerSurfaceUnread",
4680
+ shortDescription: { text: "A server's surface could not be read" },
4681
+ fullDescription: { text: "The server did not answer, refused the audit, or its configuration could not be used, so its surface was not compared. The audit did not finish, which fails it unless --allow-unreachable makes that a warning." },
4682
+ defaultConfiguration: { level: "warning" }
4683
+ }] : [],
4016
4684
  ...unverified.length > 0 ? [{
4017
4685
  id: UNVERIFIED_RULE,
4018
4686
  name: "ServerArtifactUnverified",
@@ -4060,12 +4728,12 @@ function renderSarifReport(report, options = {}) {
4060
4728
  partialFingerprints: { "mcpAuditChange/v1": `${violation.server}/${violation.tool}/${violation.kind}` }
4061
4729
  })),
4062
4730
  ...steering.flatMap(
4063
- ({ server: server2, signals }) => signals.map((signal) => ({
4731
+ ({ server: server2, signals }) => signals.map((signal2) => ({
4064
4732
  ruleId: STEERING_RULE,
4065
4733
  level: "note",
4066
- message: { text: `${server2} \u203A ${signal.field}: ${signal.quote}` },
4067
- locations: at(signal.field, `${server2}/${signal.field}`),
4068
- partialFingerprints: { "mcpAuditChange/v1": `${server2}/${signal.field}/${signal.kind}` }
4734
+ message: { text: `${server2} \u203A ${signal2.field}: ${signal2.quote}` },
4735
+ locations: at(signal2.field, `${server2}/${signal2.field}`),
4736
+ partialFingerprints: { "mcpAuditChange/v1": `${server2}/${signal2.field}/${signal2.kind}` }
4069
4737
  }))
4070
4738
  ),
4071
4739
  ...partial.map((entry) => ({
@@ -4075,6 +4743,13 @@ function renderSarifReport(report, options = {}) {
4075
4743
  locations: at(entry.server, entry.server),
4076
4744
  partialFingerprints: { "mcpAuditChange/v1": `${entry.server}/partial` }
4077
4745
  })),
4746
+ ...unread.map((failure) => ({
4747
+ ruleId: UNREAD_RULE,
4748
+ level: "warning",
4749
+ message: { text: `${failure.server}: could not be read (${AUDIT_FAILURE_LABEL[failure.kind]}). ${failure.reason}` },
4750
+ locations: at(failure.server, failure.server),
4751
+ partialFingerprints: { "mcpAuditChange/v1": `${failure.server}/unread` }
4752
+ })),
4078
4753
  ...unverified.map((server2) => ({
4079
4754
  ruleId: UNVERIFIED_RULE,
4080
4755
  level: "note",
@@ -4091,11 +4766,6 @@ function renderSarifReport(report, options = {}) {
4091
4766
  }
4092
4767
 
4093
4768
  // src/report/markdown.ts
4094
- var AUDIT_FAILURE_LABEL = {
4095
- auth: "refused the audit",
4096
- forbidden: "accepted the credentials and refused",
4097
- unreachable: "unreachable"
4098
- };
4099
4769
  var MARK2 = { high: "\u{1F534}", medium: "\u{1F7E0}", low: "\u26AA" };
4100
4770
  function plain(text) {
4101
4771
  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();
@@ -4108,8 +4778,15 @@ function code(text) {
4108
4778
  return `${fence}${pad}${body}${pad}${fence}`;
4109
4779
  }
4110
4780
  function row(change2) {
4111
- const where = change2.member ? `${change2.server}/${change2.member}` : change2.server;
4112
- return `| ${MARK2[change2.severity]} ${change2.severity} | ${code(where)} | ${plain(change2.kind)} | ${plain(change2.summary)} |`;
4781
+ const where2 = change2.member ? `${change2.server}/${change2.member}` : change2.server;
4782
+ return `| ${MARK2[change2.severity]} ${change2.severity} | ${code(where2)} | ${plain(change2.kind)} | ${plain(change2.summary)} |`;
4783
+ }
4784
+ function renderResolvedReport(report) {
4785
+ return [
4786
+ "### Nothing to review: every server matches the lock",
4787
+ "",
4788
+ `An earlier run reported findings here. On this one, all ${report.serversChecked} server${report.serversChecked === 1 ? "" : "s"} matched what was approved, and none failed to answer.`
4789
+ ].join("\n");
4113
4790
  }
4114
4791
  function renderMarkdownReport(report, options = {}) {
4115
4792
  const violations = report.violations ?? [];
@@ -4163,7 +4840,7 @@ function renderMarkdownReport(report, options = {}) {
4163
4840
  "| Server | Field | Passage |",
4164
4841
  "| --- | --- | --- |",
4165
4842
  ...steering.flatMap(
4166
- ({ server: server2, signals }) => signals.slice(0, 10).map((signal) => `| ${code(server2)} | ${code(signal.field)} | ${plain(signal.quote)} |`)
4843
+ ({ server: server2, signals }) => signals.slice(0, 10).map((signal2) => `| ${code(server2)} | ${code(signal2.field)} | ${plain(signal2.quote)} |`)
4167
4844
  ),
4168
4845
  "",
4169
4846
  "</details>",
@@ -4215,6 +4892,15 @@ function renderMarkdownReport(report, options = {}) {
4215
4892
 
4216
4893
  // src/report/comment.ts
4217
4894
  var MARKER = "<!-- nulladrift:surface -->";
4895
+ var PER_PAGE = 100;
4896
+ var MAX_COMMENT_PAGES = 10;
4897
+ var MAX_COMMENT_CHARS = 65536;
4898
+ function fitted(body) {
4899
+ if (body.length <= MAX_COMMENT_CHARS) return body;
4900
+ const note = "\n\n_The rest of this report was cut short to fit a comment; the job log has all of it._";
4901
+ const room = body.slice(0, MAX_COMMENT_CHARS - note.length);
4902
+ return `${room.slice(0, Math.max(room.lastIndexOf("\n"), 0))}${note}`;
4903
+ }
4218
4904
  function targetFromEnvironment(env = process.env) {
4219
4905
  const token = env["GITHUB_TOKEN"];
4220
4906
  const repo = env["GITHUB_REPOSITORY"];
@@ -4242,20 +4928,26 @@ async function call(target, path, init = {}) {
4242
4928
  signal: AbortSignal.timeout(1e4)
4243
4929
  });
4244
4930
  }
4245
- async function upsertComment(target, body) {
4246
- const marked = `${MARKER}
4247
- ${body}`;
4248
- const existing = await call(target, `/issues/${target.issue}/comments?per_page=100`);
4249
- if (existing.status === 403) return "forbidden";
4250
- if (!existing.ok) throw new Error(`could not read the comments (${existing.status})`);
4251
- const self = await identity2(target);
4252
- const comments = await existing.json();
4253
- const mine = comments.find((comment2) => comment2.body?.startsWith(MARKER) && comment2.user?.login === self);
4931
+ async function upsertComment(target, body, options = {}) {
4932
+ const marked = fitted(`${MARKER}
4933
+ ${body}`);
4934
+ let self;
4935
+ let mine;
4936
+ for (let page = 1; page <= MAX_COMMENT_PAGES && mine === void 0; page += 1) {
4937
+ const existing = await call(target, `/issues/${target.issue}/comments?per_page=${PER_PAGE}&page=${page}`);
4938
+ if (existing.status === 403) return "forbidden";
4939
+ if (!existing.ok) throw new Error(`could not read the comments (${existing.status})`);
4940
+ self ??= await identity2(target);
4941
+ const comments = await existing.json();
4942
+ mine = comments.find((comment2) => comment2.body?.startsWith(MARKER) && comment2.user?.login === self);
4943
+ if (comments.length < PER_PAGE) break;
4944
+ }
4254
4945
  if (mine) {
4255
4946
  const updated = await call(target, `/issues/comments/${mine.id}`, { method: "PATCH", body: JSON.stringify({ body: marked }) });
4256
4947
  if (updated.ok) return "updated";
4257
4948
  if (updated.status !== 403 && updated.status !== 404) throw new Error(`could not update the comment (${updated.status})`);
4258
4949
  }
4950
+ if (options.create === false) return "none";
4259
4951
  const created = await call(target, `/issues/${target.issue}/comments`, { method: "POST", body: JSON.stringify({ body: marked }) });
4260
4952
  if (created.status === 403) return "forbidden";
4261
4953
  if (!created.ok) throw new Error(`could not post the comment (${created.status})`);
@@ -4442,9 +5134,9 @@ async function comment(report) {
4442
5134
  return;
4443
5135
  }
4444
5136
  const body = renderMarkdownReport(report);
4445
- if (!body) return;
4446
5137
  try {
4447
- const outcome = await upsertComment(target, body);
5138
+ const outcome = await upsertComment(target, body ?? renderResolvedReport(report), { create: body !== null });
5139
+ if (outcome === "none") return;
4448
5140
  if (outcome === "forbidden") {
4449
5141
  process.stderr.write(
4450
5142
  `${yellow("--comment:")} the token cannot write comments on this repository. A pull request from a fork gets a read-only token; give the job \`pull-requests: write\` if it is not one.
@@ -4630,7 +5322,7 @@ async function runInit(options) {
4630
5322
  );
4631
5323
  if (steering.length > 0) {
4632
5324
  const byField = /* @__PURE__ */ new Map();
4633
- for (const signal of steering) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
5325
+ for (const signal2 of steering) byField.set(signal2.field, [...byField.get(signal2.field) ?? [], signal2.quote]);
4634
5326
  const fields = [...byField];
4635
5327
  lines.push(
4636
5328
  ` ${yellow(`${fields.length} field(s) carry text read as instructions to the model, not documentation:`)}`
@@ -4650,6 +5342,13 @@ async function runInit(options) {
4650
5342
  for (const failure of result.unreachable) {
4651
5343
  lines.push(` ${red("\u2717")} ${bold(visibleControls(failure.server))} ${dim("not pinned")}`, ` ${visibleLines(failure.reason, " ")}`);
4652
5344
  }
5345
+ const unagreeable = Object.keys(result.unaudited).filter((name) => options.allowUnreachable && !Object.hasOwn(unaudited ?? {}, name));
5346
+ if (unagreeable.length > 0) {
5347
+ lines.push(
5348
+ dim(` note: ${unagreeable.map((name) => visibleControls(name)).join(", ")} cannot be left unaudited: how ${unagreeable.length === 1 ? "it is" : "they are"} reached could not be read, so`),
5349
+ dim(" there is nothing to agree to. `check` will report it until the definition is fixed or removed.")
5350
+ );
5351
+ }
4653
5352
  if (result.discovery.userConfigsSkipped.length > 0) {
4654
5353
  lines.push(
4655
5354
  dim(` note: your own configs were not pinned (${result.discovery.userConfigsSkipped.join(", ")}). mcp.lock is the project's and is committed;`),
@@ -4657,7 +5356,7 @@ async function runInit(options) {
4657
5356
  );
4658
5357
  }
4659
5358
  for (const shadow of result.discovery.shadowed) {
4660
- lines.push(dim(` note: "${shadow.name}" is defined in both ${shadow.keptFrom} and ${shadow.alsoIn}; kept the first.`));
5359
+ lines.push(dim(visibleControls(` note: "${shadow.name}" is defined in both ${shadow.keptFrom} and ${shadow.alsoIn}; kept the first.`)));
4661
5360
  }
4662
5361
  lines.push(
4663
5362
  "",
@@ -4667,6 +5366,7 @@ async function runInit(options) {
4667
5366
  process.stdout.write(lines.join("\n"));
4668
5367
  await maybeOfferTelemetry();
4669
5368
  if (result.unreachable.length > 0 && !options.allowUnreachable) return EXIT_INCOMPLETE;
5369
+ if (!pinnedSomething) return EXIT_INCOMPLETE;
4670
5370
  if (result.partial.length > 0 && !options.allowPartial) return EXIT_INCOMPLETE;
4671
5371
  return EXIT_CLEAN;
4672
5372
  }
@@ -4712,8 +5412,8 @@ async function awaitCallback(expectedState) {
4712
5412
  server2.listen(0, "127.0.0.1", ready);
4713
5413
  });
4714
5414
  const { port } = server2.address();
4715
- const received = new Promise((resolve7, reject) => {
4716
- settle = resolve7;
5415
+ const received = new Promise((resolve8, reject) => {
5416
+ settle = resolve8;
4717
5417
  fail = reject;
4718
5418
  setTimeout(() => reject(new Error(`no callback within ${CALLBACK_TIMEOUT_MS / 1e3}s`)), CALLBACK_TIMEOUT_MS).unref();
4719
5419
  });
@@ -4730,9 +5430,9 @@ async function findServer(projectRoot, configFiles, name) {
4730
5430
  const named = new Set(configFiles.map((file) => portablePath(resolve5(projectRoot, file), projectRoot)));
4731
5431
  const chosen = conflict.definitions.filter((definition) => named.has(definition.file));
4732
5432
  if (chosen.length === 1) return chosen[0].server;
4733
- const where = conflict.definitions.map((definition) => ` ${definition.file}: ${describeTarget(definition.server)}`).join("\n");
5433
+ const where2 = conflict.definitions.map((definition) => ` ${definition.file}: ${describeTarget(definition.server)}`).join("\n");
4734
5434
  return { error: `"${name}" is defined differently in more than one config:
4735
- ${where}
5435
+ ${where2}
4736
5436
  Name the one you mean with --config <file>.` };
4737
5437
  }
4738
5438
  const server2 = discovery.servers.find((candidate) => candidate.name === name);
@@ -4755,7 +5455,7 @@ async function runLogin(options) {
4755
5455
  }
4756
5456
  const found = await findServer(options.projectRoot, options.configFiles, options.serverName);
4757
5457
  if ("error" in found) {
4758
- process.stderr.write(`${red(found.error)}
5458
+ process.stderr.write(`${red(visibleControls(found.error, { multiline: true }))}
4759
5459
  `);
4760
5460
  return EXIT_INCOMPLETE;
4761
5461
  }
@@ -4765,8 +5465,8 @@ async function runLogin(options) {
4765
5465
  const authenticating = new FileTokenProvider(found.name, serverUrl, { interactive: true, redirectUrl: callback.redirectUrl });
4766
5466
  Object.assign(authenticating, { stateValue: provider.stateValue });
4767
5467
  try {
4768
- process.stdout.write(`${bold(`Authorizing ${found.name}`)}
4769
- ${dim(sanitizeUrl(serverUrl))}
5468
+ process.stdout.write(`${bold(`Authorizing ${visibleControls(found.name)}`)}
5469
+ ${dim(visibleControls(sanitizeUrl(serverUrl)))}
4770
5470
  `);
4771
5471
  const started = await auth(authenticating, { serverUrl });
4772
5472
  if (started === "AUTHORIZED") {
@@ -4781,7 +5481,7 @@ ${dim(sanitizeUrl(serverUrl))}
4781
5481
  `);
4782
5482
  return EXIT_INCOMPLETE;
4783
5483
  }
4784
- process.stdout.write(`${green(`\u2713 authorized ${found.name}`)}
5484
+ process.stdout.write(`${green(`\u2713 authorized ${visibleControls(found.name)}`)}
4785
5485
  ${dim(`tokens stored in ${credentialPath(serverUrl)} (owner-only)`)}
4786
5486
  `);
4787
5487
  return EXIT_CLEAN;
@@ -4801,7 +5501,7 @@ async function runLogout(options) {
4801
5501
  }
4802
5502
  const found = await findServer(options.projectRoot, options.configFiles, options.serverName);
4803
5503
  if ("error" in found) {
4804
- process.stderr.write(`${red(found.error)}
5504
+ process.stderr.write(`${red(visibleControls(found.error, { multiline: true }))}
4805
5505
  `);
4806
5506
  return EXIT_INCOMPLETE;
4807
5507
  }
@@ -4813,7 +5513,7 @@ async function runLogout(options) {
4813
5513
  );
4814
5514
  await rm4(path, { force: true });
4815
5515
  process.stdout.write(
4816
- `${dim(existed ? `stored credentials for ${found.name} (${sanitizeUrl(url)}) deleted` : `no credentials were stored for ${found.name} (${sanitizeUrl(url)})`)}
5516
+ `${dim(visibleControls(existed ? `stored credentials for ${found.name} (${sanitizeUrl(url)}) deleted` : `no credentials were stored for ${found.name} (${sanitizeUrl(url)})`))}
4817
5517
  `
4818
5518
  );
4819
5519
  return EXIT_CLEAN;
@@ -4907,29 +5607,181 @@ async function fromGithubActions(audience, env, options) {
4907
5607
  }
4908
5608
  }
4909
5609
 
5610
+ // src/lib/origin.ts
5611
+ import { existsSync as existsSync2, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
5612
+ import { dirname as dirname4, isAbsolute as isAbsolute4, join as join5, resolve as resolve6 } from "path";
5613
+ var MAX_PROJECT = 200;
5614
+ var MAX_REF = 200;
5615
+ function first(env, ...names) {
5616
+ for (const name of names) {
5617
+ const value = env[name]?.trim();
5618
+ if (value) return value;
5619
+ }
5620
+ return void 0;
5621
+ }
5622
+ function shortRef(ref) {
5623
+ return ref.replace(/^refs\/(heads|tags)\//, "");
5624
+ }
5625
+ function repositoryPath(remote) {
5626
+ const url = remote.trim();
5627
+ let path;
5628
+ const scp = /^(?:[^/@:\s]+@)?[^/:\s\\]{2,}:(?!\/)([^\\]+)$/.exec(url);
5629
+ if (scp) path = scp[1];
5630
+ else {
5631
+ try {
5632
+ path = new URL(url).pathname;
5633
+ } catch {
5634
+ return void 0;
5635
+ }
5636
+ }
5637
+ const azure = /\/_git\/([^/]+)/.exec(path ?? "");
5638
+ if (azure) path = azure[1];
5639
+ const cleaned = (path ?? "").replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
5640
+ return cleaned && !cleaned.includes("..") ? cleaned : void 0;
5641
+ }
5642
+ function projectFromCi(env) {
5643
+ const named = first(env, "GITHUB_REPOSITORY", "CI_PROJECT_PATH", "BITBUCKET_REPO_FULL_NAME", "BUILD_REPOSITORY_NAME");
5644
+ if (named) return named;
5645
+ const user = first(env, "CIRCLE_PROJECT_USERNAME");
5646
+ const repo = first(env, "CIRCLE_PROJECT_REPONAME");
5647
+ if (user && repo) return `${user}/${repo}`;
5648
+ const buildkite = first(env, "BUILDKITE_REPO");
5649
+ return buildkite ? repositoryPath(buildkite) : void 0;
5650
+ }
5651
+ function refFromCi(env) {
5652
+ const ref = first(
5653
+ env,
5654
+ "GITHUB_REF_NAME",
5655
+ "CI_COMMIT_REF_NAME",
5656
+ "BUILD_SOURCEBRANCH",
5657
+ "BITBUCKET_BRANCH",
5658
+ "BITBUCKET_TAG",
5659
+ "CIRCLE_BRANCH",
5660
+ "CIRCLE_TAG",
5661
+ "BUILDKITE_BRANCH"
5662
+ );
5663
+ return ref ? shortRef(ref) : void 0;
5664
+ }
5665
+ function commitFromCi(env) {
5666
+ return first(env, "GITHUB_SHA", "CI_COMMIT_SHA", "BUILD_SOURCEVERSION", "BITBUCKET_COMMIT", "CIRCLE_SHA1", "BUILDKITE_COMMIT");
5667
+ }
5668
+ function read(path) {
5669
+ try {
5670
+ if (!statSync2(path).isFile() || statSync2(path).size > 4 * 1024 * 1024) return void 0;
5671
+ return readFileSync3(path, "utf8");
5672
+ } catch {
5673
+ return void 0;
5674
+ }
5675
+ }
5676
+ function gitDirectories(start) {
5677
+ let dir = resolve6(start);
5678
+ for (let depth = 0; depth < 64; depth += 1) {
5679
+ const dotGit = join5(dir, ".git");
5680
+ if (existsSync2(dotGit)) {
5681
+ let gitDir = dotGit;
5682
+ try {
5683
+ if (statSync2(dotGit).isFile()) {
5684
+ const pointer = /^gitdir:\s*(.+)$/m.exec(read(dotGit) ?? "")?.[1]?.trim();
5685
+ if (!pointer) return void 0;
5686
+ gitDir = isAbsolute4(pointer) ? pointer : resolve6(dir, pointer);
5687
+ }
5688
+ } catch {
5689
+ return void 0;
5690
+ }
5691
+ const common = read(join5(gitDir, "commondir"))?.trim();
5692
+ return { gitDir, commonDir: common ? resolve6(gitDir, common) : gitDir };
5693
+ }
5694
+ const parent = dirname4(dir);
5695
+ if (parent === dir) return void 0;
5696
+ dir = parent;
5697
+ }
5698
+ return void 0;
5699
+ }
5700
+ function resolveRef(commonDir, ref) {
5701
+ if (!/^refs\/[\w./-]+$/.test(ref) || ref.includes("..")) return void 0;
5702
+ const loose = read(join5(commonDir, ref))?.trim();
5703
+ if (loose && /^[0-9a-f]{40,64}$/.test(loose)) return loose;
5704
+ for (const line of (read(join5(commonDir, "packed-refs")) ?? "").split("\n")) {
5705
+ const [sha, name] = line.trim().split(" ");
5706
+ if (name === ref && sha && /^[0-9a-f]{40,64}$/.test(sha)) return sha;
5707
+ }
5708
+ return void 0;
5709
+ }
5710
+ function remoteUrl(commonDir) {
5711
+ const config = read(join5(commonDir, "config"));
5712
+ if (!config) return void 0;
5713
+ const remotes = /* @__PURE__ */ new Map();
5714
+ let current;
5715
+ for (const raw of config.split("\n")) {
5716
+ const line = raw.trim();
5717
+ const section = /^\[\s*remote\s+"([^"]+)"\s*\]$/.exec(line);
5718
+ if (section) {
5719
+ current = section[1];
5720
+ continue;
5721
+ }
5722
+ if (line.startsWith("[")) {
5723
+ current = void 0;
5724
+ continue;
5725
+ }
5726
+ const url = /^url\s*=\s*(.+)$/.exec(line);
5727
+ if (current && url?.[1] && !remotes.has(current)) remotes.set(current, url[1].trim());
5728
+ }
5729
+ return remotes.get("origin") ?? remotes.values().next().value;
5730
+ }
5731
+ function repositoryFacts(root) {
5732
+ const dirs = gitDirectories(root);
5733
+ if (!dirs) return {};
5734
+ const head = read(join5(dirs.gitDir, "HEAD"))?.trim() ?? "";
5735
+ const symbolic = /^ref:\s*(refs\/\S+)$/.exec(head)?.[1];
5736
+ const commit = symbolic ? resolveRef(dirs.commonDir, symbolic) : /^[0-9a-f]{40,64}$/.test(head) ? head : void 0;
5737
+ const remote = remoteUrl(dirs.commonDir);
5738
+ return {
5739
+ project: remote ? repositoryPath(remote) : void 0,
5740
+ // A detached HEAD has a commit and no branch, which is what CI checkouts usually are.
5741
+ ref: symbolic?.startsWith("refs/heads/") ? shortRef(symbolic) : void 0,
5742
+ commit
5743
+ };
5744
+ }
5745
+ function readingOrigin(root, flags, env = process.env) {
5746
+ const repo = repositoryFacts(root);
5747
+ const usable = (value, max) => value && value.length <= max ? value : void 0;
5748
+ let project;
5749
+ let projectFrom;
5750
+ const ci = usable(projectFromCi(env), MAX_PROJECT);
5751
+ const fromRepo = usable(repo.project, MAX_PROJECT);
5752
+ if (flags.project) {
5753
+ project = flags.project;
5754
+ projectFrom = "flag";
5755
+ } else if (ci) {
5756
+ project = ci;
5757
+ projectFrom = "ci";
5758
+ } else if (fromRepo) {
5759
+ project = fromRepo;
5760
+ projectFrom = "repository";
5761
+ } else {
5762
+ project = resolve6(root).split(/[\\/]/).filter(Boolean).pop() ?? "default";
5763
+ projectFrom = "folder";
5764
+ }
5765
+ return {
5766
+ project,
5767
+ projectFrom,
5768
+ ref: flags.ref ?? usable(refFromCi(env), MAX_REF) ?? usable(repo.ref, MAX_REF),
5769
+ commit: flags.commit ?? commitFromCi(env) ?? repo.commit
5770
+ };
5771
+ }
5772
+
4910
5773
  // src/commands/push.ts
4911
5774
  function describeIdentity(identity3, hint) {
4912
5775
  const shown = (text) => visibleControls(text);
4913
- const where = shown(`${identity3?.repository ?? ""}${identity3?.ref ? ` @ ${identity3.ref}` : ""}`);
5776
+ const where2 = shown(`${identity3?.repository ?? ""}${identity3?.ref ? ` @ ${identity3.ref}` : ""}`);
4914
5777
  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}`)}`;
5778
+ if (identity3?.trust === "trusted") return `${green("signed")} ${dim(`${where2} \xB7 a trusted build${contents}`)}`;
4916
5779
  if (identity3?.trust === "verified") {
4917
- return `${yellow("signed")} ${dim(`${where} \xB7 not a build this organization lists as trusted${contents}`)}`;
5780
+ return `${yellow("signed")} ${dim(`${where2} \xB7 not a build this organization lists as trusted${contents}`)}`;
4918
5781
  }
4919
5782
  if (identity3?.rejected) return `${red("build token refused")} ${dim(shown(identity3.rejected))}`;
4920
5783
  return hint ? dim(`unsigned: ${hint}`) : void 0;
4921
5784
  }
4922
- function inferProject(projectRoot) {
4923
- const fromCi = process.env["GITHUB_REPOSITORY"] ?? process.env["CI_PROJECT_PATH"] ?? process.env["BUILD_REPOSITORY_NAME"];
4924
- if (fromCi) return fromCi;
4925
- return projectRoot.split("/").filter(Boolean).pop() ?? "default";
4926
- }
4927
- function inferRef() {
4928
- return process.env["GITHUB_REF_NAME"] ?? process.env["CI_COMMIT_REF_NAME"] ?? void 0;
4929
- }
4930
- function inferCommit() {
4931
- return process.env["GITHUB_SHA"] ?? process.env["CI_COMMIT_SHA"] ?? void 0;
4932
- }
4933
5785
  function refuseApiUrl(apiUrl) {
4934
5786
  let url;
4935
5787
  try {
@@ -5005,10 +5857,29 @@ ${dim(`Looked in: ${looked}`)}
5005
5857
  promptCount: entry.prompts?.length ?? 0,
5006
5858
  surface: entry
5007
5859
  }));
5860
+ for (const [flag, value, max] of [
5861
+ ["--project", options.project, 200],
5862
+ ["--ref", options.ref, 200],
5863
+ ["--commit", options.commit, 100]
5864
+ ]) {
5865
+ const control = value !== void 0 && [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127);
5866
+ if (value !== void 0 && (value.trim() === "" || value.length > max || control)) {
5867
+ process.stderr.write(`${red(`${flag} has to be 1 to ${max} characters, with no control characters.`)}
5868
+ `);
5869
+ return EXIT_INCOMPLETE;
5870
+ }
5871
+ }
5872
+ const origin = readingOrigin(options.projectRoot, { project: options.project, ref: options.ref, commit: options.commit });
5873
+ if (origin.projectFrom === "folder") {
5874
+ process.stderr.write(
5875
+ `${yellow("note:")} reporting as project "${visibleControls(origin.project)}", this folder's name: no --project, CI variable or git remote names it. Pass --project so every push names it the same way.
5876
+ `
5877
+ );
5878
+ }
5008
5879
  const body = {
5009
- project: options.project ?? inferProject(options.projectRoot),
5010
- ref: options.ref ?? inferRef(),
5011
- commit: options.commit ?? inferCommit(),
5880
+ project: origin.project,
5881
+ ref: origin.ref,
5882
+ commit: origin.commit,
5012
5883
  context: options.watch ? "watch" : process.env["CI"] !== void 0 && process.env["CI"] !== "false" ? "ci" : "local",
5013
5884
  collectorVersion: VERSION,
5014
5885
  servers,
@@ -5062,7 +5933,8 @@ ${dim(`Looked in: ${looked}`)}
5062
5933
  const lines = [""];
5063
5934
  const mark = verdict.verdict === "clean" ? green("\u2713") : verdict.verdict === "drift" ? yellow("!") : red("\u2717");
5064
5935
  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)}`)}`);
5936
+ lines.push(`${mark} ${bold(shown(verdict.verdict))} ${dim(`\xB7 ${shown(origin.project)} \xB7 ${servers.length} server(s) \xB7 reading ${shown(verdict.readingId).slice(0, 8)}`)}`);
5937
+ if (origin.ref || origin.commit) lines.push(` ${dim(`at ${shown(origin.ref ?? "a detached commit")}${origin.commit ? ` @ ${shown(origin.commit).slice(0, 7)}` : ""}`)}`);
5066
5938
  const identity3 = describeIdentity(verdict.identity, build && "hint" in build ? build.hint : void 0);
5067
5939
  if (identity3) lines.push(` ${identity3}`);
5068
5940
  for (const change2 of verdict.changes) {
@@ -5074,6 +5946,12 @@ ${dim(`Looked in: ${looked}`)}
5074
5946
  if (verdict.verdict !== "clean") lines.push("", dim(`Review it at ${shown(verdict.url)}`));
5075
5947
  lines.push("");
5076
5948
  process.stdout.write(lines.join("\n"));
5949
+ if (result.unreachable.length > 0) {
5950
+ process.stderr.write(
5951
+ `${yellow("not read:")} ${result.unreachable.map((failure) => visibleControls(failure.server)).join(", ")} could not be reached, so ${result.unreachable.length === 1 ? "it was" : "they were"} not audited. Whether that fails the build is the control plane's policy.
5952
+ `
5953
+ );
5954
+ }
5077
5955
  if (result.partial.length > 0 && options.allowPartial !== true) {
5078
5956
  process.stderr.write(
5079
5957
  `${yellow("incomplete:")} ${result.partial.map((entry) => visibleControls(entry.server)).join(", ")} could not be read in full. Pass --allow-partial to accept that.
@@ -5097,13 +5975,13 @@ function describeSurface(subject, previous) {
5097
5975
  lines.push(worst ? yellow(text) : dim(text));
5098
5976
  }
5099
5977
  const had = new Set(
5100
- (typeof previous === "object" && previous !== null ? surfaceText(previous).flatMap((piece) => steeringSignals(piece.text, piece.field)) : []).map((signal) => `${signal.field}\0${signal.kind}\0${signal.quote}`)
5978
+ (typeof previous === "object" && previous !== null ? surfaceText(previous).flatMap((piece) => steeringSignals(piece.text, piece.field)) : []).map((signal2) => `${signal2.field}\0${signal2.kind}\0${signal2.quote}`)
5101
5979
  );
5102
- const steering = surfaceText(entry).flatMap((piece) => steeringSignals(piece.text, piece.field)).filter((signal) => !had.has(`${signal.field}\0${signal.kind}\0${signal.quote}`));
5980
+ const steering = surfaceText(entry).flatMap((piece) => steeringSignals(piece.text, piece.field)).filter((signal2) => !had.has(`${signal2.field}\0${signal2.kind}\0${signal2.quote}`));
5103
5981
  if (steering.length > 0) {
5104
5982
  lines.push(yellow(` ${steering.length} new passage(s) here read as instructions to the model:`));
5105
5983
  const byField = /* @__PURE__ */ new Map();
5106
- for (const signal of steering) if (!byField.has(signal.field)) byField.set(signal.field, signal.quote);
5984
+ for (const signal2 of steering) if (!byField.has(signal2.field)) byField.set(signal2.field, signal2.quote);
5107
5985
  for (const [field, quote] of [...byField].slice(0, 3)) {
5108
5986
  lines.push(dim(` ${elideMiddle(field, 52)}: ${truncate(quote, 72)}`));
5109
5987
  }
@@ -5161,7 +6039,7 @@ async function runReview(options) {
5161
6039
  let declined = 0;
5162
6040
  try {
5163
6041
  for (const [serverName, serverChanges] of grouped) {
5164
- const context = describeSurface(result.lock.subjects[serverName], committed.subjects[serverName]);
6042
+ const context = describeSurface(own(result.lock.subjects, serverName), own(committed.subjects, serverName));
5165
6043
  process.stdout.write(
5166
6044
  `
5167
6045
  ${bold(visibleControls(serverName))}
@@ -5179,21 +6057,36 @@ ${context.length > 0 ? `${context.join("\n")}
5179
6057
  declined += 1;
5180
6058
  continue;
5181
6059
  }
6060
+ const unread = own(result.lock.subjects, serverName) === void 0 ? own(result.unaudited, serverName) : void 0;
6061
+ if (unread !== void 0 && own(committed.subjects, serverName) !== void 0) {
6062
+ process.stdout.write(
6063
+ ` ${yellow("not accepted: it could not be read, so there is nothing to pin in place of what was approved, and the pin is kept. Review it where it answers, or pin again with `nulladrift init --force`.")}
6064
+ `
6065
+ );
6066
+ declined += 1;
6067
+ continue;
6068
+ }
6069
+ if (unread !== void 0 && unread.transport === void 0) {
6070
+ process.stdout.write(` ${yellow("not accepted: how this server is reached could not be read, so there is nothing to agree to. Fix or remove its definition.")}
6071
+ `);
6072
+ declined += 1;
6073
+ continue;
6074
+ }
5182
6075
  accepted += 1;
5183
- let fresh = result.lock.subjects[serverName];
5184
- const pin = committed.subjects[serverName]?.provenance;
6076
+ let fresh = own(result.lock.subjects, serverName);
6077
+ const pin = own(committed.subjects, serverName)?.provenance;
5185
6078
  const displaced = result.displaced.some((moved) => moved.server === serverName);
5186
6079
  if (fresh && fresh.provenance === void 0 && pin !== void 0 && result.unverified.includes(serverName) && !displaced) {
5187
6080
  fresh = { ...fresh, provenance: pin };
5188
6081
  }
5189
- if (fresh) next.subjects[serverName] = fresh;
6082
+ if (fresh) setOwn(next.subjects, serverName, fresh);
5190
6083
  else delete next.subjects[serverName];
5191
6084
  const unaudited = { ...next.unaudited };
5192
- if (!fresh && result.unaudited[serverName] !== void 0) unaudited[serverName] = result.unaudited[serverName];
6085
+ if (!fresh && unread !== void 0) setOwn(unaudited, serverName, unread);
5193
6086
  else delete unaudited[serverName];
5194
6087
  next.unaudited = Object.keys(unaudited).length > 0 ? unaudited : void 0;
5195
6088
  for (const change2 of serverChanges) {
5196
- if (change2.kind === "server.renamed" && typeof change2.before === "string") delete next.subjects[change2.before];
6089
+ if (change2.kind === "server.renamed" && typeof change2.before === "string" && own(result.unaudited, change2.before) === void 0) delete next.subjects[change2.before];
5197
6090
  }
5198
6091
  }
5199
6092
  } finally {
@@ -5240,7 +6133,9 @@ ${bold("Options")}
5240
6133
  --force re-pin over an existing lockfile, discarding it (init)
5241
6134
  --api <url> control plane to push to (push; or NULLADRIFT_API_URL)
5242
6135
  --token <token> collector token (push; or NULLADRIFT_TOKEN)
5243
- --project <name> project name to report under (push; inferred from CI otherwise)
6136
+ --project <name> project to report under (push; else from CI, then the git remote, then the folder)
6137
+ --ref <branch> branch or tag to record (push; else from CI, then the checked-out branch)
6138
+ --commit <sha> commit to record (push; else from CI, then HEAD)
5244
6139
  --watch mark this as a scheduled reading rather than one a build asked for (push)
5245
6140
  --comment post the findings on the pull request being reviewed (check; needs CI)
5246
6141
  -h, --help this text
@@ -5273,6 +6168,8 @@ async function main() {
5273
6168
  api: { type: "string" },
5274
6169
  token: { type: "string" },
5275
6170
  project: { type: "string" },
6171
+ ref: { type: "string" },
6172
+ commit: { type: "string" },
5276
6173
  watch: { type: "boolean", default: false },
5277
6174
  comment: { type: "boolean", default: false },
5278
6175
  help: { type: "boolean", short: "h", default: false },
@@ -5301,10 +6198,10 @@ async function main() {
5301
6198
  `);
5302
6199
  return EXIT_INCOMPLETE;
5303
6200
  }
5304
- const projectRoot = resolve6(values.cwd ?? process.cwd());
6201
+ const projectRoot = resolve7(values.cwd ?? process.cwd());
5305
6202
  const options = {
5306
6203
  projectRoot,
5307
- lockPath: resolve6(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
6204
+ lockPath: resolve7(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
5308
6205
  configFiles: values.config ?? [],
5309
6206
  timeoutMs,
5310
6207
  allowUnreachable: values["allow-unreachable"],
@@ -5321,7 +6218,7 @@ async function main() {
5321
6218
  case "check":
5322
6219
  return runCheck(options);
5323
6220
  case "push":
5324
- return runPush({ ...options, apiUrl: values.api, token: values.token, project: values.project, watch: values.watch });
6221
+ return runPush({ ...options, apiUrl: values.api, token: values.token, project: values.project, ref: values.ref, commit: values.commit, watch: values.watch });
5325
6222
  case "review":
5326
6223
  return runReview({ ...options, acceptAll: values["accept-all"] });
5327
6224
  case "login":