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.
package/dist/index.cjs CHANGED
@@ -4623,6 +4623,11 @@ function readConfinedText(baseDir, relativePath, maxBytes) {
4623
4623
 
4624
4624
  // src/signing.ts
4625
4625
  var SIGNATURE_FILE = "signature.json";
4626
+ function loadSigningKey(environment = process.env) {
4627
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
4628
+ if (pem === void 0 || pem.trim() === "") return null;
4629
+ return crypto__namespace.createPrivateKey({ key: pem, format: "pem" });
4630
+ }
4626
4631
  function signManifest(manifestPath, options = {}) {
4627
4632
  const bytes = fs29__namespace.readFileSync(manifestPath);
4628
4633
  const manifest = JSON.parse(bytes.toString("utf8"));
@@ -4697,7 +4702,7 @@ function verifySnapshotSignature(snapshotDir) {
4697
4702
 
4698
4703
  // src/version.ts
4699
4704
  var GENERATOR_NAME = "codebase-snapshot";
4700
- var GENERATOR_VERSION = "0.22.1";
4705
+ var GENERATOR_VERSION = "0.22.2";
4701
4706
  var SCHEMA_VERSION = "3.0.0";
4702
4707
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
4703
4708
  function isOurGeneratorName(name) {
@@ -13958,6 +13963,54 @@ function resolvePreciseChangedCallers(options) {
13958
13963
  callers
13959
13964
  };
13960
13965
  }
13966
+ var ZERO_WIDTH = /[\u200B-\u200F\u2060-\u2064\uFEFF]/g;
13967
+ var BIDI_CONTROL = /[\u202A-\u202E\u2066-\u2069]/g;
13968
+ var HTML_COMMENT = /<!--([\s\S]*?)-->/g;
13969
+ function looksLikeInstruction(body) {
13970
+ const text2 = body.replace(/\s+/g, " ").trim();
13971
+ if (text2.length === 0) return false;
13972
+ 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);
13973
+ }
13974
+ function lineAt(text2, index) {
13975
+ let line = 1;
13976
+ for (let i = 0; i < index; i += 1) if (text2.charCodeAt(i) === 10) line += 1;
13977
+ return line;
13978
+ }
13979
+ function maskPreservingLines(match, marker2) {
13980
+ const newlines = match.match(/\n/g)?.length ?? 0;
13981
+ return marker2 + "\n".repeat(newlines);
13982
+ }
13983
+ function hashSpans(spans) {
13984
+ if (spans.length === 0) return null;
13985
+ return crypto.createHash("sha256").update(spans.join("\0")).digest("hex");
13986
+ }
13987
+ function scanHiddenText(text2) {
13988
+ const findings = [];
13989
+ const removedSpans = [];
13990
+ let output = text2;
13991
+ output = output.replace(HTML_COMMENT, (match, body, offset) => {
13992
+ if (!looksLikeInstruction(body)) return match;
13993
+ findings.push({ kind: "html-comment", line: lineAt(text2, offset), detail: "hidden instruction comment removed" });
13994
+ removedSpans.push(match);
13995
+ return maskPreservingLines(match, "[REMOVED: hidden instruction comment]");
13996
+ });
13997
+ output = output.replace(ZERO_WIDTH, (match, offset) => {
13998
+ findings.push({ kind: "zero-width", line: lineAt(output, offset), detail: "zero-width character removed" });
13999
+ removedSpans.push(match);
14000
+ return "";
14001
+ });
14002
+ output = output.replace(BIDI_CONTROL, (match, offset) => {
14003
+ findings.push({ kind: "bidi-control", line: lineAt(output, offset), detail: "bidi control removed" });
14004
+ removedSpans.push(match);
14005
+ return "";
14006
+ });
14007
+ return {
14008
+ text: output,
14009
+ findings,
14010
+ removed: findings.length,
14011
+ removedDigest: hashSpans(removedSpans)
14012
+ };
14013
+ }
13961
14014
 
13962
14015
  // src/partitioner/part-format.ts
13963
14016
  var FILE_HEADING = "### FILE: ";
@@ -15372,6 +15425,56 @@ function symbolsOf(entry) {
15372
15425
  }
15373
15426
  return [...new Set(names)].sort((left, right) => left.localeCompare(right));
15374
15427
  }
15428
+ function declarationSpansOf(entry) {
15429
+ const summary = entry.summary;
15430
+ if (!summary || typeof summary !== "object") return [];
15431
+ const spans = summary.declarationSpans;
15432
+ if (!Array.isArray(spans)) return [];
15433
+ return spans.filter((span) => {
15434
+ if (span === null || typeof span !== "object") return false;
15435
+ const candidate = span;
15436
+ 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;
15437
+ });
15438
+ }
15439
+ function symbolSpanOf(entry, symbol) {
15440
+ const wanted = symbol.toLowerCase();
15441
+ const matches = declarationSpansOf(entry).filter((span) => span.name.toLowerCase() === wanted);
15442
+ return matches[0] ?? null;
15443
+ }
15444
+ function identifierTokens(value) {
15445
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2);
15446
+ }
15447
+ function questionSpanOf(entry, question) {
15448
+ const asked = question.toLowerCase();
15449
+ const tokens = new Set(identifierTokens(question));
15450
+ let best = null;
15451
+ let bestScore = 0;
15452
+ for (const span of declarationSpansOf(entry)) {
15453
+ if (span.name.length < 3) continue;
15454
+ const nameTokens = identifierTokens(span.name);
15455
+ if (nameTokens.length < 2) continue;
15456
+ let score = asked.includes(span.name.toLowerCase()) ? 8 : 0;
15457
+ for (const token of nameTokens) if (tokens.has(token)) score += 2;
15458
+ if (score > bestScore) {
15459
+ best = span;
15460
+ bestScore = score;
15461
+ }
15462
+ }
15463
+ return bestScore >= 4 ? best : null;
15464
+ }
15465
+ function clampRange(range, totalLines) {
15466
+ const start = Math.max(1, Math.min(range.startLine, Math.max(1, totalLines)));
15467
+ const end = Math.max(start, Math.min(range.endLine, Math.max(1, totalLines)));
15468
+ if (totalLines > 0 && range.startLine > totalLines) return null;
15469
+ return { startLine: start, endLine: end };
15470
+ }
15471
+ function stableJson(value) {
15472
+ if (value === void 0) return "null";
15473
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
15474
+ if (Array.isArray(value)) return "[" + value.map(stableJson).join(",") + "]";
15475
+ const record = value;
15476
+ return "{" + Object.keys(record).sort().map((key) => JSON.stringify(key) + ":" + stableJson(record[key])).join(",") + "}";
15477
+ }
15375
15478
  async function prepare(args, context, overrides = {}) {
15376
15479
  const rootOutcome = resolveRoot(args.root, context);
15377
15480
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
@@ -15485,9 +15588,9 @@ function bodyFor(workspace, index, entry, cache) {
15485
15588
  }
15486
15589
  return section.body;
15487
15590
  }
