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/bin.js CHANGED
@@ -2191,7 +2191,7 @@ function applySpansKeepingQuotes(line, spans) {
2191
2191
 
2192
2192
  // src/version.ts
2193
2193
  var GENERATOR_NAME = "codebase-snapshot";
2194
- var GENERATOR_VERSION = "0.13.0";
2194
+ var GENERATOR_VERSION = "0.15.0";
2195
2195
  var SCHEMA_VERSION = "3.0.0";
2196
2196
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2197
2197
  function isOurGeneratorName(name) {
@@ -4352,7 +4352,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4352
4352
  logCount: resolveLogCount(
4353
4353
  cliOptions?.logCount ?? cliOptions?.includeLogs ?? userConfig?.logCount
4354
4354
  ),
4355
- include: resolveInclude(userConfig?.include),
4355
+ // `--only` replaces the allow-list for this run; `--ignore` adds to the deny-list. The two
4356
+ // directions are different on purpose: a narrower allow-list is a statement about the whole
4357
+ // run, while "also ignore this" is naturally cumulative with what the config already excludes.
4358
+ include: resolveInclude(
4359
+ cliOptions?.only ?? userConfig?.include
4360
+ ),
4356
4361
  preset: preset.presetName,
4357
4362
  presetExclude,
4358
4363
  artifacts,
@@ -4363,9 +4368,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4363
4368
  kinds,
4364
4369
  // `exclude` is the flag spelling of the same setting; writing it in a config used to
4365
4370
  // be ignored without a word.
4366
- excludePatterns: resolveExcludePatterns(
4367
- userConfig?.excludePatterns ?? userConfig?.exclude
4368
- ),
4371
+ excludePatterns: [
4372
+ ...resolveExcludePatterns(
4373
+ userConfig?.excludePatterns ?? userConfig?.exclude
4374
+ ),
4375
+ ...resolveExcludePatterns(cliOptions?.ignore)
4376
+ ],
4369
4377
  secretRules,
4370
4378
  // Extra property rather than a `ResolvedSnapshotConfig` field: the resolved
4371
4379
  // shape is owned elsewhere, and every scan reads it through the registry in
@@ -11878,6 +11886,92 @@ function verifySnapshotSignature(snapshotDir) {
11878
11886
  return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
11879
11887
  }
11880
11888
 
11889
+ // src/partitioner/part-format.ts
11890
+ var FILE_HEADING = "### FILE: ";
11891
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
11892
+ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
11893
+ var META_PREFIX = "- Meta: ";
11894
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
11895
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
11896
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
11897
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
11898
+ function readIncludedLines(fields) {
11899
+ const last = fields[fields.length - 1];
11900
+ if (last === void 0) return null;
11901
+ const counts = COMPACT_COUNTS.exec(last.trim());
11902
+ return counts === null ? null : Number(counts[1]);
11903
+ }
11904
+ function parsePartSections(partText) {
11905
+ const lines = partText.split("\n");
11906
+ const sections = [];
11907
+ let index = 0;
11908
+ while (index < lines.length) {
11909
+ if (!lines[index].startsWith(FILE_HEADING)) {
11910
+ index += 1;
11911
+ continue;
11912
+ }
11913
+ const heading = lines[index].slice(FILE_HEADING.length);
11914
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
11915
+ let cursor = index + 1;
11916
+ let inclusion = null;
11917
+ let includedLines = null;
11918
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
11919
+ const line = lines[cursor];
11920
+ if (line.startsWith(FILE_HEADING)) break;
11921
+ if (line.startsWith(META_PREFIX)) {
11922
+ const fields = line.slice(META_PREFIX.length).split("|");
11923
+ for (const field of fields) {
11924
+ const value = field.trim();
11925
+ if (INCLUSION_MODES.has(value)) inclusion = value;
11926
+ }
11927
+ includedLines = readIncludedLines(fields);
11928
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
11929
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
11930
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
11931
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
11932
+ includedLines = Number.isFinite(value) ? value : null;
11933
+ }
11934
+ cursor += 1;
11935
+ }
11936
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
11937
+ index = cursor + 1;
11938
+ continue;
11939
+ }
11940
+ let fenceLine = cursor + 1;
11941
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
11942
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
11943
+ if (!fenceMatch) {
11944
+ index = cursor + 1;
11945
+ continue;
11946
+ }
11947
+ const fence = fenceMatch[1];
11948
+ const body = [];
11949
+ let bodyLine = fenceLine + 1;
11950
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
11951
+ body.push(lines[bodyLine]);
11952
+ bodyLine += 1;
11953
+ }
11954
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
11955
+ index = bodyLine + 1;
11956
+ }
11957
+ return sections;
11958
+ }
11959
+ function findSection(sections, relativePath) {
11960
+ const anchor = anchorForPath(relativePath);
11961
+ const byAnchor = sections.find((section) => section.anchor === anchor);
11962
+ if (byAnchor) return byAnchor;
11963
+ const rendered = displayPath(relativePath);
11964
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
11965
+ const exact = sections.find(samePath);
11966
+ if (exact) return exact;
11967
+ const foldedPath = rendered.toLowerCase();
11968
+ const folded = sections.filter((section) => {
11969
+ const path28 = section.path.toLowerCase();
11970
+ return path28 === relativePath.toLowerCase() || path28 === foldedPath;
11971
+ });
11972
+ return folded.length === 1 ? folded[0] : null;
11973
+ }
11974
+
11881
11975
  // src/auditor/health.ts
