codebase-snapshot 0.13.0 → 0.15.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/mcp.cjs CHANGED
@@ -2548,7 +2548,7 @@ function applySpansKeepingQuotes(line, spans) {
2548
2548
 
2549
2549
  // src/version.ts
2550
2550
  var GENERATOR_NAME = "codebase-snapshot";
2551
- var GENERATOR_VERSION = "0.13.0";
2551
+ var GENERATOR_VERSION = "0.15.0";
2552
2552
  var SCHEMA_VERSION = "3.0.0";
2553
2553
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2554
2554
  function isOurGeneratorName(name) {
@@ -4372,7 +4372,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4372
4372
  logCount: resolveLogCount(
4373
4373
  cliOptions?.logCount ?? cliOptions?.includeLogs ?? userConfig?.logCount
4374
4374
  ),
4375
- include: resolveInclude(userConfig?.include),
4375
+ // `--only` replaces the allow-list for this run; `--ignore` adds to the deny-list. The two
4376
+ // directions are different on purpose: a narrower allow-list is a statement about the whole
4377
+ // run, while "also ignore this" is naturally cumulative with what the config already excludes.
4378
+ include: resolveInclude(
4379
+ cliOptions?.only ?? userConfig?.include
4380
+ ),
4376
4381
  preset: preset.presetName,
4377
4382
  presetExclude,
4378
4383
  artifacts,
@@ -4383,9 +4388,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4383
4388
  kinds,
4384
4389
  // `exclude` is the flag spelling of the same setting; writing it in a config used to
4385
4390
  // be ignored without a word.
4386
- excludePatterns: resolveExcludePatterns(
4387
- userConfig?.excludePatterns ?? userConfig?.exclude
4388
- ),
4391
+ excludePatterns: [
4392
+ ...resolveExcludePatterns(
4393
+ userConfig?.excludePatterns ?? userConfig?.exclude
4394
+ ),
4395
+ ...resolveExcludePatterns(cliOptions?.ignore)
4396
+ ],
4389
4397
  secretRules,
4390
4398
  // Extra property rather than a `ResolvedSnapshotConfig` field: the resolved
4391
4399
  // shape is owned elsewhere, and every scan reads it through the registry in
@@ -8029,6 +8037,92 @@ function verifySnapshotSignature(snapshotDir) {
8029
8037
  return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8030
8038
  }
8031
8039
 
8040
+ // src/partitioner/part-format.ts
8041
+ var FILE_HEADING = "### FILE: ";
8042
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
8043
+ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
8044
+ var META_PREFIX = "- Meta: ";
8045
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
8046
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
8047
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
8048
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
8049
+ function readIncludedLines(fields) {
8050
+ const last = fields[fields.length - 1];
8051
+ if (last === void 0) return null;
8052
+ const counts = COMPACT_COUNTS.exec(last.trim());
8053
+ return counts === null ? null : Number(counts[1]);
8054
+ }
8055
+ function parsePartSections(partText) {
8056
+ const lines = partText.split("\n");
8057
+ const sections = [];
8058
+ let index = 0;
8059
+ while (index < lines.length) {
8060
+ if (!lines[index].startsWith(FILE_HEADING)) {
8061
+ index += 1;
8062
+ continue;
8063
+ }
8064
+ const heading = lines[index].slice(FILE_HEADING.length);
8065
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
8066
+ let cursor = index + 1;
8067
+ let inclusion = null;
8068
+ let includedLines = null;
8069
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
8070
+ const line = lines[cursor];
8071
+ if (line.startsWith(FILE_HEADING)) break;
8072
+ if (line.startsWith(META_PREFIX)) {
8073
+ const fields = line.slice(META_PREFIX.length).split("|");
8074
+ for (const field of fields) {
8075
+ const value = field.trim();
8076
+ if (INCLUSION_MODES.has(value)) inclusion = value;
8077
+ }
8078
+ includedLines = readIncludedLines(fields);
8079
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
8080
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
8081
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
8082
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
8083
+ includedLines = Number.isFinite(value) ? value : null;
8084
+ }
8085
+ cursor += 1;
8086
+ }
8087
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
8088
+ index = cursor + 1;
8089
+ continue;
8090
+ }
8091
+ let fenceLine = cursor + 1;
8092
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
8093
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
8094
+ if (!fenceMatch) {
8095
+ index = cursor + 1;
8096
+ continue;
8097
+ }
8098
+ const fence = fenceMatch[1];
8099
+ const body = [];
8100
+ let bodyLine = fenceLine + 1;
8101
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
8102
+ body.push(lines[bodyLine]);
8103
+ bodyLine += 1;
8104
+ }
8105
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
8106
+ index = bodyLine + 1;
8107
+ }
8108
+ return sections;
8109
+ }
8110
+ function findSection(sections, relativePath) {
8111
+ const anchor = anchorForPath(relativePath);
8112
+ const byAnchor = sections.find((section) => section.anchor === anchor);
8113
+ if (byAnchor) return byAnchor;
8114
+ const rendered = displayPath(relativePath);
8115
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
8116
+ const exact = sections.find(samePath);
8117
+ if (exact) return exact;
8118
+ const foldedPath = rendered.toLowerCase();
8119
+ const folded = sections.filter((section) => {
8120
+ const path16 = section.path.toLowerCase();
8121
+ return path16 === relativePath.toLowerCase() || path16 === foldedPath;
8122
+ });
8123
+ return folded.length === 1 ? folded[0] : null;
8124
+ }
8125
+
8032
8126
  // src/auditor/health.ts
