codebase-snapshot 0.22.1 → 0.22.2

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,5 +1,5 @@
1
1
  import * as crypto from 'crypto';
2
- import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'crypto';
2
+ import { createHash, randomBytes, timingSafeEqual, createPublicKey, sign, randomUUID } from 'crypto';
3
3
  import { Worker } from 'worker_threads';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
5
5
  import * as fs29 from 'fs';
@@ -4684,7 +4684,7 @@ function verifySnapshotSignature(snapshotDir) {
4684
4684
 
4685
4685
  // src/version.ts
4686
4686
  var GENERATOR_NAME = "codebase-snapshot";
4687
- var GENERATOR_VERSION = "0.22.1";
4687
+ var GENERATOR_VERSION = "0.22.2";
4688
4688
  var SCHEMA_VERSION = "3.0.0";
4689
4689
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4690
4690
  function isOurGeneratorName(name) {
@@ -14013,6 +14013,54 @@ function resolvePreciseChangedCallers(options) {
14013
14013
  callers
14014
14014
  };
14015
14015
  }
14016
+ var ZERO_WIDTH = /[\u200B-\u200F\u2060-\u2064\uFEFF]/g;
14017
+ var BIDI_CONTROL = /[\u202A-\u202E\u2066-\u2069]/g;
14018
+ var HTML_COMMENT = /<!--([\s\S]*?)-->/g;
14019
+ function looksLikeInstruction(body) {
14020
+ const text2 = body.replace(/\s+/g, " ").trim();
14021
+ if (text2.length === 0) return false;
14022
+ return /\b(ignore|disregard|forget)\b[^.]{0,100}\b(previous|prior|above|earlier)\b/i.test(text2) || /\b(system|developer|assistant)\s*:/i.test(text2) || /\b(print|reveal|show|dump|exfiltrate|send|curl|fetch|read)\b[^.]{0,100}\b(env|secret|token|key|password|credential|\.env)/i.test(text2) || /\bAI (agent|assistant|model)\b/i.test(text2) || /\bdo not (tell|mention|reveal|disclose)\b/i.test(text2) || /\b(you must|you should now|new instructions?)\b/i.test(text2);
14023
+ }
14024
+ function lineAt(text2, index) {
14025
+ let line = 1;
14026
+ for (let i = 0; i < index; i += 1) if (text2.charCodeAt(i) === 10) line += 1;
14027
+ return line;
14028
+ }
14029
+ function maskPreservingLines(match, marker2) {
14030
+ const newlines = match.match(/\n/g)?.length ?? 0;
14031
+ return marker2 + "\n".repeat(newlines);
14032
+ }
14033
+ function hashSpans(spans) {
14034
+ if (spans.length === 0) return null;
14035
+ return createHash("sha256").update(spans.join("\0")).digest("hex");
14036
+ }
14037
+ function scanHiddenText(text2) {
14038
+ const findings = [];
14039
+ const removedSpans = [];
14040
+ let output = text2;
14041
+ output = output.replace(HTML_COMMENT, (match, body, offset) => {
14042
+ if (!looksLikeInstruction(body)) return match;
14043
+ findings.push({ kind: "html-comment", line: lineAt(text2, offset), detail: "hidden instruction comment removed" });
14044
+ removedSpans.push(match);
14045
+ return maskPreservingLines(match, "[REMOVED: hidden instruction comment]");
14046
+ });
14047
+ output = output.replace(ZERO_WIDTH, (match, offset) => {
14048
+ findings.push({ kind: "zero-width", line: lineAt(output, offset), detail: "zero-width character removed" });
14049
+ removedSpans.push(match);
14050
+ return "";
14051
+ });
14052
+ output = output.replace(BIDI_CONTROL, (match, offset) => {
14053
+ findings.push({ kind: "bidi-control", line: lineAt(output, offset), detail: "bidi control removed" });
14054
+ removedSpans.push(match);
14055
+ return "";
14056
+ });
14057
+ return {
14058
+ text: output,
14059
+ findings,
14060
+ removed: findings.length,
14061
+ removedDigest: hashSpans(removedSpans)
14062
+ };
14063
+ }
14016
14064
 
14017
14065
  // src/partitioner/part-format.ts
14018
14066
  var FILE_HEADING = "### FILE: ";
@@ -15427,6 +15475,56 @@ function symbolsOf(entry) {
15427
15475
  }
15428
15476
  return [...new Set(names)].sort((left, right) => left.localeCompare(right));
15429
15477
  }