11882
11976
  var ARTIFACT_FILES = {
11883
11977
  readme: "README.md",
@@ -12187,6 +12281,206 @@ function auditSnapshot(options) {
12187
12281
  )
12188
12282
  );
12189
12283
  }
12284
+ const bookkeeping = [];
12285
+ const expect = (name, recorded2, computed) => {
12286
+ if (recorded2 !== computed) bookkeeping.push(name + ": manifest says " + recorded2 + ", the data has " + computed);
12287
+ };
12288
+ expect("counts.totalFiles", manifest.counts.totalFiles, manifest.files.length);
12289
+ expect("counts.partsCount", manifest.counts.partsCount, manifest.parts.length);
12290
+ expect("counts.skippedCount", manifest.counts.skippedCount, manifest.skipped.length);
12291
+ if (typeof manifest.totals.includedFiles === "number") {
12292
+ expect("totals.includedFiles", manifest.totals.includedFiles, manifest.files.length);
12293
+ }
12294
+ const contentBytes = manifest.files.reduce((sum, file) => sum + file.includedBytes, 0);
12295
+ expect("totals.totalContentBytes", manifest.totals.totalContentBytes, contentBytes);
12296
+ const layerCounts = /* @__PURE__ */ new Map();
12297
+ for (const file of manifest.files) layerCounts.set(file.layer, (layerCounts.get(file.layer) ?? 0) + 1);
12298
+ for (const [layer2, count] of layerCounts) {
12299
+ expect("layers." + layer2, manifest.layers[layer2] ?? -1, count);
12300
+ }
12301
+ for (const layer2 of Object.keys(manifest.layers)) {
12302
+ if (!layerCounts.has(layer2)) expect("layers." + layer2, manifest.layers[layer2], 0);
12303
+ }
12304
+ checks.push(
12305
+ bookkeeping.length === 0 ? check(
12306
+ "bookkeeping",
12307
+ "The counts equal the data they summarise",
12308
+ "critical",
12309
+ "pass",
12310
+ "Files, parts, skips, content bytes and layer counts all agree."
12311
+ ) : check(
12312
+ "bookkeeping",
12313
+ "The counts equal the data they summarise",
12314
+ "critical",
12315
+ "fail",
12316
+ bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
12317
+ )
12318
+ );
12319
+ const packReaders = [
12320
+ {
12321
+ key: "fullJson",
12322
+ file: "full-codebase.json",
12323
+ label: "JSON",
12324
+ paths: (text2) => {
12325
+ try {
12326
+ const parsed = JSON.parse(text2);
12327
+ if (!Array.isArray(parsed?.files)) return null;
12328
+ return new Set(parsed.files.map((entry) => String(entry?.relativePath)));
12329
+ } catch {
12330
+ return null;
12331
+ }
12332
+ }
12333
+ },
12334
+ {
12335
+ key: "fullXml",
12336
+ file: "full-codebase.xml",
12337
+ label: "XML",
12338
+ paths: (text2) => {
12339
+ const found = [...text2.matchAll(/<file path="([^"]+)"/g)].map((match) => match[1]);
12340
+ if (found.length === 0) return null;
12341
+ return new Set(found.map((value) => value.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")));
12342
+ }
12343
+ },
12344
+ {
12345
+ key: "fullMarkdown",
12346
+ file: "full-codebase.md",
12347
+ label: "markdown",
12348
+ paths: (text2) => {
12349
+ const found = [...text2.matchAll(/^## File: (.+)$/gm)].map((match) => match[1].trim());
12350
+ if (found.length === 0) return null;
12351
+ return new Set(found);
12352
+ }
12353
+ }
12354
+ ];
12355
+ for (const reader of packReaders) {
12356
+ if (manifest.artifacts?.[reader.key] == null) continue;
12357
+ const packText = readText2(path16.join(snapshotDir, reader.file));
12358
+ const problems = [];
12359
+ if (packText === null) {
12360
+ problems.push(reader.file + " is recorded but unreadable");
12361
+ } else {
12362
+ const packed = reader.paths(packText);
12363
+ if (packed === null) {
12364
+ problems.push(reader.file + " could not be parsed for its file list");
12365
+ } else {
12366
+ const known2 = new Set(manifest.files.map((file) => file.relativePath));
12367
+ for (const file of manifest.files) {
12368
+ if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
12369
+ }
12370
+ for (const path28 of packed) {
12371
+ if (!known2.has(path28)) problems.push(path28 + " is in the pack but not the manifest");
12372
+ }
12373
+ }
12374
+ }
12375
+ const title = "The " + reader.label + " pack holds every file the manifest lists";
12376
+ checks.push(
12377
+ problems.length === 0 ? check(
12378
+ "pipeline.monolith",
12379
+ title,
12380
+ "critical",
12381
+ "pass",
12382
+ manifest.files.length + " file(s) present in " + reader.file + ", and nothing extra."
12383
+ ) : check(
12384
+ "pipeline.monolith",
12385
+ title,
12386
+ "critical",
12387
+ "fail",
12388
+ problems.length + " problem(s): " + sample(problems)
12389
+ )
12390
+ );
12391
+ }
12392
+ const bodyProblems = [];
12393
+ let bodiesChecked = 0;
12394
+ for (const part of manifest.parts) {
12395
+ const partText = readText2(path16.join(snapshotDir, "parts", part.filename));
12396
+ if (partText === null) continue;
12397
+ const sections = parsePartSections(partText);
12398
+ for (const file of manifest.files) {
12399
+ if (file.part !== part.filename) continue;
12400
+ const section = findSection(sections, file.relativePath);
12401
+ if (section === null) {
12402
+ bodyProblems.push(file.relativePath + " has no section in " + part.filename);
12403
+ continue;
12404
+ }
12405
+ bodiesChecked += 1;
12406
+ const bytes = Buffer.byteLength(section.body, "utf8");
12407
+ const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
12408
+ if (bytes !== file.includedBytes) {
12409
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
12410
+ } else if (bodyLines !== file.includedLines) {
12411
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedLines + " line(s), part holds " + bodyLines);
12412
+ }
12413
+ }
12414
+ }
12415
+ checks.push(
12416
+ bodyProblems.length === 0 ? check(
12417
+ "pipeline.bodies",
12418
+ "Every file body matches the manifest accounting",
12419
+ "critical",
12420
+ "pass",
12421
+ bodiesChecked + " file body/bodies match their recorded bytes and lines."
12422
+ ) : check(
12423
+ "pipeline.bodies",
12424
+ "Every file body matches the manifest accounting",
12425
+ "critical",
12426
+ "fail",
12427
+ bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
12428
+ )
12429
+ );
12430
+ const indexParent = path16.dirname(snapshotDir);
12431
+ const indexPath = path16.join(indexParent, "WORKSPACE.json");
12432
+ if (fs16.existsSync(indexPath)) {
12433
+ const indexText = readText2(indexPath);
12434
+ let members = [];
12435
+ let problem2 = null;
12436
+ try {
12437
+ const parsed = JSON.parse(indexText ?? "null");
12438
+ if (!Array.isArray(parsed?.members)) problem2 = "its members field is not an array";
12439
+ else members = parsed.members;
12440
+ } catch (error) {
12441
+ problem2 = error.message;
12442
+ }
12443
+ const memberName = path16.basename(snapshotDir);
12444
+ const member = members.find((entry) => entry.name === memberName);
12445
+ if (problem2 !== null) {
12446
+ checks.push(check(
12447
+ "workspace.index",
12448
+ "The workspace index agrees with this member",
12449
+ "warning",
12450
+ "warn",
12451
+ "WORKSPACE.json could not be read: " + problem2
12452
+ ));
12453
+ } else if (member === void 0) {
12454
+ checks.push(check(
12455
+ "workspace.index",
12456
+ "The workspace index agrees with this member",
12457
+ "warning",
12458
+ "skip",
12459
+ "WORKSPACE.json lists no member named " + memberName + "."
12460
+ ));
12461
+ } else {
12462
+ const disagreements = [];
12463
+ if (member.fingerprint !== manifest.fingerprint) disagreements.push("fingerprint");
12464
+ if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12465
+ disagreements.push("file count");
12466
+ }
12467
+ checks.push(
12468
+ disagreements.length === 0 ? check(
12469
+ "workspace.index",
12470
+ "The workspace index agrees with this member",
12471
+ "warning",
12472
+ "pass",
12473
+ "Member " + memberName + " matches the index fingerprint and file count."
12474
+ ) : check(
12475
+ "workspace.index",
12476
+ "The workspace index agrees with this member",
12477
+ "warning",
12478
+ "warn",
12479
+ "The index disagrees with this member on: " + disagreements.join(", ") + ". Regenerate the workspace."
12480
+ )
12481
+ );
12482
+ }
12483
+ }
12190
12484
  const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
12191
12485
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
12192
12486
  const leakHits = [];
@@ -12465,90 +12759,6 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12465
12759
  }
12466
12760
 
12467
12761
  // src/mcp/part.ts
12468
- var FILE_HEADING = "### FILE: ";
12469
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
12470
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
12471
- var META_PREFIX = "- Meta: ";
12472
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
12473
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
12474
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
12475
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
12476
- function readIncludedLines(fields) {
12477
- const last = fields[fields.length - 1];
12478
- if (last === void 0) return null;
12479
- const counts = COMPACT_COUNTS.exec(last.trim());
12480
- return counts === null ? null : Number(counts[1]);
12481
- }
12482
- function parsePartSections(partText) {
12483
- const lines = partText.split("\n");
12484
- const sections = [];
12485
- let index = 0;
12486
- while (index < lines.length) {
12487
- if (!lines[index].startsWith(FILE_HEADING)) {
12488
- index += 1;
12489
- continue;
12490
- }
12491
- const heading = lines[index].slice(FILE_HEADING.length);
12492
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
12493
- let cursor = index + 1;
12494
- let inclusion = null;
12495
- let includedLines = null;
12496
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
12497
- const line = lines[cursor];
12498
- if (line.startsWith(FILE_HEADING)) break;
12499
- if (line.startsWith(META_PREFIX)) {
12500
- const fields = line.slice(META_PREFIX.length).split("|");
12501
- for (const field of fields) {
12502
- const value = field.trim();
12503
- if (INCLUSION_MODES.has(value)) inclusion = value;
12504
- }
12505
- includedLines = readIncludedLines(fields);
12506
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
12507
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
12508
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
12509
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
12510
- includedLines = Number.isFinite(value) ? value : null;
12511
- }
12512
- cursor += 1;
12513
- }
12514
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
12515
- index = cursor + 1;
12516
- continue;
12517
- }
12518
- let fenceLine = cursor + 1;
12519
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
12520
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
12521
- if (!fenceMatch) {
12522
- index = cursor + 1;
12523
- continue;
12524
- }
12525
- const fence = fenceMatch[1];
12526
- const body = [];
12527
- let bodyLine = fenceLine + 1;
12528
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
12529
- body.push(lines[bodyLine]);
12530
- bodyLine += 1;
12531
- }
12532
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
12533
- index = bodyLine + 1;
12534
- }
12535
- return sections;
12536
- }
12537
- function findSection(sections, relativePath) {
12538
- const anchor = anchorForPath(relativePath);
12539
- const byAnchor = sections.find((section) => section.anchor === anchor);
12540
- if (byAnchor) return byAnchor;
12541
- const rendered = displayPath(relativePath);
12542
- const samePath = (section) => section.path === relativePath || section.path === rendered;
12543
- const exact = sections.find(samePath);
12544
- if (exact) return exact;
12545
- const foldedPath = rendered.toLowerCase();
12546
- const folded = sections.filter((section) => {
12547
- const path28 = section.path.toLowerCase();
12548
- return path28 === relativePath.toLowerCase() || path28 === foldedPath;
12549
- });
12550
- return folded.length === 1 ? folded[0] : null;
12551
- }
12552
12762
  function windowText(body, fromLine, lineCount) {
12553
12763
  const lines = body.split("\n");
12554
12764
  const total = body.length === 0 ? 0 : lines.length;
@@ -13670,6 +13880,11 @@ var symbolTool = {
13670
13880
  name: { type: "string", description: "Symbol name, case-insensitive." },
13671
13881
  lines: { type: "integer", description: "Window size around the definition (default 40).", minimum: 5 },
13672
13882
  maxFiles: { type: "integer", description: "Cap on files searched (default 5).", minimum: 1 },
13883
+ references: {
13884
+ type: "boolean",
13885
+ description: "Also report call sites: other files whose body mentions the name (default true)."
13886
+ },
13887
+ maxReferences: { type: "integer", description: "Cap on reported call sites (default 20).", minimum: 1 },
13673
13888
  root: ROOT_PROPERTY,
13674
13889
  outDir: OUT_DIR_PROPERTY
13675
13890
  },
@@ -13680,7 +13895,8 @@ var symbolTool = {
13680
13895
  type: "object",
13681
13896
  properties: {
13682
13897
  found: { type: "integer" },
13683
- matches: { type: "array", items: { type: "object" } }
13898
+ matches: { type: "array", items: { type: "object" } },
13899
+ references: { type: "array", items: { type: "object" } }
13684
13900
  }
13685
13901
  },
13686
13902
  annotations: READ_ONLY,
@@ -13733,8 +13949,44 @@ var symbolTool = {
13733
13949
  structured: { found: 0, matches: [] }
13734
13950
  };
13735
13951
  }
