codebase-snapshot 0.16.0 → 0.18.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/index.cjs CHANGED
@@ -911,7 +911,7 @@ function summarizeTypeScriptSource(relativePath, content) {
911
911
  }
912
912
  const callee = node.expression;
913
913
  if (ts__default.default.isPropertyAccessExpression(callee) && ts__default.default.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts__default.default.isStringLiteral(firstArgument)) {
914
- summary.routeHandlers.push(callee.name.text.toUpperCase());
914
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
915
915
  }
916
916
  }
917
917
  if (ts__default.default.isExportDeclaration(node)) {
@@ -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.16.0";
4015
+ var GENERATOR_VERSION = "0.18.0";
4016
4016
  var SCHEMA_VERSION = "3.0.0";
4017
4017
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4018
4018
  function isOurGeneratorName(name) {
@@ -4063,6 +4063,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4063
4063
  let branch = fallbackBranch;
4064
4064
  let commit = "unknown";
4065
4065
  let isDirty = false;
4066
+ let branchFromGit = false;
4066
4067
  const records = output.split("\0").flatMap((record) => record.split("\n"));
4067
4068
  for (const record of records) {
4068
4069
  if (record.length === 0) continue;
@@ -4078,13 +4079,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4078
4079
  const head = record.match(/^# branch\.head (.+)$/);
4079
4080
  if (head) {
4080
4081
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
4082
+ branchFromGit = head[1] !== "(detached)";
4081
4083
  }
4082
4084
  }
4083
- return { branch, commit, isDirty };
4085
+ return { branch, commit, isDirty, branchFromGit };
4084
4086
  } catch (err) {
4085
4087
  const code = err.code;
4086
4088
  const isDirty = code === "ENOBUFS";
4087
- return { branch: fallbackBranch, commit: "unknown", isDirty };
4089
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
4088
4090
  }
4089
4091
  }
4090
4092
  var DEFAULT_IGNORED_DIRS = [
@@ -6070,7 +6072,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
6070
6072
  "# Codebase Health & Security Audit",
6071
6073
  "",
6072
6074
  `**Generated:** ${manifest.generatedAt} `,
6073
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
6075
+ `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})${manifest.git.branchFromGit === false ? " \u2014 fallback; git reported no branch here" : ""} `,
6074
6076
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
6075
6077
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
6076
6078
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -7201,13 +7203,19 @@ function planForQuestion(manifest, question, options = {}) {
7201
7203
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
7202
7204
  }
7203
7205
  const notes = [];
7206
+ if (manifest.files.length === 0) {
7207
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
7208
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
7209
+ }
7204
7210
  if (scored.length === 0) {
7205
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7206
7211
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
7207
7212
  for (const hub of hubs) {
7208
7213
  const file = byPath.get(hub.path);
7209
7214
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
7210
7215
  }
7216
+ if (scored.length > 0) {
7217
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7218
+ }
7211
7219
  }
7212
7220
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7213
7221
  const chosen = /* @__PURE__ */ new Map();
@@ -7271,7 +7279,14 @@ function planForQuestion(manifest, question, options = {}) {
7271
7279
  }
7272
7280
  }
7273
7281
  }
7274
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
7282
+ if (chosen.size === 0) {
7283
+ if (scored.length === 0) {
7284
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
7285
+ } else {
7286
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
7287
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
7288
+ }
7289
+ }
7275
7290
  notes.push(
7276
7291
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
7277
7292
  );