15478
+ function declarationSpansOf(entry) {
15479
+ const summary = entry.summary;
15480
+ if (!summary || typeof summary !== "object") return [];
15481
+ const spans = summary.declarationSpans;
15482
+ if (!Array.isArray(spans)) return [];
15483
+ return spans.filter((span) => {
15484
+ if (span === null || typeof span !== "object") return false;
15485
+ const candidate = span;
15486
+ return typeof candidate.name === "string" && typeof candidate.startLine === "number" && Number.isInteger(candidate.startLine) && typeof candidate.endLine === "number" && Number.isInteger(candidate.endLine) && candidate.startLine >= 1 && candidate.endLine >= candidate.startLine;
15487
+ });
15488
+ }
15489
+ function symbolSpanOf(entry, symbol) {
15490
+ const wanted = symbol.toLowerCase();
15491
+ const matches = declarationSpansOf(entry).filter((span) => span.name.toLowerCase() === wanted);
15492
+ return matches[0] ?? null;
15493
+ }
15494
+ function identifierTokens(value) {
15495
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2);
15496
+ }
15497
+ function questionSpanOf(entry, question) {
15498
+ const asked = question.toLowerCase();
15499
+ const tokens = new Set(identifierTokens(question));
15500
+ let best = null;
15501
+ let bestScore = 0;
15502
+ for (const span of declarationSpansOf(entry)) {
15503
+ if (span.name.length < 3) continue;
15504
+ const nameTokens = identifierTokens(span.name);
15505
+ if (nameTokens.length < 2) continue;
15506
+ let score = asked.includes(span.name.toLowerCase()) ? 8 : 0;
15507
+ for (const token of nameTokens) if (tokens.has(token)) score += 2;
15508
+ if (score > bestScore) {
15509
+ best = span;
15510
+ bestScore = score;
15511
+ }
15512
+ }
15513
+ return bestScore >= 4 ? best : null;
15514
+ }
15515
+ function clampRange(range, totalLines) {
15516
+ const start = Math.max(1, Math.min(range.startLine, Math.max(1, totalLines)));
15517
+ const end = Math.max(start, Math.min(range.endLine, Math.max(1, totalLines)));
15518
+ if (totalLines > 0 && range.startLine > totalLines) return null;
15519
+ return { startLine: start, endLine: end };
15520
+ }
15521
+ function stableJson(value) {
15522
+ if (value === void 0) return "null";
15523
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
15524
+ if (Array.isArray(value)) return "[" + value.map(stableJson).join(",") + "]";
15525
+ const record = value;
15526
+ return "{" + Object.keys(record).sort().map((key) => JSON.stringify(key) + ":" + stableJson(record[key])).join(",") + "}";
15527
+ }
15430
15528
  async function prepare(args, context, overrides = {}) {
15431
15529
  const rootOutcome = resolveRoot(args.root, context);
15432
15530
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
@@ -15540,9 +15638,9 @@ function bodyFor(workspace, index, entry, cache) {
15540
15638
  }
15541
15639
  return section.body;
15542
15640
  }
