codebase-snapshot 0.17.0 → 0.19.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)) {
@@ -3694,7 +3694,11 @@ function scanAndRedactSecrets(content, rules, filePath) {
3694
3694
  let finalText = segments.join("");
3695
3695
  finalText = redactStructuredValues(finalText, filePath, recordFinding);
3696
3696
  finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
3697
- const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
3697
+ const originalLines = content.split(/\r\n|\r|\n/);
3698
+ const findings = [...findingsByLine.entries()].filter(([line]) => {
3699
+ const original = originalLines[line - 1] ?? "";
3700
+ return !original.includes(REDACTION_MARKER) && !original.includes(PEM_REDACTION_MARKER);
3701
+ }).sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
3698
3702
  rules: [...rulesForLine],
3699
3703
  line,
3700
3704
  path: filePath
@@ -3762,8 +3766,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3762
3766
  if (body.trim() !== "") {
3763
3767
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
3764
3768
  if (indent <= baseIndent) break;
3769
+ if (!isMarkerLine(body)) masked2 = true;
3765
3770
  segments[cursor2] = maskLineContent(body);
3766
- masked2 = true;
3767
3771
  }
3768
3772
  cursor2 += 2;
3769
3773
  }
@@ -3783,8 +3787,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3783
3787
  if (body.trim() !== "") {
3784
3788
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
3785
3789
  if (indent < valueIndent) break;
3790
+ if (!isMarkerLine(body)) masked = true;
3786
3791
  segments[cursor] = maskValueLine(body);
3787
- masked = true;
3788
3792
  }
3789
3793
  cursor += 2;
3790
3794
  }
@@ -3894,10 +3898,14 @@ var PLACEHOLDER_PATTERNS = [
3894
3898
  /^your[-_ ].*$/i,
3895
3899
  /^(?:example|sample)(?:[-_ ].*)?$/i
3896
3900
  ];
3901
+ function isMarkerLine(value) {
3902
+ return value.includes(REDACTION_MARKER) || value.includes(PEM_REDACTION_MARKER);
3903
+ }
3897
3904
  function isPlaceholderValue(value) {
3898
3905
  const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
3899
3906
  if (trimmed.length === 0) return false;
3900
3907
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
3908
+ if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
3901
3909
  return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
3902
3910
  }