15488
- function numberWindow(text2) {
15591
+ function numberWindow(text2, startLine = 1) {
15489
15592
  if (text2.length === 0) return text2;
15490
- return text2.split("\n").map((line, index) => index + 1 + ": " + line).join("\n");
15593
+ return text2.split("\n").map((line, index) => startLine + index + ": " + line).join("\n");
15491
15594
  }
15492
15595
  var impactTool = {
15493
15596
  name: "snapshot_impact",
@@ -15679,10 +15782,28 @@ var contextTool = {
15679
15782
  question: { type: "string", description: "Natural-language question or task." },
15680
15783
  files: { type: "array", items: { type: "string" }, description: "Explicit repository-relative paths." },
15681
15784
  symbols: { type: "array", items: { type: "string" }, description: "Exported or defined symbol names." },
15785
+ ranges: {
15786
+ type: "array",
15787
+ description: "Explicit 1-based line ranges. Each range is honored before the file head or a symbol span.",
15788
+ items: {
15789
+ type: "object",
15790
+ properties: {
15791
+ path: { type: "string", description: "Repository-relative path." },
15792
+ startLine: { type: "integer", minimum: 1 },
15793
+ endLine: { type: "integer", minimum: 1 }
15794
+ },
15795
+ required: ["path", "startLine", "endLine"],
15796
+ additionalProperties: false
15797
+ }
15798
+ },
15682
15799
  maxTokens: { type: "integer", minimum: 500, maximum: 2e5, default: 2e4 },
15683
15800
  linesPerFile: { type: "integer", minimum: 10, maximum: 2e3, default: 80 },
15684
15801
  includeTests: { type: "boolean", description: "Include test files (default false)." },
15685
15802
  planOnly: { type: "boolean", description: "Return the reading plan without file bodies." },
15803
+ signReceipt: {
15804
+ type: "boolean",
15805
+ description: "Sign the context receipt with SNAPSHOT_SIGNING_KEY. Requires a configured key."
15806
+ },
15686
15807
  live: LIVE_PROPERTY,
15687
15808
  root: ROOT_PROPERTY,
15688
15809
  outDir: OUT_DIR_PROPERTY
@@ -15698,6 +15819,8 @@ var contextTool = {
15698
15819
  omitted: { type: "array", items: { type: "object" } },
15699
15820
  skipped: { type: "array", items: { type: "object" } },
15700
15821
  notes: { type: "array", items: { type: "string" } },
15822
+ security: { type: "array", items: { type: "object" } },
15823
+ receipt: { type: "object" },
15701
15824
  trust: { type: "object" }
15702
15825
  }
15703
15826
  },
@@ -15715,8 +15838,8 @@ var contextTool = {
15715
15838
  const question = typeof args.question === "string" ? args.question.trim() : "";
15716
15839
  const wantedFiles = Array.isArray(args.files) ? args.files.filter((item) => typeof item === "string") : [];
15717
15840
  const wantedSymbols = Array.isArray(args.symbols) ? args.symbols.filter((item) => typeof item === "string") : [];
15718
- if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0) {
15719
- return failure("Provide at least one of question, files or symbols.");
15841
+ if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0 && !(Array.isArray(args.ranges) && args.ranges.length > 0)) {
15842
+ return failure("Provide at least one of question, files, symbols or ranges.");
15720
15843
  }
15721
15844
  const budget = Math.min(2e5, Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 2e4));
15722
15845
  const linesPerFile = Math.min(2e3, Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80));
