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.
@@ -1,4 +1,4 @@
1
- import * as crypto4 from 'crypto';
1
+ import * as crypto3 from 'crypto';
2
2
  import { createHash, randomBytes, timingSafeEqual } from 'crypto';
3
3
  import { Worker } from 'worker_threads';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
@@ -893,7 +893,7 @@ function summarizeTypeScriptSource(relativePath, content) {
893
893
  }
894
894
  const callee = node.expression;
895
895
  if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression) && ROUTE_RECEIVERS.has(callee.expression.text) && ROUTE_REGISTRATION_VERBS.has(callee.name.text.toLowerCase()) && firstArgument !== void 0 && ts.isStringLiteral(firstArgument)) {
896
- summary.routeHandlers.push(callee.name.text.toUpperCase());
896
+ summary.routeHandlers.push(callee.name.text.toUpperCase() + " " + firstArgument.text);
897
897
  }
898
898
  }
899
899
  if (ts.isExportDeclaration(node)) {
@@ -3994,7 +3994,7 @@ function applySpansKeepingQuotes(line, spans) {
3994
3994
 
3995
3995
  // src/version.ts
3996
3996
  var GENERATOR_NAME = "codebase-snapshot";
3997
- var GENERATOR_VERSION = "0.16.0";
3997
+ var GENERATOR_VERSION = "0.18.0";
3998
3998
  var SCHEMA_VERSION = "3.0.0";
3999
3999
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4000
4000
  function isOurGeneratorName(name) {
@@ -4045,6 +4045,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4045
4045
  let branch = fallbackBranch;
4046
4046
  let commit = "unknown";
4047
4047
  let isDirty = false;
4048
+ let branchFromGit = false;
4048
4049
  const records = output.split("\0").flatMap((record) => record.split("\n"));
4049
4050
  for (const record of records) {
4050
4051
  if (record.length === 0) continue;
@@ -4060,13 +4061,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4060
4061
  const head = record.match(/^# branch\.head (.+)$/);
4061
4062
  if (head) {
4062
4063
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
4064
+ branchFromGit = head[1] !== "(detached)";
4063
4065
  }
4064
4066
  }
4065
- return { branch, commit, isDirty };
4067
+ return { branch, commit, isDirty, branchFromGit };
4066
4068
  } catch (err) {
4067
4069
  const code = err.code;
4068
4070
  const isDirty = code === "ENOBUFS";
4069
- return { branch: fallbackBranch, commit: "unknown", isDirty };
4071
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
4070
4072
  }
4071
4073
  }
4072
4074
  var DEFAULT_IGNORED_DIRS = [
@@ -6074,7 +6076,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
6074
6076
  "# Codebase Health & Security Audit",
6075
6077
  "",
6076
6078
  `**Generated:** ${manifest.generatedAt} `,
6077
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
6079
+ `**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" : ""} `,
6078
6080
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
6079
6081
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
6080
6082
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -6231,7 +6233,7 @@ var BUILTIN_RULE_IDS = new Map(
6231
6233
  function ruleIdFor(name) {
6232
6234
  const builtin = BUILTIN_RULE_IDS.get(name);
6233
6235
  if (builtin !== void 0) return builtin;
6234
- const digest = crypto4.createHash("sha256").update(name).digest("hex").slice(0, 8);
6236
+ const digest = crypto3.createHash("sha256").update(name).digest("hex").slice(0, 8);
6235
6237
  return `CS${digest.toUpperCase()}`;
6236
6238
  }
6237
6239
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -6569,7 +6571,7 @@ function renumberParts(parts, contentFingerprint) {
6569
6571
  filename: nameFor(index + 1),
6570
6572
  byteSize: Buffer.byteLength(markdown, "utf8"),
6571
6573
  estimatedTokens,
6572
- sha256: crypto4.createHash("sha256").update(markdown).digest("hex"),
6574
+ sha256: crypto3.createHash("sha256").update(markdown).digest("hex"),
6573
6575
  lines: countLines(markdown),
6574
6576
  fileCount: included.length,
6575
6577
  layersCovered: Object.keys(layerCounts).sort()
@@ -6695,7 +6697,7 @@ function rehashPart(part, markdown) {
6695
6697
  metadata: {
6696
6698
  ...part.metadata,
6697
6699
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6698
- sha256: crypto4.createHash("sha256").update(redistributed).digest("hex"),
6700
+ sha256: crypto3.createHash("sha256").update(redistributed).digest("hex"),
6699
6701
  lines: countLines(redistributed),
6700
6702
  estimatedTokens
6701
6703
  }
@@ -6776,7 +6778,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
6776
6778
  return groups.map((group, index) => {
6777
6779
  const { filename, content, estimatedTokens } = assemble(group, index, total);
6778
6780
  const byteSize = Buffer.byteLength(content, "utf8");
6779
- const sha2562 = crypto4.createHash("sha256").update(content).digest("hex");
6781
+ const sha2562 = crypto3.createHash("sha256").update(content).digest("hex");
6780
6782
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
6781
6783
  const includedFiles = group.sections.map(({ file }) => ({
6782
6784
  relativePath: file.relativePath,
@@ -6858,7 +6860,7 @@ function renderSummary(summary, inclusionMode) {
6858
6860
  }
6859
6861
  function anchorForPath(filePath) {
6860
6862
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6861
- const digest = crypto4.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6863
+ const digest = crypto3.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6862
6864
  return `${slug || "file"}-${digest}`;
6863
6865
  }
6864
6866
 
@@ -7205,13 +7207,19 @@ function planForQuestion(manifest, question, options = {}) {
7205
7207
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
7206
7208
  }
7207
7209
  const notes = [];
7210
+ if (manifest.files.length === 0) {
7211
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
7212
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
7213
+ }
7208
7214
  if (scored.length === 0) {
7209
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7210
7215
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
7211
7216
  for (const hub of hubs) {
7212
7217
  const file = byPath.get(hub.path);
7213
7218
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
7214
7219
  }
7220
+ if (scored.length > 0) {
7221
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7222
+ }
7215
7223
  }
7216
7224
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7217
7225
  const chosen = /* @__PURE__ */ new Map();
@@ -7275,7 +7283,14 @@ function planForQuestion(manifest, question, options = {}) {
7275
7283
  }
7276
7284
  }
7277
7285
  }
7278
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
7286
+ if (chosen.size === 0) {
7287
+ if (scored.length === 0) {
7288
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
7289
+ } else {
7290
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
7291
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
7292
+ }
7293
+ }
7279
7294
  notes.push(
7280
7295
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
7281
7296
  );
@@ -7890,7 +7905,7 @@ function snapshotSection(manifest, code, partsWritten) {
7890
7905
  const out = ["## This snapshot", ""];
7891
7906
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
7892
7907
  out.push(
7893
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
7908
+ "- 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)." : ".")
7894
7909
  );
7895
7910
  out.push(
7896
7911
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -8063,7 +8078,7 @@ function generateReadme(manifest, artifacts) {
8063
8078
  "",
8064
8079
  `- **Generated At:** \`${manifest.generatedAt}\``,
8065
8080
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
8066
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
8081
+ `- **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" : ""}`,
8067
8082
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
8068
8083
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
8069
8084
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -8623,6 +8638,71 @@ function detectLanguage(filePath) {
8623
8638
  const ext = path25.posix.extname(base).toLowerCase();
8624
8639
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8625
8640
  }
8641
+ var SIGNATURE_FILE = "signature.json";
8642
+ function loadSigningKey(environment = process.env) {
8643
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
8644
+ if (pem === void 0 || pem.trim() === "") return null;
8645
+ return crypto3.createPrivateKey({ key: pem, format: "pem" });
8646
+ }
8647
+ function signManifest(manifestPath, options = {}) {
8648
+ const bytes = fs24.readFileSync(manifestPath);
8649
+ const manifest = JSON.parse(bytes.toString("utf8"));
8650
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
8651
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
8652
+ }
8653
+ const configured = options.key ?? null;
8654
+ const key = configured ?? crypto3.generateKeyPairSync("ed25519").privateKey;
8655
+ const publicKey = crypto3.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
8656
+ const signature = crypto3.sign(null, bytes, key).toString("base64");
8657
+ return {
8658
+ algorithm: "ed25519",
8659
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
8660
+ fingerprint: manifest.fingerprint,
8661
+ manifestSha256: crypto3.createHash("sha256").update(bytes).digest("hex"),
8662
+ publicKey,
8663
+ signature,
8664
+ keyOrigin: configured === null ? "generated" : "configured"
8665
+ };
8666
+ }
8667
+ function writeSignature(snapshotDir, record) {
8668
+ const target = path25.join(snapshotDir, SIGNATURE_FILE);
8669
+ fs24.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
8670
+ return target;
8671
+ }
8672
+ function verifySnapshotSignature(snapshotDir) {
8673
+ const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
8674
+ const manifestPath = path25.join(snapshotDir, "manifest.json");
8675
+ if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8676
+ let record;
8677
+ try {
8678
+ record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
8679
+ } catch (error) {
8680
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
8681
+ }
8682
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8683
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
8684
+ }
8685
+ let bytes;
8686
+ try {
8687
+ bytes = fs24.readFileSync(manifestPath);
8688
+ } catch {
8689
+ return { ok: false, reason: "the signed manifest is missing" };
8690
+ }
8691
+ const sha2562 = crypto3.createHash("sha256").update(bytes).digest("hex");
8692
+ if (sha2562 !== record.manifestSha256) {
8693
+ return { ok: false, reason: "manifest.json changed after it was signed" };
8694
+ }
8695
+ let verified = false;
8696
+ try {
8697
+ const key = crypto3.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8698
+ verified = crypto3.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8699
+ } catch (error) {
8700
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
8701
+ }
8702
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8703
+ }
8704
+
8705
+ // src/validator/validate.ts
8626
8706
  function maskedPath(value, secretRules) {
8627
8707
  return findSecretInPath(value, secretRules)?.masked ?? value;
8628
8708
  }
@@ -8686,7 +8766,7 @@ function emptyDrift() {
8686
8766
  };
8687
8767
  }
8688
8768
  function sha256Hex(buffer) {
8689
- return crypto4.createHash("sha256").update(buffer).digest("hex");
8769
+ return crypto3.createHash("sha256").update(buffer).digest("hex");
8690
8770
  }
8691
8771
  function wouldNowBeIncluded(cwd, relativePath) {
8692
8772
  const absolutePath = path25.join(cwd, relativePath);
@@ -9623,6 +9703,11 @@ function validateSnapshot(configInput) {
9623
9703
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9624
9704
  );
9625
9705
  }
9706
+ const signaturePath = path25.join(path25.dirname(manifestPath), "signature.json");
9707
+ if (fs24.existsSync(signaturePath)) {
9708
+ const outcome = verifySnapshotSignature(path25.dirname(manifestPath));
9709
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9710
+ }
9626
9711
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
9627
9712
  warnings.push(
9628
9713
  "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."
@@ -10029,69 +10114,6 @@ function negotiateLegacyVersion(requested) {
10029
10114
  }
10030
10115
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
10031
10116
  }
10032
- var SIGNATURE_FILE = "signature.json";
10033
- function loadSigningKey(environment = process.env) {
10034
- const pem = environment.SNAPSHOT_SIGNING_KEY;
10035
- if (pem === void 0 || pem.trim() === "") return null;
10036
- return crypto4.createPrivateKey({ key: pem, format: "pem" });
10037
- }
10038
- function signManifest(manifestPath, options = {}) {
10039
- const bytes = fs24.readFileSync(manifestPath);
10040
- const manifest = JSON.parse(bytes.toString("utf8"));
10041
- if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
10042
- throw new Error("refusing to sign: the manifest has no valid fingerprint");
10043
- }
10044
- const configured = options.key ?? null;
10045
- const key = configured ?? crypto4.generateKeyPairSync("ed25519").privateKey;
10046
- const publicKey = crypto4.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
10047
- const signature = crypto4.sign(null, bytes, key).toString("base64");
10048
- return {
10049
- algorithm: "ed25519",
10050
- signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
10051
- fingerprint: manifest.fingerprint,
10052
- manifestSha256: crypto4.createHash("sha256").update(bytes).digest("hex"),
10053
- publicKey,
10054
- signature,
10055
- keyOrigin: configured === null ? "generated" : "configured"
10056
- };
10057
- }
10058
- function writeSignature(snapshotDir, record) {
10059
- const target = path25.join(snapshotDir, SIGNATURE_FILE);
10060
- fs24.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
10061
- return target;
10062
- }
10063
- function verifySnapshotSignature(snapshotDir) {
10064
- const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
10065
- const manifestPath = path25.join(snapshotDir, "manifest.json");
10066
- if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
10067
- let record;
10068
- try {
10069
- record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
10070
- } catch (error) {
10071
- return { ok: false, reason: "signature.json is not JSON: " + error.message };
10072
- }
10073
- if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
10074
- return { ok: false, reason: "signature.json is not an ed25519 record" };
10075
- }
10076
- let bytes;
10077
- try {
10078
- bytes = fs24.readFileSync(manifestPath);
10079
- } catch {
10080
- return { ok: false, reason: "the signed manifest is missing" };
10081
- }
10082
- const sha2562 = crypto4.createHash("sha256").update(bytes).digest("hex");
10083
- if (sha2562 !== record.manifestSha256) {
10084
- return { ok: false, reason: "manifest.json changed after it was signed" };
10085
- }
10086
- let verified = false;
10087
- try {
10088
- const key = crypto4.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
10089
- verified = crypto4.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
10090
- } catch (error) {
10091
- return { ok: false, reason: "the signature could not be checked: " + error.message };
10092
- }
10093
- return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
10094
- }
10095
10117
 
10096
10118
  // src/partitioner/part-format.ts
10097
10119
  var FILE_HEADING = "### FILE: ";
@@ -10672,8 +10694,9 @@ function auditSnapshot(options) {
10672
10694
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
10673
10695
  disagreements.push("file count");
10674
10696
  }
10697
+ const sourceGone = typeof member.path === "string" && !fs24.existsSync(member.path) ? "Member " + memberName + " source directory is gone (" + member.path + "); the snapshot still describes it. Regenerate the workspace." : null;
10675
10698
  checks.push(
10676
- disagreements.length === 0 ? check(
10699
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
10677
10700
  "workspace.index",
10678
10701
  "The workspace index agrees with this member",
10679
10702
  "warning",
@@ -10695,6 +10718,7 @@ function auditSnapshot(options) {
10695
10718
  let scannedBytes = 0;
10696
10719
  for (const relative13 of walk(snapshotDir)) {
10697
10720
  if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
10721
+ if (relative13 === SIGNATURE_FILE) continue;
10698
10722
  const text2 = readText2(path25.join(snapshotDir, relative13));
10699
10723
  if (text2 === null) continue;
10700
10724
  scannedBytes += Buffer.byteLength(text2, "utf8");
@@ -10703,6 +10727,28 @@ function auditSnapshot(options) {
10703
10727
  leakHits.push(relative13 + " (" + found.findings.length + " line(s))");
10704
10728
  }
10705
10729
  }
10730
+ const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
10731
+ if (fs24.existsSync(signatureRecordPath)) {
10732
+ const recordText = readText2(signatureRecordPath);
10733
+ if (recordText !== null) {
10734
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
10735
+ let scanText = recordText;
10736
+ try {
10737
+ const record = JSON.parse(recordText);
10738
+ const rest = { ...record };
10739
+ delete rest.publicKey;
10740
+ delete rest.signature;
10741
+ delete rest.manifestSha256;
10742
+ delete rest.fingerprint;
10743
+ scanText = JSON.stringify(rest, null, 2);
10744
+ } catch {
10745
+ }
10746
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
10747
+ if (found.findings.length > 0) {
10748
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
10749
+ }
10750
+ }
10751
+ }
10706
10752
  checks.push(
10707
10753
  leakHits.length === 0 ? check(
10708
10754
  "secrets.artifacts",
@@ -11436,6 +11482,10 @@ var WRITES = {
11436
11482
  openWorldHint: false
11437
11483
  };
11438
11484
  var MAX_RESULT_BYTES = 64 * 1024;
11485
+ function capResultText(text2) {
11486
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
11487
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
11488
+ }
11439
11489
  var ROOT_PROPERTY = {
11440
11490
  type: "string",
11441
11491
  description: "Repository root. Defaults to the directory this server was started in."
@@ -11623,6 +11673,17 @@ var historyTool = {
11623
11673
  isError: true
11624
11674
  };
11625
11675
  }
11676
+ const manifestRead = readManifest3(prepared.workspace);
11677
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
11678
+ if (recordedLog !== void 0 && recordedLog !== null) {
11679
+ const digest = createHash("sha256").update(text2, "utf8").digest("hex");
11680
+ if (digest !== recordedLog.sha256) {
11681
+ return {
11682
+ 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.",
11683
+ isError: true
11684
+ };
11685
+ }
11686
+ }
11626
11687
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
11627
11688
  const commits = parseHistoryReport(text2).slice(0, limit);
11628
11689
  return {
@@ -11682,9 +11743,12 @@ var budgetTool = {
11682
11743
  });
11683
11744
  }
11684
11745
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
11746
+ if (read.manifest.files.length === 0) {
11747
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
11748
+ }
11685
11749
  for (const row of rows) {
11686
11750
  lines.push(
11687
- 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" : "") + ")")
11751
+ 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" : "") + ")")
11688
11752
  );
11689
11753
  }
11690
11754
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -11936,7 +12000,7 @@ var routesTool = {
11936
12000
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
11937
12001
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
11938
12002
  routes.length + " route(s):",
11939
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
12003
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
11940
12004
  ].join("\n");
11941
12005
  return { text: text2, structured: { total: routes.length, routes } };
11942
12006
  }
@@ -12105,8 +12169,9 @@ var searchTool = {
12105
12169
  }
12106
12170
  }
12107
12171
  }
12172
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
12108
12173
  const lines = [
12109
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
12174
+ 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." : ""),
12110
12175
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
12111
12176
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
12112
12177
  ];
@@ -12129,7 +12194,9 @@ var statsTool = {
12129
12194
  parts: { type: "integer" },
12130
12195
  tokens: { type: "integer" },
12131
12196
  layers: { type: "object" },
12132
- kinds: { type: "object" }
12197
+ kinds: { type: "object" },
12198
+ heaviest: { type: "array", items: { type: "object" } },
12199
+ partSizes: { type: "array", items: { type: "object" } }
12133
12200
  }
12134
12201
  },
12135
12202
  annotations: READ_ONLY,
@@ -12140,7 +12207,11 @@ var statsTool = {
12140
12207
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12141
12208
  const manifest = read.manifest;
12142
12209
  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 }));
12143
- const parts = manifest.parts.map((part) => ({ filename: part.filename, tokens: part.estimatedTokens }));
12210
+ const parts = manifest.parts.map((part) => ({
12211
+ filename: part.filename,
12212
+ bytes: part.byteSize,
12213
+ tokens: part.estimatedTokens
12214
+ }));
12144
12215
  const lines = [
12145
12216
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
12146
12217
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -12196,7 +12267,7 @@ var reviewTool = {
12196
12267
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12197
12268
  let validation;
12198
12269
  try {
12199
- validation = validateSnapshot(workspace.config);
12270
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
12200
12271
  } catch (error) {
12201
12272
  return { text: error.message, isError: true };
12202
12273
  }
@@ -12296,24 +12367,17 @@ var diffContextTool = {
12296
12367
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
12297
12368
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
12298
12369
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
12370
+ const resolver = buildImportResolver(read.manifest.files, {
12371
+ tsconfig: tsconfigPathsFor(workspace.root)
12372
+ });
12299
12373
  const importers = /* @__PURE__ */ new Map();
12300
12374
  for (const entry of read.manifest.indexes.imports.byFile) {
12301
12375
  for (const specifier of entry.imports) {
12302
- if (!specifier.startsWith(".")) continue;
12303
- const base = entry.path.includes("/") ? entry.path.slice(0, entry.path.lastIndexOf("/")) : "";
12304
- const parts = [];
12305
- for (const segment of (base + "/" + specifier).split("/")) {
12306
- if (segment === "" || segment === ".") continue;
12307
- if (segment === "..") parts.pop();
12308
- else parts.push(segment);
12309
- }
12310
- const joined = parts.join("/").toLowerCase();
12311
- const withoutExtension = joined.replace(/\.[cm]?[jt]sx?$/, "");
12312
- 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);
12313
- if (target === void 0) continue;
12314
- const list2 = importers.get(target.relativePath) ?? [];
12376
+ const target = resolveSpecifier(entry.path, specifier, resolver);
12377
+ if (target === null) continue;
12378
+ const list2 = importers.get(target) ?? [];
12315
12379
  list2.push(entry.path);
12316
- importers.set(target.relativePath, list2);
12380
+ importers.set(target, list2);
12317
12381
  }
12318
12382
  }
12319
12383
  const missing = [];
@@ -12348,9 +12412,12 @@ var diffContextTool = {
12348
12412
  continue;
12349
12413
  }
12350
12414
  used += tokens;
12415
+ const capped2 = capResultText(window.text);
12351
12416
  changed.push({ path: file.relativePath, part: file.part, tokens });
12352
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12353
- text2.push(window.text);
12417
+ text2.push(
12418
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12419
+ );
12420
+ text2.push(capped2.text);
12354
12421
  }
12355
12422
  const dependents = [];
12356
12423
  for (const entry of changed) {
@@ -12432,11 +12499,13 @@ var symbolTool = {
12432
12499
  if (index === -1) continue;
12433
12500
  const from = Math.max(0, index - 3);
12434
12501
  const to = Math.min(lines.length, index + windowSize);
12502
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
12435
12503
  matches.push({
12436
12504
  path: file.relativePath,
12437
12505
  part: file.part,
12438
12506
  line: index + 1,
12439
- text: lines.slice(from, to).join("\n")
12507
+ text: capped2.text,
12508
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12440
12509
  });
12441
12510
  }
12442
12511
  if (matches.length === 0) {
@@ -12567,7 +12636,8 @@ var contextTool = {
12567
12636
  continue;
12568
12637
  }
12569
12638
  const window = windowText(section.body, 1, linesPerFile);
12570
- const body = window.text;
12639
+ const capped2 = capResultText(window.text);
12640
+ const body = capped2.text;
12571
12641
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
12572
12642
  if (used + tokens > budget) {
12573
12643
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -12576,14 +12646,19 @@ var contextTool = {
12576
12646
  missing.push(file.relativePath + " (budget)");
12577
12647
  continue;
12578
12648
  }
12579
- const partial = Math.max(1, Math.ceil(Buffer.byteLength(smaller.text, "utf8") / 4));
12580
- text2.push("### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines)");
12581
- text2.push(smaller.text);
12649
+ const smallerCapped = capResultText(smaller.text);
12650
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
12651
+ text2.push(
12652
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
12653
+ );
12654
+ text2.push(smallerCapped.text);
12582
12655
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
12583
12656
  used += partial;
12584
12657
  continue;
12585
12658
  }
12586
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12659
+ text2.push(
12660
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12661
+ );
12587
12662
  text2.push(body);
12588
12663
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
12589
12664
  used += tokens;
@@ -12757,8 +12832,17 @@ var answerTool = {
12757
12832
  maxTokens,
12758
12833
  ...args.includeTests === true ? { includeTests: true } : {}
12759
12834
  });
12835
+ if (read.manifest.files.length === 0) {
12836
+ return {
12837
+ 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).",
12838
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
12839
+ };
12840
+ }
12760
12841
  const blocks = [];
12761
- const omitted = [];
12842
+ const omitted = plan.skipped.map((entry) => ({
12843
+ path: entry.path,
12844
+ reason: entry.reason
12845
+ }));
12762
12846
  let used = 0;
12763
12847
  const parts = /* @__PURE__ */ new Map();
12764
12848
  for (const planned of plan.files) {
@@ -12787,14 +12871,23 @@ var answerTool = {
12787
12871
  continue;
12788
12872
  }
12789
12873
  const window = windowText(section.body, 1, linesPerFile);
12790
- const text2 = window.text;
12791
- const tokens = estimateTokens(text2);
12874
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
12875
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
12876
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
12877
+ const tokens = estimateTokens(bodyText);
12792
12878
  if (used + tokens > maxTokens && blocks.length > 0) {
12793
12879
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
12794
12880
  continue;
12795
12881
  }
12796
- const numbered = text2.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
12797
- blocks.push({ path: planned.path, why: planned.why, tokens, text: numbered, truncated: window.truncated, totalLines: window.totalLines });
12882
+ blocks.push({
12883
+ path: planned.path,
12884
+ why: planned.why,
12885
+ tokens,
12886
+ text: bodyText,
12887
+ truncated: window.truncated || clipped.isTruncated,
12888
+ totalLines: window.totalLines,
12889
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12890
+ });
12798
12891
  used += tokens;
12799
12892
  }
12800
12893
  const lines = [
@@ -12803,7 +12896,9 @@ var answerTool = {
12803
12896
  ];
12804
12897
  for (const block of blocks) {
12805
12898
  lines.push("");
12806
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
12899
+ lines.push(
12900
+ "## " + 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") + ")"
12901
+ );
12807
12902
  lines.push("Why: " + block.why);
12808
12903
  lines.push("```");
12809
12904
  lines.push(block.text);
@@ -12814,6 +12909,11 @@ var answerTool = {
12814
12909
  lines.push("Not included:");
12815
12910
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
12816
12911
  }
12912
+ if (plan.notes.length > 0) {
12913
+ lines.push("");
12914
+ lines.push("Notes:");
12915
+ for (const note of plan.notes) lines.push("- " + note);
12916
+ }
12817
12917
  return {
12818
12918
  text: lines.join("\n"),
12819
12919
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -12928,7 +13028,7 @@ var statusTool = {
12928
13028
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
12929
13029
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
12930
13030
  `Fingerprint: ${manifest.fingerprint}`,
12931
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
13031
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
12932
13032
  ];
12933
13033
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
12934
13034
  if (!versionMatches) {
@@ -13079,6 +13179,16 @@ var generateTool = {
13079
13179
  minimum: 500,
13080
13180
  description: "Fit the snapshot into this token budget, highest value first."
13081
13181
  },
13182
+ only: {
13183
+ type: "array",
13184
+ items: { type: "string" },
13185
+ description: "Globs to include: replaces the config allow-list for this run."
13186
+ },
13187
+ ignore: {
13188
+ type: "array",
13189
+ items: { type: "string" },
13190
+ description: "Globs to exclude, added to the config deny-list for this run."
13191
+ },
13082
13192
  ...SCOPE_PROPERTIES
13083
13193
  },
13084
13194
  additionalProperties: false
@@ -13107,7 +13217,9 @@ var generateTool = {
13107
13217
  ...args.tokenTree === true ? { tokenTree: true } : {},
13108
13218
  ...args.stripComments === true ? { stripComments: true } : {},
13109
13219
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
13110
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
13220
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
13221
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
13222
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
13111
13223
  };
13112
13224
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
13113
13225
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -13151,6 +13263,20 @@ var generateTool = {
13151
13263
  };
13152
13264
  }
13153
13265
  };
13266
+ function configAsGenerated(workspace, manifest) {
13267
+ const recorded = manifest.config;
13268
+ return {
13269
+ ...workspace.config,
13270
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13271
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13272
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13273
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13274
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13275
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13276
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13277
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
13278
+ };
13279
+ }
13154
13280
  var validateTool = {
13155
13281
  name: "snapshot_validate",
13156
13282
  title: "Validate the snapshot",
@@ -13172,9 +13298,11 @@ var validateTool = {
13172
13298
  const prepared = await prepare(args, context, workspaceOverrides(args));
13173
13299
  if (!prepared.ok) return prepared.outcome;
13174
13300
  const workspace = prepared.workspace;
13301
+ const read = readManifest3(workspace);
13302
+ if (!read.ok) return failure(read.message);
13175
13303
  let result;
13176
13304
  try {
13177
- result = validateSnapshot(workspace.config);
13305
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
13178
13306
  } catch (error) {
13179
13307
  return failure(error instanceof Error ? error.message : String(error));
13180
13308
  }
@@ -13538,6 +13666,12 @@ var readTool = {
13538
13666
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
13539
13667
  );
13540
13668
  }
13669
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
13670
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
13671
+ }
13672
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
13673
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
13674
+ }
13541
13675
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
13542
13676
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
13543
13677
  const window = windowText(section.body, fromLine, lineCount);
@@ -13987,6 +14121,8 @@ var COMMAND_OPTION_SCOPE = {
13987
14121
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
13988
14122
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
13989
14123
  // list, so removing them narrows the two together.
14124
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
14125
+ update: ["format", "help"],
13990
14126
  report: [
13991
14127
  "cwd",
13992
14128
  "out-dir",
@@ -14348,6 +14484,13 @@ function buildAgentContract() {
14348
14484
  positionals: [],
14349
14485
  exits: [0]
14350
14486
  },
14487
+ {
14488
+ name: "update",
14489
+ aliases: [],
14490
+ 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.",
14491
+ positionals: [],
14492
+ exits: [0, 1, 2]
14493
+ },
14351
14494
  {
14352
14495
  name: "skill",
14353
14496
  aliases: [],
@@ -14643,14 +14786,14 @@ function buildAgentContract() {
14643
14786
  type: "boolean",
14644
14787
  default: false,
14645
14788
  appliesTo: optionAppliesTo("include-diffs"),
14646
- 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."
14789
+ 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."
14647
14790
  },
14648
14791
  {
14649
14792
  flag: "--include-logs",
14650
14793
  type: "string",
14651
14794
  default: "unset",
14652
14795
  appliesTo: optionAppliesTo("include-logs"),
14653
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
14796
+ 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."
14654
14797
  },
14655
14798
  {
14656
14799
  flag: "--token-tree",
@@ -15644,6 +15787,18 @@ function createMcpServer(options) {
15644
15787
  if (!isJsonObject(rawArguments)) {
15645
15788
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
15646
15789
  }
15790
+ const missing = (prompt.arguments ?? []).filter((argument) => {
15791
+ if (argument.required !== true) return false;
15792
+ const value = rawArguments[argument.name];
15793
+ return typeof value !== "string" || value.trim() === "";
15794
+ });
15795
+ if (missing.length > 0) {
15796
+ return errorResponse(
15797
+ id,
15798
+ ERROR_CODES.invalidParams,
15799
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
15800
+ );
15801
+ }
15647
15802
  const built = prompt.build(rawArguments);
15648
15803
  const messages = built.messages.map((message) => ({
15649
15804
  role: message.role,
@@ -16111,20 +16266,20 @@ var SERVE_PAGE = `<!doctype html>
16111
16266
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
16112
16267
  <main>
16113
16268
  <form id="gen">
16114
- <input id="source" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
16115
- <select id="mode" title="What to generate">
16269
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
16270
+ <select id="mode" aria-label="What to generate" title="What to generate">
16116
16271
  <option value="full">whole repository</option>
16117
16272
  <option value="slice">a slice for a question</option>
16118
16273
  <option value="budget">fit a token budget</option>
16119
16274
  </select>
16120
- <input id="question" placeholder="the question (slice mode)" spellcheck="false" hidden>
16121
- <input id="budget" type="number" min="500" step="500" value="30000" title="token budget" hidden>
16275
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
16276
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
16122
16277
  <button id="run" type="submit">Generate</button>
16123
16278
  <button id="download" type="button" disabled>Download .zip</button>
16124
16279
  </form>
16125
- <div id="status">Paste an absolute path, or a repository URL (https://github.com/owner/repo). Remote fetches are shallow and public-only.</div>
16280
+ <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>
16126
16281
  <div id="auth" hidden>
16127
- <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>
16282
+ <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>
16128
16283
  </div>
16129
16284
  <div class="row">
16130
16285
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -16419,9 +16574,14 @@ async function startWebServer(options) {
16419
16574
  send(400, { error: "not a directory: " + target });
16420
16575
  return;
16421
16576
  }
16577
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
16578
+ if (loaded.errors.length > 0) {
16579
+ send(400, { error: loaded.errors.join("; ") });
16580
+ return;
16581
+ }
16422
16582
  const started = Date.now();
16423
16583
  try {
16424
- const manifest = generateSnapshot({ cwd: target }, {
16584
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
16425
16585
  ...provenance === void 0 ? {} : { source: provenance },
16426
16586
  ...mode === "slice" ? { slice: { question } } : {},
16427
16587
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -16554,8 +16714,8 @@ async function startWebServer(options) {
16554
16714
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
16555
16715
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
16556
16716
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
16557
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
16558
- var REQUEST_TIMEOUT_MS = 1200;
16717
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
16718
+ var REQUEST_TIMEOUT_MS = 2500;
16559
16719
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
16560
16720
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
16561
16721
  const script = normalise(scriptPath);
@@ -16619,7 +16779,7 @@ function shouldCheck(argv, env) {
16619
16779
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
16620
16780
  const args = argv.map((argument) => argument.toLowerCase());
16621
16781
  if (args.includes("--no-update-check")) return false;
16622
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
16782
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
16623
16783
  if (args.includes(skip)) return false;
16624
16784
  }
16625
16785
  let format = null;
@@ -16715,13 +16875,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
16715
16875
  });
16716
16876
  }
16717
16877
  async function checkForUpdate(options) {
16878
+ const latest = await resolveLatest(options);
16879
+ if (!latest) return null;
16880
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16881
+ }
16882
+ async function resolveLatest(options) {
16718
16883
  if (options.enabled === false) return null;
16719
16884
  const now = options.now ?? (() => Date.now());
16720
16885
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
16886
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
16721
16887
  let latest = null;
16722
16888
  try {
16723
16889
  const cached = readCache(options.cacheFile);
16724
- let needsFetch = cached === null;
16890
+ let needsFetch = cached === null || options.force === true;
16725
16891
  if (cached) {
16726
16892
  const age = now() - cached.checkedAt;
16727
16893
  if (cached.latest === null) {
@@ -16733,15 +16899,14 @@ async function checkForUpdate(options) {
16733
16899
  }
16734
16900
  }
16735
16901
  if (needsFetch) {
16736
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
16902
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
16737
16903
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
16738
- latest = fetched;
16904
+ latest = fetched ?? latest;
16739
16905
  }
16740
16906
  } catch {
16741
16907
  return null;
16742
16908
  }
16743
- if (!latest) return null;
16744
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16909
+ return latest;
16745
16910
  }
16746
16911
  function formatUpdateNotice(notice, kind) {
16747
16912
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -18603,7 +18768,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
18603
18768
  };
18604
18769
  }
18605
18770
  function sha256Hex2(input) {
18606
- return crypto4.createHash("sha256").update(input).digest("hex");
18771
+ return crypto3.createHash("sha256").update(input).digest("hex");
18607
18772
  }
18608
18773
  var TS_EXTENSIONS = [
18609
18774
  ".ts",
@@ -19353,7 +19518,7 @@ function acquireRunLock(stagingRoot) {
19353
19518
  pid: process.pid,
19354
19519
  stagingRoot,
19355
19520
  host: os2.hostname(),
19356
- runId: crypto4.randomUUID(),
19521
+ runId: crypto3.randomUUID(),
19357
19522
  heartbeatMs: LOCK_HEARTBEAT_MS,
19358
19523
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
19359
19524
  })}
@@ -20042,6 +20207,11 @@ function generateSnapshot(configInput, options) {
20042
20207
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
20043
20208
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
20044
20209
  };
20210
+ if (plan.files.length === 0) {
20211
+ warnings.push(
20212
+ "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.")
20213
+ );
20214
+ }
20045
20215
  }
20046
20216
  let budgetBlock;
20047
20217
  if (options?.budgetTokens !== void 0) {
@@ -20133,6 +20303,11 @@ function generateSnapshot(configInput, options) {
20133
20303
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
20134
20304
  }
20135
20305
  }
20306
+ if (config.include.length > 0 && files.length === 0) {
20307
+ warnings.push(
20308
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20309
+ );
20310
+ }
20136
20311
  if (changedScope !== null || options?.deltaBase !== void 0) {
20137
20312
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
20138
20313
  for (const relativePath of unchangedPaths) {
@@ -20271,6 +20446,12 @@ function generateSnapshot(configInput, options) {
20271
20446
  maxMonolithBytes: config.maxMonolithBytes ?? null,
20272
20447
  includeSensitiveFiles: config.includeSensitiveFiles,
20273
20448
  ...config.stripComments === true ? { stripComments: true } : {},
20449
+ // The other three settings the digest covers and the manifest did not record: without them a
20450
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20451
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20452
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20453
+ ...config.pack === null ? {} : { pack: config.pack },
20454
+ logCount: config.logCount,
20274
20455
  // The destination the instructions were written for. Not part of `digest`: the payload is
20275
20456
  // identical whatever this says, and a new delivery preference must not make an existing
20276
20457
  // snapshot fail `validate` as configuration drift.
@@ -20414,6 +20595,18 @@ function generateSnapshot(configInput, options) {
20414
20595
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20415
20596
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20416
20597
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20598
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20599
+ manifest.warnings.push(
20600
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20601
+ );
20602
+ manifest.totals.warningCount = manifest.warnings.length;
20603
+ }
20604
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20605
+ manifest.warnings.push(
20606
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20607
+ );
20608
+ manifest.totals.warningCount = manifest.warnings.length;
20609
+ }
20417
20610
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20418
20611
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20419
20612
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20463,17 +20656,19 @@ function generateSnapshot(configInput, options) {
20463
20656
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20464
20657
  }
20465
20658
  const markdown = definitelyTooLarge || !wantsMarkdown ? null : generateMonolithMarkdown(manifest, fullFiles);
20466
- const markdownBytes = markdown === null ? 0 : Buffer.byteLength(markdown, "utf8");
20467
- if (markdown !== null && (!config.maxMonolithBytes || markdownBytes <= config.maxMonolithBytes)) {
20468
- monolithMarkdown = markdown;
20469
- manifest.artifacts.fullMarkdown = {
20470
- byteSize: markdownBytes,
20471
- sha256: sha256Hex2(markdown)
20472
- };
20473
- } else if (!definitelyTooLarge) {
20474
- manifest.warnings.push(
20475
- `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20476
- );
20659
+ if (markdown !== null) {
20660
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20661
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20662
+ monolithMarkdown = markdown;
20663
+ manifest.artifacts.fullMarkdown = {
20664
+ byteSize: markdownBytes,
20665
+ sha256: sha256Hex2(markdown)
20666
+ };
20667
+ } else {
20668
+ manifest.warnings.push(
20669
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20670
+ );
20671
+ }
20477
20672
  }
20478
20673
  if (wantsXml && !definitelyTooLarge) {
20479
20674
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20489,14 +20684,16 @@ function generateSnapshot(configInput, options) {
20489
20684
  }
20490
20685
  manifest.totals.warningCount = manifest.warnings.length;
20491
20686
  const json = definitelyTooLarge || !wantsJson ? null : generateMonolithJson(manifest, fullFiles);
20492
- const jsonBytes = json === null ? 0 : Buffer.byteLength(json, "utf8");
20493
- if (json !== null && (!config.maxMonolithBytes || jsonBytes <= config.maxMonolithBytes)) {
20494
- monolithJson = json;
20495
- manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20496
- } else if (!definitelyTooLarge) {
20497
- manifest.warnings.push(
20498
- `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20499
- );
20687
+ if (json !== null) {
20688
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20689
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20690
+ monolithJson = json;
20691
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20692
+ } else {
20693
+ manifest.warnings.push(
20694
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20695
+ );
20696
+ }
20500
20697
  }
20501
20698
  manifest.totals.warningCount = manifest.warnings.length;
20502
20699
  }
@@ -20525,7 +20722,7 @@ function generateSnapshot(configInput, options) {
20525
20722
  ensureParentDirectory(outDir, "outDir");
20526
20723
  fs24.mkdirSync(tmpDir, { recursive: true });
20527
20724
  cleanStaleRunDirs(tmpDir);
20528
- const snapshotId = crypto4.randomUUID();
20725
+ const snapshotId = crypto3.randomUUID();
20529
20726
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
20530
20727
  stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
20531
20728
  fs24.mkdirSync(stagingDir);
@@ -20692,4 +20889,4 @@ async function generateSnapshotAsync(configInput, options) {
20692
20889
  return manifest;
20693
20890
  }
20694
20891
 
20695
- export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, COMMAND_OPTION_SCOPE, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, ERROR_CODES, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, LEGACY_PROTOCOL_VERSIONS, MAX_LINE_BYTES, METHOD3 as METHOD, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, MODERN_PROTOCOL_VERSIONS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, SERVER_INSTRUCTIONS, SKILL_NAME, SUPPORTED_PROTOCOL_VERSIONS, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertUsableConfigInput, auditSnapshot, buildAgentContract, buildImportResolver, buildPrompts, buildResourceProvider, buildTools, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, classifyRequest, cloneRepository, coerceNumericStrings, collectFiles, commandsForOption, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, crc32, createLineReader, createMcpServer, createServer, createSession, createWriter, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, findSection, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, inspectModernMeta, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isCommentStrippable, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, loadSigningKey, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, negotiateLegacyVersion, normalizeResolvedConfig, parseByteSize, parsePartSections, parseRemoteSource, partitionFiles, planFirstRun, profileForPath, renderConfig, renderContractText, renderDiffText, renderExplainText, renderSkill, renumberParts, resolveChangedScope, resolveConfig, resolveSafeOutputDirs, resolveSpecifier, runInit, runStdioServer, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, signManifest, skeletonizeTypeScript, startWebServer, stripComments2 as stripComments, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateArguments, validateSnapshot, walkFiles, windowText, workerEntry, wrapLines, writeSignature, writeZip };
20892
+ export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, COMMAND_OPTION_SCOPE, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_SECRET_PATTERNS, ERROR_CODES, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, LEGACY_PROTOCOL_VERSIONS, MAX_LINE_BYTES, METHOD3 as METHOD, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, MODERN_PROTOCOL_VERSIONS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REPORT_RESOURCE_URIS, REQUEST_TIMEOUT_MS, RESOURCE_TEMPLATE_URIS, SCHEMA_VERSION, SERVER_INSTRUCTIONS, SKILL_NAME, STATIC_RESOURCE_URIS, SUPPORTED_PROTOCOL_VERSIONS, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertUsableConfigInput, auditSnapshot, buildAgentContract, buildImportResolver, buildPrompts, buildResourceProvider, buildTools, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, classifyRequest, cloneRepository, coerceNumericStrings, collectFiles, commandsForOption, compareManifests, configDigest, countInvalidUtf8Bytes, countLines, crc32, createLineReader, createMcpServer, createServer, createSession, createWriter, decodeText, defaultIO, defineConfig, describeManifestShapeProblem, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, escapeControls, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findConfigFile, findSecretInPath, findSection, firstRunMessage, formatNumber, formatTokens, formatUpdateNotice, generateInWorker, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, inspectModernMeta, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isCommentStrippable, isDiscoveryMode, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, loadSigningKey, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, negotiateLegacyVersion, normalizeResolvedConfig, parseByteSize, parsePartSections, parseRemoteSource, partitionFiles, planFirstRun, profileForPath, renderConfig, renderContractText, renderDiffText, renderExplainText, renderSkill, renumberParts, resolveChangedScope, resolveConfig, resolveLatest, resolveSafeOutputDirs, resolveSpecifier, runInit, runStdioServer, runWithStdoutCapture, scanAndRedactSecrets, shouldCheck, signManifest, skeletonizeTypeScript, startWebServer, stripComments2 as stripComments, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigPathsFor, unknownPresetMessage, updateCommand, validateArguments, validateSnapshot, walkFiles, windowText, workerEntry, wrapLines, writeSignature, writeZip };