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/cli.cjs CHANGED
@@ -2221,7 +2221,7 @@ function applySpansKeepingQuotes(line, spans) {
2221
2221
 
2222
2222
  // src/version.ts
2223
2223
  var GENERATOR_NAME = "codebase-snapshot";
2224
- var GENERATOR_VERSION = "0.13.0";
2224
+ var GENERATOR_VERSION = "0.15.0";
2225
2225
  var SCHEMA_VERSION = "3.0.0";
2226
2226
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2227
2227
  function isOurGeneratorName(name) {
@@ -4367,7 +4367,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4367
4367
  logCount: resolveLogCount(
4368
4368
  cliOptions?.logCount ?? cliOptions?.includeLogs ?? userConfig?.logCount
4369
4369
  ),
4370
- include: resolveInclude(userConfig?.include),
4370
+ // `--only` replaces the allow-list for this run; `--ignore` adds to the deny-list. The two
4371
+ // directions are different on purpose: a narrower allow-list is a statement about the whole
4372
+ // run, while "also ignore this" is naturally cumulative with what the config already excludes.
4373
+ include: resolveInclude(
4374
+ cliOptions?.only ?? userConfig?.include
4375
+ ),
4371
4376
  preset: preset.presetName,
4372
4377
  presetExclude,
4373
4378
  artifacts,
@@ -4378,9 +4383,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
4378
4383
  kinds,
4379
4384
  // `exclude` is the flag spelling of the same setting; writing it in a config used to
4380
4385
  // be ignored without a word.
4381
- excludePatterns: resolveExcludePatterns(
4382
- userConfig?.excludePatterns ?? userConfig?.exclude
4383
- ),
4386
+ excludePatterns: [
4387
+ ...resolveExcludePatterns(
4388
+ userConfig?.excludePatterns ?? userConfig?.exclude
4389
+ ),
4390
+ ...resolveExcludePatterns(cliOptions?.ignore)
4391
+ ],
4384
4392
  secretRules,
4385
4393
  // Extra property rather than a `ResolvedSnapshotConfig` field: the resolved
4386
4394
  // shape is owned elsewhere, and every scan reads it through the registry in
@@ -11777,6 +11785,92 @@ function verifySnapshotSignature(snapshotDir) {
11777
11785
  return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
11778
11786
  }
11779
11787
 
11788
+ // src/partitioner/part-format.ts
11789
+ var FILE_HEADING = "### FILE: ";
11790
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
11791
+ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
11792
+ var META_PREFIX = "- Meta: ";
11793
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
11794
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
11795
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
11796
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
11797
+ function readIncludedLines(fields) {
11798
+ const last = fields[fields.length - 1];
11799
+ if (last === void 0) return null;
11800
+ const counts = COMPACT_COUNTS.exec(last.trim());
11801
+ return counts === null ? null : Number(counts[1]);
11802
+ }
11803
+ function parsePartSections(partText) {
11804
+ const lines = partText.split("\n");
11805
+ const sections = [];
11806
+ let index = 0;
11807
+ while (index < lines.length) {
11808
+ if (!lines[index].startsWith(FILE_HEADING)) {
11809
+ index += 1;
11810
+ continue;
11811
+ }
11812
+ const heading = lines[index].slice(FILE_HEADING.length);
11813
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
11814
+ let cursor = index + 1;
11815
+ let inclusion = null;
11816
+ let includedLines = null;
11817
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
11818
+ const line = lines[cursor];
11819
+ if (line.startsWith(FILE_HEADING)) break;
11820
+ if (line.startsWith(META_PREFIX)) {
11821
+ const fields = line.slice(META_PREFIX.length).split("|");
11822
+ for (const field of fields) {
11823
+ const value = field.trim();
11824
+ if (INCLUSION_MODES.has(value)) inclusion = value;
11825
+ }
11826
+ includedLines = readIncludedLines(fields);
11827
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
11828
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
11829
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
11830
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
11831
+ includedLines = Number.isFinite(value) ? value : null;
11832
+ }
11833
+ cursor += 1;
11834
+ }
11835
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
11836
+ index = cursor + 1;
11837
+ continue;
11838
+ }
11839
+ let fenceLine = cursor + 1;
11840
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
11841
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
11842
+ if (!fenceMatch) {
11843
+ index = cursor + 1;
11844
+ continue;
11845
+ }
11846
+ const fence = fenceMatch[1];
11847
+ const body = [];
11848
+ let bodyLine = fenceLine + 1;
11849
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
11850
+ body.push(lines[bodyLine]);
11851
+ bodyLine += 1;
11852
+ }
11853
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
11854
+ index = bodyLine + 1;
11855
+ }
11856
+ return sections;
11857
+ }
11858
+ function findSection(sections, relativePath) {
11859
+ const anchor = anchorForPath(relativePath);
11860
+ const byAnchor = sections.find((section) => section.anchor === anchor);
11861
+ if (byAnchor) return byAnchor;
11862
+ const rendered = displayPath(relativePath);
11863
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
11864
+ const exact = sections.find(samePath);
11865
+ if (exact) return exact;
11866
+ const foldedPath = rendered.toLowerCase();
11867
+ const folded = sections.filter((section) => {
11868
+ const path28 = section.path.toLowerCase();
11869
+ return path28 === relativePath.toLowerCase() || path28 === foldedPath;
11870
+ });
11871
+ return folded.length === 1 ? folded[0] : null;
11872
+ }
11873
+
11780
11874
  // src/auditor/health.ts
