nulladrift 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ var CHANGE_KINDS = [
26
26
  "tool.behavior.escalated",
27
27
  "tool.behavior.relaxed",
28
28
  "tool.header_params.changed",
29
+ "tool.capability.gained",
29
30
  "tool.changed",
30
31
  "resource.added",
31
32
  "resource.removed",
@@ -58,6 +59,12 @@ var SEVERITY = {
58
59
  "tool.behavior.escalated": "high",
59
60
  "tool.behavior.relaxed": "low",
60
61
  "tool.header_params.changed": "high",
62
+ /*
63
+ * Severity is set per change rather than read from here: what a tool gained decides it. A
64
+ * `command` argument is not the same finding as a `url` one, and flattening both to one number
65
+ * is how "accepts input it did not before" came to describe arbitrary command execution.
66
+ */
67
+ "tool.capability.gained": "high",
61
68
  "tool.changed": "medium",
62
69
  "resource.added": "medium",
63
70
  "resource.removed": "low",
@@ -316,6 +323,111 @@ function sanitizeUrl(raw) {
316
323
  }
317
324
  }
318
325
 
326
+ // ../core/src/risk/capability.ts
327
+ var CAPABILITY_SEVERITIES = ["critical", "high", "medium", "low"];
328
+ var CAPABILITY_KINDS = [
329
+ "process-exec",
330
+ "code-eval",
331
+ "credential-access",
332
+ "file-write",
333
+ "network-egress",
334
+ "database",
335
+ "privilege",
336
+ "agent-control",
337
+ "env-access",
338
+ "file-read"
339
+ ];
340
+ var RULES = [
341
+ { kind: "process-exec", severity: "critical", name: /(^|_)(exec|execute|spawn|shell|bash|sh|cmd|command|run_command|terminal|subprocess)(_|$)/, arg: /(^|_)(command|cmd|argv|shell|exec|script)(_|$)/ },
342
+ // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and
343
+ // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that
344
+ // teaches people to stop reading the line. `code` has to be the whole argument name for the
345
+ // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code
346
+ // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
347
+ { 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)(_|$)/ },
348
+ { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
349
+ { 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)(_|$)/ },
350
+ { 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)(_|$)/ },
351
+ // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
352
+ // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
353
+ // none of which is a database.
354
+ { kind: "database", severity: "high", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },
355
+ { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
356
+ { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
357
+ { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
358
+ { 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)(_|$)/ }
359
+ ];
360
+ var CONFUSABLES = {
361
+ "\u0430": "a",
362
+ "\u0435": "e",
363
+ "\u043E": "o",
364
+ "\u0441": "c",
365
+ "\u0440": "p",
366
+ "\u0445": "x",
367
+ "\u0443": "y",
368
+ "\u0456": "i",
369
+ "\u0458": "j",
370
+ "\u04BB": "h",
371
+ "\u0501": "d",
372
+ "\u051B": "q",
373
+ "\u03BF": "o",
374
+ "\u03B1": "a",
375
+ "\u03B5": "e",
376
+ "\u03BD": "v",
377
+ "\u03C1": "p",
378
+ "\u03C5": "u",
379
+ "\u0131": "i",
380
+ "\u1E9E": "s"
381
+ };
382
+ var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g");
383
+ function normalize(identifier) {
384
+ return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
385
+ }
386
+ function argumentNames(inputSchema, depth = 0) {
387
+ if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
388
+ const node = inputSchema;
389
+ const names = [];
390
+ const properties = node.properties;
391
+ if (typeof properties === "object" && properties !== null) {
392
+ for (const [name, child] of Object.entries(properties)) {
393
+ names.push(name);
394
+ names.push(...argumentNames(child, depth + 1));
395
+ }
396
+ }
397
+ if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
398
+ return names;
399
+ }
400
+ function toolCapabilities(tool2) {
401
+ const name = normalize(tool2.name ?? "");
402
+ const args = argumentNames(tool2.inputSchema).map((argument) => [argument, normalize(argument)]);
403
+ const found = /* @__PURE__ */ new Map();
404
+ for (const rule of RULES) {
405
+ if (found.has(rule.kind)) continue;
406
+ if (rule.name?.test(name)) {
407
+ found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: "name" });
408
+ continue;
409
+ }
410
+ const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
411
+ if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
412
+ }
413
+ return [...found.values()].sort(
414
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
415
+ );
416
+ }
417
+ function surfaceCapabilities(tools) {
418
+ const byKind = /* @__PURE__ */ new Map();
419
+ for (const tool2 of tools) {
420
+ for (const capability of toolCapabilities(tool2)) {
421
+ const existing = byKind.get(capability.kind);
422
+ if (existing) existing.tools.push(tool2.name ?? "?");
423
+ else byKind.set(capability.kind, { ...capability, tools: [tool2.name ?? "?"] });
424
+ }
425
+ }
426
+ return [...byKind.values()].sort(
427
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
428
+ );
429
+ }
430
+
319
431
  // ../core/src/diff/schema.ts