8033
8127
  var ARTIFACT_FILES = {
8034
8128
  readme: "README.md",
@@ -8338,6 +8432,206 @@ function auditSnapshot(options) {
8338
8432
  )
8339
8433
  );
8340
8434
  }
8435
+ const bookkeeping = [];
8436
+ const expect = (name, recorded2, computed) => {
8437
+ if (recorded2 !== computed) bookkeeping.push(name + ": manifest says " + recorded2 + ", the data has " + computed);
8438
+ };
8439
+ expect("counts.totalFiles", manifest.counts.totalFiles, manifest.files.length);
8440
+ expect("counts.partsCount", manifest.counts.partsCount, manifest.parts.length);
8441
+ expect("counts.skippedCount", manifest.counts.skippedCount, manifest.skipped.length);
8442
+ if (typeof manifest.totals.includedFiles === "number") {
8443
+ expect("totals.includedFiles", manifest.totals.includedFiles, manifest.files.length);
8444
+ }
8445
+ const contentBytes = manifest.files.reduce((sum, file) => sum + file.includedBytes, 0);
8446
+ expect("totals.totalContentBytes", manifest.totals.totalContentBytes, contentBytes);
8447
+ const layerCounts = /* @__PURE__ */ new Map();
8448
+ for (const file of manifest.files) layerCounts.set(file.layer, (layerCounts.get(file.layer) ?? 0) + 1);
8449
+ for (const [layer2, count] of layerCounts) {
8450
+ expect("layers." + layer2, manifest.layers[layer2] ?? -1, count);
8451
+ }
8452
+ for (const layer2 of Object.keys(manifest.layers)) {
8453
+ if (!layerCounts.has(layer2)) expect("layers." + layer2, manifest.layers[layer2], 0);
8454
+ }
8455
+ checks.push(
8456
+ bookkeeping.length === 0 ? check(
8457
+ "bookkeeping",
8458
+ "The counts equal the data they summarise",
8459
+ "critical",
8460
+ "pass",
8461
+ "Files, parts, skips, content bytes and layer counts all agree."
8462
+ ) : check(
8463
+ "bookkeeping",
8464
+ "The counts equal the data they summarise",
8465
+ "critical",
8466
+ "fail",
8467
+ bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
8468
+ )
8469
+ );
8470
+ const packReaders = [
8471
+ {
8472
+ key: "fullJson",
8473
+ file: "full-codebase.json",
8474
+ label: "JSON",
8475
+ paths: (text) => {
8476
+ try {
8477
+ const parsed = JSON.parse(text);
8478
+ if (!Array.isArray(parsed?.files)) return null;
8479
+ return new Set(parsed.files.map((entry) => String(entry?.relativePath)));
8480
+ } catch {
8481
+ return null;
8482
+ }
8483
+ }
8484
+ },
8485
+ {
8486
+ key: "fullXml",
8487
+ file: "full-codebase.xml",
8488
+ label: "XML",
8489
+ paths: (text) => {
8490
+ const found = [...text.matchAll(/<file path="([^"]+)"/g)].map((match) => match[1]);
8491
+ if (found.length === 0) return null;
8492
+ return new Set(found.map((value) => value.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")));
8493
+ }
8494
+ },
8495
+ {
8496
+ key: "fullMarkdown",
8497
+ file: "full-codebase.md",
8498
+ label: "markdown",
8499
+ paths: (text) => {
8500
+ const found = [...text.matchAll(/^## File: (.+)$/gm)].map((match) => match[1].trim());
8501
+ if (found.length === 0) return null;
8502
+ return new Set(found);
8503
+ }
8504
+ }
8505
+ ];
8506
+ for (const reader of packReaders) {
8507
+ if (manifest.artifacts?.[reader.key] == null) continue;
8508
+ const packText = readText(path5__namespace.join(snapshotDir, reader.file));
8509
+ const problems = [];
8510
+ if (packText === null) {
8511
+ problems.push(reader.file + " is recorded but unreadable");
8512
+ } else {
8513
+ const packed = reader.paths(packText);
8514
+ if (packed === null) {
8515
+ problems.push(reader.file + " could not be parsed for its file list");
8516
+ } else {
8517
+ const known2 = new Set(manifest.files.map((file) => file.relativePath));
8518
+ for (const file of manifest.files) {
8519
+ if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
8520
+ }
8521
+ for (const path16 of packed) {
8522
+ if (!known2.has(path16)) problems.push(path16 + " is in the pack but not the manifest");
8523
+ }
8524
+ }
8525
+ }
8526
+ const title = "The " + reader.label + " pack holds every file the manifest lists";
8527
+ checks.push(
8528
+ problems.length === 0 ? check(
8529
+ "pipeline.monolith",
8530
+ title,
8531
+ "critical",
8532
+ "pass",
8533
+ manifest.files.length + " file(s) present in " + reader.file + ", and nothing extra."
8534
+ ) : check(
8535
+ "pipeline.monolith",
8536
+ title,
8537
+ "critical",
8538
+ "fail",
8539
+ problems.length + " problem(s): " + sample(problems)
8540
+ )
8541
+ );
8542
+ }
8543
+ const bodyProblems = [];
8544
+ let bodiesChecked = 0;
8545
+ for (const part of manifest.parts) {
8546
+ const partText = readText(path5__namespace.join(snapshotDir, "parts", part.filename));
8547
+ if (partText === null) continue;
8548
+ const sections = parsePartSections(partText);
8549
+ for (const file of manifest.files) {
8550
+ if (file.part !== part.filename) continue;
8551
+ const section = findSection(sections, file.relativePath);
8552
+ if (section === null) {
8553
+ bodyProblems.push(file.relativePath + " has no section in " + part.filename);
8554
+ continue;
8555
+ }
8556
+ bodiesChecked += 1;
8557
+ const bytes = Buffer.byteLength(section.body, "utf8");
8558
+ const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
8559
+ if (bytes !== file.includedBytes) {
8560
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
8561
+ } else if (bodyLines !== file.includedLines) {
8562
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedLines + " line(s), part holds " + bodyLines);
8563
+ }
8564
+ }
8565
+ }
8566
+ checks.push(
8567
+ bodyProblems.length === 0 ? check(
8568
+ "pipeline.bodies",
8569
+ "Every file body matches the manifest accounting",
8570
+ "critical",
8571
+ "pass",
8572
+ bodiesChecked + " file body/bodies match their recorded bytes and lines."
8573
+ ) : check(
8574
+ "pipeline.bodies",
8575
+ "Every file body matches the manifest accounting",
8576
+ "critical",
8577
+ "fail",
8578
+ bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
8579
+ )
8580
+ );
8581
+ const indexParent = path5__namespace.dirname(snapshotDir);
8582
+ const indexPath = path5__namespace.join(indexParent, "WORKSPACE.json");
8583
+ if (fs2__namespace.existsSync(indexPath)) {
8584
+ const indexText = readText(indexPath);
8585
+ let members = [];
8586
+ let problem2 = null;
8587
+ try {
8588
+ const parsed = JSON.parse(indexText ?? "null");
8589
+ if (!Array.isArray(parsed?.members)) problem2 = "its members field is not an array";
8590
+ else members = parsed.members;
8591
+ } catch (error) {
8592
+ problem2 = error.message;
8593
+ }
8594
+ const memberName = path5__namespace.basename(snapshotDir);
8595
+ const member = members.find((entry) => entry.name === memberName);
8596
+ if (problem2 !== null) {
8597
+ checks.push(check(
8598
+ "workspace.index",
8599
+ "The workspace index agrees with this member",
8600
+ "warning",
8601
+ "warn",
8602
+ "WORKSPACE.json could not be read: " + problem2
8603
+ ));
8604
+ } else if (member === void 0) {
8605
+ checks.push(check(
8606
+ "workspace.index",
8607
+ "The workspace index agrees with this member",
8608
+ "warning",
8609
+ "skip",
8610
+ "WORKSPACE.json lists no member named " + memberName + "."
8611
+ ));
8612
+ } else {
8613
+ const disagreements = [];
8614
+ if (member.fingerprint !== manifest.fingerprint) disagreements.push("fingerprint");
8615
+ if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
8616
+ disagreements.push("file count");
8617
+ }
8618
+ checks.push(
8619
+ disagreements.length === 0 ? check(
8620
+ "workspace.index",
8621
+ "The workspace index agrees with this member",
8622
+ "warning",
8623
+ "pass",
8624
+ "Member " + memberName + " matches the index fingerprint and file count."
8625
+ ) : check(
8626
+ "workspace.index",
8627
+ "The workspace index agrees with this member",
8628
+ "warning",
8629
+ "warn",
8630
+ "The index disagrees with this member on: " + disagreements.join(", ") + ". Regenerate the workspace."
8631
+ )
8632
+ );
8633
+ }
8634
+ }
8341
8635
  const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
8342
8636
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
8343
8637
  const leakHits = [];
@@ -8849,90 +9143,6 @@ function generateInWorker(cwd, cliOptions, options = {}) {
8849
9143
  }
8850
9144
 
8851
9145
  // src/mcp/part.ts
8852
- var FILE_HEADING = "### FILE: ";
8853
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
8854
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
8855
- var META_PREFIX = "- Meta: ";
8856
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
8857
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
8858
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
8859
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
8860
- function readIncludedLines(fields) {
8861
- const last = fields[fields.length - 1];
8862
- if (last === void 0) return null;
8863
- const counts = COMPACT_COUNTS.exec(last.trim());
8864
- return counts === null ? null : Number(counts[1]);
8865
- }
8866
- function parsePartSections(partText) {
8867
- const lines = partText.split("\n");
8868
- const sections = [];
8869
- let index = 0;
8870
- while (index < lines.length) {
8871
- if (!lines[index].startsWith(FILE_HEADING)) {
8872
- index += 1;
8873
- continue;
8874
- }
8875
- const heading = lines[index].slice(FILE_HEADING.length);
8876
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
8877
- let cursor = index + 1;
8878
- let inclusion = null;
8879
- let includedLines = null;
8880
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
8881
- const line = lines[cursor];
8882
- if (line.startsWith(FILE_HEADING)) break;
8883
- if (line.startsWith(META_PREFIX)) {
8884
- const fields = line.slice(META_PREFIX.length).split("|");
8885
- for (const field of fields) {
8886
- const value = field.trim();
8887
- if (INCLUSION_MODES.has(value)) inclusion = value;
8888
- }
8889
- includedLines = readIncludedLines(fields);
8890
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
8891
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
8892
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
8893
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
8894
- includedLines = Number.isFinite(value) ? value : null;
8895
- }
8896
- cursor += 1;
8897
- }
8898
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
8899
- index = cursor + 1;
8900
- continue;
8901
- }
8902
- let fenceLine = cursor + 1;
8903
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
8904
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
8905
- if (!fenceMatch) {
8906
- index = cursor + 1;
8907
- continue;
8908
- }
8909
- const fence = fenceMatch[1];
8910
- const body = [];
8911
- let bodyLine = fenceLine + 1;
8912
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
8913
- body.push(lines[bodyLine]);
8914
- bodyLine += 1;
8915
- }
8916
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
8917
- index = bodyLine + 1;
8918
- }
8919
- return sections;
8920
- }
8921
- function findSection(sections, relativePath) {
8922
- const anchor = anchorForPath(relativePath);
8923
- const byAnchor = sections.find((section) => section.anchor === anchor);
8924
- if (byAnchor) return byAnchor;
8925
- const rendered = displayPath(relativePath);
8926
- const samePath = (section) => section.path === relativePath || section.path === rendered;
8927
- const exact = sections.find(samePath);
8928
- if (exact) return exact;
8929
- const foldedPath = rendered.toLowerCase();
8930
- const folded = sections.filter((section) => {
8931
- const path16 = section.path.toLowerCase();
8932
- return path16 === relativePath.toLowerCase() || path16 === foldedPath;
8933
- });
8934
- return folded.length === 1 ? folded[0] : null;
8935
- }
8936
9146
  function windowText(body, fromLine, lineCount) {
8937
9147
  const lines = body.split("\n");
8938
9148
  const total = body.length === 0 ? 0 : lines.length;
@@ -10050,6 +10260,11 @@ var symbolTool = {
10050
10260
  name: { type: "string", description: "Symbol name, case-insensitive." },
10051
10261
  lines: { type: "integer", description: "Window size around the definition (default 40).", minimum: 5 },
10052
10262
  maxFiles: { type: "integer", description: "Cap on files searched (default 5).", minimum: 1 },
10263
+ references: {
10264
+ type: "boolean",
10265
+ description: "Also report call sites: other files whose body mentions the name (default true)."
10266
+ },
10267
+ maxReferences: { type: "integer", description: "Cap on reported call sites (default 20).", minimum: 1 },
10053
10268
  root: ROOT_PROPERTY,
10054
10269
  outDir: OUT_DIR_PROPERTY
10055
10270
  },
@@ -10060,7 +10275,8 @@ var symbolTool = {
10060
10275
  type: "object",
10061
10276
  properties: {
10062
10277
  found: { type: "integer" },
10063
- matches: { type: "array", items: { type: "object" } }
10278
+ matches: { type: "array", items: { type: "object" } },
10279
+ references: { type: "array", items: { type: "object" } }
10064
10280
  }
10065
10281
  },
10066
10282
  annotations: READ_ONLY,
@@ -10113,8 +10329,44 @@ var symbolTool = {
10113
10329
  structured: { found: 0, matches: [] }
10114
10330
  };
10115
10331
  }