11781
11875
  var ARTIFACT_FILES = {
11782
11876
  readme: "README.md",
@@ -12086,6 +12180,206 @@ function auditSnapshot(options) {
12086
12180
  )
12087
12181
  );
12088
12182
  }
12183
+ const bookkeeping = [];
12184
+ const expect = (name, recorded2, computed) => {
12185
+ if (recorded2 !== computed) bookkeeping.push(name + ": manifest says " + recorded2 + ", the data has " + computed);
12186
+ };
12187
+ expect("counts.totalFiles", manifest.counts.totalFiles, manifest.files.length);
12188
+ expect("counts.partsCount", manifest.counts.partsCount, manifest.parts.length);
12189
+ expect("counts.skippedCount", manifest.counts.skippedCount, manifest.skipped.length);
12190
+ if (typeof manifest.totals.includedFiles === "number") {
12191
+ expect("totals.includedFiles", manifest.totals.includedFiles, manifest.files.length);
12192
+ }
12193
+ const contentBytes = manifest.files.reduce((sum, file) => sum + file.includedBytes, 0);
12194
+ expect("totals.totalContentBytes", manifest.totals.totalContentBytes, contentBytes);
12195
+ const layerCounts = /* @__PURE__ */ new Map();
12196
+ for (const file of manifest.files) layerCounts.set(file.layer, (layerCounts.get(file.layer) ?? 0) + 1);
12197
+ for (const [layer2, count] of layerCounts) {
12198
+ expect("layers." + layer2, manifest.layers[layer2] ?? -1, count);
12199
+ }
12200
+ for (const layer2 of Object.keys(manifest.layers)) {
12201
+ if (!layerCounts.has(layer2)) expect("layers." + layer2, manifest.layers[layer2], 0);
12202
+ }
12203
+ checks.push(
12204
+ bookkeeping.length === 0 ? check(
12205
+ "bookkeeping",
12206
+ "The counts equal the data they summarise",
12207
+ "critical",
12208
+ "pass",
12209
+ "Files, parts, skips, content bytes and layer counts all agree."
12210
+ ) : check(
12211
+ "bookkeeping",
12212
+ "The counts equal the data they summarise",
12213
+ "critical",
12214
+ "fail",
12215
+ bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
12216
+ )
12217
+ );
12218
+ const packReaders = [
12219
+ {
12220
+ key: "fullJson",
12221
+ file: "full-codebase.json",
12222
+ label: "JSON",
12223
+ paths: (text2) => {
12224
+ try {
12225
+ const parsed = JSON.parse(text2);
12226
+ if (!Array.isArray(parsed?.files)) return null;
12227
+ return new Set(parsed.files.map((entry) => String(entry?.relativePath)));
12228
+ } catch {
12229
+ return null;
12230
+ }
12231
+ }
12232
+ },
12233
+ {
12234
+ key: "fullXml",
12235
+ file: "full-codebase.xml",
12236
+ label: "XML",
12237
+ paths: (text2) => {
12238
+ const found = [...text2.matchAll(/<file path="([^"]+)"/g)].map((match) => match[1]);
12239
+ if (found.length === 0) return null;
12240
+ return new Set(found.map((value) => value.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")));
12241
+ }
12242
+ },
12243
+ {
12244
+ key: "fullMarkdown",
12245
+ file: "full-codebase.md",
12246
+ label: "markdown",
12247
+ paths: (text2) => {
12248
+ const found = [...text2.matchAll(/^## File: (.+)$/gm)].map((match) => match[1].trim());
12249
+ if (found.length === 0) return null;
12250
+ return new Set(found);
12251
+ }
12252
+ }
12253
+ ];
12254
+ for (const reader of packReaders) {
12255
+ if (manifest.artifacts?.[reader.key] == null) continue;
12256
+ const packText = readText2(path27__namespace.join(snapshotDir, reader.file));
12257
+ const problems = [];
12258
+ if (packText === null) {
12259
+ problems.push(reader.file + " is recorded but unreadable");
12260
+ } else {
12261
+ const packed = reader.paths(packText);
12262
+ if (packed === null) {
12263
+ problems.push(reader.file + " could not be parsed for its file list");
12264
+ } else {
12265
+ const known2 = new Set(manifest.files.map((file) => file.relativePath));
12266
+ for (const file of manifest.files) {
12267
+ if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
12268
+ }
12269
+ for (const path28 of packed) {
12270
+ if (!known2.has(path28)) problems.push(path28 + " is in the pack but not the manifest");
12271
+ }
12272
+ }
12273
+ }
12274
+ const title = "The " + reader.label + " pack holds every file the manifest lists";
12275
+ checks.push(
12276
+ problems.length === 0 ? check(
12277
+ "pipeline.monolith",
12278
+ title,
12279
+ "critical",
12280
+ "pass",
12281
+ manifest.files.length + " file(s) present in " + reader.file + ", and nothing extra."
12282
+ ) : check(
12283
+ "pipeline.monolith",
12284
+ title,
12285
+ "critical",
12286
+ "fail",
12287
+ problems.length + " problem(s): " + sample(problems)
12288
+ )
12289
+ );
12290
+ }
12291
+ const bodyProblems = [];
12292
+ let bodiesChecked = 0;
12293
+ for (const part of manifest.parts) {
12294
+ const partText = readText2(path27__namespace.join(snapshotDir, "parts", part.filename));
12295
+ if (partText === null) continue;
12296
+ const sections = parsePartSections(partText);
12297
+ for (const file of manifest.files) {
12298
+ if (file.part !== part.filename) continue;
12299
+ const section = findSection(sections, file.relativePath);
12300
+ if (section === null) {
12301
+ bodyProblems.push(file.relativePath + " has no section in " + part.filename);
12302
+ continue;
12303
+ }
12304
+ bodiesChecked += 1;
12305
+ const bytes = Buffer.byteLength(section.body, "utf8");
12306
+ const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
12307
+ if (bytes !== file.includedBytes) {
12308
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
12309
+ } else if (bodyLines !== file.includedLines) {
12310
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedLines + " line(s), part holds " + bodyLines);
12311
+ }
12312
+ }
12313
+ }
12314
+ checks.push(
12315
+ bodyProblems.length === 0 ? check(
12316
+ "pipeline.bodies",
12317
+ "Every file body matches the manifest accounting",
12318
+ "critical",
12319
+ "pass",
12320
+ bodiesChecked + " file body/bodies match their recorded bytes and lines."
12321
+ ) : check(
12322
+ "pipeline.bodies",
12323
+ "Every file body matches the manifest accounting",
12324
+ "critical",
12325
+ "fail",
12326
+ bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
12327
+ )
12328
+ );
12329
+ const indexParent = path27__namespace.dirname(snapshotDir);
12330
+ const indexPath = path27__namespace.join(indexParent, "WORKSPACE.json");
12331
+ if (fs24__namespace.existsSync(indexPath)) {
12332
+ const indexText = readText2(indexPath);
12333
+ let members = [];
12334
+ let problem2 = null;
12335
+ try {
12336
+ const parsed = JSON.parse(indexText ?? "null");
12337
+ if (!Array.isArray(parsed?.members)) problem2 = "its members field is not an array";
12338
+ else members = parsed.members;
12339
+ } catch (error) {
12340
+ problem2 = error.message;
12341
+ }
12342
+ const memberName = path27__namespace.basename(snapshotDir);
12343
+ const member = members.find((entry) => entry.name === memberName);
12344
+ if (problem2 !== null) {
12345
+ checks.push(check(
12346
+ "workspace.index",
12347
+ "The workspace index agrees with this member",
12348
+ "warning",
12349
+ "warn",
12350
+ "WORKSPACE.json could not be read: " + problem2
12351
+ ));
12352
+ } else if (member === void 0) {
12353
+ checks.push(check(
12354
+ "workspace.index",
12355
+ "The workspace index agrees with this member",
12356
+ "warning",
12357
+ "skip",
12358
+ "WORKSPACE.json lists no member named " + memberName + "."
12359
+ ));
12360
+ } else {
12361
+ const disagreements = [];
12362
+ if (member.fingerprint !== manifest.fingerprint) disagreements.push("fingerprint");
12363
+ if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
12364
+ disagreements.push("file count");
12365
+ }
12366
+ checks.push(
12367
+ disagreements.length === 0 ? check(
12368
+ "workspace.index",
12369
+ "The workspace index agrees with this member",
12370
+ "warning",
12371
+ "pass",
12372
+ "Member " + memberName + " matches the index fingerprint and file count."
12373
+ ) : check(
12374
+ "workspace.index",
12375
+ "The workspace index agrees with this member",
12376
+ "warning",
12377
+ "warn",
12378
+ "The index disagrees with this member on: " + disagreements.join(", ") + ". Regenerate the workspace."
12379
+ )
12380
+ );
12381
+ }
12382
+ }
12089
12383
  const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
12090
12384
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
12091
12385
  const leakHits = [];
@@ -12359,90 +12653,6 @@ function generateInWorker(cwd, cliOptions, options = {}) {
12359
12653
  }
12360
12654
 
12361
12655
  // src/mcp/part.ts
12362
- var FILE_HEADING = "### FILE: ";
12363
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
12364
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
12365
- var META_PREFIX = "- Meta: ";
12366
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
12367
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
12368
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
12369
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
12370
- function readIncludedLines(fields) {
12371
- const last = fields[fields.length - 1];
12372
- if (last === void 0) return null;
12373
- const counts = COMPACT_COUNTS.exec(last.trim());
12374
- return counts === null ? null : Number(counts[1]);
12375
- }
12376
- function parsePartSections(partText) {
12377
- const lines = partText.split("\n");
12378
- const sections = [];
12379
- let index = 0;
12380
- while (index < lines.length) {
12381
- if (!lines[index].startsWith(FILE_HEADING)) {
12382
- index += 1;
12383
- continue;
12384
- }
12385
- const heading = lines[index].slice(FILE_HEADING.length);
12386
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
12387
- let cursor = index + 1;
12388
- let inclusion = null;
12389
- let includedLines = null;
12390
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
12391
- const line = lines[cursor];
12392
- if (line.startsWith(FILE_HEADING)) break;
12393
- if (line.startsWith(META_PREFIX)) {
12394
- const fields = line.slice(META_PREFIX.length).split("|");
12395
- for (const field of fields) {
12396
- const value = field.trim();
12397
- if (INCLUSION_MODES.has(value)) inclusion = value;
12398
- }
12399
- includedLines = readIncludedLines(fields);
12400
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
12401
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
12402
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
12403
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
12404
- includedLines = Number.isFinite(value) ? value : null;
12405
- }
12406
- cursor += 1;
12407
- }
12408
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
12409
- index = cursor + 1;
12410
- continue;
12411
- }
12412
- let fenceLine = cursor + 1;
12413
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
12414
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
12415
- if (!fenceMatch) {
12416
- index = cursor + 1;
12417
- continue;
12418
- }
12419
- const fence = fenceMatch[1];
12420
- const body = [];
12421
- let bodyLine = fenceLine + 1;
12422
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
12423
- body.push(lines[bodyLine]);
12424
- bodyLine += 1;
12425
- }
12426
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
12427
- index = bodyLine + 1;
12428
- }
12429
- return sections;
12430
- }
12431
- function findSection(sections, relativePath) {
12432
- const anchor = anchorForPath(relativePath);
12433
- const byAnchor = sections.find((section) => section.anchor === anchor);
12434
- if (byAnchor) return byAnchor;
12435
- const rendered = displayPath(relativePath);
12436
- const samePath = (section) => section.path === relativePath || section.path === rendered;
12437
- const exact = sections.find(samePath);
12438
- if (exact) return exact;
12439
- const foldedPath = rendered.toLowerCase();
12440
- const folded = sections.filter((section) => {
12441
- const path28 = section.path.toLowerCase();
12442
- return path28 === relativePath.toLowerCase() || path28 === foldedPath;
12443
- });
12444
- return folded.length === 1 ? folded[0] : null;
12445
- }
12446
12656
  function windowText(body, fromLine, lineCount) {
12447
12657
  const lines = body.split("\n");
12448
12658
  const total = body.length === 0 ? 0 : lines.length;
@@ -13560,6 +13770,11 @@ var symbolTool = {
13560
13770
  name: { type: "string", description: "Symbol name, case-insensitive." },
13561
13771
  lines: { type: "integer", description: "Window size around the definition (default 40).", minimum: 5 },
13562
13772
  maxFiles: { type: "integer", description: "Cap on files searched (default 5).", minimum: 1 },
13773
+ references: {
13774
+ type: "boolean",
13775
+ description: "Also report call sites: other files whose body mentions the name (default true)."
13776
+ },
13777
+ maxReferences: { type: "integer", description: "Cap on reported call sites (default 20).", minimum: 1 },
13563
13778
  root: ROOT_PROPERTY,
13564
13779
  outDir: OUT_DIR_PROPERTY
13565
13780
  },
@@ -13570,7 +13785,8 @@ var symbolTool = {
13570
13785
  type: "object",
13571
13786
  properties: {
13572
13787
  found: { type: "integer" },
13573
- matches: { type: "array", items: { type: "object" } }
13788
+ matches: { type: "array", items: { type: "object" } },
13789
+ references: { type: "array", items: { type: "object" } }
13574
13790
  }
13575
13791
  },
13576
13792
  annotations: READ_ONLY,
@@ -13623,8 +13839,44 @@ var symbolTool = {
13623
13839
  structured: { found: 0, matches: [] }
13624
13840
  };
13625
13841
  }