13736
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n");
13737
- return { text: text2, structured: { found: matches.length, matches } };
13952
+ const callSites = [];
13953
+ if (args.references !== false) {
13954
+ const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13955
+ const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13956
+ const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13957
+ const parts = /* @__PURE__ */ new Map();
13958
+ let scanned = 0;
13959
+ for (const file of read.manifest.files) {
13960
+ if (callSites.length >= limit) break;
13961
+ const partPath = partPathFor(workspace, file.part);
13962
+ if (partPath === null) continue;
13963
+ let partText = parts.get(partPath);
13964
+ if (partText === void 0) {
13965
+ try {
13966
+ partText = fs18.readFileSync(partPath, "utf8");
13967
+ } catch {
13968
+ continue;
13969
+ }
13970
+ parts.set(partPath, partText);
13971
+ }
13972
+ if (scanned > MAX_SEARCH_BYTES) break;
13973
+ scanned += Buffer.byteLength(partText, "utf8");
13974
+ const section = findSection(parsePartSections(partText), file.relativePath);
13975
+ if (section === null) continue;
13976
+ const bodyLines = section.body.split("\n");
13977
+ for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
13978
+ if (!word.test(bodyLines[index])) continue;
13979
+ callSites.push({
13980
+ path: file.relativePath,
13981
+ line: index + 1,
13982
+ text: bodyLines[index].trim().slice(0, 200),
13983
+ definition: definitionKeys.has(file.relativePath + ":" + (index + 1))
13984
+ });
13985
+ }
13986
+ }
13987
+ }
13988
+ const text2 = 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")));
13989
+ return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13738
13990
  }