10116
- const text = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n");
10117
- return { text, structured: { found: matches.length, matches } };
10332
+ const callSites = [];
10333
+ if (args.references !== false) {
10334
+ const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
10335
+ const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
10336
+ const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
10337
+ const parts = /* @__PURE__ */ new Map();
10338
+ let scanned = 0;
10339
+ for (const file of read.manifest.files) {
10340
+ if (callSites.length >= limit) break;
10341
+ const partPath = partPathFor(workspace, file.part);
10342
+ if (partPath === null) continue;
10343
+ let partText = parts.get(partPath);
10344
+ if (partText === void 0) {
10345
+ try {
10346
+ partText = fs2__namespace.readFileSync(partPath, "utf8");
10347
+ } catch {
10348
+ continue;
10349
+ }
10350
+ parts.set(partPath, partText);
10351
+ }
10352
+ if (scanned > MAX_SEARCH_BYTES) break;
10353
+ scanned += Buffer.byteLength(partText, "utf8");
10354
+ const section = findSection(parsePartSections(partText), file.relativePath);
10355
+ if (section === null) continue;
10356
+ const bodyLines = section.body.split("\n");
10357
+ for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
10358
+ if (!word.test(bodyLines[index])) continue;
10359
+ callSites.push({
10360
+ path: file.relativePath,
10361
+ line: index + 1,
10362
+ text: bodyLines[index].trim().slice(0, 200),
10363
+ definition: definitionKeys.has(file.relativePath + ":" + (index + 1))
10364
+ });
10365
+ }
10366
+ }
10367
+ }
10368
+ const text = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n") + (args.references === false ? "" : "\n\n" + (callSites.length === 0 ? "No call site was found in the snapshot." : "Call sites (" + callSites.length + "):\n" + callSites.map((site) => " " + site.path + ":" + site.line + " " + site.text).join("\n")));
10369
+ return { text, structured: { found: matches.length, matches, references: callSites } };
10118
10370
  }
