codebase-snapshot 0.14.0 → 0.16.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.14.0";
2224
+ var GENERATOR_VERSION = "0.16.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
@@ -7134,6 +7142,7 @@ function validateSnapshot(configInput) {
7134
7142
  ["reports/diff.md", manifest.artifacts?.diff],
7135
7143
  ["reports/log.md", manifest.artifacts?.log],
7136
7144
  ["reports/tokens.md", manifest.artifacts?.tokenTree],
7145
+ ["reports/selection.md", manifest.artifacts?.selection],
7137
7146
  ["full-codebase.json", manifest.artifacts?.fullJson],
7138
7147
  ["full-codebase.md", manifest.artifacts?.fullMarkdown],
7139
7148
  ["full-codebase.xml", manifest.artifacts?.fullXml]
@@ -10141,6 +10150,51 @@ function generateNavigation(manifest) {
10141
10150
  return lines.join("\n");
10142
10151
  }
10143
10152
 
10153
+ // src/generator/selection.ts
10154
+ function generateSelectionReport(manifest, selection) {
10155
+ const lines = [];
10156
+ lines.push("# Selection");
10157
+ lines.push("");
10158
+ lines.push("**Kind:** `" + selection.kind + "` ");
10159
+ for (const detailLine of selection.detail.split("\n")) {
10160
+ lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
10161
+ }
10162
+ lines.push("**Selected files:** " + selection.files.length + " ");
10163
+ const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
10164
+ lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
10165
+ lines.push("");
10166
+ lines.push("## Why each file is here");
10167
+ lines.push("");
10168
+ lines.push("| File | Tokens | Reason |");
10169
+ lines.push("| :-- | --: | :-- |");
10170
+ for (const file of selection.files) {
10171
+ lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
10172
+ }
10173
+ lines.push("");
10174
+ const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
10175
+ if (typeof dropped === "number") {
10176
+ lines.push("## What was left out");
10177
+ lines.push("");
10178
+ lines.push(dropped + " file(s) were not selected. They are recorded in `manifest.json` as `skipped`");
10179
+ lines.push("with the reason `not-selected`, so nothing left the snapshot without a reason.");
10180
+ lines.push("");
10181
+ }
10182
+ const next = manifest.budget?.nextInLine ?? [];
10183
+ if (next.length > 0) {
10184
+ lines.push("## What a larger budget would buy");
10185
+ lines.push("");
10186
+ lines.push("Headroom: " + (manifest.budget?.headroomTokens ?? 0).toLocaleString("en-US") + " tokens.");
10187
+ lines.push("");
10188
+ lines.push("| File | Tokens |");
10189
+ lines.push("| :-- | --: |");
10190
+ for (const item of next) {
10191
+ lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
10192
+ }
10193
+ lines.push("");
10194
+ }
10195
+ return lines.join("\n");
10196
+ }
10197
+
10144
10198
  // src/mcp/retrieval.ts
10145
10199
  var STOPWORDS = /* @__PURE__ */ new Set([
10146
10200
  "the",
@@ -11873,6 +11927,7 @@ var ARTIFACT_FILES = {
11873
11927
  diff: "reports/diff.md",
11874
11928
  log: "reports/log.md",
11875
11929
  tokenTree: "reports/tokens.md",
11930
+ selection: "reports/selection.md",
11876
11931
  fullJson: "full-codebase.json",
11877
11932
  fullMarkdown: "full-codebase.md",
11878
11933
  fullXml: "full-codebase.xml",
@@ -13076,6 +13131,65 @@ var historyTool = {
13076
13131
  };
13077
13132
  }
13078
13133
  };
13134
+ var budgetTool = {
13135
+ name: "snapshot_budget",
13136
+ title: "What a larger budget would buy",
13137
+ description: 'Run the planner at several token budgets and report what each one adds: files, tokens used, entry points kept and the files gained over the previous budget. Answers "should I raise the budget, and what would I get?" without writing a snapshot. Read-only.',
13138
+ inputSchema: {
13139
+ type: "object",
13140
+ properties: {
13141
+ budgets: {
13142
+ type: "array",
13143
+ items: { type: "integer", minimum: 500 },
13144
+ description: "Token budgets to compare, ascending (default 10000, 30000, 60000)."
13145
+ },
13146
+ question: { type: "string", description: "Optional question to plan for; absent plans for the repository as a whole." },
13147
+ includeTests: { type: "boolean", description: "Include test files (default false)." },
13148
+ root: ROOT_PROPERTY,
13149
+ outDir: OUT_DIR_PROPERTY
13150
+ },
13151
+ additionalProperties: false
13152
+ },
13153
+ outputSchema: {
13154
+ type: "object",
13155
+ properties: { budgets: { type: "array", items: { type: "object" } } }
13156
+ },
13157
+ annotations: READ_ONLY,
13158
+ async handler(args, context) {
13159
+ const prepared = await prepare(args, context, outDirOverride(args));
13160
+ if (!prepared.ok) return prepared.outcome;
13161
+ const read = readManifest3(prepared.workspace);
13162
+ if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13163
+ const requested = Array.isArray(args.budgets) ? args.budgets.filter((value) => typeof value === "number").map((value) => Math.max(500, value)) : [1e4, 3e4, 6e4];
13164
+ const budgets = [...new Set(requested)].sort((left, right) => left - right);
13165
+ if (budgets.length === 0) return { text: "budgets must hold at least one number", isError: true };
13166
+ const question = typeof args.question === "string" ? args.question : "";
13167
+ const rows = [];
13168
+ let previous = /* @__PURE__ */ new Set();
13169
+ for (const budget of budgets) {
13170
+ const plan = planForQuestion(read.manifest, question, {
13171
+ maxTokens: budget,
13172
+ ...args.includeTests === true ? { includeTests: true } : {}
13173
+ });
13174
+ const paths = new Set(plan.files.map((file) => file.path));
13175
+ const gained = [...paths].filter((path28) => !previous.has(path28)).sort();
13176
+ previous = paths;
13177
+ rows.push({
13178
+ budget,
13179
+ files: plan.files.length,
13180
+ usedTokens: plan.usedTokens,
13181
+ gained
13182
+ });
13183
+ }
13184
+ const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
13185
+ for (const row of rows) {
13186
+ lines.push(
13187
+ row.budget.toLocaleString("en-US") + " tokens: " + row.files + " file(s), " + row.usedTokens.toLocaleString("en-US") + " used" + (row.gained.length === 0 ? "" : ", " + row.gained.length + " gained (" + row.gained.slice(0, 4).join(", ") + (row.gained.length > 4 ? ", \u2026" : "") + ")")
13188
+ );
13189
+ }
13190
+ return { text: lines.join("\n"), structured: { budgets: rows } };
13191
+ }
13192
+ };
13079
13193
  var testsTool = {
13080
13194
  name: "snapshot_tests",
13081
13195
  title: "Tests that cover a file, and files a test covers",
@@ -13762,6 +13876,11 @@ var symbolTool = {
13762
13876
  name: { type: "string", description: "Symbol name, case-insensitive." },
13763
13877
  lines: { type: "integer", description: "Window size around the definition (default 40).", minimum: 5 },
13764
13878
  maxFiles: { type: "integer", description: "Cap on files searched (default 5).", minimum: 1 },
13879
+ references: {
13880
+ type: "boolean",
13881
+ description: "Also report call sites: other files whose body mentions the name (default true)."
13882
+ },
13883
+ maxReferences: { type: "integer", description: "Cap on reported call sites (default 20).", minimum: 1 },
13765
13884
  root: ROOT_PROPERTY,
13766
13885
  outDir: OUT_DIR_PROPERTY
13767
13886
  },
@@ -13772,7 +13891,8 @@ var symbolTool = {
13772
13891
  type: "object",
13773
13892
  properties: {
13774
13893
  found: { type: "integer" },
13775
- matches: { type: "array", items: { type: "object" } }
13894
+ matches: { type: "array", items: { type: "object" } },
13895
+ references: { type: "array", items: { type: "object" } }
13776
13896
  }
13777
13897
  },
13778
13898
  annotations: READ_ONLY,
@@ -13825,8 +13945,44 @@ var symbolTool = {
13825
13945
  structured: { found: 0, matches: [] }
13826
13946
  };
13827
13947
  }
13828
- const text2 = matches.map((match) => "### " + match.path + " (" + match.part + ", line " + match.line + ")\n" + match.text).join("\n\n");
13829
- return { text: text2, structured: { found: matches.length, matches } };
13948
+ const callSites = [];
13949
+ if (args.references !== false) {
13950
+ const limit = Math.max(1, typeof args.maxReferences === "number" ? args.maxReferences : 20);
13951
+ const definitionKeys = new Set(matches.map((match) => match.path + ":" + match.line));
13952
+ const word = new RegExp("\\b" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "\\b");
13953
+ const parts = /* @__PURE__ */ new Map();
13954
+ let scanned = 0;
13955
+ for (const file of read.manifest.files) {
13956
+ if (callSites.length >= limit) break;
13957
+ const partPath = partPathFor(workspace, file.part);
13958
+ if (partPath === null) continue;
13959
+ let partText = parts.get(partPath);
13960
+ if (partText === void 0) {
13961
+ try {
13962
+ partText = fs24__namespace.readFileSync(partPath, "utf8");
13963
+ } catch {
13964
+ continue;
13965
+ }
13966
+ parts.set(partPath, partText);
13967
+ }
13968
+ if (scanned > MAX_SEARCH_BYTES) break;
13969
+ scanned += Buffer.byteLength(partText, "utf8");
13970
+ const section = findSection(parsePartSections(partText), file.relativePath);
13971
+ if (section === null) continue;
13972
+ const bodyLines = section.body.split("\n");
13973
+ for (let index = 0; index < bodyLines.length && callSites.length < limit; index += 1) {
13974
+ if (!word.test(bodyLines[index])) continue;
13975
+ callSites.push({
13976
+ path: file.relativePath,
13977
+ line: index + 1,
13978
+ text: bodyLines[index].trim().slice(0, 200),
13979
+ definition: definitionKeys.has(file.relativePath + ":" + (index + 1))
13980
+ });
13981
+ }
13982
+ }
13983
+ }
13984
+ 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")));
13985
+ return { text: text2, structured: { found: matches.length, matches, references: callSites } };
13830
13986
  }
13831
13987
  };