@@ -15725,10 +15848,45 @@ var contextTool = {
15725
15848
  includeTests: args.includeTests === true,
15726
15849
  cwd: workspace.root
15727
15850
  }) : null;
15851
+ const wantedRanges = [];
15852
+ if (args.ranges !== void 0) {
15853
+ if (!Array.isArray(args.ranges)) return failure('"ranges" must be an array.');
15854
+ for (const raw of args.ranges) {
15855
+ if (raw === null || typeof raw !== "object") return failure('"ranges" entries must be objects.');
15856
+ const candidate = raw;
15857
+ if (typeof candidate.path !== "string" || candidate.path.trim().length === 0) {
15858
+ return failure('"ranges[].path" must be a non-empty string.');
15859
+ }
15860
+ if (typeof candidate.startLine !== "number" || !Number.isInteger(candidate.startLine) || candidate.startLine < 1) {
15861
+ return failure('"ranges[].startLine" must be a positive integer.');
15862
+ }
15863
+ if (typeof candidate.endLine !== "number" || !Number.isInteger(candidate.endLine) || candidate.endLine < 1) {
15864
+ return failure('"ranges[].endLine" must be a positive integer.');
15865
+ }
15866
+ if (candidate.endLine < candidate.startLine) {
15867
+ return failure('"ranges[].endLine" must be greater than or equal to startLine.');
15868
+ }
15869
+ wantedRanges.push({ path: candidate.path.trim(), startLine: candidate.startLine, endLine: candidate.endLine });
15870
+ }
15871
+ }
15872
+ if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0 && wantedRanges.length === 0) {
15873
+ return failure("Provide at least one of question, files, symbols or ranges.");
15874
+ }
15875
+ const receiptKey = args.signReceipt === true ? loadSigningKey() : null;
15876
+ if (args.signReceipt === true && receiptKey === null) {
15877
+ return failure("signReceipt requires SNAPSHOT_SIGNING_KEY to contain an Ed25519 private key.");
15878
+ }
15728
15879
  const targets = /* @__PURE__ */ new Map();
15729
15880
  const preOmitted = [];
15730
15881
  if (plan !== null) {
15731
- for (const file of plan.files) targets.set(file.path, file.why);
15882
+ for (const file of plan.files) {
15883
+ const entry = entryFor(index.manifest, file.path);
15884
+ const span = entry === null ? null : questionSpanOf(entry, question);
15885
+ targets.set(file.path, {
15886
+ why: file.why,
15887
+ ...span === null ? {} : { range: { startLine: span.startLine, endLine: span.endLine }, symbol: span.name }
15888
+ });
15889
+ }
15732
15890
  for (const file of plan.skipped) {
15733
15891
  preOmitted.push({ path: file.path, reason: file.reason });
15734
15892
  }
@@ -15743,20 +15901,38 @@ var contextTool = {
15743
15901
  preOmitted.push({ path: relative20, reason: "sensitive-file" });
15744
15902
  continue;
15745
15903
  }
15746
- targets.set(relative20, "requested file");
15904
+ targets.set(relative20, { why: "requested file" });
15747
15905
  }
15748
15906
  for (const symbol of wantedSymbols) {
15749
15907
  const needle = symbol.toLowerCase();
15750
15908
  for (const file of index.manifest.files) {
15751
15909
  if (symbolsOf(file).some((name) => name.toLowerCase() === needle)) {
15752
- if (!targets.has(file.relativePath)) {
15753
- targets.set(file.relativePath, "defines " + symbol);
15754
- }
15910
+ const span = symbolSpanOf(file, symbol);
15911
+ targets.set(file.relativePath, {
15912
+ why: "defines " + symbol,
15913
+ ...span === null ? {} : { range: { startLine: span.startLine, endLine: span.endLine }, symbol: span.name }
15914
+ });
15755
15915
  }
15756
15916
  }
15757
15917
  }
