@vantageos/mcp-doctor 0.20.0 → 0.21.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/doctor.js CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  isJudgeable,
4
+ parseFile,
4
5
  scanR4FilterPaths
5
6
  } from "./chunk-OLW7SIJF.js";
6
7
 
7
8
  // src/doctor.ts
8
- import { readFileSync as readFileSync27, realpathSync, statSync as statSync26 } from "fs";
9
- import { dirname as dirname19, join as join36, resolve as resolve4 } from "path";
9
+ import { readFileSync as readFileSync28, realpathSync, statSync as statSync27 } from "fs";
10
+ import { dirname as dirname19, join as join37, resolve as resolve4 } from "path";
10
11
  import { fileURLToPath as fileURLToPath2 } from "url";
11
12
 
12
13
  // src/scan.ts
@@ -798,6 +799,7 @@ var STANDARD_PIN = "1c66e11c43276df302d0d0689839172e598d7bcd";
798
799
  var MANUFACT_RULES_PIN = "7e5513eff22c0e2174c100d26e0aa40f642a562f";
799
800
  var C40_RULES_PIN = "941156e5734007188d1e3c54adadf3f1a3f84761";
800
801
  var C19_RULES_PIN = "1596b8c552d8b836f4d6044569fb2e15c3bfe6cb";
802
+ var S51_RULES_PIN = "3b4982f7da3d34f0dc3bb42f8d3f3c5f9480943a";
801
803
 
802
804
  // src/detectors/dLocalIdentity.ts
803
805
  var CLOUD_IDENTITY_PACKAGE = "@vantageos/cloud-identity";