15543
- function numberWindow(text2) {
15641
+ function numberWindow(text2, startLine = 1) {
15544
15642
  if (text2.length === 0) return text2;
15545
- return text2.split("\n").map((line, index) => index + 1 + ": " + line).join("\n");
15643
+ return text2.split("\n").map((line, index) => startLine + index + ": " + line).join("\n");
15546
15644
  }
15547
15645
  var impactTool = {
15548
15646
  name: "snapshot_impact",
@@ -15734,10 +15832,28 @@ var contextTool = {
15734
15832
  question: { type: "string", description: "Natural-language question or task." },
15735
15833
  files: { type: "array", items: { type: "string" }, description: "Explicit repository-relative paths." },
15736
15834
  symbols: { type: "array", items: { type: "string" }, description: "Exported or defined symbol names." },
15835
+ ranges: {
15836
+ type: "array",
15837
+ description: "Explicit 1-based line ranges. Each range is honored before the file head or a symbol span.",
15838
+ items: {
15839
+ type: "object",
15840
+ properties: {
15841
+ path: { type: "string", description: "Repository-relative path." },
15842
+ startLine: { type: "integer", minimum: 1 },
15843
+ endLine: { type: "integer", minimum: 1 }
15844
+ },
15845
+ required: ["path", "startLine", "endLine"],
15846
+ additionalProperties: false
15847
+ }
15848
+ },
15737
15849
  maxTokens: { type: "integer", minimum: 500, maximum: 2e5, default: 2e4 },
15738
15850
  linesPerFile: { type: "integer", minimum: 10, maximum: 2e3, default: 80 },
15739
15851
  includeTests: { type: "boolean", description: "Include test files (default false)." },
15740
15852
  planOnly: { type: "boolean", description: "Return the reading plan without file bodies." },
15853
+ signReceipt: {
15854
+ type: "boolean",
15855
+ description: "Sign the context receipt with SNAPSHOT_SIGNING_KEY. Requires a configured key."
15856
+ },
15741
15857
  live: LIVE_PROPERTY,
15742
15858
  root: ROOT_PROPERTY,
15743
15859
  outDir: OUT_DIR_PROPERTY
@@ -15753,6 +15869,8 @@ var contextTool = {
15753
15869
  omitted: { type: "array", items: { type: "object" } },
15754
15870
  skipped: { type: "array", items: { type: "object" } },
15755
15871
  notes: { type: "array", items: { type: "string" } },
15872
+ security: { type: "array", items: { type: "object" } },
15873
+ receipt: { type: "object" },
15756
15874
  trust: { type: "object" }
15757
15875
  }
15758
15876
  },
@@ -15770,8 +15888,8 @@ var contextTool = {
15770
15888
  const question = typeof args.question === "string" ? args.question.trim() : "";
15771
15889
  const wantedFiles = Array.isArray(args.files) ? args.files.filter((item) => typeof item === "string") : [];
15772
15890
  const wantedSymbols = Array.isArray(args.symbols) ? args.symbols.filter((item) => typeof item === "string") : [];
15773
- if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0) {
15774
- return failure("Provide at least one of question, files or symbols.");
15891
+ if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0 && !(Array.isArray(args.ranges) && args.ranges.length > 0)) {
15892
+ return failure("Provide at least one of question, files, symbols or ranges.");
15775
15893
  }
15776
15894
  const budget = Math.min(2e5, Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 2e4));
15777
15895
  const linesPerFile = Math.min(2e3, Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80));
@@ -15780,10 +15898,45 @@ var contextTool = {
15780
15898
  includeTests: args.includeTests === true,
15781
15899
  cwd: workspace.root
15782
15900
  }) : null;
15901
+ const wantedRanges = [];
15902
+ if (args.ranges !== void 0) {
15903
+ if (!Array.isArray(args.ranges)) return failure('"ranges" must be an array.');
15904
+ for (const raw of args.ranges) {
15905
+ if (raw === null || typeof raw !== "object") return failure('"ranges" entries must be objects.');
15906
+ const candidate = raw;
15907
+ if (typeof candidate.path !== "string" || candidate.path.trim().length === 0) {
15908
+ return failure('"ranges[].path" must be a non-empty string.');
15909
+ }
15910
+ if (typeof candidate.startLine !== "number" || !Number.isInteger(candidate.startLine) || candidate.startLine < 1) {
15911
+ return failure('"ranges[].startLine" must be a positive integer.');
15912
+ }
15913
+ if (typeof candidate.endLine !== "number" || !Number.isInteger(candidate.endLine) || candidate.endLine < 1) {
15914
+ return failure('"ranges[].endLine" must be a positive integer.');
15915
+ }
15916
+ if (candidate.endLine < candidate.startLine) {
15917
+ return failure('"ranges[].endLine" must be greater than or equal to startLine.');
15918
+ }
15919
+ wantedRanges.push({ path: candidate.path.trim(), startLine: candidate.startLine, endLine: candidate.endLine });
15920
+ }
15921
+ }
15922
+ if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0 && wantedRanges.length === 0) {
15923
+ return failure("Provide at least one of question, files, symbols or ranges.");
15924
+ }
15925
+ const receiptKey = args.signReceipt === true ? loadSigningKey() : null;
15926
+ if (args.signReceipt === true && receiptKey === null) {
15927
+ return failure("signReceipt requires SNAPSHOT_SIGNING_KEY to contain an Ed25519 private key.");
15928
+ }
15783
15929
  const targets = /* @__PURE__ */ new Map();