13626
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n");
13627
- return { text: text2, structured: { found: matches.length, matches } };
13842
+ const callSites = [];
13843
+ if (args.references !== false) {
13844
+ const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13845
+ const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13846
+ const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13847
+ const parts = /* @__PURE__ */ new Map();
13848
+ let scanned = 0;
13849
+ for (const file of read.manifest.files) {
13850
+ if (callSites.length >= limit) break;
13851
+ const partPath = partPathFor(workspace, file.part);
13852
+ if (partPath === null) continue;
13853
+ let partText = parts.get(partPath);
13854
+ if (partText === void 0) {
13855
+ try {
13856
+ partText = fs24__namespace.readFileSync(partPath, "utf8");
13857
+ } catch {
13858
+ continue;
13859
+ }
13860
+ parts.set(partPath, partText);
13861
+ }
13862
+ if (scanned > MAX_SEARCH_BYTES) break;
13863
+ scanned += Buffer.byteLength(partText, "utf8");
13864
+ const section = findSection(parsePartSections(partText), file.relativePath);
13865
+ if (section === null) continue;
13866
+ const bodyLines = section.body.split("\n");
13867
+ for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
13868
+ if (!word.test(bodyLines[index])) continue;
13869
+ callSites.push({
13870
+ path: file.relativePath,
13871
+ line: index + 1,
13872
+ text: bodyLines[index].trim().slice(0, 200),
13873
+ definition: definitionKeys.has(file.relativePath + ":" + (index + 1))
13874
+ });
13875
+ }
13876
+ }
13877
+ }
13878
+ 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")));
13879
+ return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13628
13880
  }
