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.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { O as OutputFormat, P as PromptTask, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-CbD8yQRZ.js';
1
+ import { O as OutputFormat, P as PromptTask, D as DiscoveryMode, R as ResolvedSnapshotConfig } from './types-5G2Q6tWP.js';
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
  }
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
- import { startHttpTransport } from './chunk-NESEHOPU.js';
2
- import { shouldCheck, checkForUpdate, GENERATOR_VERSION, cacheFilePath, formatUpdateNotice, installKind, buildAgentContract, startWebServer, runStdioServer, parseRemoteSource, assertPublicHost, cloneRepository, makeCloneDirectory, loadConfigFileDetailed, resolveConfig, validateSnapshot, auditSnapshot, describeManifestShapeProblem, explainPath, compareManifests, loadManifest, renderDiffText, generateSnapshot, signManifest, loadSigningKey, writeSignature, formatNumber, isDiscoveryMode, ARTIFACT_NAMES, COMMAND_OPTION_SCOPE, commandsForOption, getPreset, unknownPresetMessage, GENERATOR_NAME, runInit, installPreCommitHook, PromptCancelled, SKILL_NAME, renderSkill, findConfigFile, planFirstRun, isEffectivelyEmpty, isInteractive, defaultIO, hasPriorSnapshot, DEFAULT_ANSWERS, firstRunMessage, stripJsonComments, parseByteSize, gitignorePath, appendGitignoreEntries, escapeControls, runWithStdoutCapture, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderContractText, renderExplainText } from './chunk-BOJYZQFB.js';
3
- export { buildAgentContract } from './chunk-BOJYZQFB.js';
1
+ import { startHttpTransport } from './chunk-4OHQULCV.js';
2
+ import { shouldCheck, checkForUpdate, GENERATOR_VERSION, cacheFilePath, formatUpdateNotice, installKind, buildAgentContract, startWebServer, runStdioServer, parseRemoteSource, assertPublicHost, cloneRepository, makeCloneDirectory, loadConfigFileDetailed, resolveConfig, validateSnapshot, auditSnapshot, describeManifestShapeProblem, explainPath, compareManifests, loadManifest, renderDiffText, generateSnapshot, signManifest, loadSigningKey, writeSignature, formatNumber, isDiscoveryMode, ARTIFACT_NAMES, COMMAND_OPTION_SCOPE, commandsForOption, getPreset, unknownPresetMessage, GENERATOR_NAME, runInit, installPreCommitHook, PromptCancelled, SKILL_NAME, renderSkill, findConfigFile, planFirstRun, isEffectivelyEmpty, isInteractive, defaultIO, hasPriorSnapshot, DEFAULT_ANSWERS, firstRunMessage, stripJsonComments, parseByteSize, gitignorePath, appendGitignoreEntries, escapeControls, runWithStdoutCapture, MIN_MAX_PART_TOKENS, MIN_MAX_PART_BYTES, renderContractText, renderExplainText } from './chunk-KHHUC6UT.js';
3
+ export { buildAgentContract } from './chunk-KHHUC6UT.js';
4
4
  import { spawnSync } from 'child_process';
5
5
  import * as fs2 from 'fs';
6
6
  import * as path2 from 'path';