15784
15930
  const preOmitted = [];
15785
15931
  if (plan !== null) {
15786
- for (const file of plan.files) targets.set(file.path, file.why);
15932
+ for (const file of plan.files) {
15933
+ const entry = entryFor(index.manifest, file.path);
15934
+ const span = entry === null ? null : questionSpanOf(entry, question);
15935
+ targets.set(file.path, {
15936
+ why: file.why,
15937
+ ...span === null ? {} : { range: { startLine: span.startLine, endLine: span.endLine }, symbol: span.name }
15938
+ });
15939
+ }
15787
15940
  for (const file of plan.skipped) {
15788
15941
  preOmitted.push({ path: file.path, reason: file.reason });
15789
15942
  }
@@ -15798,20 +15951,38 @@ var contextTool = {
15798
15951
  preOmitted.push({ path: relative20, reason: "sensitive-file" });
15799
15952
  continue;
15800
15953
  }
15801
- targets.set(relative20, "requested file");
15954
+ targets.set(relative20, { why: "requested file" });
15802
15955
  }
15803
15956
  for (const symbol of wantedSymbols) {
15804
15957
  const needle = symbol.toLowerCase();
15805
15958
  for (const file of index.manifest.files) {
15806
15959
  if (symbolsOf(file).some((name) => name.toLowerCase() === needle)) {
15807
- if (!targets.has(file.relativePath)) {
15808
- targets.set(file.relativePath, "defines " + symbol);
15809
- }
15960
+ const span = symbolSpanOf(file, symbol);
15961
+ targets.set(file.relativePath, {
15962
+ why: "defines " + symbol,
15963
+ ...span === null ? {} : { range: { startLine: span.startLine, endLine: span.endLine }, symbol: span.name }
15964
+ });
15810
15965
  }
15811
15966
  }
15812
15967
  }