@@ -1022,8 +1024,8 @@ function isLocalContent(e, ctx, scopes, depth) {
1022
1024
  const ch = x.match(/^(?:[\w$]+\s*\.\s*)?createHash\s*\(/);
1023
1025
  if (ch) {
1024
1026
  const c = callArgs(x, ch[0].length);
1025
- const up = c ? x.slice(c.end).match(/^\s*\.\s*update\s*\(/) : null;
1026
- const d = c && up ? callArgs(x, c.end + up[0].length) : null;
1027
+ const up2 = c ? x.slice(c.end).match(/^\s*\.\s*update\s*\(/) : null;
1028
+ const d = c && up2 ? callArgs(x, c.end + up2[0].length) : null;
1027
1029
  return d !== null && isLocalContent(d.args[0], ctx, scopes, depth + 1);
1028
1030
  }
1029
1031
  const sd = x.match(/^(?:[\w$]+\s*\.\s*)*subtle\s*\.\s*digest\s*\(/);
@@ -1384,7 +1386,7 @@ function localIdentityPositiveControls() {
1384
1386
  }
1385
1387
  function cloudIdentityBindings(file) {
1386
1388
  const text = file.lines.map((l) => l.raw).join("\n");
1387
- const names = /* @__PURE__ */ new Set();
1389
+ const names2 = /* @__PURE__ */ new Set();
1388
1390
  const namespaces = /* @__PURE__ */ new Set();
1389
1391
  const pkg = `@vantageos\\/cloud-identity(?:\\/[^"']*)?`;
1390
1392
  const named = new RegExp(`import\\s+(type\\s+)?\\{([^}]*)\\}\\s*from\\s*["']${pkg}["']`, "g");
@@ -1394,12 +1396,12 @@ function cloudIdentityBindings(file) {
1394
1396
  const p = part.trim();
1395
1397
  if (!p || p.startsWith("type ")) continue;
1396
1398
  const as = p.match(/^[\w$]+\s+as\s+([\w$]+)$/);
1397
- names.add(as ? as[1] : p);
1399
+ names2.add(as ? as[1] : p);
1398
1400
  }
1399
1401
  }
1400
1402
  const ns = new RegExp(`import\\s+\\*\\s+as\\s+([\\w$]+)\\s+from\\s*["']${pkg}["']`, "g");
1401
1403
  for (const m of text.matchAll(ns)) namespaces.add(m[1]);
1402
- return { names, namespaces };
1404
+ return { names: names2, namespaces };
1403
1405
  }
1404
1406
  function isDelegated(raw, start, callee, b) {
1405
1407
  const before = raw.slice(0, start);
@@ -2102,11 +2104,12 @@ function isCodeAtCached(file, n, col) {
2102
2104
  function wrapperDescriptionArg(tree, anchor) {
2103
2105
  return scanWrappers(tree).descriptions.get(anchor);
2104
2106
  }
2105
- function findRegisteredTools(tree) {
2107
+ function findRegisteredTools(tree, inFile) {
2106
2108
  const bindings = resolveNameBindings(tree);
2107
2109
  const out = [];
2108
2110
  const seen = /* @__PURE__ */ new Set();
2109
2111
  const push = (name, anchor) => {
2112
+ if (inFile && !inFile(anchor.slice(0, anchor.lastIndexOf(":")))) return;
2110
2113
  if (!seen.has(name)) {
2111
2114
  seen.add(name);
2112
2115
  out.push({ name, anchor });
@@ -2179,6 +2182,9 @@ function objectHasKey(lines2, at, indent) {
2179
2182
  }
2180
2183
  var TOOL_SURFACE_RE = /\bListToolsRequestSchema\b|["'`]tools\/list["'`]|\binputSchema\s*:|\bToolDefinition\b/;
2181
2184
  function toolSurfaceAnchor(tree) {
2185
+ return toolMarkerAnchor(tree) ?? mcpDependencyAnchor(tree);
2186
+ }
2187
+ function toolMarkerAnchor(tree) {
2182
2188
  for (const file of tree.files) {
2183
2189
  for (const line of file.lines) {
2184
2190
  if (line.comment) continue;
@@ -2187,8 +2193,45 @@ function toolSurfaceAnchor(tree) {
2187
2193
  }
2188
2194
  return null;
2189
2195
  }
2196
+ var MCP_MODULE_RE = /mcp|modelcontextprotocol/i;
2197
+ var READER_COVERED_MODULES = ["@modelcontextprotocol/sdk"];
2198
+ var isUncoveredMcpModule = (spec) => MCP_MODULE_RE.test(spec) && !READER_COVERED_MODULES.some((m) => spec === m || spec.startsWith(`${m}/`));
2199
+ var MODULE_SPEC_RE = /\bfrom\s*["'`]([^"'`]+)["'`]|\brequire\s*\(\s*["'`]([^"'`]+)["'`]|\bimport\s*\(\s*["'`]([^"'`]+)["'`]|^\s*import\s*["'`]([^"'`]+)["'`]/;
2200
+ var DEPENDENCY_FIELDS = [
2201
+ "dependencies",
2202
+ "devDependencies",
2203
+ "peerDependencies",
2204
+ "optionalDependencies"
2205
+ ];
2206
+ function mcpDependencyAnchor(tree) {
2207
+ const pj = tree.packageJson;
2208
+ if (pj?.unreadable)
2209
+ return `${pj.path} (unreadable: ${pj.unreadable}, so its MCP dependencies are unknown)`;
2210
+ if (pj) {
2211
+ for (const field of DEPENDENCY_FIELDS) {
2212
+ const deps = pj.json[field];
2213
+ if (typeof deps !== "object" || deps === null || Array.isArray(deps)) continue;
2214
+ const hit = Object.keys(deps).find(isUncoveredMcpModule);
2215
+ if (hit) return `${pj.path} ${field}.${hit}`;
2216
+ }
2217
+ }
2218
+ for (const file of tree.files) {
2219
+ for (const line of file.lines) {
2220
+ if (line.comment) continue;
2221
+ const m = MODULE_SPEC_RE.exec(line.raw);
2222
+ const spec = m ? m[1] ?? m[2] ?? m[3] ?? m[4] : void 0;
2223
+ if (spec && !spec.startsWith(".") && isUncoveredMcpModule(spec))
2224
+ return `${file.rel}:${line.n}`;
2225
+ }
2226
+ }
2227
+ return null;
2228
+ }
2190
2229
  function noToolsLocatedReason(tree, what) {
2191
- return `the tree serves MCP tools (tool-surface marker found) but no registered tool could be located: searched ${tree.files.length} .ts/.tsx file(s) under ${tree.root} (all directories except node_modules/dist/build/tests/fixtures) for registerTool/.tool( calls and declarative { name, inputSchema } descriptors \u2014 ${what}`;
2230
+ const searched = `searched ${tree.files.length} .ts/.tsx file(s) under ${tree.root} (all directories except node_modules/dist/build/tests/fixtures) for registerTool/.tool( calls and declarative { name, inputSchema } descriptors`;
2231
+ const dep = toolMarkerAnchor(tree) ? null : mcpDependencyAnchor(tree);
2232
+ if (dep)
2233
+ return `the tree builds on an MCP module (${dep}) but registers its tools through an API the reader does not recognise: ${searched}, and for the ListToolsRequestSchema / "tools/list" / inputSchema: / ToolDefinition markers \u2014 ${what}`;
2234
+ return `the tree serves MCP tools (tool-surface marker found) but no registered tool could be located: ${searched} \u2014 ${what}`;
2192
2235
  }
2193
2236
  var REGISTRATION_CALL_RE = /\b(?:s\.tool|\.tool|registerTool)\s*\(/;
2194
2237
  function findUnresolvedToolSites(tree) {
@@ -2238,10 +2281,10 @@ function findUnresolvedToolSites(tree) {
2238
2281
  function findListReadBuilders(tree) {
2239
2282
  const bindings = resolveNameBindings(tree);
2240
2283
  const extents = [];
2241
- const endOf = (startLine, startCol, text) => {
2284
+ const endOf = (startLine2, startCol, text) => {
2242
2285
  const lines2 = text.split("\n");
2243
2286
  const last = lines2.length - 1;
2244
- return [startLine + last, last === 0 ? startCol + text.length - 1 : lines2[last].length - 1];
2287
+ return [startLine2 + last, last === 0 ? startCol + text.length - 1 : lines2[last].length - 1];
2245
2288
  };
2246
2289
  for (const site of codeSites(tree, /(?:\.tool|\bregisterTool)\s*\(/g)) {
2247
2290
  const open = site.col + site.match[0].lastIndexOf("(");
@@ -2449,15 +2492,15 @@ function callOpenerLine(file, siteLine) {
2449
2492
  return siteLine;
2450
2493
  }
2451
2494
  function ownCallEnd(file, siteLine) {
2452
- const startLine = callOpenerLine(file, siteLine);
2495
+ const startLine2 = callOpenerLine(file, siteLine);
2453
2496
  let depth = 0;
2454
2497
  for (const line of file.lines) {
2455
- if (line.n < startLine) continue;
2498
+ if (line.n < startLine2) continue;
2456
2499
  if (!line.comment) {
2457
2500
  depth += (line.raw.match(/\(/g) ?? []).length - (line.raw.match(/\)/g) ?? []).length;
2458
2501
  }
2459
- if (line.n >= startLine && depth <= 0 && line.n > startLine) return line.n;
2460
- if (line.n === startLine && depth <= 0) {
2502
+ if (line.n >= startLine2 && depth <= 0 && line.n > startLine2) return line.n;
2503
+ if (line.n === startLine2 && depth <= 0) {
2461
2504
  return line.n;
2462
2505
  }
2463
2506
  }
@@ -2712,14 +2755,14 @@ function governingWorkflows(tree) {
2712
2755
  if (existsSync3(wf)) {
2713
2756
  const out = [];
2714
2757
  const base = baseOf(tree);
2715
- let names;
2758
+ let names2;
2716
2759
  try {
2717
- names = readdirSync3(wf).sort();
2760
+ names2 = readdirSync3(wf).sort();
2718
2761
  } catch (err) {
2719
2762
  recordSkip(tree, wf, base, `could not be listed (${fsErrorCode(err)}) \u2014 not read`);
2720
2763
  return out;
2721
2764
  }
2722
- for (const name of names) {
2765
+ for (const name of names2) {
2723
2766
  if (!/\.ya?ml$/.test(name)) continue;
2724
2767
  const full = join3(wf, name);
2725
2768
  try {
@@ -3032,13 +3075,13 @@ var a4WcagGate = {
3032
3075
  const workflowRun = governingWorkflows(tree).find(
3033
3076
  (w) => /\baxe\b|axe-core/i.test(stripYamlComments(w.text))
3034
3077
  );
3035
- const testFiles2 = diskText(tree, (name) => /\.(?:test|spec)\.[jt]sx?$/.test(name));
3036
- const testRun = testFiles2.find(
3078
+ const testFiles3 = diskText(tree, (name) => /\.(?:test|spec)\.[jt]sx?$/.test(name));
3079
+ const testRun = testFiles3.find(
3037
3080
  (f) => /\baxe\b|axe-core|jest-axe|vitest-axe/i.test(stripJsComments(f.text))
3038
3081
  );
3039
3082
  const refusedInputs = [
3040
3083
  ...refusedAsUnreadable(pkgs.refused, "its axe dependency and scripts are unread"),
3041
- ...refusedAsUnreadable(testFiles2.refused, "a test file that may run axe is unread"),
3084
+ ...refusedAsUnreadable(testFiles3.refused, "a test file that may run axe is unread"),
3042
3085
  ...refusedAsUnreadable(htmlShells.refused, "an HTML shell of the App is unread")
3043
3086
  ];
3044
3087
  const run13 = scriptRun ?? (workflowRun ? workflowRun.rel : null) ?? (testRun ? testRun.rel : null);
@@ -4113,12 +4156,12 @@ function wrapperProof(s, server, mine) {
4113
4156
  const pClose = matchClose(m, pOpen);
4114
4157
  if (pClose < 0) return "the parameter list is unbalanced";
4115
4158
  const params = splitList(m, pOpen + 1, pClose);
4116
- const names = [];
4159
+ const names2 = [];
4117
4160
  for (const p of params) {
4118
4161
  const id = /^(\.\.\.)?\s*([A-Za-z_$][\w$]*)/.exec(p);
4119
4162
  if (!id) return "a destructured parameter";
4120
4163
  if (/=>/.test(p)) return "a function type in the parameter list";
4121
- names.push(`${id[1] ?? ""}${id[2]}`);
4164
+ names2.push(`${id[1] ?? ""}${id[2]}`);
4122
4165
  }
4123
4166
  const tail = m.slice(pClose + 1);
4124
4167
  const arrow = /^\s*(?::[^=>{]*)?=>\s*/.exec(tail);
@@ -4170,9 +4213,9 @@ function wrapperProof(s, server, mine) {
4170
4213
  const argsClose = matchClose(m, argsOpen);
4171
4214
  if (argsClose < 0) return "the forwarding call is unbalanced";
4172
4215
  const args = splitList(m, argsOpen + 1, argsClose);
4173
- if (args.length !== names.length || args.some((a, i) => a !== names[i]))
4174
- return `the wrapper does not forward exactly its own parameters (${names.join(", ")}) to \`${alias}\``;
4175
- return untouchedParams(s, params, names, bStart, bEnd, argsOpen, argsClose);
4216
+ if (args.length !== names2.length || args.some((a, i) => a !== names2[i]))
4217
+ return `the wrapper does not forward exactly its own parameters (${names2.join(", ")}) to \`${alias}\``;
4218
+ return untouchedParams(s, params, names2, bStart, bEnd, argsOpen, argsClose);
4176
4219
  }
4177
4220
  function methodArgumentRead(shape, o) {
4178
4221
  const before = shape.slice(Math.max(0, o - 80), o);
@@ -4207,11 +4250,11 @@ function decoratorProof(s, server, mine) {
4207
4250
  const pOpen = rhsAt + head[0].length - 1;
4208
4251
  const pClose = matchClose(m, pOpen);
4209
4252
  if (pClose < 0) return "the parameter list is unbalanced";
4210
- const names = splitList(m, pOpen + 1, pClose).map((p) => /^\s*([A-Za-z_$][\w$]*)/.exec(p)?.[1]);
4211
- if (names.length < 2 || names.some((n) => n === void 0))
4253
+ const names2 = splitList(m, pOpen + 1, pClose).map((p) => /^\s*([A-Za-z_$][\w$]*)/.exec(p)?.[1]);
4254
+ if (names2.length < 2 || names2.some((n) => n === void 0))
4212
4255
  return "the parameters are not plain names";
4213
- const first = names[0];
4214
- const handler = names[names.length - 1];
4256
+ const first = names2[0];
4257
+ const handler = names2[names2.length - 1];
4215
4258
  const tail = m.slice(pClose + 1);
4216
4259
  const arrow = /^\s*(?::[^=>{]*)?=>\s*\{/.exec(tail);
4217
4260
  const fnBody = arrow ? void 0 : /^\s*(?::[^{]*)?\{/.exec(tail);
@@ -4254,7 +4297,7 @@ function enclosingOpens(m, at, lo) {
4254
4297
  }
4255
4298
  return out;
4256
4299
  }
4257
- function untouchedParams(s, params, names, bStart, bEnd, fwdOpen, fwdClose) {
4300
+ function untouchedParams(s, params, names2, bStart, bEnd, fwdOpen, fwdClose) {
4258
4301
  const m = s.shape;
4259
4302
  const stmt = (i) => {
4260
4303
  let a = i;
@@ -4266,8 +4309,8 @@ function untouchedParams(s, params, names, bStart, bEnd, fwdOpen, fwdClose) {
4266
4309
  const argsUse = /(?<![\w$.])arguments(?![\w$])/g.exec(m.slice(bStart, bEnd));
4267
4310
  if (argsUse)
4268
4311
  return `the wrapper reads \`arguments\`, which aliases its parameters: ${stmt(bStart + argsUse.index)}`;
4269
- for (let k = 0; k < names.length; k++) {
4270
- const id = names[k].replace(/^\.\.\./, "");
4312
+ for (let k = 0; k < names2.length; k++) {
4313
+ const id = names2[k].replace(/^\.\.\./, "");
4271
4314
  const decl = params[k].replace(/^\.\.\.\s*/, "");
4272
4315
  const typed = /^[A-Za-z_$][\w$]*\s*\??\s*:\s*([^=]*?)\s*(?:=(?![=>]).*)?$/s.exec(decl);
4273
4316
  const primitive = typed !== void 0 && typed !== null && PRIMITIVE_TYPE.test(typed[1]);
@@ -5084,28 +5127,28 @@ var requesting = /* @__PURE__ */ new WeakMap();
5084
5127
  function requestingFunctions(tree) {
5085
5128
  const hit = requesting.get(tree);
5086
5129
  if (hit) return hit;
5087
- const names = /* @__PURE__ */ new Map();
5130
+ const names2 = /* @__PURE__ */ new Map();
5088
5131
  const add = (n, s) => {
5089
- const set = names.get(n) ?? /* @__PURE__ */ new Set();
5132
+ const set = names2.get(n) ?? /* @__PURE__ */ new Set();
5090
5133
  const had = set.has(s);
5091
5134
  set.add(s);
5092
- names.set(n, set);
5135
+ names2.set(n, set);
5093
5136
  return !had;
5094
5137
  };
5095
5138
  for (const c of upstreamSurface(tree).calls)
5096
5139
  for (const f of enclosingFns(c.src, c.start)) if (f.name) add(f.name, c.src);
5097
5140
  for (let round = 0; round < 6; round++) {
5098
5141
  let grew = false;
5099
- for (const n of [...names.keys()]) {
5142
+ for (const n of [...names2.keys()]) {
5100
5143
  for (const c of callsMatching(tree, new RegExp(String.raw`^(?:[\w$]+\.)*${esc2(n)}$`))) {
5101
- if (!callReaches(c.src, c.callee, n, names.get(n))) continue;
5144
+ if (!callReaches(c.src, c.callee, n, names2.get(n))) continue;
5102
5145
  for (const f of enclosingFns(c.src, c.start)) if (f.name && add(f.name, c.src)) grew = true;
5103
5146
  }
5104
5147
  }
5105
5148
  if (!grew) break;
5106
5149
  }
5107
- requesting.set(tree, names);
5108
- return names;
5150
+ requesting.set(tree, names2);
5151
+ return names2;
5109
5152
  }
5110
5153
  function callReaches(s, callee, name, defs) {
5111
5154
  if (callee.includes(".")) return true;
@@ -5821,7 +5864,7 @@ function symbolConst(file, name) {
5821
5864
  );
5822
5865
  return uncommentedLines(file).some((row) => re.test(row));
5823
5866
  }
5824
- function computedKeys(file, lineNo, names, out) {
5867
+ function computedKeys(file, lineNo, names2, out) {
5825
5868
  const raw = file.lines[lineNo - 1].raw;
5826
5869
  for (let col = raw.indexOf("["); col >= 0; col = raw.indexOf("[", col + 1)) {
5827
5870
  if (!isCodeAt(file, lineNo, col)) continue;
@@ -5836,14 +5879,14 @@ function computedKeys(file, lineNo, names, out) {
5836
5879
  const lit = expr.match(/^(["'`])((?:\\.|(?!\1)[^\\])*)\1$/);
5837
5880
  const anchor = `${file.rel}:${lineNo}`;
5838
5881
  if (lit && !(lit[1] === "`" && lit[2].includes("${"))) {
5839
- if (names.includes(lit[2])) keyInBrace(file, lineNo, col, lit[2], "computed-key", out);
5882
+ if (names2.includes(lit[2])) keyInBrace(file, lineNo, col, lit[2], "computed-key", out);
5840
5883
  continue;
5841
5884
  }
5842
5885
  if (/^[A-Za-z_$][\w$]*$/.test(expr) && symbolConst(file, expr)) continue;
5843
5886
  if (/^[A-Za-z_$][\w$]*$/.test(expr)) {
5844
5887
  const bound = constString(file, expr);
5845
5888
  if (bound.kind === "value") {
5846
- if (bound.value !== null && names.includes(bound.value)) {
5889
+ if (bound.value !== null && names2.includes(bound.value)) {
5847
5890
  keyInBrace(file, lineNo, col, bound.value, "computed-key", out);
5848
5891
  }
5849
5892
  continue;
@@ -5864,9 +5907,9 @@ function computedKeys(file, lineNo, names, out) {
5864
5907
  }
5865
5908
  }
5866
5909
  }
5867
- function fieldWrites(tree, names) {
5910
+ function fieldWrites(tree, names2) {
5868
5911
  const out = { writes: [], unread: [], computed: [] };
5869
- const alt = names.map((n) => n.replace(/[$]/g, "\\$&")).join("|");
5912
+ const alt = names2.map((n) => n.replace(/[$]/g, "\\$&")).join("|");
5870
5913
  const identRe = new RegExp(`(?<![\\w$])(${alt})(?![\\w$])`, "g");
5871
5914
  const quotedRe = new RegExp(`(["'])(${alt})\\1`, "g");
5872
5915
  for (const file of tree.files) {
@@ -5902,7 +5945,7 @@ function fieldWrites(tree, names) {
5902
5945
  keyInBrace(file, line.n, col, name, "shorthand", out);
5903
5946
  }
5904
5947
  }
5905
- computedKeys(file, line.n, names, out);
5948
+ computedKeys(file, line.n, names2, out);
5906
5949
  for (const m of line.raw.matchAll(quotedRe)) {
5907
5950
  const col = m.index ?? 0;
5908
5951
  if (!isCodeAt(file, line.n, col)) continue;
@@ -6615,16 +6658,16 @@ function hostToolProblems(tree) {
6615
6658
  const unresolvedSites = findUnresolvedToolSites(tree);
6616
6659
  const named = [];
6617
6660
  for (const c of caps) {
6618
- for (const ts of TOOL_SETTINGS) {
6619
- if (c.key !== ts.cap) continue;
6661
+ for (const ts6 of TOOL_SETTINGS) {
6662
+ if (c.key !== ts6.cap) continue;
6620
6663
  const m = c.body.match(
6621
- new RegExp(`["'\`]?${ts.setting}["'\`]?\\s*:\\s*["'\`]([^"'\`]+)["'\`]`)
6664
+ new RegExp(`["'\`]?${ts6.setting}["'\`]?\\s*:\\s*["'\`]([^"'\`]+)["'\`]`)
6622
6665
  );
6623
6666
  if (m)
6624
6667
  named.push({
6625
6668
  name: m[1],
6626
- kind: ts.kind,
6627
- from: `${ts.cap}.${ts.setting}`,
6669
+ kind: ts6.kind,
6670
+ from: `${ts6.cap}.${ts6.setting}`,
6628
6671
  anchor: c.anchor
6629
6672
  });
6630
6673
  }
@@ -7644,13 +7687,13 @@ var MECHANISM_BASE_SET = /* @__PURE__ */ new Set([
7644
7687
  ]);
7645
7688
  var isDataLayerFile = (rel) => /(^|\/)convex\//.test(rel);
7646
7689
  function judgeIndexedFromSource(tree, id, indexed) {
7647
- const names = indexed.map((t) => `"${t.name}" (${t.searchMechanism})`).join(", ");
7690
+ const names2 = indexed.map((t) => `"${t.name}" (${t.searchMechanism})`).join(", ");
7648
7691
  const dataLayer = tree.files.filter((f) => isJudgeable(f) && isDataLayerFile(f.rel));
7649
7692
  if (dataLayer.length === 0) {
7650
7693
  return couldNotJudge(
7651
7694
  id,
7652
7695
  indexed[0].anchor,
7653
- `${indexed.length} list/search tool(s) claim an indexed mechanism (${names}) and no data-layer source is in the tree (convex/ files read: 0): no implementation confirms the declaration, and C-10 reads a data layer through backend R-4 (Convex only) (C-10)`
7696
+ `${indexed.length} list/search tool(s) claim an indexed mechanism (${names2}) and no data-layer source is in the tree (convex/ files read: 0): no implementation confirms the declaration, and C-10 reads a data layer through backend R-4 (Convex only) (C-10)`
7654
7697
  );
7655
7698
  }
7656
7699
  const scan = scanR4FilterPaths(tree.files);
@@ -7660,7 +7703,7 @@ function judgeIndexedFromSource(tree, id, indexed) {
7660
7703
  id,
7661
7704
  anchor: `${scan.violate[0].rel}:${scan.violate[0].n}`,
7662
7705
  state: "non-conforming",
7663
- verdict: `${indexed.length} list/search tool(s) claim an indexed mechanism (${names}) while ${scan.violate.length} filter path(s) of the data layer scan (read through backend R-4): ${shown.join(" | ")}${scan.violate.length > 3 ? ` | and ${scan.violate.length - 3} more` : ""} -> bound the filtered field in the index range, or declare what the path does (C-10)`
7706
+ verdict: `${indexed.length} list/search tool(s) claim an indexed mechanism (${names2}) while ${scan.violate.length} filter path(s) of the data layer scan (read through backend R-4): ${shown.join(" | ")}${scan.violate.length > 3 ? ` | and ${scan.violate.length - 3} more` : ""} -> bound the filtered field in the index range, or declare what the path does (C-10)`
7664
7707
  };
7665
7708
  }
7666
7709
  if (scan.cnj.length > 0) {
@@ -7668,14 +7711,14 @@ function judgeIndexedFromSource(tree, id, indexed) {
7668
7711
  return couldNotJudge(
7669
7712
  id,
7670
7713
  `${first.rel}:${first.n}`,
7671
- `${scan.cnj.length} filter path(s) of the data layer could not be read through backend R-4 (first: ${first.note}): whether they answer the indexed claim of ${names} is undecided (C-10)`
7714
+ `${scan.cnj.length} filter path(s) of the data layer could not be read through backend R-4 (first: ${first.note}): whether they answer the indexed claim of ${names2} is undecided (C-10)`
7672
7715
  );
7673
7716
  }
7674
7717
  if (scan.reads === 0) {
7675
7718
  return couldNotJudge(
7676
7719
  id,
7677
7720
  indexed[0].anchor,
7678
- `${indexed.length} list/search tool(s) claim an indexed mechanism (${names}) and backend R-4 found no list read in a public query door among ${dataLayer.length} convex file(s): no implementation confirms the declaration (C-10)`
7721
+ `${indexed.length} list/search tool(s) claim an indexed mechanism (${names2}) and backend R-4 found no list read in a public query door among ${dataLayer.length} convex file(s): no implementation confirms the declaration (C-10)`
7679
7722
  );
7680
7723
  }
7681
7724
  return void 0;
@@ -8207,7 +8250,7 @@ var Parser = class _Parser {
8207
8250
  return sub.parseExpr();
8208
8251
  }
8209
8252
  paramNames(from, to) {
8210
- const names = [];
8253
+ const names2 = [];
8211
8254
  let depth = 0;
8212
8255
  let expectName = true;
8213
8256
  for (let j = from; j < to; j++) {
@@ -8219,11 +8262,11 @@ var Parser = class _Parser {
8219
8262
  continue;
8220
8263
  }
8221
8264
  if (depth === 0 && expectName && t.t === "id") {
8222
- names.push(t.v);
8265
+ names2.push(t.v);
8223
8266
  expectName = false;
8224
8267
  }
8225
8268
  }
8226
- return names;
8269
+ return names2;
8227
8270
  }
8228
8271
  parsePostfix() {
8229
8272
  let node = this.parsePrimary();
@@ -8668,9 +8711,9 @@ function moduleCtx(file, tree, from) {
8668
8711
  resolving: from ? from.resolving : /* @__PURE__ */ new Set()
8669
8712
  };
8670
8713
  }
8671
- function flatten(branches) {
8714
+ function flatten(branches2) {
8672
8715
  const out = [];
8673
- for (const b of branches) {
8716
+ for (const b of branches2) {
8674
8717
  if (b.k === "union") out.push(...flatten(b.branches));
8675
8718
  else out.push(b);
8676
8719
  }
@@ -9133,12 +9176,12 @@ function walk2(s, path, useAt, out, loc) {
9133
9176
  const offsetsFor = (...offs) => offs.filter((o) => o !== void 0);
9134
9177
  switch (s.k) {
9135
9178
  case "union": {
9136
- const branches = flatten(s.branches);
9137
- const arrays = branches.filter((b) => b.k === "array").length;
9138
- const others = branches.filter(
9179
+ const branches2 = flatten(s.branches);
9180
+ const arrays = branches2.filter((b) => b.k === "array").length;
9181
+ const others = branches2.filter(
9139
9182
  (b) => b.k !== "array" && b.k !== "null" && b.k !== "unread"
9140
9183
  ).length;
9141
- const unreadB = branches.filter((b) => b.k === "unread");
9184
+ const unreadB = branches2.filter((b) => b.k === "unread");
9142
9185
  if (arrays > 0 && others > 0) {
9143
9186
  const use = loc(useAt ?? s.at);
9144
9187
  const origin = loc(s.at ?? useAt);
@@ -9158,7 +9201,7 @@ function walk2(s, path, useAt, out, loc) {
9158
9201
  anchor: loc(unreadB[0].at ?? s.at ?? useAt).anchor
9159
9202
  });
9160
9203
  }
9161
- for (const b of branches) if (b.k !== "unread") walk2(b, path, useAt, out, loc);
9204
+ for (const b of branches2) if (b.k !== "unread") walk2(b, path, useAt, out, loc);
9162
9205
  return;
9163
9206
  }
9164
9207
  case "array":
@@ -9435,9 +9478,7 @@ function runStatic(tree) {
9435
9478
  `S43 positive control FAILED: sees=${controls.sees} spares=${controls.spares} \u2014 reader broken, verdict untrustworthy`
9436
9479
  );
9437
9480
  }
9438
- const tools = findRegisteredTools(tree).filter(
9439
- (t) => isProductSource(t.anchor.slice(0, t.anchor.lastIndexOf(":")))
9440
- );
9481
+ const tools = findRegisteredTools(tree, isProductSource);
9441
9482
  const unresolvedTools = findUnresolvedToolSites(tree).filter(
9442
9483
  (a) => isProductSource(a.slice(0, a.lastIndexOf(":")))
9443
9484
  );
@@ -10094,14 +10135,14 @@ function judgeDeclaration(byAnnotation, schema) {
10094
10135
  return { missing, unread: unread2 };
10095
10136
  }
10096
10137
  if (!byAnnotation.cursor && !schema.cursor) missing.push("cursor");
10097
- const num = (declared, n, label2, finite) => {
10138
+ const num2 = (declared, n, label2, finite) => {
10098
10139
  if (declared) return;
10099
10140
  if (n.kind === "literal" && (!finite || Number.isFinite(n.value))) return;
10100
10141
  if (n.kind === "unread") unread2.push(`${label2} unread (${n.form})`);
10101
10142
  else missing.push(label2);
10102
10143
  };
10103
- num(byAnnotation.def, schema.limitDefault, "default", false);
10104
- num(byAnnotation.max, schema.limitMax, "finite max", true);
10144
+ num2(byAnnotation.def, schema.limitDefault, "default", false);
10145
+ num2(byAnnotation.max, schema.limitMax, "finite max", true);
10105
10146
  return { missing, unread: unread2 };
10106
10147
  }
10107
10148
 
@@ -11354,8 +11395,8 @@ function importedModule(file, fn) {
11354
11395
  const text = file.lines.map((l) => l.raw).join("\n");
11355
11396
  const re = /import\s*\{([^}]*)\}\s*from\s*["'](\.{1,2}\/[^"']+)["']/g;
11356
11397
  for (const m of text.matchAll(re)) {
11357
- const names = m[1].split(",").map((s) => s.trim().replace(/^type\s+/, ""));
11358
- const local = names.map(
11398
+ const names2 = m[1].split(",").map((s) => s.trim().replace(/^type\s+/, ""));
11399
+ const local = names2.map(
11359
11400
  (n) => n.split(/\s+as\s+/).pop()?.trim()
11360
11401
  );
11361
11402
  if (!local.includes(fn)) continue;
@@ -13155,15 +13196,15 @@ function filesUnder(dir, unread2, rel) {
13155
13196
  const out = /* @__PURE__ */ new Map();
13156
13197
  let incomplete = false;
13157
13198
  const walk3 = (d, prefix) => {
13158
- let names;
13199
+ let names2;
13159
13200
  try {
13160
- names = readdirSync8(d);
13201
+ names2 = readdirSync8(d);
13161
13202
  } catch (e) {
13162
13203
  unread2.push({ anchor: rel, reason: `${prefix || "."} not listed (${e.message})` });
13163
13204
  incomplete = true;
13164
13205
  return;
13165
13206
  }
13166
- for (const n of names.sort()) {
13207
+ for (const n of names2.sort()) {
13167
13208
  const full = join12(d, n);
13168
13209
  const r = prefix ? `${prefix}/${n}` : n;
13169
13210
  try {
@@ -13208,12 +13249,12 @@ function packageSkillProblems(tree, skillFiles, unread2) {
13208
13249
  if (packages.length === 0 || skillFiles.length === 0) return [];
13209
13250
  const skillsRoot = (pkg) => pkg ? `${pkg}/skills` : "skills";
13210
13251
  const inPackage = (rel) => packages.some((p) => rel.startsWith(`${skillsRoot(p)}/`));
13211
- const names = [...new Set(skillFiles.map((s) => s.dir))].sort();
13252
+ const names2 = [...new Set(skillFiles.map((s) => s.dir))].sort();
13212
13253
  const out = [];
13213
13254
  for (const pkg of packages) {
13214
13255
  const at = pkg || ".";
13215
13256
  const missing = [];
13216
- for (const name of names) {
13257
+ for (const name of names2) {
13217
13258
  const rel = `${skillsRoot(pkg)}/${name}/SKILL.md`;
13218
13259
  const copy = skillFiles.find((s) => s.rel === rel);
13219
13260
  if (!copy) {
@@ -14035,14 +14076,14 @@ function testFiles(tree, unread2) {
14035
14076
  const base = baseOf(tree);
14036
14077
  const out = [];
14037
14078
  const walk3 = (dir, rel) => {
14038
- let names;
14079
+ let names2;
14039
14080
  try {
14040
- names = readdirSync10(dir);
14081
+ names2 = readdirSync10(dir);
14041
14082
  } catch (err) {
14042
14083
  unread2.push(`${rel}/ (not listed: ${err.message})`);
14043
14084
  return;
14044
14085
  }
14045
- for (const name of names) {
14086
+ for (const name of names2) {
14046
14087
  if (name === "node_modules") continue;
14047
14088
  const full = join14(dir, name);
14048
14089
  let st;
@@ -14308,15 +14349,15 @@ function run3(tree) {
14308
14349
  if (registered2.length === 0 && listed.length > 0)
14309
14350
  v.unread.push("no tool registration located in the tree: the kit's tools are not compared");
14310
14351
  else {
14311
- const names = listed.map((t) => t.name);
14312
- const missing = registered2.filter((n) => !names.includes(n));
14313
- const extra = names.filter((n) => !registered2.includes(n));
14352
+ const names2 = listed.map((t) => t.name);
14353
+ const missing = registered2.filter((n) => !names2.includes(n));
14354
+ const extra = names2.filter((n) => !registered2.includes(n));
14314
14355
  if (missing.length > 0)
14315
14356
  v.red.push(`${KIT} omits the registered tool(s) ${missing.join(", ")}`);
14316
14357
  if (extra.length > 0)
14317
14358
  v.red.push(`${KIT} lists ${extra.join(", ")}, which the tree registers nowhere`);
14318
14359
  if (missing.length + extra.length === 0)
14319
- v.ok.push(`${names.length} tool(s) listed, one per registration`);
14360
+ v.ok.push(`${names2.length} tool(s) listed, one per registration`);
14320
14361
  }
14321
14362
  const deferred = [];
14322
14363
  for (const k of listed) {
@@ -14374,9 +14415,9 @@ function runServed2(runtime) {
14374
14415
  if (!listed) v.red.push(`${KIT} has no tools[]`);
14375
14416
  else {
14376
14417
  const served = runtime.tools;
14377
- const names = listed.map((t) => t.name);
14378
- const missing = served.filter((t) => !names.includes(t.name)).map((t) => t.name);
14379
- const extra = names.filter((n) => !served.some((t) => t.name === n));
14418
+ const names2 = listed.map((t) => t.name);
14419
+ const missing = served.filter((t) => !names2.includes(t.name)).map((t) => t.name);
14420
+ const extra = names2.filter((n) => !served.some((t) => t.name === n));
14380
14421
  if (missing.length > 0) v.red.push(`${KIT} omits the served tool(s) ${missing.join(", ")}`);
14381
14422
  if (extra.length > 0)
14382
14423
  v.red.push(`${KIT} lists ${extra.join(", ")}, which the server does not serve`);
@@ -14462,9 +14503,9 @@ function runStatic2(tree) {
14462
14503
  state: "absent",
14463
14504
  verdict: `"private": true: not published to npm \u2014 ${RULE5} n/a`
14464
14505
  };
14465
- let names;
14506
+ let names2;
14466
14507
  try {
14467
- names = readdirSync11(tree.root).filter((n) => README_RE.test(n));
14508
+ names2 = readdirSync11(tree.root).filter((n) => README_RE.test(n));
14468
14509
  } catch (err) {
14469
14510
  return couldNotJudge(
14470
14511
  ID5,
@@ -14472,7 +14513,7 @@ function runStatic2(tree) {
14472
14513
  `the package root could not be listed (${fsErrorCode(err)}) (${RULE5})`
14473
14514
  );
14474
14515
  }
14475
- if (names.length === 0)
14516
+ if (names2.length === 0)
14476
14517
  return {
14477
14518
  id: ID5,
14478
14519
  anchor: tree.root,
@@ -14480,7 +14521,7 @@ function runStatic2(tree) {
14480
14521
  verdict: `no README (no readme* file) at the package root: nothing to measure (its presence is C-1 / C-31's subject) \u2014 ${RULE5} n/a`
14481
14522
  };
14482
14523
  const sized = [];
14483
- for (const name of names.sort()) {
14524
+ for (const name of names2.sort()) {
14484
14525
  const path = join16(tree.root, name);
14485
14526
  try {
14486
14527
  const st = lstatSync(path);
@@ -14861,9 +14902,9 @@ function nested(node, path) {
14861
14902
  if (isObj3(node.properties)) out.push(...fieldsOf(node, path));
14862
14903
  if (isObj3(node.items)) out.push(...nested(node.items, `${path}[]`));
14863
14904
  for (const k of ["anyOf", "oneOf", "allOf"]) {
14864
- const branches = node[k];
14865
- if (Array.isArray(branches)) {
14866
- for (const b of branches) if (isObj3(b)) out.push(...nested(b, path));
14905
+ const branches2 = node[k];
14906
+ if (Array.isArray(branches2)) {
14907
+ for (const b of branches2) if (isObj3(b)) out.push(...nested(b, path));
14867
14908
  }
14868
14909
  }
14869
14910
  return out;
@@ -16824,7 +16865,7 @@ function classifySurface(file, startIdx, anchor, pkgIdents) {
16824
16865
  return { kind: "unreadable-source", anchor };
16825
16866
  }
16826
16867
  function packageJsonVersionConsts(tree) {
16827
- const names = /* @__PURE__ */ new Set();
16868
+ const names2 = /* @__PURE__ */ new Set();
16828
16869
  const decl = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/;
16829
16870
  for (const file of tree.files) {
16830
16871
  const code = file.lines.filter((l) => !l.comment);
@@ -16840,10 +16881,10 @@ function packageJsonVersionConsts(tree) {
16840
16881
  depth += (raw.match(/[({[]/g) ?? []).length - (raw.match(/[)}\]]/g) ?? []).length;
16841
16882
  if (depth <= 0 && /;\s*$/.test(raw)) break;
16842
16883
  }
16843
- if (/package\.json/.test(stmt) && /\.version\b/.test(stmt)) names.add(m[1]);
16884
+ if (/package\.json/.test(stmt) && /\.version\b/.test(stmt)) names2.add(m[1]);
16844
16885
  }
16845
16886
  }
16846
- return names;
16887
+ return names2;
16847
16888
  }
16848
16889
  function sdkServerVersionSurface(tree) {
16849
16890
  const derived = packageJsonVersionConsts(tree);
@@ -19107,9 +19148,9 @@ function resolvesToLiteral(tree, path) {
19107
19148
  };
19108
19149
  if (/[()]/.test(path)) return false;
19109
19150
  if (!path.includes(".")) return plainLiteral(path);
19110
- const prop = path.split(".").pop() ?? "";
19111
- const def = new RegExp(`(?:^|[\\s{,])${esc4(prop)}\\s*:\\s*([^,}\\n]+)`);
19112
- const shorthand = new RegExp(`[{,]\\s*${esc4(prop)}\\s*[,}]`);
19151
+ const prop2 = path.split(".").pop() ?? "";
19152
+ const def = new RegExp(`(?:^|[\\s{,])${esc4(prop2)}\\s*:\\s*([^,}\\n]+)`);
19153
+ const shorthand = new RegExp(`[{,]\\s*${esc4(prop2)}\\s*[,}]`);
19113
19154
  const defs = lines2.map((l) => l.match(def)).filter((m) => m !== null);
19114
19155
  if (defs.length === 0 || lines2.some((l) => shorthand.test(l))) return false;
19115
19156
  return defs.every((m) => {
@@ -19178,8 +19219,8 @@ function boundToSystemState(tree, path) {
19178
19219
  if (lines2.some((l) => param.test(l))) return null;
19179
19220
  return exprSystemKind(found[0][1]);
19180
19221
  }
19181
- const prop = path.split(".").pop() ?? "";
19182
- const def = new RegExp(`(?:^|[\\s{,])${esc4(prop)}\\s*:\\s*([^,}\\n]+)`);
19222
+ const prop2 = path.split(".").pop() ?? "";
19223
+ const def = new RegExp(`(?:^|[\\s{,])${esc4(prop2)}\\s*:\\s*([^,}\\n]+)`);
19183
19224
  const defs = lines2.map((l) => l.match(def)).filter((m) => m !== null);
19184
19225
  if (defs.length === 0) return null;
19185
19226
  const kinds = defs.map((m) => exprSystemKind(m[1]));
@@ -19513,11 +19554,11 @@ function prmRouteViaConstant(tree) {
19513
19554
  const decl = /\bconst\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*(\[[^\]]*\]|"[^"\n]*"|'[^'\n]*'|`[^`]*`)/g;
19514
19555
  for (const m of text.matchAll(decl)) if (m[2].includes(PRM_PATH_LITERAL)) holders.add(m[1]);
19515
19556
  if (holders.size === 0) continue;
19516
- const names = new Set(holders);
19557
+ const names2 = new Set(holders);
19517
19558
  const loop = /\bfor\s*\(\s*(?:const|let)\s+([A-Za-z_$][\w$]*)\s+of\s+([A-Za-z_$][\w$]*)\s*\)/g;
19518
- for (const m of text.matchAll(loop)) if (holders.has(m[2])) names.add(m[1]);
19559
+ for (const m of text.matchAll(loop)) if (holders.has(m[2])) names2.add(m[1]);
19519
19560
  const route = /\b(?:app|router|server)\.(?:get|route|all)\s*\(\s*([A-Za-z_$][\w$]*)\s*,/g;
19520
- for (const m of text.matchAll(route)) if (names.has(m[1])) return true;
19561
+ for (const m of text.matchAll(route)) if (names2.has(m[1])) return true;
19521
19562
  }
19522
19563
  return false;
19523
19564
  }
@@ -19528,8 +19569,17 @@ function challengeForwarded(tree) {
19528
19569
  const code = file.lines.filter((l) => !l.comment);
19529
19570
  const text = code.map((l) => l.raw).join("\n");
19530
19571
  if (!FORWARD_STATUS_RE.test(text)) continue;
19531
- const hit = code.find((l) => FORWARD_HEADER_LINE_RE.test(l.raw));
19532
- if (hit) return `${file.rel}:${hit.n}`;
19572
+ const ct = codeText(file);
19573
+ for (const l of code) {
19574
+ if (!FORWARD_HEADER_LINE_RE.test(l.raw)) continue;
19575
+ const start = ct.lineStart[l.n - 1] ?? 0;
19576
+ if (on401Path(ct, start, start + l.raw.length)) return `${file.rel}:${l.n}`;
19577
+ const owner = /([\w$]+)\.headers\b/.exec(l.raw)?.[1];
19578
+ if (owner === void 0) continue;
19579
+ const near = code.filter((x) => x.n >= l.n - PATH_LINES_BEFORE && x.n <= l.n + PATH_LINES_AFTER).map((x) => x.raw).join("\n");
19580
+ if (new RegExp(`\\b${owner.replace(/\$/g, "\\$")}\\.status\\b`).test(near))
19581
+ return `${file.rel}:${l.n}`;
19582
+ }
19533
19583
  }
19534
19584
  return null;
19535
19585
  }
@@ -20268,12 +20318,12 @@ function gateExemptions(tree, g, installer) {
20268
20318
  const end = exprEnd(s.shape, eq + 1);
20269
20319
  const code = s.code.slice(eq + 1, end);
20270
20320
  const shape = s.shape.slice(eq + 1, end);
20271
- const names = [];
20321
+ const names2 = [];
20272
20322
  const unread2 = [];
20273
20323
  const param = /^\s*(?:\(\s*)*(?:async\s*)?(?:function\s*[\w$]*\s*)?\(\s*([A-Za-z_$][\w$]*)/.exec(
20274
20324
  shape
20275
20325
  )?.[1];
20276
- if (!param) return { names, unread: unread2 };
20326
+ if (!param) return { names: names2, unread: unread2 };
20277
20327
  const literal = (text, home) => {
20278
20328
  const lit = stringLiteral(text);
20279
20329
  if (lit !== null) return lit;
@@ -20364,7 +20414,7 @@ function gateExemptions(tree, g, installer) {
20364
20414
  anchor: c.anchor,
20365
20415
  reason: `the exempt set passed to ${installer.name} (${c.anchor}) is not a \`new Set([...])\` of strings`
20366
20416
  });
20367
- else for (const n of got2) names.push({ name: n, anchor: c.anchor });
20417
+ else for (const n of got2) names2.push({ name: n, anchor: c.anchor });
20368
20418
  }
20369
20419
  continue;
20370
20420
  }
@@ -20375,7 +20425,7 @@ function gateExemptions(tree, g, installer) {
20375
20425
  anchor: at,
20376
20426
  reason: `the exempt set \`${id}\` (${at}) cannot be followed to a \`new Set([...])\` of strings`
20377
20427
  });
20378
- else for (const n of got) names.push({ name: n, anchor: at });
20428
+ else for (const n of got) names2.push({ name: n, anchor: at });
20379
20429
  } else if (e3) {
20380
20430
  for (const el of topLevelParts(e3[1])) {
20381
20431
  const v = literal(el, s);
@@ -20384,10 +20434,10 @@ function gateExemptions(tree, g, installer) {
20384
20434
  anchor: at,
20385
20435
  reason: `exempt list element \`${el.slice(0, 40)}\` (${at}) is not a string`
20386
20436
  });
20387
- else names.push({ name: v, anchor: at });
20437
+ else names2.push({ name: v, anchor: at });
20388
20438
  }
20389
20439
  } else if (e2 && literal(e2[1], s) !== null) {
20390
- names.push({ name: literal(e2[1], s), anchor: at });
20440
+ names2.push({ name: literal(e2[1], s), anchor: at });
20391
20441
  } else {
20392
20442
  unread2.push({
20393
20443
  anchor: at,
@@ -20396,7 +20446,7 @@ function gateExemptions(tree, g, installer) {
20396
20446
  }
20397
20447
  }
20398
20448
  }
20399
- return { names, unread: unread2 };
20449
+ return { names: names2, unread: unread2 };
20400
20450
  }
20401
20451
  function decisionCalls(tree) {
20402
20452
  const out = [];
@@ -20568,8 +20618,8 @@ function judgeStatic(tree, id) {
20568
20618
  `\`${e.name}\` (${e.anchor}) is exempt from the gate (${gate.anchor}): only the identity tool (C-33) may skip the role decision`
20569
20619
  );
20570
20620
  }
20571
- const names = installers.map((i) => i.fn?.name).filter((n) => !!n);
20572
- const callRe = names.length > 0 ? new RegExp(String.raw`(?<![\w$.])(?:${names.map(esc2).join("|")})\s*\(`) : null;
20621
+ const names2 = installers.map((i) => i.fn?.name).filter((n) => !!n);
20622
+ const callRe = names2.length > 0 ? new RegExp(String.raw`(?<![\w$.])(?:${names2.map(esc2).join("|")})\s*\(`) : null;
20573
20623
  for (const reg of regs) {
20574
20624
  if (reg.form === "tools/call dispatcher") continue;
20575
20625
  const s = reg.call.src;
@@ -20593,7 +20643,7 @@ function judgeStatic(tree, id) {
20593
20643
  if (installAt === void 0) {
20594
20644
  unreadable2.push({
20595
20645
  anchor: reg.call.anchor,
20596
- reason: `tool \`${name}\` (${reg.call.anchor}) is registered in a function that does not install the gate (${names.join(", ") || gates[0].anchor}): whether its calls pass the gate is not decidable statically`
20646
+ reason: `tool \`${name}\` (${reg.call.anchor}) is registered in a function that does not install the gate (${names2.join(", ") || gates[0].anchor}): whether its calls pass the gate is not decidable statically`
20597
20647
  });
20598
20648
  } else if (installAt > reg.call.start) {
20599
20649
  problems.push(
@@ -21441,16 +21491,16 @@ function readInstalledAs(tree) {
21441
21491
  }
21442
21492
  const files = [];
21443
21493
  const walk3 = (d) => {
21444
- let names;
21494
+ let names2;
21445
21495
  try {
21446
- names = readdirSync15(d).sort();
21496
+ names2 = readdirSync15(d).sort();
21447
21497
  } catch (e) {
21448
21498
  out.unread.push(
21449
21499
  `${d.slice(nm.length + 1)} (directory not listed: ${e.message})`
21450
21500
  );
21451
21501
  return;
21452
21502
  }
21453
- for (const n of names) {
21503
+ for (const n of names2) {
21454
21504
  if (files.length >= MAX_FILES_PER_PACKAGE) return;
21455
21505
  if (n === "node_modules") continue;
21456
21506
  const full = join31(d, n);
@@ -22273,8 +22323,8 @@ var s10SsrfGuard = {
22273
22323
  /\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:args|input|params|payload|delivery|subscription|opts|options|data|(?:req|request)\.(?:body|query|params))\b/g
22274
22324
  )) {
22275
22325
  for (const part of m[1].split(",")) {
22276
- const [prop, rename] = part.split(":").map((s) => s.trim());
22277
- if (URL_PROP_NAMES.has(prop)) aliases.add(rename || prop);
22326
+ const [prop2, rename] = part.split(":").map((s) => s.trim());
22327
+ if (URL_PROP_NAMES.has(prop2)) aliases.add(rename || prop2);
22278
22328
  }
22279
22329
  }
22280
22330
  const templateOnly = first.match(/^`\$\{([^}]+)\}`$/)?.[1] ?? first;
@@ -22615,9 +22665,9 @@ var isDeclaration = (c) => {
22615
22665
  return a !== void 0 && /^\s*[A-Za-z_$][\w$]*\??\s*:\s*\S/.test(c.src.shape.slice(a[0], a[1]));
22616
22666
  };
22617
22667
  function typedFetchNames(s) {
22618
- const names = /* @__PURE__ */ new Set();
22619
- for (const h of s.shape.matchAll(TYPED_FETCH)) names.add(h[1]);
22620
- return names;
22668
+ const names2 = /* @__PURE__ */ new Set();
22669
+ for (const h of s.shape.matchAll(TYPED_FETCH)) names2.add(h[1]);
22670
+ return names2;
22621
22671
  }
22622
22672
  function outboundSites(tree) {
22623
22673
  const sites = /* @__PURE__ */ new Map();
@@ -24651,14 +24701,14 @@ function splitTop2(m, from, to) {
24651
24701
  return parts;
24652
24702
  }
24653
24703
  function listTs(dir, unread2, out = []) {
24654
- let names;
24704
+ let names2;
24655
24705
  try {
24656
- names = readdirSync16(dir);
24706
+ names2 = readdirSync16(dir);
24657
24707
  } catch (err) {
24658
24708
  unread2.push(`${dir} could not be listed (${fsErrorCode(err)})`);
24659
24709
  return out;
24660
24710
  }
24661
- for (const n of names) {
24711
+ for (const n of names2) {
24662
24712
  if (n === "node_modules" || n === "_generated" || n === "__tests__") continue;
24663
24713
  const p = join32(dir, n);
24664
24714
  let st;
@@ -24683,7 +24733,7 @@ function discoverBackend(root) {
24683
24733
  } catch {
24684
24734
  return void 0;
24685
24735
  }
24686
- for (let up = 0; up < 5; up++) {
24736
+ for (let up2 = 0; up2 < 5; up2++) {
24687
24737
  const cand = join32(dir, "convex");
24688
24738
  if (existsSync22(join32(cand, "schema.ts"))) return cand;
24689
24739
  const parent = dirname16(dir);
@@ -24883,11 +24933,11 @@ function handOff(at, o, len2, files, propertyOf, expression = false) {
24883
24933
  let argAt = o;
24884
24934
  let key = propertyOf;
24885
24935
  if (!(/[(,]\s*$/.test(pre) && (expression || /^\s*[,)]/.test(after)))) {
24886
- const prop = /[{,]\s*([A-Za-z_$][\w$]*)\s*:\s*$/.exec(pre);
24936
+ const prop2 = /[{,]\s*([A-Za-z_$][\w$]*)\s*:\s*$/.exec(pre);
24887
24937
  const short = !expression && /[{,]\s*$/.test(pre) && /^\s*[,}]/.test(after);
24888
- if (!prop && !short) return void 0;
24938
+ if (!prop2 && !short) return void 0;
24889
24939
  if (key !== void 0) return "is nested two objects deep, which this scan does not follow";
24890
- key = prop ? prop[1] : at.m.slice(o, o + len2);
24940
+ key = prop2 ? prop2[1] : at.m.slice(o, o + len2);
24891
24941
  let depth = 0;
24892
24942
  let brace = -1;
24893
24943
  for (let i = o - 1; i >= 0; i--) {
@@ -25780,10 +25830,10 @@ function inlineNarrowing(m, start, close2, end) {
25780
25830
  const found = narrowingsOver(m, [param], bodyFrom, bodyTo);
25781
25831
  return found.length > 0 ? { narrowing: found[0] } : null;
25782
25832
  }
25783
- function rebound(m, names, from, to) {
25833
+ function rebound(m, names2, from, to) {
25784
25834
  const out = [];
25785
25835
  const region = m.slice(from, to);
25786
- for (const name of names) {
25836
+ for (const name of names2) {
25787
25837
  for (const hit of region.matchAll(
25788
25838
  new RegExp(
25789
25839
  `\\b(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*(?::[^=]+)?=\\s*${esc7(name)}\\s*(?:;|$)`,
@@ -25795,10 +25845,10 @@ function rebound(m, names, from, to) {
25795
25845
  }
25796
25846
  return out;
25797
25847
  }
25798
- function narrowingsOver(m, names, from, to) {
25848
+ function narrowingsOver(m, names2, from, to) {
25799
25849
  const out = [];
25800
25850
  const region = m.slice(from, to);
25801
- for (const name of names) {
25851
+ for (const name of names2) {
25802
25852
  const n = esc7(name);
25803
25853
  for (const hit of region.matchAll(/\bscopeFilter(List|Get)\s*\(/g)) {
25804
25854
  const open = from + (hit.index ?? 0) + hit[0].length - 1;
@@ -25877,12 +25927,12 @@ function scanS35(tree) {
25877
25927
  }
25878
25928
  const argText2 = parts.slice(1).map(([a, b]) => m.slice(a, b)).join(",");
25879
25929
  const carried = CARRY_WORD.test(argText2);
25880
- const names = boundNames(m, start);
25930
+ const names2 = boundNames(m, start);
25881
25931
  const end = blockEnd(m, start);
25882
25932
  const inline = inlineNarrowing(m, start, close2, end);
25883
25933
  const narrowings = [
25884
25934
  ...inline && "narrowing" in inline ? [inline.narrowing] : [],
25885
- ...narrowingsOver(m, [...names, ...rebound(m, names, close2 + 1, end)], close2 + 1, end)
25935
+ ...narrowingsOver(m, [...names2, ...rebound(m, names2, close2 + 1, end)], close2 + 1, end)
25886
25936
  ].sort((a, b) => a.offset - b.offset);
25887
25937
  if (narrowings.length === 0 && inline && "unreadable" in inline && !carried) {
25888
25938
  res.cnj.push({
@@ -25894,7 +25944,7 @@ function scanS35(tree) {
25894
25944
  if (narrowings.length === 0 || carried) {
25895
25945
  res.ok.push({
25896
25946
  anchor,
25897
- note: names.length === 0 && !inline ? `${anchor} ${door}: result not bound, nothing narrows it` : `${anchor} ${door}`
25947
+ note: names2.length === 0 && !inline ? `${anchor} ${door}: result not bound, nothing narrows it` : `${anchor} ${door}`
25898
25948
  });
25899
25949
  continue;
25900
25950
  }
@@ -26666,14 +26716,14 @@ function scanS37(tree) {
26666
26716
  }
26667
26717
  for (const k of outputSinks(s)) {
26668
26718
  const body = s.shape.slice(k.at, k.end);
26669
- const names = [...bound].filter(
26719
+ const names2 = [...bound].filter(
26670
26720
  (n) => new RegExp(String.raw`(?<![\w$.])${n}(?![\w$])`).test(body)
26671
26721
  );
26672
26722
  const direct = reads.find((r) => r.at >= k.at && r.at <= k.end);
26673
26723
  const secret = [...secretKeys].find(
26674
26724
  (n) => new RegExp(String.raw`\.${n}(?![\w$])`).test(body)
26675
26725
  );
26676
- const what = names[0] ?? (direct ? `${direct.name ?? "an environment value"}` : secret);
26726
+ const what = names2[0] ?? (direct ? `${direct.name ?? "an environment value"}` : secret);
26677
26727
  if (what !== void 0) {
26678
26728
  const anchor = anchorAt(s, k.at);
26679
26729
  res.red.push({
@@ -26952,8 +27002,8 @@ function scanS38(tree) {
26952
27002
  if (requesting2.length === 0) continue;
26953
27003
  const f = requesting2[0];
26954
27004
  const anchor = anchorAt(s, f.at);
26955
- const names = group.map((g) => `\`${g.name}\``).join(" -> ");
26956
- const kind = group.length === 1 ? "calls itself" : `is in a recursion cycle (${names})`;
27005
+ const names2 = group.map((g) => `\`${g.name}\``).join(" -> ");
27006
+ const kind = group.length === 1 ? "calls itself" : `is in a recursion cycle (${names2})`;
26957
27007
  const text = group.map((g) => s.shape.slice(g.at, g.to)).join("\n");
26958
27008
  if (/\b(?:sleep|delay|setTimeout)\s*\(|retry-?after|attempt/i.test(text) || /\b429\b|\b503\b/.test(text)) {
26959
27009
  res.cnj.push({
@@ -28503,7 +28553,7 @@ function runStatic4(tree) {
28503
28553
  `S44 positive control FAILED: sees=${controls.sees} spares=${controls.spares} \u2014 reader broken, verdict untrustworthy`
28504
28554
  );
28505
28555
  const inProduct = (a) => isProductSource(a.slice(0, a.lastIndexOf(":")));
28506
- const tools = findRegisteredTools(tree).filter((t) => inProduct(t.anchor));
28556
+ const tools = findRegisteredTools(tree, isProductSource);
28507
28557
  const unresolved = findUnresolvedToolSites(tree).filter(inProduct);
28508
28558
  if (tools.length === 0) {
28509
28559
  const surface = toolSurfaceAnchor(tree);
@@ -33128,6 +33178,1659 @@ var s50ServedDiscovery = {
33128
33178
  runServed: runServed7
33129
33179
  };
33130
33180
 
33181
+ // src/detectors/s51-served-output.ts
33182
+ import * as ts2 from "typescript";
33183
+
33184
+ // src/detectors/jsonSchemaCheck.ts
33185
+ var ANNOTATIONS = /* @__PURE__ */ new Set([
33186
+ "$schema",
33187
+ "$id",
33188
+ "$comment",
33189
+ "$defs",
33190
+ "definitions",
33191
+ "$vocabulary",
33192
+ "$anchor",
33193
+ "title",
33194
+ "description",
33195
+ "default",
33196
+ "deprecated",
33197
+ "readOnly",
33198
+ "writeOnly",
33199
+ "examples",
33200
+ "format",
33201
+ "contentEncoding",
33202
+ "contentMediaType",
33203
+ "contentSchema"
33204
+ ]);
33205
+ var ASSERTED = /* @__PURE__ */ new Set([
33206
+ "$ref",
33207
+ "allOf",
33208
+ "anyOf",
33209
+ "oneOf",
33210
+ "not",
33211
+ "if",
33212
+ "then",
33213
+ "else",
33214
+ "properties",
33215
+ "patternProperties",
33216
+ "additionalProperties",
33217
+ "propertyNames",
33218
+ "dependentSchemas",
33219
+ "prefixItems",
33220
+ "items",
33221
+ "contains",
33222
+ "type",
33223
+ "enum",
33224
+ "const",
33225
+ "multipleOf",
33226
+ "maximum",
33227
+ "exclusiveMaximum",
33228
+ "minimum",
33229
+ "exclusiveMinimum",
33230
+ "maxLength",
33231
+ "minLength",
33232
+ "pattern",
33233
+ "maxItems",
33234
+ "minItems",
33235
+ "uniqueItems",
33236
+ "maxContains",
33237
+ "minContains",
33238
+ "maxProperties",
33239
+ "minProperties",
33240
+ "required",
33241
+ "dependentRequired"
33242
+ ]);
33243
+ var NOT_IMPLEMENTED = /* @__PURE__ */ new Set([
33244
+ "$dynamicRef",
33245
+ "$dynamicAnchor",
33246
+ "unevaluatedItems",
33247
+ "unevaluatedProperties"
33248
+ ]);
33249
+ var SCHEMA_KEYWORD_CENSUS = /* @__PURE__ */ new Set([
33250
+ ...ANNOTATIONS,
33251
+ ...ASSERTED,
33252
+ ...NOT_IMPLEMENTED
33253
+ ]);
33254
+ var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
33255
+ var has4 = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
33256
+ var nonNegInt = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0;
33257
+ var num = (v) => typeof v === "number" && Number.isFinite(v);
33258
+ var strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
33259
+ var KEYWORD_SHAPE = {
33260
+ multipleOf: [(v) => num(v) && v > 0, "a number above 0"],
33261
+ maximum: [num, "a number"],
33262
+ exclusiveMaximum: [num, "a number"],
33263
+ minimum: [num, "a number"],
33264
+ exclusiveMinimum: [num, "a number"],
33265
+ maxLength: [nonNegInt, "a non-negative integer"],
33266
+ minLength: [nonNegInt, "a non-negative integer"],
33267
+ maxItems: [nonNegInt, "a non-negative integer"],
33268
+ minItems: [nonNegInt, "a non-negative integer"],
33269
+ maxContains: [nonNegInt, "a non-negative integer"],
33270
+ minContains: [nonNegInt, "a non-negative integer"],
33271
+ maxProperties: [nonNegInt, "a non-negative integer"],
33272
+ minProperties: [nonNegInt, "a non-negative integer"],
33273
+ pattern: [(v) => typeof v === "string", "a string"],
33274
+ uniqueItems: [(v) => typeof v === "boolean", "a boolean"],
33275
+ required: [strings, "an array of strings"],
33276
+ dependentRequired: [
33277
+ (v) => isObj4(v) && Object.values(v).every(strings),
33278
+ "an object of string arrays"
33279
+ ],
33280
+ properties: [isObj4, "an object"],
33281
+ patternProperties: [isObj4, "an object"],
33282
+ dependentSchemas: [isObj4, "an object"]
33283
+ };
33284
+ function typeOf(v) {
33285
+ if (v === null) return "null";
33286
+ if (Array.isArray(v)) return "array";
33287
+ if (typeof v === "number") return Number.isInteger(v) ? "integer" : "number";
33288
+ return typeof v;
33289
+ }
33290
+ function matchesType(v, t) {
33291
+ const k = typeOf(v);
33292
+ if (t === "number") return k === "number" || k === "integer";
33293
+ return k === t;
33294
+ }
33295
+ function jsonEqual(a, b) {
33296
+ if (a === b) return true;
33297
+ if (typeof a === "number" && typeof b === "number") return a === b;
33298
+ if (Array.isArray(a) && Array.isArray(b))
33299
+ return a.length === b.length && a.every((x, i) => jsonEqual(x, b[i]));
33300
+ if (isObj4(a) && isObj4(b)) {
33301
+ const ka = Object.keys(a);
33302
+ const kb2 = Object.keys(b);
33303
+ return ka.length === kb2.length && ka.every((k) => has4(b, k) && jsonEqual(a[k], b[k]));
33304
+ }
33305
+ return false;
33306
+ }
33307
+ function resolvePointer(root, ref) {
33308
+ if (ref === "#") return { ok: true, v: root };
33309
+ if (!ref.startsWith("#/")) return { ok: false };
33310
+ let cur = root;
33311
+ for (const raw of ref.slice(2).split("/")) {
33312
+ const seg = decodeURIComponent(raw).replace(/~1/g, "/").replace(/~0/g, "~");
33313
+ if (Array.isArray(cur) && /^\d+$/.test(seg)) cur = cur[Number(seg)];
33314
+ else if (isObj4(cur) && has4(cur, seg)) cur = cur[seg];
33315
+ else return { ok: false };
33316
+ }
33317
+ return { ok: true, v: cur };
33318
+ }
33319
+ var VALID = { kind: "valid" };
33320
+ function regex(p) {
33321
+ if (typeof p !== "string") return null;
33322
+ try {
33323
+ return new RegExp(p, "u");
33324
+ } catch {
33325
+ return null;
33326
+ }
33327
+ }
33328
+ function checkSchema(schema, value, root = schema, path = "$", depth = 0) {
33329
+ if (depth > 64) return { kind: "unread", path, why: "schema recursion deeper than 64 levels" };
33330
+ if (schema === true) return VALID;
33331
+ if (schema === false) return { kind: "invalid", path, why: "the schema is `false`" };
33332
+ if (!isObj4(schema))
33333
+ return {
33334
+ kind: "unread",
33335
+ path,
33336
+ why: `a schema that is a ${typeOf(schema)}, not an object or a boolean`
33337
+ };
33338
+ for (const k of Object.keys(schema)) {
33339
+ if (NOT_IMPLEMENTED.has(k))
33340
+ return { kind: "unread", path, why: `keyword \`${k}\` is not implemented` };
33341
+ if (!ANNOTATIONS.has(k) && !ASSERTED.has(k))
33342
+ return { kind: "unread", path, why: `keyword \`${k}\` is outside the 2020-12 census` };
33343
+ }
33344
+ for (const [k, [ok, want]] of Object.entries(KEYWORD_SHAPE))
33345
+ if (has4(schema, k) && !ok(schema[k]))
33346
+ return {
33347
+ kind: "unread",
33348
+ path,
33349
+ why: `keyword \`${k}\` carries ${JSON.stringify(schema[k])}, not ${want}`
33350
+ };
33351
+ const sub = (s, v, p) => checkSchema(s, v, root, p, depth + 1);
33352
+ const fail = (why) => ({ kind: "invalid", path, why });
33353
+ const all = (results) => {
33354
+ const unread2 = results.find((r) => r.kind === "unread");
33355
+ if (unread2) return unread2;
33356
+ return results.find((r) => r.kind === "invalid") ?? VALID;
33357
+ };
33358
+ const out = [];
33359
+ if (schema.$ref !== void 0) {
33360
+ if (typeof schema.$ref !== "string")
33361
+ return { kind: "unread", path, why: "a `$ref` that is not a string" };
33362
+ const target = resolvePointer(root, schema.$ref);
33363
+ if (!target.ok)
33364
+ return {
33365
+ kind: "unread",
33366
+ path,
33367
+ why: `\`$ref\` ${schema.$ref} is not a resolvable local pointer`
33368
+ };
33369
+ out.push(sub(target.v, value, path));
33370
+ }
33371
+ if (schema.type !== void 0) {
33372
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
33373
+ if (types.some((t) => typeof t !== "string"))
33374
+ return { kind: "unread", path, why: "a `type` that is not a string or a list of strings" };
33375
+ if (!types.some((t) => matchesType(value, t)))
33376
+ out.push(fail(`a ${typeOf(value)} where the schema says ${types.join(" | ")}`));
33377
+ }
33378
+ if (schema.enum !== void 0) {
33379
+ if (!Array.isArray(schema.enum))
33380
+ return { kind: "unread", path, why: "an `enum` that is not an array" };
33381
+ if (!schema.enum.some((e) => jsonEqual(e, value))) out.push(fail("a value outside its `enum`"));
33382
+ }
33383
+ if (has4(schema, "const") && !jsonEqual(schema.const, value))
33384
+ out.push(fail("a value other than its `const`"));
33385
+ for (const key of ["allOf", "anyOf", "oneOf"]) {
33386
+ const list = schema[key];
33387
+ if (list === void 0) continue;
33388
+ if (!Array.isArray(list)) return { kind: "unread", path, why: `\`${key}\` is not an array` };
33389
+ const results = list.map((s, i) => sub(s, value, `${path}<${key}[${i}]>`));
33390
+ const unread2 = results.find((r) => r.kind === "unread");
33391
+ if (unread2) return unread2;
33392
+ const passed = results.filter((r) => r.kind === "valid").length;
33393
+ if (key === "allOf" && passed < list.length)
33394
+ out.push(results.find((r) => r.kind === "invalid"));
33395
+ if (key === "anyOf" && passed === 0) out.push(fail("no `anyOf` branch validates"));
33396
+ if (key === "oneOf" && passed !== 1)
33397
+ out.push(fail(`${passed} \`oneOf\` branches validate, exactly one must`));
33398
+ }
33399
+ if (schema.not !== void 0) {
33400
+ const r = sub(schema.not, value, `${path}<not>`);
33401
+ if (r.kind === "unread") return r;
33402
+ if (r.kind === "valid") out.push(fail("the value validates against `not`"));
33403
+ }
33404
+ if (schema.if !== void 0) {
33405
+ const r = sub(schema.if, value, `${path}<if>`);
33406
+ if (r.kind === "unread") return r;
33407
+ const branch = r.kind === "valid" ? schema.then : schema.else;
33408
+ if (branch !== void 0) out.push(sub(branch, value, path));
33409
+ }
33410
+ if (typeof value === "number") {
33411
+ const n = (k) => typeof schema[k] === "number" ? schema[k] : void 0;
33412
+ const mo = n("multipleOf");
33413
+ if (mo !== void 0 && mo > 0 && !Number.isInteger(value / mo))
33414
+ out.push(fail(`not a multiple of ${mo}`));
33415
+ if (n("maximum") !== void 0 && value > n("maximum"))
33416
+ out.push(fail("above `maximum`"));
33417
+ if (n("minimum") !== void 0 && value < n("minimum"))
33418
+ out.push(fail("below `minimum`"));
33419
+ if (n("exclusiveMaximum") !== void 0 && value >= n("exclusiveMaximum"))
33420
+ out.push(fail("not below `exclusiveMaximum`"));
33421
+ if (n("exclusiveMinimum") !== void 0 && value <= n("exclusiveMinimum"))
33422
+ out.push(fail("not above `exclusiveMinimum`"));
33423
+ }
33424
+ if (typeof value === "string") {
33425
+ const len2 = [...value].length;
33426
+ if (typeof schema.maxLength === "number" && len2 > schema.maxLength)
33427
+ out.push(fail("longer than `maxLength`"));
33428
+ if (typeof schema.minLength === "number" && len2 < schema.minLength)
33429
+ out.push(fail("shorter than `minLength`"));
33430
+ if (schema.pattern !== void 0) {
33431
+ const re = regex(schema.pattern);
33432
+ if (!re)
33433
+ return {
33434
+ kind: "unread",
33435
+ path,
33436
+ why: `\`pattern\` ${String(schema.pattern)} does not compile`
33437
+ };
33438
+ if (!re.test(value)) out.push(fail(`does not match \`pattern\` ${schema.pattern}`));
33439
+ }
33440
+ }
33441
+ if (Array.isArray(value)) {
33442
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems)
33443
+ out.push(fail("more items than `maxItems`"));
33444
+ if (typeof schema.minItems === "number" && value.length < schema.minItems)
33445
+ out.push(fail("fewer items than `minItems`"));
33446
+ if (schema.uniqueItems === true && value.some((x, i) => value.slice(i + 1).some((y) => jsonEqual(x, y))))
33447
+ out.push(fail("duplicate items under `uniqueItems`"));
33448
+ const prefix = schema.prefixItems;
33449
+ if (prefix !== void 0 && !Array.isArray(prefix))
33450
+ return { kind: "unread", path, why: "`prefixItems` is not an array" };
33451
+ const np = Array.isArray(prefix) ? prefix.length : 0;
33452
+ value.forEach((item, i) => {
33453
+ if (i < np) out.push(sub(prefix[i], item, `${path}[${i}]`));
33454
+ else if (schema.items !== void 0) out.push(sub(schema.items, item, `${path}[${i}]`));
33455
+ });
33456
+ if (schema.contains !== void 0) {
33457
+ const hits = value.map((x, i) => sub(schema.contains, x, `${path}[${i}]`));
33458
+ const unread2 = hits.find((r) => r.kind === "unread");
33459
+ if (unread2) return unread2;
33460
+ const count = hits.filter((r) => r.kind === "valid").length;
33461
+ const min = typeof schema.minContains === "number" ? schema.minContains : 1;
33462
+ if (count < min) out.push(fail(`${count} item(s) match \`contains\`, at least ${min} must`));
33463
+ if (typeof schema.maxContains === "number" && count > schema.maxContains)
33464
+ out.push(fail(`${count} item(s) match \`contains\`, at most ${schema.maxContains} may`));
33465
+ }
33466
+ }
33467
+ if (isObj4(value)) {
33468
+ const keys = Object.keys(value);
33469
+ if (typeof schema.maxProperties === "number" && keys.length > schema.maxProperties)
33470
+ out.push(fail("more properties than `maxProperties`"));
33471
+ if (typeof schema.minProperties === "number" && keys.length < schema.minProperties)
33472
+ out.push(fail("fewer properties than `minProperties`"));
33473
+ if (schema.required !== void 0) {
33474
+ if (!Array.isArray(schema.required))
33475
+ return { kind: "unread", path, why: "`required` is not an array" };
33476
+ const missing = schema.required.filter((r) => typeof r === "string" && !has4(value, r));
33477
+ if (missing.length > 0)
33478
+ out.push(fail(`required ${missing.map((m) => `\`${m}\``).join(", ")} missing`));
33479
+ }
33480
+ if (isObj4(schema.dependentRequired)) {
33481
+ for (const [k, deps] of Object.entries(schema.dependentRequired)) {
33482
+ if (!has4(value, k) || !Array.isArray(deps)) continue;
33483
+ const missing = deps.filter((d) => typeof d === "string" && !has4(value, d));
33484
+ if (missing.length > 0) out.push(fail(`\`${k}\` present without ${missing.join(", ")}`));
33485
+ }
33486
+ }
33487
+ if (isObj4(schema.dependentSchemas)) {
33488
+ for (const [k, s] of Object.entries(schema.dependentSchemas))
33489
+ if (has4(value, k)) out.push(sub(s, value, path));
33490
+ }
33491
+ const props = isObj4(schema.properties) ? schema.properties : {};
33492
+ const patterns = [];
33493
+ if (isObj4(schema.patternProperties)) {
33494
+ for (const [p, s] of Object.entries(schema.patternProperties)) {
33495
+ const re = regex(p);
33496
+ if (!re)
33497
+ return { kind: "unread", path, why: `\`patternProperties\` key ${p} does not compile` };
33498
+ patterns.push([re, s]);
33499
+ }
33500
+ }
33501
+ for (const k of keys) {
33502
+ const p = `${path}.${k}`;
33503
+ let evaluated = false;
33504
+ if (has4(props, k)) {
33505
+ out.push(sub(props[k], value[k], p));
33506
+ evaluated = true;
33507
+ }
33508
+ for (const [re, s] of patterns) {
33509
+ if (re.test(k)) {
33510
+ out.push(sub(s, value[k], p));
33511
+ evaluated = true;
33512
+ }
33513
+ }
33514
+ if (!evaluated && schema.additionalProperties !== void 0)
33515
+ out.push(sub(schema.additionalProperties, value[k], p));
33516
+ if (schema.propertyNames !== void 0)
33517
+ out.push(sub(schema.propertyNames, k, `${path}<key ${k}>`));
33518
+ }
33519
+ }
33520
+ return all(out);
33521
+ }
33522
+ function schemaCheckControls() {
33523
+ const s = { type: "object", properties: { n: { type: "integer" } }, required: ["n"] };
33524
+ return {
33525
+ sees: checkSchema(s, { n: "x" }).kind === "invalid" && checkSchema(s, {}).kind === "invalid",
33526
+ spares: checkSchema(s, { n: 1, extra: true }).kind === "valid",
33527
+ refuses: checkSchema({ unevaluatedProperties: false }, {}).kind === "unread"
33528
+ };
33529
+ }
33530
+
33531
+ // src/detectors/outputContract.ts
33532
+ import * as ts from "typescript";
33533
+ var lineOfPos = (sf, pos) => sf.getLineAndCharacterOfPosition(pos).line + 1;
33534
+ var startLine = (n) => lineOfPos(n.getSourceFile(), n.getStart(n.getSourceFile()));
33535
+ function isFunctionLikeExpr(e) {
33536
+ return ts.isArrowFunction(e) || ts.isFunctionExpression(e);
33537
+ }
33538
+ var unwrapExpr = (e) => {
33539
+ let x = e;
33540
+ while (ts.isParenthesizedExpression(x) || ts.isAsExpression(x) || ts.isSatisfiesExpression(x) || ts.isNonNullExpression(x) || ts.isAwaitExpression(x) || ts.isTypeAssertionExpression(x))
33541
+ x = x.expression;
33542
+ return x;
33543
+ };
33544
+ function sameFileFunction(sf, name) {
33545
+ let found;
33546
+ const visit = (n) => {
33547
+ if (found) return;
33548
+ if (ts.isFunctionDeclaration(n) && n.name?.text === name && n.body) found = n;
33549
+ else if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === name && n.initializer && isFunctionLikeExpr(unwrapExpr(n.initializer)))
33550
+ found = unwrapExpr(n.initializer);
33551
+ else ts.forEachChild(n, visit);
33552
+ };
33553
+ visit(sf);
33554
+ return found;
33555
+ }
33556
+ function completes(stmts) {
33557
+ if (stmts.length === 0) return true;
33558
+ return stmtCompletes(stmts[stmts.length - 1]);
33559
+ }
33560
+ function stmtCompletes(s) {
33561
+ if (ts.isReturnStatement(s) || ts.isThrowStatement(s)) return false;
33562
+ if (ts.isBlock(s)) return completes(s.statements);
33563
+ if (ts.isIfStatement(s))
33564
+ return !s.elseStatement || stmtCompletes(s.thenStatement) || stmtCompletes(s.elseStatement);
33565
+ if (ts.isTryStatement(s)) {
33566
+ if (s.finallyBlock && !completes(s.finallyBlock.statements)) return false;
33567
+ return completes(s.tryBlock.statements) || (s.catchClause ? completes(s.catchClause.block.statements) : false);
33568
+ }
33569
+ if (ts.isSwitchStatement(s)) {
33570
+ const clauses = s.caseBlock.clauses;
33571
+ if (!clauses.some((c) => ts.isDefaultClause(c))) return true;
33572
+ return clauses.some((c) => c.statements.length === 0 || completes(c.statements));
33573
+ }
33574
+ return true;
33575
+ }
33576
+ function collectReturns(body, sf, rel, out, inCatch = false) {
33577
+ const visit = (n, catching) => {
33578
+ if (n !== body && ts.isFunctionLike(n)) return;
33579
+ if (ts.isReturnStatement(n)) {
33580
+ out.push({
33581
+ anchor: `${rel}:${startLine(n)}`,
33582
+ ...n.expression ? { expr: n.expression } : {},
33583
+ form: n.expression ? "return" : "bare-return",
33584
+ inCatch: catching
33585
+ });
33586
+ return;
33587
+ }
33588
+ if (ts.isCatchClause(n)) {
33589
+ visit(n.block, true);
33590
+ return;
33591
+ }
33592
+ ts.forEachChild(n, (c) => visit(c, catching));
33593
+ };
33594
+ visit(body, inCatch);
33595
+ void sf;
33596
+ }
33597
+ function functionReturns(fn, sf, rel) {
33598
+ const out = [];
33599
+ const body = fn.body;
33600
+ if (!body) return out;
33601
+ if (!ts.isBlock(body)) {
33602
+ out.push({
33603
+ anchor: `${rel}:${startLine(body)}`,
33604
+ expr: body,
33605
+ form: "concise",
33606
+ inCatch: false
33607
+ });
33608
+ return out;
33609
+ }
33610
+ collectReturns(body, sf, rel, out);
33611
+ if (completes(body.statements))
33612
+ out.push({
33613
+ anchor: `${rel}:${lineOfPos(sf, body.getEnd())}`,
33614
+ form: "fall-through",
33615
+ inCatch: false
33616
+ });
33617
+ return out;
33618
+ }
33619
+ function registrationCall(sf, line, name) {
33620
+ let best;
33621
+ const visit = (n) => {
33622
+ const a = startLine(n);
33623
+ const b = lineOfPos(sf, n.getEnd());
33624
+ if (a > line || b < line) return;
33625
+ if (ts.isCallExpression(n)) {
33626
+ const names2 = n.arguments.some((arg) => {
33627
+ const u = unwrapExpr(arg);
33628
+ if (ts.isStringLiteralLike(u)) return u.text === name;
33629
+ return (ts.isIdentifier(u) || ts.isPropertyAccessExpression(u)) && startLine(u) === line;
33630
+ });
33631
+ if (names2 && n.arguments.some((arg) => {
33632
+ const x = unwrapExpr(arg);
33633
+ return isFunctionLikeExpr(x) || ts.isIdentifier(x) || ts.isCallExpression(x);
33634
+ }))
33635
+ best = n;
33636
+ }
33637
+ ts.forEachChild(n, visit);
33638
+ };
33639
+ visit(sf);
33640
+ return best;
33641
+ }
33642
+ function caseClause(sf, name) {
33643
+ let found;
33644
+ const visit = (n) => {
33645
+ if (found) return;
33646
+ if (ts.isCaseClause(n) && ts.isStringLiteralLike(n.expression) && n.expression.text === name)
33647
+ found = n;
33648
+ else ts.forEachChild(n, visit);
33649
+ };
33650
+ visit(sf);
33651
+ return found;
33652
+ }
33653
+ var parsedCache = /* @__PURE__ */ new WeakMap();
33654
+ function sourceFileOf(f) {
33655
+ let sf = parsedCache.get(f);
33656
+ if (!sf) {
33657
+ sf = parseFile(f).sf;
33658
+ parsedCache.set(f, sf);
33659
+ }
33660
+ return sf;
33661
+ }
33662
+ function readHandler(tree, tool) {
33663
+ const cut = tool.anchor.lastIndexOf(":");
33664
+ const rel = tool.anchor.slice(0, cut);
33665
+ const line = Number(tool.anchor.slice(cut + 1));
33666
+ const file = tree.files.find((f) => f.rel === rel);
33667
+ if (!file)
33668
+ return {
33669
+ kind: "unread",
33670
+ anchor: tool.anchor,
33671
+ reason: `${tool.name}: its registration file is not in the scanned tree`
33672
+ };
33673
+ const sf = sourceFileOf(file);
33674
+ const call = registrationCall(sf, line, tool.name);
33675
+ if (call) {
33676
+ const last = [...call.arguments].reverse().find((a) => {
33677
+ const x = unwrapExpr(a);
33678
+ return isFunctionLikeExpr(x) || ts.isIdentifier(x) || ts.isCallExpression(x) && x.arguments.some((w) => isFunctionLikeExpr(unwrapExpr(w)));
33679
+ });
33680
+ let u = last ? unwrapExpr(last) : void 0;
33681
+ if (u && ts.isCallExpression(u))
33682
+ u = [...u.arguments].map(unwrapExpr).reverse().find(isFunctionLikeExpr);
33683
+ if (u && isFunctionLikeExpr(u))
33684
+ return {
33685
+ kind: "read",
33686
+ anchor: `${rel}:${startLine(u)}`,
33687
+ returns: functionReturns(u, sf, rel),
33688
+ sf,
33689
+ file
33690
+ };
33691
+ if (u && ts.isIdentifier(u)) {
33692
+ const fn = sameFileFunction(sf, u.text);
33693
+ if (fn)
33694
+ return {
33695
+ kind: "read",
33696
+ anchor: `${rel}:${startLine(fn)}`,
33697
+ returns: functionReturns(fn, sf, rel),
33698
+ sf,
33699
+ file
33700
+ };
33701
+ return {
33702
+ kind: "unread",
33703
+ anchor: `${rel}:${startLine(u)}`,
33704
+ reason: `${tool.name}: its handler \`${u.text}\` is not a function declared in ${rel}`
33705
+ };
33706
+ }
33707
+ }
33708
+ for (const f of tree.files.filter((x) => isProductSource(x.rel))) {
33709
+ const csf = sourceFileOf(f);
33710
+ const clause = caseClause(csf, tool.name);
33711
+ if (!clause) continue;
33712
+ const out = [];
33713
+ for (const st of clause.statements) collectReturns(st, csf, f.rel, out);
33714
+ if (completes(clause.statements))
33715
+ return {
33716
+ kind: "unread",
33717
+ anchor: `${f.rel}:${startLine(clause)}`,
33718
+ reason: `${tool.name}: its \`case\` clause falls through to the next one`
33719
+ };
33720
+ return {
33721
+ kind: "read",
33722
+ anchor: `${f.rel}:${startLine(clause)}`,
33723
+ returns: out,
33724
+ sf: csf,
33725
+ file: f
33726
+ };
33727
+ }
33728
+ return {
33729
+ kind: "unread",
33730
+ anchor: tool.anchor,
33731
+ reason: `${tool.name}: no handler found (not a function argument of its registration, a same-file function, or a \`case\` clause)`
33732
+ };
33733
+ }
33734
+ function productRegistrations(tree) {
33735
+ const inProduct = (a) => isProductSource(a.slice(0, a.lastIndexOf(":")));
33736
+ const all = findRegisteredTools(tree, isProductSource);
33737
+ const computed = all.filter((t) => t.name.includes("${"));
33738
+ return {
33739
+ tools: all.filter((t) => !t.name.includes("${")),
33740
+ unresolved: [
33741
+ ...findUnresolvedToolSites(tree).filter(inProduct),
33742
+ ...computed.map((t) => t.anchor)
33743
+ ]
33744
+ };
33745
+ }
33746
+ function returnedValues(expr, sf, depth = 0) {
33747
+ if (expr === void 0) return [{ kind: "nullish", form: "undefined" }];
33748
+ const e = unwrapExpr(expr);
33749
+ if (e.kind === ts.SyntaxKind.NullKeyword) return [{ kind: "nullish", form: "null" }];
33750
+ if (ts.isIdentifier(e) && e.text === "undefined") return [{ kind: "nullish", form: "undefined" }];
33751
+ if (ts.isVoidExpression(e)) return [{ kind: "nullish", form: "void" }];
33752
+ if (ts.isObjectLiteralExpression(e)) return [{ kind: "object", node: e }];
33753
+ if (ts.isConditionalExpression(e))
33754
+ return [...returnedValues(e.whenTrue, sf, depth), ...returnedValues(e.whenFalse, sf, depth)];
33755
+ if (depth >= 4)
33756
+ return [{ kind: "unread", form: `\`${e.getText(sf).slice(0, 60)}\` (followed too deep)` }];
33757
+ if (ts.isIdentifier(e)) {
33758
+ const init = constInitOf(e);
33759
+ if (init) return returnedValues(init, sf, depth + 1).filter((v) => v.kind !== "nullish");
33760
+ return [{ kind: "unread", form: `identifier \`${e.text}\` not bound to a const in reach` }];
33761
+ }
33762
+ if (ts.isCallExpression(e) && ts.isIdentifier(e.expression)) {
33763
+ const fn = sameFileFunction(sf, e.expression.text);
33764
+ if (fn) {
33765
+ const out = [];
33766
+ for (const r of functionReturns(fn, sf, sf.fileName))
33767
+ out.push(...returnedValues(r.expr, sf, depth + 1));
33768
+ return out.filter((v) => v.kind !== "nullish");
33769
+ }
33770
+ return [
33771
+ { kind: "unread", form: `a call to \`${e.expression.text}\`, not a function of this file` }
33772
+ ];
33773
+ }
33774
+ return [{ kind: "unread", form: `\`${e.getText(sf).slice(0, 60)}\`` }];
33775
+ }
33776
+ function constInitOf(id) {
33777
+ for (let x = id.parent; x; x = x.parent) {
33778
+ if (!(ts.isBlock(x) || ts.isSourceFile(x))) continue;
33779
+ for (const st of x.statements) {
33780
+ if (!ts.isVariableStatement(st) || !(st.declarationList.flags & ts.NodeFlags.Const)) continue;
33781
+ for (const d of st.declarationList.declarations)
33782
+ if (ts.isIdentifier(d.name) && d.name.text === id.text && d.initializer && d.getStart() < id.getStart())
33783
+ return d.initializer;
33784
+ }
33785
+ }
33786
+ return void 0;
33787
+ }
33788
+ function prop(obj, name) {
33789
+ for (const p of obj.properties) {
33790
+ if (ts.isPropertyAssignment(p) && (ts.isIdentifier(p.name) || ts.isStringLiteralLike(p.name)) && p.name.text === name)
33791
+ return { kind: "value", value: p.initializer };
33792
+ if (ts.isShorthandPropertyAssignment(p) && p.name.text === name)
33793
+ return { kind: "shorthand", ident: p.name };
33794
+ }
33795
+ if (obj.properties.some((p) => ts.isSpreadAssignment(p))) return { kind: "spread" };
33796
+ return { kind: "absent" };
33797
+ }
33798
+ function isErrorObject(obj) {
33799
+ const p = prop(obj, "isError");
33800
+ return p.kind === "value" && p.value.kind === ts.SyntaxKind.TrueKeyword;
33801
+ }
33802
+ function servedToolCalls(id, rule, runtime) {
33803
+ const anchor = `${runtime.root} (served)`;
33804
+ if (runtime.launchError)
33805
+ return {
33806
+ cnj: couldNotJudge(
33807
+ id,
33808
+ anchor,
33809
+ `the server could not be started/introspected, so no served tool result was read: ${runtime.launchError} (${rule})`
33810
+ )
33811
+ };
33812
+ if (!runtime.served?.toolCalls)
33813
+ return {
33814
+ cnj: couldNotJudge(
33815
+ id,
33816
+ anchor,
33817
+ `the introspector recorded no tools/call answers for this run (a record written before they were recorded), so no served tool result was read (${rule})`
33818
+ )
33819
+ };
33820
+ const paging = runtime.served.toolsPaging;
33821
+ if (!paging)
33822
+ return {
33823
+ cnj: couldNotJudge(
33824
+ id,
33825
+ anchor,
33826
+ `the introspector recorded no tools/list paging for this run (a record written before it was recorded), so it is unknown whether every served tool was read (${rule})`
33827
+ )
33828
+ };
33829
+ if (!paging.complete)
33830
+ return {
33831
+ cnj: couldNotJudge(
33832
+ id,
33833
+ anchor,
33834
+ `tools/list was read on ${paging.pages} page(s) only, cursor ${JSON.stringify(paging.unreadCursor)} left unread: ${paging.reason}; the tools on the unread pages are not judged (${rule})`
33835
+ )
33836
+ };
33837
+ return { calls: runtime.served.toolCalls, tools: runtime.tools, anchor };
33838
+ }
33839
+ function noSuccessReason(c) {
33840
+ if (!c) return "no tools/call record for it in this run";
33841
+ if (c.kind === "not-sent") return `no call sent: ${c.reason}`;
33842
+ if (c.kind === "no-answer") return `the call got no answer: ${c.reason}`;
33843
+ if (c.kind === "error")
33844
+ return `the call answered a JSON-RPC error ${String(c.code)}${c.message ? ` ${c.message}` : ""}`;
33845
+ if (c.isError) return "the call answered an execution error (isError: true), not a success";
33846
+ return void 0;
33847
+ }
33848
+ function names(list, max = 400) {
33849
+ return list.length <= max ? list.join(", ") : `${list.slice(0, max).join(", ")}, ... and ${list.length - max} more`;
33850
+ }
33851
+
33852
+ // src/detectors/s51-served-output.ts
33853
+ var ID17 = "S51 served-output";
33854
+ var RULE17 = "S-51";
33855
+ var isNullish = (e) => {
33856
+ let x = e;
33857
+ while (ts2.isParenthesizedExpression(x) || ts2.isAsExpression(x)) x = x.expression;
33858
+ return x.kind === ts2.SyntaxKind.NullKeyword || ts2.isIdentifier(x) && x.text === "undefined" || ts2.isVoidExpression(x);
33859
+ };
33860
+ var strip = (e) => {
33861
+ let x = e;
33862
+ while (ts2.isParenthesizedExpression(x) || ts2.isAsExpression(x) || ts2.isSatisfiesExpression(x))
33863
+ x = x.expression;
33864
+ return x;
33865
+ };
33866
+ var isOutputKey = (n) => (ts2.isIdentifier(n) || ts2.isStringLiteralLike(n)) && n.text === "outputSchema";
33867
+ var objectHasOutput = (e) => {
33868
+ const x = strip(e);
33869
+ return ts2.isObjectLiteralExpression(x) && x.properties.some(
33870
+ (p) => (ts2.isPropertyAssignment(p) || ts2.isShorthandPropertyAssignment(p)) && isOutputKey(p.name)
33871
+ );
33872
+ };
33873
+ var LOGICAL = /* @__PURE__ */ new Set([
33874
+ ts2.SyntaxKind.AmpersandAmpersandToken,
33875
+ ts2.SyntaxKind.BarBarToken,
33876
+ ts2.SyntaxKind.QuestionQuestionToken
33877
+ ]);
33878
+ function branches(e) {
33879
+ const x = strip(e);
33880
+ if (ts2.isConditionalExpression(x)) return [x.whenTrue, x.whenFalse];
33881
+ if (ts2.isBinaryExpression(x) && LOGICAL.has(x.operatorToken.kind)) {
33882
+ if (x.operatorToken.kind === ts2.SyntaxKind.AmpersandAmpersandToken)
33883
+ return [ts2.factory.createIdentifier("undefined"), x.right];
33884
+ return [x.left, x.right];
33885
+ }
33886
+ return void 0;
33887
+ }
33888
+ var accessesOutput = (n) => ts2.isPropertyAccessExpression(n) && n.name.text === "outputSchema" || ts2.isElementAccessExpression(n) && ts2.isStringLiteralLike(n.argumentExpression) && n.argumentExpression.text === "outputSchema";
33889
+ function underCondition(n) {
33890
+ for (let x = n.parent; x && !ts2.isFunctionLike(x) && !ts2.isSourceFile(x); x = x.parent) {
33891
+ if (ts2.isIfStatement(x) || ts2.isConditionalExpression(x)) return true;
33892
+ if (ts2.isBinaryExpression(x) && LOGICAL.has(x.operatorToken.kind)) return true;
33893
+ }
33894
+ return false;
33895
+ }
33896
+ function exemptionSites(sf, rel) {
33897
+ const out = [];
33898
+ const at = (n) => `${rel}:${sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1}`;
33899
+ const text = (n) => n.getText(sf).replace(/\s+/g, " ").slice(0, 120);
33900
+ const visit = (n) => {
33901
+ if (ts2.isSpreadAssignment(n)) {
33902
+ const b = branches(n.expression);
33903
+ if (b?.some(objectHasOutput) && !b.every(objectHasOutput))
33904
+ out.push({ anchor: at(n), form: "X1", text: text(n) });
33905
+ } else if (ts2.isPropertyAssignment(n) && isOutputKey(n.name)) {
33906
+ const b = branches(n.initializer);
33907
+ if (isNullish(n.initializer) || b?.some(isNullish))
33908
+ out.push({ anchor: at(n), form: "X2", text: text(n) });
33909
+ } else if (ts2.isBinaryExpression(n) && n.operatorToken.kind === ts2.SyntaxKind.EqualsToken && accessesOutput(n.left) && (underCondition(n) || isNullish(n.right) || branches(n.right)?.some(isNullish))) {
33910
+ out.push({ anchor: at(n), form: "X3", text: text(n) });
33911
+ } else if (ts2.isDeleteExpression(n) && accessesOutput(strip(n.expression))) {
33912
+ out.push({ anchor: at(n), form: "X3", text: text(n) });
33913
+ }
33914
+ ts2.forEachChild(n, visit);
33915
+ };
33916
+ visit(sf);
33917
+ return out;
33918
+ }
33919
+ function s51Controls() {
33920
+ const sf = (code) => ts2.createSourceFile("c.ts", code, ts2.ScriptTarget.Latest, true, ts2.ScriptKind.TS);
33921
+ const red = [
33922
+ "f({ ...(s !== undefined ? { outputSchema: s } : {}) });",
33923
+ "f({ outputSchema: skip.has(n) ? undefined : s });",
33924
+ "if (!skip.has(n)) cfg.outputSchema = s;"
33925
+ ].map((c) => exemptionSites(sf(c), "c.ts").length);
33926
+ const green = exemptionSites(
33927
+ sf("f({ outputSchema: s, ...(c ? { title } : {}) });"),
33928
+ "c.ts"
33929
+ ).length;
33930
+ const v = schemaCheckControls();
33931
+ return {
33932
+ sees: red.every((n) => n === 1) && v.sees && v.refuses,
33933
+ spares: green === 0 && v.spares
33934
+ };
33935
+ }
33936
+ function runStatic5(tree) {
33937
+ const ctl = s51Controls();
33938
+ if (!ctl.sees || !ctl.spares)
33939
+ throw new Error(
33940
+ `S51 positive control FAILED: ${JSON.stringify(ctl)} \u2014 reader broken, verdict untrustworthy`
33941
+ );
33942
+ const { tools, unresolved } = productRegistrations(tree);
33943
+ if (tools.length === 0) {
33944
+ const surface = toolSurfaceAnchor(tree);
33945
+ if (surface || unresolved.length > 0)
33946
+ return couldNotJudge(
33947
+ ID17,
33948
+ surface ?? unresolved[0],
33949
+ noToolsLocatedReason(tree, `no registration was read (${RULE17})`)
33950
+ );
33951
+ return {
33952
+ id: ID17,
33953
+ anchor: tree.root,
33954
+ state: "absent",
33955
+ verdict: `no MCP tool registered in product source \u2014 ${RULE17} n/a`
33956
+ };
33957
+ }
33958
+ const unread2 = unresolved.map((a) => ({
33959
+ anchor: a,
33960
+ reason: `a tool registered here has a name the scan cannot resolve, so whether it declares an output schema is unread (${RULE17})`
33961
+ }));
33962
+ const missing = [];
33963
+ const declared = [];
33964
+ for (const t of tools) {
33965
+ const r = closedOutputSites(tree, t.name, t.anchor);
33966
+ if (r.kind === "none") missing.push(`${t.name} (${t.anchor})`);
33967
+ else {
33968
+ const loc = r.sites.find(
33969
+ (s) => s.path === t.name && s.kind === "unread" && /^registration/.test(s.form)
33970
+ );
33971
+ if (loc) unread2.push({ anchor: loc.anchor, reason: `${loc.form} (${RULE17})` });
33972
+ else declared.push(t.name);
33973
+ }
33974
+ }
33975
+ const exemptions = [];
33976
+ for (const f of tree.files)
33977
+ if (isProductSource(f.rel)) exemptions.push(...exemptionSites(sourceFileOf(f), f.rel));
33978
+ if (missing.length > 0 || exemptions.length > 0) {
33979
+ const parts = [];
33980
+ if (exemptions.length > 0)
33981
+ parts.push(
33982
+ `${exemptions.length} exemption mechanism(s) that skip the output schema for some registrations: ${exemptions.map((e) => `${e.anchor} ${e.form} \`${e.text}\``).join("; ")}`
33983
+ );
33984
+ if (missing.length > 0)
33985
+ parts.push(
33986
+ `${missing.length} of ${tools.length} registered tool(s) declare no outputSchema: ${names(missing)}`
33987
+ );
33988
+ return settle(
33989
+ ID17,
33990
+ {
33991
+ id: ID17,
33992
+ anchor: exemptions[0]?.anchor ?? missing[0].replace(/^.* \((.*)\)$/, "$1"),
33993
+ state: "non-conforming",
33994
+ verdict: `${parts.join("; ")} \u2014 every served tool carries an outputSchema and no code path exempts one (${RULE17})`
33995
+ },
33996
+ unread2
33997
+ );
33998
+ }
33999
+ return settle(
34000
+ ID17,
34001
+ couldNotJudge(
34002
+ ID17,
34003
+ tools[0].anchor,
34004
+ `static half: ${declared.length} registered tool(s) declare an outputSchema and no exemption mechanism (X1..X3) is in the registration code; unread by a static run: whether each served result's structuredContent validates against it (${names(declared)}) \u2014 run --mode=dynamic (${RULE17})`
34005
+ ),
34006
+ unread2
34007
+ );
34008
+ }
34009
+ function runServedHalf3(runtime) {
34010
+ const got = servedToolCalls(ID17, RULE17, runtime);
34011
+ if ("cnj" in got) return got.cnj;
34012
+ const { calls, tools, anchor } = got;
34013
+ if (tools.length === 0)
34014
+ return { id: ID17, anchor, state: "absent", verdict: `the server serves no tool \u2014 ${RULE17} n/a` };
34015
+ const noSchema = tools.filter((t) => t.outputSchema === void 0).map((t) => t.name);
34016
+ const invalid = [];
34017
+ const unread2 = [];
34018
+ let validated = 0;
34019
+ for (const t of tools) {
34020
+ if (t.outputSchema === void 0) continue;
34021
+ const c = calls.find((x) => x.tool === t.name);
34022
+ const why = noSuccessReason(c);
34023
+ if (why || !c || c.kind !== "result") {
34024
+ unread2.push({
34025
+ anchor: `${anchor} tools/call ${t.name}`,
34026
+ reason: `${t.name}: ${why} (${RULE17})`
34027
+ });
34028
+ continue;
34029
+ }
34030
+ if (!c.hasStructured || c.structuredContent === void 0) {
34031
+ invalid.push(
34032
+ `${t.name}: a successful result with no structuredContent under its outputSchema`
34033
+ );
34034
+ continue;
34035
+ }
34036
+ const v = checkSchema(t.outputSchema, c.structuredContent);
34037
+ if (v.kind === "invalid") invalid.push(`${t.name}: structuredContent ${v.path} \u2014 ${v.why}`);
34038
+ else if (v.kind === "unread")
34039
+ unread2.push({
34040
+ anchor: `${anchor} tools/list ${t.name}`,
34041
+ reason: `${t.name}: the outputSchema could not be read at ${v.path} \u2014 ${v.why} (${RULE17})`
34042
+ });
34043
+ else validated++;
34044
+ }
34045
+ if (noSchema.length > 0 || invalid.length > 0) {
34046
+ const parts = [];
34047
+ if (noSchema.length > 0)
34048
+ parts.push(
34049
+ `${noSchema.length} of ${tools.length} served tool(s) carry no outputSchema: ${names(noSchema)}`
34050
+ );
34051
+ if (invalid.length > 0)
34052
+ parts.push(`${invalid.length} served result(s) do not validate: ${invalid.join("; ")}`);
34053
+ return settle(
34054
+ ID17,
34055
+ { id: ID17, anchor, state: "non-conforming", verdict: `${parts.join("; ")} (${RULE17})` },
34056
+ unread2
34057
+ );
34058
+ }
34059
+ return settle(
34060
+ ID17,
34061
+ {
34062
+ id: ID17,
34063
+ anchor,
34064
+ state: "present",
34065
+ verdict: `${tools.length} served tool(s) declare an outputSchema; ${validated} successful result(s) read, each structuredContent valid against it (${RULE17})`
34066
+ },
34067
+ unread2
34068
+ );
34069
+ }
34070
+ var s51ServedOutput = {
34071
+ id: ID17,
34072
+ rule: RULE17,
34073
+ pin: S51_RULES_PIN,
34074
+ run: runStatic5,
34075
+ runServed: (runtime) => runServedHalf3(runtime)
34076
+ };
34077
+
34078
+ // src/detectors/s52-no-null-success.ts
34079
+ import * as ts3 from "typescript";
34080
+ var ID18 = "S52 no-null-success";
34081
+ var RULE18 = "S-52";
34082
+ function nullReturns(tool, read) {
34083
+ const red = [];
34084
+ const unread2 = [];
34085
+ for (const r of read.returns) {
34086
+ if (r.inCatch) continue;
34087
+ if (r.form === "bare-return" || r.form === "fall-through") {
34088
+ red.push({
34089
+ tool,
34090
+ anchor: r.anchor,
34091
+ form: r.form === "bare-return" ? "N1 bare `return;`" : "N1 the handler falls off its end (answers undefined)"
34092
+ });
34093
+ continue;
34094
+ }
34095
+ for (const v of returnedValues(r.expr, read.sf)) {
34096
+ if (v.kind === "nullish") red.push({ tool, anchor: r.anchor, form: `N1 returns ${v.form}` });
34097
+ else if (v.kind === "unread")
34098
+ unread2.push({
34099
+ anchor: r.anchor,
34100
+ reason: `${tool}: the returned value is ${v.form} (${RULE18})`
34101
+ });
34102
+ else {
34103
+ if (isErrorObject(v.node)) continue;
34104
+ const sc = prop(v.node, "structuredContent");
34105
+ if (sc.kind === "value") {
34106
+ const x = sc.value;
34107
+ if (x.kind === ts3.SyntaxKind.NullKeyword || ts3.isIdentifier(x) && x.text === "undefined")
34108
+ red.push({ tool, anchor: r.anchor, form: "N2 `structuredContent: null`" });
34109
+ else if (ts3.isObjectLiteralExpression(x) && x.properties.length === 0)
34110
+ red.push({ tool, anchor: r.anchor, form: "N4 `structuredContent: {}`" });
34111
+ }
34112
+ const content = prop(v.node, "content");
34113
+ if (content.kind === "value" && ts3.isArrayLiteralExpression(content.value) && content.value.elements.length === 0)
34114
+ red.push({ tool, anchor: r.anchor, form: "N5 `content: []`" });
34115
+ else if (content.kind === "absent")
34116
+ red.push({ tool, anchor: r.anchor, form: "N5 a result with no `content`" });
34117
+ }
34118
+ }
34119
+ }
34120
+ return { red, unread: unread2 };
34121
+ }
34122
+ function servedNullForm(c, hasSchema) {
34123
+ if (c.hasStructured && c.structuredContent === null) return "N2 structuredContent is null";
34124
+ if (hasSchema && (!c.hasStructured || c.structuredContent === void 0))
34125
+ return "N3 structuredContent absent under a declared outputSchema";
34126
+ const sc = c.structuredContent;
34127
+ if (typeof sc === "object" && sc !== null && !Array.isArray(sc) && Object.keys(sc).length === 0)
34128
+ return "N4 structuredContent is {}";
34129
+ if (c.contentKind !== "array")
34130
+ return `N5 content is ${c.contentKind === "absent" ? "absent" : "not an array"}`;
34131
+ if (c.content.length === 0) return "N5 content is []";
34132
+ const texts2 = c.content.filter((b) => b.type === "text");
34133
+ if (texts2.length === c.content.length && texts2.every((b) => ["", "null", "undefined", "{}"].includes((b.text ?? "").trim())))
34134
+ return `N6 the text answers ${JSON.stringify((texts2[0].text ?? "").trim())}`;
34135
+ return void 0;
34136
+ }
34137
+ function runStatic6(tree) {
34138
+ const { tools, unresolved } = productRegistrations(tree);
34139
+ if (tools.length === 0) {
34140
+ const surface = toolSurfaceAnchor(tree);
34141
+ if (surface || unresolved.length > 0)
34142
+ return couldNotJudge(
34143
+ ID18,
34144
+ surface ?? unresolved[0],
34145
+ noToolsLocatedReason(tree, `no handler was read (${RULE18})`)
34146
+ );
34147
+ return {
34148
+ id: ID18,
34149
+ anchor: tree.root,
34150
+ state: "absent",
34151
+ verdict: `no MCP tool registered in product source \u2014 ${RULE18} n/a`
34152
+ };
34153
+ }
34154
+ const red = [];
34155
+ const unread2 = unresolved.map((a) => ({
34156
+ anchor: a,
34157
+ reason: `a tool registered here has a name the scan cannot resolve, so its handler is unread (${RULE18})`
34158
+ }));
34159
+ const read = [];
34160
+ for (const t of tools) {
34161
+ const h = readHandler(tree, t);
34162
+ if (h.kind === "unread") {
34163
+ unread2.push({ anchor: h.anchor, reason: `${h.reason} (${RULE18})` });
34164
+ continue;
34165
+ }
34166
+ read.push(t.name);
34167
+ const r = nullReturns(t.name, h);
34168
+ red.push(...r.red);
34169
+ unread2.push(...r.unread);
34170
+ }
34171
+ if (red.length > 0)
34172
+ return settle(
34173
+ ID18,
34174
+ {
34175
+ id: ID18,
34176
+ anchor: red[0].anchor,
34177
+ state: "non-conforming",
34178
+ verdict: `${red.length} success-path return(s) answer null or empty: ${red.map((f) => `${f.tool} ${f.form} (${f.anchor})`).join("; ")} \u2014 a tool that found nothing returns a typed empty value (${RULE18})`
34179
+ },
34180
+ unread2
34181
+ );
34182
+ return settle(
34183
+ ID18,
34184
+ couldNotJudge(
34185
+ ID18,
34186
+ tools[0].anchor,
34187
+ `static half: no success-path return writes null or empty in the ${read.length} handler(s) read (${names(read)}); unread by a static run: what each returned expression evaluates to \u2014 run --mode=dynamic (${RULE18})`
34188
+ ),
34189
+ unread2
34190
+ );
34191
+ }
34192
+ function runServedHalf4(runtime) {
34193
+ const got = servedToolCalls(ID18, RULE18, runtime);
34194
+ if ("cnj" in got) return got.cnj;
34195
+ const { calls, anchor } = got;
34196
+ if (runtime.tools.length === 0)
34197
+ return { id: ID18, anchor, state: "absent", verdict: `the server serves no tool \u2014 ${RULE18} n/a` };
34198
+ const red = [];
34199
+ const unread2 = [];
34200
+ let ok = 0;
34201
+ for (const t of runtime.tools) {
34202
+ const c = calls.find((x) => x.tool === t.name);
34203
+ const why = noSuccessReason(c);
34204
+ if (why || !c || c.kind !== "result") {
34205
+ unread2.push({
34206
+ anchor: `${anchor} tools/call ${t.name}`,
34207
+ reason: `${t.name}: ${why} (${RULE18})`
34208
+ });
34209
+ continue;
34210
+ }
34211
+ const form = servedNullForm(c, t.outputSchema !== void 0);
34212
+ if (form) red.push(`${t.name}: ${form}`);
34213
+ else ok++;
34214
+ }
34215
+ if (red.length > 0)
34216
+ return settle(
34217
+ ID18,
34218
+ {
34219
+ id: ID18,
34220
+ anchor,
34221
+ state: "non-conforming",
34222
+ verdict: `${red.length} successful result(s) answer null or empty: ${red.join("; ")} (${RULE18})`
34223
+ },
34224
+ unread2
34225
+ );
34226
+ return settle(
34227
+ ID18,
34228
+ {
34229
+ id: ID18,
34230
+ anchor,
34231
+ state: "present",
34232
+ verdict: `${ok} successful result(s) read, each carrying a typed value (${RULE18})`
34233
+ },
34234
+ unread2
34235
+ );
34236
+ }
34237
+ var s52NoNullSuccess = {
34238
+ id: ID18,
34239
+ rule: RULE18,
34240
+ pin: S51_RULES_PIN,
34241
+ run: runStatic6,
34242
+ runServed: (runtime) => runServedHalf4(runtime)
34243
+ };
34244
+
34245
+ // src/detectors/s53-structured-not-text.ts
34246
+ import * as ts4 from "typescript";
34247
+ var ID19 = "S53 structured-not-text";
34248
+ var RULE19 = "S-53";
34249
+ function classifyTextExpr(e, sf, depth = 0) {
34250
+ let x = e;
34251
+ while (ts4.isParenthesizedExpression(x) || ts4.isAsExpression(x)) x = x.expression;
34252
+ if (ts4.isStringLiteral(x) || ts4.isNoSubstitutionTemplateLiteral(x)) return { kind: "none" };
34253
+ const t = x.getText(sf);
34254
+ if (ts4.isCallExpression(x) && /^JSON\s*\.\s*stringify$/.test(x.expression.getText(sf)))
34255
+ return { kind: "data", form: "T1 JSON.stringify(...) in the text" };
34256
+ if (ts4.isTemplateExpression(x) || ts4.isBinaryExpression(x) && x.operatorToken.kind === ts4.SyntaxKind.PlusToken) {
34257
+ if (/\bJSON\s*\.\s*stringify\s*\(/.test(t))
34258
+ return { kind: "data", form: "T2 a serialized value inside the text" };
34259
+ if (/\.\s*(join|map)\s*\(/.test(t))
34260
+ return { kind: "data", form: "T2 a list joined into the text" };
34261
+ if (/\.\s*length\b/.test(t))
34262
+ return { kind: "data", form: "T2 a count interpolated into the text" };
34263
+ const spans = ts4.isTemplateExpression(x) ? x.templateSpans.map((sp) => sp.expression) : [x.left, x.right];
34264
+ const idSpan = spans.find(
34265
+ (sp) => /(?:^|\.)id$|[a-z0-9](?:Id|Ids|ID)$/.test(sp.getText(sf).trim())
34266
+ );
34267
+ if (idSpan)
34268
+ return {
34269
+ kind: "data",
34270
+ form: `T2 an identifier interpolated into the text (${idSpan.getText(sf).trim()})`
34271
+ };
34272
+ if (ts4.isBinaryExpression(x)) {
34273
+ const parts = [classifyTextExpr(x.left, sf, depth), classifyTextExpr(x.right, sf, depth)];
34274
+ return parts.find((p) => p.kind === "data") ?? parts.find((p) => p.kind === "unread") ?? { kind: "none" };
34275
+ }
34276
+ return {
34277
+ kind: "unread",
34278
+ form: `a template with interpolated values \`${t.replace(/\s+/g, " ").slice(0, 60)}\``
34279
+ };
34280
+ }
34281
+ if (ts4.isCallExpression(x) && /\.\s*join$/.test(x.expression.getText(sf)))
34282
+ return { kind: "data", form: "T2 a list joined into the text" };
34283
+ if (ts4.isConditionalExpression(x)) {
34284
+ const parts = [
34285
+ classifyTextExpr(x.whenTrue, sf, depth),
34286
+ classifyTextExpr(x.whenFalse, sf, depth)
34287
+ ];
34288
+ return parts.find((p) => p.kind === "data") ?? parts.find((p) => p.kind === "unread") ?? { kind: "none" };
34289
+ }
34290
+ if (ts4.isIdentifier(x) && depth < 2) {
34291
+ const init = constInit(x);
34292
+ if (init) return classifyTextExpr(init, sf, depth + 1);
34293
+ }
34294
+ return { kind: "unread", form: `text \`${t.replace(/\s+/g, " ").slice(0, 60)}\`` };
34295
+ }
34296
+ function constInit(id) {
34297
+ for (let p = id.parent; p; p = p.parent) {
34298
+ if (!(ts4.isBlock(p) || ts4.isSourceFile(p))) continue;
34299
+ for (const st of p.statements) {
34300
+ if (!ts4.isVariableStatement(st) || !(st.declarationList.flags & ts4.NodeFlags.Const)) continue;
34301
+ for (const d of st.declarationList.declarations)
34302
+ if (ts4.isIdentifier(d.name) && d.name.text === id.text && d.initializer && d.getStart() < id.getStart())
34303
+ return d.initializer;
34304
+ }
34305
+ }
34306
+ return void 0;
34307
+ }
34308
+ function textOnlyReturn(obj, sf) {
34309
+ const content = prop(obj, "content");
34310
+ if (content.kind === "absent") return { kind: "none" };
34311
+ if (content.kind !== "value" || !ts4.isArrayLiteralExpression(content.value))
34312
+ return { kind: "unread", form: "a `content` that is not an array literal" };
34313
+ const out = [];
34314
+ for (const el of content.value.elements) {
34315
+ if (!ts4.isObjectLiteralExpression(el)) {
34316
+ out.push({ kind: "unread", form: "a content block that is not an object literal" });
34317
+ continue;
34318
+ }
34319
+ const text = prop(el, "text");
34320
+ if (text.kind === "value") out.push(classifyTextExpr(text.value, sf));
34321
+ else if (text.kind === "shorthand") out.push(classifyTextExpr(text.ident, sf));
34322
+ else if (text.kind === "spread")
34323
+ out.push({ kind: "unread", form: "a content block built with a spread" });
34324
+ }
34325
+ return out.find((p) => p.kind === "data") ?? out.find((p) => p.kind === "unread") ?? { kind: "none" };
34326
+ }
34327
+ function runStatic7(tree) {
34328
+ const { tools, unresolved } = productRegistrations(tree);
34329
+ if (tools.length === 0) {
34330
+ const surface = toolSurfaceAnchor(tree);
34331
+ if (surface || unresolved.length > 0)
34332
+ return couldNotJudge(
34333
+ ID19,
34334
+ surface ?? unresolved[0],
34335
+ noToolsLocatedReason(tree, `no handler was read (${RULE19})`)
34336
+ );
34337
+ return {
34338
+ id: ID19,
34339
+ anchor: tree.root,
34340
+ state: "absent",
34341
+ verdict: `no MCP tool registered in product source \u2014 ${RULE19} n/a`
34342
+ };
34343
+ }
34344
+ const red = [];
34345
+ const unread2 = unresolved.map((a) => ({
34346
+ anchor: a,
34347
+ reason: `a tool registered here has a name the scan cannot resolve, so its handler is unread (${RULE19})`
34348
+ }));
34349
+ const read = [];
34350
+ let firstRed = "";
34351
+ for (const t of tools) {
34352
+ const h = readHandler(tree, t);
34353
+ if (h.kind === "unread") {
34354
+ unread2.push({ anchor: h.anchor, reason: `${h.reason} (${RULE19})` });
34355
+ continue;
34356
+ }
34357
+ read.push(t.name);
34358
+ for (const r of h.returns) {
34359
+ if (r.inCatch || !r.expr) continue;
34360
+ for (const v of returnedValues(r.expr, h.sf)) {
34361
+ if (v.kind !== "object") {
34362
+ if (v.kind === "unread")
34363
+ unread2.push({
34364
+ anchor: r.anchor,
34365
+ reason: `${t.name}: the returned value is ${v.form} (${RULE19})`
34366
+ });
34367
+ continue;
34368
+ }
34369
+ if (isErrorObject(v.node)) continue;
34370
+ const sc = prop(v.node, "structuredContent");
34371
+ if (sc.kind === "spread") {
34372
+ unread2.push({
34373
+ anchor: r.anchor,
34374
+ reason: `${t.name}: a result object built with a spread, structuredContent unread (${RULE19})`
34375
+ });
34376
+ continue;
34377
+ }
34378
+ if (sc.kind !== "absent") continue;
34379
+ const c = textOnlyReturn(v.node, h.sf);
34380
+ if (c.kind === "data") {
34381
+ red.push(`${t.name} ${c.form}, no structuredContent (${r.anchor})`);
34382
+ firstRed ||= r.anchor;
34383
+ } else if (c.kind === "unread")
34384
+ unread2.push({ anchor: r.anchor, reason: `${t.name}: ${c.form} (${RULE19})` });
34385
+ }
34386
+ }
34387
+ }
34388
+ if (red.length > 0)
34389
+ return settle(
34390
+ ID19,
34391
+ {
34392
+ id: ID19,
34393
+ anchor: firstRed,
34394
+ state: "non-conforming",
34395
+ verdict: `${red.length} success-path return(s) carry data in the text only: ${red.join("; ")} \u2014 return it as structuredContent under the outputSchema, the text being its serialization (${RULE19})`
34396
+ },
34397
+ unread2
34398
+ );
34399
+ return settle(
34400
+ ID19,
34401
+ couldNotJudge(
34402
+ ID19,
34403
+ tools[0].anchor,
34404
+ `static half: no text-only return carrying data in the ${read.length} handler(s) read (${names(read)}); unread by a static run: whether each served text is the serialization of its structuredContent \u2014 run --mode=dynamic (${RULE19})`
34405
+ ),
34406
+ unread2
34407
+ );
34408
+ }
34409
+ var UUID = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i;
34410
+ var TOKEN = /\b(?=[A-Za-z0-9_]*[A-Za-z])(?=[A-Za-z0-9_]*\d)[A-Za-z0-9_]{16,}\b/;
34411
+ var COUNT = /(?<![\w.])\d+\s+[A-Za-z]{2,}/;
34412
+ var LIST_LINE = /^\s*(?:[-*•]\s+\S|\d+[.)]\s+\S|[A-Za-z_][\w ]{0,40}:\s+\S)/;
34413
+ var INLINE_ITEM = /^[\p{L}\p{N}_.@'+-]+$/u;
34414
+ var isInlineList = (text) => {
34415
+ const t = text.trim();
34416
+ if (t.includes("\n")) return false;
34417
+ const items = t.split(/\s*[,;]\s*/);
34418
+ return items.length >= 3 && items.every((i) => INLINE_ITEM.test(i));
34419
+ };
34420
+ function leadingJson(text) {
34421
+ const t = text.trim();
34422
+ if (!/^[[{]/.test(t)) {
34423
+ try {
34424
+ const v = JSON.parse(t);
34425
+ return typeof v === "object" && v !== null ? { value: v } : void 0;
34426
+ } catch {
34427
+ return void 0;
34428
+ }
34429
+ }
34430
+ const close2 = t[0] === "{" ? "}" : "]";
34431
+ let end = t.length;
34432
+ while (end > 0) {
34433
+ try {
34434
+ return { value: JSON.parse(t.slice(0, end)) };
34435
+ } catch {
34436
+ }
34437
+ const k = t.lastIndexOf(close2, end - 2);
34438
+ if (k < 0) break;
34439
+ end = k + 1;
34440
+ }
34441
+ return void 0;
34442
+ }
34443
+ function classifyServedText(text) {
34444
+ const j = leadingJson(text);
34445
+ if (j) return { kind: "data", form: "J the text is JSON", json: j.value };
34446
+ const lines2 = text.split("\n").filter((l) => l.trim() !== "");
34447
+ if (lines2.filter((l) => LIST_LINE.test(l)).length >= 2)
34448
+ return { kind: "data", form: "L the text is a list" };
34449
+ if (isInlineList(text)) return { kind: "data", form: "L the text is an inline list" };
34450
+ const id = text.match(UUID) ?? text.match(TOKEN);
34451
+ if (id) return { kind: "data", form: `I the text names identifier ${id[0]}` };
34452
+ const count = text.match(COUNT);
34453
+ if (count) return { kind: "data", form: `C the text states a count (${count[0]})` };
34454
+ if (!/\d/.test(text)) return { kind: "prose" };
34455
+ return { kind: "unclassifiable" };
34456
+ }
34457
+ var hasData = (sc) => sc !== void 0 && sc !== null && !(typeof sc === "object" && !Array.isArray(sc) && Object.keys(sc).length === 0);
34458
+ function servedTextForm(c) {
34459
+ const texts2 = c.content.filter((b) => b.type === "text" && typeof b.text === "string");
34460
+ const structured = hasData(c.structuredContent);
34461
+ for (const b of texts2) {
34462
+ const text = b.text;
34463
+ const k = classifyServedText(text);
34464
+ if (!structured) {
34465
+ if (k.kind === "data")
34466
+ return { kind: "red", form: `${k.form} and structuredContent carries no data` };
34467
+ if (k.kind === "unclassifiable")
34468
+ return {
34469
+ kind: "unread",
34470
+ form: `a text that is neither JSON, a list, an identifier nor prose: ${JSON.stringify(text.slice(0, 80))}`
34471
+ };
34472
+ continue;
34473
+ }
34474
+ if (k.kind === "data" && "json" in k && k.json !== void 0) {
34475
+ if (b.truncated)
34476
+ return {
34477
+ kind: "unread",
34478
+ form: "the text was cut at the recording cap, so its serialization cannot be compared whole"
34479
+ };
34480
+ if (!jsonEqual(k.json, c.structuredContent) && !JSON.stringify(c.structuredContent).includes(JSON.stringify(k.json)))
34481
+ return {
34482
+ kind: "red",
34483
+ form: "the text carries JSON that is not the serialization of structuredContent"
34484
+ };
34485
+ continue;
34486
+ }
34487
+ const flat = JSON.stringify(c.structuredContent);
34488
+ const tokens = [
34489
+ ...text.match(new RegExp(UUID.source, "gi")) ?? [],
34490
+ ...text.match(new RegExp(TOKEN.source, "g")) ?? []
34491
+ ];
34492
+ const lacked = tokens.find((tk) => !flat.includes(tk));
34493
+ if (lacked)
34494
+ return { kind: "red", form: `the text names ${lacked}, which structuredContent lacks` };
34495
+ }
34496
+ return { kind: "green" };
34497
+ }
34498
+ function runServedHalf5(runtime) {
34499
+ const got = servedToolCalls(ID19, RULE19, runtime);
34500
+ if ("cnj" in got) return got.cnj;
34501
+ const { calls, anchor } = got;
34502
+ if (runtime.tools.length === 0)
34503
+ return { id: ID19, anchor, state: "absent", verdict: `the server serves no tool \u2014 ${RULE19} n/a` };
34504
+ const red = [];
34505
+ const unread2 = [];
34506
+ let ok = 0;
34507
+ for (const t of runtime.tools) {
34508
+ const c = calls.find((x) => x.tool === t.name);
34509
+ const why = noSuccessReason(c);
34510
+ if (why || !c || c.kind !== "result") {
34511
+ unread2.push({
34512
+ anchor: `${anchor} tools/call ${t.name}`,
34513
+ reason: `${t.name}: ${why} (${RULE19})`
34514
+ });
34515
+ continue;
34516
+ }
34517
+ const v = servedTextForm(c);
34518
+ if (v.kind === "red") red.push(`${t.name}: ${v.form}`);
34519
+ else if (v.kind === "unread")
34520
+ unread2.push({
34521
+ anchor: `${anchor} tools/call ${t.name}`,
34522
+ reason: `${t.name}: ${v.form} (${RULE19})`
34523
+ });
34524
+ else ok++;
34525
+ }
34526
+ if (red.length > 0)
34527
+ return settle(
34528
+ ID19,
34529
+ {
34530
+ id: ID19,
34531
+ anchor,
34532
+ state: "non-conforming",
34533
+ verdict: `${red.length} successful result(s) carry data in free text: ${red.join("; ")} (${RULE19})`
34534
+ },
34535
+ unread2
34536
+ );
34537
+ return settle(
34538
+ ID19,
34539
+ {
34540
+ id: ID19,
34541
+ anchor,
34542
+ state: "present",
34543
+ verdict: `${ok} successful result(s) read: data in structuredContent, text its serialization or summary (${RULE19})`
34544
+ },
34545
+ unread2
34546
+ );
34547
+ }
34548
+ var s53StructuredNotText = {
34549
+ id: ID19,
34550
+ rule: RULE19,
34551
+ pin: S51_RULES_PIN,
34552
+ run: runStatic7,
34553
+ runServed: (runtime) => runServedHalf5(runtime)
34554
+ };
34555
+
34556
+ // src/detectors/s54-tools-tested.ts
34557
+ import { readFileSync as readFileSync24, readdirSync as readdirSync17, statSync as statSync24 } from "fs";
34558
+ import { join as join35, relative as relative15, sep as sep7 } from "path";
34559
+ import * as ts5 from "typescript";
34560
+ var ID20 = "S54 tools-tested";
34561
+ var RULE20 = "S-54";
34562
+ var TEST_DIR = /(^|\/)(test|tests|__tests__|spec|specs|e2e)\//;
34563
+ var TEST_NAME = /\.(test|spec)\.[cm]?[jt]sx?$/;
34564
+ var CODE2 = /\.[cm]?[jt]sx?$/;
34565
+ var NOT_TESTS = /* @__PURE__ */ new Set([
34566
+ ...Object.keys(SKIP_DIR_INFO).filter((d) => !SKIP_DIR_INFO[d].authored),
34567
+ "fixtures"
34568
+ ]);
34569
+ function isTestFile(rel) {
34570
+ return CODE2.test(rel) && !/\.d\.[cm]?ts$/.test(rel) && (TEST_NAME.test(rel) || TEST_DIR.test(rel));
34571
+ }
34572
+ function testFiles2(root) {
34573
+ const files = [];
34574
+ const unread2 = [];
34575
+ const walk3 = (dir) => {
34576
+ let entries;
34577
+ try {
34578
+ entries = readdirSync17(dir);
34579
+ } catch (e) {
34580
+ unread2.push({
34581
+ anchor: relative15(root, dir) || ".",
34582
+ reason: `directory not listed (${e.message}) (${RULE20})`
34583
+ });
34584
+ return;
34585
+ }
34586
+ for (const name of entries) {
34587
+ const full = join35(dir, name);
34588
+ let st;
34589
+ try {
34590
+ st = statSync24(full);
34591
+ } catch (e) {
34592
+ unread2.push({
34593
+ anchor: relative15(root, full),
34594
+ reason: `not read (${e.message}) (${RULE20})`
34595
+ });
34596
+ continue;
34597
+ }
34598
+ if (st.isDirectory()) {
34599
+ if (!NOT_TESTS.has(name)) walk3(full);
34600
+ continue;
34601
+ }
34602
+ const rel = relative15(root, full).split(sep7).join("/");
34603
+ if (!st.isFile() || !isTestFile(rel)) continue;
34604
+ try {
34605
+ const text = readFileSync24(full, "utf8");
34606
+ const kind = /x$/.test(rel) ? ts5.ScriptKind.TSX : /\.[cm]?js$/.test(rel) ? ts5.ScriptKind.JS : ts5.ScriptKind.TS;
34607
+ files.push({ rel, sf: ts5.createSourceFile(rel, text, ts5.ScriptTarget.Latest, true, kind) });
34608
+ } catch (e) {
34609
+ unread2.push({
34610
+ anchor: rel,
34611
+ reason: `test file not read (${e.message}) (${RULE20})`
34612
+ });
34613
+ }
34614
+ }
34615
+ };
34616
+ walk3(root);
34617
+ return { files, unread: unread2 };
34618
+ }
34619
+ var up = (n) => {
34620
+ let x = n;
34621
+ while (x.parent && (ts5.isParenthesizedExpression(x.parent) || ts5.isAsExpression(x.parent) || ts5.isNonNullExpression(x.parent) || ts5.isAwaitExpression(x.parent) || ts5.isSatisfiesExpression(x.parent)))
34622
+ x = x.parent;
34623
+ return x;
34624
+ };
34625
+ var calleeName = (c) => {
34626
+ const e = c.expression;
34627
+ if (ts5.isIdentifier(e)) return e.text;
34628
+ if (ts5.isPropertyAccessExpression(e)) return e.name.text;
34629
+ return void 0;
34630
+ };
34631
+ var propName = (p) => p.name && (ts5.isIdentifier(p.name) || ts5.isStringLiteralLike(p.name)) ? p.name.text : void 0;
34632
+ function invoked(access) {
34633
+ const a = up(access);
34634
+ const p = a.parent;
34635
+ if (!p) return false;
34636
+ if (ts5.isCallExpression(p) && p.expression === a) return true;
34637
+ if (ts5.isPropertyAccessExpression(p) && p.expression === a && ["handler", "callback"].includes(p.name.text)) {
34638
+ const q = up(p).parent;
34639
+ return !!q && ts5.isCallExpression(q) && up(q.expression) === up(p);
34640
+ }
34641
+ if (ts5.isVariableDeclaration(p) && p.initializer && up(p.initializer) === a && ts5.isIdentifier(p.name)) {
34642
+ const bound = p.name.text;
34643
+ let scope2 = p;
34644
+ while (scope2.parent && !ts5.isBlock(scope2) && !ts5.isSourceFile(scope2)) scope2 = scope2.parent;
34645
+ let called = false;
34646
+ const visit = (n) => {
34647
+ if (called) return;
34648
+ if (ts5.isIdentifier(n) && n.text === bound && n !== p.name && invoked(n)) called = true;
34649
+ else ts5.forEachChild(n, visit);
34650
+ };
34651
+ visit(scope2);
34652
+ return called;
34653
+ }
34654
+ return false;
34655
+ }
34656
+ function callsAt(e, helpers) {
34657
+ const x = up(e);
34658
+ const p = x.parent;
34659
+ if (!p) return false;
34660
+ if (ts5.isPropertyAssignment(p) && p.initializer === x && propName(p) === "name" || ts5.isShorthandPropertyAssignment(p) && p.name === x && p.name.text === "name") {
34661
+ const obj = p.parent;
34662
+ const holder = up(obj).parent;
34663
+ if (holder && ts5.isCallExpression(holder) && holder.arguments.some((a) => up(a) === up(obj)) && calleeName(holder) === "callTool")
34664
+ return true;
34665
+ if (holder && ts5.isPropertyAssignment(holder) && propName(holder) === "params") {
34666
+ const req = holder.parent;
34667
+ return req.properties.some(
34668
+ (q) => ts5.isPropertyAssignment(q) && propName(q) === "method" && ts5.isStringLiteralLike(q.initializer) && q.initializer.text === "tools/call"
34669
+ );
34670
+ }
34671
+ return false;
34672
+ }
34673
+ if (ts5.isCallExpression(p) && p.arguments.some((a) => up(a) === x)) {
34674
+ const i = p.arguments.findIndex((a) => up(a) === x);
34675
+ if (calleeName(p) === "get" && i === 0 && ts5.isPropertyAccessExpression(p.expression))
34676
+ return invoked(p);
34677
+ const name = calleeName(p);
34678
+ return !!name && (helpers.get(name)?.has(i) ?? false);
34679
+ }
34680
+ if (ts5.isElementAccessExpression(p) && up(p.argumentExpression) === x) return invoked(p);
34681
+ return false;
34682
+ }
34683
+ function deriveHelpers(files) {
34684
+ const helpers = /* @__PURE__ */ new Map();
34685
+ const fns = [];
34686
+ for (const { sf } of files) {
34687
+ const visit = (n) => {
34688
+ if (ts5.isFunctionDeclaration(n) && n.name && n.body) fns.push({ name: n.name.text, fn: n });
34689
+ else if (ts5.isVariableDeclaration(n) && ts5.isIdentifier(n.name) && n.initializer && (ts5.isArrowFunction(n.initializer) || ts5.isFunctionExpression(n.initializer)))
34690
+ fns.push({ name: n.name.text, fn: n.initializer });
34691
+ ts5.forEachChild(n, visit);
34692
+ };
34693
+ visit(sf);
34694
+ }
34695
+ for (let round = 0; round < 5; round++) {
34696
+ let grew = false;
34697
+ for (const { name, fn } of fns) {
34698
+ fn.parameters.forEach((param, i) => {
34699
+ if (!ts5.isIdentifier(param.name) || helpers.get(name)?.has(i)) return;
34700
+ const pname = param.name.text;
34701
+ let hit = false;
34702
+ const visit = (n) => {
34703
+ if (hit) return;
34704
+ if (ts5.isIdentifier(n) && n.text === pname && n !== param.name && callsAt(n, helpers))
34705
+ hit = true;
34706
+ else ts5.forEachChild(n, visit);
34707
+ };
34708
+ if (fn.body) visit(fn.body);
34709
+ if (hit) {
34710
+ if (!helpers.has(name)) helpers.set(name, /* @__PURE__ */ new Set());
34711
+ helpers.get(name)?.add(i);
34712
+ grew = true;
34713
+ }
34714
+ });
34715
+ }
34716
+ if (!grew) break;
34717
+ }
34718
+ return helpers;
34719
+ }
34720
+ function testCalls(files, tools) {
34721
+ const helpers = deriveHelpers(files);
34722
+ const wanted = new Set(tools);
34723
+ const out = new Map(tools.map((t) => [t, []]));
34724
+ for (const { rel, sf } of files) {
34725
+ const visit = (n) => {
34726
+ if ((ts5.isStringLiteral(n) || ts5.isNoSubstitutionTemplateLiteral(n)) && wanted.has(n.text) && callsAt(n, helpers))
34727
+ out.get(n.text)?.push(`${rel}:${sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1}`);
34728
+ ts5.forEachChild(n, visit);
34729
+ };
34730
+ visit(sf);
34731
+ }
34732
+ return out;
34733
+ }
34734
+ function s54Controls() {
34735
+ const f = (code) => [
34736
+ {
34737
+ rel: "c.test.ts",
34738
+ sf: ts5.createSourceFile("c.test.ts", code, ts5.ScriptTarget.Latest, true, ts5.ScriptKind.TS)
34739
+ }
34740
+ ];
34741
+ const k = (code) => (testCalls(f(code), ["t"]).get("t") ?? []).length;
34742
+ return {
34743
+ sees: k('await client.callTool({ name: "t", arguments: {} });') === 1 && k('send({ method: "tools/call", params: { name: "t" } });') === 1 && k('tools.get("t")!({});') === 1 && k('function call(m, n) { return m.get(n)({}); }\ncall(tools, "t");') === 1,
34744
+ spares: k('expect(names).toContain("t");\nconst all = ["t"];') === 0
34745
+ };
34746
+ }
34747
+ function runStatic8(tree) {
34748
+ const ctl = s54Controls();
34749
+ if (!ctl.sees || !ctl.spares)
34750
+ throw new Error(
34751
+ `S54 positive control FAILED: ${JSON.stringify(ctl)} \u2014 reader broken, verdict untrustworthy`
34752
+ );
34753
+ const { tools, unresolved } = productRegistrations(tree);
34754
+ if (tools.length === 0) {
34755
+ const surface = toolSurfaceAnchor(tree);
34756
+ if (surface || unresolved.length > 0)
34757
+ return couldNotJudge(
34758
+ ID20,
34759
+ surface ?? unresolved[0],
34760
+ noToolsLocatedReason(tree, `no tool name was derived (${RULE20})`)
34761
+ );
34762
+ return {
34763
+ id: ID20,
34764
+ anchor: tree.root,
34765
+ state: "absent",
34766
+ verdict: `no MCP tool registered in product source \u2014 ${RULE20} n/a`
34767
+ };
34768
+ }
34769
+ let root = tree.root;
34770
+ try {
34771
+ if (!statSync24(root).isDirectory()) root = join35(root, "..");
34772
+ } catch {
34773
+ }
34774
+ const { files, unread: unread2 } = testFiles2(root);
34775
+ for (const a of unresolved)
34776
+ unread2.push({
34777
+ anchor: a,
34778
+ reason: `a tool registered here has a computed name, so whether a test calls it is unread (${RULE20})`
34779
+ });
34780
+ if (files.length === 0)
34781
+ return settle(
34782
+ ID20,
34783
+ couldNotJudge(
34784
+ ID20,
34785
+ tools[0].anchor,
34786
+ `no test file under ${root} (searched: *.test.* / *.spec.* and test/, tests/, __tests__/, spec/, specs/, e2e/ directories): a suite outside the scanned root is not read, so whether the ${tools.length} registered tool(s) are called is unread (${RULE20})`
34787
+ ),
34788
+ unread2
34789
+ );
34790
+ const calls = testCalls(
34791
+ files,
34792
+ tools.map((t) => t.name)
34793
+ );
34794
+ const untested = tools.filter((t) => (calls.get(t.name) ?? []).length === 0);
34795
+ if (untested.length > 0)
34796
+ return settle(
34797
+ ID20,
34798
+ {
34799
+ id: ID20,
34800
+ anchor: untested[0].anchor,
34801
+ state: "non-conforming",
34802
+ verdict: `${untested.length} of ${tools.length} registered tool(s) are called by no test (${files.length} test file(s) read under ${root}; call positions K1..K4): ${names(untested.map((t) => `${t.name} (${t.anchor})`))} (${RULE20})`
34803
+ },
34804
+ unread2
34805
+ );
34806
+ return settle(
34807
+ ID20,
34808
+ {
34809
+ id: ID20,
34810
+ anchor: tools[0].anchor,
34811
+ state: "present",
34812
+ verdict: `${tools.length} registered tool(s), each called by at least one test (${files.length} test file(s) read under ${root}) (${RULE20})`
34813
+ },
34814
+ unread2
34815
+ );
34816
+ }
34817
+ function runServedHalf6(runtime) {
34818
+ const anchor = `${runtime.root} (served)`;
34819
+ const why = runtime.remote ? `a URL scan has no repository: S-54 reads the repository's test files, which the served list does not carry (${RULE20})` : `the served tools/list does not say which tests call a tool: S-54 is read from the repository (static) (${RULE20})`;
34820
+ return couldNotJudge(
34821
+ ID20,
34822
+ anchor,
34823
+ runtime.launchError ? `${why}; and the server could not be started/introspected: ${runtime.launchError}` : why
34824
+ );
34825
+ }
34826
+ var s54ToolsTested = {
34827
+ id: ID20,
34828
+ rule: RULE20,
34829
+ pin: S51_RULES_PIN,
34830
+ run: runStatic8,
34831
+ runServed: (runtime) => runServedHalf6(runtime)
34832
+ };
34833
+
33131
34834
  // src/detectors/index.ts
33132
34835
  var registered = [
33133
34836
  d2,
@@ -33251,6 +34954,10 @@ var registered = [
33251
34954
  s42WriteReadClaims,
33252
34955
  s43UnionInput,
33253
34956
  s44ClosedOutput,
34957
+ s51ServedOutput,
34958
+ s52NoNullSuccess,
34959
+ s53StructuredNotText,
34960
+ s54ToolsTested,
33254
34961
  e5ExtensionIsolation,
33255
34962
  a3SandboxRespected,
33256
34963
  a4WcagGate,
@@ -33287,6 +34994,10 @@ var READS_CODE = /* @__PURE__ */ new Set([
33287
34994
  "S-42",
33288
34995
  "S-43",
33289
34996
  "S-44",
34997
+ "S-51",
34998
+ "S-52",
34999
+ "S-53",
35000
+ "S-54",
33290
35001
  "E-5",
33291
35002
  "A-3"
33292
35003
  ]);
@@ -33404,13 +35115,13 @@ function parseEventsArgs(args) {
33404
35115
  }
33405
35116
 
33406
35117
  // src/gate.ts
33407
- import { readFileSync as readFileSync24 } from "fs";
35118
+ import { readFileSync as readFileSync25 } from "fs";
33408
35119
  var OWED_FILE_NAME = "mcp-doctor.owed.json";
33409
35120
  var FORMAT = `expected {"owed": [{"id": "<detector id, the table's first column>", "reason": "<why this row may publish undecided>"}, ...]}`;
33410
35121
  function readOwedFile(path, opts) {
33411
35122
  let text;
33412
35123
  try {
33413
- text = readFileSync24(path, "utf8");
35124
+ text = readFileSync25(path, "utf8");
33414
35125
  } catch (err) {
33415
35126
  const code = err.code;
33416
35127
  if (code === "ENOENT" && !opts.explicit) return { kind: "none", path };
@@ -34099,7 +35810,7 @@ function selfSignedCert(commonName = "mcp-doctor events-ready receiver") {
34099
35810
  const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
34100
35811
  const name = seq(tlv(49, seq(CN, tlv(12, Buffer.from(commonName, "utf8")))));
34101
35812
  const serial = randomBytes(16);
34102
- serial[0] = serial[0] & 127;
35813
+ serial[0] = serial[0] & 63 | 64;
34103
35814
  const now = Date.now();
34104
35815
  const san = seq(
34105
35816
  tlv(135, Buffer.from([127, 0, 0, 1])),
@@ -34163,7 +35874,7 @@ var HEADERS2 = [
34163
35874
  "webhook-signature",
34164
35875
  "x-mcp-subscription-id"
34165
35876
  ];
34166
- var isObj4 = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
35877
+ var isObj5 = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
34167
35878
  function describe(o) {
34168
35879
  switch (o.kind) {
34169
35880
  case "result":
@@ -34178,7 +35889,7 @@ function describe(o) {
34178
35889
  }
34179
35890
  var isCode = (o, code) => o.kind === "error" && o.code === code;
34180
35891
  var authRefused = (o) => isCode(o, -32012) || o.kind === "http" && (o.status === 401 || o.status === 403);
34181
- var subId = (o) => o?.kind === "result" && isObj4(o.result) && typeof o.result.id === "string" ? o.result.id : void 0;
35892
+ var subId = (o) => o?.kind === "result" && isObj5(o.result) && typeof o.result.id === "string" ? o.result.id : void 0;
34182
35893
  var RpcClient = class {
34183
35894
  constructor(ep, timeoutMs) {
34184
35895
  this.ep = ep;
@@ -34245,10 +35956,10 @@ var RpcClient = class {
34245
35956
  reason: `HTTP ${res.status} body is not JSON-RPC (${e.message})`
34246
35957
  } : { kind: "http", status: res.status, raw: "" };
34247
35958
  }
34248
- const msg = messages.find((m) => isObj4(m) && m.id === id);
34249
- if (!isObj4(msg))
35959
+ const msg = messages.find((m) => isObj5(m) && m.id === id);
35960
+ if (!isObj5(msg))
34250
35961
  return res.ok ? { kind: "no-answer", reason: `HTTP ${res.status} carried no answer to request ${id}` } : { kind: "http", status: res.status, raw };
34251
- if (isObj4(msg.error)) {
35962
+ if (isObj5(msg.error)) {
34252
35963
  return {
34253
35964
  kind: "error",
34254
35965
  code: msg.error.code,
@@ -34281,7 +35992,7 @@ async function readSse(res, id) {
34281
35992
  if (data) {
34282
35993
  const m = JSON.parse(data);
34283
35994
  messages.push(m);
34284
- if (isObj4(m) && m.id === id) {
35995
+ if (isObj5(m) && m.id === id) {
34285
35996
  raw = data;
34286
35997
  await reader.cancel();
34287
35998
  return { messages, raw };
@@ -34295,7 +36006,7 @@ async function readSse(res, id) {
34295
36006
  function answer(role, hit, seen, redirectTarget, leakMarker) {
34296
36007
  if (role === "redirect") return { status: 307, headers: { location: redirectTarget } };
34297
36008
  if (hit.kind === "verification") {
34298
- const challenge = isObj4(hit.body) ? hit.body.challenge : void 0;
36009
+ const challenge = isObj5(hit.body) ? hit.body.challenge : void 0;
34299
36010
  if (role === "noecho") {
34300
36011
  return { status: 200, body: JSON.stringify({ challenge: leakMarker, note: leakMarker }) };
34301
36012
  }
@@ -34313,7 +36024,7 @@ function answer(role, hit, seen, redirectTarget, leakMarker) {
34313
36024
  return { status: 200 };
34314
36025
  }
34315
36026
  function eventIdOf(h) {
34316
- if (isObj4(h.body) && typeof h.body.eventId === "string") return h.body.eventId;
36027
+ if (isObj5(h.body) && typeof h.body.eventId === "string") return h.body.eventId;
34317
36028
  return h.headers["webhook-id"];
34318
36029
  }
34319
36030
  async function listen(cert, port, route) {
@@ -34331,7 +36042,7 @@ async function listen(cert, port, route) {
34331
36042
  let kind = "unreadable";
34332
36043
  try {
34333
36044
  body = JSON.parse(raw.toString("utf8"));
34334
- kind = isObj4(body) ? body.type === "verification" ? "verification" : "event" : "unreadable";
36045
+ kind = isObj5(body) ? body.type === "verification" ? "verification" : "event" : "unreadable";
34335
36046
  } catch {
34336
36047
  kind = "unreadable";
34337
36048
  }
@@ -34411,7 +36122,7 @@ async function runEventsReady(opts) {
34411
36122
  clientInfo: { name: "mcp-doctor events-ready", version: "0" }
34412
36123
  });
34413
36124
  if (disc.kind === "result") {
34414
- if (isObj4(disc.result) && typeof disc.result.protocolVersion === "string") {
36125
+ if (isObj5(disc.result) && typeof disc.result.protocolVersion === "string") {
34415
36126
  client.setProtocolVersion(disc.result.protocolVersion);
34416
36127
  }
34417
36128
  await client.notify("notifications/initialized");
@@ -34422,15 +36133,15 @@ async function runEventsReady(opts) {
34422
36133
  );
34423
36134
  }
34424
36135
  }
34425
- const caps = isObj4(disc.result) ? disc.result.capabilities : void 0;
34426
- if (!isObj4(caps)) {
36136
+ const caps = isObj5(disc.result) ? disc.result.capabilities : void 0;
36137
+ if (!isObj5(caps)) {
34427
36138
  const why = `the ${via} result carries no capabilities object (${describe(disc)})`;
34428
36139
  return EVENTS_READY_CHECKS.map((c) => couldNotJudge(c.id, via, `${why} (${c.rule})`));
34429
36140
  }
34430
- const declared = isObj4(caps.events);
36141
+ const declared = isObj5(caps.events);
34431
36142
  const list = await client.call("events/list", {});
34432
- const listed = list.kind === "result" && isObj4(list.result) && Array.isArray(list.result.events) ? list.result.events : [];
34433
- const firstName = listed.find((d) => isObj4(d) && typeof d.name === "string");
36143
+ const listed = list.kind === "result" && isObj5(list.result) && Array.isArray(list.result.events) ? list.result.events : [];
36144
+ const firstName = listed.find((d) => isObj5(d) && typeof d.name === "string");
34434
36145
  const eventName = opts.event?.name ?? firstName?.name;
34435
36146
  const args = opts.event?.arguments ?? {};
34436
36147
  const outcomes = /* @__PURE__ */ new Map();
@@ -34666,7 +36377,7 @@ async function runEventsReady(opts) {
34666
36377
  );
34667
36378
  })();
34668
36379
  const okEvents = hitsOf("ok").filter((h) => h.kind === "event");
34669
- const triggerFailed = triggerOut && (triggerOut.kind !== "result" || isObj4(triggerOut.result) && triggerOut.result.isError === true);
36380
+ const triggerFailed = triggerOut && (triggerOut.kind !== "result" || isObj5(triggerOut.result) && triggerOut.result.isError === true);
34670
36381
  const rowE = (() => {
34671
36382
  const anchor = "callback verification";
34672
36383
  if (!base) return cnj("e", anchor, NO_BASE);
@@ -34686,7 +36397,7 @@ async function runEventsReady(opts) {
34686
36397
  "no verification envelope reached the conforming receiver before events/subscribe returned"
34687
36398
  );
34688
36399
  } else {
34689
- const ch = isObj4(env.body) ? env.body.challenge : void 0;
36400
+ const ch = isObj5(env.body) ? env.body.challenge : void 0;
34690
36401
  if (typeof ch !== "string" || ch === "")
34691
36402
  fails.push("the verification envelope carries no challenge string");
34692
36403
  if (!env.headers["webhook-id"]) fails.push("the verification envelope has no webhook-id");
@@ -34697,7 +36408,7 @@ async function runEventsReady(opts) {
34697
36408
  (h) => h.kind === "verification" && h.role !== "redirect-target"
34698
36409
  );
34699
36410
  const dup = (vals) => vals.length !== new Set(vals).size;
34700
- if (dup(envs.map((h) => isObj4(h.body) ? h.body.challenge : void 0)))
36411
+ if (dup(envs.map((h) => isObj5(h.body) ? h.body.challenge : void 0)))
34701
36412
  fails.push("a challenge was reused across verifications");
34702
36413
  if (dup(envs.map((h) => h.headers["webhook-id"])))
34703
36414
  fails.push("a webhook-id was reused across verifications");
@@ -34705,7 +36416,7 @@ async function runEventsReady(opts) {
34705
36416
  if (no.kind === "result") {
34706
36417
  fails.push(`a receiver that did not echo the challenge was accepted (${describe(no)})`);
34707
36418
  } else if (no.kind === "error" && no.code === -32015) {
34708
- const reason = isObj4(no.data) ? no.data.reason : void 0;
36419
+ const reason = isObj5(no.data) ? no.data.reason : void 0;
34709
36420
  if (typeof reason !== "string" || !REASONS.includes(reason)) {
34710
36421
  fails.push(
34711
36422
  `the -32015 data.reason ${JSON.stringify(reason)} is not one of ${REASONS.join("|")}`
@@ -34849,7 +36560,7 @@ async function runEventsReady(opts) {
34849
36560
  const single = [...groups.values()].filter((g) => g.length === 1).map((g) => g[0]);
34850
36561
  const sameData = single.filter(
34851
36562
  (a) => single.some(
34852
- (b) => a !== b && isObj4(a.body) && isObj4(b.body) && JSON.stringify(a.body.data) === JSON.stringify(b.body.data) && a.status >= 500
36563
+ (b) => a !== b && isObj5(a.body) && isObj5(b.body) && JSON.stringify(a.body.data) === JSON.stringify(b.body.data) && a.status >= 500
34853
36564
  )
34854
36565
  );
34855
36566
  if (sameData.length > 0) fails.push("a retry after a 500 was sent under a new eventId");
@@ -34961,17 +36672,17 @@ function verifySignature(secret, h) {
34961
36672
 
34962
36673
  // src/runtime/launch.ts
34963
36674
  import { spawnSync as spawnSync3 } from "child_process";
34964
- import { existsSync as existsSync23, readFileSync as readFileSync25, statSync as statSync24 } from "fs";
34965
- import { dirname as dirname17, isAbsolute, join as join35, resolve as resolve3 } from "path";
36675
+ import { existsSync as existsSync23, readFileSync as readFileSync26, statSync as statSync25 } from "fs";
36676
+ import { dirname as dirname17, isAbsolute, join as join36, resolve as resolve3 } from "path";
34966
36677
  function findPackageDir(target) {
34967
36678
  let dir;
34968
36679
  try {
34969
- dir = statSync24(target).isDirectory() ? target : dirname17(target);
36680
+ dir = statSync25(target).isDirectory() ? target : dirname17(target);
34970
36681
  } catch {
34971
36682
  return null;
34972
36683
  }
34973
36684
  for (let depth = 0; depth < 8; depth++) {
34974
- if (existsSync23(join35(dir, "package.json"))) return dir;
36685
+ if (existsSync23(join36(dir, "package.json"))) return dir;
34975
36686
  const parent = dirname17(dir);
34976
36687
  if (parent === dir) break;
34977
36688
  dir = parent;
@@ -34996,13 +36707,13 @@ function deriveLaunchPlan(target) {
34996
36707
  }
34997
36708
  let pkg;
34998
36709
  try {
34999
- if (!statSync24(join35(pkgDir, "package.json")).isFile()) {
35000
- return { error: `${join35(pkgDir, "package.json")} is not a regular file \u2014 not read` };
36710
+ if (!statSync25(join36(pkgDir, "package.json")).isFile()) {
36711
+ return { error: `${join36(pkgDir, "package.json")} is not a regular file \u2014 not read` };
35001
36712
  }
35002
- pkg = JSON.parse(readFileSync25(join35(pkgDir, "package.json"), "utf8"));
36713
+ pkg = JSON.parse(readFileSync26(join36(pkgDir, "package.json"), "utf8"));
35003
36714
  } catch (err) {
35004
36715
  return {
35005
- error: `could not parse ${join35(pkgDir, "package.json")}: ${err instanceof Error ? err.message : String(err)}`
36716
+ error: `could not parse ${join36(pkgDir, "package.json")}: ${err instanceof Error ? err.message : String(err)}`
35006
36717
  };
35007
36718
  }
35008
36719
  const bin = firstBinEntry(pkg.bin);
@@ -35050,8 +36761,21 @@ const pending = new Map();
35050
36761
  const lists = [];
35051
36762
  // The one served tool-call response (S-2): a tool declared read-only that needs no argument.
35052
36763
  const calls = [];
36764
+ // S-51..S-53: one record per served tool, its tools/call answer or why none was sent. The result is recorded WITH its
36765
+ // structuredContent and its text blocks (each text cut at 64 KiB), because those rules read the value itself: whether
36766
+ // it validates against the served outputSchema, whether it is null or empty, whether the data lives in the text. The
36767
+ // call goes through the same callability() rule as every other call (consent over --url, read-only, no invented
36768
+ // argument), so a tool that could not be called is named with the reason, never skipped.
36769
+ const toolCalls = [];
36770
+ const callPending = new Map();
35053
36771
  const listPending = new Map();
35054
36772
  let nextId = 10;
36773
+ // S-51..S-53 judge EVERY served tool, so tools/list is followed to its last page and each page's tools are merged
36774
+ // into tools / toolCalls. Until the last page has answered, toolsPaging names the cursor left unread: a reader never
36775
+ // calls a partial list "every tool". A server that keeps serving a cursor stops at the page cap, named as such.
36776
+ const TOOLS_PAGE_CAP = 50;
36777
+ let toolsPaging = { complete: true, pages: 1 };
36778
+ let ingestTools;
35055
36779
  let probeTimer;
35056
36780
  let transport;
35057
36781
  // The authorization server's metadata and its authorization endpoint are PUBLIC: a server that refuses the MCP
@@ -35067,15 +36791,18 @@ const publicAuthAfterFailure = async () => {
35067
36791
  } catch (e) { return { authServer: { kind: "unavailable", url: plan.url, reason: "the public read failed: " + (e && e.message ? e.message : String(e)) } }; }
35068
36792
  };
35069
36793
  const fail = (msg) => { if (settled) return; settled = true; Promise.resolve(transport && transport.close()).then(() => publicAuthAfterFailure()).catch(() => undefined).then((publicAuth) => done({ launchError: msg, ...(publicAuth ? { publicAuth } : {}) })); };
35070
- const outstanding = () => pending.size + listPending.size;
36794
+ const outstanding = () => pending.size + listPending.size + callPending.size;
35071
36795
  const finish = (why) => {
35072
36796
  if (settled) return; settled = true; clearTimeout(to); clearTimeout(probeTimer);
35073
36797
  for (const idx of pending.values()) probes[idx].outcome = { kind: "no-answer", reason: why };
36798
+ if (!toolsPaging.complete && / got no answer$/.test(toolsPaging.reason)) toolsPaging.reason += " (" + why + ")";
35074
36799
  for (const rec of listPending.values()) {
36800
+ if (rec.toolsPageOf !== undefined) continue;
35075
36801
  if (rec.followUpOf) rec.followUpOf.followUp = { outcome: "no-answer", detail: why };
35076
- else { rec.outcome = "no-answer"; rec.detail = why; }
36802
+ else { rec.outcome = "no-answer"; rec.detail = why; if (rec.alsoTool) { rec.alsoTool.reason = why; delete rec.alsoTool; } }
35077
36803
  }
35078
- const served = { capabilities, protocolVersion: negotiated, lists, calls, versionProbe: { kind: "not-run", reason: "not run" }, authServer: { kind: "not-run", reason: "not run" }, authorize: { kind: "not-run", reason: "not run" }, ...(initializeRecord ? { initialize: initializeRecord } : {}), toolMetaRecorded: Array.isArray(tools), discovery: { kind: "not-run", reason: "not run" } };
36804
+ for (const rec of callPending.values()) { rec.kind = "no-answer"; rec.reason = why; }
36805
+ const served = { capabilities, protocolVersion: negotiated, lists, calls, toolCalls: Array.isArray(tools) ? toolCalls : undefined, versionProbe: { kind: "not-run", reason: "not run" }, authServer: { kind: "not-run", reason: "not run" }, authorize: { kind: "not-run", reason: "not run" }, ...(initializeRecord ? { initialize: initializeRecord } : {}), toolMetaRecorded: Array.isArray(tools), toolsPaging, discovery: { kind: "not-run", reason: "not run" } };
35079
36806
  Promise.resolve(extras(served))
35080
36807
  .catch((e) => { served.versionProbe = { kind: "not-run", reason: "the probe threw: " + (e && e.message ? e.message : String(e)) }; })
35081
36808
  .then(() => transport && transport.close())
@@ -35362,6 +37089,58 @@ const followCursor = (rec) => {
35362
37089
  listPending.set(fid, { method: rec.method, followUpOf: rec });
35363
37090
  send({ jsonrpc: "2.0", id: fid, method: rec.method, params: { cursor: rec.nextCursor } });
35364
37091
  };
37092
+ // tools/list pages beyond the second: the cursor is presented back untouched, as for followCursor.
37093
+ const followToolsPage = (cursor) => {
37094
+ const fid = nextId++;
37095
+ listPending.set(fid, { method: "tools/list", toolsPageOf: cursor });
37096
+ send({ jsonrpc: "2.0", id: fid, method: "tools/list", params: { cursor } });
37097
+ };
37098
+ // One answered tools/list page after the first: its tools are merged, then the next cursor is followed.
37099
+ const onToolsPage = (cursor, got, msg) => {
37100
+ const page = msg.result && Array.isArray(msg.result.tools) ? msg.result.tools : undefined;
37101
+ if (got.outcome !== "answered" || !page || !ingestTools) {
37102
+ toolsPaging = { complete: false, pages: toolsPaging.pages, unreadCursor: cursor, reason: "the tools/list page for cursor " + JSON.stringify(cursor) + " was not read: " + (got.detail || "its result carries no tools array") };
37103
+ return;
37104
+ }
37105
+ ingestTools(page);
37106
+ const pages = toolsPaging.pages + 1;
37107
+ const next = msg.result.nextCursor;
37108
+ if (typeof next !== "string" || !next) { toolsPaging = { complete: true, pages }; return; }
37109
+ if (pages >= TOOLS_PAGE_CAP) {
37110
+ toolsPaging = { complete: false, pages, unreadCursor: next, reason: "the tools/list page cap (" + TOOLS_PAGE_CAP + " pages) was reached with a cursor still served" };
37111
+ return;
37112
+ }
37113
+ toolsPaging = { complete: false, pages, unreadCursor: next, reason: "tools/list page " + (pages + 1) + " got no answer" };
37114
+ followToolsPage(next);
37115
+ };
37116
+ // One tools/call answer read into its S-51 record (the record keeps only its tool name before it is filled).
37117
+ const fillToolCall = (rec, msg) => {
37118
+ const name = rec.tool;
37119
+ for (const k of Object.keys(rec)) delete rec[k];
37120
+ rec.tool = name;
37121
+ if (msg.error && typeof msg.error === "object") {
37122
+ Object.assign(rec, { kind: "error", code: msg.error.code, ...(typeof msg.error.message === "string" ? { message: msg.error.message } : {}) });
37123
+ } else if (msg.result && typeof msg.result === "object" && !Array.isArray(msg.result)) {
37124
+ const r = msg.result;
37125
+ const CAP = 65536;
37126
+ const block = (b) => {
37127
+ if (!b || typeof b !== "object") return { type: "<" + (b === null ? "null" : typeof b) + ">" };
37128
+ const out = { type: typeof b.type === "string" ? b.type : "<no type>" };
37129
+ if (typeof b.text === "string") { out.text = b.text.slice(0, CAP); if (b.text.length > CAP) out.truncated = true; }
37130
+ return out;
37131
+ };
37132
+ Object.assign(rec, {
37133
+ kind: "result",
37134
+ isError: r.isError === true,
37135
+ hasStructured: Object.prototype.hasOwnProperty.call(r, "structuredContent"),
37136
+ ...(r.structuredContent !== undefined ? { structuredContent: r.structuredContent } : {}),
37137
+ contentKind: Array.isArray(r.content) ? "array" : r.content === undefined ? "absent" : "other",
37138
+ content: Array.isArray(r.content) ? r.content.map(block) : [],
37139
+ });
37140
+ } else {
37141
+ Object.assign(rec, { kind: "no-answer", reason: "an answer with neither result nor error" });
37142
+ }
37143
+ };
35365
37144
  const onMessage = (msg) => {
35366
37145
  // A request or notification FROM the server carries a method: it is not an answer.
35367
37146
  if (msg.method !== undefined) return;
@@ -35424,13 +37203,17 @@ const onMessage = (msg) => {
35424
37203
  const props = schemaOf(t).properties;
35425
37204
  return Boolean(props && typeof props === "object" && Object.prototype.hasOwnProperty.call(props, "cursor"));
35426
37205
  };
35427
- tools = served.map((t) => ({ name: String(t && t.name), description: t && typeof t.description === "string" ? t.description : undefined, cursorArgument: takesCursor(t), inputSchema: t && t.inputSchema && typeof t.inputSchema === "object" && !Array.isArray(t.inputSchema) ? t.inputSchema : undefined, outputSchema: t && t.outputSchema && typeof t.outputSchema === "object" && !Array.isArray(t.outputSchema) ? t.outputSchema : undefined, title: t && typeof t.title === "string" ? t.title : undefined, annotations: t && t.annotations && typeof t.annotations === "object" && !Array.isArray(t.annotations) ? { readOnlyHint: t.annotations.readOnlyHint, destructiveHint: t.annotations.destructiveHint, idempotentHint: t.annotations.idempotentHint, openWorldHint: t.annotations.openWorldHint, title: t.annotations.title } : undefined, ...(t && t._meta !== undefined ? { meta: t._meta } : {}) }));
37206
+ const toolRecord = (t) => ({ name: String(t && t.name), description: t && typeof t.description === "string" ? t.description : undefined, cursorArgument: takesCursor(t), inputSchema: t && t.inputSchema && typeof t.inputSchema === "object" && !Array.isArray(t.inputSchema) ? t.inputSchema : undefined, outputSchema: t && t.outputSchema && typeof t.outputSchema === "object" && !Array.isArray(t.outputSchema) ? t.outputSchema : undefined, title: t && typeof t.title === "string" ? t.title : undefined, annotations: t && t.annotations && typeof t.annotations === "object" && !Array.isArray(t.annotations) ? { readOnlyHint: t.annotations.readOnlyHint, destructiveHint: t.annotations.destructiveHint, idempotentHint: t.annotations.idempotentHint, openWorldHint: t.annotations.openWorldHint, title: t.annotations.title } : undefined, ...(t && t._meta !== undefined ? { meta: t._meta } : {}) });
37207
+ tools = served.map(toolRecord);
35428
37208
  const methods = ["tools/list"];
35429
37209
  if (capabilities.resources) methods.push("resources/list", "resources/templates/list");
35430
37210
  if (capabilities.prompts) methods.push("prompts/list");
35431
37211
  const first = listRecord("tools/list", msg);
35432
37212
  lists.push(first);
35433
- if (first.outcome === "answered" && typeof first.nextCursor === "string" && first.nextCursor) followCursor(first);
37213
+ if (first.outcome === "answered" && typeof first.nextCursor === "string" && first.nextCursor) {
37214
+ toolsPaging = { complete: false, pages: 1, unreadCursor: first.nextCursor, reason: "tools/list page 2 got no answer" };
37215
+ followCursor(first);
37216
+ }
35434
37217
  // The other declared list methods, asked for their first page: S-3 / S-12 read what they serve.
35435
37218
  for (const m of methods.slice(1)) {
35436
37219
  const lid = nextId++;
@@ -35439,13 +37222,33 @@ const onMessage = (msg) => {
35439
37222
  listPending.set(lid, rec);
35440
37223
  send({ jsonrpc: "2.0", id: lid, method: m, params: {} });
35441
37224
  }
37225
+ // One S-51 record per tool of a page; skip is the S-2 tool of page 1, whose record that call fills.
37226
+ const recordCalls = (page, skip) => {
37227
+ for (const t of page) {
37228
+ const name = String(t && t.name);
37229
+ const gate = callability(t, []);
37230
+ if (!gate.callable) { toolCalls.push({ tool: name, kind: "not-sent", reason: gate.reason }); continue; }
37231
+ const rec = { tool: name, kind: "no-answer", reason: "pending" };
37232
+ toolCalls.push(rec);
37233
+ if (t === skip) continue;
37234
+ const cid = nextId++;
37235
+ callPending.set(cid, rec);
37236
+ send({ jsonrpc: "2.0", id: cid, method: "tools/call", params: { name: t.name, arguments: {} } });
37237
+ }
37238
+ };
37239
+ // The first callable tool is the S-2 call below, which fills this record from its own answer.
37240
+ recordCalls(served, served.find((x) => callability(x, []).callable));
37241
+ // A later tools/list page: its tools join tools and get their S-51 records through the same callability() rule.
37242
+ // Declared divergence: the C-11 cursor-argument probe below reads page 1's tools only.
37243
+ ingestTools = (page) => { for (const t of page) tools.push(toolRecord(t)); recordCalls(page, undefined); };
35442
37244
  // S-2 is verified "on the response returned" to a tool call: ONE tool that callability() admits
35443
- // with no argument supplied is called with {}; only the KEYS of its result are recorded, never its
35444
- // content. No such tool: no call is invented.
37245
+ // with no argument supplied is called with {}; its S-2 record keeps only the KEYS of the result. The same answer
37246
+ // fills that tool's S-51 record (toolCalls, above), so the tool is called once. No such tool: no call is invented.
35445
37247
  const safe = served.find((t) => callability(t, []).callable);
35446
37248
  if (safe) {
35447
37249
  const cid = nextId++;
35448
- const rec = { method: "tools/call " + String(safe.name) };
37250
+ // The S-51 record of this same tool reads this same answer: the tool is called once, never twice.
37251
+ const rec = { method: "tools/call " + String(safe.name), alsoTool: toolCalls.find((c) => c.tool === String(safe.name) && c.kind === "no-answer") };
35449
37252
  calls.push(rec);
35450
37253
  listPending.set(cid, rec);
35451
37254
  send({ jsonrpc: "2.0", id: cid, method: "tools/call", params: { name: safe.name, arguments: {} } });
@@ -35463,12 +37266,20 @@ const onMessage = (msg) => {
35463
37266
  }
35464
37267
  if (outstanding() === 0) { finish("no probe pending"); return; }
35465
37268
  probeTimer = setTimeout(() => finish("no answer within the 5 s probe deadline"), 5000);
37269
+ } else if (callPending.has(msg.id)) {
37270
+ const rec = callPending.get(msg.id); callPending.delete(msg.id);
37271
+ fillToolCall(rec, msg);
37272
+ if (outstanding() === 0) finish("no probe pending");
35466
37273
  } else if (listPending.has(msg.id)) {
35467
37274
  const rec = listPending.get(msg.id); listPending.delete(msg.id);
35468
- if (rec.followUpOf) {
37275
+ if (rec.toolsPageOf !== undefined) {
37276
+ onToolsPage(rec.toolsPageOf, listRecord(rec.method, msg), msg);
37277
+ } else if (rec.followUpOf) {
35469
37278
  const got = listRecord(rec.method, msg);
35470
37279
  rec.followUpOf.followUp = { outcome: got.outcome, detail: got.detail, entries: got.entries };
37280
+ if (rec.method === "tools/list" && rec.followUpOf.method === "tools/list") onToolsPage(rec.followUpOf.nextCursor, got, msg);
35471
37281
  } else {
37282
+ if (rec.alsoTool) { fillToolCall(rec.alsoTool, msg); delete rec.alsoTool; }
35472
37283
  Object.assign(rec, listRecord(rec.method, msg));
35473
37284
  if (rec.outcome === "answered" && typeof rec.nextCursor === "string" && rec.nextCursor) followCursor(rec);
35474
37285
  }
@@ -35490,17 +37301,17 @@ const onMessage = (msg) => {
35490
37301
  transport = plan.kind === "http" ? makeHttpTransport() : makeStdioTransport();
35491
37302
  if (transport) send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "mcp-doctor", version: "0" } } });
35492
37303
  `;
35493
- var isObj5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
37304
+ var isObj6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
35494
37305
  var outcomeOf = (v) => v === "answered" || v === "refused" ? v : "no-answer";
35495
37306
  function readServed(raw) {
35496
- if (!isObj5(raw)) return void 0;
37307
+ if (!isObj6(raw)) return void 0;
35497
37308
  const readList = (l) => {
35498
- const r = isObj5(l) ? l : {};
37309
+ const r = isObj6(l) ? l : {};
35499
37310
  const method = typeof r.method === "string" ? r.method : "<unnamed list>";
35500
- const fu = isObj5(r.followUp) ? r.followUp : void 0;
37311
+ const fu = isObj6(r.followUp) ? r.followUp : void 0;
35501
37312
  return {
35502
37313
  method,
35503
- outcome: isObj5(l) ? outcomeOf(r.outcome) : "no-answer",
37314
+ outcome: isObj6(l) ? outcomeOf(r.outcome) : "no-answer",
35504
37315
  ...typeof r.detail === "string" ? { detail: r.detail } : {},
35505
37316
  ...Array.isArray(r.resultKeys) ? { resultKeys: r.resultKeys.map(String) } : {},
35506
37317
  ...r.resultType !== void 0 ? { resultType: r.resultType } : {},
@@ -35519,29 +37330,29 @@ function readServed(raw) {
35519
37330
  };
35520
37331
  const lists = (Array.isArray(raw.lists) ? raw.lists : []).map(readList);
35521
37332
  const vp = raw.versionProbe;
35522
- const versionProbe = isObj5(vp) && vp.kind === "statuses" && typeof vp.supportedVersion === "string" && typeof vp.supported === "number" && typeof vp.unsupported === "number" ? {
37333
+ const versionProbe = isObj6(vp) && vp.kind === "statuses" && typeof vp.supportedVersion === "string" && typeof vp.supported === "number" && typeof vp.unsupported === "number" ? {
35523
37334
  kind: "statuses",
35524
37335
  supportedVersion: vp.supportedVersion,
35525
37336
  supported: vp.supported,
35526
37337
  unsupported: vp.unsupported
35527
37338
  } : {
35528
37339
  kind: "not-run",
35529
- reason: isObj5(vp) && vp.kind === "not-run" && typeof vp.reason === "string" ? vp.reason : "unreadable version-probe record"
37340
+ reason: isObj6(vp) && vp.kind === "not-run" && typeof vp.reason === "string" ? vp.reason : "unreadable version-probe record"
35530
37341
  };
35531
37342
  const as = raw.authServer;
35532
- const authServer = isObj5(as) && as.kind === "document" && typeof as.url === "string" && typeof as.status === "number" && isObj5(as.document) ? { kind: "document", url: as.url, status: as.status, document: as.document } : isObj5(as) && as.kind === "unavailable" && typeof as.url === "string" ? {
37343
+ const authServer = isObj6(as) && as.kind === "document" && typeof as.url === "string" && typeof as.status === "number" && isObj6(as.document) ? { kind: "document", url: as.url, status: as.status, document: as.document } : isObj6(as) && as.kind === "unavailable" && typeof as.url === "string" ? {
35533
37344
  kind: "unavailable",
35534
37345
  url: as.url,
35535
37346
  reason: typeof as.reason === "string" ? as.reason : "no reason given"
35536
37347
  } : {
35537
37348
  kind: "not-run",
35538
- reason: isObj5(as) && as.kind === "not-run" && typeof as.reason === "string" ? as.reason : "unreadable authorization-server record"
37349
+ reason: isObj6(as) && as.kind === "not-run" && typeof as.reason === "string" ? as.reason : "unreadable authorization-server record"
35539
37350
  };
35540
37351
  const authorize = readAuthorize(raw.authorize);
35541
- const init = isObj5(raw.initialize) ? raw.initialize : void 0;
37352
+ const init = isObj6(raw.initialize) ? raw.initialize : void 0;
35542
37353
  const discovery = readDiscovery(raw.discovery);
35543
37354
  return {
35544
- capabilities: isObj5(raw.capabilities) ? raw.capabilities : {},
37355
+ capabilities: isObj6(raw.capabilities) ? raw.capabilities : {},
35545
37356
  ...typeof raw.protocolVersion === "string" ? { protocolVersion: raw.protocolVersion } : {},
35546
37357
  lists,
35547
37358
  calls: (Array.isArray(raw.calls) ? raw.calls : []).map(readList),
@@ -35555,43 +37366,86 @@ function readServed(raw) {
35555
37366
  }
35556
37367
  } : {},
35557
37368
  ...raw.toolMetaRecorded === true ? { toolMetaRecorded: true } : {},
35558
- ...discovery ? { discovery } : {}
37369
+ ...discovery ? { discovery } : {},
37370
+ ...Array.isArray(raw.toolCalls) ? { toolCalls: raw.toolCalls.map(readToolCall) } : {},
37371
+ ...isObj6(raw.toolsPaging) ? { toolsPaging: readToolsPaging(raw.toolsPaging) } : {}
37372
+ };
37373
+ }
37374
+ function readToolsPaging(r) {
37375
+ const pages = typeof r.pages === "number" ? r.pages : 0;
37376
+ if (r.complete === true) return { complete: true, pages };
37377
+ return {
37378
+ complete: false,
37379
+ pages,
37380
+ ...r.unreadCursor !== void 0 ? { unreadCursor: r.unreadCursor } : {},
37381
+ reason: typeof r.reason === "string" ? r.reason : "the paging record names no reason"
35559
37382
  };
35560
37383
  }
37384
+ function readToolCall(raw) {
37385
+ const r = isObj6(raw) ? raw : {};
37386
+ const tool = typeof r.tool === "string" ? r.tool : "<unnamed tool>";
37387
+ const reason = typeof r.reason === "string" ? r.reason : "no reason recorded";
37388
+ if (r.kind === "not-sent") return { tool, kind: "not-sent", reason };
37389
+ if (r.kind === "error")
37390
+ return {
37391
+ tool,
37392
+ kind: "error",
37393
+ code: r.code,
37394
+ ...typeof r.message === "string" ? { message: r.message } : {}
37395
+ };
37396
+ if (r.kind === "result" && typeof r.hasStructured === "boolean" && Array.isArray(r.content)) {
37397
+ const contentKind = r.contentKind === "array" || r.contentKind === "absent" || r.contentKind === "other" ? r.contentKind : "other";
37398
+ return {
37399
+ tool,
37400
+ kind: "result",
37401
+ isError: r.isError === true,
37402
+ hasStructured: r.hasStructured,
37403
+ ...r.structuredContent !== void 0 ? { structuredContent: r.structuredContent } : {},
37404
+ contentKind,
37405
+ content: r.content.filter(isObj6).map((b) => ({
37406
+ type: typeof b.type === "string" ? b.type : "<no type>",
37407
+ ...typeof b.text === "string" ? { text: b.text } : {},
37408
+ ...b.truncated === true ? { truncated: true } : {}
37409
+ }))
37410
+ };
37411
+ }
37412
+ if (r.kind === "no-answer") return { tool, kind: "no-answer", reason };
37413
+ return { tool, kind: "no-answer", reason: "unreadable tool-call record" };
37414
+ }
35561
37415
  function readDiscovery(raw) {
35562
37416
  if (raw === void 0) return void 0;
35563
37417
  const get = (g) => {
35564
- const r = isObj5(g) ? g : {};
37418
+ const r = isObj6(g) ? g : {};
35565
37419
  return {
35566
37420
  url: typeof r.url === "string" ? r.url : "<unnamed url>",
35567
37421
  ...typeof r.status === "number" ? { status: r.status } : {},
35568
37422
  ...typeof r.contentType === "string" ? { contentType: r.contentType } : {},
35569
- ...isObj5(r.json) ? { json: r.json } : {},
37423
+ ...isObj6(r.json) ? { json: r.json } : {},
35570
37424
  ...typeof r.text === "string" ? { text: r.text } : {},
35571
- ...typeof r.detail === "string" ? { detail: r.detail } : isObj5(g) ? {} : { detail: "unreadable GET record" }
37425
+ ...typeof r.detail === "string" ? { detail: r.detail } : isObj6(g) ? {} : { detail: "unreadable GET record" }
35572
37426
  };
35573
37427
  };
35574
- if (isObj5(raw) && raw.kind === "probed" && Array.isArray(raw.cards) && isObj5(raw.landing))
37428
+ if (isObj6(raw) && raw.kind === "probed" && Array.isArray(raw.cards) && isObj6(raw.landing))
35575
37429
  return { kind: "probed", cards: raw.cards.map(get), landing: get(raw.landing) };
35576
37430
  return {
35577
37431
  kind: "not-run",
35578
- reason: isObj5(raw) && raw.kind === "not-run" && typeof raw.reason === "string" ? raw.reason : "unreadable discovery record"
37432
+ reason: isObj6(raw) && raw.kind === "not-run" && typeof raw.reason === "string" ? raw.reason : "unreadable discovery record"
35579
37433
  };
35580
37434
  }
35581
37435
  function readAuthorize(raw) {
35582
- if (!isObj5(raw)) return void 0;
37436
+ if (!isObj6(raw)) return void 0;
35583
37437
  if (raw.kind !== "probed" || !Array.isArray(raw.clients))
35584
37438
  return {
35585
37439
  kind: "not-run",
35586
37440
  reason: typeof raw.reason === "string" ? raw.reason : "unreadable sign-in probe record"
35587
37441
  };
35588
37442
  const str = (v) => typeof v === "string" ? v : void 0;
35589
- const clients = raw.clients.filter(isObj5).map((c) => {
37443
+ const clients = raw.clients.filter(isObj6).map((c) => {
35590
37444
  const host = str(c.host) ?? "<unnamed host>";
35591
37445
  const clientId = str(c.clientId) ?? "<unnamed client>";
35592
37446
  if (c.kind !== "probed" || !Array.isArray(c.attempts))
35593
37447
  return { host, clientId, kind: "unavailable", reason: str(c.reason) ?? "no reason given" };
35594
- const attempts = c.attempts.filter(isObj5).map((a) => ({
37448
+ const attempts = c.attempts.filter(isObj6).map((a) => ({
35595
37449
  redirect: str(a.redirect) ?? "<unnamed redirect>",
35596
37450
  ...typeof a.status === "number" ? { status: a.status } : {},
35597
37451
  ...str(a.location) ? { location: str(a.location) } : {},
@@ -35608,14 +37462,14 @@ function readEvalCounts(target) {
35608
37462
  if (!pkgDir) return { counts };
35609
37463
  let dir = pkgDir;
35610
37464
  for (let depth = 0; depth < 8; depth++) {
35611
- const candidate = join35(dir, "evals", "evals.json");
37465
+ const candidate = join36(dir, "evals", "evals.json");
35612
37466
  if (existsSync23(candidate)) {
35613
37467
  let text;
35614
37468
  try {
35615
- if (!statSync24(candidate).isFile()) {
37469
+ if (!statSync25(candidate).isFile()) {
35616
37470
  return { counts, unreadable: `${candidate} is not a regular file \u2014 not read` };
35617
37471
  }
35618
- text = readFileSync25(candidate, "utf8");
37472
+ text = readFileSync26(candidate, "utf8");
35619
37473
  } catch (err) {
35620
37474
  return {
35621
37475
  counts,
@@ -35639,7 +37493,7 @@ function readEvalCounts(target) {
35639
37493
  }
35640
37494
  function statSyncSafe(p) {
35641
37495
  try {
35642
- return statSync24(p).isDirectory();
37496
+ return statSync25(p).isDirectory();
35643
37497
  } catch {
35644
37498
  return false;
35645
37499
  }
@@ -35776,7 +37630,7 @@ function introspect(plan, root, evalSource, expectedCommit, evalsNote, secrets)
35776
37630
  };
35777
37631
  }
35778
37632
  if (parsed.launchError) {
35779
- const pub = isObj5(parsed.publicAuth) ? readServed(parsed.publicAuth) : void 0;
37633
+ const pub = isObj6(parsed.publicAuth) ? readServed(parsed.publicAuth) : void 0;
35780
37634
  return {
35781
37635
  root,
35782
37636
  tools: [],
@@ -35865,7 +37719,7 @@ function isLiveDetector(d) {
35865
37719
  }
35866
37720
 
35867
37721
  // src/urlArgs.ts
35868
- import { statSync as statSync25 } from "fs";
37722
+ import { statSync as statSync26 } from "fs";
35869
37723
  var VALUE_OPTIONS2 = [
35870
37724
  "--url",
35871
37725
  "--header",
@@ -35983,7 +37837,7 @@ function parseUrlArgs(args, env) {
35983
37837
  const src = values["--source"][0];
35984
37838
  let isDir2 = false;
35985
37839
  try {
35986
- isDir2 = statSync25(src).isDirectory();
37840
+ isDir2 = statSync26(src).isDirectory();
35987
37841
  } catch {
35988
37842
  isDir2 = false;
35989
37843
  }
@@ -36004,7 +37858,7 @@ function parseUrlArgs(args, env) {
36004
37858
  }
36005
37859
 
36006
37860
  // src/kit/rule-ids.ts
36007
- import { readFileSync as readFileSync26 } from "fs";
37861
+ import { readFileSync as readFileSync27 } from "fs";
36008
37862
  var StandardUnreadableError = class extends Error {
36009
37863
  constructor(path, cause) {
36010
37864
  super(
@@ -36044,7 +37898,7 @@ function stateless(pattern) {
36044
37898
  function deriveRuleIds(path, pattern) {
36045
37899
  let blob;
36046
37900
  try {
36047
- blob = readFileSync26(path, "utf8");
37901
+ blob = readFileSync27(path, "utf8");
36048
37902
  } catch (e) {
36049
37903
  throw new StandardUnreadableError(path, e);
36050
37904
  }
@@ -36505,11 +38359,11 @@ function renderJson(surface, results, skipped, coverage, gate) {
36505
38359
  function renderResults(surface, results, coverageLine) {
36506
38360
  const cols = { item: 24, anchor: 26, state: 15 };
36507
38361
  const header = `${pad("item", cols.item)} | ${pad("file:line", cols.anchor)} | ${pad("state", cols.state)} | verdict`;
36508
- const sep7 = "-".repeat(header.length);
38362
+ const sep8 = "-".repeat(header.length);
36509
38363
  const rows = results.map(
36510
38364
  (r) => `${pad(r.id, cols.item)} | ${pad(r.anchor, cols.anchor)} | ${pad(r.state, cols.state)} | ${r.verdict}`
36511
38365
  );
36512
- const table = [`surface: ${surface}`, coverageLine, header, sep7, ...rows].join("\n");
38366
+ const table = [`surface: ${surface}`, coverageLine, header, sep8, ...rows].join("\n");
36513
38367
  const unjudged = results.filter((r) => r.state === "could-not-judge");
36514
38368
  if (unjudged.length === 0) return table;
36515
38369
  const cnjHeader = `could-not-judge (${unjudged.length}) \u2014 the doctor could NOT read these; this is NOT a clean bill:`;
@@ -36592,7 +38446,7 @@ var USAGE = [
36592
38446
  function readVersion() {
36593
38447
  try {
36594
38448
  const here = dirname19(fileURLToPath2(import.meta.url));
36595
- const manifest = JSON.parse(readFileSync27(join36(here, "..", "package.json"), "utf8"));
38449
+ const manifest = JSON.parse(readFileSync28(join37(here, "..", "package.json"), "utf8"));
36596
38450
  return manifest.version ?? null;
36597
38451
  } catch {
36598
38452
  return null;
@@ -36660,10 +38514,10 @@ function runEventsMode(endpoint, rest, options) {
36660
38514
  }
36661
38515
  function defaultOwedPath(target) {
36662
38516
  try {
36663
- if (statSync26(target).isFile()) return join36(dirname19(target), OWED_FILE_NAME);
38517
+ if (statSync27(target).isFile()) return join37(dirname19(target), OWED_FILE_NAME);
36664
38518
  } catch {
36665
38519
  }
36666
- return join36(target, OWED_FILE_NAME);
38520
+ return join37(target, OWED_FILE_NAME);
36667
38521
  }
36668
38522
  function main() {
36669
38523
  const argv = process.argv.slice(2);