codebase-snapshot 0.15.0 → 0.17.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/CHANGELOG.md CHANGED
@@ -30,6 +30,172 @@ deprecated with an explanatory message instead. `latest` has pointed at 0.9.0 si
30
30
 
31
31
  ---
32
32
 
33
+ ## 0.17.0
34
+
35
+ **The endgame: what this is, and how it is proven.**
36
+
37
+ `codebase-snapshot` reads a repository and writes a text representation of it that an AI reader can
38
+ use: budgeted parts, a manifest that accounts for every path, and — since 0.12.15 — a server that
39
+ answers questions about the repository instead of making the reader open all of it.
40
+
41
+ ### What a reader gets
42
+
43
+ - **A dump that fits.** Byte-budgeted parts, a per-file accounting of what was written, previewed,
44
+ stripped or skipped, and an audit that recomputes those claims from the parts.
45
+ - **A selection, when the question is narrower than the repository**: `--slice` for a question,
46
+ `--budget-tokens` for a ceiling, `--delta` for a change set. Each explains itself in
47
+ `reports/selection.md`, and each records what it left out.
48
+ - **A server that answers questions.** 26 MCP tools over stdio or Streamable HTTP with bearer tokens,
49
+ from `snapshot_answer` (question to cited windows) to `snapshot_health` (an audit of the snapshot
50
+ itself), plus prompts and resources. Reads come from the snapshot, so redaction and exclusions
51
+ still apply.
52
+ - **Proof of its own output.** Ed25519 signatures, artifact digests, a workspace index that must
53
+ agree with its members, and `snapshot health` with a score and a strict exit code.
54
+
55
+ ### The program, by milestone
56
+
57
+ | Version | Theme | Published |
58
+ | :--- | :--- | :--- |
59
+ | 0.13.0 | The MCP server, remote ingestion, signing, slicing, delta packs, multi-repo | 2026-11-18 |
60
+ | 0.14.0 | The audit proves the manifest: bodies, counts, packs, workspace index, metrics | 2026-11-18 |
61
+ | 0.15.0 | Parity measured on ten public repositories; per-run `--only`/`--ignore` | 2026-11-18 |
62
+ | 0.16.0 | Beyond parity: self-explaining selections, what-if budgets, `snapshot_answer` | 2026-11-18 |
63
+ | 0.17.0 | This milestone: the site, the security review, the migration guide, the final number | 2026-11-18 |
64
+
65
+ Every version in between was committed, tagged and pushed; `x.y.0` is what the registry carries, and
66
+ `latest` never points at a patch. The number is not the promise — the changelog entry is.
67
+
68
+ ### How it is proven
69
+
70
+ - **Tests**: 1333 in the suite, 1325 passing, 0 failing, 8 skipped because they need a host this
71
+ runner is not. The suite treats the tool as a black box where it can: generate, validate, serve,
72
+ ask, and check the answer.
73
+ - **The audit**: every generated snapshot in the suite is audited, and the audit is itself probed by
74
+ breaking what it claims to check — a truncated part, an edited count, a pack minus one entry, an
75
+ index with a wrong fingerprint, an edited selection report.
76
+ - **Measurement**: ten public repositories through this tool, repomix and gitingest in one command
77
+ (`scripts/benchmark-suite.mjs`), with the page saying where the numbers are comparable and where
78
+ they are a policy difference.
79
+ - **The artifact**: a 53-file tarball whose lockfile agrees with `package.json`, checked before every
80
+ publish by the same `verify` a reader can run.
81
+ - **The site**: 30 pages, every one with a description, a canonical URL and no broken link
82
+ (`audit-site`), generated from the same documents the repository ships.
83
+
84
+ ### What is deliberately not here
85
+
86
+ - **No 1.0.0.** The line ends at 0.17.0 because a version number is a promise about stability, and
87
+ this project would rather make the next promise in a changelog than in a semver jump.
88
+ - **No runtime dependencies.** Node built-ins and the TypeScript compiler (a dev dependency) only.
89
+ - **No silent fallback.** An unknown flag, preset, budget or config key is an error, and a path that
90
+ leaves the snapshot is recorded with the reason it left.
91
+ ## 0.16.2
92
+
93
+ **The endgame pages.**
94
+
95
+ - `docs/answer.md` is a site page of its own: one call from question to cited, line-numbered
96
+ context, the four-way comparison with `plan_for`/`read`/`budget`, and what the tool deliberately
97
+ will not do (invent a path, truncate silently, read the working tree, exceed the budget without
98
+ saying so). 30 pages, audit-site clean.
99
+ - The site builder still described the tool reference as "All 22 MCP tools"; it is 26, and the
100
+ number now matches `tools/list`.
101
+ - `docs/security-review.md` gains "What changed since this review was written": metrics labels, the
102
+ web server's allowed roots, the audit that stopped trusting the manifest, `snapshot_answer`, and
103
+ `--only`/`--ignore` — each reviewed for what new input arrives and what it can reach.
104
+ - `docs/migration.md` gains the 0.13.0-0.17.0 table: what a reader upgrading across those milestones
105
+ will notice, and why nothing was removed.
106
+ ## 0.16.1
107
+
108
+ - The goal log records the fourth published milestone: 0.16.0 tagged, released on GitHub and
109
+ published to npm (`latest` at 01:52Z). `ROADMAP.md` marks it published.
110
+ ## 0.16.0
111
+
112
+ **Things neither competitor has.**
113
+
114
+ Parity was the floor. This milestone is what the snapshot does that repomix and gitingest do not:
115
+
116
+ - **Selections, not dumps.** `--slice "question"`, `--budget-tokens N` and `--delta <base>` each
117
+ narrow the snapshot to what answers a question, fits a budget, or changed. The three are mutually
118
+ exclusive on purpose: each is a different claim, and letting two win silently would make the
119
+ manifest describe a selection nobody asked for.
120
+ - **The selection explains itself.** `reports/selection.md` (0.15.3) lists every chosen file with its
121
+ cost and reason, what was left out, and what a larger budget would buy next; it is a recorded
122
+ artifact, so `validate` treats an edited one as drift.
123
+ - **Budgets answer "what if".** `snapshot_budget` (0.15.2) runs the planner at several budgets and
124
+ reports what each adds; the manifest records `headroomTokens` and `nextInLine`.
125
+ - **Question in, cited context out.** `snapshot_answer` (0.15.5) plans a question and returns
126
+ line-numbered windows within one budget, each with its reason, every omission named.
127
+ - **Multi-repo workspaces** with `WORKSPACE.json`, cross-member import links and a workspace-wide
128
+ audit (`health --all-members`).
129
+ - **Signed manifests** (Ed25519) behind `--sign`, verified by `validate` and the audit.
130
+ - **An audit that proves the manifest** rather than trusting it: bodies, counts, packs, the workspace
131
+ index, host paths and secrets — the work of 0.14.x, now part of what a snapshot is.
132
+
133
+ ### The shape of the whole
134
+
135
+ A reader should be able to take a snapshot and answer three questions without the working tree:
136
+ what is in it (manifest, navigation, tree), why it is in it (selection report, skip records), and
137
+ whether it is what it says it is (hashes, signatures, audit). None of the three depends on the other
138
+ two agreeing by accident.
139
+
140
+ ### How it was verified
141
+
142
+ Full `npm run verify`: 1333 tests, 1325 pass, 0 fail, 8 host skips; 29 site pages with no link or
143
+ metadata problems; a 52-file tarball whose lockfile agrees with `package.json`. The new tools are
144
+ pinned by tests that call them over the real MCP registry, and the docs/schema parity test fails if a
145
+ tool is documented but absent or present but undocumented.
146
+ ## 0.15.5
147
+
148
+ **`snapshot_answer`: question in, cited context out, in one call.**
149
+
150
+ - The 26th tool. `snapshot_plan_for` says which files to read and `snapshot_read` returns one of
151
+ them; an agent that wants an answer had to make a call per file and do its own budget arithmetic.
152
+ `snapshot_answer` plans the question, then returns each chosen file as a head window with line
153
+ numbers, within one token budget.
154
+ - Every included file carries its `why` from the planner. Every planned file that did not fit is
155
+ listed under "Not included" with the reason — the budget, a missing part, or a missing section —
156
+ so a truncated answer never looks like a complete one.
157
+ - The block is measured with the same estimator as the manifest, so `usedTokens` is comparable with
158
+ every other token figure this tool prints.
159
+
160
+ Verified: a question about a fixture module returns line-numbered windows, each with a reason;
161
+ `usedTokens` stays within the requested budget.
162
+ ## 0.15.4
163
+
164
+ - The goal log records the 0.15.2-0.15.3 round: `snapshot_budget`, budget headroom and `nextInLine`,
165
+ and `reports/selection.md` for narrowed snapshots.
166
+ - `AGENTS.md` said the MCP server exposes 21 tools; it exposes 25. The count is part of the contract
167
+ and a wrong one is a lie, however small.
168
+ ## 0.15.3
169
+
170
+ **A narrowed snapshot explains itself.**
171
+
172
+ - A slice or a budget now writes `reports/selection.md`: the question and budget, every chosen file
173
+ with its token cost and the reason it was chosen, the count of files left out, and for a budget
174
+ the files a larger budget would buy next. The numbers come from the manifest blocks, so the report
175
+ and the data cannot drift.
176
+ - The report is a recorded artifact: `validate` fails when it is edited or deleted, and the audit
177
+ expects it only when the manifest records it.
178
+
179
+ Verified: `--slice` writes the question and the chosen path; `--budget-tokens 500` names the
180
+ headroom and the next files; appending one line to the report makes `validate` fail with the path.
181
+ ## 0.15.2
182
+
183
+ **Budgets answer "what if", not only "what fits".**
184
+
185
+ - **`snapshot_budget`, the 25th tool**: run the planner at several budgets and report what each one
186
+ adds — files, tokens used, and the paths gained over the previous budget. The question a budget
187
+ raises ("should I raise it, and what would I get?") is now answerable without writing a snapshot.
188
+ - The budget block in the manifest records `headroomTokens` and `nextInLine` — the files a larger
189
+ budget would take, in the order it would take them. `report` prints both, so the CLI shows the same
190
+ answer as the tool.
191
+
192
+ Verified: a 500-token budget on a fixture selects 3 of 8 files, reports 2 tokens of headroom and
193
+ names the next six by cost; `snapshot_budget` at 500 and 5,000 returns a superset with the gained
194
+ paths listed.
195
+ ## 0.15.1
196
+
197
+ - The goal log records the third published milestone: 0.15.0 tagged, released on GitHub and
198
+ published to npm (`latest` at 01:33Z). `ROADMAP.md` marks it published.
33
199
  ## 0.15.0