15968
+ for (const wanted of wantedRanges) {
15969
+ const relative20 = toRelativePath(workspace.root, wanted.path);
15970
+ if (relative20 === null) {
15971
+ preOmitted.push({ path: wanted.path, reason: "outside the served repository" });
15972
+ continue;
15973
+ }
15974
+ if (isSensitivePath(relative20)) {
15975
+ preOmitted.push({ path: relative20, reason: "sensitive-file" });
15976
+ continue;
15977
+ }
15978
+ targets.set(relative20, {
15979
+ why: "requested range",
15980
+ range: { startLine: wanted.startLine, endLine: wanted.endLine },
15981
+ explicitRange: true
15982
+ });
15983
+ }
15813
15984
  if (args.planOnly === true) {
15814
- if (plan !== null && wantedFiles.length === 0 && wantedSymbols.length === 0) {
15985
+ if (plan !== null && wantedFiles.length === 0 && wantedSymbols.length === 0 && wantedRanges.length === 0) {
15815
15986
  return {
15816
15987
  text: [
15817
15988
  "Plan for: " + question,
@@ -15825,13 +15996,19 @@ var contextTool = {
15825
15996
  const plannedFiles = [];
15826
15997
  const planSkipped = [...preOmitted];
15827
15998
  let planUsed = 0;
15828
- for (const [relativePath, why] of targets.entries()) {
15999
+ for (const [relativePath, target] of targets.entries()) {
15829
16000
  const entry = entryFor(index.manifest, relativePath);
15830
16001
  if (entry === null) {
15831
16002
  planSkipped.push({ path: relativePath, reason: "not in the index" });
15832
16003
  continue;
15833
16004
  }
15834
- const estimated = Math.max(1, Math.ceil(entry.includedBytes / 4));
16005
+ const range = target.range === void 0 ? null : clampRange(target.range, entry.lines);
16006
+ if (target.range !== void 0 && range === null) {
16007
+ planSkipped.push({ path: target.symbol === void 0 ? relativePath : relativePath + " (" + target.symbol + ")", reason: "range is past the end of the file" });
16008
+ continue;
16009
+ }
16010
+ const lineCount = range === null ? null : range.endLine - range.startLine + 1;
16011
+ const estimated = range === null ? Math.max(1, Math.ceil(entry.includedBytes / 4)) : Math.max(1, Math.ceil(entry.includedBytes * lineCount / Math.max(1, entry.includedLines) / 4));
15835
16012
  if (planUsed + estimated > budget) {
15836
16013
  planSkipped.push({ path: relativePath, reason: "does not fit the remaining budget" });
15837
16014
  continue;
@@ -15843,8 +16020,11 @@ var contextTool = {
15843
16020
  layer: entry.layer,
15844
16021
  kind: entry.kind,
15845
16022
  tokens: estimated,
15846
- mode: "full",
15847
- why
16023
+ mode: range === null ? "full" : "range",
16024
+ fromLine: range === null ? 1 : range.startLine,
16025
+ toLine: range === null ? entry.lines : range.endLine,
16026
+ ...target.symbol === void 0 ? {} : { symbol: target.symbol },
16027
+ why: target.why
15848
16028
  });
15849
16029
  }
15850
16030
  const planNotes = plan === null ? [] : [...plan.notes];
@@ -15852,7 +16032,7 @@ var contextTool = {
15852
16032
  text: [
15853
16033
  "Plan" + (question.length > 0 ? " for: " + question : ""),
15854
16034
  "Budget: " + planUsed + " of " + budget + " tokens; " + plannedFiles.length + " file(s).",
15855
- ...plannedFiles.map((file, position) => position + 1 + ". " + file.path + " (" + file.tokens + " tokens) - " + file.why),
16035
+ ...plannedFiles.map((file, position) => position + 1 + ". " + file.path + " (" + file.tokens + " tokens, lines " + file.fromLine + "\u2013" + file.toLine + ") - " + file.why),
15856
16036
  ...planNotes.map((note) => "- " + note)
15857
16037
  ].join("\n"),
15858
16038
  structured: {
@@ -15867,10 +16047,11 @@ var contextTool = {
15867
16047
  };
15868
16048
  }
15869
16049
  const omitted = [...preOmitted];
16050
+ const security = [];
15870
16051
  const blocks = [];
15871
16052
  const sections = [];
15872
16053
  let used = 0;
15873
- for (const [relativePath, why] of targets.entries()) {
16054
+ for (const [relativePath, target] of targets.entries()) {
15874
16055
  if (used >= budget) {
15875
16056
  omitted.push({ path: relativePath, reason: "budget" });
15876
16057
  continue;
@@ -15880,7 +16061,7 @@ var contextTool = {
15880
16061
  omitted.push({ path: relativePath, reason: "not in the index" });
15881
16062
  continue;
15882
16063
  }
15883
- const body = bodyFor(workspace, index, entry);
16064
+ let body = bodyFor(workspace, index, entry);
15884
16065
  if (body === null) {
15885
16066
  omitted.push({
15886
16067
  path: relativePath,
@@ -15888,18 +16069,36 @@ var contextTool = {
15888
16069
  });
15889
16070
  continue;
15890
16071
  }
15891
- let window = windowText(body, 1, linesPerFile);
15892
- let capped2 = capResultText(numberWindow(window.text));
16072
+ const hidden = scanHiddenText(body);
16073
+ if (hidden.findings.length > 0) {
16074
+ body = hidden.text;
16075
+ for (const finding of hidden.findings) security.push({ path: relativePath, ...finding });
16076
+ }
16077
+ const totalLines = body.length === 0 ? 0 : body.split("\n").length;
16078
+ const range = target.range === void 0 ? null : clampRange(target.range, totalLines);
16079
+ if (target.range !== void 0 && range === null) {
16080
+ omitted.push({ path: relativePath, reason: "range is past the end of the file" });
16081
+ continue;
16082
+ }
16083
+ const startLine = range === null ? 1 : range.startLine;
16084
+ const requestedLines = range === null ? linesPerFile : range.endLine - range.startLine + 1;
16085
+ const lineLimit = target.explicitRange === true ? Math.min(2e3, requestedLines) : Math.min(linesPerFile, requestedLines);
16086
+ let window = windowText(body, startLine, lineLimit);
16087
+ if (window.pastEnd || window.returnedLines === 0) {
16088
+ omitted.push({ path: relativePath, reason: "range is past the end of the file" });
16089
+ continue;
16090
+ }
16091
+ let capped2 = capResultText(numberWindow(window.text, startLine));
15893
16092
  let text2 = capped2.text;
15894
16093
  let tokens = Math.max(1, estimateTokens(text2));
15895
16094
  if (used + tokens > budget) {
15896
- const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
16095
+ const keep = Math.max(4, Math.floor((budget - used) / tokens * window.returnedLines));
15897
16096
  if (keep < 4) {
15898
16097
  omitted.push({ path: relativePath, reason: "budget" });
15899
16098
  continue;
15900
16099
  }
15901
- window = windowText(body, 1, keep);
15902
- capped2 = capResultText(numberWindow(window.text));
16100
+ window = windowText(body, startLine, keep);
16101
+ capped2 = capResultText(numberWindow(window.text, startLine));
15903
16102
  text2 = capped2.text;
15904
16103
  tokens = Math.max(1, estimateTokens(text2));
15905
16104
  if (used + tokens > budget || text2.length === 0) {
@@ -15909,22 +16108,60 @@ var contextTool = {
15909
16108
  }
15910
16109
  const returnedLines = text2.length === 0 ? 0 : text2.split("\n").length;
15911
16110
  const truncated = window.truncated || capped2.clipped;
16111
+ const toLine = startLine + returnedLines - 1;
15912
16112
  sections.push(
15913
- "### " + relativePath + " (" + entry.part + ", lines 1\u2013" + returnedLines + " of " + window.totalLines + (truncated ? "; more remains" : "") + ")"
16113
+ "### " + relativePath + (target.symbol === void 0 ? "" : " \u2014 " + target.symbol) + " (" + entry.part + ", lines " + startLine + "\u2013" + toLine + " of " + window.totalLines + (truncated ? "; more remains" : "") + ")"
15914
16114
  );
15915
16115
  sections.push(text2);
15916
16116
  blocks.push({
15917
16117
  path: relativePath,
15918
16118
  tokens,
15919
- why,
15920
- fromLine: 1,
16119
+ why: target.why,
16120
+ fromLine: startLine,
16121
+ toLine,
15921
16122
  returnedLines,
15922
16123
  totalLines: window.totalLines,
15923
- truncated
16124
+ truncated,
16125
+ ...target.symbol === void 0 ? {} : { symbol: target.symbol },
16126
+ chunkHash: sha256Of(Buffer.from(text2, "utf8"))
15924
16127
  });
15925
16128
  used += tokens;
15926
16129
  }
15927
- const notes = omitted.length === 0 ? [] : ["Not returned: " + omitted.map((entry) => entry.path + " (" + entry.reason + ")").join(", ") + "."];
16130
+ if (security.length > 0) {
16131
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, security.length + " hidden instruction or invisible character(s) removed"])];
16132
+ }
16133
+ const notes = [];
16134
+ if (omitted.length > 0) notes.push("Not returned: " + omitted.map((entry) => entry.path + " (" + entry.reason + ")").join(", ") + ".");
16135
+ if (security.length > 0) notes.push("Security: " + security.length + " hidden item(s) removed.");
16136
+ const receiptChunks = blocks.map((block) => ({
16137
+ path: block.path,
16138
+ fromLine: block.fromLine,
16139
+ toLine: block.toLine,
16140
+ tokens: block.tokens,
16141
+ why: block.why,
16142
+ ...block.symbol === void 0 ? {} : { symbol: block.symbol },
16143
+ sha256: block.chunkHash
16144
+ }));
16145
+ const receiptPayload = {
16146
+ schemaVersion: 1,
16147
+ algorithm: "sha256",
16148
+ chunks: receiptChunks,
16149
+ omitted,
16150
+ security,
16151
+ trust: index.trust
16152
+ };
16153
+ const receiptDigest = sha256Of(Buffer.from(stableJson(receiptPayload), "utf8"));
16154
+ const receipt = { ...receiptPayload, digest: receiptDigest };
16155
+ if (receiptKey !== null) {
16156
+ const payloadBytes = Buffer.from(stableJson(receiptPayload), "utf8");
16157
+ const publicKey = createPublicKey(receiptKey).export({ type: "spki", format: "der" }).toString("base64");
16158
+ receipt.signature = {
16159
+ algorithm: "ed25519",
16160
+ publicKey,
16161
+ value: sign(null, payloadBytes, receiptKey).toString("base64")
16162
+ };
16163
+ }
16164
+ if (receiptChunks.length > 0) notes.push("Receipt: sha256 " + receiptDigest.slice(0, 16) + "\u2026");
15928
16165
  const response = capResponseText([sections.join("\n\n"), ...notes].filter((part) => part.length > 0).join("\n\n"));
15929
16166
  return {
15930
16167
  text: response.text,
@@ -15933,6 +16170,8 @@ var contextTool = {
15933
16170
  usedTokens: used,
15934
16171
  files: blocks,
15935
16172
  omitted,
16173
+ security,
16174
+ receipt,
15936
16175
  ...response.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {},
15937
16176
  trust: index.trust
15938
16177
  }
@@ -15966,7 +16205,11 @@ var locateTool = {
15966
16205
  },
15967
16206
  outputSchema: {
15968
16207
  type: "object",
15969
- properties: { total: { type: "integer" }, matches: { type: "array", items: { type: "object" } } }
16208
+ properties: {
16209
+ total: { type: "integer" },
16210
+ matches: { type: "array", items: { type: "object" } },
16211
+ security: { type: "array", items: { type: "object" } }
16212
+ }
15970
16213
  },
15971
16214
  annotations: READ_ONLY,
15972
16215
  async handler(args, context) {
@@ -16073,6 +16316,7 @@ var locateTool = {
16073
16316
  }
16074
16317
  const shouldText = by === "text" || by === "auto" && matches.length === 0 && rawQuery.length >= 3;
16075
16318
  let textCapReason = null;
16319
+ const security = [];
16076
16320
  if (shouldText) {
16077
16321
  let scanned = 0;
16078
16322
  for (const entry of index.manifest.files) {
@@ -16093,6 +16337,13 @@ var locateTool = {
16093
16337
  if (!(pattern === null ? line.toLowerCase().includes(needle) : pattern.test(line))) continue;
16094
16338
  const from = Math.max(0, lineIndex - contextLines);
16095
16339
  const to = Math.min(lines2.length, lineIndex + contextLines + 1);
16340
+ const excerpt = scanHiddenText(lines2.slice(from, to).join("\n").trim());
16341
+ if (excerpt.findings.length > 0) {
16342
+ for (const finding of excerpt.findings) {
16343
+ security.push({ path: entry.relativePath, ...finding, line: lineIndex + 1 });
16344
+ }
16345
+ }
16346
+ if (excerpt.text.trim().length === 0) continue;
16096
16347
  textMatches.push({
16097
16348
  path: entry.relativePath,
16098
16349
  layer: entry.layer,
@@ -16100,7 +16351,7 @@ var locateTool = {
16100
16351
  part: entry.part,
16101
16352
  matchedBy: "text",
16102
16353
  line: lineIndex + 1,
16103
- text: lines2.slice(from, to).join("\n").trim().slice(0, 500)
16354
+ text: excerpt.text.slice(0, 500)
16104
16355
  });
16105
16356
  if (textMatches.length >= limit) break;
16106
16357
  }
@@ -16172,6 +16423,7 @@ var locateTool = {
16172
16423
  structured: {
16173
16424
  total: matches.length + textMatches.length,
16174
16425
  matches: combined,
16426
+ ...security.length === 0 ? {} : { security },
16175
16427
  ...references.length === 0 ? {} : { references },
16176
16428
  trust: index.trust
16177
16429
  }
@@ -16181,7 +16433,7 @@ var locateTool = {
16181
16433
  var readTool = {
16182
16434
  name: "snapshot_read",
16183
16435
  title: "Read a redacted line window",
16184
- description: "Return lines from one redacted file, served by the live index when available. Sensitive paths are never readable, and one response is capped at 64 KiB. Read-only.",
16436
+ description: "Return lines from one redacted file, served by the live index when available. Sensitive paths are never readable, hidden instructions are removed, and one response is capped at 64 KiB. Read-only.",
16185
16437
  inputSchema: {
16186
16438
  type: "object",
16187
16439
  properties: {
@@ -16204,6 +16456,7 @@ var readTool = {
16204
16456
  returnedLines: { type: "integer" },
16205
16457
  totalLines: { type: "integer" },
16206
16458
  pageable: { type: "boolean" },
16459
+ security: { type: "array", items: { type: "object" } },
16207
16460
  trust: { type: "object" }
16208
16461
  }
16209
16462
  },
@@ -16243,10 +16496,17 @@ var readTool = {
16243
16496
  if (partTooLargeFor(workspace, entry)) {
16244
16497
  return failure(entry.part + " is larger than the " + MAX_PART_READ_BYTES + "-byte read cap; narrow the snapshot or use snapshot_locate.");
16245
16498
  }
16246
- const body = bodyFor(workspace, index, entry);
16499
+ let body = bodyFor(workspace, index, entry);
16247
16500
  if (body === null) {
16248
16501
  return failure(relativePath + " is recorded in " + entry.part + " but its body could not be read. Run snapshot_generate.");
16249
16502
  }
16503
+ const security = [];
16504
+ const hidden = scanHiddenText(body);
16505
+ if (hidden.findings.length > 0) {
16506
+ body = hidden.text;
16507
+ for (const finding of hidden.findings) security.push({ path: entry.relativePath, ...finding });
16508
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, security.length + " hidden instruction or invisible character(s) removed"])];
16509
+ }
16250
16510
  const window = windowText(body, fromLine, lineCount);
16251
16511
  const cappedText = capResultText(window.text, MAX_RESULT_BYTES - 1024);
16252
16512
  const bodyLines = cappedText.text.length === 0 ? 0 : cappedText.text.split("\n").length;
@@ -16276,6 +16536,7 @@ var readTool = {
16276
16536
  ...!clipped && window.truncated ? { nextFromLine: window.fromLine + returnedLines } : {},
16277
16537
  truncated: window.truncated || clipped,
16278
16538
  pageable: !clipped,
16539
+ security,
16279
16540
  trust: index.trust
16280
16541
  }
16281
16542
  };
@@ -18293,8 +18554,11 @@ diff, and the commit, are then yours.
18293
18554
  If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
18294
18555
  as 7 tools over stdio instead of shelling out. Reads are live by default, so uncommitted edits and
18295
18556
  new files are overlaid in memory; the snapshot is not required. Excluded files and redacted values
18296
- never reach the context. Use \`snapshot_impact\` before editing, \`snapshot_locate\` before
18297
- \`snapshot_read\`, and \`snapshot_validate\` before trusting context from an earlier session.
18557
+ never reach the context. \`snapshot_context\` starts an explicit symbol at its declaration span
18558
+ (or a requested range), removes hidden instructions, and returns a receipt that hashes exactly
18559
+ what it returned; pass \`signReceipt: true\` with \`SNAPSHOT_SIGNING_KEY\` set to sign it. Use
18560
+ \`snapshot_impact\` before editing, \`snapshot_locate\` before \`snapshot_read\`, and
18561
+ \`snapshot_validate\` before trusting context from an earlier session.
18298
18562
  `;
18299
18563
  }
18300
18564