@@ -185,6 +185,8 @@ var CLI_OPTIONS = {
185
185
  workspace: { type: "string" },
186
186
  "strip-comments": { type: "boolean" },
187
187
  "remove-empty-lines": { type: "boolean" },
188
+ only: { type: "string" },
189
+ ignore: { type: "string" },
188
190
  "all-members": { type: "boolean" },
189
191
  help: { type: "boolean", short: "h" },
190
192
  version: { type: "boolean", short: "v" }
@@ -633,6 +635,8 @@ function parseCliArgs(argv) {
633
635
  workspace: values.workspace === void 0 ? void 0 : String(values.workspace),
634
636
  stripComments: values["strip-comments"] === true ? true : void 0,
635
637
  removeEmptyLines: values["remove-empty-lines"] === true ? true : void 0,
638
+ only: values.only === void 0 ? void 0 : String(values.only).split(",").map((item) => item.trim()).filter(Boolean),
639
+ ignore: values.ignore === void 0 ? void 0 : String(values.ignore).split(",").map((item) => item.trim()).filter(Boolean),
636
640
  allMembers: values["all-members"] === true ? true : void 0,
637
641
  budgetTokens: values["budget-tokens"] === void 0 ? void 0 : parsePositiveInteger(values["budget-tokens"], "budget-tokens", 500),
638
642
  delta: values.delta === void 0 ? void 0 : String(values.delta),
@@ -1334,6 +1338,8 @@ ${USAGE}
1334
1338
  ...invocation.tokenTree === true ? { tokenTree: true } : {},
1335
1339
  ...invocation.stripComments === true ? { stripComments: true } : {},
1336
1340
  ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
1341
+ ...invocation.only === void 0 ? {} : { only: invocation.only },
1342
+ ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
1337
1343
  ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
1338
1344
  brief: invocation.brief,
1339
1345
  promptTask: invocation.promptTask,
package/dist/index.cjs CHANGED
@@ -4012,7 +4012,7 @@ function applySpansKeepingQuotes(line, spans) {
4012
4012
 
4013
4013
  // src/version.ts
4014
4014
  var GENERATOR_NAME = "codebase-snapshot";
4015
- var GENERATOR_VERSION = "0.13.0";
4015
+ var GENERATOR_VERSION = "0.15.0";
4016
4016
  var SCHEMA_VERSION = "3.0.0";
4017
4017
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4018
4018
  function isOurGeneratorName(name) {
@@ -5884,7 +5884,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5884
5884
  logCount: resolveLogCount(
5885
5885
  cliOptions?.logCount ?? cliOptions?.includeLogs ?? userConfig?.logCount
5886
5886
  ),
5887
- include: resolveInclude(userConfig?.include),
5887
+ // `--only` replaces the allow-list for this run; `--ignore` adds to the deny-list. The two
5888
+ // directions are different on purpose: a narrower allow-list is a statement about the whole
5889
+ // run, while "also ignore this" is naturally cumulative with what the config already excludes.
5890
+ include: resolveInclude(
5891
+ cliOptions?.only ?? userConfig?.include
5892
+ ),
5888
5893
  preset: preset.presetName,
5889
5894
  presetExclude,
5890
5895
  artifacts,
@@ -5895,9 +5900,12 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5895
5900
  kinds,
5896
5901
  // `exclude` is the flag spelling of the same setting; writing it in a config used to
5897
5902
  // be ignored without a word.
5898
- excludePatterns: resolveExcludePatterns(
5899
- userConfig?.excludePatterns ?? userConfig?.exclude
5900
- ),
5903
+ excludePatterns: [
5904
+ ...resolveExcludePatterns(
5905
+ userConfig?.excludePatterns ?? userConfig?.exclude
5906
+ ),
5907
+ ...resolveExcludePatterns(cliOptions?.ignore)
5908
+ ],
5901
5909
  secretRules,
5902
5910
  // Extra property rather than a `ResolvedSnapshotConfig` field: the resolved
5903
5911
  // shape is owned elsewhere, and every scan reads it through the registry in
@@ -9995,6 +10003,92 @@ function verifySnapshotSignature(snapshotDir) {
9995
10003
  return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
9996
10004
  }
9997
10005
 
10006
+ // src/partitioner/part-format.ts
10007
+ var FILE_HEADING = "### FILE: ";
10008
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10009
+ var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10010
+ var META_PREFIX = "- Meta: ";
10011
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10012
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10013
+ var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10014
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10015
+ function readIncludedLines(fields) {
10016
+ const last = fields[fields.length - 1];
10017
+ if (last === void 0) return null;
10018
+ const counts = COMPACT_COUNTS.exec(last.trim());
10019
+ return counts === null ? null : Number(counts[1]);
10020
+ }
10021
+ function parsePartSections(partText) {
10022
+ const lines = partText.split("\n");
10023
+ const sections = [];
10024
+ let index = 0;
10025
+ while (index < lines.length) {
10026
+ if (!lines[index].startsWith(FILE_HEADING)) {
10027
+ index += 1;
10028
+ continue;
10029
+ }
10030
+ const heading = lines[index].slice(FILE_HEADING.length);
10031
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
10032
+ let cursor = index + 1;
10033
+ let inclusion = null;
10034
+ let includedLines = null;
10035
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10036
+ const line = lines[cursor];
10037
+ if (line.startsWith(FILE_HEADING)) break;
10038
+ if (line.startsWith(META_PREFIX)) {
10039
+ const fields = line.slice(META_PREFIX.length).split("|");
10040
+ for (const field of fields) {
10041
+ const value = field.trim();
10042
+ if (INCLUSION_MODES.has(value)) inclusion = value;
10043
+ }
10044
+ includedLines = readIncludedLines(fields);
10045
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10046
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10047
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10048
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10049
+ includedLines = Number.isFinite(value) ? value : null;
10050
+ }
10051
+ cursor += 1;
10052
+ }
10053
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
10054
+ index = cursor + 1;
10055
+ continue;
10056
+ }
10057
+ let fenceLine = cursor + 1;
10058
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
10059
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
10060
+ if (!fenceMatch) {
10061
+ index = cursor + 1;
10062
+ continue;
10063
+ }
10064
+ const fence = fenceMatch[1];
10065
+ const body = [];
10066
+ let bodyLine = fenceLine + 1;
10067
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
10068
+ body.push(lines[bodyLine]);
10069
+ bodyLine += 1;
10070
+ }
10071
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
10072
+ index = bodyLine + 1;
10073
+ }
10074
+ return sections;
10075
+ }
10076
+ function findSection(sections, relativePath) {
10077
+ const anchor = anchorForPath(relativePath);
10078
+ const byAnchor = sections.find((section) => section.anchor === anchor);
10079
+ if (byAnchor) return byAnchor;
10080
+ const rendered = displayPath(relativePath);
10081
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
10082
+ const exact = sections.find(samePath);
10083
+ if (exact) return exact;
10084
+ const foldedPath = rendered.toLowerCase();
10085
+ const folded = sections.filter((section) => {
10086
+ const path26 = section.path.toLowerCase();
10087
+ return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10088
+ });
10089
+ return folded.length === 1 ? folded[0] : null;
10090
+ }
10091
+
9998
10092
  // src/auditor/health.ts
9999
10093
  var ARTIFACT_FILES = {
10000
10094
  readme: "README.md",
@@ -10304,6 +10398,206 @@ function auditSnapshot(options) {
10304
10398
  )
10305
10399
  );
10306
10400
  }