@@ -7886,7 +7901,7 @@ function snapshotSection(manifest, code, partsWritten) {
7886
7901
  const out = ["## This snapshot", ""];
7887
7902
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
7888
7903
  out.push(
7889
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
7904
+ "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + (manifest.git.branchFromGit === false ? " (the branch is a configured fallback; git reported none)." : ".")
7890
7905
  );
7891
7906
  out.push(
7892
7907
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -8059,7 +8074,7 @@ function generateReadme(manifest, artifacts) {
8059
8074
  "",
8060
8075
  `- **Generated At:** \`${manifest.generatedAt}\``,
8061
8076
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
8062
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
8077
+ `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})${manifest.git.branchFromGit === false ? " \u2014 fallback; git reported no branch here" : ""}`,
8063
8078
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
8064
8079
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
8065
8080
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -8619,6 +8634,41 @@ function detectLanguage(filePath) {
8619
8634
  const ext = path25__namespace.posix.extname(base).toLowerCase();
8620
8635
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8621
8636
  }
8637
+ var SIGNATURE_FILE = "signature.json";
8638
+ function verifySnapshotSignature(snapshotDir) {
8639
+ const signaturePath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
8640
+ const manifestPath = path25__namespace.join(snapshotDir, "manifest.json");
8641
+ if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8642
+ let record;
8643
+ try {
8644
+ record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
8645
+ } catch (error) {
8646
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
8647
+ }
8648
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8649
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
8650
+ }
8651
+ let bytes;
8652
+ try {
8653
+ bytes = fs24__namespace.readFileSync(manifestPath);
8654
+ } catch {
8655
+ return { ok: false, reason: "the signed manifest is missing" };
8656
+ }
8657
+ const sha2562 = crypto2__namespace.createHash("sha256").update(bytes).digest("hex");
8658
+ if (sha2562 !== record.manifestSha256) {
8659
+ return { ok: false, reason: "manifest.json changed after it was signed" };
8660
+ }
8661
+ let verified = false;
8662
+ try {
8663
+ const key = crypto2__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8664
+ verified = crypto2__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8665
+ } catch (error) {
8666
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
8667
+ }
8668
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8669
+ }
8670
+
8671
+ // src/validator/validate.ts
8622
8672
  function maskedPath(value, secretRules) {
8623
8673
  return findSecretInPath(value, secretRules)?.masked ?? value;
8624
8674
  }
@@ -9619,6 +9669,11 @@ function validateSnapshot(configInput) {
9619
9669
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9620
9670
  );
9621
9671
  }
9672
+ const signaturePath = path25__namespace.join(path25__namespace.dirname(manifestPath), "signature.json");
9673
+ if (fs24__namespace.existsSync(signaturePath)) {
9674
+ const outcome = verifySnapshotSignature(path25__namespace.dirname(manifestPath));
9675
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9676
+ }
9622
9677
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
9623
9678
  warnings.push(
9624
9679
  "This snapshot is a selection (" + (manifest.slice !== void 0 ? "--slice" : "--budget-tokens") + "); validate checks what is present and does not re-run the planner, so a file the selection left out is not reported as missing."
@@ -10015,39 +10070,6 @@ function negotiateLegacyVersion(requested) {
10015
10070
  }
10016
10071
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
10017
10072
  }
10018
- var SIGNATURE_FILE = "signature.json";
10019
- function verifySnapshotSignature(snapshotDir) {
10020
- const signaturePath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
10021
- const manifestPath = path25__namespace.join(snapshotDir, "manifest.json");
10022
- if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
10023
- let record;
10024
- try {
10025
- record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
10026
- } catch (error) {
10027
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
10028
- }
10029
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
10030
- return { ok: false, reason: "signature.json is not an ed25519 record" };
10031
- }
10032
- let bytes;
10033
- try {
10034
- bytes = fs24__namespace.readFileSync(manifestPath);
10035
- } catch {
10036
- return { ok: false, reason: "the signed manifest is missing" };
10037
- }
10038
- const sha2562 = crypto2__namespace.createHash("sha256").update(bytes).digest("hex");
10039
- if (sha2562 !== record.manifestSha256) {
10040
- return { ok: false, reason: "manifest.json changed after it was signed" };
10041
- }
10042
- let verified = false;
10043
- try {
10044
- const key = crypto2__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
10045
- verified = crypto2__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
10046
- } catch (error) {
10047
- return { ok: false, reason: "the signature could not be checked: " + error.message };
10048
- }
10049
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
10050
- }
10051
10073
 
10052
10074
  // src/partitioner/part-format.ts
10053
10075
  var FILE_HEADING = "### FILE: ";
@@ -10628,8 +10650,9 @@ function auditSnapshot(options) {
10628
10650
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
10629
10651
  disagreements.push("file count");
10630
10652
  }