34
200
 
35
201
  **Parity, measured on someone else's repositories.**
package/README.md CHANGED
@@ -210,13 +210,13 @@ Everything an agent needs is available as data, and the tool can install its own
210
210
  ```bash
211
211
  npx codebase-snapshot describe --format json # contract: workflow, options, exit codes
212
212
  npx codebase-snapshot skill --install # into .claude/skills + .cursor/rules
213
- npx -y codebase-snapshot@0.15.0 mcp # or serve it over MCP
213
+ npx -y codebase-snapshot@0.17.0 mcp # or serve it over MCP
214
214
  ```
215
215
 
216
216
  An agent told only "use `npx codebase-snapshot`" can read the contract, follow its ordered
217
217
  workflow, and produce a validated snapshot unaided — that path is covered by a test.
218
218
 
219
- The MCP server exposes 24 tools — status, health, entrypoints, neighbors, routes, cycles, stats, search, review, symbol, diff_context, context, query, plan_for, plan, generate, validate, locate, dependents, read, explain — plus
219
+ The MCP server exposes 26 tools — status, health, entrypoints, neighbors, routes, cycles, stats, search, review, symbol, diff_context, context, query, plan_for, plan, generate, validate, locate, dependents, read, explain — plus
220
220
  `snapshot://` resources and two prompts. Its reads come from the snapshot rather than the working