10401
+ const bookkeeping = [];
10402
+ const expect = (name, recorded2, computed) => {
10403
+ if (recorded2 !== computed) bookkeeping.push(name + ": manifest says " + recorded2 + ", the data has " + computed);
10404
+ };
10405
+ expect("counts.totalFiles", manifest.counts.totalFiles, manifest.files.length);
10406
+ expect("counts.partsCount", manifest.counts.partsCount, manifest.parts.length);
10407
+ expect("counts.skippedCount", manifest.counts.skippedCount, manifest.skipped.length);
10408
+ if (typeof manifest.totals.includedFiles === "number") {
10409
+ expect("totals.includedFiles", manifest.totals.includedFiles, manifest.files.length);
10410
+ }
10411
+ const contentBytes = manifest.files.reduce((sum, file) => sum + file.includedBytes, 0);
10412
+ expect("totals.totalContentBytes", manifest.totals.totalContentBytes, contentBytes);
10413
+ const layerCounts = /* @__PURE__ */ new Map();
10414
+ for (const file of manifest.files) layerCounts.set(file.layer, (layerCounts.get(file.layer) ?? 0) + 1);
10415
+ for (const [layer2, count] of layerCounts) {
10416
+ expect("layers." + layer2, manifest.layers[layer2] ?? -1, count);
10417
+ }
10418
+ for (const layer2 of Object.keys(manifest.layers)) {
10419
+ if (!layerCounts.has(layer2)) expect("layers." + layer2, manifest.layers[layer2], 0);
10420
+ }
10421
+ checks.push(
10422
+ bookkeeping.length === 0 ? check(
10423
+ "bookkeeping",
10424
+ "The counts equal the data they summarise",
10425
+ "critical",
10426
+ "pass",
10427
+ "Files, parts, skips, content bytes and layer counts all agree."
10428
+ ) : check(
10429
+ "bookkeeping",
10430
+ "The counts equal the data they summarise",
10431
+ "critical",
10432
+ "fail",
10433
+ bookkeeping.length + " mismatch(es): " + sample(bookkeeping)
10434
+ )
10435
+ );
10436
+ const packReaders = [
10437
+ {
10438
+ key: "fullJson",
10439
+ file: "full-codebase.json",
10440
+ label: "JSON",
10441
+ paths: (text2) => {
10442
+ try {
10443
+ const parsed = JSON.parse(text2);
10444
+ if (!Array.isArray(parsed?.files)) return null;
10445
+ return new Set(parsed.files.map((entry) => String(entry?.relativePath)));
10446
+ } catch {
10447
+ return null;
10448
+ }
10449
+ }
10450
+ },
10451
+ {
10452
+ key: "fullXml",
10453
+ file: "full-codebase.xml",
10454
+ label: "XML",
10455
+ paths: (text2) => {
10456
+ const found = [...text2.matchAll(/<file path="([^"]+)"/g)].map((match) => match[1]);
10457
+ if (found.length === 0) return null;
10458
+ return new Set(found.map((value) => value.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")));
10459
+ }
10460
+ },
10461
+ {
10462
+ key: "fullMarkdown",
10463
+ file: "full-codebase.md",
10464
+ label: "markdown",
10465
+ paths: (text2) => {
10466
+ const found = [...text2.matchAll(/^## File: (.+)$/gm)].map((match) => match[1].trim());
10467
+ if (found.length === 0) return null;
10468
+ return new Set(found);
10469
+ }
10470
+ }
10471
+ ];
10472
+ for (const reader of packReaders) {
10473
+ if (manifest.artifacts?.[reader.key] == null) continue;
10474
+ const packText = readText2(path25__namespace.join(snapshotDir, reader.file));
10475
+ const problems = [];
10476
+ if (packText === null) {
10477
+ problems.push(reader.file + " is recorded but unreadable");
10478
+ } else {
10479
+ const packed = reader.paths(packText);
10480
+ if (packed === null) {
10481
+ problems.push(reader.file + " could not be parsed for its file list");
10482
+ } else {
10483
+ const known2 = new Set(manifest.files.map((file) => file.relativePath));
10484
+ for (const file of manifest.files) {
10485
+ if (!packed.has(file.relativePath)) problems.push(file.relativePath + " is in the manifest but not the pack");
10486
+ }
10487
+ for (const path26 of packed) {
10488
+ if (!known2.has(path26)) problems.push(path26 + " is in the pack but not the manifest");
10489
+ }
10490
+ }
10491
+ }
10492
+ const title = "The " + reader.label + " pack holds every file the manifest lists";
10493
+ checks.push(
10494
+ problems.length === 0 ? check(
10495
+ "pipeline.monolith",
10496
+ title,
10497
+ "critical",
10498
+ "pass",
10499
+ manifest.files.length + " file(s) present in " + reader.file + ", and nothing extra."
10500
+ ) : check(
10501
+ "pipeline.monolith",
10502
+ title,
10503
+ "critical",
10504
+ "fail",
10505
+ problems.length + " problem(s): " + sample(problems)
10506
+ )
10507
+ );
10508
+ }
10509
+ const bodyProblems = [];
10510
+ let bodiesChecked = 0;
10511
+ for (const part of manifest.parts) {
10512
+ const partText = readText2(path25__namespace.join(snapshotDir, "parts", part.filename));
10513
+ if (partText === null) continue;
10514
+ const sections = parsePartSections(partText);
10515
+ for (const file of manifest.files) {
10516
+ if (file.part !== part.filename) continue;
10517
+ const section = findSection(sections, file.relativePath);
10518
+ if (section === null) {
10519
+ bodyProblems.push(file.relativePath + " has no section in " + part.filename);
10520
+ continue;
10521
+ }
10522
+ bodiesChecked += 1;
10523
+ const bytes = Buffer.byteLength(section.body, "utf8");
10524
+ const bodyLines = section.body === "" ? 0 : section.body.split("\n").length - (section.body.endsWith("\n") ? 1 : 0);
10525
+ if (bytes !== file.includedBytes) {
10526
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedBytes + " B, part holds " + bytes + " B");
10527
+ } else if (bodyLines !== file.includedLines) {
10528
+ bodyProblems.push(file.relativePath + ": manifest says " + file.includedLines + " line(s), part holds " + bodyLines);
10529
+ }
10530
+ }
10531
+ }
10532
+ checks.push(
10533
+ bodyProblems.length === 0 ? check(
10534
+ "pipeline.bodies",
10535
+ "Every file body matches the manifest accounting",
10536
+ "critical",
10537
+ "pass",
10538
+ bodiesChecked + " file body/bodies match their recorded bytes and lines."
10539
+ ) : check(
10540
+ "pipeline.bodies",
10541
+ "Every file body matches the manifest accounting",
10542
+ "critical",
10543
+ "fail",
10544
+ bodyProblems.length + " file(s) disagree: " + sample(bodyProblems)
10545
+ )
10546
+ );
10547
+ const indexParent = path25__namespace.dirname(snapshotDir);
10548
+ const indexPath = path25__namespace.join(indexParent, "WORKSPACE.json");
10549
+ if (fs24__namespace.existsSync(indexPath)) {
10550
+ const indexText = readText2(indexPath);
10551
+ let members = [];
10552
+ let problem2 = null;
10553
+ try {
10554
+ const parsed = JSON.parse(indexText ?? "null");
10555
+ if (!Array.isArray(parsed?.members)) problem2 = "its members field is not an array";
10556
+ else members = parsed.members;
10557
+ } catch (error) {
10558
+ problem2 = error.message;
10559
+ }
10560
+ const memberName = path25__namespace.basename(snapshotDir);
10561
+ const member = members.find((entry) => entry.name === memberName);
10562
+ if (problem2 !== null) {
10563
+ checks.push(check(
10564
+ "workspace.index",
10565
+ "The workspace index agrees with this member",
10566
+ "warning",
10567
+ "warn",
10568
+ "WORKSPACE.json could not be read: " + problem2
10569
+ ));
10570
+ } else if (member === void 0) {
10571
+ checks.push(check(
10572
+ "workspace.index",
10573
+ "The workspace index agrees with this member",
10574
+ "warning",
10575
+ "skip",
10576
+ "WORKSPACE.json lists no member named " + memberName + "."
10577
+ ));
10578
+ } else {
10579
+ const disagreements = [];
10580
+ if (member.fingerprint !== manifest.fingerprint) disagreements.push("fingerprint");
10581
+ if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
10582
+ disagreements.push("file count");
10583
+ }
10584
+ checks.push(
10585
+ disagreements.length === 0 ? check(
10586
+ "workspace.index",
10587
+ "The workspace index agrees with this member",
10588
+ "warning",
10589
+ "pass",
10590
+ "Member " + memberName + " matches the index fingerprint and file count."
10591
+ ) : check(
10592
+ "workspace.index",
10593
+ "The workspace index agrees with this member",
10594
+ "warning",
10595
+ "warn",
10596
+ "The index disagrees with this member on: " + disagreements.join(", ") + ". Regenerate the workspace."
10597
+ )
10598
+ );
10599
+ }
10600
+ }
10307
10601
  const rules = [...compileSecretRules(DEFAULT_SECRET_PATTERNS), ...options.secretRules ?? []];
10308
10602
  const scanBudget = options.maxScanBytes ?? 32 * 1024 * 1024;
10309
10603
  const leakHits = [];
@@ -10815,90 +11109,6 @@ function generateInWorker(cwd, cliOptions, options = {}) {
10815
11109
  }
10816
11110
 
10817
11111
  // src/mcp/part.ts
10818
- var FILE_HEADING = "### FILE: ";
10819
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
10820
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
10821
- var META_PREFIX = "- Meta: ";
10822
- var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
10823
- var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
10824
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
10825
- var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
10826
- function readIncludedLines(fields) {
10827
- const last = fields[fields.length - 1];
10828
- if (last === void 0) return null;
10829
- const counts = COMPACT_COUNTS.exec(last.trim());
10830
- return counts === null ? null : Number(counts[1]);
10831
- }
10832
- function parsePartSections(partText) {
10833
- const lines = partText.split("\n");
10834
- const sections = [];
10835
- let index = 0;
10836
- while (index < lines.length) {
10837
- if (!lines[index].startsWith(FILE_HEADING)) {
10838
- index += 1;
10839
- continue;
10840
- }
10841
- const heading = lines[index].slice(FILE_HEADING.length);
10842
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
10843
- let cursor = index + 1;
10844
- let inclusion = null;
10845
- let includedLines = null;
10846
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
10847
- const line = lines[cursor];
10848
- if (line.startsWith(FILE_HEADING)) break;
10849
- if (line.startsWith(META_PREFIX)) {
10850
- const fields = line.slice(META_PREFIX.length).split("|");
10851
- for (const field of fields) {
10852
- const value = field.trim();
10853
- if (INCLUSION_MODES.has(value)) inclusion = value;
10854
- }
10855
- includedLines = readIncludedLines(fields);
10856
- } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
10857
- inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
10858
- } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
10859
- const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
10860
- includedLines = Number.isFinite(value) ? value : null;
10861
- }
10862
- cursor += 1;
10863
- }
10864
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
10865
- index = cursor + 1;
10866
- continue;
10867
- }
10868
- let fenceLine = cursor + 1;
10869
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
10870
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
10871
- if (!fenceMatch) {
10872
- index = cursor + 1;
10873
- continue;
10874
- }
10875
- const fence = fenceMatch[1];
10876
- const body = [];
10877
- let bodyLine = fenceLine + 1;
10878
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
10879
- body.push(lines[bodyLine]);
10880
- bodyLine += 1;
10881
- }
10882
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
10883
- index = bodyLine + 1;
10884
- }
10885
- return sections;
10886
- }
10887
- function findSection(sections, relativePath) {
10888
- const anchor = anchorForPath(relativePath);
10889
- const byAnchor = sections.find((section) => section.anchor === anchor);
10890
- if (byAnchor) return byAnchor;
10891
- const rendered = displayPath(relativePath);
10892
- const samePath = (section) => section.path === relativePath || section.path === rendered;
10893
- const exact = sections.find(samePath);
10894
- if (exact) return exact;
10895
- const foldedPath = rendered.toLowerCase();
10896
- const folded = sections.filter((section) => {
10897
- const path26 = section.path.toLowerCase();
10898
- return path26 === relativePath.toLowerCase() || path26 === foldedPath;
10899
- });
10900
- return folded.length === 1 ? folded[0] : null;
10901
- }
10902
11112
  function windowText(body, fromLine, lineCount) {
10903
11113
  const lines = body.split("\n");
10904
11114
  const total = body.length === 0 ? 0 : lines.length;
@@ -12016,6 +12226,11 @@ var symbolTool = {
12016
12226
  name: { type: "string", description: "Symbol name, case-insensitive." },
12017
12227
  lines: { type: "integer", description: "Window size around the definition (default 40).", minimum: 5 },
12018
12228
  maxFiles: { type: "integer", description: "Cap on files searched (default 5).", minimum: 1 },
12229
+ references: {
12230
+ type: "boolean",
12231
+ description: "Also report call sites: other files whose body mentions the name (default true)."
12232
+ },
12233
+ maxReferences: { type: "integer", description: "Cap on reported call sites (default 20).", minimum: 1 },
12019
12234
  root: ROOT_PROPERTY,
12020
12235
  outDir: OUT_DIR_PROPERTY
12021
12236
  },
@@ -12026,7 +12241,8 @@ var symbolTool = {
12026
12241
  type: "object",
12027
12242
  properties: {
12028
12243
  found: { type: "integer" },
12029
- matches: { type: "array", items: { type: "object" } }
12244
+ matches: { type: "array", items: { type: "object" } },
12245
+ references: { type: "array", items: { type: "object" } }
12030
12246
  }
12031
12247
  },
12032
12248
  annotations: READ_ONLY,
@@ -12079,8 +12295,44 @@ var symbolTool = {
12079
12295
  structured: { found: 0, matches: [] }
12080
12296
  };
12081
12297
  }