10653
+ const sourceGone = typeof member.path === "string" && !fs24__namespace.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
10631
10654
  checks.push(
10632
- disagreements.length === 0 ? check(
10655
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
10633
10656
  "workspace.index",
10634
10657
  "The workspace index agrees with this member",
10635
10658
  "warning",
@@ -10651,6 +10674,7 @@ function auditSnapshot(options) {
10651
10674
  let scannedBytes = 0;
10652
10675
  for (const relative13 of walk(snapshotDir)) {
10653
10676
  if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
10677
+ if (relative13 === SIGNATURE_FILE) continue;
10654
10678
  const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
10655
10679
  if (text2 === null) continue;
10656
10680
  scannedBytes += Buffer.byteLength(text2, "utf8");
@@ -10659,6 +10683,28 @@ function auditSnapshot(options) {
10659
10683
  leakHits.push(relative13 + " (" + found.findings.length + " line(s))");
10660
10684
  }
10661
10685
  }
10686
+ const signatureRecordPath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
10687
+ if (fs24__namespace.existsSync(signatureRecordPath)) {
10688
+ const recordText = readText2(signatureRecordPath);
10689
+ if (recordText !== null) {
10690
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
10691
+ let scanText = recordText;
10692
+ try {
10693
+ const record = JSON.parse(recordText);
10694
+ const rest = { ...record };
10695
+ delete rest.publicKey;
10696
+ delete rest.signature;
10697
+ delete rest.manifestSha256;
10698
+ delete rest.fingerprint;
10699
+ scanText = JSON.stringify(rest, null, 2);
10700
+ } catch {
10701
+ }
10702
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
10703
+ if (found.findings.length > 0) {
10704
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
10705
+ }
10706
+ }
10707
+ }
10662
10708
  checks.push(
10663
10709
  leakHits.length === 0 ? check(
10664
10710
  "secrets.artifacts",
@@ -11392,6 +11438,10 @@ var WRITES = {
11392
11438
  openWorldHint: false
11393
11439
  };
11394
11440
  var MAX_RESULT_BYTES = 64 * 1024;
11441
+ function capResultText(text2) {
11442
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
11443
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
11444
+ }
11395
11445
  var ROOT_PROPERTY = {
11396
11446
  type: "string",
11397
11447
  description: "Repository root. Defaults to the directory this server was started in."
@@ -11579,6 +11629,17 @@ var historyTool = {
11579
11629
  isError: true
11580
11630
  };
11581
11631
  }
11632
+ const manifestRead = readManifest3(prepared.workspace);
11633
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
11634
+ if (recordedLog !== void 0 && recordedLog !== null) {
11635
+ const digest = crypto2.createHash("sha256").update(text2, "utf8").digest("hex");
11636
+ if (digest !== recordedLog.sha256) {
11637
+ return {
11638
+ text: "reports/log.md changed after the snapshot was generated (its digest no longer matches the manifest). Regenerate the snapshot rather than trusting this history.",
11639
+ isError: true
11640
+ };
11641
+ }
11642
+ }
11582
11643
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
11583
11644
  const commits = parseHistoryReport(text2).slice(0, limit);
11584
11645
  return {
@@ -11638,9 +11699,12 @@ var budgetTool = {
11638
11699
  });
11639
11700
  }
11640
11701
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
11702
+ if (read.manifest.files.length === 0) {
11703
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
11704
+ }
11641
11705
  for (const row of rows) {
11642
11706
  lines.push(
11643
- 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" : "") + ")")
11707
+ row.budget.toLocaleString("en-US") + " tokens: " + row.files + " file(s), " + row.usedTokens.toLocaleString("en-US") + " used" + (row.files === 0 && read.manifest.files.length > 0 ? " - no file fits this budget" : "") + (row.gained.length === 0 ? "" : ", " + row.gained.length + " gained (" + row.gained.slice(0, 4).join(", ") + (row.gained.length > 4 ? ", \u2026" : "") + ")")
11644
11708
  );
11645
11709
  }
11646
11710
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -11892,7 +11956,7 @@ var routesTool = {
11892
11956
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
11893
11957
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
11894
11958
  routes.length + " route(s):",
11895
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
11959
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
11896
11960
  ].join("\n");
11897
11961
  return { text: text2, structured: { total: routes.length, routes } };
11898
11962
  }
@@ -12061,8 +12125,9 @@ var searchTool = {
12061
12125
  }
12062
12126
  }
12063
12127
  }
12128
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
12064
12129
  const lines = [
12065
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
12130
+ matches.length === 0 ? "No match in " + read.manifest.files.length + " file(s)." : matches.length + " match(es) in " + matchedFiles + " file(s) of " + read.manifest.files.length + " searched." + (truncated ? " Results are capped, so not every file was searched; narrow the query." : ""),
12066
12131
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
12067
12132
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
12068
12133
  ];
@@ -12085,7 +12150,9 @@ var statsTool = {
12085
12150
  parts: { type: "integer" },
12086
12151
  tokens: { type: "integer" },
12087
12152
  layers: { type: "object" },
12088
- kinds: { type: "object" }
12153
+ kinds: { type: "object" },
12154
+ heaviest: { type: "array", items: { type: "object" } },
12155
+ partSizes: { type: "array", items: { type: "object" } }
12089
12156
  }
12090
12157
  },
12091
12158
  annotations: READ_ONLY,