15918
+ for (const wanted of wantedRanges) {
15919
+ const relative20 = toRelativePath(workspace.root, wanted.path);
15920
+ if (relative20 === null) {
15921
+ preOmitted.push({ path: wanted.path, reason: "outside the served repository" });
15922
+ continue;
15923
+ }
15924
+ if (isSensitivePath(relative20)) {
15925
+ preOmitted.push({ path: relative20, reason: "sensitive-file" });
15926
+ continue;
15927
+ }
15928
+ targets.set(relative20, {
15929
+ why: "requested range",
15930
+ range: { startLine: wanted.startLine, endLine: wanted.endLine },
15931
+ explicitRange: true
15932
+ });
15933
+ }
15758
15934
  if (args.planOnly === true) {
15759
- if (plan !== null && wantedFiles.length === 0 && wantedSymbols.length === 0) {
15935
+ if (plan !== null && wantedFiles.length === 0 && wantedSymbols.length === 0 && wantedRanges.length === 0) {
15760
15936
  return {
15761
15937
  text: [
15762
15938
  "Plan for: " + question,
@@ -15770,13 +15946,19 @@ var contextTool = {
15770
15946
  const plannedFiles = [];
15771
15947
  const planSkipped = [...preOmitted];
15772
15948
  let planUsed = 0;
15773
- for (const [relativePath, why] of targets.entries()) {
15949
+ for (const [relativePath, target] of targets.entries()) {
15774
15950
  const entry = entryFor(index.manifest, relativePath);
15775
15951
  if (entry === null) {
15776
15952
  planSkipped.push({ path: relativePath, reason: "not in the index" });
15777
15953
  continue;
15778
15954
  }
15779
- const estimated = Math.max(1, Math.ceil(entry.includedBytes / 4));
15955
+ const range = target.range === void 0 ? null : clampRange(target.range, entry.lines);
15956
+ if (target.range !== void 0 && range === null) {
15957
+ planSkipped.push({ path: target.symbol === void 0 ? relativePath : relativePath + " (" + target.symbol + ")", reason: "range is past the end of the file" });
15958
+ continue;
15959
+ }
15960
+ const lineCount = range === null ? null : range.endLine - range.startLine + 1;
15961
+ 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));
15780
15962
  if (planUsed + estimated > budget) {
15781
15963
  planSkipped.push({ path: relativePath, reason: "does not fit the remaining budget" });
15782
15964
  continue;
@@ -15788,8 +15970,11 @@ var contextTool = {
15788
15970
  layer: entry.layer,
15789
15971
  kind: entry.kind,
15790
15972
  tokens: estimated,
15791
- mode: "full",
15792
- why
15973
+ mode: range === null ? "full" : "range",
15974
+ fromLine: range === null ? 1 : range.startLine,
15975
+ toLine: range === null ? entry.lines : range.endLine,
15976
+ ...target.symbol === void 0 ? {} : { symbol: target.symbol },
15977
+ why: target.why
15793
15978
  });
15794
15979
  }
15795
15980
  const planNotes = plan === null ? [] : [...plan.notes];
@@ -15797,7 +15982,7 @@ var contextTool = {
15797
15982
  text: [
15798
15983
  "Plan" + (question.length > 0 ? " for: " + question : ""),
15799
15984
  "Budget: " + planUsed + " of " + budget + " tokens; " + plannedFiles.length + " file(s).",
15800
- ...plannedFiles.map((file, position) => position + 1 + ". " + file.path + " (" + file.tokens + " tokens) - " + file.why),
15985
+ ...plannedFiles.map((file, position) => position + 1 + ". " + file.path + " (" + file.tokens + " tokens, lines " + file.fromLine + "\u2013" + file.toLine + ") - " + file.why),
15801
15986
  ...planNotes.map((note) => "- " + note)
15802
15987
  ].join("\n"),
15803
15988
  structured: {
@@ -15812,10 +15997,11 @@ var contextTool = {
15812
15997
  };
15813
15998
  }
15814
15999
  const omitted = [...preOmitted];
16000
+ const security = [];
15815
16001
  const blocks = [];
15816
16002
  const sections = [];
15817
16003
  let used = 0;
15818
- for (const [relativePath, why] of targets.entries()) {
16004
+ for (const [relativePath, target] of targets.entries()) {
15819
16005
  if (used >= budget) {
15820
16006
  omitted.push({ path: relativePath, reason: "budget" });
15821
16007
  continue;
@@ -15825,7 +16011,7 @@ var contextTool = {
15825
16011
  omitted.push({ path: relativePath, reason: "not in the index" });
15826
16012
  continue;
15827
16013
  }
15828
- const body = bodyFor(workspace, index, entry);
16014
+ let body = bodyFor(workspace, index, entry);
15829
16015
  if (body === null) {
15830
16016
  omitted.push({
15831
16017
  path: relativePath,
@@ -15833,18 +16019,36 @@ var contextTool = {
15833
16019
  });
15834
16020
  continue;
15835
16021
  }
15836
- let window = windowText(body, 1, linesPerFile);
15837
- let capped2 = capResultText(numberWindow(window.text));
16022
+ const hidden = scanHiddenText(body);
16023
+ if (hidden.findings.length > 0) {
16024
+ body = hidden.text;
16025
+ for (const finding of hidden.findings) security.push({ path: relativePath, ...finding });
16026
+ }
16027
+ const totalLines = body.length === 0 ? 0 : body.split("\n").length;
16028
+ const range = target.range === void 0 ? null : clampRange(target.range, totalLines);
16029
+ if (target.range !== void 0 && range === null) {
16030
+ omitted.push({ path: relativePath, reason: "range is past the end of the file" });
16031
+ continue;
16032
+ }
16033
+ const startLine = range === null ? 1 : range.startLine;
16034
+ const requestedLines = range === null ? linesPerFile : range.endLine - range.startLine + 1;
16035
+ const lineLimit = target.explicitRange === true ? Math.min(2e3, requestedLines) : Math.min(linesPerFile, requestedLines);
16036
+ let window = windowText(body, startLine, lineLimit);
16037
+ if (window.pastEnd || window.returnedLines === 0) {
16038
+ omitted.push({ path: relativePath, reason: "range is past the end of the file" });
16039
+ continue;
16040
+ }
16041
+ let capped2 = capResultText(numberWindow(window.text, startLine));
15838
16042
  let text2 = capped2.text;
15839
16043
  let tokens = Math.max(1, estimateTokens(text2));
15840
16044
  if (used + tokens > budget) {
15841
- const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
16045
+ const keep = Math.max(4, Math.floor((budget - used) / tokens * window.returnedLines));
15842
16046
  if (keep < 4) {
15843
16047
  omitted.push({ path: relativePath, reason: "budget" });
15844
16048
  continue;
15845
16049
  }
15846
- window = windowText(body, 1, keep);
15847
- capped2 = capResultText(numberWindow(window.text));
16050
+ window = windowText(body, startLine, keep);
16051
+ capped2 = capResultText(numberWindow(window.text, startLine));
15848
16052
  text2 = capped2.text;
15849
16053
  tokens = Math.max(1, estimateTokens(text2));
15850
16054
  if (used + tokens > budget || text2.length === 0) {
@@ -15854,22 +16058,60 @@ var contextTool = {
15854
16058
  }
15855
16059
  const returnedLines = text2.length === 0 ? 0 : text2.split("\n").length;
15856
16060
  const truncated = window.truncated || capped2.clipped;
16061
+ const toLine = startLine + returnedLines - 1;
15857
16062
  sections.push(
15858
- "### " + relativePath + " (" + entry.part + ", lines 1\u2013" + returnedLines + " of " + window.totalLines + (truncated ? "; more remains" : "") + ")"
16063
+ "### " + relativePath + (target.symbol === void 0 ? "" : " \u2014 " + target.symbol) + " (" + entry.part + ", lines " + startLine + "\u2013" + toLine + " of " + window.totalLines + (truncated ? "; more remains" : "") + ")"
15859
16064
  );
15860
16065
  sections.push(text2);
15861
16066
  blocks.push({
15862
16067
  path: relativePath,
15863
16068
  tokens,
15864
- why,
15865
- fromLine: 1,
16069
+ why: target.why,
16070
+ fromLine: startLine,
16071
+ toLine,
15866
16072
  returnedLines,
15867
16073
  totalLines: window.totalLines,
15868
- truncated
16074
+ truncated,
16075
+ ...target.symbol === void 0 ? {} : { symbol: target.symbol },
16076
+ chunkHash: sha256Of(Buffer.from(text2, "utf8"))
15869
16077
  });
15870
16078
  used += tokens;
15871
16079
  }
15872
- const notes = omitted.length === 0 ? [] : ["Not returned: " + omitted.map((entry) => entry.path + " (" + entry.reason + ")").join(", ") + "."];
16080
+ if (security.length > 0) {
16081
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, security.length + " hidden instruction or invisible character(s) removed"])];
16082
+ }
16083
+ const notes = [];
16084
+ if (omitted.length > 0) notes.push("Not returned: " + omitted.map((entry) => entry.path + " (" + entry.reason + ")").join(", ") + ".");
16085
+ if (security.length > 0) notes.push("Security: " + security.length + " hidden item(s) removed.");
16086
+ const receiptChunks = blocks.map((block) => ({
16087
+ path: block.path,
16088
+ fromLine: block.fromLine,
16089
+ toLine: block.toLine,
16090
+ tokens: block.tokens,
16091
+ why: block.why,
16092
+ ...block.symbol === void 0 ? {} : { symbol: block.symbol },
16093
+ sha256: block.chunkHash
16094
+ }));
16095
+ const receiptPayload = {
16096
+ schemaVersion: 1,
16097
+ algorithm: "sha256",
16098
+ chunks: receiptChunks,
16099
+ omitted,
16100
+ security,
16101
+ trust: index.trust
16102
+ };
16103
+ const receiptDigest = sha256Of(Buffer.from(stableJson(receiptPayload), "utf8"));
16104
+ const receipt = { ...receiptPayload, digest: receiptDigest };
16105
+ if (receiptKey !== null) {
16106
+ const payloadBytes = Buffer.from(stableJson(receiptPayload), "utf8");
16107
+ const publicKey = crypto.createPublicKey(receiptKey).export({ type: "spki", format: "der" }).toString("base64");
16108
+ receipt.signature = {
16109
+ algorithm: "ed25519",
16110
+ publicKey,
16111
+ value: crypto.sign(null, payloadBytes, receiptKey).toString("base64")
16112
+ };
16113
+ }
16114
+ if (receiptChunks.length > 0) notes.push("Receipt: sha256 " + receiptDigest.slice(0, 16) + "\u2026");
15873
16115
  const response = capResponseText([sections.join("\n\n"), ...notes].filter((part) => part.length > 0).join("\n\n"));
15874
16116
  return {
15875
16117
  text: response.text,
@@ -15878,6 +16120,8 @@ var contextTool = {
15878
16120
  usedTokens: used,
15879
16121
  files: blocks,
15880
16122
  omitted,
16123
+ security,
16124
+ receipt,
15881
16125
  ...response.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {},
15882
16126
  trust: index.trust
15883
16127
  }
@@ -15911,7 +16155,11 @@ var locateTool = {
15911
16155
  },
15912
16156
  outputSchema: {
15913
16157
  type: "object",
15914
- properties: { total: { type: "integer" }, matches: { type: "array", items: { type: "object" } } }
16158
+ properties: {
16159
+ total: { type: "integer" },
16160
+ matches: { type: "array", items: { type: "object" } },
16161
+ security: { type: "array", items: { type: "object" } }
16162
+ }
15915
16163
  },
15916
16164
  annotations: READ_ONLY,
15917
16165
  async handler(args, context) {
@@ -16018,6 +16266,7 @@ var locateTool = {
16018
16266
  }
16019
16267
  const shouldText = by === "text" || by === "auto" && matches.length === 0 && rawQuery.length >= 3;
16020
16268
  let textCapReason = null;
16269
+ const security = [];
16021
16270
  if (shouldText) {
16022
16271
  let scanned = 0;
16023
16272
  for (const entry of index.manifest.files) {
@@ -16038,6 +16287,13 @@ var locateTool = {
16038
16287
  if (!(pattern === null ? line.toLowerCase().includes(needle) : pattern.test(line))) continue;
16039
16288
  const from = Math.max(0, lineIndex - contextLines);
16040
16289
  const to = Math.min(lines2.length, lineIndex + contextLines + 1);
16290
+ const excerpt = scanHiddenText(lines2.slice(from, to).join("\n").trim());
16291
+ if (excerpt.findings.length > 0) {
16292
+ for (const finding of excerpt.findings) {
16293
+ security.push({ path: entry.relativePath, ...finding, line: lineIndex + 1 });
16294
+ }
16295
+ }
16296
+ if (excerpt.text.trim().length === 0) continue;
16041
16297
  textMatches.push({
16042
16298
  path: entry.relativePath,
16043
16299
  layer: entry.layer,
@@ -16045,7 +16301,7 @@ var locateTool = {
16045
16301
  part: entry.part,
16046
16302
  matchedBy: "text",
16047
16303
  line: lineIndex + 1,
16048
- text: lines2.slice(from, to).join("\n").trim().slice(0, 500)
16304
+ text: excerpt.text.slice(0, 500)
16049
16305
  });
16050
16306
  if (textMatches.length >= limit) break;
16051
16307
  }
@@ -16117,6 +16373,7 @@ var locateTool = {
16117
16373
  structured: {
16118
16374
  total: matches.length + textMatches.length,
16119
16375
  matches: combined,
16376
+ ...security.length === 0 ? {} : { security },
16120
16377
  ...references.length === 0 ? {} : { references },
16121
16378
  trust: index.trust
16122
16379
  }
@@ -16126,7 +16383,7 @@ var locateTool = {
16126
16383
  var readTool = {
16127
16384
  name: "snapshot_read",
16128
16385
  title: "Read a redacted line window",
16129
- 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.",
16386
+ 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.",
16130
16387
  inputSchema: {
16131
16388
  type: "object",
16132
16389
  properties: {
@@ -16149,6 +16406,7 @@ var readTool = {
16149
16406
  returnedLines: { type: "integer" },
16150
16407
  totalLines: { type: "integer" },
16151
16408
  pageable: { type: "boolean" },
16409
+ security: { type: "array", items: { type: "object" } },
16152
16410
  trust: { type: "object" }
16153
16411
  }
16154
16412
  },
@@ -16188,10 +16446,17 @@ var readTool = {
16188
16446
  if (partTooLargeFor(workspace, entry)) {
16189
16447
  return failure(entry.part + " is larger than the " + MAX_PART_READ_BYTES + "-byte read cap; narrow the snapshot or use snapshot_locate.");
16190
16448
  }
16191
- const body = bodyFor(workspace, index, entry);
16449
+ let body = bodyFor(workspace, index, entry);
16192
16450
  if (body === null) {
16193
16451
  return failure(relativePath + " is recorded in " + entry.part + " but its body could not be read. Run snapshot_generate.");
16194
16452
  }
16453
+ const security = [];
16454
+ const hidden = scanHiddenText(body);
16455
+ if (hidden.findings.length > 0) {
16456
+ body = hidden.text;
16457
+ for (const finding of hidden.findings) security.push({ path: entry.relativePath, ...finding });
16458
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, security.length + " hidden instruction or invisible character(s) removed"])];
16459
+ }
16195
16460
  const window = windowText(body, fromLine, lineCount);
16196
16461
  const cappedText = capResultText(window.text, MAX_RESULT_BYTES - 1024);
16197
16462
  const bodyLines = cappedText.text.length === 0 ? 0 : cappedText.text.split("\n").length;
@@ -16221,6 +16486,7 @@ var readTool = {
16221
16486
  ...!clipped && window.truncated ? { nextFromLine: window.fromLine + returnedLines } : {},
16222
16487
  truncated: window.truncated || clipped,
16223
16488
  pageable: !clipped,
16489
+ security,
16224
16490
  trust: index.trust
16225
16491
  }
16226
16492
  };
@@ -18169,8 +18435,11 @@ diff, and the commit, are then yours.
18169
18435
  If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
18170
18436
  as 7 tools over stdio instead of shelling out. Reads are live by default, so uncommitted edits and
18171
18437
  new files are overlaid in memory; the snapshot is not required. Excluded files and redacted values
18172
- never reach the context. Use \`snapshot_impact\` before editing, \`snapshot_locate\` before
18173
- \`snapshot_read\`, and \`snapshot_validate\` before trusting context from an earlier session.
18438
+ never reach the context. \`snapshot_context\` starts an explicit symbol at its declaration span
18439
+ (or a requested range), removes hidden instructions, and returns a receipt that hashes exactly
18440
+ what it returned; pass \`signReceipt: true\` with \`SNAPSHOT_SIGNING_KEY\` set to sign it. Use
18441
+ \`snapshot_impact\` before editing, \`snapshot_locate\` before \`snapshot_read\`, and
18442
+ \`snapshot_validate\` before trusting context from an earlier session.
18174
18443
  `;
18175
18444
  }
18176
18445
 
package/dist/index.d.cts CHANGED
@@ -742,7 +742,7 @@ declare function validateSnapshot(configInput: ResolvedSnapshotConfig | Snapshot
742
742
  * `package.json` carries the same version; `npm run verify` compares the two.
743
743
  */
744
744
  declare const GENERATOR_NAME = "codebase-snapshot";
745
- declare const GENERATOR_VERSION = "0.22.1";
745
+ declare const GENERATOR_VERSION = "0.22.2";
746
746
  /**
747
747
  * The manifest and ownership-marker schema this build writes and understands.
748
748
  *
package/dist/index.d.ts CHANGED
@@ -742,7 +742,7 @@ declare function validateSnapshot(configInput: ResolvedSnapshotConfig | Snapshot
742
742
  * `package.json` carries the same version; `npm run verify` compares the two.
743
743
  */
744
744
  declare const GENERATOR_NAME = "codebase-snapshot";
745
- declare const GENERATOR_VERSION = "0.22.1";
745
+ declare const GENERATOR_VERSION = "0.22.2";
746
746
  /**
747
747
  * The manifest and ownership-marker schema this build writes and understands.
748
748
  *
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_MAX_PROGRAM_FILES, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertServerSafeConfig, assertUsableConfigInput, assertUsableRef, auditSnapshot, buildBrief, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, cloneRepository, collectFiles, compareManifests, computeImpact, configDigest, countInvalidUtf8Bytes, countLines, crc32, createScopedProgram, decodeText, defineConfig, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findMultipleSymbolReferences, findSecretInPath, findSymbolReferences, firstRunMessage, formatTokens, formatUpdateNotice, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, parseRemoteSource, partitionFiles, planFirstRun, planTestRun, profileForPath, releaseAbandonedRun, renderConfig, renderDiffText, renderExplainText, renderImpactText, renumberParts, resolveChangedScope, resolveConfig, resolveDiffBase, resolveDiffChangedLines, resolveImpactChanges, resolveLatest, resolvePreciseChangedCallers, resolveSafeOutputDirs, resolveSpecifier, resolveSpecifierDetailed, runInit, runTestPlan, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, startWebServer, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, tokenAllowedForHost, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigFromWorkspace, tsconfigPathsFor, updateCommand, validateSnapshot, walkFiles, workerEntry, workspaceResolutionFor, wrapLines, writeZip } from './chunk-7AAXOTKS.js';
1
+ export { ARTIFACT_NAMES, CHECK_INTERVAL_MS, CONFIG_KEYS, DEFAULT_ANSWERS, DEFAULT_MAX_PROGRAM_FILES, DEFAULT_SECRET_PATTERNS, FAILURE_INTERVAL_MS, GENERATOR_NAME, GENERATOR_VERSION, HOOK_MARKER, LANGUAGE_PROFILES, MIN_MAX_PART_BYTES, MIN_MAX_PART_TOKENS, PACKAGE_LATEST_URL, PRESETS, PromptBack, PromptCancelled, REQUEST_TIMEOUT_MS, SCHEMA_VERSION, UP_TO_DATE_INTERVAL_MS, anchorForPath, appendGitignoreEntries, assertPublicHost, assertReplaceable, assertServerSafeConfig, assertUsableConfigInput, assertUsableRef, auditSnapshot, buildBrief, buildImportResolver, bytesForTokens, cacheDirectory, cacheFilePath, checkForUpdate, classifyKind, classifyLayer, cloneRepository, collectFiles, compareManifests, computeImpact, configDigest, countInvalidUtf8Bytes, countLines, crc32, createScopedProgram, decodeText, defineConfig, detectLanguage, detectPreset, displayPath, displayWidth, enforceBudget, estimateTokens, explainPath, fenceForContent, fenceForText, fetchLatestVersion, findMultipleSymbolReferences, findSecretInPath, findSymbolReferences, firstRunMessage, formatTokens, formatUpdateNotice, generateProjectTree, generateSarifReport, generateSnapshot, generateSnapshotAsync, getGitInfo, getPreset, gitignorePath, globToRegExp, hasPriorSnapshot, importsChangedFile, importsOfFile, importsOfText, installKind, installPreCommitHook, isBinaryBuffer, isBinaryExtension, isBinaryFile, isEffectivelyEmpty, isInteractive, isNewer, isPrivateHost, isResolvedConfig, isSensitivePath, isSkeletonizable, isTsxFileName, listPresetNames, loadConfigFile, loadConfigFileDetailed, loadManifest, lockPathFor, makeCloneDirectory, markResolvedConfig, matchRule, matchesExclude, normalizeResolvedConfig, parseByteSize, parseRemoteSource, partitionFiles, planFirstRun, planTestRun, profileForPath, releaseAbandonedRun, renderConfig, renderDiffText, renderExplainText, renderImpactText, renumberParts, resolveChangedScope, resolveConfig, resolveDiffBase, resolveDiffChangedLines, resolveImpactChanges, resolveLatest, resolvePreciseChangedCallers, resolveSafeOutputDirs, resolveSpecifier, resolveSpecifierDetailed, runInit, runTestPlan, scanAndRedactSecrets, shouldCheck, skeletonizeTypeScript, startWebServer, stripJsonComments, summarizeJson, summarizeMarkdown, summarizeTypeScriptSource, summarizeWithProfile, supportsTypeScriptImports, tokenAllowedForHost, treeTruncationWarnings, truncatePreview, truncateToBytes, tsconfigFromWorkspace, tsconfigPathsFor, updateCommand, validateSnapshot, walkFiles, workerEntry, workspaceResolutionFor, wrapLines, writeZip } from './chunk-OVH6B3GV.js';