12082
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n");
12083
- return { text: text2, structured: { found: matches.length, matches } };
12298
+ const callSites = [];
12299
+ if (args.references !== false) {
12300
+ const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
12301
+ const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
12302
+ const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
12303
+ const parts = /* @__PURE__ */ new Map();
12304
+ let scanned = 0;
12305
+ for (const file of read.manifest.files) {
12306
+ if (callSites.length >= limit) break;
12307
+ const partPath = partPathFor(workspace, file.part);
12308
+ if (partPath === null) continue;
12309
+ let partText = parts.get(partPath);
12310
+ if (partText === void 0) {
12311
+ try {
12312
+ partText = fs24__namespace.readFileSync(partPath, "utf8");
12313
+ } catch {
12314
+ continue;
12315
+ }
12316
+ parts.set(partPath, partText);
12317
+ }
12318
+ if (scanned > MAX_SEARCH_BYTES) break;
12319
+ scanned += Buffer.byteLength(partText, "utf8");
12320
+ const section = findSection(parsePartSections(partText), file.relativePath);
12321
+ if (section === null) continue;
12322
+ const bodyLines = section.body.split("\n");
12323
+ for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
12324
+ if (!word.test(bodyLines[index])) continue;
12325
+ callSites.push({
12326
+ path: file.relativePath,
12327
+ line: index + 1,
12328
+ text: bodyLines[index].trim().slice(0, 200),
12329
+ definition: definitionKeys.has(file.relativePath + ":" + (index + 1))
12330
+ });
12331
+ }
12332
+ }
12333
+ }
12334
+ 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")));
12335
+ return { text: text2, structured: { found: matches.length, matches, references: callSites } };
12084
12336
  }