@@ -12096,7 +12163,11 @@ var statsTool = {
12096
12163
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12097
12164
  const manifest = read.manifest;
12098
12165
  const heaviest = [...manifest.files].sort((left, right) => right.includedBytes - left.includedBytes).slice(0, 10).map((file) => ({ path: file.relativePath, tokens: Math.ceil(file.includedBytes / 4), part: file.part }));
12099
- const parts = manifest.parts.map((part) => ({ filename: part.filename, tokens: part.estimatedTokens }));
12166
+ const parts = manifest.parts.map((part) => ({
12167
+ filename: part.filename,
12168
+ bytes: part.byteSize,
12169
+ tokens: part.estimatedTokens
12170
+ }));
12100
12171
  const lines = [
12101
12172
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
12102
12173
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -12152,7 +12223,7 @@ var reviewTool = {
12152
12223
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12153
12224
  let validation;
12154
12225
  try {
12155
- validation = validateSnapshot(workspace.config);
12226
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
12156
12227
  } catch (error) {
12157
12228
  return { text: error.message, isError: true };
12158
12229
  }
@@ -12252,24 +12323,17 @@ var diffContextTool = {
12252
12323
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
12253
12324
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
12254
12325
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
12326
+ const resolver = buildImportResolver(read.manifest.files, {
12327
+ tsconfig: tsconfigPathsFor(workspace.root)
12328
+ });
12255
12329
  const importers = /* @__PURE__ */ new Map();
12256
12330
  for (const entry of read.manifest.indexes.imports.byFile) {
12257
12331
  for (const specifier of entry.imports) {
12258
- if (!specifier.startsWith(".")) continue;
12259
- const base = entry.path.includes("/") ? entry.path.slice(0, entry.path.lastIndexOf("/")) : "";
12260
- const parts = [];
12261
- for (const segment of (base + "/" + specifier).split("/")) {
12262
- if (segment === "" || segment === ".") continue;
12263
- if (segment === "..") parts.pop();
12264
- else parts.push(segment);
12265
- }
12266
- const joined = parts.join("/").toLowerCase();
12267
- const withoutExtension = joined.replace(/\.[cm]?[jt]sx?$/, "");
12268
- const target = byPath.get(joined) ?? byPath.get(withoutExtension + ".ts") ?? byPath.get(withoutExtension + ".tsx") ?? byPath.get(withoutExtension + ".js") ?? byPath.get(withoutExtension + ".py") ?? byPath.get(withoutExtension + "/index.ts") ?? byPath.get(withoutExtension);
12269
- if (target === void 0) continue;
12270
- const list2 = importers.get(target.relativePath) ?? [];
12332
+ const target = resolveSpecifier(entry.path, specifier, resolver);
12333
+ if (target === null) continue;
12334
+ const list2 = importers.get(target) ?? [];
12271
12335
  list2.push(entry.path);
12272
- importers.set(target.relativePath, list2);
12336
+ importers.set(target, list2);
12273
12337
  }
12274
12338
  }
12275
12339
  const missing = [];
@@ -12304,9 +12368,12 @@ var diffContextTool = {
12304
12368
  continue;
12305
12369
  }
12306
12370
  used += tokens;
12371
+ const capped2 = capResultText(window.text);
12307
12372
  changed.push({ path: file.relativePath, part: file.part, tokens });
12308
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12309
- text2.push(window.text);
12373
+ text2.push(
12374
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12375
+ );
12376
+ text2.push(capped2.text);
12310
12377
  }
12311
12378
  const dependents = [];
12312
12379
  for (const entry of changed) {
@@ -12388,11 +12455,13 @@ var symbolTool = {
12388
12455
  if (index === -1) continue;
12389
12456
  const from = Math.max(0, index - 3);
12390
12457
  const to = Math.min(lines.length, index + windowSize);
12458
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
12391
12459
  matches.push({
12392
12460
  path: file.relativePath,
12393
12461
  part: file.part,
12394
12462
  line: index + 1,
12395
- text: lines.slice(from, to).join("\n")
12463
+ text: capped2.text,
12464
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12396
12465
  });
12397
12466
  }
12398
12467
  if (matches.length === 0) {
@@ -12523,7 +12592,8 @@ var contextTool = {
12523
12592
  continue;
12524
12593
  }
12525
12594
  const window = windowText(section.body, 1, linesPerFile);
12526
- const body = window.text;
12595
+ const capped2 = capResultText(window.text);
12596
+ const body = capped2.text;
12527
12597
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
12528
12598
  if (used + tokens > budget) {
12529
12599
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -12532,14 +12602,19 @@ var contextTool = {
12532
12602
  missing.push(file.relativePath + " (budget)");
12533
12603
  continue;
12534
12604
  }
12535
- const partial = Math.max(1, Math.ceil(Buffer.byteLength(smaller.text, "utf8") / 4));
12536
- text2.push("### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines)");
12537
- text2.push(smaller.text);
12605
+ const smallerCapped = capResultText(smaller.text);
12606
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
12607
+ text2.push(
12608
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
12609
+ );
12610
+ text2.push(smallerCapped.text);
12538
12611
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
12539
12612
  used += partial;
12540
12613
  continue;
12541
12614
  }
12542
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12615
+ text2.push(
12616
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12617
+ );
12543
12618
  text2.push(body);
12544
12619
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
12545
12620
  used += tokens;
@@ -12713,8 +12788,17 @@ var answerTool = {
12713
12788
  maxTokens,
12714
12789
  ...args.includeTests === true ? { includeTests: true } : {}
12715
12790
  });
12791
+ if (read.manifest.files.length === 0) {
12792
+ return {
12793
+ text: "The snapshot holds no files, so nothing can be assembled for this question. manifest.skipped records why paths were not emitted (excluded, binary, unchanged).",
12794
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
12795
+ };
12796
+ }
12716
12797
  const blocks = [];
12717
- const omitted = [];
12798
+ const omitted = plan.skipped.map((entry) => ({
12799
+ path: entry.path,
12800
+ reason: entry.reason
12801
+ }));
12718
12802
  let used = 0;
12719
12803
  const parts = /* @__PURE__ */ new Map();
12720
12804
  for (const planned of plan.files) {
@@ -12743,14 +12827,23 @@ var answerTool = {
12743
12827
  continue;
12744
12828
  }
12745
12829
  const window = windowText(section.body, 1, linesPerFile);
12746
- const text2 = window.text;
12747
- const tokens = estimateTokens(text2);
12830
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
12831
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
12832
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
12833
+ const tokens = estimateTokens(bodyText);
12748
12834
  if (used + tokens > maxTokens && blocks.length > 0) {
12749
12835
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
12750
12836
  continue;
12751
12837
  }
12752
- const numbered = text2.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
12753
- blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
12838
+ blocks.push({
12839
+ path: planned.path,
12840
+ why: planned.why,
12841
+ tokens,
12842
+ text: bodyText,
12843
+ truncated: window.truncated || clipped.isTruncated,
12844
+ totalLines: window.totalLines,
12845
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12846
+ });
12754
12847
  used += tokens;
12755
12848
  }
12756
12849
  const lines = [
@@ -12759,7 +12852,9 @@ var answerTool = {
12759
12852
  ];
12760
12853
  for (const block of blocks) {
12761
12854
  lines.push("");
12762
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
12855
+ lines.push(
12856
+ "## " + block.path + " (" + block.tokens + " tokens, " + (block.clippedAtBytes !== void 0 ? "first " + Math.round(block.clippedAtBytes / 1024) + " KiB of the window" : block.truncated ? "first lines of " + block.totalLines : "whole file") + ")"
12857
+ );
12763
12858
  lines.push("Why: " + block.why);
12764
12859
  lines.push("```");
12765
12860
  lines.push(block.text);
@@ -12770,6 +12865,11 @@ var answerTool = {
12770
12865
  lines.push("Not included:");
12771
12866
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
12772
12867
  }
12868
+ if (plan.notes.length > 0) {
12869
+ lines.push("");
12870
+ lines.push("Notes:");
12871
+ for (const note of plan.notes) lines.push("- " + note);
12872
+ }
12773
12873
  return {
12774
12874
  text: lines.join("\n"),
12775
12875
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -12884,7 +12984,7 @@ var statusTool = {
12884
12984
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
12885
12985
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
12886
12986
  `Fingerprint: ${manifest.fingerprint}`,
12887
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
12987
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
12888
12988
  ];
12889
12989
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
12890
12990
  if (!versionMatches) {
@@ -13035,6 +13135,16 @@ var generateTool = {
13035
13135
  minimum: 500,
13036
13136
  description: "Fit the snapshot into this token budget, highest value first."
13037
13137
  },
13138
+ only: {
13139
+ type: "array",
13140
+ items: { type: "string" },
13141
+ description: "Globs to include: replaces the config allow-list for this run."
13142
+ },
13143
+ ignore: {
13144
+ type: "array",
13145
+ items: { type: "string" },
13146
+ description: "Globs to exclude, added to the config deny-list for this run."
13147
+ },
13038
13148
  ...SCOPE_PROPERTIES
13039
13149
  },
13040
13150
  additionalProperties: false
@@ -13063,7 +13173,9 @@ var generateTool = {
13063
13173
  ...args.tokenTree === true ? { tokenTree: true } : {},
13064
13174
  ...args.stripComments === true ? { stripComments: true } : {},
13065
13175
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
13066
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
13176
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
13177
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
13178
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
13067
13179
  };
13068
13180
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
13069
13181
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -13107,6 +13219,20 @@ var generateTool = {
13107
13219
  };
13108
13220
  }
13109
13221
  };
13222
+ function configAsGenerated(workspace, manifest) {
13223
+ const recorded = manifest.config;
13224
+ return {
13225
+ ...workspace.config,
13226
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13227
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13228
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13229
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13230
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13231
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13232
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13233
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
13234
+ };
13235
+ }
13110
13236
  var validateTool = {
13111
13237
  name: "snapshot_validate",
13112
13238
  title: "Validate the snapshot",
@@ -13128,9 +13254,11 @@ var validateTool = {
13128
13254
  const prepared = await prepare(args, context, workspaceOverrides(args));
13129
13255
  if (!prepared.ok) return prepared.outcome;
13130
13256
  const workspace = prepared.workspace;
13257
+ const read = readManifest3(workspace);
13258
+ if (!read.ok) return failure(read.message);
13131
13259
  let result;
13132
13260
  try {
13133
- result = validateSnapshot(workspace.config);
13261
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
13134
13262
  } catch (error) {
13135
13263
  return failure(error instanceof Error ? error.message : String(error));
13136
13264
  }
@@ -13494,6 +13622,12 @@ var readTool = {
13494
13622
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
13495
13623
  );
13496
13624
  }
13625
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
13626
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
13627
+ }
13628
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
13629
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
13630
+ }
13497
13631
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
13498
13632
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
13499
13633
  const window = windowText(section.body, fromLine, lineCount);
@@ -13943,6 +14077,8 @@ var COMMAND_OPTION_SCOPE = {
13943
14077
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
13944
14078
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
13945
14079
  // list, so removing them narrows the two together.
14080
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
14081
+ update: ["format", "help"],
13946
14082
  report: [
13947
14083
  "cwd",
13948
14084
  "out-dir",
@@ -14235,6 +14371,13 @@ function buildAgentContract() {
14235
14371
  positionals: [],
14236
14372
  exits: [0]
14237
14373
  },
14374
+ {
14375
+ name: "update",
14376
+ aliases: [],
14377
+ summary: "Ask the npm registry whether a newer release exists and print the version it compared against. Exit 0 when current, 1 when an update is available, 2 when the registry could not be reached. The passive notice is suppressed in CI and JSON output; this command always asks and bypasses the cache.",
14378
+ positionals: [],
14379
+ exits: [0, 1, 2]
14380
+ },
14238
14381
  {
14239
14382
  name: "skill",
14240
14383
  aliases: [],
@@ -14530,14 +14673,14 @@ function buildAgentContract() {
14530
14673
  type: "boolean",
14531
14674
  default: false,
14532
14675
  appliesTo: optionAppliesTo("include-diffs"),
14533
- summary: "Also write reports/diff.md: the unstaged and staged diff, with the command that produced each, bounded to 200 KiB and truncated with a note. Absent when there is no change."
14676
+ summary: "Also write reports/diff.md: the unstaged and staged diff, with the command that produced each, bounded to 200 KiB and truncated with a note. Absent when there is no change; outside a git repository the run warns and writes nothing."
14534
14677
  },
14535
14678
  {
14536
14679
  flag: "--include-logs",
14537
14680
  type: "string",
14538
14681
  default: "unset",
14539
14682
  appliesTo: optionAppliesTo("include-logs"),
14540
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
14683
+ summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first. Outside a git repository the run warns and writes nothing."
14541
14684
  },
14542
14685
  {
14543
14686
  flag: "--token-tree",
@@ -15531,6 +15674,18 @@ function createMcpServer(options) {
15531
15674
  if (!isJsonObject(rawArguments)) {
15532
15675
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
15533
15676
  }
15677
+ const missing = (prompt.arguments ?? []).filter((argument) => {
15678
+ if (argument.required !== true) return false;
15679
+ const value = rawArguments[argument.name];
15680
+ return typeof value !== "string" || value.trim() === "";
15681
+ });
15682
+ if (missing.length > 0) {
15683
+ return errorResponse(
15684
+ id,
15685
+ ERROR_CODES.invalidParams,
15686
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
15687
+ );
15688
+ }
15534
15689
  const built = prompt.build(rawArguments);
15535
15690
  const messages = built.messages.map((message) => ({
15536
15691
  role: message.role,
@@ -15809,20 +15964,20 @@ var SERVE_PAGE = `<!doctype html>
15809
15964
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
15810
15965
  <main>
15811
15966
  <form id="gen">
15812
- <input id="source" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
15813
- <select id="mode" title="What to generate">
15967
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
15968
+ <select id="mode" aria-label="What to generate" title="What to generate">
15814
15969
  <option value="full">whole repository</option>
15815
15970
  <option value="slice">a slice for a question</option>
15816
15971
  <option value="budget">fit a token budget</option>
15817
15972
  </select>
15818
- <input id="question" placeholder="the question (slice mode)" spellcheck="false" hidden>
15819
- <input id="budget" type="number" min="500" step="500" value="30000" title="token budget" hidden>
15973
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
15974
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
15820
15975
  <button id="run" type="submit">Generate</button>
15821
15976
  <button id="download" type="button" disabled>Download .zip</button>
15822
15977
  </form>
15823
- <div id="status">Paste an absolute path, or a repository URL (https://github.com/owner/repo). Remote fetches are shallow and public-only.</div>
15978
+ <div id="status" role="status" aria-live="polite">Paste an absolute path, or a repository URL (https://github.com/owner/repo). Remote fetches are shallow and public-only.</div>
15824
15979
  <div id="auth" hidden>
15825
- <form id="token-form"><input id="token" type="password" placeholder="paste the token printed by snapshot serve" style="flex:1"><button type="submit">Use token</button></form>
15980
+ <form id="token-form"><input id="token" type="password" aria-label="Server token" placeholder="paste the token printed by snapshot serve" style="flex:1"><button type="submit">Use token</button></form>
15826
15981
  </div>
15827
15982
  <div class="row">
15828
15983
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -16117,9 +16272,14 @@ async function startWebServer(options) {
16117
16272
  send(400, { error: "not a directory: " + target });
16118
16273
  return;
16119
16274
  }
16275
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
16276
+ if (loaded.errors.length > 0) {
16277
+ send(400, { error: loaded.errors.join("; ") });
16278
+ return;
16279
+ }
16120
16280
  const started = Date.now();
16121
16281
  try {
16122
- const manifest = generateSnapshot({ cwd: target }, {
16282
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
16123
16283
  ...provenance === void 0 ? {} : { source: provenance },
16124
16284
  ...mode === "slice" ? { slice: { question } } : {},
16125
16285
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -16252,8 +16412,8 @@ async function startWebServer(options) {
16252
16412
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
16253
16413
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
16254
16414
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
16255
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
16256
- var REQUEST_TIMEOUT_MS = 1200;
16415
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
16416
+ var REQUEST_TIMEOUT_MS = 2500;
16257
16417
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
16258
16418
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
16259
16419
  const script = normalise(scriptPath);
@@ -16317,7 +16477,7 @@ function shouldCheck(argv, env) {
16317
16477
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
16318
16478
  const args = argv.map((argument) => argument.toLowerCase());
16319
16479
  if (args.includes("--no-update-check")) return false;
16320
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
16480
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
16321
16481
  if (args.includes(skip)) return false;
16322
16482
  }
16323
16483
  let format = null;
@@ -16413,13 +16573,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
16413
16573
  });
16414
16574
  }
16415
16575
  async function checkForUpdate(options) {
16576
+ const latest = await resolveLatest(options);
16577
+ if (!latest) return null;
16578
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16579
+ }
16580
+ async function resolveLatest(options) {
16416
16581
  if (options.enabled === false) return null;
16417
16582
  const now = options.now ?? (() => Date.now());
16418
16583
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
16584
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
16419
16585
  let latest = null;
16420
16586
  try {
16421
16587
  const cached = readCache(options.cacheFile);
16422
- let needsFetch = cached === null;
16588
+ let needsFetch = cached === null || options.force === true;
16423
16589
  if (cached) {
16424
16590
  const age = now() - cached.checkedAt;
16425
16591
  if (cached.latest === null) {
@@ -16431,15 +16597,14 @@ async function checkForUpdate(options) {
16431
16597
  }
16432
16598
  }
16433
16599
  if (needsFetch) {
16434
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
16600
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
16435
16601
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
16436
- latest = fetched;
16602
+ latest = fetched ?? latest;
16437
16603
  }
16438
16604
  } catch {
16439
16605
  return null;
16440
16606
  }
16441
- if (!latest) return null;
16442
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16607
+ return latest;
16443
16608
  }
16444
16609
  function formatUpdateNotice(notice, kind) {
16445
16610
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -19740,6 +19905,11 @@ function generateSnapshot(configInput, options) {
19740
19905
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
19741
19906
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
19742
19907
  };
19908
+ if (plan.files.length === 0) {
19909
+ warnings.push(
19910
+ "The slice selected no files for this question, so the snapshot is empty. " + (plan.notes.length > 0 ? plan.notes[0] : "See the plan notes in the manifest.")
19911
+ );
19912
+ }
19743
19913
  }
19744
19914
  let budgetBlock;
19745
19915
  if (options?.budgetTokens !== void 0) {
@@ -19831,6 +20001,11 @@ function generateSnapshot(configInput, options) {
19831
20001
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
19832
20002
  }
19833
20003
  }
20004
+ if (config.include.length > 0 && files.length === 0) {
20005
+ warnings.push(
20006
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20007
+ );
20008
+ }
19834
20009
  if (changedScope !== null || options?.deltaBase !== void 0) {
19835
20010
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
19836
20011
  for (const relativePath of unchangedPaths) {
@@ -19969,6 +20144,12 @@ function generateSnapshot(configInput, options) {
19969
20144
  maxMonolithBytes: config.maxMonolithBytes ?? null,
19970
20145
  includeSensitiveFiles: config.includeSensitiveFiles,
19971
20146
  ...config.stripComments === true ? { stripComments: true } : {},
20147
+ // The other three settings the digest covers and the manifest did not record: without them a
20148
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20149
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20150
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20151
+ ...config.pack === null ? {} : { pack: config.pack },
20152
+ logCount: config.logCount,
19972
20153
  // The destination the instructions were written for. Not part of `digest`: the payload is
19973
20154
  // identical whatever this says, and a new delivery preference must not make an existing
19974
20155
  // snapshot fail `validate` as configuration drift.
@@ -20112,6 +20293,18 @@ function generateSnapshot(configInput, options) {
20112
20293
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20113
20294
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20114
20295
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20296
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20297
+ manifest.warnings.push(
20298
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20299
+ );
20300
+ manifest.totals.warningCount = manifest.warnings.length;
20301
+ }
20302
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20303
+ manifest.warnings.push(
20304
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20305
+ );
20306
+ manifest.totals.warningCount = manifest.warnings.length;
20307
+ }
20115
20308
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20116
20309
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20117
20310
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20161,17 +20354,19 @@ function generateSnapshot(configInput, options) {
20161
20354
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20162
20355
  }
20163
20356
  const markdown = definitelyTooLarge || !wantsMarkdown ? null : generateMonolithMarkdown(manifest, fullFiles);
20164
- const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
20165
- if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
20166
- monolithMarkdown = markdown;
20167
- manifest.artifacts.fullMarkdown = {
20168
- byteSize: markdownBytes,
20169
- sha256: sha256Hex2(markdown)
20170
- };
20171
- } else if (!definitelyTooLarge) {
20172
- manifest.warnings.push(
20173
- `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20174
- );
20357
+ if (markdown !== null) {
20358
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20359
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20360
+ monolithMarkdown = markdown;
20361
+ manifest.artifacts.fullMarkdown = {
20362
+ byteSize: markdownBytes,
20363
+ sha256: sha256Hex2(markdown)
20364
+ };
20365
+ } else {
20366
+ manifest.warnings.push(
20367
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20368
+ );
20369
+ }
20175
20370
  }
20176
20371
  if (wantsXml && !definitelyTooLarge) {
20177
20372
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20187,14 +20382,16 @@ function generateSnapshot(configInput, options) {
20187
20382
  }
20188
20383
  manifest.totals.warningCount = manifest.warnings.length;
20189
20384
  const json = definitelyTooLarge || !wantsJson ? null : generateMonolithJson(manifest, fullFiles);
20190
- const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
20191
- if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
20192
- monolithJson = json;
20193
- manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20194
- } else if (!definitelyTooLarge) {
20195
- manifest.warnings.push(
20196
- `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20197
- );
20385
+ if (json !== null) {
20386
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20387
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20388
+ monolithJson = json;
20389
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20390
+ } else {
20391
+ manifest.warnings.push(
20392
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20393
+ );
20394
+ }
20198
20395
  }
20199
20396
  manifest.totals.warningCount = manifest.warnings.length;
20200
20397
  }