13739
13991
  };
13740
13992
  var contextTool = {
@@ -15038,6 +15290,8 @@ var VALIDATE_OPTIONS = [
15038
15290
  "sarif",
15039
15291
  "strip-comments",
15040
15292
  "remove-empty-lines",
15293
+ "only",
15294
+ "ignore",
15041
15295
  "pack",
15042
15296
  // The opt-in reports change the artifact selection the manifest records, so validate must accept
15043
15297
  // them to compare like with like: without the flags it reports the selection as drift.
@@ -15073,6 +15327,8 @@ var COMMAND_OPTION_SCOPE = {
15073
15327
  generate: [
15074
15328
  "strip-comments",
15075
15329
  "remove-empty-lines",
15330
+ "only",
15331
+ "ignore",
15076
15332
  "workspace",
15077
15333
  "budget-tokens",
15078
15334
  "sign",
@@ -15153,6 +15409,10 @@ var COMMAND_OPTION_SCOPE = {
15153
15409
  // Removed rather than implemented, because a flag that parses and does nothing is the defect
15154
15410
  // this table exists to prevent.
15155
15411
  "large-file-bytes",
15412
+ // `--only` and `--ignore` change which files are scanned, so they change what `explain` can say
15413
+ // about a path; without them the answer for an ignored file is "included: true".
15414
+ "only",
15415
+ "ignore",
15156
15416
  "include-sensitive-files",
15157
15417
  "no-config",
15158
15418
  "discovery",
@@ -15694,6 +15954,18 @@ function buildAgentContract() {
15694
15954
  appliesTo: optionAppliesTo("allow-origin"),
15695
15955
  summary: "mcp --http: comma-separated extra CORS origins. Loopback origins are always allowed."
15696
15956
  },
15957
+ {
15958
+ flag: "--only",
15959
+ type: "string",
15960
+ summary: "Comma-separated globs to include: overrides the config include list for this run.",
15961
+ appliesTo: optionAppliesTo("only")
15962
+ },
15963
+ {
15964
+ flag: "--ignore",
15965
+ type: "string",
15966
+ summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
15967
+ appliesTo: optionAppliesTo("ignore")
15968
+ },
15697
15969
  {
15698
15970
  flag: "--remove-empty-lines",
15699
15971
  type: "boolean",
@@ -20380,12 +20652,25 @@ async function startHttpTransport(options) {
20380
20652
  return fromQuery !== null && timingSafeEqual3(fromQuery, token);
20381
20653
  };
20382
20654
  const sessions = /* @__PURE__ */ new Map();
20655
+ const metrics = {
20656
+ requests: 0,
20657
+ byMethod: /* @__PURE__ */ new Map(),
20658
+ refused: 0,
20659
+ rateLimited: 0,
20660
+ started: Date.now()
20661
+ };
20662
+ const noteRequest = (request) => {
20663
+ metrics.requests += 1;
20664
+ const method = request.method ?? "UNKNOWN";
20665
+ metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
20666
+ };
20383
20667
  const allowedOrigin = (origin) => {
20384
20668
  if (origin === void 0) return null;
20385
20669
  if (isLoopbackOrigin(origin)) return origin;
20386
20670
  return extraOrigins.includes(origin) ? origin : null;
20387
20671
  };
20388
20672
  const httpServer = http3.createServer((request, response) => {
20673
+ noteRequest(request);
20389
20674
  const send = (status, body, extra = {}) => {
20390
20675
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
20391
20676
  response.writeHead(status, {
@@ -20399,6 +20684,7 @@ async function startHttpTransport(options) {
20399
20684
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20400
20685
  const allowed = allowedOrigin(origin);
20401
20686
  if (origin !== void 0 && allowed === null) {
20687
+ metrics.refused += 1;
20402
20688
  send(403, { error: "origin not allowed" });
20403
20689
  return;
20404
20690
  }
@@ -20428,6 +20714,33 @@ async function startHttpTransport(options) {
20428
20714
  );
20429
20715
  return;
20430
20716
  }
20717
+ if (request.method === "GET" && request.url === "/metrics") {
20718
+ const lines = [
20719
+ "# HELP snapshot_uptime_seconds Seconds since the process started.",
20720
+ "# TYPE snapshot_uptime_seconds gauge",
20721
+ "snapshot_uptime_seconds " + Math.round(process.uptime()),
20722
+ "# HELP snapshot_requests_total HTTP requests received.",
20723
+ "# TYPE snapshot_requests_total counter",
20724
+ "snapshot_requests_total " + metrics.requests,
20725
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
20726
+ "# TYPE snapshot_requests_refused_total counter",
20727
+ "snapshot_requests_refused_total " + metrics.refused,
20728
+ "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
20729
+ "# TYPE snapshot_requests_rate_limited_total counter",
20730
+ "snapshot_requests_rate_limited_total " + metrics.rateLimited,
20731
+ "# HELP snapshot_tools Number of tools this server serves.",
20732
+ "# TYPE snapshot_tools gauge",
20733
+ "snapshot_tools " + toolCount
20734
+ ];
20735
+ for (const [method, count] of metrics.byMethod) {
20736
+ lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
20737
+ }
20738
+ send(200, lines.join("\n") + "\n", {
20739
+ ...cors,
20740
+ "content-type": "text/plain; version=0.0.4; charset=utf-8"
20741
+ });
20742
+ return;
20743
+ }
20431
20744
  const url = new URL(request.url ?? "/", "http://localhost");
20432
20745
  if (request.method === "GET" && url.pathname === "/sse") {
20433
20746
  if (!tokenAccepted(request, url)) {
@@ -20519,6 +20832,7 @@ async function startHttpTransport(options) {
20519
20832
  const window = sessions.get(remote);
20520
20833
  if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
20521
20834
  else if (window.count >= RATE_LIMIT) {
20835
+ metrics.rateLimited += 1;
20522
20836
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
20523
20837
  return;
20524
20838
  } else window.count += 1;
@@ -20686,6 +21000,8 @@ var CLI_OPTIONS = {
20686
21000
  workspace: { type: "string" },
20687
21001
  "strip-comments": { type: "boolean" },
20688
21002
  "remove-empty-lines": { type: "boolean" },
21003
+ only: { type: "string" },
21004
+ ignore: { type: "string" },
20689
21005
  "all-members": { type: "boolean" },
20690
21006
  help: { type: "boolean", short: "h" },
20691
21007
  version: { type: "boolean", short: "v" }
@@ -21134,6 +21450,8 @@ function parseCliArgs(argv) {
21134
21450
  workspace: values.workspace === void 0 ? void 0 : String(values.workspace),
21135
21451
  stripComments: values["strip-comments"] === true ? true : void 0,
21136
21452
  removeEmptyLines: values["remove-empty-lines"] === true ? true : void 0,
21453
+ only: values.only === void 0 ? void 0 : String(values.only).split(",").map((item) => item.trim()).filter(Boolean),
21454
+ ignore: values.ignore === void 0 ? void 0 : String(values.ignore).split(",").map((item) => item.trim()).filter(Boolean),
21137
21455
  allMembers: values["all-members"] === true ? true : void 0,
21138
21456
  budgetTokens: values["budget-tokens"] === void 0 ? void 0 : parsePositiveInteger(values["budget-tokens"], "budget-tokens", 500),
21139
21457
  delta: values.delta === void 0 ? void 0 : String(values.delta),
@@ -21835,6 +22153,8 @@ ${USAGE}
21835
22153
  ...invocation.tokenTree === true ? { tokenTree: true } : {},
21836
22154
  ...invocation.stripComments === true ? { stripComments: true } : {},
21837
22155
  ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
22156
+ ...invocation.only === void 0 ? {} : { only: invocation.only },
22157
+ ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
21838
22158
  ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
21839
22159
  brief: invocation.brief,
21840
22160
  promptTask: invocation.promptTask,