12085
12337
  };
12086
12338
  var contextTool = {
@@ -13384,6 +13636,8 @@ var VALIDATE_OPTIONS = [
13384
13636
  "sarif",
13385
13637
  "strip-comments",
13386
13638
  "remove-empty-lines",
13639
+ "only",
13640
+ "ignore",
13387
13641
  "pack",
13388
13642
  // The opt-in reports change the artifact selection the manifest records, so validate must accept
13389
13643
  // them to compare like with like: without the flags it reports the selection as drift.
@@ -13419,6 +13673,8 @@ var COMMAND_OPTION_SCOPE = {
13419
13673
  generate: [
13420
13674
  "strip-comments",
13421
13675
  "remove-empty-lines",
13676
+ "only",
13677
+ "ignore",
13422
13678
  "workspace",
13423
13679
  "budget-tokens",
13424
13680
  "sign",
@@ -13499,6 +13755,10 @@ var COMMAND_OPTION_SCOPE = {
13499
13755
  // Removed rather than implemented, because a flag that parses and does nothing is the defect
13500
13756
  // this table exists to prevent.
13501
13757
  "large-file-bytes",
13758
+ // `--only` and `--ignore` change which files are scanned, so they change what `explain` can say
13759
+ // about a path; without them the answer for an ignored file is "included: true".
13760
+ "only",
13761
+ "ignore",
13502
13762
  "include-sensitive-files",
13503
13763
  "no-config",
13504
13764
  "discovery",
@@ -13971,6 +14231,18 @@ function buildAgentContract() {
13971
14231
  appliesTo: optionAppliesTo("allow-origin"),
13972
14232
  summary: "mcp --http: comma-separated extra CORS origins. Loopback origins are always allowed."
13973
14233
  },
14234
+ {
14235
+ flag: "--only",
14236
+ type: "string",
14237
+ summary: "Comma-separated globs to include: overrides the config include list for this run.",
14238
+ appliesTo: optionAppliesTo("only")
14239
+ },
14240
+ {
14241
+ flag: "--ignore",
14242
+ type: "string",
14243
+ summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
14244
+ appliesTo: optionAppliesTo("ignore")
14245
+ },
13974
14246
  {
13975
14247
  flag: "--remove-empty-lines",
13976
14248
  type: "boolean",
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SecretRule, D as DiscoveryMode, a as SkipRecord, J as JsonSummary, M as MarkdownSummary, b as SourceSummary, K as KindRule, L as LayerRule, R as ResolvedSnapshotConfig, c as SnapshotConfig, B as ByteSize, C as CliOptions, d as PartMetadata, F as FileEntry, T as TextEncoding, e as SecretFinding, V as ValidationResult, f as Manifest, A as ArtifactSelection } from './types-CbD8yQRZ.cjs';
2
- export { g as BudgetConfig, H as HooksConfig, I as InclusionMode, h as IncompleteFile, i as ManifestArtifact, j as ManifestConfigSnapshot, k as ManifestIndexes, l as ManifestTotals, m as Mode, O as OutputFormat, n as OwnerBrief, o as PartFileEntry, P as PromptTask, p as ResolvedArtifacts, q as ResolvedBudgets, r as SecretRuleInput, s as SkipReason, t as SummaryQuality, u as TruncationReason, v as ValidationDrift } from './types-CbD8yQRZ.cjs';
1
+ import { S as SecretRule, D as DiscoveryMode, a as SkipRecord, J as JsonSummary, M as MarkdownSummary, b as SourceSummary, K as KindRule, L as LayerRule, R as ResolvedSnapshotConfig, c as SnapshotConfig, B as ByteSize, C as CliOptions, d as PartMetadata, F as FileEntry, T as TextEncoding, e as SecretFinding, V as ValidationResult, f as Manifest, A as ArtifactSelection } from './types-5G2Q6tWP.cjs';
2
+ export { g as BudgetConfig, H as HooksConfig, I as InclusionMode, h as IncompleteFile, i as ManifestArtifact, j as ManifestConfigSnapshot, k as ManifestIndexes, l as ManifestTotals, m as Mode, O as OutputFormat, n as OwnerBrief, o as PartFileEntry, P as PromptTask, p as ResolvedArtifacts, q as ResolvedBudgets, r as SecretRuleInput, s as SkipReason, t as SummaryQuality, u as TruncationReason, v as ValidationDrift } from './types-5G2Q6tWP.cjs';
3
3
  export { w as workerEntry } from './generate-worker-B79yGkQO.cjs';
4
4
 
5
5
  interface GitInfo {
@@ -548,7 +548,7 @@ declare function validateSnapshot(configInput: ResolvedSnapshotConfig | Snapshot
548
548
  * `package.json` carries the same version; `npm run verify` compares the two.
549
549
  */
550
550
  declare const GENERATOR_NAME = "codebase-snapshot";
551
- declare const GENERATOR_VERSION = "0.13.0";
551
+ declare const GENERATOR_VERSION = "0.15.0";
552
552
  /**
553
553
  * The manifest and ownership-marker schema this build writes and understands.
554
554
  *
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { S as SecretRule, D as DiscoveryMode, a as SkipRecord, J as JsonSummary, M as MarkdownSummary, b as SourceSummary, K as KindRule, L as LayerRule, R as ResolvedSnapshotConfig, c as SnapshotConfig, B as ByteSize, C as CliOptions, d as PartMetadata, F as FileEntry, T as TextEncoding, e as SecretFinding, V as ValidationResult, f as Manifest, A as ArtifactSelection } from './types-CbD8yQRZ.js';
2
- export { g as BudgetConfig, H as HooksConfig, I as InclusionMode, h as IncompleteFile, i as ManifestArtifact, j as ManifestConfigSnapshot, k as ManifestIndexes, l as ManifestTotals, m as Mode, O as OutputFormat, n as OwnerBrief, o as PartFileEntry, P as PromptTask, p as ResolvedArtifacts, q as ResolvedBudgets, r as SecretRuleInput, s as SkipReason, t as SummaryQuality, u as TruncationReason, v as ValidationDrift } from './types-CbD8yQRZ.js';
1
+ import { S as SecretRule, D as DiscoveryMode, a as SkipRecord, J as JsonSummary, M as MarkdownSummary, b as SourceSummary, K as KindRule, L as LayerRule, R as ResolvedSnapshotConfig, c as SnapshotConfig, B as ByteSize, C as CliOptions, d as PartMetadata, F as FileEntry, T as TextEncoding, e as SecretFinding, V as ValidationResult, f as Manifest, A as ArtifactSelection } from './types-5G2Q6tWP.js';
2
+ export { g as BudgetConfig, H as HooksConfig, I as InclusionMode, h as IncompleteFile, i as ManifestArtifact, j as ManifestConfigSnapshot, k as ManifestIndexes, l as ManifestTotals, m as Mode, O as OutputFormat, n as OwnerBrief, o as PartFileEntry, P as PromptTask, p as ResolvedArtifacts, q as ResolvedBudgets, r as SecretRuleInput, s as SkipReason, t as SummaryQuality, u as TruncationReason, v as ValidationDrift } from './types-5G2Q6tWP.js';
3
3
  export { w as workerEntry } from './generate-worker-B79yGkQO.js';
4
4
 
5
5
  interface GitInfo {
@@ -548,7 +548,7 @@ declare function validateSnapshot(configInput: ResolvedSnapshotConfig | Snapshot
548
548
  * `package.json` carries the same version; `npm run verify` compares the two.
549
549
  */
550
550
  declare const GENERATOR_NAME = "codebase-snapshot";
551
- declare const GENERATOR_VERSION = "0.13.0";
551
+ declare const GENERATOR_VERSION = "0.15.0";
552
552
  /**
553
553
  * The manifest and ownership-marker schema this build writes and understands.
554
554
  *
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, cloneRepository, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, crc32, decodeText, defineConfig, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findSecretInPath, firstRunMessage, formatTokens, formatUpdateNotice, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, parseRemoteSource, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, startWebServer, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, updateCommand, validateSnapshot, walkFiles, workerEntry, wrapLines, writeZip } from './chunk-BOJYZQFB.js';
1
+ export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertUsableConfigInput, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, cloneRepository, collectFiles, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, crc32, decodeText, defineConfig, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findSecretInPath, firstRunMessage, formatTokens, formatUpdateNotice, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, parseRemoteSource, partitionFiles, planFirstRun, profileForPath, renderConfig, renderDiffText, renderExplainText, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, startWebServer, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, updateCommand, validateSnapshot, walkFiles, workerEntry, wrapLines, writeZip } from './chunk-KHHUC6UT.js';