13629
13881
  };
13630
13882
  var contextTool = {
@@ -14928,6 +15180,8 @@ var VALIDATE_OPTIONS = [
14928
15180
  "sarif",
14929
15181
  "strip-comments",
14930
15182
  "remove-empty-lines",
15183
+ "only",
15184
+ "ignore",
14931
15185
  "pack",
14932
15186
  // The opt-in reports change the artifact selection the manifest records, so validate must accept
14933
15187
  // them to compare like with like: without the flags it reports the selection as drift.
@@ -14963,6 +15217,8 @@ var COMMAND_OPTION_SCOPE = {
14963
15217
  generate: [
14964
15218
  "strip-comments",
14965
15219
  "remove-empty-lines",
15220
+ "only",
15221
+ "ignore",
14966
15222
  "workspace",
14967
15223
  "budget-tokens",
14968
15224
  "sign",
@@ -15043,6 +15299,10 @@ var COMMAND_OPTION_SCOPE = {
15043
15299
  // Removed rather than implemented, because a flag that parses and does nothing is the defect
15044
15300
  // this table exists to prevent.
15045
15301
  "large-file-bytes",
15302
+ // `--only` and `--ignore` change which files are scanned, so they change what `explain` can say
15303
+ // about a path; without them the answer for an ignored file is "included: true".
15304
+ "only",
15305
+ "ignore",
15046
15306
  "include-sensitive-files",
15047
15307
  "no-config",
15048
15308
  "discovery",
@@ -15584,6 +15844,18 @@ function buildAgentContract() {
15584
15844
  appliesTo: optionAppliesTo("allow-origin"),
15585
15845
  summary: "mcp --http: comma-separated extra CORS origins. Loopback origins are always allowed."
15586
15846
  },
15847
+ {
15848
+ flag: "--only",
15849
+ type: "string",
15850
+ summary: "Comma-separated globs to include: overrides the config include list for this run.",
15851
+ appliesTo: optionAppliesTo("only")
15852
+ },
15853
+ {
15854
+ flag: "--ignore",
15855
+ type: "string",
15856
+ summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
15857
+ appliesTo: optionAppliesTo("ignore")
15858
+ },
15587
15859
  {
15588
15860
  flag: "--remove-empty-lines",
15589
15861
  type: "boolean",
@@ -20243,12 +20515,23 @@ async function startHttpTransport(options) {
20243
20515
  return fromQuery !== null && timingSafeEqual3(fromQuery, token);
20244
20516
  };
20245
20517
  const sessions = /* @__PURE__ */ new Map();
20518
+ const metrics = {
20519
+ requests: 0,
20520
+ byMethod: /* @__PURE__ */ new Map(),
20521
+ refused: 0,
20522
+ rateLimited: 0};
20523
+ const noteRequest = (request) => {
20524
+ metrics.requests += 1;
20525
+ const method = request.method ?? "UNKNOWN";
20526
+ metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
20527
+ };
20246
20528
  const allowedOrigin = (origin) => {
20247
20529
  if (origin === void 0) return null;
20248
20530
  if (isLoopbackOrigin(origin)) return origin;
20249
20531
  return extraOrigins.includes(origin) ? origin : null;
20250
20532
  };
20251
20533
  const httpServer = http__namespace.createServer((request, response) => {
20534
+ noteRequest(request);
20252
20535
  const send = (status, body, extra = {}) => {
20253
20536
  const text2 = typeof body === "string" ? body : JSON.stringify(body);
20254
20537
  response.writeHead(status, {
@@ -20262,6 +20545,7 @@ async function startHttpTransport(options) {
20262
20545
  const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
20263
20546
  const allowed = allowedOrigin(origin);
20264
20547
  if (origin !== void 0 && allowed === null) {
20548
+ metrics.refused += 1;
20265
20549
  send(403, { error: "origin not allowed" });
20266
20550
  return;
20267
20551
  }
@@ -20291,6 +20575,33 @@ async function startHttpTransport(options) {
20291
20575
  );
20292
20576
  return;
20293
20577
  }
20578
+ if (request.method === "GET" && request.url === "/metrics") {
20579
+ const lines = [
20580
+ "# HELP snapshot_uptime_seconds Seconds since the process started.",
20581
+ "# TYPE snapshot_uptime_seconds gauge",
20582
+ "snapshot_uptime_seconds " + Math.round(process.uptime()),
20583
+ "# HELP snapshot_requests_total HTTP requests received.",
20584
+ "# TYPE snapshot_requests_total counter",
20585
+ "snapshot_requests_total " + metrics.requests,
20586
+ "# HELP snapshot_requests_refused_total Requests refused before dispatch.",
20587
+ "# TYPE snapshot_requests_refused_total counter",
20588
+ "snapshot_requests_refused_total " + metrics.refused,
20589
+ "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
20590
+ "# TYPE snapshot_requests_rate_limited_total counter",
20591
+ "snapshot_requests_rate_limited_total " + metrics.rateLimited,
20592
+ "# HELP snapshot_tools Number of tools this server serves.",
20593
+ "# TYPE snapshot_tools gauge",
20594
+ "snapshot_tools " + toolCount
20595
+ ];
20596
+ for (const [method, count] of metrics.byMethod) {
20597
+ lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
20598
+ }
20599
+ send(200, lines.join("\n") + "\n", {
20600
+ ...cors,
20601
+ "content-type": "text/plain; version=0.0.4; charset=utf-8"
20602
+ });
20603
+ return;
20604
+ }
20294
20605
  const url = new URL(request.url ?? "/", "http://localhost");
20295
20606
  if (request.method === "GET" && url.pathname === "/sse") {
20296
20607
  if (!tokenAccepted(request, url)) {
@@ -20382,6 +20693,7 @@ async function startHttpTransport(options) {
20382
20693
  const window = sessions.get(remote);
20383
20694
  if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
20384
20695
  else if (window.count >= RATE_LIMIT) {
20696
+ metrics.rateLimited += 1;
20385
20697
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
20386
20698
  return;
20387
20699
  } else window.count += 1;
@@ -20549,6 +20861,8 @@ var CLI_OPTIONS = {
20549
20861
  workspace: { type: "string" },
20550
20862
  "strip-comments": { type: "boolean" },
20551
20863
  "remove-empty-lines": { type: "boolean" },
20864
+ only: { type: "string" },
20865
+ ignore: { type: "string" },
20552
20866
  "all-members": { type: "boolean" },
20553
20867
  help: { type: "boolean", short: "h" },
20554
20868
  version: { type: "boolean", short: "v" }
@@ -20997,6 +21311,8 @@ function parseCliArgs(argv) {
20997
21311
  workspace: values.workspace === void 0 ? void 0 : String(values.workspace),
20998
21312
  stripComments: values["strip-comments"] === true ? true : void 0,
20999
21313
  removeEmptyLines: values["remove-empty-lines"] === true ? true : void 0,
21314
+ only: values.only === void 0 ? void 0 : String(values.only).split(",").map((item) => item.trim()).filter(Boolean),
21315
+ ignore: values.ignore === void 0 ? void 0 : String(values.ignore).split(",").map((item) => item.trim()).filter(Boolean),
21000
21316
  allMembers: values["all-members"] === true ? true : void 0,
21001
21317
  budgetTokens: values["budget-tokens"] === void 0 ? void 0 : parsePositiveInteger(values["budget-tokens"], "budget-tokens", 500),
21002
21318
  delta: values.delta === void 0 ? void 0 : String(values.delta),
@@ -21698,6 +22014,8 @@ ${USAGE}
21698
22014
  ...invocation.tokenTree === true ? { tokenTree: true } : {},
21699
22015
  ...invocation.stripComments === true ? { stripComments: true } : {},
21700
22016
  ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
22017
+ ...invocation.only === void 0 ? {} : { only: invocation.only },
22018
+ ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
21701
22019
  ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
21702
22020
  brief: invocation.brief,
21703
22021
  promptTask: invocation.promptTask,
package/dist/cli.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { O as OutputFormat, P as PromptTask, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-CbD8yQRZ.cjs';
1
+ import { O as OutputFormat, P as PromptTask, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-5G2Q6tWP.cjs';
2
2
 
3
3
  /**
4
4
  * The machine-readable description of this tool.
@@ -304,6 +304,12 @@ declare const CLI_OPTIONS: {
304
304
  readonly "remove-empty-lines": {
305
305
  readonly type: "boolean";
306
306
  };
307
+ readonly only: {
308
+ readonly type: "string";
309
+ };
310
+ readonly ignore: {
311
+ readonly type: "string";
312
+ };
307
313
  readonly "all-members": {
308
314
  readonly type: "boolean";
309
315
  };
@@ -436,6 +442,10 @@ interface ParsedInvocation {
436
442
  stripComments?: boolean;
437
443
  /** `--remove-empty-lines`: drop blank lines from emitted bodies (line numbers move). */
438
444
  removeEmptyLines?: boolean;
445
+ /** `--only <globs>`: override the include allow-list for this run. */
446
+ only?: string[];
447
+ /** `--ignore <globs>`: add to the exclude list for this run. */
448
+ ignore?: string[];
439
449
  /** `--all-members` (health): audit every snapshot a `--workspace` run wrote. */
440
450
  allMembers?: boolean;
441
451
  }