13832
13988
  var contextTool = {
@@ -14060,6 +14216,110 @@ var planForTool = {
14060
14216
  return { text: lines.join("\n"), structured: plan };
14061
14217
  }
14062
14218
  };
14219
+ var answerTool = {
14220
+ name: "snapshot_answer",
14221
+ title: "Question in, budgeted context out",
14222
+ description: "The one-call version of plan-then-read: plan a question, then return each chosen file as a head window with line numbers within the token budget. Every included file says why it is there; every planned file that did not fit says so. Read-only.",
14223
+ inputSchema: {
14224
+ type: "object",
14225
+ properties: {
14226
+ question: { type: "string", description: "What you need to answer." },
14227
+ maxTokens: { type: "integer", description: "Budget for the whole block (default 20000).", minimum: 500 },
14228
+ linesPerFile: { type: "integer", description: "Head lines per file (default 60).", minimum: 10 },
14229
+ includeTests: { type: "boolean", description: "Include test files (default false)." },
14230
+ root: ROOT_PROPERTY,
14231
+ outDir: OUT_DIR_PROPERTY
14232
+ },
14233
+ required: ["question"],
14234
+ additionalProperties: false
14235
+ },
14236
+ outputSchema: {
14237
+ type: "object",
14238
+ properties: {
14239
+ question: { type: "string" },
14240
+ budgetTokens: { type: "integer" },
14241
+ usedTokens: { type: "integer" },
14242
+ files: { type: "array", items: { type: "object" } },
14243
+ omitted: { type: "array", items: { type: "object" } }
14244
+ }
14245
+ },
14246
+ annotations: READ_ONLY,
14247
+ async handler(args, context) {
14248
+ const question = typeof args.question === "string" ? args.question.trim() : "";
14249
+ if (question.length === 0) return { text: "question must be a non-empty string", isError: true };
14250
+ const prepared = await prepare(args, context, outDirOverride(args));
14251
+ if (!prepared.ok) return prepared.outcome;
14252
+ const read = readManifest3(prepared.workspace);
14253
+ if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14254
+ const maxTokens = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 2e4);
14255
+ const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 60);
14256
+ const plan = planForQuestion(read.manifest, question, {
14257
+ maxTokens,
14258
+ ...args.includeTests === true ? { includeTests: true } : {}
14259
+ });
14260
+ const blocks = [];
14261
+ const omitted = [];
14262
+ let used = 0;
14263
+ const parts = /* @__PURE__ */ new Map();
14264
+ for (const planned of plan.files) {
14265
+ if (used >= maxTokens) {
14266
+ omitted.push({ path: planned.path, reason: "the budget was spent on earlier files" });
14267
+ continue;
14268
+ }
14269
+ const partPath = partPathFor(prepared.workspace, planned.part);
14270
+ if (partPath === null) {
14271
+ omitted.push({ path: planned.path, reason: "its part is not in the snapshot" });
14272
+ continue;
14273
+ }
14274
+ let partText = parts.get(partPath);
14275
+ if (partText === void 0) {
14276
+ try {
14277
+ partText = fs24__namespace.readFileSync(partPath, "utf8");
14278
+ } catch {
14279
+ omitted.push({ path: planned.path, reason: "its part could not be read" });
14280
+ continue;
14281
+ }
14282
+ parts.set(partPath, partText);
14283
+ }
14284
+ const section = findSection(parsePartSections(partText), planned.path);
14285
+ if (section === null) {
14286
+ omitted.push({ path: planned.path, reason: "no section in its part" });
14287
+ continue;
14288
+ }
14289
+ const window = windowText(section.body, 1, linesPerFile);
14290
+ const text2 = window.text;
14291
+ const tokens = estimateTokens(text2);
14292
+ if (used + tokens > maxTokens && blocks.length > 0) {
14293
+ omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
14294
+ continue;
14295
+ }
14296
+ const numbered = text2.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14297
+ blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
14298
+ used += tokens;
14299
+ }
14300
+ const lines = [
14301
+ "# Answer context: " + question,
14302
+ "Budget: " + used + " of " + maxTokens + " tokens; " + blocks.length + " file(s)."
14303
+ ];
14304
+ for (const block of blocks) {
14305
+ lines.push("");
14306
+ lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
14307
+ lines.push("Why: " + block.why);
14308
+ lines.push("```");
14309
+ lines.push(block.text);
14310
+ lines.push("```");
14311
+ }
14312
+ if (omitted.length > 0) {
14313
+ lines.push("");
14314
+ lines.push("Not included:");
14315
+ for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
14316
+ }
14317
+ return {
14318
+ text: lines.join("\n"),
14319
+ structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
14320
+ };
14321
+ }
14322
+ };
14063
14323
  var healthTool = {
14064
14324
  name: "snapshot_health",
14065
14325
  title: "Snapshot health audit",
@@ -14910,6 +15170,7 @@ var explainTool = {
14910
15170
  var TOOL_COSTS = {
14911
15171
  snapshot_status: "cheap",
14912
15172
  snapshot_health: "expensive",
15173
+ snapshot_budget: "medium",
14913
15174
  snapshot_history: "cheap",
14914
15175
  snapshot_tests: "cheap",
14915
15176
  snapshot_workspace: "cheap",
@@ -14925,6 +15186,7 @@ var TOOL_COSTS = {
14925
15186
  snapshot_context: "medium",
14926
15187
  snapshot_query: "cheap",
14927
15188
  snapshot_plan_for: "cheap",
15189
+ snapshot_answer: "medium",
14928
15190
  snapshot_plan: "expensive",
14929
15191
  snapshot_generate: "expensive",
14930
15192
  snapshot_validate: "medium",
@@ -14937,6 +15199,7 @@ function buildTools() {
14937
15199
  return [
14938
15200
  statusTool,
14939
15201
  healthTool,
15202
+ budgetTool,
14940
15203
  historyTool,
14941
15204
  testsTool,
14942
15205
  workspaceTool,
@@ -14952,6 +15215,7 @@ function buildTools() {
14952
15215
  contextTool,
14953
15216
  queryTool,
14954
15217
  planForTool,
15218
+ answerTool,
14955
15219
  planTool,
14956
15220
  generateTool,
14957
15221
  validateTool,
@@ -15130,6 +15394,8 @@ var VALIDATE_OPTIONS = [
15130
15394
  "sarif",
15131
15395
  "strip-comments",
15132
15396
  "remove-empty-lines",
15397
+ "only",
15398
+ "ignore",
15133
15399
  "pack",
15134
15400
  // The opt-in reports change the artifact selection the manifest records, so validate must accept
15135
15401
  // them to compare like with like: without the flags it reports the selection as drift.
@@ -15165,6 +15431,8 @@ var COMMAND_OPTION_SCOPE = {
15165
15431
  generate: [
15166
15432
  "strip-comments",
15167
15433
  "remove-empty-lines",
15434
+ "only",
15435
+ "ignore",
15168
15436
  "workspace",
15169
15437
  "budget-tokens",
15170
15438
  "sign",
@@ -15245,6 +15513,10 @@ var COMMAND_OPTION_SCOPE = {
15245
15513
  // Removed rather than implemented, because a flag that parses and does nothing is the defect
15246
15514
  // this table exists to prevent.
15247
15515
  "large-file-bytes",
15516
+ // `--only` and `--ignore` change which files are scanned, so they change what `explain` can say
15517
+ // about a path; without them the answer for an ignored file is "included: true".
15518
+ "only",
15519
+ "ignore",
15248
15520
  "include-sensitive-files",
15249
15521
  "no-config",
15250
15522
  "discovery",
@@ -15786,6 +16058,18 @@ function buildAgentContract() {
15786
16058
  appliesTo: optionAppliesTo("allow-origin"),
15787
16059
  summary: "mcp --http: comma-separated extra CORS origins. Loopback origins are always allowed."
15788
16060
  },
16061
+ {
16062
+ flag: "--only",
16063
+ type: "string",
16064
+ summary: "Comma-separated globs to include: overrides the config include list for this run.",
16065
+ appliesTo: optionAppliesTo("only")
16066
+ },
16067
+ {
16068
+ flag: "--ignore",
16069
+ type: "string",
16070
+ summary: "Comma-separated globs to exclude, added to the config exclude list for this run.",
16071
+ appliesTo: optionAppliesTo("ignore")
16072
+ },
15789
16073
  {
15790
16074
  flag: "--remove-empty-lines",
15791
16075
  type: "boolean",
@@ -16324,7 +16608,7 @@ diff, and the commit, are then yours.
16324
16608
  ## When the client speaks MCP
16325
16609
 
16326
16610
  If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
16327
- as 24 tools over stdio instead of shelling out. Its reads come from the snapshot rather than
16611
+ as 26 tools over stdio instead of shelling out. Its reads come from the snapshot rather than
16328
16612
  the working tree, so excluded files and redacted values never reach the context. Use
16329
16613
  \`snapshot_locate\` before \`snapshot_read\`, and \`snapshot_validate\` before trusting a snapshot
16330
16614
  from an earlier session.
@@ -19677,6 +19961,7 @@ function generateSnapshot(configInput, options) {
19677
19961
  }
19678
19962
  }
19679
19963
  let sliceBlock;
19964
+ let selectionReport = null;
19680
19965
  if (options?.slice !== void 0) {
19681
19966
  const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => ({
19682
19967
  path: file.relativePath,
@@ -19700,6 +19985,11 @@ function generateSnapshot(configInput, options) {
19700
19985
  files: plan.files.map((file) => file.path),
19701
19986
  dropped: scanned - plan.files.length
19702
19987
  };
19988
+ selectionReport = {
19989
+ kind: "slice",
19990
+ detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
19991
+ files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
19992
+ };
19703
19993
  }
19704
19994
  let budgetBlock;
19705
19995
  if (options?.budgetTokens !== void 0) {
@@ -19725,12 +20015,26 @@ function generateSnapshot(configInput, options) {
19725
20015
  const keep = /* @__PURE__ */ new Set();
19726
20016
  let used = 0;
19727
20017
  const selected = [];
20018
+ const chosen = [];
19728
20019
  for (const item of ranked) {
19729
20020
  if (used + item.tokens > budget) continue;
19730
20021
  keep.add(item.file.relativePath);
19731
20022
  selected.push(item.file.relativePath);
20023
+ chosen.push({
20024
+ path: item.file.relativePath,
20025
+ tokens: item.tokens,
20026
+ why: (entry(item.file.relativePath) ? "entry point" : "not an entry point") + "; " + (importers.get(item.file.relativePath) ?? 0) + " importer(s); layer " + item.file.layer
20027
+ });
19732
20028
  used += item.tokens;
19733
20029
  }
20030
+ const nextInLine = [];
20031
+ let headroom = budget - used;
20032
+ for (const item of ranked) {
20033
+ if (keep.has(item.file.relativePath)) continue;
20034
+ if (nextInLine.length >= 10) break;
20035
+ nextInLine.push({ path: item.file.relativePath, tokens: item.tokens });
20036
+ headroom = Math.max(headroom, item.tokens);
20037
+ }
19734
20038
  const scanned = files.length;
19735
20039
  const byLayer = {};
19736
20040
  let entryKept = 0;
@@ -19759,7 +20063,14 @@ function generateSnapshot(configInput, options) {
19759
20063
  usedTokens: used,
19760
20064
  files: selected,
19761
20065
  dropped: scanned - selected.length,
19762
- coverage: { byLayer, entryPoints: { kept: entryKept, total: entryTotal }, symbols: { kept: symbolsKept, total: symbolsTotal } }
20066
+ coverage: { byLayer, entryPoints: { kept: entryKept, total: entryTotal }, symbols: { kept: symbolsKept, total: symbolsTotal } },
20067
+ headroomTokens: Math.max(0, budget - used),
20068
+ nextInLine
20069
+ };
20070
+ selectionReport = {
20071
+ kind: "budget",
20072
+ detail: "Budget: " + budget.toLocaleString("en-US") + " tokens",
20073
+ files: chosen
19763
20074
  };
19764
20075
  if (entryTotal > 0 && entryKept < entryTotal) {
19765
20076
  warnings.push(
@@ -20068,6 +20379,8 @@ function generateSnapshot(configInput, options) {
20068
20379
  }) : null;
20069
20380
  if (promptText !== null) manifest.artifacts.prompt = artifactRecord(promptText);
20070
20381
  if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
20382
+ const selectionText = selectionReport === null ? null : generateSelectionReport(manifest, selectionReport);
20383
+ if (selectionText !== null) manifest.artifacts.selection = artifactRecord(selectionText);
20071
20384
  let monolithJson = null;
20072
20385
  let monolithMarkdown = null;
20073
20386
  let monolithXml = null;
@@ -20224,6 +20537,9 @@ function generateSnapshot(configInput, options) {
20224
20537
  if (tokenTree !== null) {
20225
20538
  writeArtifact(reportsDir, "tokens.md", tokenTree.text);
20226
20539
  }
20540
+ if (selectionText !== null) {
20541
+ writeArtifact(reportsDir, "selection.md", selectionText);
20542
+ }
20227
20543
  if (sarifText !== null) {
20228
20544
  writeArtifact(reportsDir, "audit.sarif", sarifText);
20229
20545
  }
@@ -20791,6 +21107,8 @@ var CLI_OPTIONS = {
20791
21107
  workspace: { type: "string" },
20792
21108
  "strip-comments": { type: "boolean" },
20793
21109
  "remove-empty-lines": { type: "boolean" },
21110
+ only: { type: "string" },
21111
+ ignore: { type: "string" },
20794
21112
  "all-members": { type: "boolean" },
20795
21113
  help: { type: "boolean", short: "h" },
20796
21114
  version: { type: "boolean", short: "v" }
@@ -21239,6 +21557,8 @@ function parseCliArgs(argv) {
21239
21557
  workspace: values.workspace === void 0 ? void 0 : String(values.workspace),
21240
21558
  stripComments: values["strip-comments"] === true ? true : void 0,
21241
21559
  removeEmptyLines: values["remove-empty-lines"] === true ? true : void 0,
21560
+ only: values.only === void 0 ? void 0 : String(values.only).split(",").map((item) => item.trim()).filter(Boolean),
21561
+ ignore: values.ignore === void 0 ? void 0 : String(values.ignore).split(",").map((item) => item.trim()).filter(Boolean),
21242
21562
  allMembers: values["all-members"] === true ? true : void 0,
21243
21563
  budgetTokens: values["budget-tokens"] === void 0 ? void 0 : parsePositiveInteger(values["budget-tokens"], "budget-tokens", 500),
21244
21564
  delta: values.delta === void 0 ? void 0 : String(values.delta),
@@ -21940,6 +22260,8 @@ ${USAGE}
21940
22260
  ...invocation.tokenTree === true ? { tokenTree: true } : {},
21941
22261
  ...invocation.stripComments === true ? { stripComments: true } : {},
21942
22262
  ...invocation.removeEmptyLines === true ? { removeEmptyLines: true } : {},
22263
+ ...invocation.only === void 0 ? {} : { only: invocation.only },
22264
+ ...invocation.ignore === void 0 ? {} : { ignore: invocation.ignore },
21943
22265
  ...invocation.pack === void 0 ? {} : { pack: invocation.pack },
21944
22266
  brief: invocation.brief,
21945
22267
  promptTask: invocation.promptTask,
@@ -22076,6 +22398,15 @@ ${USAGE}
22076
22398
  info(` - Entry points: ${coverage.entryPoints.kept} of ${coverage.entryPoints.total}`);
22077
22399
  info(` - Symbols: ${coverage.symbols.kept} of ${coverage.symbols.total}`);
22078
22400
  }
22401
+ if (manifest.budget.headroomTokens !== void 0) {
22402
+ info(` - Headroom: ${formatNumber(manifest.budget.headroomTokens)} tokens`);
22403
+ }
22404
+ if (manifest.budget.nextInLine !== void 0 && manifest.budget.nextInLine.length > 0) {
22405
+ const next = manifest.budget.nextInLine.slice(0, 5);
22406
+ info(
22407
+ " - Next in line: " + next.map((item) => item.path + " (" + formatNumber(item.tokens) + ")").join(", ") + (manifest.budget.nextInLine.length > next.length ? ", \u2026" : "")
22408
+ );
22409
+ }
22079
22410
  }
22080
22411
  if (manifest.delta !== void 0) {
22081
22412
  const delta = manifest.delta;
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-Cr5H2Y3t.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
  }
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-Cr5H2Y3t.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-7WSZUMT6.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-2YNQ42B3.js';
3
- export { buildAgentContract } from './chunk-2YNQ42B3.js';
1
+ import { startHttpTransport } from './chunk-ZDTAWUD4.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-AEGJYOCF.js';
3
+ export { buildAgentContract } from './chunk-AEGJYOCF.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,
@@ -1470,6 +1476,15 @@ ${USAGE}
1470
1476
  info(` - Entry points: ${coverage.entryPoints.kept} of ${coverage.entryPoints.total}`);
1471
1477
  info(` - Symbols: ${coverage.symbols.kept} of ${coverage.symbols.total}`);
1472
1478
  }
1479
+ if (manifest.budget.headroomTokens !== void 0) {
1480
+ info(` - Headroom: ${formatNumber(manifest.budget.headroomTokens)} tokens`);
1481
+ }
1482
+ if (manifest.budget.nextInLine !== void 0 && manifest.budget.nextInLine.length > 0) {
1483
+ const next = manifest.budget.nextInLine.slice(0, 5);
1484
+ info(
1485
+ " - Next in line: " + next.map((item) => item.path + " (" + formatNumber(item.tokens) + ")").join(", ") + (manifest.budget.nextInLine.length > next.length ? ", \u2026" : "")
1486
+ );
1487
+ }
1473
1488
  }
1474
1489
  if (manifest.delta !== void 0) {
1475
1490
  const delta = manifest.delta;