10119
10371
  };
10120
10372
  var contextTool = {
@@ -11387,6 +11639,8 @@ var VALIDATE_OPTIONS = [
11387
11639
  "sarif",
11388
11640
  "strip-comments",
11389
11641
  "remove-empty-lines",
11642
+ "only",
11643
+ "ignore",
11390
11644
  "pack",
11391
11645
  // The opt-in reports change the artifact selection the manifest records, so validate must accept
11392
11646
  // them to compare like with like: without the flags it reports the selection as drift.
@@ -11422,6 +11676,8 @@ var COMMAND_OPTION_SCOPE = {
11422
11676
  generate: [
11423
11677
  "strip-comments",
11424
11678
  "remove-empty-lines",
11679
+ "only",
11680
+ "ignore",
11425
11681
  "workspace",
11426
11682
  "budget-tokens",
11427
11683
  "sign",
@@ -11502,6 +11758,10 @@ var COMMAND_OPTION_SCOPE = {
11502
11758
  // Removed rather than implemented, because a flag that parses and does nothing is the defect
11503
11759
  // this table exists to prevent.
11504
11760
  "large-file-bytes",
11761
+ // `--only` and `--ignore` change which files are scanned, so they change what `explain` can say
11762
+ // about a path; without them the answer for an ignored file is "included: true".
11763
+ "only",
11764
+ "ignore",
11505
11765
  "include-sensitive-files",
11506
11766
  "no-config",
11507
11767
  "discovery",
@@ -11974,6 +12234,18 @@ function buildAgentContract() {
11974
12234
  appliesTo: optionAppliesTo("allow-origin"),
11975
12235
  summary: "mcp --http: comma-separated extra CORS origins. Loopback origins are always allowed."
11976
12236
  },
12237
+ {
12238
+ flag: "--only",
12239
+ type: "string",
12240
+ summary: "Comma-separated globs to include: overrides the config include list for this run.",
12241
+ appliesTo: optionAppliesTo("only")
12242
+ },
12243
+ {
12244
+ flag: "--ignore",
12245
+ type: "string",
12246
+ summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
12247
+ appliesTo: optionAppliesTo("ignore")
12248
+ },
11977
12249
  {
11978
12250
  flag: "--remove-empty-lines",
11979
12251
  type: "boolean",
@@ -13203,12 +13475,23 @@ async function startHttpTransport(options) {
13203
13475
  return fromQuery !== null && timingSafeEqual2(fromQuery, token);
13204
13476
  };
13205
13477
  const sessions = /* @__PURE__ */ new Map();
13478
+ const metrics = {
13479
+ requests: 0,
13480
+ byMethod: /* @__PURE__ */ new Map(),
13481
+ refused: 0,
13482
+ rateLimited: 0};
13483
+ const noteRequest = (request) => {
13484
+ metrics.requests += 1;
13485
+ const method = request.method ?? "UNKNOWN";
13486
+ metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
13487
+ };
13206
13488
  const allowedOrigin = (origin) => {
13207
13489
  if (origin === void 0) return null;
13208
13490
  if (isLoopbackOrigin(origin)) return origin;
13209
13491
  return extraOrigins.includes(origin) ? origin : null;
13210
13492
  };
13211
13493
  const httpServer = http__namespace.createServer((request, response) => {
13494
+ noteRequest(request);
13212
13495
  const send = (status, body, extra = {}) => {
13213
13496
  const text = typeof body === "string" ? body : JSON.stringify(body);
13214
13497
  response.writeHead(status, {
@@ -13222,6 +13505,7 @@ async function startHttpTransport(options) {
13222
13505
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
13223
13506
  const allowed = allowedOrigin(origin);
13224
13507
  if (origin !== void 0 && allowed === null) {
13508
+ metrics.refused += 1;
13225
13509
  send(403, { error: "origin not allowed" });
13226
13510
  return;
13227
13511
  }
@@ -13251,6 +13535,33 @@ async function startHttpTransport(options) {
13251
13535
  );
13252
13536
  return;
13253
13537
  }
13538
+ if (request.method === "GET" && request.url === "/metrics") {
13539
+ const lines = [
13540
+ "# HELP snapshot_uptime_seconds Seconds since the process started.",
13541
+ "# TYPE snapshot_uptime_seconds gauge",
13542
+ "snapshot_uptime_seconds " + Math.round(process.uptime()),
13543
+ "# HELP snapshot_requests_total HTTP requests received.",
13544
+ "# TYPE snapshot_requests_total counter",
13545
+ "snapshot_requests_total " + metrics.requests,
13546
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
13547
+ "# TYPE snapshot_requests_refused_total counter",
13548
+ "snapshot_requests_refused_total " + metrics.refused,
13549
+ "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
13550
+ "# TYPE snapshot_requests_rate_limited_total counter",
13551
+ "snapshot_requests_rate_limited_total " + metrics.rateLimited,
13552
+ "# HELP snapshot_tools Number of tools this server serves.",
13553
+ "# TYPE snapshot_tools gauge",
13554
+ "snapshot_tools " + toolCount
13555
+ ];
13556
+ for (const [method, count] of metrics.byMethod) {
13557
+ lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
13558
+ }
13559
+ send(200, lines.join("\n") + "\n", {
13560
+ ...cors,
13561
+ "content-type": "text/plain; version=0.0.4; charset=utf-8"
13562
+ });
13563
+ return;
13564
+ }
13254
13565
  const url = new URL(request.url ?? "/", "http://localhost");
13255
13566
  if (request.method === "GET" && url.pathname === "/sse") {
13256
13567
  if (!tokenAccepted(request, url)) {
@@ -13342,6 +13653,7 @@ async function startHttpTransport(options) {
13342
13653
  const window = sessions.get(remote);
13343
13654
  if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
13344
13655
  else if (window.count >= RATE_LIMIT) {
13656
+ metrics.rateLimited += 1;
13345
13657
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
13346
13658
  return;
13347
13659
  } else window.count += 1;
package/dist/mcp.d.cts CHANGED
@@ -361,21 +361,6 @@ interface StripResult {
361
361
  }
362
362
  declare function stripComments(text: string, relativePath: string): StripResult;
363
363
 
364
- /**
365
- * Reads one file's section back out of a rendered part.
366
- *
367
- * `snapshot_read` must not open the working tree. The snapshot is the contract: sensitive files
368
- * are excluded from it, secret-shaped strings inside ordinary files are redacted on the way in,
369
- * and a large file is emitted as a bounded preview. Reading the source directly would hand the
370
- * model the `.env` the snapshot deliberately skipped and the credential it masked — so the read
371
- * goes through the artifact instead.
372
- *
373
- * The format it parses is written by `renderFileSection`, and the parser is deliberately tied to
374
- * that shape rather than to a regex over the whole document: a file's *content* may legitimately
375
- * contain a line that looks like `### FILE: something`, and only fence tracking tells the two
376
- * apart. Content fences are four or more backticks (`fenceForContent` never emits three), which
377
- * is what makes "the next line equal to this exact fence" an unambiguous terminator.
378
- */
379
364
  interface PartSection {
380
365
  /** The path as rendered in the `### FILE:` heading. */
381
366
  path: string;
@@ -403,6 +388,12 @@ declare function parsePartSections(partText: string): PartSection[];
403
388
  * was read, or a part whose anchor line was edited by hand.
404
389
  */
405
390
  declare function findSection(sections: readonly PartSection[], relativePath: string): PartSection | null;
391
+
392
+ /**
393
+ * The MCP reader's view of a part: parsing lives in `partitioner/part-format.ts` so the auditor
394
+ * can use the same parser, and this module adds the windowing the tools need.
395
+ */
396
+
406
397
  interface Window {
407
398
  text: string;
408
399
  fromLine: number;
package/dist/mcp.d.ts CHANGED
@@ -361,21 +361,6 @@ interface StripResult {
361
361
  }
362
362
  declare function stripComments(text: string, relativePath: string): StripResult;
363
363
 
364
- /**
365
- * Reads one file's section back out of a rendered part.
366
- *
367
- * `snapshot_read` must not open the working tree. The snapshot is the contract: sensitive files
368
- * are excluded from it, secret-shaped strings inside ordinary files are redacted on the way in,
369
- * and a large file is emitted as a bounded preview. Reading the source directly would hand the
370
- * model the `.env` the snapshot deliberately skipped and the credential it masked — so the read
371
- * goes through the artifact instead.
372
- *
373
- * The format it parses is written by `renderFileSection`, and the parser is deliberately tied to
374
- * that shape rather than to a regex over the whole document: a file's *content* may legitimately
375
- * contain a line that looks like `### FILE: something`, and only fence tracking tells the two
376
- * apart. Content fences are four or more backticks (`fenceForContent` never emits three), which
377
- * is what makes "the next line equal to this exact fence" an unambiguous terminator.
378
- */
379
364
  interface PartSection {
380
365
  /** The path as rendered in the `### FILE:` heading. */
381
366
  path: string;
@@ -403,6 +388,12 @@ declare function parsePartSections(partText: string): PartSection[];
403
388
  * was read, or a part whose anchor line was edited by hand.
404
389
  */
405
390
  declare function findSection(sections: readonly PartSection[], relativePath: string): PartSection | null;
391
+
392
+ /**
393
+ * The MCP reader's view of a part: parsing lives in `partitioner/part-format.ts` so the auditor
394
+ * can use the same parser, and this module adds the windowing the tools need.
395
+ */
396
+
406
397
  interface Window {
407
398
  text: string;
408
399
  fromLine: number;