320
432
  function numberAt(node, key) {
321
433
  const value = node[key];
@@ -460,6 +572,32 @@ function compareCapabilities(before, after, name) {
460
572
  }
461
573
  return [change("server.capabilities.changed", name, "declared capabilities changed", { before: before.capabilities, after: after.capabilities })];
462
574
  }
575
+ var CAPABILITY_SEVERITY = {
576
+ critical: "high",
577
+ high: "high",
578
+ medium: "medium",
579
+ low: "low"
580
+ };
581
+ function compareToolCapabilities(server2, before, after) {
582
+ const previous = indexBy(before, (tool2) => tool2.name);
583
+ const changes = [];
584
+ for (const tool2 of after ?? []) {
585
+ const existing = previous.get(tool2.name);
586
+ if (!existing) continue;
587
+ const had = new Set(toolCapabilities(existing).map((capability) => capability.kind));
588
+ for (const capability of toolCapabilities(tool2)) {
589
+ if (had.has(capability.kind)) continue;
590
+ changes.push(
591
+ change("tool.capability.gained", server2, `can now ${capability.kind} (${capability.evidence})`, {
592
+ member: tool2.name,
593
+ severity: CAPABILITY_SEVERITY[capability.severity],
594
+ after: { kind: capability.kind, severity: capability.severity, evidence: capability.evidence }
595
+ })
596
+ );
597
+ }
598
+ }
599
+ return changes;
600
+ }
463
601
  function compareTool(name, before, after) {
464
602
  if (before.digest === after.digest) return [];
465
603
  const changes = [];
@@ -517,7 +655,10 @@ function compareMembers(name, before, after, spec, deep) {
517
655
  for (const [key, member] of next) {
518
656
  const existing = previous.get(key);
519
657
  if (!existing) {
520
- changes.push(change(spec.added, name, `new ${spec.noun} ${spec.label(member)}`, { member: spec.label(member), after: member }));
658
+ const extra = spec.arriving?.(member);
659
+ changes.push(
660
+ change(spec.added, name, `new ${spec.noun} ${spec.label(member)}${extra ? ` \xB7 ${extra}` : ""}`, { member: spec.label(member), after: member })
661
+ );
521
662
  continue;
522
663
  }
523
664
  if (existing.digest === member.digest) continue;
@@ -561,10 +702,22 @@ function compareServer(name, before, after) {
561
702
  name,
562
703
  before.tools,
563
704
  after.tools,
564
- { key: (t) => t.name, label: (t) => t.name, added: "tool.added", removed: "tool.removed", changed: "tool.changed", noun: "tool" },
705
+ {
706
+ key: (t) => t.name,
707
+ label: (t) => t.name,
708
+ added: "tool.added",
709
+ removed: "tool.removed",
710
+ changed: "tool.changed",
711
+ noun: "tool",
712
+ arriving: (t) => {
713
+ const can = toolCapabilities(t);
714
+ return can.length > 0 ? `can ${can.map((capability) => capability.kind).join(", ")}` : "";
715
+ }
716
+ },
565
717
  (_key, a, b) => compareTool(name, a, b)
566
718
  )
567
719
  );
720
+ changes.push(...compareToolCapabilities(name, before.tools, after.tools));
568
721
  changes.push(
569
722
  ...compareMembers(name, before.resources, after.resources, {
570
723
  key: (r) => r.uri,
@@ -644,99 +797,6 @@ function diffLockfiles(before, after) {
644
797
  return sortChanges(changes);
645
798
  }
646
799
 
647
- // ../core/src/risk/capability.ts
648
- var CAPABILITY_SEVERITIES = ["critical", "high", "medium", "low"];
649
- var RULES = [
650
- { kind: "process-exec", severity: "critical", name: /(^|_)(exec|execute|spawn|shell|bash|sh|cmd|command|run_command|terminal|subprocess)(_|$)/, arg: /(^|_)(command|cmd|argv|shell|exec|script)(_|$)/ },
651
- // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and
652
- // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that
653
- // teaches people to stop reading the line. `code` has to be the whole argument name for the
654
- // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code
655
- // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
656
- { 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)(_|$)/ },
657
- { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
658
- { 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)(_|$)/ },
659
- { 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)(_|$)/ },
660
- // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
661
- // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
662
- // none of which is a database.
663
- { kind: "database", severity: "high", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },
664
- { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
665
- { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
666
- { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
667
- { 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)(_|$)/ }
668
- ];
669
- var CONFUSABLES = {
670
- "\u0430": "a",
671
- "\u0435": "e",
672
- "\u043E": "o",
673
- "\u0441": "c",
674
- "\u0440": "p",
675
- "\u0445": "x",
676
- "\u0443": "y",
677
- "\u0456": "i",
678
- "\u0458": "j",
679
- "\u04BB": "h",
680
- "\u0501": "d",
681
- "\u051B": "q",
682
- "\u03BF": "o",
683
- "\u03B1": "a",
684
- "\u03B5": "e",
685
- "\u03BD": "v",
686
- "\u03C1": "p",
687
- "\u03C5": "u",
688
- "\u0131": "i",
689
- "\u1E9E": "s"
690
- };
691
- var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g");
692
- function normalize(identifier) {
693
- return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
694
- }
695
- function argumentNames(inputSchema, depth = 0) {
696
- if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
697
- const node = inputSchema;
698
- const names = [];
699
- const properties = node.properties;
700
- if (typeof properties === "object" && properties !== null) {
701
- for (const [name, child] of Object.entries(properties)) {
702
- names.push(name);
703
- names.push(...argumentNames(child, depth + 1));
704
- }
705
- }
706
- if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
707
- return names;
708
- }
709
- function toolCapabilities(tool2) {
710
- const name = normalize(tool2.name ?? "");
711
- const args = argumentNames(tool2.inputSchema).map((argument) => [argument, normalize(argument)]);
712
- const found = /* @__PURE__ */ new Map();
713
- for (const rule of RULES) {
714
- if (found.has(rule.kind)) continue;
715
- if (rule.name?.test(name)) {
716
- found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: "name" });
717
- continue;
718
- }
719
- const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
720
- if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
721
- }
722
- return [...found.values()].sort(
723
- (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
724
- );
725
- }
726
- function surfaceCapabilities(tools) {
727
- const byKind = /* @__PURE__ */ new Map();
728
- for (const tool2 of tools) {
729
- for (const capability of toolCapabilities(tool2)) {
730
- const existing = byKind.get(capability.kind);
731
- if (existing) existing.tools.push(tool2.name ?? "?");
732
- else byKind.set(capability.kind, { ...capability, tools: [tool2.name ?? "?"] });
733
- }
734
- }
735
- return [...byKind.values()].sort(
736
- (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
737
- );
738
- }
739
-
740
800
  // ../core/src/risk/steering.ts
741
801
  var PATTERNS = [
742
802
  // Imperatives aimed at the reader of the prompt, not at a person reading documentation.
@@ -790,6 +850,22 @@ function steeringSignals(text, field) {
790
850
  return found;
791
851
  }
792
852
 
853
+ // ../core/src/risk/policy.ts
854
+ function capabilityViolations(lock, denied) {
855
+ if (!denied || denied.length === 0) return [];
856
+ const forbidden = new Set(denied);
857
+ const found = [];
858
+ for (const [server2, subject] of Object.entries(lock.subjects ?? {})) {
859
+ for (const tool2 of subject.tools ?? []) {
860
+ for (const capability of toolCapabilities(tool2)) {
861
+ if (!forbidden.has(capability.kind)) continue;
862
+ found.push({ server: server2, tool: tool2.name ?? "?", kind: capability.kind, severity: capability.severity, evidence: capability.evidence });
863
+ }
864
+ }
865
+ }
866
+ return found.sort((a, b) => a.server.localeCompare(b.server) || a.tool.localeCompare(b.tool) || a.kind.localeCompare(b.kind));
867
+ }
868
+
793
869
  // ../core/src/risk/surface-text.ts
794
870
  var MAX_NODES = 2e4;
795
871
  function schemaText(root, rootPath, out) {
@@ -1355,7 +1431,7 @@ import { dirname, join as join2 } from "path";
1355
1431
  import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
1356
1432
 
1357
1433
  // src/lib/version.ts
1358
- var VERSION = "0.2.0";
1434
+ var VERSION = "0.3.0";
1359
1435
  var USER_AGENT = `nulladrift/${VERSION}`;
1360
1436
 
1361
1437
  // src/mcp/oauth.ts
@@ -1886,7 +1962,13 @@ var lockfileSchema = z2.object({
1886
1962
  generatedBy: z2.string().optional(),
1887
1963
  policy: z2.object({
1888
1964
  ignoreMetaPrefixes: z2.array(z2.string()).optional(),
1889
- allowUnreachable: z2.boolean().optional()
1965
+ allowUnreachable: z2.boolean().optional(),
1966
+ /*
1967
+ * Validated against the real list rather than accepted as free strings: a policy with
1968
+ * `process_exec` in it would otherwise parse, forbid nothing, and read in the diff of
1969
+ * whoever added it as though the rule were in force.
1970
+ */
1971
+ deniedCapabilities: z2.array(z2.enum(CAPABILITY_KINDS)).optional()
1890
1972
  }).optional(),
1891
1973
  /*
1892
1974
  * One map for everything pinned, each entry saying what it is. `z.discriminatedUnion` on a
@@ -1900,7 +1982,7 @@ var lockfileSchema = z2.object({
1900
1982
  var DEFAULT_LOCK_FILENAME = "mcp.lock";
1901
1983
  var KEY_ORDER = {
1902
1984
  root: ["lockfileVersion", "generatedBy", "policy", "subjects"],
1903
- policy: ["ignoreMetaPrefixes", "allowUnreachable"],
1985
+ policy: ["ignoreMetaPrefixes", "allowUnreachable", "deniedCapabilities"],
1904
1986
  server: ["kind", "source", "transport", "protocol", "serverInfo", "capabilities", "instructions", "tools", "resources", "resourceTemplates", "prompts", "digest"],
1905
1987
  source: ["client", "file", "scope"],
1906
1988
  transport: ["type", "command", "args", "envKeys", "cwd", "url", "headerKeys"],
@@ -2116,8 +2198,27 @@ function renderSteering(report) {
2116
2198
  lines.push("", dim("This did not change the verdict. Read the passages and decide; a server documenting"), dim('"before using this tool, call authenticate first" has the same shape as an attack.'), "");
2117
2199
  return lines;
2118
2200
  }
2201
+ function renderViolations(report) {
2202
+ const found = report.violations ?? [];
2203
+ if (found.length === 0) return [];
2204
+ const lines = ["", bold(red(`${found.length} capability(ies) this project does not permit:`)), ""];
2205
+ for (const violation of found) {
2206
+ lines.push(
2207
+ ` ${red("denied")} ${bold(`${violation.server} \u203A ${violation.tool}`)} ${dim(violation.kind)}`,
2208
+ ` ${violation.severity} \xB7 ${violation.evidence}`
2209
+ );
2210
+ }
2211
+ lines.push(
2212
+ "",
2213
+ dim("Set by `policy.deniedCapabilities` in the lockfile. Accepting the change does not clear"),
2214
+ dim("this; remove the capability, or change the policy deliberately."),
2215
+ ""
2216
+ );
2217
+ return lines;
2218
+ }
2119
2219
  function renderHumanReport(report) {
2120
2220
  const lines = [];
2221
+ lines.push(...renderViolations(report));
2121
2222
  if (report.changes.length > 0) {
2122
2223
  const drifted = new Set(report.changes.map((change2) => change2.server)).size;
2123
2224
  const heading = drifted > report.serversChecked ? `Drift in ${drifted} server(s); ${report.serversChecked} still configured:` : `Drift in ${drifted} of ${report.serversChecked} server(s):`;
@@ -2140,7 +2241,7 @@ function renderHumanReport(report) {
2140
2241
  }
2141
2242
  }
2142
2243
  lines.push(...renderSteering(report));
2143
- if (report.changes.length === 0 && report.unreachable.length === 0) {
2244
+ if (report.changes.length === 0 && report.unreachable.length === 0 && (report.violations ?? []).length === 0) {
2144
2245
  lines.push(green(`\u2713 ${report.serversChecked} server(s) match ${report.lockPath}`));
2145
2246
  return `${lines.join("\n")}
2146
2247
  `;
@@ -2190,7 +2291,9 @@ function renderJsonReport(report, exitCode) {
2190
2291
  * Counted separately from `changes` because it is not part of the verdict. A consumer
2191
2292
  * that gates on this field is gating on a regex, which is the thing this must never be.
2192
2293
  */
2193
- steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0)
2294
+ steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0),
2295
+ /** Unlike steering, these DO decide the exit code. */
2296
+ violations: (report.violations ?? []).length
2194
2297
  },
2195
2298
  changes: report.changes.map((change2) => ({
2196
2299
  kind: change2.kind,
@@ -2203,7 +2306,8 @@ function renderJsonReport(report, exitCode) {
2203
2306
  })),
2204
2307
  unreachable: report.unreachable,
2205
2308
  /** Text that began addressing the model since the lock was approved. Reported, never gated. */
2206
- steering: report.steering ?? []
2309
+ steering: report.steering ?? [],
2310
+ violations: report.violations ?? []
2207
2311
  },
2208
2312
  null,
2209
2313
  2
@@ -2237,7 +2341,10 @@ var LEVEL = {
2237
2341
  medium: "warning",
2238
2342
  low: "note"
2239
2343
  };
2344
+ var DENIED_RULE = "policy.capability.denied";
2345
+ var STEERING_RULE = "steering.passage.arrived";
2240
2346
  var RULE_HELP = {
2347
+ "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.",
2241
2348
  "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.",
2242
2349
  "server.instructions.changed": "The server's instructions string is placed in the model's system prompt by the client. Treat a change the way you would treat a change to prompt source.",
2243
2350
  "tool.behavior.escalated": "The tool now claims a power it did not claim when it was pinned. Annotation defaults are not neutral: removing readOnlyHint is an escalation.",
@@ -2255,8 +2362,32 @@ function sarifUri(report) {
2255
2362
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) return report.lockPath;
2256
2363
  return rel.split(sep2).join("/");
2257
2364
  }
2258
- function renderSarifReport(report) {
2365
+ function renderSarifReport(report, options = {}) {
2259
2366
  const used = [...new Set(report.changes.map((change2) => change2.kind))].sort();
2367
+ const violations = report.violations ?? [];
2368
+ const steering = options.steering ? report.steering ?? [] : [];
2369
+ const at = (name, qualified) => [
2370
+ {
2371
+ physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
2372
+ logicalLocations: [{ name, fullyQualifiedName: qualified, kind: "member" }]
2373
+ }
2374
+ ];
2375
+ const extraRules = [
2376
+ ...violations.length > 0 ? [{
2377
+ id: DENIED_RULE,
2378
+ name: "PolicyCapabilityDenied",
2379
+ shortDescription: { text: "A capability this project does not permit" },
2380
+ fullDescription: { text: "A pinned tool has a capability listed in policy.deniedCapabilities. Derived from the shape of the declaration, and not cleared by accepting the change." },
2381
+ defaultConfiguration: { level: "error" }
2382
+ }] : [],
2383
+ ...steering.length > 0 ? [{
2384
+ id: STEERING_RULE,
2385
+ name: "SteeringPassageArrived",
2386
+ shortDescription: { text: "Text that began addressing the model" },
2387
+ fullDescription: { text: "A passage a model is shown started reading as an instruction since this lock was approved. A signal to read, not a verdict: legitimate servers trip the same shape. It does not affect the exit code." },
2388
+ defaultConfiguration: { level: "note" }
2389
+ }] : []
2390
+ ];
2260
2391
  const document = {
2261
2392
  $schema: "https://json.schemastore.org/sarif-2.1.0.json",
2262
2393
  version: "2.1.0",
@@ -2267,28 +2398,44 @@ function renderSarifReport(report) {
2267
2398
  name: "nulladrift",
2268
2399
  version: VERSION,
2269
2400
  ...publishedDocsUrl() === void 0 ? {} : { informationUri: publishedDocsUrl() },
2270
- rules: (used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
2271
- id: kind,
2272
- name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
2273
- shortDescription: { text: `MCP capability drift: ${kind}` },
2274
- fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
2275
- defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
2276
- ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
2277
- }))
2401
+ rules: [
2402
+ ...(used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
2403
+ id: kind,
2404
+ name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
2405
+ shortDescription: { text: `MCP capability drift: ${kind}` },
2406
+ fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
2407
+ defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
2408
+ ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
2409
+ })),
2410
+ ...extraRules
2411
+ ]
2278
2412
  }
2279
2413
  },
2280
- results: report.changes.map((change2) => ({
2281
- ruleId: change2.kind,
2282
- level: LEVEL[change2.severity],
2283
- message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
2284
- locations: [
2285
- {
2286
- physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
2287
- logicalLocations: [{ name: change2.member ?? change2.server, fullyQualifiedName: change2.member ? `${change2.server}/${change2.member}` : change2.server, kind: "member" }]
2288
- }
2289
- ],
2290
- partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
2291
- }))
2414
+ results: [
2415
+ ...report.changes.map((change2) => ({
2416
+ ruleId: change2.kind,
2417
+ level: LEVEL[change2.severity],
2418
+ message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
2419
+ locations: at(change2.member ?? change2.server, change2.member ? `${change2.server}/${change2.member}` : change2.server),
2420
+ partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
2421
+ })),
2422
+ ...violations.map((violation) => ({
2423
+ ruleId: DENIED_RULE,
2424
+ level: "error",
2425
+ message: { text: `${violation.server} \u203A ${violation.tool}: ${violation.kind} is not permitted here (${violation.evidence})` },
2426
+ locations: at(violation.tool, `${violation.server}/${violation.tool}`),
2427
+ partialFingerprints: { "mcpAuditChange/v1": `${violation.server}/${violation.tool}/${violation.kind}` }
2428
+ })),
2429
+ ...steering.flatMap(
2430
+ ({ server: server2, signals }) => signals.map((signal) => ({
2431
+ ruleId: STEERING_RULE,
2432
+ level: "note",
2433
+ message: { text: `${server2} \u203A ${signal.field}: ${signal.quote}` },
2434
+ locations: at(signal.field, `${server2}/${signal.field}`),
2435
+ partialFingerprints: { "mcpAuditChange/v1": `${server2}/${signal.field}/${signal.kind}` }
2436
+ }))
2437
+ )
2438
+ ]
2292
2439
  }
2293
2440
  ]
2294
2441
  };
@@ -2530,6 +2677,11 @@ async function buildReport(options) {
2530
2677
  * first" must not be able to fail somebody's build.
2531
2678
  */
2532
2679
  steering: newSteering(committed, result.lock),
2680
+ /*
2681
+ * Against the freshly read surface, not the diff. A rule saying nothing here may execute
2682
+ * processes has to fail on the day it is added, not on the next day a server happens to move.
2683
+ */
2684
+ violations: capabilityViolations(result.lock, committed.policy?.deniedCapabilities),
2533
2685
  unreachable: result.unreachable,
2534
2686
  serversChecked: Object.keys(result.lock.subjects).length,
2535
2687
  lockPath: options.lockPath,
@@ -2538,7 +2690,12 @@ async function buildReport(options) {
2538
2690
  return {
2539
2691
  report,
2540
2692
  exitCode: resolveExitCode({
2541
- driftCount: changes.length,
2693
+ /*
2694
+ * A forbidden capability fails the build like drift does. It is not drift -- nothing moved
2695
+ * -- but the surface is not one the project permits, and `review --accept-all` must not be
2696
+ * able to make it pass: policy is the thing acceptance cannot overrule.
2697
+ */
2698
+ driftCount: changes.length + (report.violations?.length ?? 0),
2542
2699
  incompleteCount: allowUnreachable ? 0 : result.unreachable.length
2543
2700
  })
2544
2701
  };
@@ -2546,7 +2703,7 @@ async function buildReport(options) {
2546
2703
  async function runCheck(options) {
2547
2704
  const { report, exitCode } = await buildReport(options);
2548
2705
  if (options.format === "json") process.stdout.write(renderJsonReport(report, exitCode));
2549
- else if (options.format === "sarif") process.stdout.write(renderSarifReport(report));
2706
+ else if (options.format === "sarif") process.stdout.write(renderSarifReport(report, { steering: options.sarifSteering }));
2550
2707
  else process.stdout.write(renderHumanReport(report));
2551
2708
  await reportIfChanged(report, report.changes);
2552
2709
  if (options.comment) await comment(report);
@@ -3039,6 +3196,30 @@ ${dim(`Looked in: ${looked}`)}
3039
3196
 
3040
3197
  // src/commands/review.ts
3041
3198
  import { createInterface as createInterface2 } from "readline/promises";
3199
+ function describeSurface(subject, previous) {
3200
+ if (typeof subject !== "object" || subject === null) return [];
3201
+ const entry = subject;
3202
+ const lines = [];
3203
+ const capabilities = surfaceCapabilities(entry.tools ?? []);
3204
+ if (capabilities.length > 0) {
3205
+ const worst = capabilities.some((c) => c.severity === "critical" || c.severity === "high");
3206
+ const text = ` after accepting, this server can: ${capabilities.map((c) => c.kind).join(", ")}`;
3207
+ lines.push(worst ? yellow(text) : dim(text));
3208
+ }
3209
+ const had = new Set(
3210
+ (typeof previous === "object" && previous !== null ? surfaceText(previous).flatMap((piece) => steeringSignals(piece.text, piece.field)) : []).map((signal) => `${signal.field}\0${signal.kind}\0${signal.quote}`)
3211
+ );
3212
+ const steering = surfaceText(entry).flatMap((piece) => steeringSignals(piece.text, piece.field)).filter((signal) => !had.has(`${signal.field}\0${signal.kind}\0${signal.quote}`));
3213
+ if (steering.length > 0) {
3214
+ lines.push(yellow(` ${steering.length} new passage(s) here read as instructions to the model:`));
3215
+ const byField = /* @__PURE__ */ new Map();
3216
+ for (const signal of steering) if (!byField.has(signal.field)) byField.set(signal.field, signal.quote);
3217
+ for (const [field, quote] of [...byField].slice(0, 3)) {
3218
+ lines.push(dim(` ${elideMiddle(field, 52)}: ${truncate(quote, 72)}`));
3219
+ }
3220
+ }
3221
+ return lines;
3222
+ }
3042
3223
  function describe(change2) {
3043
3224
  const head = ` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${change2.member ? `${bold(change2.member)}: ` : ""}${change2.summary} ${dim(change2.kind)}`;
3044
3225
  if (change2.kind !== "tool.description.changed" && change2.kind !== "server.instructions.changed") return head;
@@ -3082,10 +3263,14 @@ async function runReview(options) {
3082
3263
  let declined = 0;
3083
3264
  try {
3084
3265
  for (const [serverName, serverChanges] of grouped) {
3085
- process.stdout.write(`
3266
+ const context = describeSurface(result.lock.subjects[serverName], committed.subjects[serverName]);
3267
+ process.stdout.write(
3268
+ `
3086
3269
  ${bold(serverName)}
3087
3270
  ${serverChanges.map(describe).join("\n")}
3088
- `);
3271
+ ${context.length > 0 ? `${context.join("\n")}
3272
+ ` : ""}`
3273
+ );
3089
3274
  let take = options.acceptAll;
3090
3275
  if (readline) {
3091
3276
  const answer = (await readline.question(`
@@ -3139,6 +3324,7 @@ ${bold("Options")}
3139
3324
  --allow-unreachable a server that cannot be reached warns instead of failing
3140
3325
  --json machine-readable output (check)
3141
3326
  --sarif SARIF 2.1.0 output (check)
3327
+ --sarif-steering also emit steering passages as SARIF notes (off: an alert is a gate)
3142
3328
  --accept-all accept every change without prompting (review)
3143
3329
  --force re-pin over an existing lockfile, discarding it (init)
3144
3330
  --api <url> control plane to push to (push; or NULLADRIFT_API_URL)
@@ -3167,6 +3353,7 @@ async function main() {
3167
3353
  "allow-unreachable": { type: "boolean", default: false },
3168
3354
  json: { type: "boolean", default: false },
3169
3355
  sarif: { type: "boolean", default: false },
3356
+ "sarif-steering": { type: "boolean", default: false },
3170
3357
  "accept-all": { type: "boolean", default: false },
3171
3358
  force: { type: "boolean", default: false },
3172
3359
  api: { type: "string" },
@@ -3208,6 +3395,7 @@ async function main() {
3208
3395
  timeoutMs,
3209
3396
  allowUnreachable: values["allow-unreachable"],
3210
3397
  format: values.sarif ? "sarif" : values.json ? "json" : "human",
3398
+ sarifSteering: values["sarif-steering"] === true,
3211
3399
  comment: values.comment
3212
3400
  };
3213
3401
  switch (command) {