3903
3911
  function quotesAreBalanced(text2) {
@@ -4012,7 +4020,7 @@ function applySpansKeepingQuotes(line, spans) {
4012
4020
 
4013
4021
  // src/version.ts
4014
4022
  var GENERATOR_NAME = "codebase-snapshot";
4015
- var GENERATOR_VERSION = "0.17.0";
4023
+ var GENERATOR_VERSION = "0.19.0";
4016
4024
  var SCHEMA_VERSION = "3.0.0";
4017
4025
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4018
4026
  function isOurGeneratorName(name) {
@@ -4063,6 +4071,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4063
4071
  let branch = fallbackBranch;
4064
4072
  let commit = "unknown";
4065
4073
  let isDirty = false;
4074
+ let branchFromGit = false;
4066
4075
  const records = output.split("\0").flatMap((record) => record.split("\n"));
4067
4076
  for (const record of records) {
4068
4077
  if (record.length === 0) continue;
@@ -4078,13 +4087,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4078
4087
  const head = record.match(/^# branch\.head (.+)$/);
4079
4088
  if (head) {
4080
4089
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
4090
+ branchFromGit = head[1] !== "(detached)";
4081
4091
  }
4082
4092
  }
4083
- return { branch, commit, isDirty };
4093
+ return { branch, commit, isDirty, branchFromGit };
4084
4094
  } catch (err) {
4085
4095
  const code = err.code;
4086
4096
  const isDirty = code === "ENOBUFS";
4087
- return { branch: fallbackBranch, commit: "unknown", isDirty };
4097
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
4088
4098
  }
4089
4099
  }
4090
4100
  var DEFAULT_IGNORED_DIRS = [
@@ -6070,7 +6080,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
6070
6080
  "# Codebase Health & Security Audit",
6071
6081
  "",
6072
6082
  `**Generated:** ${manifest.generatedAt} `,
6073
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
6083
+ `**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
6084
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
6075
6085
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
6076
6086
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -7201,13 +7211,19 @@ function planForQuestion(manifest, question, options = {}) {
7201
7211
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
7202
7212
  }
7203
7213
  const notes = [];
7214
+ if (manifest.files.length === 0) {
7215
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
7216
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
7217
+ }
7204
7218
  if (scored.length === 0) {
7205
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7206
7219
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
7207
7220
  for (const hub of hubs) {
7208
7221
  const file = byPath.get(hub.path);
7209
7222
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
7210
7223
  }
7224
+ if (scored.length > 0) {
7225
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7226
+ }
7211
7227
  }
7212
7228
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7213
7229
  const chosen = /* @__PURE__ */ new Map();
@@ -7271,7 +7287,14 @@ function planForQuestion(manifest, question, options = {}) {
7271
7287
  }
7272
7288
  }
7273
7289
  }
7274
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
7290
+ if (chosen.size === 0) {
7291
+ if (scored.length === 0) {
7292
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
7293
+ } else {
7294
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
7295
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
7296
+ }
7297
+ }
7275
7298
  notes.push(
7276
7299
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
7277
7300
  );
@@ -7886,7 +7909,7 @@ function snapshotSection(manifest, code, partsWritten) {
7886
7909
  const out = ["## This snapshot", ""];
7887
7910
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
7888
7911
  out.push(
7889
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
7912
+ "- 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
7913
  );
7891
7914
  out.push(
7892
7915
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -8059,7 +8082,7 @@ function generateReadme(manifest, artifacts) {
8059
8082
  "",
8060
8083
  `- **Generated At:** \`${manifest.generatedAt}\``,
8061
8084
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
8062
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
8085
+ `- **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
8086
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
8064
8087
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
8065
8088
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -8619,6 +8642,41 @@ function detectLanguage(filePath) {
8619
8642
  const ext = path25__namespace.posix.extname(base).toLowerCase();
8620
8643
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8621
8644
  }
8645
+ var SIGNATURE_FILE = "signature.json";
8646
+ function verifySnapshotSignature(snapshotDir) {
8647
+ const signaturePath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
8648
+ const manifestPath = path25__namespace.join(snapshotDir, "manifest.json");
8649
+ if (!fs24__namespace.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8650
+ let record;
8651
+ try {
8652
+ record = JSON.parse(fs24__namespace.readFileSync(signaturePath, "utf8"));
8653
+ } catch (error) {
8654
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
8655
+ }
8656
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8657
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
8658
+ }
8659
+ let bytes;
8660
+ try {
8661
+ bytes = fs24__namespace.readFileSync(manifestPath);
8662
+ } catch {
8663
+ return { ok: false, reason: "the signed manifest is missing" };
8664
+ }
8665
+ const sha2562 = crypto2__namespace.createHash("sha256").update(bytes).digest("hex");
8666
+ if (sha2562 !== record.manifestSha256) {
8667
+ return { ok: false, reason: "manifest.json changed after it was signed" };
8668
+ }
8669
+ let verified = false;
8670
+ try {
8671
+ const key = crypto2__namespace.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8672
+ verified = crypto2__namespace.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8673
+ } catch (error) {
8674
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
8675
+ }
8676
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8677
+ }
8678
+
8679
+ // src/validator/validate.ts
8622
8680
  function maskedPath(value, secretRules) {
8623
8681
  return findSecretInPath(value, secretRules)?.masked ?? value;
8624
8682
  }
@@ -9619,6 +9677,11 @@ function validateSnapshot(configInput) {
9619
9677
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9620
9678
  );
9621
9679
  }
9680
+ const signaturePath = path25__namespace.join(path25__namespace.dirname(manifestPath), "signature.json");
9681
+ if (fs24__namespace.existsSync(signaturePath)) {
9682
+ const outcome = verifySnapshotSignature(path25__namespace.dirname(manifestPath));
9683
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9684
+ }
9622
9685
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
9623
9686
  warnings.push(
9624
9687
  "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 +10078,6 @@ function negotiateLegacyVersion(requested) {
10015
10078
  }
10016
10079
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
10017
10080
  }
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
10081
 
10052
10082
  // src/partitioner/part-format.ts
10053
10083
  var FILE_HEADING = "### FILE: ";
@@ -10628,8 +10658,9 @@ function auditSnapshot(options) {
10628
10658
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
10629
10659
  disagreements.push("file count");
10630
10660
  }
10661
+ 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
10662
  checks.push(
10632
- disagreements.length === 0 ? check(
10663
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
10633
10664
  "workspace.index",
10634
10665
  "The workspace index agrees with this member",
10635
10666
  "warning",
@@ -10651,12 +10682,45 @@ function auditSnapshot(options) {
10651
10682
  let scannedBytes = 0;
10652
10683
  for (const relative13 of walk(snapshotDir)) {
10653
10684
  if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
10685
+ if (relative13 === SIGNATURE_FILE) continue;
10654
10686
  const text2 = readText2(path25__namespace.join(snapshotDir, relative13));
10655
10687
  if (text2 === null) continue;
10656
10688
  scannedBytes += Buffer.byteLength(text2, "utf8");
10657
- const found = scanAndRedactSecrets(text2, rules, relative13);
10658
- if (found.findings.length > 0) {
10659
- leakHits.push(relative13 + " (" + found.findings.length + " line(s))");
10689
+ let findingCount = 0;
10690
+ if (/^parts[\\/].*\.md$/i.test(relative13)) {
10691
+ let headerText = text2;
10692
+ for (const section of parsePartSections(text2)) {
10693
+ findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
10694
+ headerText = headerText.replace(section.body, "");
10695
+ }
10696
+ findingCount += scanAndRedactSecrets(headerText, rules, relative13).findings.length;
10697
+ } else {
10698
+ findingCount = scanAndRedactSecrets(text2, rules, relative13).findings.length;
10699
+ }
10700
+ if (findingCount > 0) {
10701
+ leakHits.push(relative13 + " (" + findingCount + " line(s))");
10702
+ }
10703
+ }
10704
+ const signatureRecordPath = path25__namespace.join(snapshotDir, SIGNATURE_FILE);
10705
+ if (fs24__namespace.existsSync(signatureRecordPath)) {
10706
+ const recordText = readText2(signatureRecordPath);
10707
+ if (recordText !== null) {
10708
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
10709
+ let scanText = recordText;
10710
+ try {
10711
+ const record = JSON.parse(recordText);
10712
+ const rest = { ...record };
10713
+ delete rest.publicKey;
10714
+ delete rest.signature;
10715
+ delete rest.manifestSha256;
10716
+ delete rest.fingerprint;
10717
+ scanText = JSON.stringify(rest, null, 2);
10718
+ } catch {
10719
+ }
10720
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
10721
+ if (found.findings.length > 0) {
10722
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
10723
+ }
10660
10724
  }
10661
10725
  }
10662
10726
  checks.push(
@@ -11392,6 +11456,10 @@ var WRITES = {
11392
11456
  openWorldHint: false
11393
11457
  };
11394
11458
  var MAX_RESULT_BYTES = 64 * 1024;
11459
+ function capResultText(text2) {
11460
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
11461
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
11462
+ }
11395
11463
  var ROOT_PROPERTY = {
11396
11464
  type: "string",
11397
11465
  description: "Repository root. Defaults to the directory this server was started in."
@@ -11579,6 +11647,17 @@ var historyTool = {
11579
11647
  isError: true
11580
11648
  };
11581
11649
  }
11650
+ const manifestRead = readManifest3(prepared.workspace);
11651
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
11652
+ if (recordedLog !== void 0 && recordedLog !== null) {
11653
+ const digest = crypto2.createHash("sha256").update(text2, "utf8").digest("hex");
11654
+ if (digest !== recordedLog.sha256) {
11655
+ return {
11656
+ 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.",
11657
+ isError: true
11658
+ };
11659
+ }
11660
+ }
11582
11661
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
11583
11662
  const commits = parseHistoryReport(text2).slice(0, limit);
11584
11663
  return {
@@ -11638,9 +11717,12 @@ var budgetTool = {
11638
11717
  });
11639
11718
  }
11640
11719
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
11720
+ if (read.manifest.files.length === 0) {
11721
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
11722
+ }
11641
11723
  for (const row of rows) {
11642
11724
  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" : "") + ")")
11725
+ 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
11726
  );
11645
11727
  }
11646
11728
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -11892,7 +11974,7 @@ var routesTool = {
11892
11974
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
11893
11975
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
11894
11976
  routes.length + " route(s):",
11895
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
11977
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
11896
11978
  ].join("\n");
11897
11979
  return { text: text2, structured: { total: routes.length, routes } };
11898
11980
  }
@@ -12061,8 +12143,9 @@ var searchTool = {
12061
12143
  }
12062
12144
  }
12063
12145
  }
12146
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
12064
12147
  const lines = [
12065
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
12148
+ 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
12149
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
12067
12150
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
12068
12151
  ];
@@ -12085,7 +12168,9 @@ var statsTool = {
12085
12168
  parts: { type: "integer" },
12086
12169
  tokens: { type: "integer" },
12087
12170
  layers: { type: "object" },
12088
- kinds: { type: "object" }
12171
+ kinds: { type: "object" },
12172
+ heaviest: { type: "array", items: { type: "object" } },
12173
+ partSizes: { type: "array", items: { type: "object" } }
12089
12174
  }
12090
12175
  },
12091
12176
  annotations: READ_ONLY,
@@ -12096,7 +12181,11 @@ var statsTool = {
12096
12181
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12097
12182
  const manifest = read.manifest;
12098
12183
  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 }));
12184
+ const parts = manifest.parts.map((part) => ({
12185
+ filename: part.filename,
12186
+ bytes: part.byteSize,
12187
+ tokens: part.estimatedTokens
12188
+ }));
12100
12189
  const lines = [
12101
12190
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
12102
12191
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -12152,7 +12241,7 @@ var reviewTool = {
12152
12241
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12153
12242
  let validation;
12154
12243
  try {
12155
- validation = validateSnapshot(workspace.config);
12244
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
12156
12245
  } catch (error) {
12157
12246
  return { text: error.message, isError: true };
12158
12247
  }
@@ -12252,24 +12341,17 @@ var diffContextTool = {
12252
12341
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
12253
12342
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
12254
12343
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
12344
+ const resolver = buildImportResolver(read.manifest.files, {
12345
+ tsconfig: tsconfigPathsFor(workspace.root)
12346
+ });
12255
12347
  const importers = /* @__PURE__ */ new Map();
12256
12348
  for (const entry of read.manifest.indexes.imports.byFile) {
12257
12349
  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) ?? [];
12350
+ const target = resolveSpecifier(entry.path, specifier, resolver);
12351
+ if (target === null) continue;
12352
+ const list2 = importers.get(target) ?? [];
12271
12353
  list2.push(entry.path);
12272
- importers.set(target.relativePath, list2);
12354
+ importers.set(target, list2);
12273
12355
  }
12274
12356
  }
12275
12357
  const missing = [];
@@ -12304,9 +12386,12 @@ var diffContextTool = {
12304
12386
  continue;
12305
12387
  }
12306
12388
  used += tokens;
12389
+ const capped2 = capResultText(window.text);
12307
12390
  changed.push({ path: file.relativePath, part: file.part, tokens });
12308
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12309
- text2.push(window.text);
12391
+ text2.push(
12392
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12393
+ );
12394
+ text2.push(capped2.text);
12310
12395
  }
12311
12396
  const dependents = [];
12312
12397
  for (const entry of changed) {
@@ -12388,11 +12473,13 @@ var symbolTool = {
12388
12473
  if (index === -1) continue;
12389
12474
  const from = Math.max(0, index - 3);
12390
12475
  const to = Math.min(lines.length, index + windowSize);
12476
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
12391
12477
  matches.push({
12392
12478
  path: file.relativePath,
12393
12479
  part: file.part,
12394
12480
  line: index + 1,
12395
- text: lines.slice(from, to).join("\n")
12481
+ text: capped2.text,
12482
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12396
12483
  });
12397
12484
  }
12398
12485
  if (matches.length === 0) {
@@ -12523,7 +12610,8 @@ var contextTool = {
12523
12610
  continue;
12524
12611
  }
12525
12612
  const window = windowText(section.body, 1, linesPerFile);
12526
- const body = window.text;
12613
+ const capped2 = capResultText(window.text);
12614
+ const body = capped2.text;
12527
12615
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
12528
12616
  if (used + tokens > budget) {
12529
12617
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -12532,14 +12620,19 @@ var contextTool = {
12532
12620
  missing.push(file.relativePath + " (budget)");
12533
12621
  continue;
12534
12622
  }
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);
12623
+ const smallerCapped = capResultText(smaller.text);
12624
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
12625
+ text2.push(
12626
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
12627
+ );
12628
+ text2.push(smallerCapped.text);
12538
12629
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
12539
12630
  used += partial;
12540
12631
  continue;
12541
12632
  }
12542
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12633
+ text2.push(
12634
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12635
+ );
12543
12636
  text2.push(body);
12544
12637
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
12545
12638
  used += tokens;
@@ -12713,8 +12806,17 @@ var answerTool = {
12713
12806
  maxTokens,
12714
12807
  ...args.includeTests === true ? { includeTests: true } : {}
12715
12808
  });
12809
+ if (read.manifest.files.length === 0) {
12810
+ return {
12811
+ 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).",
12812
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
12813
+ };
12814
+ }
12716
12815
  const blocks = [];
12717
- const omitted = [];
12816
+ const omitted = plan.skipped.map((entry) => ({
12817
+ path: entry.path,
12818
+ reason: entry.reason
12819
+ }));
12718
12820
  let used = 0;
12719
12821
  const parts = /* @__PURE__ */ new Map();
12720
12822
  for (const planned of plan.files) {
@@ -12743,14 +12845,23 @@ var answerTool = {
12743
12845
  continue;
12744
12846
  }
12745
12847
  const window = windowText(section.body, 1, linesPerFile);
12746
- const text2 = window.text;
12747
- const tokens = estimateTokens(text2);
12848
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
12849
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
12850
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
12851
+ const tokens = estimateTokens(bodyText);
12748
12852
  if (used + tokens > maxTokens && blocks.length > 0) {
12749
12853
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
12750
12854
  continue;
12751
12855
  }
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 });
12856
+ blocks.push({
12857
+ path: planned.path,
12858
+ why: planned.why,
12859
+ tokens,
12860
+ text: bodyText,
12861
+ truncated: window.truncated || clipped.isTruncated,
12862
+ totalLines: window.totalLines,
12863
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12864
+ });
12754
12865
  used += tokens;
12755
12866
  }
12756
12867
  const lines = [
@@ -12759,7 +12870,9 @@ var answerTool = {
12759
12870
  ];
12760
12871
  for (const block of blocks) {
12761
12872
  lines.push("");
12762
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
12873
+ lines.push(
12874
+ "## " + 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") + ")"
12875
+ );
12763
12876
  lines.push("Why: " + block.why);
12764
12877
  lines.push("```");
12765
12878
  lines.push(block.text);
@@ -12770,6 +12883,11 @@ var answerTool = {
12770
12883
  lines.push("Not included:");
12771
12884
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
12772
12885
  }
12886
+ if (plan.notes.length > 0) {
12887
+ lines.push("");
12888
+ lines.push("Notes:");
12889
+ for (const note of plan.notes) lines.push("- " + note);
12890
+ }
12773
12891
  return {
12774
12892
  text: lines.join("\n"),
12775
12893
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -12884,7 +13002,7 @@ var statusTool = {
12884
13002
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
12885
13003
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
12886
13004
  `Fingerprint: ${manifest.fingerprint}`,
12887
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
13005
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
12888
13006
  ];
12889
13007
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
12890
13008
  if (!versionMatches) {
@@ -13035,6 +13153,16 @@ var generateTool = {
13035
13153
  minimum: 500,
13036
13154
  description: "Fit the snapshot into this token budget, highest value first."
13037
13155
  },
13156
+ only: {
13157
+ type: "array",
13158
+ items: { type: "string" },
13159
+ description: "Globs to include: replaces the config allow-list for this run."
13160
+ },
13161
+ ignore: {
13162
+ type: "array",
13163
+ items: { type: "string" },
13164
+ description: "Globs to exclude, added to the config deny-list for this run."
13165
+ },
13038
13166
  ...SCOPE_PROPERTIES
13039
13167
  },
13040
13168
  additionalProperties: false
@@ -13063,7 +13191,9 @@ var generateTool = {
13063
13191
  ...args.tokenTree === true ? { tokenTree: true } : {},
13064
13192
  ...args.stripComments === true ? { stripComments: true } : {},
13065
13193
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
13066
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
13194
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
13195
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
13196
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
13067
13197
  };
13068
13198
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
13069
13199
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -13107,6 +13237,20 @@ var generateTool = {
13107
13237
  };
13108
13238
  }
13109
13239
  };
13240
+ function configAsGenerated(workspace, manifest) {
13241
+ const recorded = manifest.config;
13242
+ return {
13243
+ ...workspace.config,
13244
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13245
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13246
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13247
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13248
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13249
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13250
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13251
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
13252
+ };
13253
+ }
13110
13254
  var validateTool = {
13111
13255
  name: "snapshot_validate",
13112
13256
  title: "Validate the snapshot",
@@ -13128,9 +13272,11 @@ var validateTool = {
13128
13272
  const prepared = await prepare(args, context, workspaceOverrides(args));
13129
13273
  if (!prepared.ok) return prepared.outcome;
13130
13274
  const workspace = prepared.workspace;
13275
+ const read = readManifest3(workspace);
13276
+ if (!read.ok) return failure(read.message);
13131
13277
  let result;
13132
13278
  try {
13133
- result = validateSnapshot(workspace.config);
13279
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
13134
13280
  } catch (error) {
13135
13281
  return failure(error instanceof Error ? error.message : String(error));
13136
13282
  }
@@ -13494,6 +13640,12 @@ var readTool = {
13494
13640
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
13495
13641
  );
13496
13642
  }
13643
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
13644
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
13645
+ }
13646
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
13647
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
13648
+ }
13497
13649
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
13498
13650
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
13499
13651
  const window = windowText(section.body, fromLine, lineCount);
@@ -13943,6 +14095,8 @@ var COMMAND_OPTION_SCOPE = {
13943
14095
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
13944
14096
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
13945
14097
  // list, so removing them narrows the two together.
14098
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
14099
+ update: ["format", "help"],
13946
14100
  report: [
13947
14101
  "cwd",
13948
14102
  "out-dir",
@@ -14235,6 +14389,13 @@ function buildAgentContract() {
14235
14389
  positionals: [],
14236
14390
  exits: [0]
14237
14391
  },
14392
+ {
14393
+ name: "update",
14394
+ aliases: [],
14395
+ 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.",
14396
+ positionals: [],
14397
+ exits: [0, 1, 2]
14398
+ },
14238
14399
  {
14239
14400
  name: "skill",
14240
14401
  aliases: [],
@@ -14530,14 +14691,14 @@ function buildAgentContract() {
14530
14691
  type: "boolean",
14531
14692
  default: false,
14532
14693
  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."
14694
+ 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
14695
  },
14535
14696
  {
14536
14697
  flag: "--include-logs",
14537
14698
  type: "string",
14538
14699
  default: "unset",
14539
14700
  appliesTo: optionAppliesTo("include-logs"),
14540
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
14701
+ 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
14702
  },
14542
14703
  {
14543
14704
  flag: "--token-tree",
@@ -15531,6 +15692,18 @@ function createMcpServer(options) {
15531
15692
  if (!isJsonObject(rawArguments)) {
15532
15693
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
15533
15694
  }
15695
+ const missing = (prompt.arguments ?? []).filter((argument) => {
15696
+ if (argument.required !== true) return false;
15697
+ const value = rawArguments[argument.name];
15698
+ return typeof value !== "string" || value.trim() === "";
15699
+ });
15700
+ if (missing.length > 0) {
15701
+ return errorResponse(
15702
+ id,
15703
+ ERROR_CODES.invalidParams,
15704
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
15705
+ );
15706
+ }
15534
15707
  const built = prompt.build(rawArguments);
15535
15708
  const messages = built.messages.map((message) => ({
15536
15709
  role: message.role,
@@ -15809,20 +15982,20 @@ var SERVE_PAGE = `<!doctype html>
15809
15982
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
15810
15983
  <main>
15811
15984
  <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">
15985
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
15986
+ <select id="mode" aria-label="What to generate" title="What to generate">
15814
15987
  <option value="full">whole repository</option>
15815
15988
  <option value="slice">a slice for a question</option>
15816
15989
  <option value="budget">fit a token budget</option>
15817
15990
  </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>
15991
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
15992
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
15820
15993
  <button id="run" type="submit">Generate</button>
15821
15994
  <button id="download" type="button" disabled>Download .zip</button>
15822
15995
  </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>
15996
+ <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
15997
  <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>
15998
+ <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
15999
  </div>
15827
16000
  <div class="row">
15828
16001
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -16117,9 +16290,14 @@ async function startWebServer(options) {
16117
16290
  send(400, { error: "not a directory: " + target });
16118
16291
  return;
16119
16292
  }
16293
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
16294
+ if (loaded.errors.length > 0) {
16295
+ send(400, { error: loaded.errors.join("; ") });
16296
+ return;
16297
+ }
16120
16298
  const started = Date.now();
16121
16299
  try {
16122
- const manifest = generateSnapshot({ cwd: target }, {
16300
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
16123
16301
  ...provenance === void 0 ? {} : { source: provenance },
16124
16302
  ...mode === "slice" ? { slice: { question } } : {},
16125
16303
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -16252,8 +16430,8 @@ async function startWebServer(options) {
16252
16430
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
16253
16431
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
16254
16432
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
16255
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
16256
- var REQUEST_TIMEOUT_MS = 1200;
16433
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
16434
+ var REQUEST_TIMEOUT_MS = 2500;
16257
16435
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
16258
16436
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
16259
16437
  const script = normalise(scriptPath);
@@ -16317,7 +16495,7 @@ function shouldCheck(argv, env) {
16317
16495
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
16318
16496
  const args = argv.map((argument) => argument.toLowerCase());
16319
16497
  if (args.includes("--no-update-check")) return false;
16320
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
16498
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
16321
16499
  if (args.includes(skip)) return false;
16322
16500
  }
16323
16501
  let format = null;
@@ -16413,13 +16591,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
16413
16591
  });
16414
16592
  }
16415
16593
  async function checkForUpdate(options) {
16594
+ const latest = await resolveLatest(options);
16595
+ if (!latest) return null;
16596
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16597
+ }
16598
+ async function resolveLatest(options) {
16416
16599
  if (options.enabled === false) return null;
16417
16600
  const now = options.now ?? (() => Date.now());
16418
16601
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
16602
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
16419
16603
  let latest = null;
16420
16604
  try {
16421
16605
  const cached = readCache(options.cacheFile);
16422
- let needsFetch = cached === null;
16606
+ let needsFetch = cached === null || options.force === true;
16423
16607
  if (cached) {
16424
16608
  const age = now() - cached.checkedAt;
16425
16609
  if (cached.latest === null) {
@@ -16431,15 +16615,14 @@ async function checkForUpdate(options) {
16431
16615
  }
16432
16616
  }
16433
16617
  if (needsFetch) {
16434
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
16618
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
16435
16619
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
16436
- latest = fetched;
16620
+ latest = fetched ?? latest;
16437
16621
  }
16438
16622
  } catch {
16439
16623
  return null;
16440
16624
  }
16441
- if (!latest) return null;
16442
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16625
+ return latest;
16443
16626
  }
16444
16627
  function formatUpdateNotice(notice, kind) {
16445
16628
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -19740,6 +19923,11 @@ function generateSnapshot(configInput, options) {
19740
19923
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
19741
19924
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
19742
19925
  };
19926
+ if (plan.files.length === 0) {
19927
+ warnings.push(
19928
+ "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.")
19929
+ );
19930
+ }
19743
19931
  }
19744
19932
  let budgetBlock;
19745
19933
  if (options?.budgetTokens !== void 0) {
@@ -19831,6 +20019,11 @@ function generateSnapshot(configInput, options) {
19831
20019
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
19832
20020
  }
19833
20021
  }
20022
+ if (config.include.length > 0 && files.length === 0) {
20023
+ warnings.push(
20024
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20025
+ );
20026
+ }
19834
20027
  if (changedScope !== null || options?.deltaBase !== void 0) {
19835
20028
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
19836
20029
  for (const relativePath of unchangedPaths) {
@@ -19969,6 +20162,12 @@ function generateSnapshot(configInput, options) {
19969
20162
  maxMonolithBytes: config.maxMonolithBytes ?? null,
19970
20163
  includeSensitiveFiles: config.includeSensitiveFiles,
19971
20164
  ...config.stripComments === true ? { stripComments: true } : {},
20165
+ // The other three settings the digest covers and the manifest did not record: without them a
20166
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20167
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20168
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20169
+ ...config.pack === null ? {} : { pack: config.pack },
20170
+ logCount: config.logCount,
19972
20171
  // The destination the instructions were written for. Not part of `digest`: the payload is
19973
20172
  // identical whatever this says, and a new delivery preference must not make an existing
19974
20173
  // snapshot fail `validate` as configuration drift.
@@ -20112,6 +20311,18 @@ function generateSnapshot(configInput, options) {
20112
20311
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20113
20312
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20114
20313
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20314
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20315
+ manifest.warnings.push(
20316
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20317
+ );
20318
+ manifest.totals.warningCount = manifest.warnings.length;
20319
+ }
20320
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20321
+ manifest.warnings.push(
20322
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20323
+ );
20324
+ manifest.totals.warningCount = manifest.warnings.length;
20325
+ }
20115
20326
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20116
20327
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20117
20328
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20161,17 +20372,19 @@ function generateSnapshot(configInput, options) {
20161
20372
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20162
20373
  }
20163
20374
  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
- );
20375
+ if (markdown !== null) {
20376
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20377
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20378
+ monolithMarkdown = markdown;
20379
+ manifest.artifacts.fullMarkdown = {
20380
+ byteSize: markdownBytes,
20381
+ sha256: sha256Hex2(markdown)
20382
+ };
20383
+ } else {
20384
+ manifest.warnings.push(
20385
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20386
+ );
20387
+ }
20175
20388
  }
20176
20389
  if (wantsXml && !definitelyTooLarge) {
20177
20390
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20187,14 +20400,16 @@ function generateSnapshot(configInput, options) {
20187
20400
  }
20188
20401
  manifest.totals.warningCount = manifest.warnings.length;
20189
20402
  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
- );
20403
+ if (json !== null) {
20404
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20405
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20406
+ monolithJson = json;
20407
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20408
+ } else {
20409
+ manifest.warnings.push(
20410
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20411
+ );
20412
+ }
20198
20413
  }
20199
20414
  manifest.totals.warningCount = manifest.warnings.length;
20200
20415
  }