221
221
  tree, so an excluded file stays excluded and a redacted value stays redacted, and
222
222
  `snapshot_validate` answers the question an agent otherwise cannot ask: is the context I was given
@@ -283,7 +283,7 @@ others.
283
283
  | [Token budget](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/budget.md) | `--budget-tokens`: whole files chosen to fit a limit, not torn to fit a part |
284
284
  | [The brief](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/brief.md) | The half of PROMPT.md only you can write, and what is refused |
285
285
  | [AI agents](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/agent.md) | The contract, the skill, what an agent should avoid |
286
- | [MCP server](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/mcp.md) | 24 tools, resources, both protocol eras |
286
+ | [MCP server](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/mcp.md) | 26 tools, resources, both protocol eras |
287
287
  | [Troubleshooting](https://github.com/ankurhalder/codebase-snapshot/blob/main/docs/troubleshooting.md) | Every message and what to do about it |
288
288
  | [Changelog](https://github.com/ankurhalder/codebase-snapshot/blob/main/CHANGELOG.md) | Release history and breaking changes |
289
289
 
package/SECURITY.md CHANGED
@@ -6,11 +6,11 @@ Only the latest published release receives security fixes.
6
6
 
7
7
  | Version | Supported |
8
8
  | :--- | :--- |
9
- | <!--@majorMinor-->0.15<!--/@majorMinor-->.x | ✅ |
9
+ | <!--@majorMinor-->0.17<!--/@majorMinor-->.x | ✅ |
10
10
  | anything older | ❌ |
11
11
 
12
12
  The number line restarted at 0.9.0 when the package moved to the unscoped `codebase-snapshot` name,
13
- so <!--@majorMinor-->0.15<!--/@majorMinor-->.x is newer than 4.4.1, not older. That is explained in full in the
13
+ so <!--@majorMinor-->0.17<!--/@majorMinor-->.x is newer than 4.4.1, not older. That is explained in full in the
14
14
  [changelog](CHANGELOG.md#a-note-on-version-numbers).
15
15
 
16
16
  ## Reporting a vulnerability
package/dist/bin.js CHANGED
@@ -2191,7 +2191,7 @@ function applySpansKeepingQuotes(line, spans) {
2191
2191
 
2192
2192
  // src/version.ts
2193
2193
  var GENERATOR_NAME = "codebase-snapshot";
2194
- var GENERATOR_VERSION = "0.15.0";
2194
+ var GENERATOR_VERSION = "0.17.0";
2195
2195
  var SCHEMA_VERSION = "3.0.0";
2196
2196
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2197
2197
  function isOurGeneratorName(name) {
@@ -7145,6 +7145,7 @@ function validateSnapshot(configInput) {
7145
7145
  ["reports/diff.md", manifest.artifacts?.diff],
7146
7146
  ["reports/log.md", manifest.artifacts?.log],
7147
7147
  ["reports/tokens.md", manifest.artifacts?.tokenTree],
7148
+ ["reports/selection.md", manifest.artifacts?.selection],
7148
7149
  ["full-codebase.json", manifest.artifacts?.fullJson],
7149
7150
  ["full-codebase.md", manifest.artifacts?.fullMarkdown],
7150
7151
  ["full-codebase.xml", manifest.artifacts?.fullXml]
@@ -10203,6 +10204,51 @@ function generateNavigation(manifest) {
10203
10204
  return lines.join("\n");
10204
10205
  }
10205
10206
 
10207
+ // src/generator/selection.ts
10208
+ function generateSelectionReport(manifest, selection) {
10209
+ const lines = [];
10210
+ lines.push("# Selection");
10211
+ lines.push("");
10212
+ lines.push("**Kind:** `" + selection.kind + "` ");
10213
+ for (const detailLine of selection.detail.split("\n")) {
10214
+ lines.push("**" + detailLine.slice(0, detailLine.indexOf(":")) + ":**" + detailLine.slice(detailLine.indexOf(":") + 1) + " ");
10215
+ }
10216
+ lines.push("**Selected files:** " + selection.files.length + " ");
10217
+ const spent = manifest.budget?.usedTokens ?? manifest.slice?.usedTokens ?? 0;
10218
+ lines.push("**Tokens spent:** " + spent.toLocaleString("en-US"));
10219
+ lines.push("");
10220
+ lines.push("## Why each file is here");
10221
+ lines.push("");
10222
+ lines.push("| File | Tokens | Reason |");
10223
+ lines.push("| :-- | --: | :-- |");
10224
+ for (const file of selection.files) {
10225
+ lines.push("| `" + file.path + "` | " + file.tokens.toLocaleString("en-US") + " | " + file.why + " |");
10226
+ }
10227
+ lines.push("");
10228
+ const dropped = selection.kind === "slice" ? manifest.slice?.dropped : manifest.budget?.dropped;
10229
+ if (typeof dropped === "number") {
10230
+ lines.push("## What was left out");
10231
+ lines.push("");
10232
+ lines.push(dropped + " file(s) were not selected. They are recorded in `manifest.json` as `skipped`");
10233
+ lines.push("with the reason `not-selected`, so nothing left the snapshot without a reason.");
10234
+ lines.push("");
10235
+ }
10236
+ const next = manifest.budget?.nextInLine ?? [];
10237
+ if (next.length > 0) {
10238
+ lines.push("## What a larger budget would buy");
10239
+ lines.push("");
10240
+ lines.push("Headroom: " + (manifest.budget?.headroomTokens ?? 0).toLocaleString("en-US") + " tokens.");
10241
+ lines.push("");
10242
+ lines.push("| File | Tokens |");
10243
+ lines.push("| :-- | --: |");
10244
+ for (const item of next) {
10245
+ lines.push("| `" + item.path + "` | " + item.tokens.toLocaleString("en-US") + " |");
10246
+ }
10247
+ lines.push("");
10248
+ }
10249
+ return lines.join("\n");
10250
+ }
10251
+
10206
10252
  // src/mcp/retrieval.ts
10207
10253
  var STOPWORDS = /* @__PURE__ */ new Set([
10208
10254
  "the",
@@ -11982,6 +12028,7 @@ var ARTIFACT_FILES = {
11982
12028
  diff: "reports/diff.md",
11983
12029
  log: "reports/log.md",
11984
12030
  tokenTree: "reports/tokens.md",
12031
+ selection: "reports/selection.md",
11985
12032
  fullJson: "full-codebase.json",
11986
12033
  fullMarkdown: "full-codebase.md",
11987
12034
  fullXml: "full-codebase.xml",
@@ -13194,6 +13241,65 @@ var historyTool = {
13194
13241
  };
13195
13242
  }
13196
13243
  };
13244
+ var budgetTool = {
13245
+ name: "snapshot_budget",
13246
+ title: "What a larger budget would buy",
13247
+ 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.',
13248
+ inputSchema: {
13249
+ type: "object",
13250
+ properties: {
13251
+ budgets: {
13252
+ type: "array",
13253
+ items: { type: "integer", minimum: 500 },
13254
+ description: "Token budgets to compare, ascending (default 10000, 30000, 60000)."
13255
+ },
13256
+ question: { type: "string", description: "Optional question to plan for; absent plans for the repository as a whole." },
13257
+ includeTests: { type: "boolean", description: "Include test files (default false)." },
13258
+ root: ROOT_PROPERTY,
13259
+ outDir: OUT_DIR_PROPERTY
13260
+ },
13261
+ additionalProperties: false
13262
+ },
13263
+ outputSchema: {
13264
+ type: "object",
13265
+ properties: { budgets: { type: "array", items: { type: "object" } } }
13266
+ },
13267
+ annotations: READ_ONLY,
13268
+ async handler(args, context) {
13269
+ const prepared = await prepare(args, context, outDirOverride(args));
13270
+ if (!prepared.ok) return prepared.outcome;
13271
+ const read = readManifest3(prepared.workspace);
13272
+ if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
13273
+ const requested = Array.isArray(args.budgets) ? args.budgets.filter((value) => typeof value === "number").map((value) => Math.max(500, value)) : [1e4, 3e4, 6e4];
13274
+ const budgets = [...new Set(requested)].sort((left, right) => left - right);
13275
+ if (budgets.length === 0) return { text: "budgets must hold at least one number", isError: true };
13276
+ const question = typeof args.question === "string" ? args.question : "";
13277
+ const rows = [];
13278
+ let previous = /* @__PURE__ */ new Set();
13279
+ for (const budget of budgets) {
13280
+ const plan = planForQuestion(read.manifest, question, {
13281
+ maxTokens: budget,
13282
+ ...args.includeTests === true ? { includeTests: true } : {}
13283
+ });
13284
+ const paths = new Set(plan.files.map((file) => file.path));
13285
+ const gained = [...paths].filter((path28) => !previous.has(path28)).sort();
13286
+ previous = paths;
13287
+ rows.push({
13288
+ budget,
13289
+ files: plan.files.length,
13290
+ usedTokens: plan.usedTokens,
13291
+ gained
13292
+ });
13293
+ }
13294
+ const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
13295
+ for (const row of rows) {
13296
+ lines.push(
13297
+ 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" : "") + ")")
13298
+ );
13299
+ }
13300
+ return { text: lines.join("\n"), structured: { budgets: rows } };
13301
+ }
13302
+ };
13197
13303
  var testsTool = {
13198
13304
  name: "snapshot_tests",
13199
13305
  title: "Tests that cover a file, and files a test covers",
@@ -14220,6 +14326,110 @@ var planForTool = {
14220
14326
  return { text: lines.join("\n"), structured: plan };
14221
14327
  }
14222
14328
  };
14329
+ var answerTool = {
14330
+ name: "snapshot_answer",
14331
+ title: "Question in, budgeted context out",
14332
+ 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.",
14333
+ inputSchema: {
14334
+ type: "object",
14335
+ properties: {
14336
+ question: { type: "string", description: "What you need to answer." },
14337
+ maxTokens: { type: "integer", description: "Budget for the whole block (default 20000).", minimum: 500 },
14338
+ linesPerFile: { type: "integer", description: "Head lines per file (default 60).", minimum: 10 },
14339
+ includeTests: { type: "boolean", description: "Include test files (default false)." },
14340
+ root: ROOT_PROPERTY,
14341
+ outDir: OUT_DIR_PROPERTY
14342
+ },
14343
+ required: ["question"],
14344
+ additionalProperties: false
14345
+ },
14346
+ outputSchema: {
14347
+ type: "object",
14348
+ properties: {
14349
+ question: { type: "string" },
14350
+ budgetTokens: { type: "integer" },
14351
+ usedTokens: { type: "integer" },
14352
+ files: { type: "array", items: { type: "object" } },
14353
+ omitted: { type: "array", items: { type: "object" } }
14354
+ }
14355
+ },
14356
+ annotations: READ_ONLY,
14357
+ async handler(args, context) {
14358
+ const question = typeof args.question === "string" ? args.question.trim() : "";
14359
+ if (question.length === 0) return { text: "question must be a non-empty string", isError: true };
14360
+ const prepared = await prepare(args, context, outDirOverride(args));
14361
+ if (!prepared.ok) return prepared.outcome;
14362
+ const read = readManifest3(prepared.workspace);
14363
+ if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
14364
+ const maxTokens = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 2e4);
14365
+ const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 60);
14366
+ const plan = planForQuestion(read.manifest, question, {
14367
+ maxTokens,
14368
+ ...args.includeTests === true ? { includeTests: true } : {}
14369
+ });
14370
+ const blocks = [];
14371
+ const omitted = [];
14372
+ let used = 0;
14373
+ const parts = /* @__PURE__ */ new Map();
14374
+ for (const planned of plan.files) {
14375
+ if (used >= maxTokens) {
14376
+ omitted.push({ path: planned.path, reason: "the budget was spent on earlier files" });
14377
+ continue;
14378
+ }
14379
+ const partPath = partPathFor(prepared.workspace, planned.part);
14380
+ if (partPath === null) {
14381
+ omitted.push({ path: planned.path, reason: "its part is not in the snapshot" });
14382
+ continue;
14383
+ }
14384
+ let partText = parts.get(partPath);
14385
+ if (partText === void 0) {
14386
+ try {
14387
+ partText = fs18.readFileSync(partPath, "utf8");
14388
+ } catch {
14389
+ omitted.push({ path: planned.path, reason: "its part could not be read" });
14390
+ continue;
14391
+ }
14392
+ parts.set(partPath, partText);
14393
+ }
14394
+ const section = findSection(parsePartSections(partText), planned.path);
14395
+ if (section === null) {
14396
+ omitted.push({ path: planned.path, reason: "no section in its part" });
14397
+ continue;
14398
+ }
14399
+ const window = windowText(section.body, 1, linesPerFile);
14400
+ const text2 = window.text;
14401
+ const tokens = estimateTokens(text2);
14402
+ if (used + tokens > maxTokens && blocks.length > 0) {
14403
+ omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
14404
+ continue;
14405
+ }
14406
+ const numbered = text2.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
14407
+ blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
14408
+ used += tokens;
14409
+ }
14410
+ const lines = [
14411
+ "# Answer context: " + question,
14412
+ "Budget: " + used + " of " + maxTokens + " tokens; " + blocks.length + " file(s)."
14413
+ ];
14414
+ for (const block of blocks) {
14415
+ lines.push("");
14416
+ lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
14417
+ lines.push("Why: " + block.why);
14418
+ lines.push("```");
14419
+ lines.push(block.text);
14420
+ lines.push("```");
14421
+ }
14422
+ if (omitted.length > 0) {
14423
+ lines.push("");
14424
+ lines.push("Not included:");
14425
+ for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
14426
+ }
14427
+ return {
14428
+ text: lines.join("\n"),
14429
+ structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
14430
+ };
14431
+ }
14432
+ };
14223
14433
  var healthTool = {
14224
14434
  name: "snapshot_health",
14225
14435
  title: "Snapshot health audit",
@@ -15070,6 +15280,7 @@ var explainTool = {
15070
15280
  var TOOL_COSTS = {
15071
15281
  snapshot_status: "cheap",
15072
15282
  snapshot_health: "expensive",
15283
+ snapshot_budget: "medium",
15073
15284
  snapshot_history: "cheap",
15074
15285
  snapshot_tests: "cheap",
15075
15286
  snapshot_workspace: "cheap",
@@ -15085,6 +15296,7 @@ var TOOL_COSTS = {
15085
15296
  snapshot_context: "medium",
15086
15297
  snapshot_query: "cheap",
15087
15298
  snapshot_plan_for: "cheap",
15299
+ snapshot_answer: "medium",
15088
15300
  snapshot_plan: "expensive",
15089
15301
  snapshot_generate: "expensive",
15090
15302
  snapshot_validate: "medium",
@@ -15097,6 +15309,7 @@ function buildTools() {
15097
15309
  return [
15098
15310
  statusTool,
15099
15311
  healthTool,
15312
+ budgetTool,
15100
15313
  historyTool,
15101
15314
  testsTool,
15102
15315
  workspaceTool,
@@ -15112,6 +15325,7 @@ function buildTools() {
15112
15325
  contextTool,
15113
15326
  queryTool,
15114
15327
  planForTool,
15328
+ answerTool,
15115
15329
  planTool,
15116
15330
  generateTool,
15117
15331
  validateTool,
@@ -16504,7 +16718,7 @@ diff, and the commit, are then yours.
16504
16718
  ## When the client speaks MCP
16505
16719
 
16506
16720
  If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
16507
- as 24 tools over stdio instead of shelling out. Its reads come from the snapshot rather than
16721
+ as 26 tools over stdio instead of shelling out. Its reads come from the snapshot rather than
16508
16722
  the working tree, so excluded files and redacted values never reach the context. Use
16509
16723
  \`snapshot_locate\` before \`snapshot_read\`, and \`snapshot_validate\` before trusting a snapshot
16510
16724
  from an earlier session.
@@ -19876,6 +20090,7 @@ function generateSnapshot(configInput, options) {
19876
20090
  }
19877
20091
  }
19878
20092
  let sliceBlock;
20093
+ let selectionReport = null;
19879
20094
  if (options?.slice !== void 0) {
19880
20095
  const byFile = files.filter((file) => isSourceSummary(file.summary)).map((file) => ({
19881
20096
  path: file.relativePath,
@@ -19899,6 +20114,11 @@ function generateSnapshot(configInput, options) {
19899
20114
  files: plan.files.map((file) => file.path),
19900
20115
  dropped: scanned - plan.files.length
19901
20116
  };
20117
+ selectionReport = {
20118
+ kind: "slice",
20119
+ detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
20120
+ files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
20121
+ };
19902
20122
  }
19903
20123
  let budgetBlock;
19904
20124
  if (options?.budgetTokens !== void 0) {
@@ -19924,12 +20144,26 @@ function generateSnapshot(configInput, options) {
19924
20144
  const keep = /* @__PURE__ */ new Set();
19925
20145
  let used = 0;
19926
20146
  const selected = [];
20147
+ const chosen = [];
19927
20148
  for (const item of ranked) {
19928
20149
  if (used + item.tokens > budget) continue;
19929
20150
  keep.add(item.file.relativePath);
19930
20151
  selected.push(item.file.relativePath);
20152
+ chosen.push({
20153
+ path: item.file.relativePath,
20154
+ tokens: item.tokens,
20155
+ why: (entry(item.file.relativePath) ? "entry point" : "not an entry point") + "; " + (importers.get(item.file.relativePath) ?? 0) + " importer(s); layer " + item.file.layer
20156
+ });
19931
20157
  used += item.tokens;
19932
20158
  }
20159
+ const nextInLine = [];
20160
+ let headroom = budget - used;
20161
+ for (const item of ranked) {
20162
+ if (keep.has(item.file.relativePath)) continue;
20163
+ if (nextInLine.length >= 10) break;
20164
+ nextInLine.push({ path: item.file.relativePath, tokens: item.tokens });
20165
+ headroom = Math.max(headroom, item.tokens);
20166
+ }
19933
20167
  const scanned = files.length;
19934
20168
  const byLayer = {};
19935
20169
  let entryKept = 0;
@@ -19958,7 +20192,14 @@ function generateSnapshot(configInput, options) {
19958
20192
  usedTokens: used,
19959
20193
  files: selected,
19960
20194
  dropped: scanned - selected.length,
19961
- coverage: { byLayer, entryPoints: { kept: entryKept, total: entryTotal }, symbols: { kept: symbolsKept, total: symbolsTotal } }
20195
+ coverage: { byLayer, entryPoints: { kept: entryKept, total: entryTotal }, symbols: { kept: symbolsKept, total: symbolsTotal } },
20196
+ headroomTokens: Math.max(0, budget - used),
20197
+ nextInLine
20198
+ };
20199
+ selectionReport = {
20200
+ kind: "budget",
20201
+ detail: "Budget: " + budget.toLocaleString("en-US") + " tokens",
20202
+ files: chosen
19962
20203
  };
19963
20204
  if (entryTotal > 0 && entryKept < entryTotal) {
19964
20205
  warnings.push(
@@ -20267,6 +20508,8 @@ function generateSnapshot(configInput, options) {
20267
20508
  }) : null;
20268
20509
  if (promptText !== null) manifest.artifacts.prompt = artifactRecord(promptText);
20269
20510
  if (projectTree !== null) manifest.artifacts.projectTree = artifactRecord(projectTree);
20511
+ const selectionText = selectionReport === null ? null : generateSelectionReport(manifest, selectionReport);
20512
+ if (selectionText !== null) manifest.artifacts.selection = artifactRecord(selectionText);
20270
20513
  let monolithJson = null;
20271
20514
  let monolithMarkdown = null;
20272
20515
  let monolithXml = null;
@@ -20423,6 +20666,9 @@ function generateSnapshot(configInput, options) {
20423
20666
  if (tokenTree !== null) {
20424
20667
  writeArtifact(reportsDir, "tokens.md", tokenTree.text);
20425
20668
  }
20669
+ if (selectionText !== null) {
20670
+ writeArtifact(reportsDir, "selection.md", selectionText);
20671
+ }
20426
20672
  if (sarifText !== null) {
20427
20673
  writeArtifact(reportsDir, "audit.sarif", sarifText);
20428
20674
  }
@@ -22291,6 +22537,15 @@ ${USAGE}
22291
22537
  info(` - Entry points: ${coverage.entryPoints.kept} of ${coverage.entryPoints.total}`);
22292
22538
  info(` - Symbols: ${coverage.symbols.kept} of ${coverage.symbols.total}`);
22293
22539
  }
22540
+ if (manifest.budget.headroomTokens !== void 0) {
22541
+ info(` - Headroom: ${formatNumber(manifest.budget.headroomTokens)} tokens`);
22542
+ }
22543
+ if (manifest.budget.nextInLine !== void 0 && manifest.budget.nextInLine.length > 0) {
22544
+ const next = manifest.budget.nextInLine.slice(0, 5);
22545
+ info(
22546
+ " - Next in line: " + next.map((item) => item.path + " (" + formatNumber(item.tokens) + ")").join(", ") + (manifest.budget.nextInLine.length > next.length ? ", \u2026" : "")
22547
+ );
22548
+ }
22294
22549
  }
22295
22550
  if (manifest.delta !== void 0) {
22296
22551
  const delta = manifest.delta;