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.
@@ -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)) {
@@ -3676,7 +3676,11 @@ function scanAndRedactSecrets(content, rules, filePath) {
3676
3676
  let finalText = segments.join("");
3677
3677
  finalText = redactStructuredValues(finalText, filePath, recordFinding);
3678
3678
  finalText = redactDockerfileEnv(finalText, filePath, recordFinding);
3679
- const findings = [...findingsByLine.entries()].sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
3679
+ const originalLines = content.split(/\r\n|\r|\n/);
3680
+ const findings = [...findingsByLine.entries()].filter(([line]) => {
3681
+ const original = originalLines[line - 1] ?? "";
3682
+ return !original.includes(REDACTION_MARKER) && !original.includes(PEM_REDACTION_MARKER);
3683
+ }).sort(([left], [right]) => left - right).map(([line, rulesForLine]) => ({
3680
3684
  rules: [...rulesForLine],
3681
3685
  line,
3682
3686
  path: filePath
@@ -3744,8 +3748,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3744
3748
  if (body.trim() !== "") {
3745
3749
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
3746
3750
  if (indent <= baseIndent) break;
3751
+ if (!isMarkerLine(body)) masked2 = true;
3747
3752
  segments[cursor2] = maskLineContent(body);
3748
- masked2 = true;
3749
3753
  }
3750
3754
  cursor2 += 2;
3751
3755
  }
@@ -3765,8 +3769,8 @@ function redactStructuredValues(text2, filePath, recordFinding) {
3765
3769
  if (body.trim() !== "") {
3766
3770
  const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
3767
3771
  if (indent < valueIndent) break;
3772
+ if (!isMarkerLine(body)) masked = true;
3768
3773
  segments[cursor] = maskValueLine(body);
3769
- masked = true;
3770
3774
  }
3771
3775
  cursor += 2;
3772
3776
  }
@@ -3876,10 +3880,14 @@ var PLACEHOLDER_PATTERNS = [
3876
3880
  /^your[-_ ].*$/i,
3877
3881
  /^(?:example|sample)(?:[-_ ].*)?$/i
3878
3882
  ];
3883
+ function isMarkerLine(value) {
3884
+ return value.includes(REDACTION_MARKER) || value.includes(PEM_REDACTION_MARKER);
3885
+ }
3879
3886
  function isPlaceholderValue(value) {
3880
3887
  const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
3881
3888
  if (trimmed.length === 0) return false;
3882
3889
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
3890
+ if (trimmed.includes(REDACTION_MARKER) || trimmed.includes(PEM_REDACTION_MARKER)) return true;
3883
3891
  return trimmed.includes("...") || /^<[^>]*$/.test(trimmed);
3884
3892
  }
3885
3893
  function quotesAreBalanced(text2) {
@@ -3994,7 +4002,7 @@ function applySpansKeepingQuotes(line, spans) {
3994
4002
 
3995
4003
  // src/version.ts
3996
4004
  var GENERATOR_NAME = "codebase-snapshot";
3997
- var GENERATOR_VERSION = "0.17.0";
4005
+ var GENERATOR_VERSION = "0.19.0";
3998
4006
  var SCHEMA_VERSION = "3.0.0";
3999
4007
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4000
4008
  function isOurGeneratorName(name) {
@@ -4045,6 +4053,7 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4045
4053
  let branch = fallbackBranch;
4046
4054
  let commit = "unknown";
4047
4055
  let isDirty = false;
4056
+ let branchFromGit = false;
4048
4057
  const records = output.split("\0").flatMap((record) => record.split("\n"));
4049
4058
  for (const record of records) {
4050
4059
  if (record.length === 0) continue;
@@ -4060,13 +4069,14 @@ function getGitInfo(cwd, fallbackBranch = "main") {
4060
4069
  const head = record.match(/^# branch\.head (.+)$/);
4061
4070
  if (head) {
4062
4071
  branch = head[1] === "(detached)" ? fallbackBranch : head[1];
4072
+ branchFromGit = head[1] !== "(detached)";
4063
4073
  }
4064
4074
  }
4065
- return { branch, commit, isDirty };
4075
+ return { branch, commit, isDirty, branchFromGit };
4066
4076
  } catch (err) {
4067
4077
  const code = err.code;
4068
4078
  const isDirty = code === "ENOBUFS";
4069
- return { branch: fallbackBranch, commit: "unknown", isDirty };
4079
+ return { branch: fallbackBranch, commit: "unknown", isDirty, branchFromGit: false };
4070
4080
  }
4071
4081
  }
4072
4082
  var DEFAULT_IGNORED_DIRS = [
@@ -6074,7 +6084,7 @@ function generateAuditReport(manifest, secretFindings, secretRules) {
6074
6084
  "# Codebase Health & Security Audit",
6075
6085
  "",
6076
6086
  `**Generated:** ${manifest.generatedAt} `,
6077
- `**Git Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""}) `,
6087
+ `**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
6088
  `**Total Files:** ${formatNumber(manifest.counts.totalFiles)} `,
6079
6089
  `**Source Lines:** ${formatNumber(manifest.counts.totalLines)} `,
6080
6090
  `**Emitted Lines:** ${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)} `,
@@ -6231,7 +6241,7 @@ var BUILTIN_RULE_IDS = new Map(
6231
6241
  function ruleIdFor(name) {
6232
6242
  const builtin = BUILTIN_RULE_IDS.get(name);
6233
6243
  if (builtin !== void 0) return builtin;
6234
- const digest = crypto4.createHash("sha256").update(name).digest("hex").slice(0, 8);
6244
+ const digest = crypto3.createHash("sha256").update(name).digest("hex").slice(0, 8);
6235
6245
  return `CS${digest.toUpperCase()}`;
6236
6246
  }
6237
6247
  function generateSarifReport(manifest, findings, rules, toolVersion) {
@@ -6569,7 +6579,7 @@ function renumberParts(parts, contentFingerprint) {
6569
6579
  filename: nameFor(index + 1),
6570
6580
  byteSize: Buffer.byteLength(markdown, "utf8"),
6571
6581
  estimatedTokens,
6572
- sha256: crypto4.createHash("sha256").update(markdown).digest("hex"),
6582
+ sha256: crypto3.createHash("sha256").update(markdown).digest("hex"),
6573
6583
  lines: countLines(markdown),
6574
6584
  fileCount: included.length,
6575
6585
  layersCovered: Object.keys(layerCounts).sort()
@@ -6695,7 +6705,7 @@ function rehashPart(part, markdown) {
6695
6705
  metadata: {
6696
6706
  ...part.metadata,
6697
6707
  byteSize: Buffer.byteLength(redistributed, "utf8"),
6698
- sha256: crypto4.createHash("sha256").update(redistributed).digest("hex"),
6708
+ sha256: crypto3.createHash("sha256").update(redistributed).digest("hex"),
6699
6709
  lines: countLines(redistributed),
6700
6710
  estimatedTokens
6701
6711
  }
@@ -6776,7 +6786,7 @@ function renderGroups(groups, contentFingerprint, assemble = (group, index, tota
6776
6786
  return groups.map((group, index) => {
6777
6787
  const { filename, content, estimatedTokens } = assemble(group, index, total);
6778
6788
  const byteSize = Buffer.byteLength(content, "utf8");
6779
- const sha2562 = crypto4.createHash("sha256").update(content).digest("hex");
6789
+ const sha2562 = crypto3.createHash("sha256").update(content).digest("hex");
6780
6790
  const layersCovered = Array.from(new Set(group.sections.map((s) => s.file.layer))).sort();
6781
6791
  const includedFiles = group.sections.map(({ file }) => ({
6782
6792
  relativePath: file.relativePath,
@@ -6858,7 +6868,7 @@ function renderSummary(summary, inclusionMode) {
6858
6868
  }
6859
6869
  function anchorForPath(filePath) {
6860
6870
  const slug = filePath.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
6861
- const digest = crypto4.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6871
+ const digest = crypto3.createHash("sha256").update(filePath).digest("hex").slice(0, 8);
6862
6872
  return `${slug || "file"}-${digest}`;
6863
6873
  }
6864
6874
 
@@ -7205,13 +7215,19 @@ function planForQuestion(manifest, question, options = {}) {
7205
7215
  scored.push({ file, score, why: reasons.slice(0, 3).join(", ") || "centrality " + hub });
7206
7216
  }
7207
7217
  const notes = [];
7218
+ if (manifest.files.length === 0) {
7219
+ notes.push("The snapshot holds no files; there is nothing to plan. Check manifest.skipped for why paths were not emitted.");
7220
+ return { question, budgetTokens: budget, usedTokens: 0, files: [], skipped: [], notes };
7221
+ }
7208
7222
  if (scored.length === 0) {
7209
- notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7210
7223
  const hubs = manifest.indexes.imports.centralFiles.slice(0, 12);
7211
7224
  for (const hub of hubs) {
7212
7225
  const file = byPath.get(hub.path);
7213
7226
  if (file !== void 0) scored.push({ file, score: 1, why: "hub, " + hub.importedByCount + " importers" });
7214
7227
  }
7228
+ if (scored.length > 0) {
7229
+ notes.push("No file matched the question's terms; the plan falls back to the most-imported files.");
7230
+ }
7215
7231
  }
7216
7232
  scored.sort((left, right) => right.score - left.score || left.file.relativePath.localeCompare(right.file.relativePath));
7217
7233
  const chosen = /* @__PURE__ */ new Map();
@@ -7275,7 +7291,14 @@ function planForQuestion(manifest, question, options = {}) {
7275
7291
  }
7276
7292
  }
7277
7293
  }
7278
- if (chosen.size === 0) notes.push("The budget is too small for any file in this snapshot.");
7294
+ if (chosen.size === 0) {
7295
+ if (scored.length === 0) {
7296
+ notes.push("No candidate file matched the question, and this snapshot has no centrality data to fall back on.");
7297
+ } else {
7298
+ const cheapest = scored.reduce((minimum, item) => Math.min(minimum, Math.ceil(item.file.includedBytes / 4)), Infinity);
7299
+ notes.push("Nothing fit the budget: the cheapest candidate costs about " + formatNumber2(cheapest) + " tokens.");
7300
+ }
7301
+ }
7279
7302
  notes.push(
7280
7303
  formatNumber2(chosen.size) + " file(s) chosen of " + formatNumber2(manifest.files.length) + " in the snapshot; " + formatNumber2(skipped.length) + " skipped for budget."
7281
7304
  );
@@ -7890,7 +7913,7 @@ function snapshotSection(manifest, code, partsWritten) {
7890
7913
  const out = ["## This snapshot", ""];
7891
7914
  out.push("- Fingerprint: " + code(manifest.fingerprint) + " - quote it verbatim in your answer.");
7892
7915
  out.push(
7893
- "- Generated: " + code(manifest.generatedAt) + " from branch " + code(manifest.git.branch) + " at commit " + code(manifest.git.commit.slice(0, 8)) + "."
7916
+ "- 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
7917
  );
7895
7918
  out.push(
7896
7919
  manifest.git.isDirty ? " The working tree had uncommitted changes at generation time." : " The working tree was clean at generation time."
@@ -8063,7 +8086,7 @@ function generateReadme(manifest, artifacts) {
8063
8086
  "",
8064
8087
  `- **Generated At:** \`${manifest.generatedAt}\``,
8065
8088
  `- **Schema Version:** \`${manifest.schemaVersion}\``,
8066
- `- **Branch:** ${inlineCode(escapeControls(manifest.git.branch))} (\`${manifest.git.commit.slice(0, 8)}\`${manifest.git.isDirty ? " - dirty" : ""})`,
8089
+ `- **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
8090
  `- **Total Tracked Files:** \`${manifest.counts.totalFiles}\``,
8068
8091
  `- **Source Lines:** \`${formatNumber(manifest.counts.totalLines)}\``,
8069
8092
  `- **Emitted Lines:** \`${formatNumber(manifest.totals.emittedLines ?? manifest.counts.totalLines)}\``,
@@ -8623,6 +8646,71 @@ function detectLanguage(filePath) {
8623
8646
  const ext = path25.posix.extname(base).toLowerCase();
8624
8647
  return LANGUAGE_BY_EXTENSION[ext] ?? "text";
8625
8648
  }
8649
+ var SIGNATURE_FILE = "signature.json";
8650
+ function loadSigningKey(environment = process.env) {
8651
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
8652
+ if (pem === void 0 || pem.trim() === "") return null;
8653
+ return crypto3.createPrivateKey({ key: pem, format: "pem" });
8654
+ }
8655
+ function signManifest(manifestPath, options = {}) {
8656
+ const bytes = fs24.readFileSync(manifestPath);
8657
+ const manifest = JSON.parse(bytes.toString("utf8"));
8658
+ if (typeof manifest.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(manifest.fingerprint)) {
8659
+ throw new Error("refusing to sign: the manifest has no valid fingerprint");
8660
+ }
8661
+ const configured = options.key ?? null;
8662
+ const key = configured ?? crypto3.generateKeyPairSync("ed25519").privateKey;
8663
+ const publicKey = crypto3.createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
8664
+ const signature = crypto3.sign(null, bytes, key).toString("base64");
8665
+ return {
8666
+ algorithm: "ed25519",
8667
+ signedAt: options.signedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
8668
+ fingerprint: manifest.fingerprint,
8669
+ manifestSha256: crypto3.createHash("sha256").update(bytes).digest("hex"),
8670
+ publicKey,
8671
+ signature,
8672
+ keyOrigin: configured === null ? "generated" : "configured"
8673
+ };
8674
+ }
8675
+ function writeSignature(snapshotDir, record) {
8676
+ const target = path25.join(snapshotDir, SIGNATURE_FILE);
8677
+ fs24.writeFileSync(target, JSON.stringify(record, null, 2) + "\n", "utf8");
8678
+ return target;
8679
+ }
8680
+ function verifySnapshotSignature(snapshotDir) {
8681
+ const signaturePath = path25.join(snapshotDir, SIGNATURE_FILE);
8682
+ const manifestPath = path25.join(snapshotDir, "manifest.json");
8683
+ if (!fs24.existsSync(signaturePath)) return { ok: false, reason: "no signature.json in this snapshot" };
8684
+ let record;
8685
+ try {
8686
+ record = JSON.parse(fs24.readFileSync(signaturePath, "utf8"));
8687
+ } catch (error) {
8688
+ return { ok: false, reason: "signature.json is not JSON: " + error.message };
8689
+ }
8690
+ if (record.algorithm !== "ed25519" || typeof record.signature !== "string" || typeof record.publicKey !== "string") {
8691
+ return { ok: false, reason: "signature.json is not an ed25519 record" };
8692
+ }
8693
+ let bytes;
8694
+ try {
8695
+ bytes = fs24.readFileSync(manifestPath);
8696
+ } catch {
8697
+ return { ok: false, reason: "the signed manifest is missing" };
8698
+ }
8699
+ const sha2562 = crypto3.createHash("sha256").update(bytes).digest("hex");
8700
+ if (sha2562 !== record.manifestSha256) {
8701
+ return { ok: false, reason: "manifest.json changed after it was signed" };
8702
+ }
8703
+ let verified = false;
8704
+ try {
8705
+ const key = crypto3.createPublicKey({ key: Buffer.from(record.publicKey, "base64"), format: "der", type: "spki" });
8706
+ verified = crypto3.verify(null, bytes, key, Buffer.from(record.signature, "base64"));
8707
+ } catch (error) {
8708
+ return { ok: false, reason: "the signature could not be checked: " + error.message };
8709
+ }
8710
+ return verified ? { ok: true, record } : { ok: false, reason: "the signature does not match the manifest" };
8711
+ }
8712
+
8713
+ // src/validator/validate.ts
8626
8714
  function maskedPath(value, secretRules) {
8627
8715
  return findSecretInPath(value, secretRules)?.masked ?? value;
8628
8716
  }
@@ -8686,7 +8774,7 @@ function emptyDrift() {
8686
8774
  };
8687
8775
  }
8688
8776
  function sha256Hex(buffer) {
8689
- return crypto4.createHash("sha256").update(buffer).digest("hex");
8777
+ return crypto3.createHash("sha256").update(buffer).digest("hex");
8690
8778
  }
8691
8779
  function wouldNowBeIncluded(cwd, relativePath) {
8692
8780
  const absolutePath = path25.join(cwd, relativePath);
@@ -9623,6 +9711,11 @@ function validateSnapshot(configInput) {
9623
9711
  `${drift.configMismatches.length} configuration mismatch(es) between the manifest and this run.`
9624
9712
  );
9625
9713
  }
9714
+ const signaturePath = path25.join(path25.dirname(manifestPath), "signature.json");
9715
+ if (fs24.existsSync(signaturePath)) {
9716
+ const outcome = verifySnapshotSignature(path25.dirname(manifestPath));
9717
+ if (!outcome.ok) errors.push("signature: " + outcome.reason + ".");
9718
+ }
9626
9719
  if (manifest.slice !== void 0 || manifest.budget !== void 0) {
9627
9720
  warnings.push(
9628
9721
  "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 +10122,6 @@ function negotiateLegacyVersion(requested) {
10029
10122
  }
10030
10123
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
10031
10124
  }
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
10125
 
10096
10126
  // src/partitioner/part-format.ts
10097
10127
  var FILE_HEADING = "### FILE: ";
@@ -10672,8 +10702,9 @@ function auditSnapshot(options) {
10672
10702
  if (typeof member.files === "number" && member.files !== manifest.counts.totalFiles) {
10673
10703
  disagreements.push("file count");
10674
10704
  }
10705
+ 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
10706
  checks.push(
10676
- disagreements.length === 0 ? check(
10707
+ sourceGone !== null ? check("workspace.index", "The workspace index agrees with this member", "warning", "warn", sourceGone) : disagreements.length === 0 ? check(
10677
10708
  "workspace.index",
10678
10709
  "The workspace index agrees with this member",
10679
10710
  "warning",
@@ -10695,12 +10726,45 @@ function auditSnapshot(options) {
10695
10726
  let scannedBytes = 0;
10696
10727
  for (const relative13 of walk(snapshotDir)) {
10697
10728
  if (!TEXT_ARTIFACT.test(relative13) || scannedBytes > scanBudget) continue;
10729
+ if (relative13 === SIGNATURE_FILE) continue;
10698
10730
  const text2 = readText2(path25.join(snapshotDir, relative13));
10699
10731
  if (text2 === null) continue;
10700
10732
  scannedBytes += Buffer.byteLength(text2, "utf8");
10701
- const found = scanAndRedactSecrets(text2, rules, relative13);
10702
- if (found.findings.length > 0) {
10703
- leakHits.push(relative13 + " (" + found.findings.length + " line(s))");
10733
+ let findingCount = 0;
10734
+ if (/^parts[\\/].*\.md$/i.test(relative13)) {
10735
+ let headerText = text2;
10736
+ for (const section of parsePartSections(text2)) {
10737
+ findingCount += scanAndRedactSecrets(section.body, rules, section.path).findings.length;
10738
+ headerText = headerText.replace(section.body, "");
10739
+ }
10740
+ findingCount += scanAndRedactSecrets(headerText, rules, relative13).findings.length;
10741
+ } else {
10742
+ findingCount = scanAndRedactSecrets(text2, rules, relative13).findings.length;
10743
+ }
10744
+ if (findingCount > 0) {
10745
+ leakHits.push(relative13 + " (" + findingCount + " line(s))");
10746
+ }
10747
+ }
10748
+ const signatureRecordPath = path25.join(snapshotDir, SIGNATURE_FILE);
10749
+ if (fs24.existsSync(signatureRecordPath)) {
10750
+ const recordText = readText2(signatureRecordPath);
10751
+ if (recordText !== null) {
10752
+ scannedBytes += Buffer.byteLength(recordText, "utf8");
10753
+ let scanText = recordText;
10754
+ try {
10755
+ const record = JSON.parse(recordText);
10756
+ const rest = { ...record };
10757
+ delete rest.publicKey;
10758
+ delete rest.signature;
10759
+ delete rest.manifestSha256;
10760
+ delete rest.fingerprint;
10761
+ scanText = JSON.stringify(rest, null, 2);
10762
+ } catch {
10763
+ }
10764
+ const found = scanAndRedactSecrets(scanText, rules, SIGNATURE_FILE);
10765
+ if (found.findings.length > 0) {
10766
+ leakHits.push(SIGNATURE_FILE + " (" + found.findings.length + " line(s))");
10767
+ }
10704
10768
  }
10705
10769
  }
10706
10770
  checks.push(
@@ -11436,6 +11500,10 @@ var WRITES = {
11436
11500
  openWorldHint: false
11437
11501
  };
11438
11502
  var MAX_RESULT_BYTES = 64 * 1024;
11503
+ function capResultText(text2) {
11504
+ const clipped = truncateToBytes(text2, MAX_RESULT_BYTES);
11505
+ return { text: clipped.isTruncated ? clipped.content : text2, clipped: clipped.isTruncated };
11506
+ }
11439
11507
  var ROOT_PROPERTY = {
11440
11508
  type: "string",
11441
11509
  description: "Repository root. Defaults to the directory this server was started in."
@@ -11623,6 +11691,17 @@ var historyTool = {
11623
11691
  isError: true
11624
11692
  };
11625
11693
  }
11694
+ const manifestRead = readManifest3(prepared.workspace);
11695
+ const recordedLog = manifestRead.ok ? manifestRead.manifest.artifacts?.log : void 0;
11696
+ if (recordedLog !== void 0 && recordedLog !== null) {
11697
+ const digest = createHash("sha256").update(text2, "utf8").digest("hex");
11698
+ if (digest !== recordedLog.sha256) {
11699
+ return {
11700
+ 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.",
11701
+ isError: true
11702
+ };
11703
+ }
11704
+ }
11626
11705
  const limit = Math.max(1, typeof args.limit === "number" ? args.limit : 20);
11627
11706
  const commits = parseHistoryReport(text2).slice(0, limit);
11628
11707
  return {
@@ -11682,9 +11761,12 @@ var budgetTool = {
11682
11761
  });
11683
11762
  }
11684
11763
  const lines = [question === "" ? "No question: planning for the repository as a whole." : "Question: " + question];
11764
+ if (read.manifest.files.length === 0) {
11765
+ lines.push("The snapshot holds no files, so every budget selects nothing. Check manifest.skipped for why.");
11766
+ }
11685
11767
  for (const row of rows) {
11686
11768
  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" : "") + ")")
11769
+ 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
11770
  );
11689
11771
  }
11690
11772
  return { text: lines.join("\n"), structured: { budgets: rows } };
@@ -11936,7 +12018,7 @@ var routesTool = {
11936
12018
  routes.sort((left, right) => left.path.localeCompare(right.path) || left.route.localeCompare(right.route));
11937
12019
  const text2 = routes.length === 0 ? "No route was recorded. Routes come from decorators, framework attributes and route tables." : [
11938
12020
  routes.length + " route(s):",
11939
- ...routes.map((route) => route.route + " (" + route.path + ", " + route.part + ")")
12021
+ ...routes.map((route) => route.route.trim() + " (" + route.path + ", " + route.part + ")")
11940
12022
  ].join("\n");
11941
12023
  return { text: text2, structured: { total: routes.length, routes } };
11942
12024
  }
@@ -12105,8 +12187,9 @@ var searchTool = {
12105
12187
  }
12106
12188
  }
12107
12189
  }
12190
+ const matchedFiles = new Set(matches.map((match) => match.path)).size;
12108
12191
  const lines = [
12109
- matches.length + " match(es) in " + read.manifest.files.length + " file(s)." + (truncated ? " Results are capped; narrow the query." : ""),
12192
+ 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
12193
  ...skippedOversize.length > 0 ? ["Skipped " + skippedOversize.length + " oversized part(s): " + skippedOversize.slice(0, 5).join(", ")] : [],
12111
12194
  ...matches.map((match) => match.path + ":" + match.line + " (" + match.part + "): " + match.text)
12112
12195
  ];
@@ -12129,7 +12212,9 @@ var statsTool = {
12129
12212
  parts: { type: "integer" },
12130
12213
  tokens: { type: "integer" },
12131
12214
  layers: { type: "object" },
12132
- kinds: { type: "object" }
12215
+ kinds: { type: "object" },
12216
+ heaviest: { type: "array", items: { type: "object" } },
12217
+ partSizes: { type: "array", items: { type: "object" } }
12133
12218
  }
12134
12219
  },
12135
12220
  annotations: READ_ONLY,
@@ -12140,7 +12225,11 @@ var statsTool = {
12140
12225
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12141
12226
  const manifest = read.manifest;
12142
12227
  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 }));
12228
+ const parts = manifest.parts.map((part) => ({
12229
+ filename: part.filename,
12230
+ bytes: part.byteSize,
12231
+ tokens: part.estimatedTokens
12232
+ }));
12144
12233
  const lines = [
12145
12234
  manifest.counts.totalFiles + " file(s) in " + manifest.counts.partsCount + " part(s), " + (manifest.totals.estimatedTokens ?? 0) + " estimated tokens.",
12146
12235
  "Layers: " + Object.entries(manifest.layers).map(([name, count]) => name + "=" + count).join(", "),
@@ -12196,7 +12285,7 @@ var reviewTool = {
12196
12285
  if (!read.ok) return { text: read.message + " Call snapshot_generate first.", isError: true };
12197
12286
  let validation;
12198
12287
  try {
12199
- validation = validateSnapshot(workspace.config);
12288
+ validation = validateSnapshot(configAsGenerated(workspace, read.manifest));
12200
12289
  } catch (error) {
12201
12290
  return { text: error.message, isError: true };
12202
12291
  }
@@ -12296,24 +12385,17 @@ var diffContextTool = {
12296
12385
  const budget = Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 15e3);
12297
12386
  const linesPerFile = Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80);
12298
12387
  const byPath = new Map(read.manifest.files.map((file) => [file.relativePath.toLowerCase(), file]));
12388
+ const resolver = buildImportResolver(read.manifest.files, {
12389
+ tsconfig: tsconfigPathsFor(workspace.root)
12390
+ });
12299
12391
  const importers = /* @__PURE__ */ new Map();
12300
12392
  for (const entry of read.manifest.indexes.imports.byFile) {
12301
12393
  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) ?? [];
12394
+ const target = resolveSpecifier(entry.path, specifier, resolver);
12395
+ if (target === null) continue;
12396
+ const list2 = importers.get(target) ?? [];
12315
12397
  list2.push(entry.path);
12316
- importers.set(target.relativePath, list2);
12398
+ importers.set(target, list2);
12317
12399
  }
12318
12400
  }
12319
12401
  const missing = [];
@@ -12348,9 +12430,12 @@ var diffContextTool = {
12348
12430
  continue;
12349
12431
  }
12350
12432
  used += tokens;
12433
+ const capped2 = capResultText(window.text);
12351
12434
  changed.push({ path: file.relativePath, part: file.part, tokens });
12352
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12353
- text2.push(window.text);
12435
+ text2.push(
12436
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12437
+ );
12438
+ text2.push(capped2.text);
12354
12439
  }
12355
12440
  const dependents = [];
12356
12441
  for (const entry of changed) {
@@ -12432,11 +12517,13 @@ var symbolTool = {
12432
12517
  if (index === -1) continue;
12433
12518
  const from = Math.max(0, index - 3);
12434
12519
  const to = Math.min(lines.length, index + windowSize);
12520
+ const capped2 = capResultText(lines.slice(from, to).join("\n"));
12435
12521
  matches.push({
12436
12522
  path: file.relativePath,
12437
12523
  part: file.part,
12438
12524
  line: index + 1,
12439
- text: lines.slice(from, to).join("\n")
12525
+ text: capped2.text,
12526
+ ...capped2.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12440
12527
  });
12441
12528
  }
12442
12529
  if (matches.length === 0) {
@@ -12567,7 +12654,8 @@ var contextTool = {
12567
12654
  continue;
12568
12655
  }
12569
12656
  const window = windowText(section.body, 1, linesPerFile);
12570
- const body = window.text;
12657
+ const capped2 = capResultText(window.text);
12658
+ const body = capped2.text;
12571
12659
  let tokens = Math.max(1, Math.ceil(Buffer.byteLength(body, "utf8") / 4));
12572
12660
  if (used + tokens > budget) {
12573
12661
  const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
@@ -12576,14 +12664,19 @@ var contextTool = {
12576
12664
  missing.push(file.relativePath + " (budget)");
12577
12665
  continue;
12578
12666
  }
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);
12667
+ const smallerCapped = capResultText(smaller.text);
12668
+ const partial = Math.max(1, Math.ceil(Buffer.byteLength(smallerCapped.text, "utf8") / 4));
12669
+ text2.push(
12670
+ "### " + file.relativePath + " (" + file.part + ", first " + Math.max(4, keep) + " lines" + (smallerCapped.clipped ? ", first 64 KiB" : "") + ")"
12671
+ );
12672
+ text2.push(smallerCapped.text);
12582
12673
  blocks.push({ path: file.relativePath, part: file.part, lines: Math.max(4, keep), tokens: partial });
12583
12674
  used += partial;
12584
12675
  continue;
12585
12676
  }
12586
- text2.push("### " + file.relativePath + " (" + file.part + ")");
12677
+ text2.push(
12678
+ "### " + file.relativePath + " (" + file.part + (capped2.clipped ? ", first 64 KiB" : "") + ")"
12679
+ );
12587
12680
  text2.push(body);
12588
12681
  blocks.push({ path: file.relativePath, part: file.part, lines: window.text === "" ? 0 : window.text.split("\n").length, tokens });
12589
12682
  used += tokens;
@@ -12757,8 +12850,17 @@ var answerTool = {
12757
12850
  maxTokens,
12758
12851
  ...args.includeTests === true ? { includeTests: true } : {}
12759
12852
  });
12853
+ if (read.manifest.files.length === 0) {
12854
+ return {
12855
+ 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).",
12856
+ structured: { question, budgetTokens: maxTokens, usedTokens: 0, files: [], omitted: [] }
12857
+ };
12858
+ }
12760
12859
  const blocks = [];
12761
- const omitted = [];
12860
+ const omitted = plan.skipped.map((entry) => ({
12861
+ path: entry.path,
12862
+ reason: entry.reason
12863
+ }));
12762
12864
  let used = 0;
12763
12865
  const parts = /* @__PURE__ */ new Map();
12764
12866
  for (const planned of plan.files) {
@@ -12787,14 +12889,23 @@ var answerTool = {
12787
12889
  continue;
12788
12890
  }
12789
12891
  const window = windowText(section.body, 1, linesPerFile);
12790
- const text2 = window.text;
12791
- const tokens = estimateTokens(text2);
12892
+ const numbered = window.text.split("\n").map((line, index) => String(index + 1).padStart(5, " ") + " " + line).join("\n");
12893
+ const clipped = truncateToBytes(numbered, MAX_RESULT_BYTES);
12894
+ const bodyText = clipped.isTruncated ? clipped.content : numbered;
12895
+ const tokens = estimateTokens(bodyText);
12792
12896
  if (used + tokens > maxTokens && blocks.length > 0) {
12793
12897
  omitted.push({ path: planned.path, reason: "did not fit the remaining budget" });
12794
12898
  continue;
12795
12899
  }
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 });
12900
+ blocks.push({
12901
+ path: planned.path,
12902
+ why: planned.why,
12903
+ tokens,
12904
+ text: bodyText,
12905
+ truncated: window.truncated || clipped.isTruncated,
12906
+ totalLines: window.totalLines,
12907
+ ...clipped.isTruncated ? { clippedAtBytes: MAX_RESULT_BYTES } : {}
12908
+ });
12798
12909
  used += tokens;
12799
12910
  }
12800
12911
  const lines = [
@@ -12803,7 +12914,9 @@ var answerTool = {
12803
12914
  ];
12804
12915
  for (const block of blocks) {
12805
12916
  lines.push("");
12806
- lines.push("## " + block.path + " (" + block.tokens + " tokens, " + (block.truncated ? "first lines of " + block.totalLines : "whole file") + ")");
12917
+ lines.push(
12918
+ "## " + 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") + ")"
12919
+ );
12807
12920
  lines.push("Why: " + block.why);
12808
12921
  lines.push("```");
12809
12922
  lines.push(block.text);
@@ -12814,6 +12927,11 @@ var answerTool = {
12814
12927
  lines.push("Not included:");
12815
12928
  for (const entry of omitted) lines.push("- " + entry.path + " - " + entry.reason);
12816
12929
  }
12930
+ if (plan.notes.length > 0) {
12931
+ lines.push("");
12932
+ lines.push("Notes:");
12933
+ for (const note of plan.notes) lines.push("- " + note);
12934
+ }
12817
12935
  return {
12818
12936
  text: lines.join("\n"),
12819
12937
  structured: { question, budgetTokens: maxTokens, usedTokens: used, files: blocks, omitted }
@@ -12928,7 +13046,7 @@ var statusTool = {
12928
13046
  `Files: ${manifest.counts.totalFiles} included, ${manifest.counts.skippedCount} skipped, ${plural(manifest.counts.partsCount, "part")}`,
12929
13047
  `Content: ${formatBytes2(manifest.counts.totalSizeBytes)} of source in ${formatBytes2(manifest.totals.totalContentBytes)} emitted`,
12930
13048
  `Fingerprint: ${manifest.fingerprint}`,
12931
- `Git: ${manifest.git.branch} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
13049
+ `Git: ${manifest.git.branch}${manifest.git.branchFromGit === false ? " (fallback; no git branch)" : ""} @ ${manifest.git.commit}${manifest.git.isDirty ? " (dirty)" : " (clean)"}`
12932
13050
  ];
12933
13051
  if (manifest.totals.warningCount > 0) lines.push(`Warnings: ${manifest.totals.warningCount}`);
12934
13052
  if (!versionMatches) {
@@ -13079,6 +13197,16 @@ var generateTool = {
13079
13197
  minimum: 500,
13080
13198
  description: "Fit the snapshot into this token budget, highest value first."
13081
13199
  },
13200
+ only: {
13201
+ type: "array",
13202
+ items: { type: "string" },
13203
+ description: "Globs to include: replaces the config allow-list for this run."
13204
+ },
13205
+ ignore: {
13206
+ type: "array",
13207
+ items: { type: "string" },
13208
+ description: "Globs to exclude, added to the config deny-list for this run."
13209
+ },
13082
13210
  ...SCOPE_PROPERTIES
13083
13211
  },
13084
13212
  additionalProperties: false
@@ -13107,7 +13235,9 @@ var generateTool = {
13107
13235
  ...args.tokenTree === true ? { tokenTree: true } : {},
13108
13236
  ...args.stripComments === true ? { stripComments: true } : {},
13109
13237
  ...args.removeEmptyLines === true ? { removeEmptyLines: true } : {},
13110
- ...typeof args.pack === "string" ? { pack: args.pack } : {}
13238
+ ...typeof args.pack === "string" ? { pack: args.pack } : {},
13239
+ ...Array.isArray(args.only) ? { only: args.only.filter((value) => typeof value === "string") } : {},
13240
+ ...Array.isArray(args.ignore) ? { ignore: args.ignore.filter((value) => typeof value === "string") } : {}
13111
13241
  };
13112
13242
  if (typeof args.slice === "string" && typeof args.budgetTokens === "number") {
13113
13243
  return failure("slice and budgetTokens both narrow the selection; pass one.");
@@ -13151,6 +13281,20 @@ var generateTool = {
13151
13281
  };
13152
13282
  }
13153
13283
  };
13284
+ function configAsGenerated(workspace, manifest) {
13285
+ const recorded = manifest.config;
13286
+ return {
13287
+ ...workspace.config,
13288
+ ...recorded?.artifacts === void 0 ? {} : { artifacts: recorded.artifacts },
13289
+ ...recorded?.stripComments === void 0 ? {} : { stripComments: recorded.stripComments },
13290
+ ...recorded?.removeEmptyLines === void 0 ? {} : { removeEmptyLines: recorded.removeEmptyLines },
13291
+ ...recorded?.pack === void 0 ? {} : { pack: recorded.pack },
13292
+ ...recorded?.logCount === void 0 ? {} : { logCount: recorded.logCount },
13293
+ ...recorded?.skeleton === void 0 ? {} : { skeleton: recorded.skeleton },
13294
+ ...recorded?.sarif === void 0 ? {} : { sarif: recorded.sarif },
13295
+ ...recorded?.maxParts === void 0 ? {} : { maxParts: recorded.maxParts }
13296
+ };
13297
+ }
13154
13298
  var validateTool = {
13155
13299
  name: "snapshot_validate",
13156
13300
  title: "Validate the snapshot",
@@ -13172,9 +13316,11 @@ var validateTool = {
13172
13316
  const prepared = await prepare(args, context, workspaceOverrides(args));
13173
13317
  if (!prepared.ok) return prepared.outcome;
13174
13318
  const workspace = prepared.workspace;
13319
+ const read = readManifest3(workspace);
13320
+ if (!read.ok) return failure(read.message);
13175
13321
  let result;
13176
13322
  try {
13177
- result = validateSnapshot(workspace.config);
13323
+ result = validateSnapshot(configAsGenerated(workspace, read.manifest));
13178
13324
  } catch (error) {
13179
13325
  return failure(error instanceof Error ? error.message : String(error));
13180
13326
  }
@@ -13538,6 +13684,12 @@ var readTool = {
13538
13684
  `${relativePath} is recorded in ${entry.part} but its section could not be located there. Run snapshot_generate to rebuild the snapshot.`
13539
13685
  );
13540
13686
  }
13687
+ if (typeof args.fromLine === "number" && (!Number.isInteger(args.fromLine) || args.fromLine < 1)) {
13688
+ return failure('"fromLine" must be an integer of at least 1 (received ' + String(args.fromLine) + ").");
13689
+ }
13690
+ if (typeof args.lines === "number" && (!Number.isInteger(args.lines) || args.lines < 1)) {
13691
+ return failure('"lines" must be an integer of at least 1 (received ' + String(args.lines) + ").");
13692
+ }
13541
13693
  const fromLine = typeof args.fromLine === "number" ? args.fromLine : 1;
13542
13694
  const lineCount = typeof args.lines === "number" ? args.lines : 200;
13543
13695
  const window = windowText(section.body, fromLine, lineCount);
@@ -13987,6 +14139,8 @@ var COMMAND_OPTION_SCOPE = {
13987
14139
  // — the exact "flag that parses but changes nothing" this table exists to prevent — while
13988
14140
  // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
13989
14141
  // list, so removing them narrows the two together.
14142
+ // It asks the registry, not the repository: no cwd, no out-dir, nothing a config could change.
14143
+ update: ["format", "help"],
13990
14144
  report: [
13991
14145
  "cwd",
13992
14146
  "out-dir",
@@ -14348,6 +14502,13 @@ function buildAgentContract() {
14348
14502
  positionals: [],
14349
14503
  exits: [0]
14350
14504
  },
14505
+ {
14506
+ name: "update",
14507
+ aliases: [],
14508
+ 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.",
14509
+ positionals: [],
14510
+ exits: [0, 1, 2]
14511
+ },
14351
14512
  {
14352
14513
  name: "skill",
14353
14514
  aliases: [],
@@ -14643,14 +14804,14 @@ function buildAgentContract() {
14643
14804
  type: "boolean",
14644
14805
  default: false,
14645
14806
  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."
14807
+ 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
14808
  },
14648
14809
  {
14649
14810
  flag: "--include-logs",
14650
14811
  type: "string",
14651
14812
  default: "unset",
14652
14813
  appliesTo: optionAppliesTo("include-logs"),
14653
- summary: "Also write reports/log.md: the last n commits (1-500), one line each, newest first."
14814
+ 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
14815
  },
14655
14816
  {
14656
14817
  flag: "--token-tree",
@@ -15644,6 +15805,18 @@ function createMcpServer(options) {
15644
15805
  if (!isJsonObject(rawArguments)) {
15645
15806
  return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
15646
15807
  }
15808
+ const missing = (prompt.arguments ?? []).filter((argument) => {
15809
+ if (argument.required !== true) return false;
15810
+ const value = rawArguments[argument.name];
15811
+ return typeof value !== "string" || value.trim() === "";
15812
+ });
15813
+ if (missing.length > 0) {
15814
+ return errorResponse(
15815
+ id,
15816
+ ERROR_CODES.invalidParams,
15817
+ 'Prompt "' + name + '" requires the ' + missing.map((argument) => '"' + argument.name + '"').join(", ") + " argument(s): " + missing.map((argument) => argument.description).join(" ")
15818
+ );
15819
+ }
15647
15820
  const built = prompt.build(rawArguments);
15648
15821
  const messages = built.messages.map((message) => ({
15649
15822
  role: message.role,
@@ -16111,20 +16284,20 @@ var SERVE_PAGE = `<!doctype html>
16111
16284
  <header><b>codebase-snapshot</b><span>a snapshot an agent can trust</span></header>
16112
16285
  <main>
16113
16286
  <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">
16287
+ <input id="source" aria-label="repository path or URL" placeholder="/absolute/path/to/repo or https://github.com/owner/repo" spellcheck="false" autofocus>
16288
+ <select id="mode" aria-label="What to generate" title="What to generate">
16116
16289
  <option value="full">whole repository</option>
16117
16290
  <option value="slice">a slice for a question</option>
16118
16291
  <option value="budget">fit a token budget</option>
16119
16292
  </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>
16293
+ <input id="question" aria-label="Question for the slice" placeholder="the question (slice mode)" spellcheck="false" hidden>
16294
+ <input id="budget" type="number" min="500" step="500" value="30000" aria-label="Token budget" title="token budget" hidden>
16122
16295
  <button id="run" type="submit">Generate</button>
16123
16296
  <button id="download" type="button" disabled>Download .zip</button>
16124
16297
  </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>
16298
+ <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
16299
  <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>
16300
+ <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
16301
  </div>
16129
16302
  <div class="row">
16130
16303
  <section><h2>Brief <span id="fingerprint"></span> <span id="health"></span></h2><pre id="brief">No snapshot loaded.</pre></section>
@@ -16419,9 +16592,14 @@ async function startWebServer(options) {
16419
16592
  send(400, { error: "not a directory: " + target });
16420
16593
  return;
16421
16594
  }
16595
+ const loaded = await loadConfigFileDetailed(target, { allowExecutableConfig: false });
16596
+ if (loaded.errors.length > 0) {
16597
+ send(400, { error: loaded.errors.join("; ") });
16598
+ return;
16599
+ }
16422
16600
  const started = Date.now();
16423
16601
  try {
16424
- const manifest = generateSnapshot({ cwd: target }, {
16602
+ const manifest = generateSnapshot({ ...loaded.config ?? {}, cwd: target }, {
16425
16603
  ...provenance === void 0 ? {} : { source: provenance },
16426
16604
  ...mode === "slice" ? { slice: { question } } : {},
16427
16605
  ...mode === "budget" && budgetTokens !== void 0 ? { budgetTokens } : {}
@@ -16554,8 +16732,8 @@ async function startWebServer(options) {
16554
16732
  var PACKAGE_LATEST_URL = "https://registry.npmjs.org/codebase-snapshot/latest";
16555
16733
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
16556
16734
  var UP_TO_DATE_INTERVAL_MS = 60 * 60 * 1e3;
16557
- var FAILURE_INTERVAL_MS = 60 * 60 * 1e3;
16558
- var REQUEST_TIMEOUT_MS = 1200;
16735
+ var FAILURE_INTERVAL_MS = 5 * 60 * 1e3;
16736
+ var REQUEST_TIMEOUT_MS = 2500;
16559
16737
  function installKind(scriptPath = process.argv[1] ?? "", cwd = process.cwd()) {
16560
16738
  const normalise = (value) => value.replace(/\\/g, "/").replace(/\/+$/, "");
16561
16739
  const script = normalise(scriptPath);
@@ -16619,7 +16797,7 @@ function shouldCheck(argv, env) {
16619
16797
  if (env.CI !== void 0 && env.CI !== "" && env.CI !== "false" && env.CI !== "0") return false;
16620
16798
  const args = argv.map((argument) => argument.toLowerCase());
16621
16799
  if (args.includes("--no-update-check")) return false;
16622
- for (const skip of ["mcp", "describe", "skill", "--version", "-v", "--help", "-h"]) {
16800
+ for (const skip of ["mcp", "describe", "skill", "update", "--version", "-v", "--help", "-h"]) {
16623
16801
  if (args.includes(skip)) return false;
16624
16802
  }
16625
16803
  let format = null;
@@ -16715,13 +16893,19 @@ function fetchLatestVersion(url = PACKAGE_LATEST_URL, timeoutMs = REQUEST_TIMEOU
16715
16893
  });
16716
16894
  }
16717
16895
  async function checkForUpdate(options) {
16896
+ const latest = await resolveLatest(options);
16897
+ if (!latest) return null;
16898
+ return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16899
+ }
16900
+ async function resolveLatest(options) {
16718
16901
  if (options.enabled === false) return null;
16719
16902
  const now = options.now ?? (() => Date.now());
16720
16903
  const fetchLatest = options.fetchLatest ?? fetchLatestVersion;
16904
+ const latestUrl = options.latestUrl ?? PACKAGE_LATEST_URL;
16721
16905
  let latest = null;
16722
16906
  try {
16723
16907
  const cached = readCache(options.cacheFile);
16724
- let needsFetch = cached === null;
16908
+ let needsFetch = cached === null || options.force === true;
16725
16909
  if (cached) {
16726
16910
  const age = now() - cached.checkedAt;
16727
16911
  if (cached.latest === null) {
@@ -16733,15 +16917,14 @@ async function checkForUpdate(options) {
16733
16917
  }
16734
16918
  }
16735
16919
  if (needsFetch) {
16736
- const fetched = await fetchLatest(PACKAGE_LATEST_URL, REQUEST_TIMEOUT_MS);
16920
+ const fetched = await fetchLatest(latestUrl, REQUEST_TIMEOUT_MS);
16737
16921
  writeCache(options.cacheFile, { checkedAt: now(), latest: fetched });
16738
- latest = fetched;
16922
+ latest = fetched ?? latest;
16739
16923
  }
16740
16924
  } catch {
16741
16925
  return null;
16742
16926
  }
16743
- if (!latest) return null;
16744
- return isNewer(latest, options.current) ? { current: options.current, latest } : null;
16927
+ return latest;
16745
16928
  }
16746
16929
  function formatUpdateNotice(notice, kind) {
16747
16930
  return `\u2191 codebase-snapshot ${notice.latest} is available \u2014 you have ${notice.current}.
@@ -18603,7 +18786,7 @@ function deriveFile(relativePath, rawContent, sizeBytes, config) {
18603
18786
  };
18604
18787
  }
18605
18788
  function sha256Hex2(input) {
18606
- return crypto4.createHash("sha256").update(input).digest("hex");
18789
+ return crypto3.createHash("sha256").update(input).digest("hex");
18607
18790
  }
18608
18791
  var TS_EXTENSIONS = [
18609
18792
  ".ts",
@@ -19353,7 +19536,7 @@ function acquireRunLock(stagingRoot) {
19353
19536
  pid: process.pid,
19354
19537
  stagingRoot,
19355
19538
  host: os2.hostname(),
19356
- runId: crypto4.randomUUID(),
19539
+ runId: crypto3.randomUUID(),
19357
19540
  heartbeatMs: LOCK_HEARTBEAT_MS,
19358
19541
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
19359
19542
  })}
@@ -20042,6 +20225,11 @@ function generateSnapshot(configInput, options) {
20042
20225
  detail: "Question: " + options.slice.question + "\nBudget: " + plan.budgetTokens.toLocaleString("en-US") + " tokens",
20043
20226
  files: plan.files.map((file) => ({ path: file.path, tokens: file.tokens, why: file.why }))
20044
20227
  };
20228
+ if (plan.files.length === 0) {
20229
+ warnings.push(
20230
+ "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.")
20231
+ );
20232
+ }
20045
20233
  }
20046
20234
  let budgetBlock;
20047
20235
  if (options?.budgetTokens !== void 0) {
@@ -20133,6 +20321,11 @@ function generateSnapshot(configInput, options) {
20133
20321
  warnings.push("No file fits --budget-tokens " + budget + "; the snapshot is empty.");
20134
20322
  }
20135
20323
  }
20324
+ if (config.include.length > 0 && files.length === 0) {
20325
+ warnings.push(
20326
+ "No file matched the include allow-list (" + config.include.length + " pattern(s): " + config.include.join(", ") + "), so the snapshot is empty."
20327
+ );
20328
+ }
20136
20329
  if (changedScope !== null || options?.deltaBase !== void 0) {
20137
20330
  const detail = changedScope !== null ? `not ${changedScope.detail}` : "identical to the base snapshot given with --delta";
20138
20331
  for (const relativePath of unchangedPaths) {
@@ -20271,6 +20464,12 @@ function generateSnapshot(configInput, options) {
20271
20464
  maxMonolithBytes: config.maxMonolithBytes ?? null,
20272
20465
  includeSensitiveFiles: config.includeSensitiveFiles,
20273
20466
  ...config.stripComments === true ? { stripComments: true } : {},
20467
+ // The other three settings the digest covers and the manifest did not record: without them a
20468
+ // validator (or `snapshot_review`) had no way to reconstruct the run, so a snapshot taken
20469
+ // with `--remove-empty-lines`, `--pack` or `--include-logs 3` looked stale forever.
20470
+ ...config.removeEmptyLines === true ? { removeEmptyLines: true } : {},
20471
+ ...config.pack === null ? {} : { pack: config.pack },
20472
+ logCount: config.logCount,
20274
20473
  // The destination the instructions were written for. Not part of `digest`: the payload is
20275
20474
  // identical whatever this says, and a new delivery preference must not make an existing
20276
20475
  // snapshot fail `validate` as configuration drift.
@@ -20414,6 +20613,18 @@ function generateSnapshot(configInput, options) {
20414
20613
  const diffReport = artifacts.diff ? generateDiffReport(config.cwd) : null;
20415
20614
  if (diffReport !== null) manifest.artifacts.diff = artifactRecord(diffReport.text);
20416
20615
  const logReport = artifacts.log ? generateLogReport(config.cwd, { count: config.logCount }) : null;
20616
+ if (artifacts.diff && diffReport === null && !isGitRepository(config.cwd)) {
20617
+ manifest.warnings.push(
20618
+ "--include-diffs was requested, but the generated directory is not a git repository; reports/diff.md was not written."
20619
+ );
20620
+ manifest.totals.warningCount = manifest.warnings.length;
20621
+ }
20622
+ if (artifacts.log && logReport === null && !isGitRepository(config.cwd)) {
20623
+ manifest.warnings.push(
20624
+ "--include-logs was requested, but the generated directory is not a git repository; reports/log.md was not written."
20625
+ );
20626
+ manifest.totals.warningCount = manifest.warnings.length;
20627
+ }
20417
20628
  if (logReport !== null) manifest.artifacts.log = artifactRecord(logReport.text);
20418
20629
  const tokenTree = artifacts.tokenTree ? generateTokenTree(manifest) : null;
20419
20630
  if (tokenTree !== null) manifest.artifacts.tokenTree = artifactRecord(tokenTree.text);
@@ -20463,17 +20674,19 @@ function generateSnapshot(configInput, options) {
20463
20674
  if (wantsXml) manifest.warnings.push(`full-codebase.xml skipped: ${reason}`);
20464
20675
  }
20465
20676
  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
- );
20677
+ if (markdown !== null) {
20678
+ const markdownBytes = Buffer.byteLength(markdown, "utf8");
20679
+ if (config.maxMonolithBytes === null || markdownBytes <= config.maxMonolithBytes) {
20680
+ monolithMarkdown = markdown;
20681
+ manifest.artifacts.fullMarkdown = {
20682
+ byteSize: markdownBytes,
20683
+ sha256: sha256Hex2(markdown)
20684
+ };
20685
+ } else {
20686
+ manifest.warnings.push(
20687
+ `full-codebase.md skipped: ${markdownBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20688
+ );
20689
+ }
20477
20690
  }
20478
20691
  if (wantsXml && !definitelyTooLarge) {
20479
20692
  const xml = generateMonolithXml(manifest, fullFiles);
@@ -20489,14 +20702,16 @@ function generateSnapshot(configInput, options) {
20489
20702
  }
20490
20703
  manifest.totals.warningCount = manifest.warnings.length;
20491
20704
  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
- );
20705
+ if (json !== null) {
20706
+ const jsonBytes = Buffer.byteLength(json, "utf8");
20707
+ if (config.maxMonolithBytes === null || jsonBytes <= config.maxMonolithBytes) {
20708
+ monolithJson = json;
20709
+ manifest.artifacts.fullJson = { byteSize: jsonBytes, sha256: sha256Hex2(json) };
20710
+ } else {
20711
+ manifest.warnings.push(
20712
+ `full-codebase.json skipped: ${jsonBytes} B exceeds maxMonolithBytes ${config.maxMonolithBytes} B`
20713
+ );
20714
+ }
20500
20715
  }
20501
20716
  manifest.totals.warningCount = manifest.warnings.length;
20502
20717
  }
@@ -20525,7 +20740,7 @@ function generateSnapshot(configInput, options) {
20525
20740
  ensureParentDirectory(outDir, "outDir");
20526
20741
  fs24.mkdirSync(tmpDir, { recursive: true });
20527
20742
  cleanStaleRunDirs(tmpDir);
20528
- const snapshotId = crypto4.randomUUID();
20743
+ const snapshotId = crypto3.randomUUID();
20529
20744
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
20530
20745
  stagingDir = path25.join(tmpDir, `${RUN_DIR_PREFIX}${process.pid}-${snapshotId.slice(0, 8)}`);
20531
20746
  fs24.mkdirSync(stagingDir);
@@ -20692,4 +20907,4 @@ async function generateSnapshotAsync(configInput, options) {
20692
20907
  return manifest;
20693
20908
  }
20694
20909
 
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 };
20910
+ 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 };