codebase-snapshot 0.22.0 → 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/mcp.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var fs17 = require('fs');
3
+ var fs18 = require('fs');
4
4
  var path7 = require('path');
5
5
  var crypto = require('crypto');
6
6
  var module$1 = require('module');
@@ -34,7 +34,7 @@ function _interopNamespace(e) {
34
34
  return Object.freeze(n);
35
35
  }
36
36
 
37
- var fs17__namespace = /*#__PURE__*/_interopNamespace(fs17);
37
+ var fs18__namespace = /*#__PURE__*/_interopNamespace(fs18);
38
38
  var path7__namespace = /*#__PURE__*/_interopNamespace(path7);
39
39
  var crypto__namespace = /*#__PURE__*/_interopNamespace(crypto);
40
40
  var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
@@ -536,9 +536,9 @@ var SKIPPED_WALK_DIRS = /* @__PURE__ */ new Set([
536
536
  ]);
537
537
  function readSmallFile(fullPath) {
538
538
  try {
539
- const stats = fs17__namespace.statSync(fullPath);
539
+ const stats = fs18__namespace.statSync(fullPath);
540
540
  if (!stats.isFile() || stats.size > MANIFEST_MAX_BYTES) return null;
541
- return fs17__namespace.readFileSync(fullPath, "utf8");
541
+ return fs18__namespace.readFileSync(fullPath, "utf8");
542
542
  } catch {
543
543
  return null;
544
544
  }
@@ -604,7 +604,7 @@ function pnpmWorkspacePatterns(raw) {
604
604
  function childDirectories(cwd, parent) {
605
605
  let entries;
606
606
  try {
607
- entries = fs17__namespace.readdirSync(path7__namespace.join(cwd, parent), { withFileTypes: true });
607
+ entries = fs18__namespace.readdirSync(path7__namespace.join(cwd, parent), { withFileTypes: true });
608
608
  } catch {
609
609
  return [];
610
610
  }
@@ -639,10 +639,10 @@ function workspacePackageDirs(cwd, patterns) {
639
639
  function scanWorkspacePackages(cwd, patterns) {
640
640
  const files = /* @__PURE__ */ new Set();
641
641
  const dependencies = /* @__PURE__ */ new Set();
642
- for (const relative12 of workspacePackageDirs(cwd, patterns)) {
643
- const full = path7__namespace.join(cwd, relative12);
642
+ for (const relative14 of workspacePackageDirs(cwd, patterns)) {
643
+ const full = path7__namespace.join(cwd, relative14);
644
644
  try {
645
- for (const entry of fs17__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
645
+ for (const entry of fs18__namespace.readdirSync(full, { withFileTypes: true })) files.add(entry.name);
646
646
  } catch {
647
647
  }
648
648
  const raw = readSmallFile(path7__namespace.join(full, "package.json"));
@@ -655,7 +655,7 @@ function scanWorkspacePackages(cwd, patterns) {
655
655
  var SNAPSHOT_MARKER = ".codebase-snapshot";
656
656
  function isToolOwnedDirectory(dir) {
657
657
  try {
658
- return fs17__namespace.statSync(dir).isDirectory() && fs17__namespace.existsSync(path7__namespace.join(dir, SNAPSHOT_MARKER));
658
+ return fs18__namespace.statSync(dir).isDirectory() && fs18__namespace.existsSync(path7__namespace.join(dir, SNAPSHOT_MARKER));
659
659
  } catch {
660
660
  return false;
661
661
  }
@@ -670,7 +670,7 @@ function countMarkdownFiles(cwd) {
670
670
  directoriesSeen += 1;
671
671
  let entries;
672
672
  try {
673
- entries = fs17__namespace.readdirSync(current.dir, { withFileTypes: true });
673
+ entries = fs18__namespace.readdirSync(current.dir, { withFileTypes: true });
674
674
  } catch {
675
675
  continue;
676
676
  }
@@ -692,7 +692,7 @@ function buildPresetContext(cwd) {
692
692
  const files = /* @__PURE__ */ new Set();
693
693
  const dirs = /* @__PURE__ */ new Set();
694
694
  try {
695
- for (const entry of fs17__namespace.readdirSync(cwd, { withFileTypes: true })) {
695
+ for (const entry of fs18__namespace.readdirSync(cwd, { withFileTypes: true })) {
696
696
  if (entry.isDirectory()) dirs.add(entry.name);
697
697
  else if (entry.isFile()) files.add(entry.name);
698
698
  }
@@ -1823,7 +1823,7 @@ var DEFAULT_SECRET_PATTERNS = [
1823
1823
  // query parameter or `$VARIABLE` reference is not an assignment).
1824
1824
  rule: "credential-assignment-unquoted",
1825
1825
  pattern: new RegExp(
1826
- `(?:${QUOTED_CREDENTIAL_KEY}|${UNQUOTED_STRONG_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}|(?<=${UNQUOTED_STRONG_NAME}\\s{0,8}=(?!=)\\s{0,8})(?![\\s#$"'\`])[^\\s]{1,}|(?<=${UNQUOTED_STRONG_NAME}\\s{0,8}:[ ]{1,8})(?![ ]*["'\`])(?![ ]*[|>])${NOT_A_LITERAL_VALUE}[^\r
1826
+ `(?:${QUOTED_CREDENTIAL_KEY}|${UNQUOTED_STRONG_NAME})\\s{0,8}${ASSIGN}\\s{0,8}${NOT_A_LITERAL_VALUE}${UNQUOTED_LITERAL}|(?<=${UNQUOTED_STRONG_NAME}["']?\\s{0,8}=(?!=)\\s{0,8})(?![\\s#$"'\`])[^\\s]{1,}|(?<=${UNQUOTED_STRONG_NAME}["']?\\s{0,8}:[ ]{1,8})(?![ ]*["'\`])(?![ ]*[|>])(?![ ]*\\$\\{[A-Za-z_][A-Za-z0-9_]*[:}#%/])${NOT_A_LITERAL_VALUE}[^\r
1827
1827
  #]{1,300}`,
1828
1828
  "i"
1829
1829
  ),
@@ -1883,7 +1883,12 @@ var DEFAULT_SECRET_PATTERNS = [
1883
1883
  pattern: new RegExp(
1884
1884
  // The operator set deliberately omits `?`: `${VAR:?message}` is an error message in shell
1885
1885
  // and Compose, not a fallback value, and masking it hid the sentence a user is meant to read.
1886
- `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=+]([^}"\`\\r\\n]{2,512})\\}["'\`]?`,
1886
+ // The fallback may itself be quoted — `${VAR:-"prodSecret"}` is standard POSIX shell
1887
+ // and Docker Compose — so the capture takes everything between the operator and the
1888
+ // closing brace. Quotes are part of the value here: masking the whole fallback is
1889
+ // correct, and it keeps a quoted default from slipping between the two quote-aware
1890
+ // rules.
1891
+ `(?:["']${STRONG_CREDENTIAL_NAME}["']|${NOT_AFTER_QUOTE}${STRONG_CREDENTIAL_NAME})\\s{0,8}${ASSIGN}\\s{0,8}["'\`]?\\$\\{[A-Za-z_][A-Za-z0-9_]*:?[-=+]([^}\\r\\n]{2,512})\\}["'\`]?`,
1887
1892
  "i"
1888
1893
  ),
1889
1894
  valueGroup: 1
@@ -2375,7 +2380,19 @@ function maskValueLine(line) {
2375
2380
  return `${indent}${REDACTION_MARKER}`;
2376
2381
  }
2377
2382
  var STRUCTURED_KEY = /^([ \t]*)(?:-[ \t]+)?["']?([A-Za-z0-9_$.-]{1,128})["']?[ \t]*([:=])[ \t]*(.*)$/;
2378
- var BLOCK_SCALAR = /^[|>][+-]?\d*[ \t]*(?:#.*)?$/;
2383
+ var BLOCK_SCALAR = /^[|>](?:[+-]\d*|\d[+-]?)?[ \t]*(?:#.*)?$/;
2384
+ var YAML_LIST_ITEM = /^([ \t]*-[ \t]+)(.*)$/;
2385
+ function isJsonFile(filePath) {
2386
+ return filePath !== void 0 && /\.(?:json|jsonc|json5)$/i.test(filePath);
2387
+ }
2388
+ function maskJsonStrings(line) {
2389
+ let changed = false;
2390
+ const text = line.replace(/"(?:[^"\\]|\\.)*"/g, () => {
2391
+ changed = true;
2392
+ return `"${REDACTION_MARKER}"`;
2393
+ });
2394
+ return { text, changed };
2395
+ }
2379
2396
  function redactStructuredValues(text, filePath, recordFinding) {
2380
2397
  if (!isStructuredFile(filePath)) return text;
2381
2398
  const segments = text.split(LINE_BREAK);
@@ -2388,6 +2405,7 @@ function redactStructuredValues(text, filePath, recordFinding) {
2388
2405
  if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
2389
2406
  const baseIndent = (match[1] ?? "").length;
2390
2407
  const rest = (match[4] ?? "").trim();
2408
+ const restIsComment = rest.startsWith("#");
2391
2409
  if (BLOCK_SCALAR.test(rest)) {
2392
2410
  let cursor2 = index + 2;
2393
2411
  let masked2 = false;
@@ -2404,14 +2422,67 @@ function redactStructuredValues(text, filePath, recordFinding) {
2404
2422
  if (masked2) recordFinding(index / 2 + 1, ["credential-block-scalar"]);
2405
2423
  continue;
2406
2424
  }
2407
- if (rest !== "") continue;
2425
+ if (isJsonFile(filePath) && rest.startsWith("[") && !rest.startsWith(REDACTION_MARKER)) {
2426
+ let cursor2 = index;
2427
+ let masked2 = false;
2428
+ let depth = 0;
2429
+ do {
2430
+ const body = segments[cursor2] ?? "";
2431
+ const start = cursor2 === index ? body.length - (match[4] ?? "").length : 0;
2432
+ const head = body.slice(0, start);
2433
+ const tail = body.slice(start);
2434
+ const maskedTail = maskJsonStrings(tail);
2435
+ if (maskedTail.changed) {
2436
+ masked2 = true;
2437
+ segments[cursor2] = head + maskedTail.text;
2438
+ }
2439
+ depth += (tail.match(/\[/g)?.length ?? 0) - (tail.match(/\]/g)?.length ?? 0);
2440
+ cursor2 += 2;
2441
+ } while (cursor2 < segments.length && depth > 0);
2442
+ if (masked2) recordFinding(index / 2 + 1, ["credential-array-value"]);
2443
+ continue;
2444
+ }
2445
+ const quotedKey = /^["']/.test(line.slice((match[1] ?? "").length));
2446
+ const commentAt = rest.search(/[ \t]#/);
2447
+ const valueText = commentAt >= 0 ? rest.slice(0, commentAt) : rest;
2448
+ const valueSuffix = commentAt >= 0 ? rest.slice(commentAt) : "";
2449
+ const markerOnly = valueText === REDACTION_MARKER || valueText === `"${REDACTION_MARKER}"` || valueText.replace(REDACTION_MARKER, "").trim() === "";
2450
+ if (valueText !== "" && !restIsComment && !/^["'`]/.test(valueText) && (quotedKey || valueText.includes("&") || valueText.startsWith(REDACTION_MARKER))) {
2451
+ if (markerOnly) continue;
2452
+ const prefix = line.slice(0, line.length - rest.length);
2453
+ segments[index] = prefix + (isJsonFile(filePath) ? `"${REDACTION_MARKER}"` : REDACTION_MARKER) + valueSuffix;
2454
+ recordFinding(index / 2 + 1, ["credential-scalar-value"]);
2455
+ continue;
2456
+ }
2457
+ if (rest !== "" && !restIsComment) continue;
2408
2458
  let cursor = index + 2;
2409
2459
  while (cursor < segments.length && (segments[cursor] ?? "").trim() === "") cursor += 2;
2410
2460
  const firstValue = segments[cursor];
2411
2461
  if (firstValue === void 0) continue;
2412
2462
  const valueIndent = (/^[ \t]*/.exec(firstValue)?.[0] ?? "").length;
2413
2463
  if (valueIndent <= baseIndent) continue;
2414
- if (STRUCTURED_KEY.test(firstValue) || /^[ \t]*-[ \t]/.test(firstValue)) continue;
2464
+ if (STRUCTURED_KEY.test(firstValue) && !YAML_LIST_ITEM.test(firstValue)) continue;
2465
+ if (YAML_LIST_ITEM.test(firstValue)) {
2466
+ let masked2 = false;
2467
+ while (cursor < segments.length) {
2468
+ const body = segments[cursor] ?? "";
2469
+ if (body.trim() === "") {
2470
+ cursor += 2;
2471
+ continue;
2472
+ }
2473
+ const item = YAML_LIST_ITEM.exec(body);
2474
+ const indent = (/^[ \t]*/.exec(body)?.[0] ?? "").length;
2475
+ if (indent < valueIndent || item === null) break;
2476
+ const content = (item[2] ?? "").trim();
2477
+ if (content !== "" && !/^[A-Za-z0-9_$.-]+:/.test(content)) {
2478
+ if (!isMarkerLine(content)) masked2 = true;
2479
+ segments[cursor] = (item[1] ?? "") + REDACTION_MARKER;
2480
+ }
2481
+ cursor += 2;
2482
+ }
2483
+ if (masked2) recordFinding(index / 2 + 1, ["credential-list-value"]);
2484
+ continue;
2485
+ }
2415
2486
  let masked = false;
2416
2487
  while (cursor < segments.length) {
2417
2488
  const body = segments[cursor] ?? "";
@@ -2428,20 +2499,118 @@ function redactStructuredValues(text, filePath, recordFinding) {
2428
2499
  return segments.join("");
2429
2500
  }
2430
2501
  var DOCKERFILE_ENV = /^([ \t]*)(ENV|ARG)([ \t]+)([A-Za-z_][A-Za-z0-9_]*)([ \t]*=[ \t]*|[ \t]+)(\S.*)$/i;
2502
+ var DOCKERFILE_LEADING_CONTINUATION = /^([ \t]*)(ENV|ARG)[ \t]*\\[ \t]*$/i;
2431
2503
  function endsWithDockerContinuation(line) {
2432
- const end = line.replace(/[ \t]+$/, "");
2504
+ let end = line.length;
2505
+ while (end > 0 && (line[end - 1] === " " || line[end - 1] === " ")) end -= 1;
2506
+ const trimmed = line.slice(0, end);
2433
2507
  let count = 0;
2434
- while (count < end.length && end[end.length - 1 - count] === "\\") count += 1;
2508
+ while (count < trimmed.length && trimmed[trimmed.length - 1 - count] === "\\") count += 1;
2435
2509
  return count % 2 === 1;
2436
2510
  }
2511
+ function isBenignDockerValue(value) {
2512
+ return value === "" || isMarkerLine(value) || isPlaceholderValue(value) || isShellReference(value);
2513
+ }
2514
+ function firstSensitiveAssignment(segments, start, end) {
2515
+ const assignment = /(?:^|[ \t])([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*/g;
2516
+ for (let at = start; at <= end; at += 2) {
2517
+ const line = segments[at] ?? "";
2518
+ assignment.lastIndex = 0;
2519
+ let match;
2520
+ while ((match = assignment.exec(line)) !== null) {
2521
+ const key = match[1] ?? "";
2522
+ if (!CREDENTIAL_KEY_TAIL.test(key)) continue;
2523
+ const valueStart = match.index + match[0].length;
2524
+ const parts = [];
2525
+ const first = line.slice(valueStart).replace(/\\[ \t]*$/, "").trim();
2526
+ if (first !== "") parts.push(first);
2527
+ if (first === "" && !endsWithDockerContinuation(line)) continue;
2528
+ for (let next = at + 2; next <= end; next += 2) {
2529
+ const part = (segments[next] ?? "").replace(/\\[ \t]*$/, "").trim();
2530
+ if (part !== "") parts.push(part);
2531
+ }
2532
+ if (parts.length === 0) continue;
2533
+ if (parts.every(isBenignDockerValue)) continue;
2534
+ return { at, valueStart };
2535
+ }
2536
+ }
2537
+ return null;
2538
+ }
2539
+ function maskDockerAssignment(segments, start, end, found) {
2540
+ for (let at = start; at <= end; at += 2) {
2541
+ if (at < found.at) continue;
2542
+ const body = segments[at] ?? "";
2543
+ const keep = endsWithDockerContinuation(body);
2544
+ segments[at] = at === found.at ? body.slice(0, found.valueStart) + REDACTION_MARKER + (keep ? " \\" : "") : maskLineContent(body.replace(/\\[ \t]*$/, "")) + (keep ? " \\" : "");
2545
+ }
2546
+ }
2547
+ function firstSpaceSeparatedSecret(segments, start, end) {
2548
+ for (let at = start; at <= end; at += 2) {
2549
+ const body = segments[at] ?? "";
2550
+ const match = /^([ \t]*)([A-Za-z_][A-Za-z0-9_]*)([ \t]+)(\S.*)$/.exec(body);
2551
+ if (match === null) continue;
2552
+ if (!CREDENTIAL_KEY_TAIL.test(match[2] ?? "")) continue;
2553
+ const first = (match[4] ?? "").replace(/\\[ \t]*$/, "").trim();
2554
+ const parts = [];
2555
+ if (first !== "") parts.push(first);
2556
+ if (first === "" && !endsWithDockerContinuation(body)) continue;
2557
+ for (let next = at + 2; next <= end; next += 2) {
2558
+ const part = (segments[next] ?? "").replace(/\\[ \t]*$/, "").trim();
2559
+ if (part !== "") parts.push(part);
2560
+ }
2561
+ if (parts.length === 0 || parts.every(isBenignDockerValue)) continue;
2562
+ return {
2563
+ at,
2564
+ valueStart: (match[1] ?? "").length + (match[2] ?? "").length + (match[3] ?? "").length
2565
+ };
2566
+ }
2567
+ return null;
2568
+ }
2437
2569
  function redactDockerfileEnv(text, filePath, recordFinding) {
2438
2570
  if (!isDockerfile(filePath)) return text;
2439
2571
  const segments = text.split(LINE_BREAK);
2440
2572
  for (let index = 0; index < segments.length; index += 2) {
2441
2573
  const line = segments[index];
2442
2574
  if (line === void 0) continue;
2575
+ const leading = DOCKERFILE_LEADING_CONTINUATION.exec(line);
2576
+ if (leading !== null) {
2577
+ let end = index;
2578
+ let current2 = line;
2579
+ while (endsWithDockerContinuation(current2) && end + 2 < segments.length) {
2580
+ end += 2;
2581
+ current2 = segments[end] ?? "";
2582
+ }
2583
+ const found = firstSensitiveAssignment(segments, index, end);
2584
+ if (found !== null) {
2585
+ maskDockerAssignment(segments, index, end, found);
2586
+ recordFinding(found.at / 2 + 1, ["dockerfile-env-secret"]);
2587
+ } else {
2588
+ const spaced = firstSpaceSeparatedSecret(segments, index + 2, end);
2589
+ if (spaced !== null) {
2590
+ maskDockerAssignment(segments, index, end, spaced);
2591
+ recordFinding(spaced.at / 2 + 1, ["dockerfile-env-secret"]);
2592
+ }
2593
+ }
2594
+ index = end;
2595
+ continue;
2596
+ }
2443
2597
  const match = DOCKERFILE_ENV.exec(line);
2444
2598
  if (match === null) continue;
2599
+ const assignmentForm = (match[5] ?? "").includes("=");
2600
+ if (assignmentForm) {
2601
+ let end = index;
2602
+ let current2 = line;
2603
+ while (endsWithDockerContinuation(current2) && end + 2 < segments.length) {
2604
+ end += 2;
2605
+ current2 = segments[end] ?? "";
2606
+ }
2607
+ const found = firstSensitiveAssignment(segments, index, end);
2608
+ if (found === null) continue;
2609
+ maskDockerAssignment(segments, index, end, found);
2610
+ recordFinding(found.at / 2 + 1, ["dockerfile-env-secret"]);
2611
+ index = end;
2612
+ continue;
2613
+ }
2445
2614
  if (!CREDENTIAL_KEY_TAIL.test(match[4] ?? "")) continue;
2446
2615
  const value = (match[6] ?? "").trim();
2447
2616
  const continuationLines = [];
@@ -2458,9 +2627,7 @@ function redactDockerfileEnv(text, filePath, recordFinding) {
2458
2627
  }
2459
2628
  combined = combined.trim();
2460
2629
  const keepContinuation = endsWithDockerContinuation(line);
2461
- if (markerOnly || isPlaceholderValue(combined) || /^\$[({A-Za-z_]/.test(combined)) {
2462
- continue;
2463
- }
2630
+ if (markerOnly || isBenignDockerValue(combined)) continue;
2464
2631
  const separator = match[5] ?? "";
2465
2632
  segments[index] = `${match[1]}${match[2]}${match[3]}${match[4]}${separator}${REDACTION_MARKER}`;
2466
2633
  if (keepContinuation) segments[index] += " \\";
@@ -2577,7 +2744,12 @@ function isMarkerLine(value) {
2577
2744
  return trimmed === REDACTION_MARKER || trimmed === PEM_REDACTION_MARKER;
2578
2745
  }
2579
2746
  function isPlaceholderValue(value) {
2580
- const trimmed = value.trim().replace(/^["'`]+/, "").replace(/["'`]+$/, "");
2747
+ const base = value.trim();
2748
+ let start = 0;
2749
+ while (start < base.length && (base[start] === '"' || base[start] === "'" || base[start] === "`")) start += 1;
2750
+ let end = base.length;
2751
+ while (end > start && (base[end - 1] === '"' || base[end - 1] === "'" || base[end - 1] === "`")) end -= 1;
2752
+ const trimmed = base.slice(start, end);
2581
2753
  if (trimmed.length === 0) return false;
2582
2754
  if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(trimmed))) return true;
2583
2755
  if (trimmed === REDACTION_MARKER || trimmed === PEM_REDACTION_MARKER) return true;
@@ -2635,7 +2807,7 @@ function isShellFile(filePath) {
2635
2807
  return SHELL_FILE.test(normalised) || SHELL_BASENAME.test(normalised.slice(normalised.lastIndexOf("/") + 1));
2636
2808
  }
2637
2809
  function isShellReference(value) {
2638
- return /^\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[^}]*\}|\([^)]*\))$/.test(value);
2810
+ return /^\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[A-Za-z_][A-Za-z0-9_]*\}|\([^)]*\))$/.test(value);
2639
2811
  }
2640
2812
  function isUnquotedValue(line, start) {
2641
2813
  const before = start > 0 ? line[start - 1] : "";
@@ -2841,8 +3013,8 @@ function applySpansKeepingQuotes(line, spans) {
2841
3013
  return out;
2842
3014
  }
2843
3015
  function isInside(parent, child) {
2844
- const relative12 = path7__namespace.relative(parent, child);
2845
- return relative12 === "" || relative12 !== ".." && !relative12.startsWith(`..${path7__namespace.sep}`) && !relative12.startsWith("../") && !path7__namespace.isAbsolute(relative12);
3016
+ const relative14 = path7__namespace.relative(parent, child);
3017
+ return relative14 === "" || relative14 !== ".." && !relative14.startsWith(`..${path7__namespace.sep}`) && !relative14.startsWith("../") && !path7__namespace.isAbsolute(relative14);
2846
3018
  }
2847
3019
  function resolveConfined(baseDir, relativePath) {
2848
3020
  if (relativePath.length === 0 || relativePath.includes("\0")) {
@@ -2853,7 +3025,7 @@ function resolveConfined(baseDir, relativePath) {
2853
3025
  }
2854
3026
  let baseReal;
2855
3027
  try {
2856
- baseReal = fs17__namespace.realpathSync(path7__namespace.resolve(baseDir));
3028
+ baseReal = fs18__namespace.realpathSync(path7__namespace.resolve(baseDir));
2857
3029
  } catch {
2858
3030
  return { ok: false, reason: "missing", message: "the snapshot directory does not exist" };
2859
3031
  }
@@ -2863,7 +3035,7 @@ function resolveConfined(baseDir, relativePath) {
2863
3035
  }
2864
3036
  let stats;
2865
3037
  try {
2866
- stats = fs17__namespace.lstatSync(candidate);
3038
+ stats = fs18__namespace.lstatSync(candidate);
2867
3039
  } catch (error) {
2868
3040
  const code = error.code;
2869
3041
  return {
@@ -2880,7 +3052,7 @@ function resolveConfined(baseDir, relativePath) {
2880
3052
  }
2881
3053
  let real;
2882
3054
  try {
2883
- real = fs17__namespace.realpathSync(candidate);
3055
+ real = fs18__namespace.realpathSync(candidate);
2884
3056
  } catch {
2885
3057
  return { ok: false, reason: "unreadable", message: "the file could not be resolved" };
2886
3058
  }
@@ -2900,7 +3072,7 @@ function readConfinedBytes(baseDir, relativePath, maxBytes) {
2900
3072
  };
2901
3073
  }
2902
3074
  try {
2903
- const bytes = fs17__namespace.readFileSync(resolved.path);
3075
+ const bytes = fs18__namespace.readFileSync(resolved.path);
2904
3076
  return { ok: true, bytes, path: resolved.path, stats: resolved.stats };
2905
3077
  } catch {
2906
3078
  return { ok: false, reason: "unreadable", message: "the file could not be read" };
@@ -2917,7 +3089,7 @@ function readConfinedText(baseDir, relativePath, maxBytes) {
2917
3089
  };
2918
3090
  }
2919
3091
  try {
2920
- const text = fs17__namespace.readFileSync(resolved.path, "utf8");
3092
+ const text = fs18__namespace.readFileSync(resolved.path, "utf8");
2921
3093
  return { ok: true, text, path: resolved.path, stats: resolved.stats };
2922
3094
  } catch {
2923
3095
  return { ok: false, reason: "unreadable", message: "the file could not be read" };
@@ -2926,6 +3098,11 @@ function readConfinedText(baseDir, relativePath, maxBytes) {
2926
3098
 
2927
3099
  // src/signing.ts
2928
3100
  var SIGNATURE_FILE = "signature.json";
3101
+ function loadSigningKey(environment = process.env) {
3102
+ const pem = environment.SNAPSHOT_SIGNING_KEY;
3103
+ if (pem === void 0 || pem.trim() === "") return null;
3104
+ return crypto__namespace.createPrivateKey({ key: pem, format: "pem" });
3105
+ }
2929
3106
  var MAX_SIGNATURE_BYTES = 64 * 1024;
2930
3107
  function verifySnapshotSignature(snapshotDir) {
2931
3108
  const signatureRead = readConfinedBytes(snapshotDir, SIGNATURE_FILE);
@@ -2980,7 +3157,7 @@ function verifySnapshotSignature(snapshotDir) {
2980
3157
 
2981
3158
  // src/version.ts
2982
3159
  var GENERATOR_NAME = "codebase-snapshot";
2983
- var GENERATOR_VERSION = "0.22.0";
3160
+ var GENERATOR_VERSION = "0.22.2";
2984
3161
  var SCHEMA_VERSION = "3.0.0";
2985
3162
  var LEGACY_GENERATOR_NAMES = ["@ankurhalder/codebase-snapshot"];
2986
3163
  function isOurGeneratorName(name) {
@@ -2997,7 +3174,7 @@ var PRESET_IGNORES = new Set(
2997
3174
  );
2998
3175
  function readLinkTarget(linkPath, fallback) {
2999
3176
  try {
3000
- return fs17__namespace.readlinkSync(linkPath);
3177
+ return fs18__namespace.readlinkSync(linkPath);
3001
3178
  } catch {
3002
3179
  return fallback;
3003
3180
  }
@@ -3012,8 +3189,8 @@ function brokenLinkRecord(linkPath, relativePath, rootReal) {
3012
3189
  };
3013
3190
  }
3014
3191
  function isInside2(root, candidate) {
3015
- const relative12 = path7__namespace.relative(root, candidate);
3016
- return relative12 === "" || !relative12.startsWith(`..${path7__namespace.sep}`) && relative12 !== ".." && !path7__namespace.isAbsolute(relative12);
3192
+ const relative14 = path7__namespace.relative(root, candidate);
3193
+ return relative14 === "" || !relative14.startsWith(`..${path7__namespace.sep}`) && relative14 !== ".." && !path7__namespace.isAbsolute(relative14);
3017
3194
  }
3018
3195
  var GIT_OUTPUT_LIMIT = 68157440;
3019
3196
  function getGitInfo(cwd, fallbackBranch = "main") {
@@ -3335,7 +3512,7 @@ function readGitignoreRules(dir) {
3335
3512
  const gitignorePath = path7__namespace.join(dir, ".gitignore");
3336
3513
  let raw;
3337
3514
  try {
3338
- raw = fs17__namespace.readFileSync(gitignorePath, "utf8");
3515
+ raw = fs18__namespace.readFileSync(gitignorePath, "utf8");
3339
3516
  } catch {
3340
3517
  return [];
3341
3518
  }
@@ -3427,12 +3604,7 @@ function compileGitignorePattern(pattern) {
3427
3604
  }
3428
3605
  function matchesGitignoreRule(rule, scoped, isDirectory) {
3429
3606
  if (!rule.dirOnly) return matchGitignorePattern(scoped, rule.pattern);
3430
- const segments = scoped.split("/");
3431
- const limit = isDirectory ? segments.length : segments.length - 1;
3432
- for (let depth = 1; depth <= limit; depth += 1) {
3433
- if (matchGitignorePattern(segments.slice(0, depth).join("/"), rule.pattern)) return true;
3434
- }
3435
- return false;
3607
+ return isDirectory && matchGitignorePattern(scoped, rule.pattern);
3436
3608
  }
3437
3609
  function gitignoreVerdict(layers, relativePath, isDirectory) {
3438
3610
  let verdict = null;
@@ -3509,7 +3681,7 @@ function listIgnoredPaths(cwd) {
3509
3681
  }
3510
3682
  function hasSnapshotMarker(target) {
3511
3683
  try {
3512
- return fs17__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
3684
+ return fs18__namespace.statSync(target).isDirectory() && isToolOwnedDirectory2(target);
3513
3685
  } catch {
3514
3686
  return false;
3515
3687
  }
@@ -3518,7 +3690,7 @@ var IGNORABLE_DIRECTORY_ENTRIES = /* @__PURE__ */ new Set([".DS_Store"]);
3518
3690
  function isToolOwnedDirectory2(dir) {
3519
3691
  let raw;
3520
3692
  try {
3521
- raw = fs17__namespace.readFileSync(path7__namespace.join(dir, ".codebase-snapshot"), "utf8");
3693
+ raw = fs18__namespace.readFileSync(path7__namespace.join(dir, ".codebase-snapshot"), "utf8");
3522
3694
  } catch {
3523
3695
  return false;
3524
3696
  }
@@ -3535,7 +3707,7 @@ function isToolOwnedDirectory2(dir) {
3535
3707
  }
3536
3708
  let manifestBytes;
3537
3709
  try {
3538
- manifestBytes = fs17__namespace.readFileSync(path7__namespace.join(dir, "manifest.json"));
3710
+ manifestBytes = fs18__namespace.readFileSync(path7__namespace.join(dir, "manifest.json"));
3539
3711
  } catch {
3540
3712
  return false;
3541
3713
  }
@@ -3553,14 +3725,14 @@ function isToolOwnedDirectory2(dir) {
3553
3725
  const full = path7__namespace.join(dir, ...entry.split("/"));
3554
3726
  let stats;
3555
3727
  try {
3556
- stats = fs17__namespace.lstatSync(full);
3728
+ stats = fs18__namespace.lstatSync(full);
3557
3729
  } catch {
3558
3730
  return false;
3559
3731
  }
3560
3732
  if (!stats.isFile() || stats.size !== record.bytes) return false;
3561
3733
  let digest;
3562
3734
  try {
3563
- digest = crypto.createHash("sha256").update(fs17__namespace.readFileSync(full)).digest("hex");
3735
+ digest = crypto.createHash("sha256").update(fs18__namespace.readFileSync(full)).digest("hex");
3564
3736
  } catch {
3565
3737
  return false;
3566
3738
  }
@@ -3572,22 +3744,22 @@ function isToolOwnedDirectory2(dir) {
3572
3744
  const current = stack.pop();
3573
3745
  let entries;
3574
3746
  try {
3575
- entries = fs17__namespace.readdirSync(path7__namespace.join(dir, current), { withFileTypes: true });
3747
+ entries = fs18__namespace.readdirSync(path7__namespace.join(dir, current), { withFileTypes: true });
3576
3748
  } catch {
3577
3749
  return false;
3578
3750
  }
3579
3751
  for (const entry of entries) {
3580
- const relative12 = current === "" ? entry.name : current + "/" + entry.name;
3581
- if (relative12 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
3752
+ const relative14 = current === "" ? entry.name : current + "/" + entry.name;
3753
+ if (relative14 === ".codebase-snapshot" || IGNORABLE_DIRECTORY_ENTRIES.has(entry.name)) continue;
3582
3754
  if (entry.isDirectory()) {
3583
- stack.push(relative12);
3755
+ stack.push(relative14);
3584
3756
  continue;
3585
3757
  }
3586
3758
  if (!entry.isFile()) return false;
3587
- if (relative12 === "signature.json" && !recordedFiles.has(relative12) && verifySnapshotSignature(dir).ok) {
3759
+ if (relative14 === "signature.json" && !recordedFiles.has(relative14) && verifySnapshotSignature(dir).ok) {
3588
3760
  continue;
3589
3761
  }
3590
- if (!recordedFiles.has(relative12)) return false;
3762
+ if (!recordedFiles.has(relative14)) return false;
3591
3763
  }
3592
3764
  }
3593
3765
  return true;
@@ -3619,7 +3791,7 @@ function makeLinkProbe() {
3619
3791
  let known = cache.get(absolutePath);
3620
3792
  if (known === void 0) {
3621
3793
  try {
3622
- known = fs17__namespace.lstatSync(absolutePath).isSymbolicLink();
3794
+ known = fs18__namespace.lstatSync(absolutePath).isSymbolicLink();
3623
3795
  } catch {
3624
3796
  known = false;
3625
3797
  }
@@ -3632,7 +3804,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3632
3804
  const isLink = makeLinkProbe();
3633
3805
  let rootReal = cwd;
3634
3806
  try {
3635
- rootReal = fs17__namespace.realpathSync(cwd);
3807
+ rootReal = fs18__namespace.realpathSync(cwd);
3636
3808
  } catch {
3637
3809
  }
3638
3810
  const reported = /* @__PURE__ */ new Set();
@@ -3660,7 +3832,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3660
3832
  const rawTarget = readLinkTarget(absolute, absolute);
3661
3833
  let targetReal = null;
3662
3834
  try {
3663
- targetReal = fs17__namespace.realpathSync(absolute);
3835
+ targetReal = fs18__namespace.realpathSync(absolute);
3664
3836
  } catch {
3665
3837
  targetReal = null;
3666
3838
  }
@@ -3678,7 +3850,7 @@ function dropLinkedDirectories(cwd, candidates, skipped) {
3678
3850
  }
3679
3851
  let stats = null;
3680
3852
  try {
3681
- stats = fs17__namespace.statSync(absolute);
3853
+ stats = fs18__namespace.statSync(absolute);
3682
3854
  } catch {
3683
3855
  stats = null;
3684
3856
  }
@@ -3784,7 +3956,7 @@ function collectFiles(cwd, options = {}) {
3784
3956
  "Discovery mode is `git`, but git could not list this directory's files. Run inside a working repository, or pass --discovery walk (or auto) to scan the tree directly."
3785
3957
  );
3786
3958
  }
3787
- if (fs17__namespace.existsSync(path7__namespace.join(cwd, ".git"))) {
3959
+ if (fs18__namespace.existsSync(path7__namespace.join(cwd, ".git"))) {
3788
3960
  throw new Error(
3789
3961
  "This directory is a git repository, but git could not list its files. A plain walk honours .gitignore files, but git also applies .git/info/exclude and your global excludes file, includes files that are tracked although a .gitignore now matches them, and treats a submodule as a single entry. Fix the repository (git status should work), run outside git, or pass --discovery walk to accept those differences."
3790
3962
  );
@@ -3864,7 +4036,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3864
4036
  const aliases = /* @__PURE__ */ new Set();
3865
4037
  for (const file of files) {
3866
4038
  try {
3867
- if (fs17__namespace.lstatSync(path7__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
4039
+ if (fs18__namespace.lstatSync(path7__namespace.join(cwd, file)).isSymbolicLink()) aliases.add(file);
3868
4040
  } catch {
3869
4041
  }
3870
4042
  }
@@ -3873,7 +4045,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3873
4045
  for (const file of files) {
3874
4046
  if (aliases.has(file)) continue;
3875
4047
  try {
3876
- includedTargets.add(fs17__namespace.realpathSync(path7__namespace.join(cwd, file)));
4048
+ includedTargets.add(fs18__namespace.realpathSync(path7__namespace.join(cwd, file)));
3877
4049
  } catch {
3878
4050
  }
3879
4051
  }
@@ -3885,7 +4057,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3885
4057
  }
3886
4058
  let target;
3887
4059
  try {
3888
- target = fs17__namespace.realpathSync(path7__namespace.join(cwd, file));
4060
+ target = fs18__namespace.realpathSync(path7__namespace.join(cwd, file));
3889
4061
  } catch {
3890
4062
  skipped.push({ path: file, reason: "read-error", detail: "symlink target could not be resolved" });
3891
4063
  continue;
@@ -3904,7 +4076,7 @@ function dropSymlinksToUnincludedTargets(cwd, files, skipped) {
3904
4076
  }
3905
4077
  function rootRealFor(root) {
3906
4078
  try {
3907
- return fs17__namespace.realpathSync(root);
4079
+ return fs18__namespace.realpathSync(root);
3908
4080
  } catch {
3909
4081
  return root;
3910
4082
  }
@@ -3924,7 +4096,7 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3924
4096
  ];
3925
4097
  let entries;
3926
4098
  try {
3927
- entries = fs17__namespace.readdirSync(current, { withFileTypes: true });
4099
+ entries = fs18__namespace.readdirSync(current, { withFileTypes: true });
3928
4100
  } catch {
3929
4101
  results.skipped.push({
3930
4102
  path: relativeToBase(current),
@@ -3988,14 +4160,14 @@ function walkDirectory(dir, baseDir, rootReal, visited, reservedPaths = /* @__PU
3988
4160
  if (entry.isSymbolicLink()) {
3989
4161
  let targetReal;
3990
4162
  try {
3991
- targetReal = fs17__namespace.realpathSync(fullPath);
4163
+ targetReal = fs18__namespace.realpathSync(fullPath);
3992
4164
  } catch {
3993
4165
  results.skipped.push(brokenLinkRecord(fullPath, relPath, rootReal));
3994
4166
  continue;
3995
4167
  }
3996
4168
  let stats;
3997
4169
  try {
3998
- stats = fs17__namespace.statSync(fullPath);
4170
+ stats = fs18__namespace.statSync(fullPath);
3999
4171
  } catch {
4000
4172
  results.skipped.push({ path: relPath, reason: "read-error", detail: "unreadable symlink" });
4001
4173
  continue;
@@ -4263,6 +4435,17 @@ function assertServerSafeConfig(config, source = "The configuration") {
4263
4435
  source + " enables includeSensitiveFiles. The MCP and serve transports never emit sensitive files; remove that setting or run the CLI directly."
4264
4436
  );
4265
4437
  }
4438
+ if (config.cwd !== void 0) {
4439
+ if (typeof config.cwd !== "string" || config.cwd.trim() === "") {
4440
+ throw new Error(source + " has an invalid cwd; it must be a non-empty path string.");
4441
+ }
4442
+ const normalized = config.cwd.replace(/\\/g, "/");
4443
+ if (path7__namespace.isAbsolute(config.cwd) || normalized.split("/").includes("..")) {
4444
+ throw new Error(
4445
+ source + " sets cwd to " + config.cwd + ". The MCP and serve transports confine every run to the repository they were started for; remove cwd or make it a relative subdirectory."
4446
+ );
4447
+ }
4448
+ }
4266
4449
  if (config.secrets !== void 0 && config.secrets !== null) {
4267
4450
  if (config.secrets.disableDefaultPatterns === true) {
4268
4451
  throw new Error(
@@ -4354,20 +4537,25 @@ function normalizeResolvedConfig(config) {
4354
4537
  `maxPartBytes must be at least ${MIN_MAX_PART_BYTES} bytes (received ${String(config.maxPartBytes)}).`
4355
4538
  );
4356
4539
  }
4357
- if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 0) {
4540
+ if (!Number.isSafeInteger(config.largeFileBytes) || config.largeFileBytes < 1) {
4541
+ throw new Error(
4542
+ `largeFileBytes must be a positive integer; received ${String(config.largeFileBytes)}.`
4543
+ );
4544
+ }
4545
+ if (config.largeFileBytes > config.maxPartBytes) {
4358
4546
  throw new Error(
4359
- `largeFileBytes must be a non-negative integer; received ${String(config.largeFileBytes)}.`
4547
+ `largeFileBytes (${config.largeFileBytes} B) is larger than maxPartBytes (${config.maxPartBytes} B). Raise maxPartBytes, or lower largeFileBytes.`
4360
4548
  );
4361
4549
  }
4362
- const maxPartTokens = config.maxPartTokens ?? Math.floor(config.maxPartBytes / 4);
4363
- if (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS) {
4550
+ const maxPartTokens = config.maxPartTokens;
4551
+ if (maxPartTokens !== void 0 && (!Number.isSafeInteger(maxPartTokens) || maxPartTokens < MIN_MAX_PART_TOKENS)) {
4364
4552
  throw new Error(
4365
4553
  `maxPartTokens must be at least ${MIN_MAX_PART_TOKENS} tokens; received ${String(maxPartTokens)}.`
4366
4554
  );
4367
4555
  }
4368
4556
  return markResolvedConfig({
4369
4557
  ...config,
4370
- maxPartTokens,
4558
+ ...maxPartTokens === void 0 ? {} : { maxPartTokens },
4371
4559
  discovery,
4372
4560
  // A spread copy built before the field existed carries no value; the default applies, and it
4373
4561
  // is re-validated because the number reaches a rendered artifact.
@@ -4523,10 +4711,10 @@ function readConfigExport(exported, file) {
4523
4711
  var lastModuleConfig = null;
4524
4712
  function moduleConfigKey(fullPath) {
4525
4713
  try {
4526
- return crypto.createHash("sha256").update(fs17__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
4714
+ return crypto.createHash("sha256").update(fs18__namespace.readFileSync(fullPath)).digest("hex").slice(0, 24);
4527
4715
  } catch {
4528
4716
  try {
4529
- const stats = fs17__namespace.statSync(fullPath);
4717
+ const stats = fs18__namespace.statSync(fullPath);
4530
4718
  return `stat-${stats.mtimeMs}-${stats.size}`;
4531
4719
  } catch {
4532
4720
  return "unreadable";
@@ -4568,9 +4756,9 @@ async function loadConfigFileDetailed(cwd, options = {}) {
4568
4756
  const fullPath = path7__namespace.join(cwd, filename);
4569
4757
  let candidateStats = null;
4570
4758
  try {
4571
- candidateStats = fs17__namespace.statSync(fullPath);
4759
+ candidateStats = fs18__namespace.statSync(fullPath);
4572
4760
  } catch {
4573
- if (!fs17__namespace.existsSync(fullPath)) continue;
4761
+ if (!fs18__namespace.existsSync(fullPath)) continue;
4574
4762
  }
4575
4763
  if (candidateStats !== null && !candidateStats.isFile()) {
4576
4764
  configDirectories.push(fullPath);
@@ -4578,7 +4766,7 @@ async function loadConfigFileDetailed(cwd, options = {}) {
4578
4766
  }
4579
4767
  if (filename.endsWith(".json") || filename === ".snapshotrc") {
4580
4768
  try {
4581
- const config = parseJsonish(fs17__namespace.readFileSync(fullPath, "utf8"), fullPath);
4769
+ const config = parseJsonish(fs18__namespace.readFileSync(fullPath, "utf8"), fullPath);
4582
4770
  if (config === null || typeof config !== "object" || Array.isArray(config)) {
4583
4771
  throw new Error(
4584
4772
  `${fullPath} does not hold a configuration object (received ${describeValue2(config)}).`
@@ -4624,9 +4812,9 @@ async function loadConfigFileDetailed(cwd, options = {}) {
4624
4812
  }
4625
4813
  }
4626
4814
  const pkgJsonPath = path7__namespace.join(cwd, "package.json");
4627
- if (fs17__namespace.existsSync(pkgJsonPath)) {
4815
+ if (fs18__namespace.existsSync(pkgJsonPath)) {
4628
4816
  try {
4629
- const parsed = parseJsonish(fs17__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
4817
+ const parsed = parseJsonish(fs18__namespace.readFileSync(pkgJsonPath, "utf8"), pkgJsonPath);
4630
4818
  const snapshotKey = parsed.snapshot;
4631
4819
  if (snapshotKey && typeof snapshotKey === "object" && !Array.isArray(snapshotKey)) {
4632
4820
  assertKnownConfigKeys(
@@ -4798,7 +4986,7 @@ function readConfiguredBrief(cwd, value) {
4798
4986
  }
4799
4987
  const rootReal = (() => {
4800
4988
  try {
4801
- return fs17__namespace.realpathSync(cwd);
4989
+ return fs18__namespace.realpathSync(cwd);
4802
4990
  } catch {
4803
4991
  return path7__namespace.resolve(cwd);
4804
4992
  }
@@ -4806,19 +4994,19 @@ function readConfiguredBrief(cwd, value) {
4806
4994
  const requested = path7__namespace.resolve(cwd, value);
4807
4995
  let filePath;
4808
4996
  try {
4809
- filePath = fs17__namespace.realpathSync(requested);
4997
+ filePath = fs18__namespace.realpathSync(requested);
4810
4998
  } catch {
4811
4999
  throw new Error(
4812
5000
  'brief "' + value + '" could not be read as a file; a snapshot must not ship without the half of the brief the owner wrote.'
4813
5001
  );
4814
5002
  }
4815
- const relative12 = path7__namespace.relative(rootReal, filePath);
4816
- if (relative12.length === 0 || relative12 === ".." || relative12.startsWith(`..${path7__namespace.sep}`) || path7__namespace.isAbsolute(relative12)) {
5003
+ const relative14 = path7__namespace.relative(rootReal, filePath);
5004
+ if (relative14.length === 0 || relative14 === ".." || relative14.startsWith(`..${path7__namespace.sep}`) || path7__namespace.isAbsolute(relative14)) {
4817
5005
  throw new Error(
4818
5006
  'brief "' + value + '" resolves outside the repository. A brief must be a file inside the repository being described; an absolute or parent path is refused.'
4819
5007
  );
4820
5008
  }
4821
- const posixRelative = relative12.split(path7__namespace.sep).join("/");
5009
+ const posixRelative = relative14.split(path7__namespace.sep).join("/");
4822
5010
  if (isSensitivePath(posixRelative) || isSensitivePath(value)) {
4823
5011
  throw new Error(
4824
5012
  'brief "' + value + '" is a credential-bearing file. A snapshot must not reproduce secrets, so it cannot be used as the owner brief.'
@@ -4832,14 +5020,14 @@ function readConfiguredBrief(cwd, value) {
4832
5020
  }
4833
5021
  let text;
4834
5022
  try {
4835
- const stats = fs17__namespace.statSync(filePath);
5023
+ const stats = fs18__namespace.statSync(filePath);
4836
5024
  if (!stats.isFile()) throw new Error("not a file");
4837
5025
  if (stats.size > MAX_BRIEF_BYTES) {
4838
5026
  throw new Error(
4839
5027
  'brief "' + value + '" is ' + stats.size + " bytes; the limit is " + MAX_BRIEF_BYTES + ". Keep it to what a reader can act on, or move the detail into a document the snapshot carries."
4840
5028
  );
4841
5029
  }
4842
- text = fs17__namespace.readFileSync(filePath, "utf8");
5030
+ text = fs18__namespace.readFileSync(filePath, "utf8");
4843
5031
  } catch (error) {
4844
5032
  if (error instanceof Error && error.message.startsWith('brief "')) throw error;
4845
5033
  throw new Error(
@@ -4966,11 +5154,11 @@ function outputExcludePatterns(cwd, outDir, tmpDir) {
4966
5154
  const patterns = [];
4967
5155
  for (const dir of [outDir, tmpDir]) {
4968
5156
  const absolute = path7__namespace.resolve(cwd, dir);
4969
- const relative12 = path7__namespace.relative(cwd, absolute);
4970
- if (!relative12 || relative12 === ".." || relative12.startsWith(`..${path7__namespace.sep}`) || path7__namespace.isAbsolute(relative12)) {
5157
+ const relative14 = path7__namespace.relative(cwd, absolute);
5158
+ if (!relative14 || relative14 === ".." || relative14.startsWith(`..${path7__namespace.sep}`) || path7__namespace.isAbsolute(relative14)) {
4971
5159
  continue;
4972
5160
  }
4973
- patterns.push(`${relative12.replace(/\\/g, "/")}/**`);
5161
+ patterns.push(`${relative14.replace(/\\/g, "/")}/**`);
4974
5162
  }
4975
5163
  return patterns;
4976
5164
  }
@@ -5108,10 +5296,10 @@ function resolveCandidateCwd(userConfig, cliOptions, baseDir) {
5108
5296
  }
5109
5297
  const candidate = cliOptions?.cwd || userConfig?.cwd || baseDir || process.cwd();
5110
5298
  const resolved = path7__namespace.resolve(candidate);
5111
- if (!fs17__namespace.existsSync(resolved)) {
5299
+ if (!fs18__namespace.existsSync(resolved)) {
5112
5300
  throw new Error(`Working directory does not exist: ${resolved}`);
5113
5301
  }
5114
- if (!fs17__namespace.statSync(resolved).isDirectory()) {
5302
+ if (!fs18__namespace.statSync(resolved).isDirectory()) {
5115
5303
  throw new Error(`Working directory is not a directory: ${resolved}`);
5116
5304
  }
5117
5305
  return resolved;
@@ -5265,10 +5453,10 @@ function resolveConfig(userConfig, cliOptions, baseDir) {
5265
5453
  outDir,
5266
5454
  tmpDir,
5267
5455
  maxPartBytes: resolvedMaxPartBytes,
5268
- // Record the effective value even when the user did not set it. normalizeResolvedConfig
5269
- // derives it for the manifest; leaving validate's fresh resolution unset made a clean
5270
- // snapshot report a configuration mismatch.
5271
- maxPartTokens: maxPartTokens ?? Math.floor(resolvedMaxPartBytes / 4),
5456
+ // Record only the token ceiling the user named. The byte budget is the enforced limit; a
5457
+ // derived token number is an estimate, and writing it into the manifest made a default run
5458
+ // look like it had chosen one.
5459
+ ...maxPartTokens === void 0 ? {} : { maxPartTokens },
5272
5460
  largeFileBytes: largeFileBytesFor(resolvedMaxPartBytes, cliOptions, userConfig),
5273
5461
  previewHeadLines: strictPositiveInteger(userConfig?.previewHeadLines, 80, "`previewHeadLines`"),
5274
5462
  previewTailLines: strictPositiveInteger(userConfig?.previewTailLines, 40, "`previewTailLines`"),
@@ -5385,7 +5573,7 @@ function configDigest(config) {
5385
5573
  // The user's own unit. `maxPartBytes` above already reflects the converted ceiling, but
5386
5574
  // recording the token number means changing 32k to 64k moves the digest even in the
5387
5575
  // corner where both round to the same byte budget.
5388
- maxPartTokens: config.maxPartTokens ?? null,
5576
+ maxPartTokens: config.maxPartTokens === void 0 || config.maxPartTokens === Math.floor(config.maxPartBytes / 4) ? null : config.maxPartTokens,
5389
5577
  // A changed-files scope decides which files are in the snapshot at all, so a snapshot
5390
5578
  // taken over a different scope is a different snapshot.
5391
5579
  changedSince: config.changedSince ?? null,
@@ -5776,9 +5964,9 @@ var JAVA_METHOD = /^\s+(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)
5776
5964
  var jvmProfile = {
5777
5965
  id: "jvm",
5778
5966
  extensions: [".java", ".kt", ".kts", ".scala"],
5779
- summarize(path21, content) {
5967
+ summarize(path22, content) {
5780
5968
  const summary = emptySummary();
5781
- const lower = path21.toLowerCase();
5969
+ const lower = path22.toLowerCase();
5782
5970
  const isJava = lower.endsWith(".java");
5783
5971
  const isKotlin = lower.endsWith(".kt") || lower.endsWith(".kts");
5784
5972
  eachLine(content, (line) => {
@@ -6001,9 +6189,9 @@ var rubyProfile = {
6001
6189
  eachLine(content, (line) => {
6002
6190
  const trimmed = line.trim();
6003
6191
  if (!trimmed || trimmed.startsWith("#")) return;
6004
- const relative12 = REQUIRE_RELATIVE.exec(trimmed);
6005
- if (relative12) {
6006
- summary.imports.push(`./${relative12[1]}`);
6192
+ const relative14 = REQUIRE_RELATIVE.exec(trimmed);
6193
+ if (relative14) {
6194
+ summary.imports.push(`./${relative14[1]}`);
6007
6195
  return;
6008
6196
  }
6009
6197
  const required = REQUIRE.exec(trimmed);
@@ -6552,17 +6740,17 @@ function summarizeTypeScriptSource(relativePath, content) {
6552
6740
  var SCRIPT_BLOCK = /<script([^>]*)>([\s\S]*?)<\/script(?:\s[^>]*)?>/gi;
6553
6741
  var JSX_LANG = /\blang\s*=\s*["']?[tj]sx\b/i;
6554
6742
  var ASTRO_FRONTMATTER = /^\uFEFF?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?=\r?\n|$)/;
6555
- function componentName(path21) {
6556
- const base = path21.split("/").pop() ?? path21;
6743
+ function componentName(path22) {
6744
+ const base = path22.split("/").pop() ?? path22;
6557
6745
  return base.replace(/\.[^.]+$/, "");
6558
6746
  }
6559
6747
  var sfcProfile = {
6560
6748
  id: "sfc",
6561
6749
  extensions: [".vue", ".svelte", ".astro"],
6562
- summarize(path21, content) {
6750
+ summarize(path22, content) {
6563
6751
  let script = "";
6564
- let usesJsx = path21.toLowerCase().endsWith(".astro");
6565
- if (path21.toLowerCase().endsWith(".astro")) {
6752
+ let usesJsx = path22.toLowerCase().endsWith(".astro");
6753
+ if (path22.toLowerCase().endsWith(".astro")) {
6566
6754
  const frontmatter = ASTRO_FRONTMATTER.exec(content);
6567
6755
  if (frontmatter) script += `${frontmatter[1]}
6568
6756
  `;
@@ -6572,7 +6760,7 @@ var sfcProfile = {
6572
6760
  script += `${match[2]}
6573
6761
  `;
6574
6762
  }
6575
- const name = componentName(path21);
6763
+ const name = componentName(path22);
6576
6764
  if (!script.trim()) {
6577
6765
  const summary2 = emptySummary();
6578
6766
  if (name) {
@@ -6763,15 +6951,15 @@ for (const profile of LANGUAGE_PROFILES) {
6763
6951
  BY_EXTENSION.set(extension.toLowerCase(), profile);
6764
6952
  }
6765
6953
  }
6766
- function profileForPath(path21) {
6767
- const lower = path21.toLowerCase();
6954
+ function profileForPath(path22) {
6955
+ const lower = path22.toLowerCase();
6768
6956
  const dot = lower.lastIndexOf(".");
6769
6957
  if (dot === -1) return null;
6770
6958
  return BY_EXTENSION.get(lower.slice(dot)) ?? null;
6771
6959
  }
6772
- function summarizeWithProfile(path21, content) {
6773
- const profile = profileForPath(path21);
6774
- return profile ? profile.summarize(path21, content) : null;
6960
+ function summarizeWithProfile(path22, content) {
6961
+ const profile = profileForPath(path22);
6962
+ return profile ? profile.summarize(path22, content) : null;
6775
6963
  }
6776
6964
  var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
6777
6965
  ".png",
@@ -6983,13 +7171,13 @@ function isBinaryFile(absolutePath) {
6983
7171
  if (isBinaryExtension(absolutePath)) return true;
6984
7172
  let fd;
6985
7173
  try {
6986
- fd = fs17__namespace.openSync(absolutePath, "r");
7174
+ fd = fs18__namespace.openSync(absolutePath, "r");
6987
7175
  const buffer = Buffer.alloc(CHUNK);
6988
7176
  let sample;
6989
7177
  let position = 0;
6990
7178
  while (position < BINARY_SCAN_BYTES) {
6991
7179
  const wanted = Math.min(CHUNK, BINARY_SCAN_BYTES - position);
6992
- const bytesRead = fs17__namespace.readSync(fd, buffer, 0, wanted, position);
7180
+ const bytesRead = fs18__namespace.readSync(fd, buffer, 0, wanted, position);
6993
7181
  if (bytesRead === 0) return false;
6994
7182
  const chunk = buffer.subarray(0, bytesRead);
6995
7183
  if (sample === void 0) {
@@ -7007,7 +7195,7 @@ function isBinaryFile(absolutePath) {
7007
7195
  } finally {
7008
7196
  if (fd !== void 0) {
7009
7197
  try {
7010
- fs17__namespace.closeSync(fd);
7198
+ fs18__namespace.closeSync(fd);
7011
7199
  } catch {
7012
7200
  }
7013
7201
  }
@@ -7205,13 +7393,16 @@ var TOKEN_LINE_SLACK = 32;
7205
7393
  function truncateWithBudgetMarker(content, maxBytes, budget, originalLines) {
7206
7394
  const base = content.replace(BUDGET_MARKER_SUFFIX, "");
7207
7395
  const truncated = truncateToBytes(base, Math.max(0, maxBytes));
7208
- if (!truncated.isTruncated) return { content: base, isTruncated: false };
7396
+ if (!truncated.isTruncated) return { content: base, isTruncated: false, cutMidLine: false };
7209
7397
  const keptLines = countLines(truncated.content);
7210
7398
  const omitted = Math.max(1, Math.max(countLines(base), originalLines) - keptLines);
7399
+ const next = base[truncated.content.length];
7400
+ const cutMidLine = next !== void 0 && next !== "\n" && next !== "\r";
7401
+ const separator = truncated.content.endsWith("\n") || truncated.content.endsWith("\r") ? "" : "\n";
7211
7402
  return {
7212
- content: `${truncated.content}
7213
- ... [${omitted} lines omitted: part budget ${budget} B] ...`,
7214
- isTruncated: true
7403
+ content: `${truncated.content}${separator}... [${omitted} lines omitted: part budget ${budget} B] ...`,
7404
+ isTruncated: true,
7405
+ cutMidLine
7215
7406
  };
7216
7407
  }
7217
7408
  function partitionFiles(files, maxPartBytes, contentFingerprint) {
@@ -7283,7 +7474,7 @@ function partitionFilesForBuckets(buckets, contentFingerprint) {
7283
7474
  section.file.originalLines
7284
7475
  );
7285
7476
  if (shrunk.isTruncated) {
7286
- applyTruncatedContent(section.file, shrunk.content, "part-budget");
7477
+ applyTruncatedContent(section.file, shrunk.content, "part-budget", shrunk.cutMidLine);
7287
7478
  section.text = renderFileSection(section.file);
7288
7479
  section.byteSize = Buffer.byteLength(section.text, "utf8");
7289
7480
  assemblies.delete(group);
@@ -7357,7 +7548,7 @@ function prepareSection(file, sectionBudget, partBudget) {
7357
7548
  file.originalLines
7358
7549
  );
7359
7550
  if (!truncated.isTruncated) return;
7360
- applyTruncatedContent(file, truncated.content, "part-budget");
7551
+ applyTruncatedContent(file, truncated.content, "part-budget", truncated.cutMidLine);
7361
7552
  text = renderFileSection(file);
7362
7553
  byteSize = Buffer.byteLength(text, "utf8");
7363
7554
  };
@@ -7424,7 +7615,7 @@ function fenceIsOpen(text, fence) {
7424
7615
  return open;
7425
7616
  }
7426
7617
  var OMISSION_NOTICE_LINE = /^\.\.\. \[\d+ lines omitted: [^\]]*\] \.\.\.$/;
7427
- function applyTruncatedContent(file, content, reason) {
7618
+ function applyTruncatedContent(file, content, reason, cutMidLine = false) {
7428
7619
  const keptLines = content.split("\n").filter(
7429
7620
  (line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE
7430
7621
  ).length;
@@ -7437,22 +7628,26 @@ function applyTruncatedContent(file, content, reason) {
7437
7628
  const noticeAt = lines.findIndex(
7438
7629
  (line) => OMISSION_NOTICE_LINE.test(line) || line.trim() === SECTION_TRUNCATION_NOTICE
7439
7630
  );
7440
- if (noticeAt >= 0 && priorGap !== void 0 && priorGap.length === 1 && priorGap[0] !== void 0) {
7631
+ if (noticeAt >= 0 && priorGap !== void 0 && priorGap.length >= 1 && priorGap[0] !== void 0) {
7441
7632
  const headKept = lines.slice(0, noticeAt).filter((line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE).length;
7442
7633
  const tailKept = lines.slice(noticeAt + 1).filter((line) => !OMISSION_NOTICE_LINE.test(line) && line.trim() !== SECTION_TRUNCATION_NOTICE).length;
7443
7634
  const gapEnd = priorGap[0][1];
7444
- const headStart = Math.min(file.originalLines, headKept + 1);
7635
+ const headStart = Math.min(
7636
+ file.originalLines,
7637
+ cutMidLine ? Math.max(1, headKept) : headKept + 1
7638
+ );
7445
7639
  const ranges = [];
7446
7640
  if (tailKept === 0) {
7447
7641
  ranges.push([headStart, file.originalLines]);
7448
7642
  } else {
7449
7643
  if (headStart <= gapEnd) ranges.push([headStart, gapEnd]);
7450
- const tailStart = gapEnd + tailKept + 1;
7644
+ const tailStart = cutMidLine ? gapEnd + tailKept : gapEnd + tailKept + 1;
7451
7645
  if (tailStart <= file.originalLines) ranges.push([tailStart, file.originalLines]);
7452
7646
  }
7453
7647
  file.omittedRanges = ranges.length === 0 ? [[file.originalLines, file.originalLines]] : ranges;
7454
7648
  } else {
7455
- file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[keptLines + 1, file.originalLines]];
7649
+ const firstOmitted = cutMidLine ? Math.max(1, keptLines) : keptLines + 1;
7650
+ file.omittedRanges = keptLines >= file.originalLines ? file.originalLines > 0 ? [[file.originalLines, file.originalLines]] : [] : [[Math.min(firstOmitted, file.originalLines), file.originalLines]];
7456
7651
  }
7457
7652
  file.includedBytes = Buffer.byteLength(content, "utf8");
7458
7653
  file.includedLines = countBodyLines(content);
@@ -7663,8 +7858,8 @@ var MAX_CONFIG_BYTES = 4 * 1024 * 1024;
7663
7858
  var MAX_PACKAGE_BYTES = 1 * 1024 * 1024;
7664
7859
  function repositoryRelative(cwd, target) {
7665
7860
  const absolute = path7__namespace.isAbsolute(target) ? target : path7__namespace.resolve(cwd, target);
7666
- const relative12 = path7__namespace.relative(cwd, absolute).replace(/\\/g, "/");
7667
- return relative12.length === 0 || relative12 !== ".." && !relative12.startsWith(".." + path7__namespace.sep) && !relative12.startsWith("../") && !path7__namespace.isAbsolute(relative12) ? relative12 : null;
7861
+ const relative14 = path7__namespace.relative(cwd, absolute).replace(/\\/g, "/");
7862
+ return relative14.length === 0 || relative14 !== ".." && !relative14.startsWith(".." + path7__namespace.sep) && !relative14.startsWith("../") && !path7__namespace.isAbsolute(relative14) ? relative14 : null;
7668
7863
  }
7669
7864
  function insideCwd(cwd, file) {
7670
7865
  return repositoryRelative(cwd, file);
@@ -7720,8 +7915,8 @@ function parseImports(value) {
7720
7915
  return Object.entries(record).filter(([key]) => key.startsWith("#")).map(([pattern, target]) => ({ pattern, targets: targetList(target) }));
7721
7916
  }
7722
7917
  function readPackageJson(cwd, packageDir) {
7723
- const relative12 = packageDir.length === 0 ? "package.json" : packageDir + "/package.json";
7724
- const parsed = asRecord(readJson(cwd, relative12, MAX_PACKAGE_BYTES));
7918
+ const relative14 = packageDir.length === 0 ? "package.json" : packageDir + "/package.json";
7919
+ const parsed = asRecord(readJson(cwd, relative14, MAX_PACKAGE_BYTES));
7725
7920
  if (parsed === null) return null;
7726
7921
  const exportsMap = parseExports(parsed.exports);
7727
7922
  if (exportsMap.length === 0) {
@@ -7763,18 +7958,18 @@ function parsePnpmWorkspace(cwd) {
7763
7958
  }
7764
7959
  function listChildDirectories(cwd, relativeDir) {
7765
7960
  const absolute = path7__namespace.resolve(cwd, relativeDir);
7766
- const relative12 = repositoryRelative(cwd, absolute);
7767
- if (relative12 === null) return [];
7961
+ const relative14 = repositoryRelative(cwd, absolute);
7962
+ if (relative14 === null) return [];
7768
7963
  let entries;
7769
7964
  try {
7770
- entries = fs17__namespace.readdirSync(absolute === cwd ? cwd : absolute, { withFileTypes: true });
7965
+ entries = fs18__namespace.readdirSync(absolute === cwd ? cwd : absolute, { withFileTypes: true });
7771
7966
  } catch {
7772
7967
  return [];
7773
7968
  }
7774
7969
  const out = [];
7775
7970
  for (const entry of entries) {
7776
7971
  if (!entry.isDirectory()) continue;
7777
- const child = relative12.length === 0 ? entry.name : relative12 + "/" + entry.name;
7972
+ const child = relative14.length === 0 ? entry.name : relative14 + "/" + entry.name;
7778
7973
  if (child.split("/").includes("node_modules")) continue;
7779
7974
  out.push(child);
7780
7975
  }
@@ -7787,15 +7982,15 @@ function expandWorkspacePattern(cwd, rawPattern) {
7787
7982
  if (pattern.endsWith("/*")) {
7788
7983
  const base = pattern.slice(0, -2);
7789
7984
  return listChildDirectories(cwd, base).filter(
7790
- (dir) => fs17__namespace.existsSync(path7__namespace.join(cwd, dir, "package.json"))
7985
+ (dir) => fs18__namespace.existsSync(path7__namespace.join(cwd, dir, "package.json"))
7791
7986
  );
7792
7987
  }
7793
7988
  if (pattern.includes("*")) {
7794
7989
  const base = path7__namespace.posix.dirname(pattern);
7795
7990
  const direct = listChildDirectories(cwd, base === "." ? "" : base);
7796
- return direct.filter((dir) => fs17__namespace.existsSync(path7__namespace.join(cwd, dir, "package.json")));
7991
+ return direct.filter((dir) => fs18__namespace.existsSync(path7__namespace.join(cwd, dir, "package.json")));
7797
7992
  }
7798
- return fs17__namespace.existsSync(path7__namespace.join(cwd, pattern, "package.json")) ? [pattern] : [];
7993
+ return fs18__namespace.existsSync(path7__namespace.join(cwd, pattern, "package.json")) ? [pattern] : [];
7799
7994
  }
7800
7995
  function workspaceDirectories(cwd, files) {
7801
7996
  const root = asRecord(readJson(cwd, "package.json", MAX_PACKAGE_BYTES));
@@ -7894,7 +8089,7 @@ function configCandidates(cwd, files, packageDirs) {
7894
8089
  for (const dir of packageDirs) {
7895
8090
  for (const base of ["tsconfig.json", "jsconfig.json"]) {
7896
8091
  const candidate = dir.length === 0 ? base : dir + "/" + base;
7897
- if (fs17__namespace.existsSync(path7__namespace.join(cwd, candidate))) candidates.add(candidate);
8092
+ if (fs18__namespace.existsSync(path7__namespace.join(cwd, candidate))) candidates.add(candidate);
7898
8093
  }
7899
8094
  }
7900
8095
  for (const relativePath of files) {
@@ -7903,14 +8098,14 @@ function configCandidates(cwd, files, packageDirs) {
7903
8098
  while (dir !== "." && dir.length > 0) {
7904
8099
  for (const base of ["tsconfig.json", "jsconfig.json"]) {
7905
8100
  const candidate = dir + "/" + base;
7906
- if (fs17__namespace.existsSync(path7__namespace.join(cwd, candidate))) candidates.add(candidate);
8101
+ if (fs18__namespace.existsSync(path7__namespace.join(cwd, candidate))) candidates.add(candidate);
7907
8102
  }
7908
8103
  dir = path7__namespace.posix.dirname(dir);
7909
8104
  }
7910
8105
  }
7911
8106
  return [...candidates].filter((relativePath) => {
7912
- if (!fs17__namespace.existsSync(path7__namespace.join(cwd, relativePath))) return false;
7913
- const stat = fs17__namespace.lstatSync(path7__namespace.join(cwd, relativePath));
8107
+ if (!fs18__namespace.existsSync(path7__namespace.join(cwd, relativePath))) return false;
8108
+ const stat = fs18__namespace.lstatSync(path7__namespace.join(cwd, relativePath));
7914
8109
  return stat.isFile() && !stat.isSymbolicLink();
7915
8110
  }).slice(0, MAX_CONFIG_FILES * 2);
7916
8111
  }
@@ -8333,12 +8528,12 @@ function planForQuestion(manifest, question, options = {}) {
8333
8528
  const scored = [];
8334
8529
  for (const file of manifest.files) {
8335
8530
  if (isTest(file) && !wantsTests) continue;
8336
- const path21 = file.relativePath.toLowerCase();
8337
- const words = path21.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
8531
+ const path22 = file.relativePath.toLowerCase();
8532
+ const words = path22.split(/[^a-z0-9_]+/).filter((word) => word.length >= 3);
8338
8533
  let score = 0;
8339
8534
  const reasons = [];
8340
8535
  for (const term of terms) {
8341
- if (path21.includes(term)) {
8536
+ if (path22.includes(term)) {
8342
8537
  score += 8;
8343
8538
  reasons.push("path:" + term);
8344
8539
  continue;
@@ -8636,6 +8831,7 @@ function resolveDiffChangedLines(cwd, ref, files) {
8636
8831
  "--no-color",
8637
8832
  "--no-ext-diff",
8638
8833
  "--no-renames",
8834
+ "--relative",
8639
8835
  base,
8640
8836
  ...files === void 0 || files.length === 0 ? [] : ["--", ...files]
8641
8837
  ];
@@ -8663,8 +8859,8 @@ function resolveDiffChangedLines(cwd, ref, files) {
8663
8859
  continue;
8664
8860
  }
8665
8861
  const withoutPrefix = raw.startsWith("b/") ? raw.slice(2) : raw;
8666
- const path21 = withoutPrefix.split(" ")[0];
8667
- current = path21.length > 0 ? path21 : null;
8862
+ const path22 = withoutPrefix.split(" ")[0];
8863
+ current = path22.length > 0 ? path22 : null;
8668
8864
  if (current !== null && !ranges.has(current)) ranges.set(current, []);
8669
8865
  continue;
8670
8866
  }
@@ -8693,11 +8889,11 @@ function resolveChangedScope(cwd, request) {
8693
8889
  if (request.changedSince !== void 0) {
8694
8890
  assertUsableRef(request.changedSince);
8695
8891
  if (request.changedSince === "HEAD" && !hasHeadCommit(cwd)) {
8696
- for (const path21 of gitPaths(cwd, ["ls-files", "--cached", "-z", "--"])) {
8697
- paths.add(path21);
8892
+ for (const path22 of gitPaths(cwd, ["ls-files", "--cached", "-z", "--"])) {
8893
+ paths.add(path22);
8698
8894
  }
8699
- for (const path21 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8700
- paths.add(path21);
8895
+ for (const path22 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8896
+ paths.add(path22);
8701
8897
  }
8702
8898
  descriptions.push("changed since HEAD (unborn)");
8703
8899
  } else {
@@ -8710,7 +8906,7 @@ function resolveChangedScope(cwd, request) {
8710
8906
  );
8711
8907
  }
8712
8908
  if (base !== null) {
8713
- for (const path21 of gitPaths(cwd, [
8909
+ for (const path22 of gitPaths(cwd, [
8714
8910
  "-c",
8715
8911
  "core.quotepath=false",
8716
8912
  "-c",
@@ -8727,17 +8923,17 @@ function resolveChangedScope(cwd, request) {
8727
8923
  base,
8728
8924
  "--"
8729
8925
  ])) {
8730
- paths.add(path21);
8926
+ paths.add(path22);
8731
8927
  }
8732
8928
  }
8733
- for (const path21 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8734
- paths.add(path21);
8929
+ for (const path22 of gitPaths(cwd, ["ls-files", "--others", "--exclude-standard", "-z", "--"])) {
8930
+ paths.add(path22);
8735
8931
  }
8736
8932
  descriptions.push(`changed since ${request.changedSince}`);
8737
8933
  }
8738
8934
  }
8739
8935
  if (request.staged === true) {
8740
- for (const path21 of gitPaths(cwd, [
8936
+ for (const path22 of gitPaths(cwd, [
8741
8937
  "-c",
8742
8938
  "core.quotepath=false",
8743
8939
  "diff",
@@ -8748,10 +8944,10 @@ function resolveChangedScope(cwd, request) {
8748
8944
  "--no-renames",
8749
8945
  "--"
8750
8946
  ])) {
8751
- paths.add(path21);
8752
- stagedPaths.add(path21);
8947
+ paths.add(path22);
8948
+ stagedPaths.add(path22);
8753
8949
  }
8754
- for (const path21 of gitPaths(cwd, [
8950
+ for (const path22 of gitPaths(cwd, [
8755
8951
  "-c",
8756
8952
  "core.quotepath=false",
8757
8953
  "diff",
@@ -8763,7 +8959,7 @@ function resolveChangedScope(cwd, request) {
8763
8959
  "--diff-filter=D",
8764
8960
  "--"
8765
8961
  ])) {
8766
- deletedPaths.add(path21);
8962
+ deletedPaths.add(path22);
8767
8963
  }
8768
8964
  descriptions.push("staged");
8769
8965
  }
@@ -8967,8 +9163,8 @@ function describeManifestShapeProblem(value) {
8967
9163
  }
8968
9164
  }
8969
9165
  const lines = fields.lines;
8970
- if (fields.includedLines > lines) {
8971
- return 'an "incomplete" entry "includedLines" exceeds its "lines"';
9166
+ if (fields.includedLines > lines + 1) {
9167
+ return 'an "incomplete" entry "includedLines" exceeds its "lines" by more than the notice line';
8972
9168
  }
8973
9169
  const ranges = fields.omittedRanges;
8974
9170
  if (!Array.isArray(ranges)) return 'an "incomplete" entry has no "omittedRanges" array';
@@ -9123,11 +9319,11 @@ var MAX_LINE_BYTES = 32 * 1024 * 1024;
9123
9319
  function createWriter(output) {
9124
9320
  return {
9125
9321
  write(value) {
9126
- return new Promise((resolve14, reject) => {
9322
+ return new Promise((resolve15, reject) => {
9127
9323
  output.write(`${JSON.stringify(value)}
9128
9324
  `, (error) => {
9129
9325
  if (error) reject(error);
9130
- else resolve14();
9326
+ else resolve15();
9131
9327
  });
9132
9328
  });
9133
9329
  }
@@ -9435,7 +9631,15 @@ function resolveImpactChanges(cwd, request) {
9435
9631
  throw new Error("impact needs --diff <ref> or --paths <path,...>.");
9436
9632
  }
9437
9633
  function isTestPath(filePath) {
9438
- return /\.(test|spec)\.[a-z0-9]+$/i.test(filePath);
9634
+ const base = filePath.slice(filePath.lastIndexOf("/") + 1);
9635
+ return (
9636
+ // Jest/Vitest/Mocha and their Ruby equivalents.
9637
+ /\.(?:test|spec)\.[a-z0-9]+$/i.test(base) || // Python: test_auth.py, auth_test.py, auth_tests.py.
9638
+ /^test_.*\.py$/i.test(base) || /_tests?\.py$/i.test(base) || // Go and Rust put the suffix before the extension.
9639
+ /_test\.(?:go|rs|exs?)$/i.test(base) || // Ruby spec files.
9640
+ /_spec\.rb$/i.test(base) || // JUnit/NUnit/XCTest/PHPUnit class names.
9641
+ /(?:Test|Tests)\.(?:java|kt|cs|swift|php)$/.test(base)
9642
+ );
9439
9643
  }
9440
9644
  function isTestSupportPath(filePath) {
9441
9645
  return !isTestPath(filePath) && /(^|\/)(tests?|__tests__|spec)\//.test(filePath);
@@ -9487,10 +9691,10 @@ function internalSpecifier(specifier, resolver) {
9487
9691
  }
9488
9692
  function manifestLabel(cwd, manifestPath) {
9489
9693
  if (manifestPath === void 0) return "manifest.json";
9490
- const relative12 = path7__namespace.relative(cwd, manifestPath).replace(/\\/g, "/");
9491
- if (relative12.length === 0) return "manifest.json";
9492
- if (relative12.startsWith("../") || path7__namespace.isAbsolute(relative12)) return path7__namespace.basename(manifestPath);
9493
- return relative12;
9694
+ const relative14 = path7__namespace.relative(cwd, manifestPath).replace(/\\/g, "/");
9695
+ if (relative14.length === 0) return "manifest.json";
9696
+ if (relative14.startsWith("../") || path7__namespace.isAbsolute(relative14)) return path7__namespace.basename(manifestPath);
9697
+ return relative14;
9494
9698
  }
9495
9699
  function isPureBarrel(summary, file) {
9496
9700
  if (summary.parseErrors !== void 0 && summary.parseErrors > 0) return false;
@@ -9540,18 +9744,20 @@ function matchEdge(fromSummary, fromFile, specifier, incoming) {
9540
9744
  const named = reExports2.filter(
9541
9745
  (binding) => binding.kind !== "star" && binding.kind !== "namespace"
9542
9746
  );
9543
- if (named.length > 0) {
9747
+ const onlyNamedReExports = reExports2.every((binding) => binding.kind === "named");
9748
+ if (named.length > 0 && imports2.length === 0 && onlyNamedReExports) {
9544
9749
  const next2 = /* @__PURE__ */ new Set();
9545
9750
  for (const binding of named) {
9546
9751
  for (const entry of binding.entries ?? []) next2.add(entry.exported);
9547
9752
  }
9548
9753
  if (next2.size > 0) {
9754
+ const typeOnly = named.every((binding) => binding.typeOnly);
9549
9755
  return {
9550
9756
  fired: true,
9551
- kind: "reexport",
9757
+ kind: typeOnly ? "type-only" : "reexport",
9552
9758
  next: next2,
9553
9759
  matched: [...next2].sort((left, right) => left.localeCompare(right)),
9554
- typeOnly: named.every((binding) => binding.typeOnly)
9760
+ typeOnly
9555
9761
  };
9556
9762
  }
9557
9763
  }
@@ -9742,7 +9948,7 @@ function computeImpact(input) {
9742
9948
  );
9743
9949
  const skippedByPath = new Map(manifest.skipped.map((skip) => [skip.path, skip]));
9744
9950
  const changed = input.changes.paths.map((changedPath) => {
9745
- const deleted2 = !fs17__namespace.existsSync(path7__namespace.resolve(input.cwd, changedPath));
9951
+ const deleted2 = !fs18__namespace.existsSync(path7__namespace.resolve(input.cwd, changedPath));
9746
9952
  const direct = filesByPath.get(changedPath);
9747
9953
  if (direct !== void 0) return { path: direct.relativePath, inSnapshot: true, deleted: deleted2 };
9748
9954
  const folded = filesByFoldedPath.get(changedPath.toLowerCase());
@@ -9838,7 +10044,7 @@ function computeImpact(input) {
9838
10044
  const widened = !(previous.has("*") && merged.size === previous.size) && !(previous.size === merged.size && [...merged].every((name) => previous.has(name)));
9839
10045
  if (widened) {
9840
10046
  visitedSymbols.set(edge.from, merged);
9841
- if (match.kind !== "type-only") {
10047
+ if (match.kind !== "type-only" || fromSummary !== null && isPureBarrel(fromSummary, fromFile)) {
9842
10048
  queue.push({ path: edge.from, symbols: merged, distance: current.distance + 1 });
9843
10049
  }
9844
10050
  }
@@ -9887,8 +10093,8 @@ function computeImpact(input) {
9887
10093
  }
9888
10094
  }
9889
10095
  const impacted = /* @__PURE__ */ new Set([...changedSet, ...affected.keys()]);
9890
- for (const path21 of visitedSymbols.keys()) {
9891
- if (!isTestPath(path21) && !isTestSupportPath(path21)) impacted.add(path21);
10096
+ for (const path22 of visitedSymbols.keys()) {
10097
+ if (!isTestPath(path22) && !isTestSupportPath(path22)) impacted.add(path22);
9892
10098
  }
9893
10099
  const tests = [...testHits.entries()].map(([testPath, hit]) => ({
9894
10100
  path: testPath,
@@ -9945,7 +10151,8 @@ function computeImpact(input) {
9945
10151
  ])
9946
10152
  )
9947
10153
  ) : void 0;
9948
- const coverage = input.trust?.coverage ?? (truncated || depthTruncated || notInSnapshot.length > 0 ? "partial" : "complete");
10154
+ const impactPartial = truncated || depthTruncated || notInSnapshot.length > 0;
10155
+ const coverage = input.trust?.coverage === "partial" || impactPartial ? "partial" : "complete";
9949
10156
  const trust = {
9950
10157
  indexSource: input.trust?.indexSource ?? "snapshot",
9951
10158
  freshness: input.trust?.freshness ?? "unknown",
@@ -9954,7 +10161,7 @@ function computeImpact(input) {
9954
10161
  ...input.trust?.overlayStats === void 0 ? {} : { overlayStats: input.trust.overlayStats },
9955
10162
  sensitiveExcludedCount: input.trust?.sensitiveExcludedCount ?? manifest.skipped.filter((skip) => skip.reason === "sensitive-file").length,
9956
10163
  redactedLines: input.trust?.redactedLines ?? manifest.totals.redactedLines,
9957
- omittedCount: input.trust?.omittedCount ?? notInSnapshot.length + (truncated ? 1 : 0),
10164
+ omittedCount: (input.trust?.omittedCount ?? 0) + notInSnapshot.length + (truncated || depthTruncated ? 1 : 0),
9958
10165
  unresolvedCount: unresolved.length,
9959
10166
  reasons: [...input.trust?.reasons ?? [], ...warnings]
9960
10167
  };
@@ -10096,6 +10303,54 @@ var requireFromHere = module$1.createRequire((typeof document === 'undefined' ?
10096
10303
  path7__namespace.dirname(requireFromHere.resolve("typescript"));
10097
10304
  var DEFAULT_MAX_PROGRAM_FILES = 2500;
10098
10305
  process.platform === "win32" || process.platform === "darwin";
10306
+ var ZERO_WIDTH = /[\u200B-\u200F\u2060-\u2064\uFEFF]/g;
10307
+ var BIDI_CONTROL = /[\u202A-\u202E\u2066-\u2069]/g;
10308
+ var HTML_COMMENT = /<!--([\s\S]*?)-->/g;
10309
+ function looksLikeInstruction(body) {
10310
+ const text = body.replace(/\s+/g, " ").trim();
10311
+ if (text.length === 0) return false;
10312
+ return /\b(ignore|disregard|forget)\b[^.]{0,100}\b(previous|prior|above|earlier)\b/i.test(text) || /\b(system|developer|assistant)\s*:/i.test(text) || /\b(print|reveal|show|dump|exfiltrate|send|curl|fetch|read)\b[^.]{0,100}\b(env|secret|token|key|password|credential|\.env)/i.test(text) || /\bAI (agent|assistant|model)\b/i.test(text) || /\bdo not (tell|mention|reveal|disclose)\b/i.test(text) || /\b(you must|you should now|new instructions?)\b/i.test(text);
10313
+ }
10314
+ function lineAt(text, index) {
10315
+ let line = 1;
10316
+ for (let i = 0; i < index; i += 1) if (text.charCodeAt(i) === 10) line += 1;
10317
+ return line;
10318
+ }
10319
+ function maskPreservingLines(match, marker) {
10320
+ const newlines = match.match(/\n/g)?.length ?? 0;
10321
+ return marker + "\n".repeat(newlines);
10322
+ }
10323
+ function hashSpans(spans) {
10324
+ if (spans.length === 0) return null;
10325
+ return crypto.createHash("sha256").update(spans.join("\0")).digest("hex");
10326
+ }
10327
+ function scanHiddenText(text) {
10328
+ const findings = [];
10329
+ const removedSpans = [];
10330
+ let output = text;
10331
+ output = output.replace(HTML_COMMENT, (match, body, offset) => {
10332
+ if (!looksLikeInstruction(body)) return match;
10333
+ findings.push({ kind: "html-comment", line: lineAt(text, offset), detail: "hidden instruction comment removed" });
10334
+ removedSpans.push(match);
10335
+ return maskPreservingLines(match, "[REMOVED: hidden instruction comment]");
10336
+ });
10337
+ output = output.replace(ZERO_WIDTH, (match, offset) => {
10338
+ findings.push({ kind: "zero-width", line: lineAt(output, offset), detail: "zero-width character removed" });
10339
+ removedSpans.push(match);
10340
+ return "";
10341
+ });
10342
+ output = output.replace(BIDI_CONTROL, (match, offset) => {
10343
+ findings.push({ kind: "bidi-control", line: lineAt(output, offset), detail: "bidi control removed" });
10344
+ removedSpans.push(match);
10345
+ return "";
10346
+ });
10347
+ return {
10348
+ text: output,
10349
+ findings,
10350
+ removed: findings.length,
10351
+ removedDigest: hashSpans(removedSpans)
10352
+ };
10353
+ }
10099
10354
 
10100
10355
  // src/partitioner/part-format.ts
10101
10356
  var FILE_HEADING = "### FILE: ";
@@ -10199,8 +10454,8 @@ function findSection(sections, relativePath) {
10199
10454
  if (exact) return exact;
10200
10455
  const foldedPath = rendered.toLowerCase();
10201
10456
  const folded = sections.filter((section) => {
10202
- const path21 = section.path.toLowerCase();
10203
- return path21 === relativePath.toLowerCase() || path21 === foldedPath;
10457
+ const path22 = section.path.toLowerCase();
10458
+ return path22 === relativePath.toLowerCase() || path22 === foldedPath;
10204
10459
  });
10205
10460
  return folded.length === 1 ? folded[0] : null;
10206
10461
  }
@@ -10296,7 +10551,7 @@ var WORKER_SOURCE = `
10296
10551
  })();
10297
10552
  `;
10298
10553
  function generateInWorker(cwd, cliOptions, options = {}) {
10299
- return new Promise((resolve14) => {
10554
+ return new Promise((resolve15) => {
10300
10555
  let settled = false;
10301
10556
  let worker = null;
10302
10557
  const finish = (result) => {
@@ -10307,7 +10562,7 @@ function generateInWorker(cwd, cliOptions, options = {}) {
10307
10562
  if (!result.ok && options.runId !== void 0 && options.lockRoots !== void 0) {
10308
10563
  releaseAbandonedRun(options.lockRoots, options.runId);
10309
10564
  }
10310
- resolve14(result);
10565
+ resolve15(result);
10311
10566
  });
10312
10567
  };
10313
10568
  const isCjs = typeof __dirname !== "undefined";
@@ -10420,21 +10675,30 @@ var WORKER_SOURCE2 = `
10420
10675
  }
10421
10676
  })();
10422
10677
  `;
10423
- function analysisInWorker(request) {
10424
- return new Promise((resolve14) => {
10678
+ function analysisInWorker(request, signal) {
10679
+ return new Promise((resolve15) => {
10425
10680
  let settled = false;
10426
10681
  let worker = null;
10427
10682
  const timer = setTimeout(() => {
10428
10683
  finish({ ok: false, message: "The analysis worker exceeded its two-minute timeout." });
10429
10684
  }, 12e4);
10430
10685
  timer.unref();
10686
+ const onAbort = () => {
10687
+ finish({ ok: false, message: "The analysis was cancelled." });
10688
+ };
10431
10689
  const finish = (result) => {
10432
10690
  if (settled) return;
10433
10691
  settled = true;
10434
10692
  clearTimeout(timer);
10693
+ signal?.removeEventListener("abort", onAbort);
10435
10694
  const terminated = worker === null ? Promise.resolve(void 0) : worker.terminate();
10436
- void terminated.catch(() => void 0).then(() => resolve14(result));
10695
+ void terminated.catch(() => void 0).then(() => resolve15(result));
10437
10696
  };
10697
+ if (signal?.aborted === true) {
10698
+ finish({ ok: false, message: "The analysis was cancelled." });
10699
+ return;
10700
+ }
10701
+ signal?.addEventListener("abort", onAbort, { once: true });
10438
10702
  const isCjs = typeof __dirname !== "undefined";
10439
10703
  const directory = isCjs ? __dirname : path7__namespace.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('mcp.cjs', document.baseURI).href))));
10440
10704
  try {
@@ -10499,6 +10763,7 @@ function baselineUsable(manifest, config) {
10499
10763
  if (manifest.generator.version !== GENERATOR_VERSION) return false;
10500
10764
  if (manifest.config.digest === void 0 || manifest.config.digest !== configDigest(config)) return false;
10501
10765
  if (manifest.slice !== void 0 || manifest.budget !== void 0 || manifest.delta !== void 0) return false;
10766
+ if (manifest.config.artifacts.parts === false) return false;
10502
10767
  return true;
10503
10768
  }
10504
10769
  function gitWorkingState(cwd) {
@@ -10557,6 +10822,26 @@ function collectStatStamps(config, manifest, gitState) {
10557
10822
  for (const dirty of gitState.dirtyPaths) candidates.add(dirty);
10558
10823
  } else {
10559
10824
  if (manifest.files.length > 500) return [];
10825
+ const directories = [];
10826
+ const pending = [""];
10827
+ while (pending.length > 0) {
10828
+ const directory = pending.shift();
10829
+ let entries;
10830
+ try {
10831
+ entries = fs18__namespace.readdirSync(path7__namespace.join(config.cwd, directory), { withFileTypes: true });
10832
+ } catch {
10833
+ continue;
10834
+ }
10835
+ for (const entry of entries) {
10836
+ if (!entry.isDirectory()) continue;
10837
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
10838
+ const relative14 = directory === "" ? entry.name : directory + "/" + entry.name;
10839
+ directories.push(relative14);
10840
+ pending.push(relative14);
10841
+ if (directories.length > 500) return [];
10842
+ }
10843
+ }
10844
+ for (const directory of directories) candidates.add(directory);
10560
10845
  for (const file of manifest.files) {
10561
10846
  candidates.add(file.relativePath);
10562
10847
  let dir = path7__namespace.posix.dirname(file.relativePath);
@@ -10569,18 +10854,18 @@ function collectStatStamps(config, manifest, gitState) {
10569
10854
  }
10570
10855
  }
10571
10856
  const stamps = [];
10572
- for (const relative12 of [...candidates].sort((left, right) => left.localeCompare(right))) {
10573
- const target = relative12.length === 0 ? config.cwd : path7__namespace.join(config.cwd, relative12);
10857
+ for (const relative14 of [...candidates].sort((left, right) => left.localeCompare(right))) {
10858
+ const target = relative14.length === 0 ? config.cwd : path7__namespace.join(config.cwd, relative14);
10574
10859
  try {
10575
- const stat = fs17__namespace.lstatSync(target);
10860
+ const stat = fs18__namespace.lstatSync(target);
10576
10861
  stamps.push({
10577
- path: relative12,
10862
+ path: relative14,
10578
10863
  exists: true,
10579
10864
  mtimeMs: stat.mtimeMs,
10580
10865
  size: stat.size
10581
10866
  });
10582
10867
  } catch {
10583
- stamps.push({ path: relative12, exists: false, mtimeMs: 0, size: 0 });
10868
+ stamps.push({ path: relative14, exists: false, mtimeMs: 0, size: 0 });
10584
10869
  }
10585
10870
  }
10586
10871
  return stamps;
@@ -10590,7 +10875,7 @@ function stampsMatch(cwd, stamps) {
10590
10875
  for (const stamp of stamps) {
10591
10876
  const target = stamp.path.length === 0 ? cwd : path7__namespace.join(cwd, stamp.path);
10592
10877
  try {
10593
- const stat = fs17__namespace.lstatSync(target);
10878
+ const stat = fs18__namespace.lstatSync(target);
10594
10879
  if (!stamp.exists || stat.mtimeMs !== stamp.mtimeMs || stat.size !== stamp.size) {
10595
10880
  return false;
10596
10881
  }
@@ -10618,7 +10903,7 @@ function readCache(config) {
10618
10903
  const file = liveIndexCachePath(config);
10619
10904
  let raw;
10620
10905
  try {
10621
- raw = fs17__namespace.readFileSync(file, "utf8");
10906
+ raw = fs18__namespace.readFileSync(file, "utf8");
10622
10907
  } catch {
10623
10908
  return null;
10624
10909
  }
@@ -10651,12 +10936,12 @@ function readCache(config) {
10651
10936
  function writeCache(config, payload) {
10652
10937
  try {
10653
10938
  const file = liveIndexCachePath(config);
10654
- fs17__namespace.mkdirSync(path7__namespace.dirname(file), { recursive: true, mode: 448 });
10939
+ fs18__namespace.mkdirSync(path7__namespace.dirname(file), { recursive: true, mode: 448 });
10655
10940
  const temporary = file + "." + process.pid + "." + Date.now() + ".tmp";
10656
- fs17__namespace.writeFileSync(temporary, JSON.stringify(payload), { encoding: "utf8", mode: 384 });
10657
- fs17__namespace.renameSync(temporary, file);
10941
+ fs18__namespace.writeFileSync(temporary, JSON.stringify(payload), { encoding: "utf8", mode: 384 });
10942
+ fs18__namespace.renameSync(temporary, file);
10658
10943
  try {
10659
- fs17__namespace.chmodSync(file, 384);
10944
+ fs18__namespace.chmodSync(file, 384);
10660
10945
  } catch {
10661
10946
  return;
10662
10947
  }
@@ -10741,7 +11026,25 @@ function readRedacted(config, allowedFiles, relativePath) {
10741
11026
  if (isSensitivePath(normalized)) return null;
10742
11027
  const lookup = CASE_INSENSITIVE_PATHS2 ? normalized.toLowerCase() : normalized;
10743
11028
  if (!allowedFiles.has(lookup)) return null;
10744
- const read = readConfinedBytes(config.cwd, normalized, MAX_READ_BYTES);
11029
+ let read = readConfinedBytes(config.cwd, normalized, MAX_READ_BYTES);
11030
+ if (!read.ok && read.reason === "not-file") {
11031
+ try {
11032
+ const alias = path7__namespace.join(config.cwd, normalized);
11033
+ if (fs18__namespace.lstatSync(alias).isSymbolicLink()) {
11034
+ const rootReal = fs18__namespace.realpathSync(config.cwd);
11035
+ const targetReal = fs18__namespace.realpathSync(alias);
11036
+ const targetRelative = path7__namespace.relative(rootReal, targetReal).split(path7__namespace.sep).join("/");
11037
+ if (targetRelative === "" || targetRelative === ".." || targetRelative.startsWith("../") || path7__namespace.isAbsolute(targetRelative) || isSensitivePath(targetRelative)) {
11038
+ return null;
11039
+ }
11040
+ const targetLookup = CASE_INSENSITIVE_PATHS2 ? targetRelative.toLowerCase() : targetRelative;
11041
+ if (!allowedFiles.has(targetLookup)) return null;
11042
+ read = readConfinedBytes(config.cwd, targetRelative, MAX_READ_BYTES);
11043
+ }
11044
+ } catch {
11045
+ return null;
11046
+ }
11047
+ }
10745
11048
  if (!read.ok) return null;
10746
11049
  const decoded = decodeText(read.bytes);
10747
11050
  if (decoded.binary) return null;
@@ -10830,7 +11133,7 @@ function foldForComparison(value) {
10830
11133
  function canonicalPath(value) {
10831
11134
  const absolute = path7__namespace.resolve(value);
10832
11135
  try {
10833
- return fs17__namespace.realpathSync(absolute);
11136
+ return fs18__namespace.realpathSync(absolute);
10834
11137
  } catch {
10835
11138
  return absolute;
10836
11139
  }
@@ -10843,7 +11146,7 @@ function isInside3(parent, child) {
10843
11146
  function resolveThroughExistingAncestor(target) {
10844
11147
  let existing = target;
10845
11148
  const missing = [];
10846
- while (!fs17__namespace.existsSync(existing)) {
11149
+ while (!fs18__namespace.existsSync(existing)) {
10847
11150
  missing.unshift(path7__namespace.basename(existing));
10848
11151
  const parent = path7__namespace.dirname(existing);
10849
11152
  if (parent === existing) break;
@@ -10872,7 +11175,7 @@ function resolveRoot(requested, context) {
10872
11175
  if (!lexicalRoots.some((allowed) => isInside3(allowed, absolute))) return outside();
10873
11176
  let linkStats;
10874
11177
  try {
10875
- linkStats = fs17__namespace.lstatSync(absolute);
11178
+ linkStats = fs18__namespace.lstatSync(absolute);
10876
11179
  } catch {
10877
11180
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
10878
11181
  }
@@ -10884,7 +11187,7 @@ function resolveRoot(requested, context) {
10884
11187
  }
10885
11188
  let stats;
10886
11189
  try {
10887
- stats = fs17__namespace.statSync(absolute);
11190
+ stats = fs18__namespace.statSync(absolute);
10888
11191
  } catch {
10889
11192
  return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
10890
11193
  }
@@ -10963,6 +11266,21 @@ async function openWorkspace(root, overrides = {}, allowedRoots, options = {}) {
10963
11266
  if (typeof overrides.sarif === "boolean") cliOptions.sarif = overrides.sarif;
10964
11267
  if (typeof overrides.staged === "boolean") cliOptions.staged = overrides.staged;
10965
11268
  if (typeof overrides.withDependents === "boolean") cliOptions.withDependents = overrides.withDependents;
11269
+ for (const key of ["includeDiffs", "tokenTree", "stripComments", "removeEmptyLines"]) {
11270
+ if (typeof overrides[key] === "boolean") cliOptions[key] = overrides[key];
11271
+ }
11272
+ if (overrides.includeLogs !== void 0) {
11273
+ if (typeof overrides.includeLogs !== "number" || !Number.isSafeInteger(overrides.includeLogs) || overrides.includeLogs < 1 || overrides.includeLogs > 500) {
11274
+ return { ok: false, message: '"includeLogs" must be an integer from 1 to 500.' };
11275
+ }
11276
+ cliOptions.includeLogs = overrides.includeLogs;
11277
+ }
11278
+ if (overrides.pack !== void 0) {
11279
+ if (overrides.pack !== "single" && overrides.pack !== "xml" && overrides.pack !== "json") {
11280
+ return { ok: false, message: '"pack" must be "single", "xml" or "json".' };
11281
+ }
11282
+ cliOptions.pack = overrides.pack;
11283
+ }
10966
11284
  for (const key of ["only", "ignore"]) {
10967
11285
  const value = overrides[key];
10968
11286
  if (value === void 0) continue;
@@ -11017,21 +11335,21 @@ function partPathFor(workspace, filename) {
11017
11335
  if (filename.length === 0 || filename.includes("\0")) return null;
11018
11336
  const partsDir = path7__namespace.resolve(workspace.root, workspace.config.outDir, "parts");
11019
11337
  const resolved = path7__namespace.resolve(partsDir, filename);
11020
- const relative12 = path7__namespace.relative(partsDir, resolved);
11021
- if (relative12.length === 0 || relative12.includes(path7__namespace.sep) || relative12.includes("/") || relative12.includes("\\") || path7__namespace.isAbsolute(relative12)) {
11338
+ const relative14 = path7__namespace.relative(partsDir, resolved);
11339
+ if (relative14.length === 0 || relative14.includes(path7__namespace.sep) || relative14.includes("/") || relative14.includes("\\") || path7__namespace.isAbsolute(relative14)) {
11022
11340
  return null;
11023
11341
  }
11024
11342
  let stats;
11025
11343
  try {
11026
- stats = fs17__namespace.lstatSync(resolved);
11344
+ stats = fs18__namespace.lstatSync(resolved);
11027
11345
  } catch {
11028
11346
  return null;
11029
11347
  }
11030
11348
  if (!stats.isFile()) return null;
11031
11349
  try {
11032
- const snapshotReal = fs17__namespace.realpathSync(path7__namespace.resolve(workspace.root, workspace.config.outDir));
11033
- const partsReal = fs17__namespace.realpathSync(partsDir);
11034
- const resolvedReal = fs17__namespace.realpathSync(resolved);
11350
+ const snapshotReal = fs18__namespace.realpathSync(path7__namespace.resolve(workspace.root, workspace.config.outDir));
11351
+ const partsReal = fs18__namespace.realpathSync(partsDir);
11352
+ const resolvedReal = fs18__namespace.realpathSync(resolved);
11035
11353
  if (!isInside3(snapshotReal, partsReal)) return null;
11036
11354
  if (!isInside3(partsReal, resolvedReal)) return null;
11037
11355
  if (path7__namespace.dirname(resolvedReal) !== partsReal) return null;
@@ -11125,8 +11443,8 @@ var WRITES = {
11125
11443
  var MAX_RESULT_BYTES = 64 * 1024;
11126
11444
  var MAX_SEARCH_BYTES = 4 * 1024 * 1024;
11127
11445
  var MAX_PART_READ_BYTES = 16 * 1024 * 1024;
11128
- function capResultText(text) {
11129
- const clipped = truncateToBytes(text, MAX_RESULT_BYTES);
11446
+ function capResultText(text, maxBytes = MAX_RESULT_BYTES) {
11447
+ const clipped = truncateToBytes(text, maxBytes);
11130
11448
  return { text: clipped.isTruncated ? clipped.content : text, clipped: clipped.isTruncated };
11131
11449
  }
11132
11450
  function capResponseText(text) {
@@ -11175,9 +11493,21 @@ function workspaceOverrides(args) {
11175
11493
  staged: args.staged,
11176
11494
  withDependents: args.withDependents,
11177
11495
  only: args.only,
11178
- ignore: args.ignore
11496
+ ignore: args.ignore,
11497
+ includeDiffs: args.includeDiffs,
11498
+ includeLogs: args.includeLogs,
11499
+ tokenTree: args.tokenTree,
11500
+ stripComments: args.stripComments,
11501
+ removeEmptyLines: args.removeEmptyLines,
11502
+ pack: args.pack
11179
11503
  };
11180
11504
  }
11505
+ function cancellationSignal(context) {
11506
+ if (context.onCancel === void 0) return void 0;
11507
+ const controller = new AbortController();
11508
+ context.onCancel(() => controller.abort());
11509
+ return controller.signal;
11510
+ }
11181
11511
  function failure(message) {
11182
11512
  return { text: message, isError: true };
11183
11513
  }
@@ -11211,11 +11541,11 @@ function toRelativePath(root, value) {
11211
11541
  if (cleaned.length === 0 || cleaned.includes("\0")) return null;
11212
11542
  const resolvedRoot = path7__namespace.resolve(root);
11213
11543
  const absolute = path7__namespace.resolve(resolvedRoot, cleaned);
11214
- const relative12 = path7__namespace.relative(resolvedRoot, absolute);
11215
- if (relative12 === "" || relative12 === ".." || relative12.startsWith(".." + path7__namespace.sep) || path7__namespace.isAbsolute(relative12)) {
11544
+ const relative14 = path7__namespace.relative(resolvedRoot, absolute);
11545
+ if (relative14 === "" || relative14 === ".." || relative14.startsWith(".." + path7__namespace.sep) || path7__namespace.isAbsolute(relative14)) {
11216
11546
  return null;
11217
11547
  }
11218
- return relative12.split(path7__namespace.sep).join("/");
11548
+ return relative14.split(path7__namespace.sep).join("/");
11219
11549
  }
11220
11550
  function symbolsOf(entry) {
11221
11551
  const summary = entry.summary;
@@ -11244,6 +11574,56 @@ function symbolsOf(entry) {
11244
11574
  }
11245
11575
  return [...new Set(names)].sort((left, right) => left.localeCompare(right));
11246
11576
  }
11577
+ function declarationSpansOf(entry) {
11578
+ const summary = entry.summary;
11579
+ if (!summary || typeof summary !== "object") return [];
11580
+ const spans = summary.declarationSpans;
11581
+ if (!Array.isArray(spans)) return [];
11582
+ return spans.filter((span) => {
11583
+ if (span === null || typeof span !== "object") return false;
11584
+ const candidate = span;
11585
+ 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;
11586
+ });
11587
+ }
11588
+ function symbolSpanOf(entry, symbol) {
11589
+ const wanted = symbol.toLowerCase();
11590
+ const matches = declarationSpansOf(entry).filter((span) => span.name.toLowerCase() === wanted);
11591
+ return matches[0] ?? null;
11592
+ }
11593
+ function identifierTokens(value) {
11594
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2);
11595
+ }
11596
+ function questionSpanOf(entry, question) {
11597
+ const asked = question.toLowerCase();
11598
+ const tokens = new Set(identifierTokens(question));
11599
+ let best = null;
11600
+ let bestScore = 0;
11601
+ for (const span of declarationSpansOf(entry)) {
11602
+ if (span.name.length < 3) continue;
11603
+ const nameTokens = identifierTokens(span.name);
11604
+ if (nameTokens.length < 2) continue;
11605
+ let score = asked.includes(span.name.toLowerCase()) ? 8 : 0;
11606
+ for (const token of nameTokens) if (tokens.has(token)) score += 2;
11607
+ if (score > bestScore) {
11608
+ best = span;
11609
+ bestScore = score;
11610
+ }
11611
+ }
11612
+ return bestScore >= 4 ? best : null;
11613
+ }
11614
+ function clampRange(range, totalLines) {
11615
+ const start = Math.max(1, Math.min(range.startLine, Math.max(1, totalLines)));
11616
+ const end = Math.max(start, Math.min(range.endLine, Math.max(1, totalLines)));
11617
+ if (totalLines > 0 && range.startLine > totalLines) return null;
11618
+ return { startLine: start, endLine: end };
11619
+ }
11620
+ function stableJson(value) {
11621
+ if (value === void 0) return "null";
11622
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
11623
+ if (Array.isArray(value)) return "[" + value.map(stableJson).join(",") + "]";
11624
+ const record = value;
11625
+ return "{" + Object.keys(record).sort().map((key) => JSON.stringify(key) + ":" + stableJson(record[key])).join(",") + "}";
11626
+ }
11247
11627
  async function prepare(args, context, overrides = {}) {
11248
11628
  const rootOutcome = resolveRoot(args.root, context);
11249
11629
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
@@ -11291,25 +11671,75 @@ function partTooLargeFor(workspace, entry) {
11291
11671
  const partPath = partPathFor(workspace, entry.part);
11292
11672
  if (partPath === null) return false;
11293
11673
  try {
11294
- return fs17__namespace.statSync(partPath).size > MAX_PART_READ_BYTES;
11674
+ return fs18__namespace.statSync(partPath).size > MAX_PART_READ_BYTES;
11295
11675
  } catch {
11296
11676
  return false;
11297
11677
  }
11298
11678
  }
11299
- function bodyFor(workspace, index, entry) {
11679
+ var partCaches = /* @__PURE__ */ new WeakMap();
11680
+ function sha256Of(bytes) {
11681
+ return crypto.createHash("sha256").update(bytes).digest("hex");
11682
+ }
11683
+ function noteUnverifiedPart(index, detail) {
11684
+ index.trust.coverage = "partial";
11685
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, detail])];
11686
+ }
11687
+ function liveBody(index, entry) {
11688
+ return index.live?.readRedactedFile(entry.relativePath)?.text ?? null;
11689
+ }
11690
+ function bodyFor(workspace, index, entry, cache) {
11300
11691
  if (index.live !== null && index.trust.indexSource !== "snapshot") {
11301
11692
  return index.live.readRedactedFile(entry.relativePath)?.text ?? null;
11302
11693
  }
11303
11694
  const partPath = partPathFor(workspace, entry.part);
11304
- if (partPath === null) return null;
11305
- try {
11306
- if (fs17__namespace.statSync(partPath).size > MAX_PART_READ_BYTES) return null;
11307
- const sections = parsePartSections(fs17__namespace.readFileSync(partPath, "utf8"));
11308
- const section = findSection(sections, entry.relativePath);
11309
- return section === null ? null : section.body;
11310
- } catch {
11695
+ if (partPath === null) {
11696
+ if (index.live !== null) {
11697
+ noteUnverifiedPart(index, entry.part + " is missing; live bytes used");
11698
+ return liveBody(index, entry);
11699
+ }
11311
11700
  return null;
11312
11701
  }
11702
+ const store = partCaches.get(index) ?? (() => {
11703
+ const created = /* @__PURE__ */ new Map();
11704
+ partCaches.set(index, created);
11705
+ return created;
11706
+ })();
11707
+ let sections = store.get(entry.part);
11708
+ if (sections === void 0) {
11709
+ try {
11710
+ if (fs18__namespace.statSync(partPath).size > MAX_PART_READ_BYTES) {
11711
+ store.set(entry.part, null);
11712
+ return null;
11713
+ }
11714
+ const bytes = fs18__namespace.readFileSync(partPath);
11715
+ const recorded = index.manifest.parts.find((part) => part.filename === entry.part);
11716
+ if (recorded === void 0 || bytes.length !== recorded.byteSize || sha256Of(bytes) !== recorded.sha256) {
11717
+ store.set(entry.part, null);
11718
+ noteUnverifiedPart(
11719
+ index,
11720
+ entry.part + " does not match its recorded digest; live bytes used"
11721
+ );
11722
+ return liveBody(index, entry);
11723
+ }
11724
+ sections = parsePartSections(bytes.toString("utf8"));
11725
+ store.set(entry.part, sections);
11726
+ } catch {
11727
+ store.set(entry.part, null);
11728
+ noteUnverifiedPart(index, entry.part + " could not be read; live bytes used");
11729
+ return liveBody(index, entry);
11730
+ }
11731
+ }
11732
+ if (sections === null) return liveBody(index, entry);
11733
+ const section = findSection(sections, entry.relativePath);
11734
+ if (section === null) {
11735
+ noteUnverifiedPart(index, entry.relativePath + " is absent from " + entry.part + "; live bytes used");
11736
+ return liveBody(index, entry);
11737
+ }
11738
+ return section.body;
11739
+ }
11740
+ function numberWindow(text, startLine = 1) {
11741
+ if (text.length === 0) return text;
11742
+ return text.split("\n").map((line, index) => startLine + index + ": " + line).join("\n");
11313
11743
  }
11314
11744
  var impactTool = {
11315
11745
  name: "snapshot_impact",
@@ -11425,7 +11855,18 @@ var impactTool = {
11425
11855
  targetPath: entry.path
11426
11856
  }));
11427
11857
  });
11428
- if (tsEntries.length > DEFAULT_MAX_PROGRAM_FILES) {
11858
+ const lossyBodies = index.trust.indexSource === "snapshot" && tsEntries.some(
11859
+ (entry) => entry.inclusionMode === "preview" || entry.inclusionMode === "signatures"
11860
+ );
11861
+ if (lossyBodies) {
11862
+ const reason = "TypeScript compiler pass skipped: the snapshot holds previewed or skeletonised bodies; run snapshot_impact with live: true for compiler-resolved references";
11863
+ report = {
11864
+ ...report,
11865
+ precise: { references: [], coverage: "partial", reasons: [reason] }
11866
+ };
11867
+ report.trust.coverage = "partial";
11868
+ report.trust.reasons = [.../* @__PURE__ */ new Set([...report.trust.reasons, reason])];
11869
+ } else if (tsEntries.length > DEFAULT_MAX_PROGRAM_FILES) {
11429
11870
  const reason = "TypeScript compiler pass skipped: " + tsEntries.length + " TS/JS files exceed the " + DEFAULT_MAX_PROGRAM_FILES + "-file cap; fell back to import-binding results";
11430
11871
  report = {
11431
11872
  ...report,
@@ -11443,14 +11884,17 @@ var impactTool = {
11443
11884
  const body = bodyFor(workspace, index, entry);
11444
11885
  return body === null ? null : { relativePath: entry.relativePath, content: body };
11445
11886
  }).filter((entry) => entry !== null);
11446
- const workerResult = await analysisInWorker({
11447
- task: "ts-batch-refs",
11448
- options: {
11449
- root: workspace.root,
11450
- files,
11451
- targets
11452
- }
11453
- });
11887
+ const workerResult = await analysisInWorker(
11888
+ {
11889
+ task: "ts-batch-refs",
11890
+ options: {
11891
+ root: workspace.root,
11892
+ files,
11893
+ targets
11894
+ }
11895
+ },
11896
+ cancellationSignal(context)
11897
+ );
11454
11898
  if (!workerResult.ok) return failure(workerResult.message);
11455
11899
  const result = workerResult.result;
11456
11900
  const references = [];
@@ -11487,10 +11931,28 @@ var contextTool = {
11487
11931
  question: { type: "string", description: "Natural-language question or task." },
11488
11932
  files: { type: "array", items: { type: "string" }, description: "Explicit repository-relative paths." },
11489
11933
  symbols: { type: "array", items: { type: "string" }, description: "Exported or defined symbol names." },
11934
+ ranges: {
11935
+ type: "array",
11936
+ description: "Explicit 1-based line ranges. Each range is honored before the file head or a symbol span.",
11937
+ items: {
11938
+ type: "object",
11939
+ properties: {
11940
+ path: { type: "string", description: "Repository-relative path." },
11941
+ startLine: { type: "integer", minimum: 1 },
11942
+ endLine: { type: "integer", minimum: 1 }
11943
+ },
11944
+ required: ["path", "startLine", "endLine"],
11945
+ additionalProperties: false
11946
+ }
11947
+ },
11490
11948
  maxTokens: { type: "integer", minimum: 500, maximum: 2e5, default: 2e4 },
11491
11949
  linesPerFile: { type: "integer", minimum: 10, maximum: 2e3, default: 80 },
11492
11950
  includeTests: { type: "boolean", description: "Include test files (default false)." },
11493
11951
  planOnly: { type: "boolean", description: "Return the reading plan without file bodies." },
11952
+ signReceipt: {
11953
+ type: "boolean",
11954
+ description: "Sign the context receipt with SNAPSHOT_SIGNING_KEY. Requires a configured key."
11955
+ },
11494
11956
  live: LIVE_PROPERTY,
11495
11957
  root: ROOT_PROPERTY,
11496
11958
  outDir: OUT_DIR_PROPERTY
@@ -11504,6 +11966,10 @@ var contextTool = {
11504
11966
  usedTokens: { type: "integer" },
11505
11967
  files: { type: "array", items: { type: "object" } },
11506
11968
  omitted: { type: "array", items: { type: "object" } },
11969
+ skipped: { type: "array", items: { type: "object" } },
11970
+ notes: { type: "array", items: { type: "string" } },
11971
+ security: { type: "array", items: { type: "object" } },
11972
+ receipt: { type: "object" },
11507
11973
  trust: { type: "object" }
11508
11974
  }
11509
11975
  },
@@ -11521,8 +11987,8 @@ var contextTool = {
11521
11987
  const question = typeof args.question === "string" ? args.question.trim() : "";
11522
11988
  const wantedFiles = Array.isArray(args.files) ? args.files.filter((item) => typeof item === "string") : [];
11523
11989
  const wantedSymbols = Array.isArray(args.symbols) ? args.symbols.filter((item) => typeof item === "string") : [];
11524
- if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0) {
11525
- return failure("Provide at least one of question, files or symbols.");
11990
+ if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0 && !(Array.isArray(args.ranges) && args.ranges.length > 0)) {
11991
+ return failure("Provide at least one of question, files, symbols or ranges.");
11526
11992
  }
11527
11993
  const budget = Math.min(2e5, Math.max(500, typeof args.maxTokens === "number" ? args.maxTokens : 2e4));
11528
11994
  const linesPerFile = Math.min(2e3, Math.max(10, typeof args.linesPerFile === "number" ? args.linesPerFile : 80));
@@ -11531,38 +11997,91 @@ var contextTool = {
11531
11997
  includeTests: args.includeTests === true,
11532
11998
  cwd: workspace.root
11533
11999
  }) : null;
12000
+ const wantedRanges = [];
12001
+ if (args.ranges !== void 0) {
12002
+ if (!Array.isArray(args.ranges)) return failure('"ranges" must be an array.');
12003
+ for (const raw of args.ranges) {
12004
+ if (raw === null || typeof raw !== "object") return failure('"ranges" entries must be objects.');
12005
+ const candidate = raw;
12006
+ if (typeof candidate.path !== "string" || candidate.path.trim().length === 0) {
12007
+ return failure('"ranges[].path" must be a non-empty string.');
12008
+ }
12009
+ if (typeof candidate.startLine !== "number" || !Number.isInteger(candidate.startLine) || candidate.startLine < 1) {
12010
+ return failure('"ranges[].startLine" must be a positive integer.');
12011
+ }
12012
+ if (typeof candidate.endLine !== "number" || !Number.isInteger(candidate.endLine) || candidate.endLine < 1) {
12013
+ return failure('"ranges[].endLine" must be a positive integer.');
12014
+ }
12015
+ if (candidate.endLine < candidate.startLine) {
12016
+ return failure('"ranges[].endLine" must be greater than or equal to startLine.');
12017
+ }
12018
+ wantedRanges.push({ path: candidate.path.trim(), startLine: candidate.startLine, endLine: candidate.endLine });
12019
+ }
12020
+ }
12021
+ if (question.length === 0 && wantedFiles.length === 0 && wantedSymbols.length === 0 && wantedRanges.length === 0) {
12022
+ return failure("Provide at least one of question, files, symbols or ranges.");
12023
+ }
12024
+ const receiptKey = args.signReceipt === true ? loadSigningKey() : null;
12025
+ if (args.signReceipt === true && receiptKey === null) {
12026
+ return failure("signReceipt requires SNAPSHOT_SIGNING_KEY to contain an Ed25519 private key.");
12027
+ }
11534
12028
  const targets = /* @__PURE__ */ new Map();
11535
12029
  const preOmitted = [];
11536
12030
  if (plan !== null) {
11537
- for (const file of plan.files) targets.set(file.path, file.why);
12031
+ for (const file of plan.files) {
12032
+ const entry = entryFor(index.manifest, file.path);
12033
+ const span = entry === null ? null : questionSpanOf(entry, question);
12034
+ targets.set(file.path, {
12035
+ why: file.why,
12036
+ ...span === null ? {} : { range: { startLine: span.startLine, endLine: span.endLine }, symbol: span.name }
12037
+ });
12038
+ }
11538
12039
  for (const file of plan.skipped) {
11539
12040
  preOmitted.push({ path: file.path, reason: file.reason });
11540
12041
  }
11541
12042
  }
11542
12043
  for (const wanted of wantedFiles) {
11543
- const relative12 = toRelativePath(workspace.root, wanted);
11544
- if (relative12 === null) {
12044
+ const relative14 = toRelativePath(workspace.root, wanted);
12045
+ if (relative14 === null) {
11545
12046
  preOmitted.push({ path: wanted, reason: "outside the served repository" });
11546
12047
  continue;
11547
12048
  }
11548
- if (isSensitivePath(relative12)) {
11549
- preOmitted.push({ path: relative12, reason: "sensitive-file" });
12049
+ if (isSensitivePath(relative14)) {
12050
+ preOmitted.push({ path: relative14, reason: "sensitive-file" });
11550
12051
  continue;
11551
12052
  }
11552
- targets.set(relative12, "requested file");
12053
+ targets.set(relative14, { why: "requested file" });
11553
12054
  }
11554
12055
  for (const symbol of wantedSymbols) {
11555
12056
  const needle = symbol.toLowerCase();
11556
12057
  for (const file of index.manifest.files) {
11557
12058
  if (symbolsOf(file).some((name) => name.toLowerCase() === needle)) {
11558
- if (!targets.has(file.relativePath)) {
11559
- targets.set(file.relativePath, "defines " + symbol);
11560
- }
12059
+ const span = symbolSpanOf(file, symbol);
12060
+ targets.set(file.relativePath, {
12061
+ why: "defines " + symbol,
12062
+ ...span === null ? {} : { range: { startLine: span.startLine, endLine: span.endLine }, symbol: span.name }
12063
+ });
11561
12064
  }
11562
12065
  }
11563
12066
  }
12067
+ for (const wanted of wantedRanges) {
12068
+ const relative14 = toRelativePath(workspace.root, wanted.path);
12069
+ if (relative14 === null) {
12070
+ preOmitted.push({ path: wanted.path, reason: "outside the served repository" });
12071
+ continue;
12072
+ }
12073
+ if (isSensitivePath(relative14)) {
12074
+ preOmitted.push({ path: relative14, reason: "sensitive-file" });
12075
+ continue;
12076
+ }
12077
+ targets.set(relative14, {
12078
+ why: "requested range",
12079
+ range: { startLine: wanted.startLine, endLine: wanted.endLine },
12080
+ explicitRange: true
12081
+ });
12082
+ }
11564
12083
  if (args.planOnly === true) {
11565
- if (plan !== null && wantedFiles.length === 0 && wantedSymbols.length === 0) {
12084
+ if (plan !== null && wantedFiles.length === 0 && wantedSymbols.length === 0 && wantedRanges.length === 0) {
11566
12085
  return {
11567
12086
  text: [
11568
12087
  "Plan for: " + question,
@@ -11576,13 +12095,19 @@ var contextTool = {
11576
12095
  const plannedFiles = [];
11577
12096
  const planSkipped = [...preOmitted];
11578
12097
  let planUsed = 0;
11579
- for (const [relativePath, why] of targets.entries()) {
12098
+ for (const [relativePath, target] of targets.entries()) {
11580
12099
  const entry = entryFor(index.manifest, relativePath);
11581
12100
  if (entry === null) {
11582
12101
  planSkipped.push({ path: relativePath, reason: "not in the index" });
11583
12102
  continue;
11584
12103
  }
11585
- const estimated = Math.max(1, Math.ceil(entry.includedBytes / 4));
12104
+ const range = target.range === void 0 ? null : clampRange(target.range, entry.lines);
12105
+ if (target.range !== void 0 && range === null) {
12106
+ planSkipped.push({ path: target.symbol === void 0 ? relativePath : relativePath + " (" + target.symbol + ")", reason: "range is past the end of the file" });
12107
+ continue;
12108
+ }
12109
+ const lineCount = range === null ? null : range.endLine - range.startLine + 1;
12110
+ 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));
11586
12111
  if (planUsed + estimated > budget) {
11587
12112
  planSkipped.push({ path: relativePath, reason: "does not fit the remaining budget" });
11588
12113
  continue;
@@ -11594,8 +12119,11 @@ var contextTool = {
11594
12119
  layer: entry.layer,
11595
12120
  kind: entry.kind,
11596
12121
  tokens: estimated,
11597
- mode: "full",
11598
- why
12122
+ mode: range === null ? "full" : "range",
12123
+ fromLine: range === null ? 1 : range.startLine,
12124
+ toLine: range === null ? entry.lines : range.endLine,
12125
+ ...target.symbol === void 0 ? {} : { symbol: target.symbol },
12126
+ why: target.why
11599
12127
  });
11600
12128
  }
11601
12129
  const planNotes = plan === null ? [] : [...plan.notes];
@@ -11603,7 +12131,7 @@ var contextTool = {
11603
12131
  text: [
11604
12132
  "Plan" + (question.length > 0 ? " for: " + question : ""),
11605
12133
  "Budget: " + planUsed + " of " + budget + " tokens; " + plannedFiles.length + " file(s).",
11606
- ...plannedFiles.map((file, position) => position + 1 + ". " + file.path + " (" + file.tokens + " tokens) - " + file.why),
12134
+ ...plannedFiles.map((file, position) => position + 1 + ". " + file.path + " (" + file.tokens + " tokens, lines " + file.fromLine + "\u2013" + file.toLine + ") - " + file.why),
11607
12135
  ...planNotes.map((note) => "- " + note)
11608
12136
  ].join("\n"),
11609
12137
  structured: {
@@ -11618,10 +12146,11 @@ var contextTool = {
11618
12146
  };
11619
12147
  }
11620
12148
  const omitted = [...preOmitted];
12149
+ const security = [];
11621
12150
  const blocks = [];
11622
12151
  const sections = [];
11623
12152
  let used = 0;
11624
- for (const [relativePath, why] of targets.entries()) {
12153
+ for (const [relativePath, target] of targets.entries()) {
11625
12154
  if (used >= budget) {
11626
12155
  omitted.push({ path: relativePath, reason: "budget" });
11627
12156
  continue;
@@ -11631,7 +12160,7 @@ var contextTool = {
11631
12160
  omitted.push({ path: relativePath, reason: "not in the index" });
11632
12161
  continue;
11633
12162
  }
11634
- const body = bodyFor(workspace, index, entry);
12163
+ let body = bodyFor(workspace, index, entry);
11635
12164
  if (body === null) {
11636
12165
  omitted.push({
11637
12166
  path: relativePath,
@@ -11639,29 +12168,99 @@ var contextTool = {
11639
12168
  });
11640
12169
  continue;
11641
12170
  }
11642
- const window = windowText(body, 1, linesPerFile);
11643
- let text = capResultText(window.text).text;
12171
+ const hidden = scanHiddenText(body);
12172
+ if (hidden.findings.length > 0) {
12173
+ body = hidden.text;
12174
+ for (const finding of hidden.findings) security.push({ path: relativePath, ...finding });
12175
+ }
12176
+ const totalLines = body.length === 0 ? 0 : body.split("\n").length;
12177
+ const range = target.range === void 0 ? null : clampRange(target.range, totalLines);
12178
+ if (target.range !== void 0 && range === null) {
12179
+ omitted.push({ path: relativePath, reason: "range is past the end of the file" });
12180
+ continue;
12181
+ }
12182
+ const startLine = range === null ? 1 : range.startLine;
12183
+ const requestedLines = range === null ? linesPerFile : range.endLine - range.startLine + 1;
12184
+ const lineLimit = target.explicitRange === true ? Math.min(2e3, requestedLines) : Math.min(linesPerFile, requestedLines);
12185
+ let window = windowText(body, startLine, lineLimit);
12186
+ if (window.pastEnd || window.returnedLines === 0) {
12187
+ omitted.push({ path: relativePath, reason: "range is past the end of the file" });
12188
+ continue;
12189
+ }
12190
+ let capped2 = capResultText(numberWindow(window.text, startLine));
12191
+ let text = capped2.text;
11644
12192
  let tokens = Math.max(1, estimateTokens(text));
11645
12193
  if (used + tokens > budget) {
11646
- const keep = Math.max(4, Math.floor((budget - used) / tokens * linesPerFile));
12194
+ const keep = Math.max(4, Math.floor((budget - used) / tokens * window.returnedLines));
11647
12195
  if (keep < 4) {
11648
12196
  omitted.push({ path: relativePath, reason: "budget" });
11649
12197
  continue;
11650
12198
  }
11651
- const smaller = windowText(body, 1, keep);
11652
- text = capResultText(smaller.text).text;
12199
+ window = windowText(body, startLine, keep);
12200
+ capped2 = capResultText(numberWindow(window.text, startLine));
12201
+ text = capped2.text;
11653
12202
  tokens = Math.max(1, estimateTokens(text));
11654
12203
  if (used + tokens > budget || text.length === 0) {
11655
12204
  omitted.push({ path: relativePath, reason: "budget" });
11656
12205
  continue;
11657
12206
  }
11658
12207
  }
11659
- sections.push("### " + relativePath + " (" + entry.part + ", " + linesPerFile + " line window)");
12208
+ const returnedLines = text.length === 0 ? 0 : text.split("\n").length;
12209
+ const truncated = window.truncated || capped2.clipped;
12210
+ const toLine = startLine + returnedLines - 1;
12211
+ sections.push(
12212
+ "### " + relativePath + (target.symbol === void 0 ? "" : " \u2014 " + target.symbol) + " (" + entry.part + ", lines " + startLine + "\u2013" + toLine + " of " + window.totalLines + (truncated ? "; more remains" : "") + ")"
12213
+ );
11660
12214
  sections.push(text);
11661
- blocks.push({ path: relativePath, tokens, why });
12215
+ blocks.push({
12216
+ path: relativePath,
12217
+ tokens,
12218
+ why: target.why,
12219
+ fromLine: startLine,
12220
+ toLine,
12221
+ returnedLines,
12222
+ totalLines: window.totalLines,
12223
+ truncated,
12224
+ ...target.symbol === void 0 ? {} : { symbol: target.symbol },
12225
+ chunkHash: sha256Of(Buffer.from(text, "utf8"))
12226
+ });
11662
12227
  used += tokens;
11663
12228
  }
11664
- const notes = omitted.length === 0 ? [] : ["Not returned: " + omitted.map((entry) => entry.path + " (" + entry.reason + ")").join(", ") + "."];
12229
+ if (security.length > 0) {
12230
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, security.length + " hidden instruction or invisible character(s) removed"])];
12231
+ }
12232
+ const notes = [];
12233
+ if (omitted.length > 0) notes.push("Not returned: " + omitted.map((entry) => entry.path + " (" + entry.reason + ")").join(", ") + ".");
12234
+ if (security.length > 0) notes.push("Security: " + security.length + " hidden item(s) removed.");
12235
+ const receiptChunks = blocks.map((block) => ({
12236
+ path: block.path,
12237
+ fromLine: block.fromLine,
12238
+ toLine: block.toLine,
12239
+ tokens: block.tokens,
12240
+ why: block.why,
12241
+ ...block.symbol === void 0 ? {} : { symbol: block.symbol },
12242
+ sha256: block.chunkHash
12243
+ }));
12244
+ const receiptPayload = {
12245
+ schemaVersion: 1,
12246
+ algorithm: "sha256",
12247
+ chunks: receiptChunks,
12248
+ omitted,
12249
+ security,
12250
+ trust: index.trust
12251
+ };
12252
+ const receiptDigest = sha256Of(Buffer.from(stableJson(receiptPayload), "utf8"));
12253
+ const receipt = { ...receiptPayload, digest: receiptDigest };
12254
+ if (receiptKey !== null) {
12255
+ const payloadBytes = Buffer.from(stableJson(receiptPayload), "utf8");
12256
+ const publicKey = crypto.createPublicKey(receiptKey).export({ type: "spki", format: "der" }).toString("base64");
12257
+ receipt.signature = {
12258
+ algorithm: "ed25519",
12259
+ publicKey,
12260
+ value: crypto.sign(null, payloadBytes, receiptKey).toString("base64")
12261
+ };
12262
+ }
12263
+ if (receiptChunks.length > 0) notes.push("Receipt: sha256 " + receiptDigest.slice(0, 16) + "\u2026");
11665
12264
  const response = capResponseText([sections.join("\n\n"), ...notes].filter((part) => part.length > 0).join("\n\n"));
11666
12265
  return {
11667
12266
  text: response.text,
@@ -11670,6 +12269,8 @@ var contextTool = {
11670
12269
  usedTokens: used,
11671
12270
  files: blocks,
11672
12271
  omitted,
12272
+ security,
12273
+ receipt,
11673
12274
  ...response.clipped ? { clippedAtBytes: MAX_RESULT_BYTES } : {},
11674
12275
  trust: index.trust
11675
12276
  }
@@ -11703,7 +12304,11 @@ var locateTool = {
11703
12304
  },
11704
12305
  outputSchema: {
11705
12306
  type: "object",
11706
- properties: { total: { type: "integer" }, matches: { type: "array", items: { type: "object" } } }
12307
+ properties: {
12308
+ total: { type: "integer" },
12309
+ matches: { type: "array", items: { type: "object" } },
12310
+ security: { type: "array", items: { type: "object" } }
12311
+ }
11707
12312
  },
11708
12313
  annotations: READ_ONLY,
11709
12314
  async handler(args, context) {
@@ -11809,11 +12414,18 @@ var locateTool = {
11809
12414
  for (const entry of index.manifest.files) add(entry, "filter");
11810
12415
  }
11811
12416
  const shouldText = by === "text" || by === "auto" && matches.length === 0 && rawQuery.length >= 3;
12417
+ let textCapReason = null;
12418
+ const security = [];
11812
12419
  if (shouldText) {
11813
12420
  let scanned = 0;
11814
12421
  for (const entry of index.manifest.files) {
11815
12422
  if (!allowed(entry)) continue;
11816
- if (scanned >= MAX_SEARCH_BYTES) break;
12423
+ if (scanned >= MAX_SEARCH_BYTES) {
12424
+ textCapReason = "text search stopped after 4 MiB of indexed bodies; later files were not scanned";
12425
+ index.trust.coverage = "partial";
12426
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, textCapReason])];
12427
+ break;
12428
+ }
11817
12429
  const body = bodyFor(workspace, index, entry);
11818
12430
  if (body === null) continue;
11819
12431
  scanned += Buffer.byteLength(body, "utf8");
@@ -11824,6 +12436,13 @@ var locateTool = {
11824
12436
  if (!(pattern === null ? line.toLowerCase().includes(needle) : pattern.test(line))) continue;
11825
12437
  const from = Math.max(0, lineIndex - contextLines);
11826
12438
  const to = Math.min(lines2.length, lineIndex + contextLines + 1);
12439
+ const excerpt = scanHiddenText(lines2.slice(from, to).join("\n").trim());
12440
+ if (excerpt.findings.length > 0) {
12441
+ for (const finding of excerpt.findings) {
12442
+ security.push({ path: entry.relativePath, ...finding, line: lineIndex + 1 });
12443
+ }
12444
+ }
12445
+ if (excerpt.text.trim().length === 0) continue;
11827
12446
  textMatches.push({
11828
12447
  path: entry.relativePath,
11829
12448
  layer: entry.layer,
@@ -11831,7 +12450,7 @@ var locateTool = {
11831
12450
  part: entry.part,
11832
12451
  matchedBy: "text",
11833
12452
  line: lineIndex + 1,
11834
- text: lines2.slice(from, to).join("\n").trim().slice(0, 500)
12453
+ text: excerpt.text.slice(0, 500)
11835
12454
  });
11836
12455
  if (textMatches.length >= limit) break;
11837
12456
  }
@@ -11845,7 +12464,15 @@ var locateTool = {
11845
12464
  let referenceReasons = [];
11846
12465
  if (args.includeReferences === true && rawQuery.length > 0) {
11847
12466
  const tsEntries = index.manifest.files.filter((entry) => /\.(?:[cm]?[jt]sx?)$/i.test(entry.relativePath));
11848
- if (tsEntries.length > DEFAULT_MAX_PROGRAM_FILES) {
12467
+ const lossyBodies = index.trust.indexSource === "snapshot" && tsEntries.some(
12468
+ (entry) => entry.inclusionMode === "preview" || entry.inclusionMode === "signatures"
12469
+ );
12470
+ const lossyReason = "TypeScript compiler pass skipped: the snapshot holds previewed or skeletonised bodies; run snapshot_locate with live: true for compiler-resolved references";
12471
+ if (lossyBodies) {
12472
+ referenceReasons = [lossyReason];
12473
+ index.trust.coverage = "partial";
12474
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, lossyReason])];
12475
+ } else if (tsEntries.length > DEFAULT_MAX_PROGRAM_FILES) {
11849
12476
  const reason = "TypeScript compiler pass skipped: " + tsEntries.length + " TS/JS files exceed the " + DEFAULT_MAX_PROGRAM_FILES + "-file cap; fell back to syntactic matches";
11850
12477
  referenceReasons = [reason];
11851
12478
  index.trust.coverage = "partial";
@@ -11859,15 +12486,18 @@ var locateTool = {
11859
12486
  (entry) => entry.matchedBy === "symbol" && (pattern === null ? entry.detail?.toLowerCase() === needle : entry.detail === rawQuery)
11860
12487
  );
11861
12488
  const target = exact?.path;
11862
- const workerResult = await analysisInWorker({
11863
- task: "ts-refs",
11864
- options: {
11865
- root: workspace.root,
11866
- files,
11867
- symbolName: rawQuery,
11868
- ...target === void 0 ? {} : { targetPath: target }
11869
- }
11870
- });
12489
+ const workerResult = await analysisInWorker(
12490
+ {
12491
+ task: "ts-refs",
12492
+ options: {
12493
+ root: workspace.root,
12494
+ files,
12495
+ symbolName: rawQuery,
12496
+ ...target === void 0 ? {} : { targetPath: target }
12497
+ }
12498
+ },
12499
+ cancellationSignal(context)
12500
+ );
11871
12501
  if (!workerResult.ok) return failure(workerResult.message);
11872
12502
  const result = workerResult.result;
11873
12503
  references = result.references;
@@ -11884,6 +12514,7 @@ var locateTool = {
11884
12514
  (match) => match.line === void 0 ? " - " + match.path + " [" + match.matchedBy + (match.detail === void 0 ? "" : ": " + match.detail) + "]" : " - " + match.path + ":" + match.line + " " + (match.text ?? "")
11885
12515
  ),
11886
12516
  ...references.length === 0 ? [] : ["", "References:", ...references.slice(0, 25).map((reference) => " - " + reference.path + ":" + reference.line + " (" + reference.name + ")")],
12517
+ ...textCapReason === null ? [] : ["Note: " + textCapReason],
11887
12518
  ...referenceReasons.slice(0, 3).map((reason) => "Note: " + reason)
11888
12519
  ];
11889
12520
  return {
@@ -11891,6 +12522,7 @@ var locateTool = {
11891
12522
  structured: {
11892
12523
  total: matches.length + textMatches.length,
11893
12524
  matches: combined,
12525
+ ...security.length === 0 ? {} : { security },
11894
12526
  ...references.length === 0 ? {} : { references },
11895
12527
  trust: index.trust
11896
12528
  }
@@ -11900,7 +12532,7 @@ var locateTool = {
11900
12532
  var readTool = {
11901
12533
  name: "snapshot_read",
11902
12534
  title: "Read a redacted line window",
11903
- 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.",
12535
+ 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.",
11904
12536
  inputSchema: {
11905
12537
  type: "object",
11906
12538
  properties: {
@@ -11923,6 +12555,7 @@ var readTool = {
11923
12555
  returnedLines: { type: "integer" },
11924
12556
  totalLines: { type: "integer" },
11925
12557
  pageable: { type: "boolean" },
12558
+ security: { type: "array", items: { type: "object" } },
11926
12559
  trust: { type: "object" }
11927
12560
  }
11928
12561
  },
@@ -11962,34 +12595,47 @@ var readTool = {
11962
12595
  if (partTooLargeFor(workspace, entry)) {
11963
12596
  return failure(entry.part + " is larger than the " + MAX_PART_READ_BYTES + "-byte read cap; narrow the snapshot or use snapshot_locate.");
11964
12597
  }
11965
- const body = bodyFor(workspace, index, entry);
12598
+ let body = bodyFor(workspace, index, entry);
11966
12599
  if (body === null) {
11967
12600
  return failure(relativePath + " is recorded in " + entry.part + " but its body could not be read. Run snapshot_generate.");
11968
12601
  }
12602
+ const security = [];
12603
+ const hidden = scanHiddenText(body);
12604
+ if (hidden.findings.length > 0) {
12605
+ body = hidden.text;
12606
+ for (const finding of hidden.findings) security.push({ path: entry.relativePath, ...finding });
12607
+ index.trust.reasons = [.../* @__PURE__ */ new Set([...index.trust.reasons, security.length + " hidden instruction or invisible character(s) removed"])];
12608
+ }
11969
12609
  const window = windowText(body, fromLine, lineCount);
11970
- const cappedText = capResultText(window.text);
11971
- const returnedLines = cappedText.text.length === 0 ? 0 : cappedText.text.split("\n").length;
12610
+ const cappedText = capResultText(window.text, MAX_RESULT_BYTES - 1024);
12611
+ const bodyLines = cappedText.text.length === 0 ? 0 : cappedText.text.split("\n").length;
11972
12612
  const header2 = [
11973
12613
  relativePath + " \u2014 " + entry.part + ", " + entry.layer + "/" + entry.kind + ", " + entry.language,
11974
- window.totalLines === 0 ? "This file is empty." : window.pastEnd ? "This file has " + window.totalLines + " line(s); fromLine=" + window.fromLine + " is past its end." : "Lines " + window.fromLine + "\u2013" + (window.fromLine + returnedLines - 1) + " of " + window.totalLines + ".",
12614
+ window.totalLines === 0 ? "This file is empty." : window.pastEnd ? "This file has " + window.totalLines + " line(s); fromLine=" + window.fromLine + " is past its end." : "Lines " + window.fromLine + "\u2013" + (window.fromLine + bodyLines - 1) + " of " + window.totalLines + ".",
11975
12615
  ...index.trust.indexSource === "snapshot" && entry.inclusionMode === "preview" ? ["Bounded preview: the snapshot holds this file's head and tail only."] : [],
11976
12616
  ...cappedText.clipped ? ["Truncated: a line is longer than one result can carry, so this page may end mid-line."] : []
11977
12617
  ];
11978
12618
  const text = [...header2, "", cappedText.text];
11979
- if (window.truncated || cappedText.clipped) {
11980
- text.push("", "Truncated. Call snapshot_read with fromLine=" + (window.fromLine + returnedLines) + " for the rest.");
11981
- }
12619
+ if (!cappedText.clipped && window.truncated) {
12620
+ text.push("", "Truncated. Call snapshot_read with fromLine=" + (window.fromLine + bodyLines) + " for the rest.");
12621
+ }
12622
+ const response = capResponseText(text.join("\n"));
12623
+ const clipped = cappedText.clipped || response.clipped;
12624
+ const headerPrefix = header2.join("\n") + "\n\n";
12625
+ const delivered = response.text.startsWith(headerPrefix) ? response.text.slice(headerPrefix.length) : "";
12626
+ const returnedLines = response.clipped ? delivered.length === 0 ? 0 : delivered.split("\n").length : bodyLines;
11982
12627
  return {
11983
- text: capResponseText(text.join("\n")).text,
12628
+ text: response.text,
11984
12629
  structured: {
11985
12630
  path: entry.relativePath,
11986
12631
  part: entry.part,
11987
12632
  fromLine: window.fromLine,
11988
12633
  returnedLines,
11989
12634
  totalLines: window.totalLines,
11990
- ...!cappedText.clipped && window.truncated ? { nextFromLine: window.fromLine + returnedLines } : {},
11991
- truncated: window.truncated || cappedText.clipped,
11992
- pageable: !cappedText.clipped,
12635
+ ...!clipped && window.truncated ? { nextFromLine: window.fromLine + returnedLines } : {},
12636
+ truncated: window.truncated || clipped,
12637
+ pageable: !clipped,
12638
+ security,
11993
12639
  trust: index.trust
11994
12640
  }
11995
12641
  };
@@ -12005,6 +12651,19 @@ var validateTool = {
12005
12651
  mode: { type: "string", enum: ["status", "drift", "audit"], default: "drift" },
12006
12652
  deep: { type: "boolean", description: "With audit, replay every full body." },
12007
12653
  maxScanBytes: { type: "integer", minimum: 1, description: "Cap the audit text scan." },
12654
+ // `snapshot_generate` accepts every option below, and each one enters `configDigest`.
12655
+ // A validator that did not accept them reported permanent drift for a snapshot the same
12656
+ // server had just written.
12657
+ maxPartBytes: { type: ["string", "number"], description: 'Byte budget per part, for example 307200 or "300k".' },
12658
+ maxPartTokens: { type: ["string", "number"], description: 'Token budget per part, for example 32000 or "32k".' },
12659
+ skeleton: { type: "boolean", description: "Signature-compress JS/TS bodies." },
12660
+ sarif: { type: "boolean", description: "Also write reports/audit.sarif." },
12661
+ stripComments: { type: "boolean", description: "Remove comments from JS/TS bodies." },
12662
+ removeEmptyLines: { type: "boolean", description: "Drop blank lines from bodies." },
12663
+ pack: { type: "string", enum: ["single", "xml", "json"], description: "Write one full-repository file." },
12664
+ includeDiffs: { type: "boolean", description: "Also write reports/diff.md." },
12665
+ includeLogs: { type: "integer", minimum: 1, maximum: 500, description: "Also write reports/log.md." },
12666
+ tokenTree: { type: "boolean", description: "Also write reports/tokens.md." },
12008
12667
  root: ROOT_PROPERTY,
12009
12668
  outDir: OUT_DIR_PROPERTY,
12010
12669
  ...SCOPE_PROPERTIES
@@ -12055,19 +12714,22 @@ var validateTool = {
12055
12714
  };
12056
12715
  }
12057
12716
  if (mode === "audit") {
12058
- const analysis2 = await analysisInWorker({
12059
- task: "health",
12060
- options: {
12061
- snapshotDir: path7__namespace.resolve(workspace.root, workspace.config.outDir),
12062
- repoDir: workspace.root,
12063
- // Only the project's own rules: `auditSnapshot` adds the built-in set itself for the
12064
- // section scan. Passing all 32 here re-scans every raw part under its Markdown path,
12065
- // where an unquoted TypeScript expression looks like an unmasked credential.
12066
- ...(workspace.config.customSecretRules ?? []).length === 0 ? {} : { secretRules: workspace.config.customSecretRules },
12067
- deep: args.deep === true,
12068
- ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {}
12069
- }
12070
- });
12717
+ const analysis2 = await analysisInWorker(
12718
+ {
12719
+ task: "health",
12720
+ options: {
12721
+ snapshotDir: path7__namespace.resolve(workspace.root, workspace.config.outDir),
12722
+ repoDir: workspace.root,
12723
+ // Only the project's own rules: `auditSnapshot` adds the built-in set itself for the
12724
+ // section scan. Passing all 32 here re-scans every raw part under its Markdown path,
12725
+ // where an unquoted TypeScript expression looks like an unmasked credential.
12726
+ ...(workspace.config.customSecretRules ?? []).length === 0 ? {} : { secretRules: workspace.config.customSecretRules },
12727
+ deep: args.deep === true,
12728
+ ...typeof args.maxScanBytes === "number" ? { maxScanBytes: args.maxScanBytes } : {}
12729
+ }
12730
+ },
12731
+ cancellationSignal(context)
12732
+ );
12071
12733
  if (!analysis2.ok) return failure(analysis2.message);
12072
12734
  const report = analysis2.result;
12073
12735
  const failed = report.checks.filter((check) => check.status === "fail");
@@ -12087,12 +12749,15 @@ var validateTool = {
12087
12749
  }
12088
12750
  };
12089
12751
  }
12090
- const analysis = await analysisInWorker({
12091
- task: "validate-workspace",
12092
- root: workspace.root,
12093
- sourceConfig: workspace.sourceConfig,
12094
- cliOptions: workspace.cliOptions
12095
- });
12752
+ const analysis = await analysisInWorker(
12753
+ {
12754
+ task: "validate-workspace",
12755
+ root: workspace.root,
12756
+ sourceConfig: workspace.sourceConfig,
12757
+ cliOptions: workspace.cliOptions
12758
+ },
12759
+ cancellationSignal(context)
12760
+ );
12096
12761
  if (!analysis.ok) return failure(analysis.message);
12097
12762
  const result = analysis.result;
12098
12763
  const lines = [result.valid ? "The snapshot matches the repository." : "The snapshot is out of date."];
@@ -12151,13 +12816,16 @@ var explainTool = {
12151
12816
  if (typeof args.path !== "string") return failure('"path" must be a string.');
12152
12817
  const relativePath = toRelativePath(workspace.root, args.path);
12153
12818
  if (relativePath === null) return failure('"' + args.path + '" is outside ' + workspace.root + ".");
12154
- const analysis = await analysisInWorker({
12155
- task: "explain",
12156
- root: workspace.root,
12157
- sourceConfig: workspace.sourceConfig,
12158
- cliOptions: workspace.cliOptions,
12159
- path: relativePath
12160
- });
12819
+ const analysis = await analysisInWorker(
12820
+ {
12821
+ task: "explain",
12822
+ root: workspace.root,
12823
+ sourceConfig: workspace.sourceConfig,
12824
+ cliOptions: workspace.cliOptions,
12825
+ path: relativePath
12826
+ },
12827
+ cancellationSignal(context)
12828
+ );
12161
12829
  if (!analysis.ok) return failure(analysis.message);
12162
12830
  const result = analysis.result;
12163
12831
  return {
@@ -12381,8 +13049,8 @@ async function runStdioServer(options) {
12381
13049
  let inFlight = 0;
12382
13050
  let inputEnded = false;
12383
13051
  let resolveDone = () => void 0;
12384
- const finished = new Promise((resolve14) => {
12385
- resolveDone = resolve14;
13052
+ const finished = new Promise((resolve15) => {
13053
+ resolveDone = resolve15;
12386
13054
  });
12387
13055
  const finishIfIdle = () => {
12388
13056
  if (inputEnded && inFlight === 0) resolveDone(0);
@@ -12717,14 +13385,51 @@ function createMcpHttpHandler(options) {
12717
13385
  const token = options.token;
12718
13386
  const maxBody = options.maxBodyBytes ?? DEFAULT_MAX_BODY;
12719
13387
  const extraOrigins = options.allowedOrigins ?? [];
12720
- const createMcp = () => createServer({
13388
+ const modernCancellations = /* @__PURE__ */ new Map();
13389
+ const MAX_MODERN_SCOPES = 64;
13390
+ const modernCancellationMap = (scope) => {
13391
+ let map = modernCancellations.get(scope);
13392
+ if (map !== void 0) return map;
13393
+ if (modernCancellations.size >= MAX_MODERN_SCOPES) {
13394
+ const oldest = modernCancellations.keys().next().value;
13395
+ if (oldest !== void 0) modernCancellations.delete(oldest);
13396
+ }
13397
+ map = /* @__PURE__ */ new Map();
13398
+ modernCancellations.set(scope, map);
13399
+ return map;
13400
+ };
13401
+ const createMcp = (cancellations) => createServer({
12721
13402
  cwd: options.cwd,
12722
13403
  log,
12723
- // Each server owns its cancellation map. A map shared by every HTTP and SSE session keyed
12724
- // only by the JSON-RPC id let one client's `id: 1` overwrite another's, and let either one
12725
- // cancel the other's in-flight tool call.
13404
+ // Each non-modern server owns its cancellation map. A map shared by every HTTP and SSE
13405
+ // session keyed only by the JSON-RPC id let one client's `id: 1` overwrite another's, and
13406
+ // let either one cancel the other's in-flight tool call.
13407
+ ...cancellations === void 0 ? {} : { cancellations },
12726
13408
  ...options.noConfig === true ? { noConfig: true } : {}
12727
13409
  });
13410
+ const clientScopeHint = (message) => {
13411
+ const items = Array.isArray(message) ? message : [message];
13412
+ for (const item of items) {
13413
+ if (!isJsonObject(item)) continue;
13414
+ const params = item.params;
13415
+ if (!isJsonObject(params)) continue;
13416
+ const meta = params._meta;
13417
+ if (!isJsonObject(meta)) continue;
13418
+ const info = meta[META_KEYS.clientInfo];
13419
+ if (!isJsonObject(info)) continue;
13420
+ const name = typeof info.name === "string" ? info.name : "";
13421
+ const version = typeof info.version === "string" ? info.version : "";
13422
+ if (name !== "" || version !== "") return "client:" + name + "@" + version;
13423
+ }
13424
+ return "";
13425
+ };
13426
+ const messageMethod = (message) => {
13427
+ const items = Array.isArray(message) ? message : [message];
13428
+ for (const item of items) {
13429
+ if (isJsonObject(item) && typeof item.method === "string") return item.method;
13430
+ }
13431
+ return "";
13432
+ };
12728
13433
  const toolCount = buildTools().length;
12729
13434
  const mcpSessions = /* @__PURE__ */ new Map();
12730
13435
  const socketServers = /* @__PURE__ */ new WeakMap();
@@ -13073,7 +13778,30 @@ function createMcpHttpHandler(options) {
13073
13778
  responseSession = newSessionId();
13074
13779
  rememberSession(responseSession, server, Date.now());
13075
13780
  } else if (modern) {
13076
- server = createMcp();
13781
+ const hint = clientScopeHint(message);
13782
+ const anonymous = "anonymous:" + anonymousKey(request);
13783
+ let cancellations;
13784
+ if (supplied !== "") {
13785
+ cancellations = modernCancellationMap("session:" + supplied);
13786
+ } else if (messageMethod(message) === "notifications/cancelled" && hint === "") {
13787
+ cancellations = /* @__PURE__ */ new Map();
13788
+ for (const [scope, map] of modernCancellations) {
13789
+ if (scope !== anonymous && !scope.startsWith(anonymous + "|")) continue;
13790
+ for (const [id, pending] of map) {
13791
+ let merged = cancellations.get(id);
13792
+ if (merged === void 0) {
13793
+ merged = /* @__PURE__ */ new Set();
13794
+ cancellations.set(id, merged);
13795
+ }
13796
+ for (const cancel of pending) merged.add(cancel);
13797
+ }
13798
+ }
13799
+ } else {
13800
+ cancellations = modernCancellationMap(
13801
+ hint === "" ? anonymous : anonymous + "|" + hint
13802
+ );
13803
+ }
13804
+ server = createMcp(cancellations);
13077
13805
  } else if (supplied !== "") {
13078
13806
  const now = Date.now();
13079
13807
  pruneSessions(now);
@@ -13306,11 +14034,11 @@ async function startHttpTransport(options) {
13306
14034
  }
13307
14035
  send(405, { error: "method not allowed" }, { ...cors, allow: "POST, GET, OPTIONS, DELETE" });
13308
14036
  });
13309
- await new Promise((resolve14, reject) => {
14037
+ await new Promise((resolve15, reject) => {
13310
14038
  httpServer.once("error", reject);
13311
14039
  httpServer.listen(port, host, () => {
13312
14040
  httpServer.removeListener("error", reject);
13313
- resolve14();
14041
+ resolve15();
13314
14042
  });
13315
14043
  });
13316
14044
  const address = httpServer.address();
@@ -13323,8 +14051,8 @@ async function startHttpTransport(options) {
13323
14051
  token,
13324
14052
  close: async () => {
13325
14053
  await mcp.close();
13326
- await new Promise((resolve14) => {
13327
- httpServer.close(() => resolve14());
14054
+ await new Promise((resolve15) => {
14055
+ httpServer.close(() => resolve15());
13328
14056
  httpServer.closeAllConnections();
13329
14057
  });
13330
14058
  }
@@ -13336,16 +14064,16 @@ var SUMMARY_MAX_SOURCE_BYTES2 = SUMMARY_MAX_SOURCE_BYTES;
13336
14064
  var FILE_DERIVATIONS = /* @__PURE__ */ new Map();
13337
14065
  var FILE_DERIVATION_LIMIT_BYTES = 64 * 1024 * 1024;
13338
14066
  var fileDerivationBytes = 0;
13339
- function takeDerivation(path21, relativePath, hash, settings) {
13340
- const key = path21 + "\0" + relativePath;
14067
+ function takeDerivation(path22, relativePath, hash, settings) {
14068
+ const key = path22 + "\0" + relativePath;
13341
14069
  const cached = FILE_DERIVATIONS.get(key);
13342
14070
  if (cached === void 0 || cached.hash !== hash || cached.settings !== settings) return void 0;
13343
14071
  FILE_DERIVATIONS.delete(key);
13344
14072
  FILE_DERIVATIONS.set(key, cached);
13345
14073
  return cached;
13346
14074
  }
13347
- function rememberDerivation(path21, relativePath, hash, settings, derivation) {
13348
- const key = path21 + "\0" + relativePath;
14075
+ function rememberDerivation(path22, relativePath, hash, settings, derivation) {
14076
+ const key = path22 + "\0" + relativePath;
13349
14077
  const bodyBytes = derivation.finalContent === derivation.redacted ? derivation.redacted.length : derivation.redacted.length + derivation.finalContent.length;
13350
14078
  const bytes = bodyBytes * 2 + 512;
13351
14079
  if (bytes > FILE_DERIVATION_LIMIT_BYTES / 4) return;
@@ -13612,6 +14340,11 @@ function verifyInMemory(files, parts, unaccounted) {
13612
14340
  );
13613
14341
  }
13614
14342
  }
14343
+ if (typeof file.includedLines === "number" && file.includedLines > file.lines + 1) {
14344
+ errors.push(
14345
+ `${file.relativePath} records ${file.includedLines} included line(s) for a ${file.lines}-line file.`
14346
+ );
14347
+ }
13615
14348
  }
13616
14349
  const partNames = new Set(parts.map((part) => part.filename));
13617
14350
  for (const file of files) {
@@ -13705,12 +14438,12 @@ var SNAPSHOT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9
13705
14438
  var SHA256_HEX_PATTERN = /^[0-9a-f]{64}$/;
13706
14439
  function readOwnershipMarker(dir) {
13707
14440
  const markerPath = path7__namespace.join(dir, OWNERSHIP_MARKER);
13708
- if (!fs17__namespace.existsSync(markerPath)) {
14441
+ if (!fs18__namespace.existsSync(markerPath)) {
13709
14442
  return { marker: null, problem: "it holds no .codebase-snapshot marker" };
13710
14443
  }
13711
14444
  let raw;
13712
14445
  try {
13713
- raw = fs17__namespace.readFileSync(markerPath, "utf8");
14446
+ raw = fs18__namespace.readFileSync(markerPath, "utf8");
13714
14447
  } catch {
13715
14448
  return { marker: null, problem: "its .codebase-snapshot marker could not be read" };
13716
14449
  }
@@ -13797,7 +14530,7 @@ function canonicalLockTarget(targetPath) {
13797
14530
  const tail = [];
13798
14531
  for (; ; ) {
13799
14532
  try {
13800
- return path7__namespace.join(fs17__namespace.realpathSync(existing), ...tail);
14533
+ return path7__namespace.join(fs18__namespace.realpathSync(existing), ...tail);
13801
14534
  } catch {
13802
14535
  const parent = path7__namespace.dirname(existing);
13803
14536
  if (parent === existing) return resolved;
@@ -13814,13 +14547,13 @@ function releaseAbandonedRun(stagingRoots, runId) {
13814
14547
  for (const root of new Set(stagingRoots)) {
13815
14548
  const lockPath = lockPathFor(root);
13816
14549
  try {
13817
- const payload = JSON.parse(fs17__namespace.readFileSync(lockPath, "utf8"));
13818
- if (payload.runId === runId) fs17__namespace.rmSync(lockPath, { force: true });
14550
+ const payload = JSON.parse(fs18__namespace.readFileSync(lockPath, "utf8"));
14551
+ if (payload.runId === runId) fs18__namespace.rmSync(lockPath, { force: true });
13819
14552
  } catch {
13820
14553
  }
13821
14554
  let entries;
13822
14555
  try {
13823
- entries = fs17__namespace.readdirSync(root);
14556
+ entries = fs18__namespace.readdirSync(root);
13824
14557
  } catch {
13825
14558
  continue;
13826
14559
  }
@@ -13830,7 +14563,7 @@ function releaseAbandonedRun(stagingRoots, runId) {
13830
14563
  const { marker } = readOwnershipMarker(directory);
13831
14564
  if (marker?.runId !== runId) continue;
13832
14565
  try {
13833
- fs17__namespace.rmSync(directory, { recursive: true, force: true });
14566
+ fs18__namespace.rmSync(directory, { recursive: true, force: true });
13834
14567
  } catch {
13835
14568
  }
13836
14569
  }
@@ -13975,7 +14708,7 @@ function generateSnapshot(configInput, options) {
13975
14708
  toolOwnedPaths: [config.outDir, config.tmpDir].map(
13976
14709
  (directory) => path7__namespace.relative(config.cwd, path7__namespace.resolve(config.cwd, directory)).replace(/\\/g, "/")
13977
14710
  ).filter(
13978
- (relative12) => relative12.length > 0 && relative12 !== ".." && !relative12.startsWith(`..${path7__namespace.sep}`) && !relative12.startsWith("../") && !path7__namespace.isAbsolute(relative12)
14711
+ (relative14) => relative14.length > 0 && relative14 !== ".." && !relative14.startsWith(`..${path7__namespace.sep}`) && !relative14.startsWith("../") && !path7__namespace.isAbsolute(relative14)
13979
14712
  ),
13980
14713
  // A staged path can be absent from the working tree while its index blob exists. Discovery
13981
14714
  // lists the working tree, so those paths would never reach the scan at all.
@@ -14035,9 +14768,9 @@ function generateSnapshot(configInput, options) {
14035
14768
  } else {
14036
14769
  let stats;
14037
14770
  try {
14038
- stats = fs17__namespace.statSync(absolutePath);
14771
+ stats = fs18__namespace.statSync(absolutePath);
14039
14772
  if (!stats.isFile()) {
14040
- const nestedRepository = stats.isDirectory() && fs17__namespace.existsSync(path7__namespace.join(absolutePath, ".git"));
14773
+ const nestedRepository = stats.isDirectory() && fs18__namespace.existsSync(path7__namespace.join(absolutePath, ".git"));
14041
14774
  skipped.push(
14042
14775
  nestedRepository ? {
14043
14776
  path: relativePath,
@@ -14073,7 +14806,7 @@ function generateSnapshot(configInput, options) {
14073
14806
  continue;
14074
14807
  }
14075
14808
  try {
14076
- buffer = fs17__namespace.readFileSync(absolutePath);
14809
+ buffer = fs18__namespace.readFileSync(absolutePath);
14077
14810
  } catch (err) {
14078
14811
  const code = err.code;
14079
14812
  skipped.push({
@@ -14190,14 +14923,14 @@ function generateSnapshot(configInput, options) {
14190
14923
  }
14191
14924
  retain(secretFindings, (finding) => finding.path === void 0 || keep.has(finding.path));
14192
14925
  retain(encodingNotes, (note) => keep.has(note.path));
14193
- retain(oversizeSummaryPaths, (path21) => keep.has(path21));
14194
- retain(previewSummaryPaths, (path21) => keep.has(path21));
14926
+ retain(oversizeSummaryPaths, (path22) => keep.has(path22));
14927
+ retain(previewSummaryPaths, (path22) => keep.has(path22));
14195
14928
  retain(fileWarnings, (warning) => keep.has(warning.path));
14196
- for (const path21 of [...monolithBodies.keys()]) {
14197
- if (!keep.has(path21)) monolithBodies.delete(path21);
14929
+ for (const path22 of [...monolithBodies.keys()]) {
14930
+ if (!keep.has(path22)) monolithBodies.delete(path22);
14198
14931
  }
14199
- for (const path21 of [...skippedSummaryImports.keys()]) {
14200
- if (!keep.has(path21)) skippedSummaryImports.delete(path21);
14932
+ for (const path22 of [...skippedSummaryImports.keys()]) {
14933
+ if (!keep.has(path22)) skippedSummaryImports.delete(path22);
14201
14934
  }
14202
14935
  };
14203
14936
  if (changedScope !== null && changedPaths !== null && config.withDependents === true) {
@@ -14458,7 +15191,8 @@ function generateSnapshot(configInput, options) {
14458
15191
  );
14459
15192
  }
14460
15193
  }
14461
- const partitioned = partitionByBudget(files, config, fingerprint);
15194
+ const partitionConfig = { ...config, maxParts: null } ;
15195
+ const partitioned = partitionByBudget(files, partitionConfig, fingerprint);
14462
15196
  const parts = partitioned.parts;
14463
15197
  const truncatedPreviewCount = files.filter((file) => file.isPreviewTruncated).length;
14464
15198
  const incomplete = files.flatMap((file) => {
@@ -14764,7 +15498,7 @@ var COMMAND_OPTION_SCOPE = {
14764
15498
  ],
14765
15499
  // The health audit resolves the config only to find the output directory; --strict decides the
14766
15500
  // exit code, and every other setting would be a promise the command does not keep.
14767
- health: ["cwd", "out-dir", "format", "strict", "all-members", "deep", "mode", "no-update-check", "help", "version"],
15501
+ health: ["cwd", "out-dir", "format", "strict", "all-members", "deep", "no-config", "mode", "no-update-check", "help", "version"],
14768
15502
  // `impact` reads the existing manifest and the working tree. It deliberately takes no
14769
15503
  // generation settings: accepting one would imply the report regenerated or re-scoped the
14770
15504
  // snapshot, which it never does.
@@ -15210,42 +15944,42 @@ function buildAgentContract() {
15210
15944
  type: "string",
15211
15945
  default: null,
15212
15946
  appliesTo: optionAppliesTo("diff"),
15213
- summary: "impact and brief: compare the working tree against this git ref. The set includes committed, staged, unstaged and untracked changes relative to the ref."
15947
+ summary: "impact, guard and brief: compare the working tree against this git ref. The set includes committed, staged, unstaged and untracked changes relative to the ref."
15214
15948
  },
15215
15949
  {
15216
15950
  flag: "--paths",
15217
15951
  type: "string",
15218
15952
  default: null,
15219
15953
  appliesTo: optionAppliesTo("paths"),
15220
- summary: "impact and brief: comma-separated repository-relative paths to treat as the change. Mutually exclusive with --diff."
15954
+ summary: "impact, guard and brief: comma-separated repository-relative paths to treat as the change. Mutually exclusive with --diff."
15221
15955
  },
15222
15956
  {
15223
15957
  flag: "--depth",
15224
15958
  type: "number",
15225
15959
  default: 3,
15226
15960
  appliesTo: optionAppliesTo("depth"),
15227
- summary: "impact and brief: reverse-import hops to follow, 1-8 (default 3)."
15961
+ summary: "impact, guard and brief: reverse-import hops to follow, 1-8 (default 3)."
15228
15962
  },
15229
15963
  {
15230
15964
  flag: "--max-results",
15231
15965
  type: "number",
15232
15966
  default: 200,
15233
15967
  appliesTo: optionAppliesTo("max-results"),
15234
- summary: "impact and brief: maximum affected files, 1-1000 (default 200)."
15968
+ summary: "impact, guard and brief: maximum affected files, 1-1000 (default 200)."
15235
15969
  },
15236
15970
  {
15237
15971
  flag: "--no-cache",
15238
15972
  type: "boolean",
15239
15973
  default: false,
15240
15974
  appliesTo: optionAppliesTo("no-cache"),
15241
- summary: "impact/brief only: bypass the OS live-index summary cache."
15975
+ summary: "impact, guard and brief: bypass the OS live-index summary cache."
15242
15976
  },
15243
15977
  {
15244
15978
  flag: "--no-live",
15245
15979
  type: "boolean",
15246
15980
  default: false,
15247
15981
  appliesTo: optionAppliesTo("no-live"),
15248
- summary: "impact/brief only: require the generated snapshot instead of using the live index."
15982
+ summary: "impact, guard and brief: require the generated snapshot instead of using the live index."
15249
15983
  },
15250
15984
  {
15251
15985
  flag: "--tests-paths",
@@ -15488,7 +16222,7 @@ function buildAgentContract() {
15488
16222
  {
15489
16223
  flag: "--port",
15490
16224
  type: "string",
15491
- default: "4789",
16225
+ default: "4789 (mcp) / 4788 (serve)",
15492
16226
  appliesTo: optionAppliesTo("port"),
15493
16227
  summary: "mcp --http: port to bind. 0 picks an ephemeral port and prints it."
15494
16228
  },
@@ -15674,7 +16408,7 @@ function buildAgentContract() {
15674
16408
  type: "string",
15675
16409
  default: "generate",
15676
16410
  appliesTo: optionAppliesTo("mode"),
15677
- summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill, mcp, health, impact, brief, update, serve. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
16411
+ summary: "Select the command when no command word is given. Values: generate, validate, check, report, impact, guard, brief, init, setup, explain, diff, describe, skill, mcp, health, update, serve. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
15678
16412
  },
15679
16413
  {
15680
16414
  flag: "--cwd",
@@ -15833,7 +16567,7 @@ function buildAgentContract() {
15833
16567
  { key: "maxParts", type: "number | null", default: null, summary: "Experimental: the most parts a snapshot may have. The per-part budget grows to fit, up to the run's own needs; the effective ceiling is recorded in manifest.budgets.maxPartBytes and may exceed maxPartBytes." },
15834
16568
  { key: "attachmentSlots", type: "number", default: 10, summary: "Files the destination accepts in one message (0 = no limit); PROMPT.md plans the delivery to fit. It does not change the payload, and it is not part of the config digest." },
15835
16569
  { key: "discovery", type: '"auto" | "git" | "walk"', default: "auto", summary: "How files are discovered; `walk` scans the tree and reads .gitignore directly when a .git directory cannot be listed." },
15836
- { key: "artifacts", type: "object", default: "all on except monolith", summary: "Per-artifact opt-out." },
16570
+ { key: "artifacts", type: "object", default: "all on except monolith, diff, log and tokenTree", summary: "Per-artifact opt-out." },
15837
16571
  { key: "budgets", type: "object", default: "{ default, byLayer }", summary: "Per-layer byte budgets." },
15838
16572
  { key: "layersMode", type: '"merge" | "replace"', default: "merge", summary: "Whether custom layers extend or replace the preset's." },
15839
16573
  { key: "layers", type: "array", default: "preset layers", summary: "Custom layer rules (glob or RegExp)." },
@@ -16098,8 +16832,11 @@ diff, and the commit, are then yours.
16098
16832
  If the agent runs inside an MCP client, \`npx ${PACKAGE_NAME2}@latest mcp\` serves this repository
16099
16833
  as 7 tools over stdio instead of shelling out. Reads are live by default, so uncommitted edits and
16100
16834
  new files are overlaid in memory; the snapshot is not required. Excluded files and redacted values
16101
- never reach the context. Use \`snapshot_impact\` before editing, \`snapshot_locate\` before
16102
- \`snapshot_read\`, and \`snapshot_validate\` before trusting context from an earlier session.
16835
+ never reach the context. \`snapshot_context\` starts an explicit symbol at its declaration span
16836
+ (or a requested range), removes hidden instructions, and returns a receipt that hashes exactly
16837
+ what it returned; pass \`signReceipt: true\` with \`SNAPSHOT_SIGNING_KEY\` set to sign it. Use
16838
+ \`snapshot_impact\` before editing, \`snapshot_locate\` before \`snapshot_read\`, and
16839
+ \`snapshot_validate\` before trusting context from an earlier session.
16103
16840
  `;
16104
16841
  }
16105
16842
 
@@ -16169,7 +16906,7 @@ async function workspaceFor(context) {
16169
16906
  }
16170
16907
  function readFileIfPresent(file) {
16171
16908
  try {
16172
- return fs17__namespace.readFileSync(file, "utf8");
16909
+ return fs18__namespace.readFileSync(file, "utf8");
16173
16910
  } catch {
16174
16911
  return null;
16175
16912
  }
@@ -16213,7 +16950,7 @@ function buildResourceProvider() {
16213
16950
  const read = readManifest2(workspace);
16214
16951
  if (!read.ok) return resources;
16215
16952
  for (const [uri, report] of REPORT_URIS) {
16216
- const present = reportsDir !== null && fs17__namespace.existsSync(path7__namespace.join(reportsDir, report.file));
16953
+ const present = reportsDir !== null && fs18__namespace.existsSync(path7__namespace.join(reportsDir, report.file));
16217
16954
  if (!present) continue;
16218
16955
  resources.push({
16219
16956
  uri,
@@ -16354,7 +17091,7 @@ function buildResourceProvider() {
16354
17091
  }
16355
17092
  let partBytes;
16356
17093
  try {
16357
- partBytes = fs17__namespace.statSync(partPath).size;
17094
+ partBytes = fs18__namespace.statSync(partPath).size;
16358
17095
  } catch {
16359
17096
  throw new ResourceNotFoundError(uri, part.filename + " is missing from this snapshot.");
16360
17097
  }
@@ -16392,41 +17129,41 @@ function validateArguments(schema, value) {
16392
17129
  }
16393
17130
  return problems;
16394
17131
  }
16395
- function checkValue(path21, schema, value) {
17132
+ function checkValue(path22, schema, value) {
16396
17133
  if (schema.enum && !schema.enum.includes(value)) {
16397
- return [`"${path21}" must be one of: ${schema.enum.join(", ")}`];
17134
+ return [`"${path22}" must be one of: ${schema.enum.join(", ")}`];
16398
17135
  }
16399
17136
  const declared = schema.type === void 0 ? [] : Array.isArray(schema.type) ? schema.type : [schema.type];
16400
17137
  if (declared.length > 0 && !declared.some((type) => matchesType(type, value))) {
16401
17138
  if (declared.length === 1 && declared[0] === "integer" && typeof value !== "number") {
16402
- return [`"${path21}" must be a number`];
17139
+ return [`"${path22}" must be a number`];
16403
17140
  }
16404
17141
  const article = (type) => type === "integer" || type === "object" || type === "array" ? `an ${type}` : `a ${type}`;
16405
- return [`"${path21}" must be ${declared.map(article).join(" or ")}`];
17142
+ return [`"${path22}" must be ${declared.map(article).join(" or ")}`];
16406
17143
  }
16407
17144
  const problems = [];
16408
17145
  if (declared.includes("string") && typeof value === "string") {
16409
17146
  if (schema.minLength !== void 0 && value.length < schema.minLength) {
16410
- problems.push(`"${path21}" must be at least ${schema.minLength} character(s)`);
17147
+ problems.push(`"${path22}" must be at least ${schema.minLength} character(s)`);
16411
17148
  }
16412
17149
  if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
16413
- problems.push(`"${path21}" must be at most ${schema.maxLength} character(s)`);
17150
+ problems.push(`"${path22}" must be at most ${schema.maxLength} character(s)`);
16414
17151
  }
16415
17152
  }
16416
17153
  if ((declared.includes("number") || declared.includes("integer")) && typeof value === "number" && !Number.isNaN(value)) {
16417
17154
  if (declared.includes("integer") && !declared.includes("number") && !Number.isInteger(value)) {
16418
- problems.push(`"${path21}" must be an integer`);
17155
+ problems.push(`"${path22}" must be an integer`);
16419
17156
  }
16420
17157
  if (schema.minimum !== void 0 && value < schema.minimum) {
16421
- problems.push(`"${path21}" must be >= ${schema.minimum}`);
17158
+ problems.push(`"${path22}" must be >= ${schema.minimum}`);
16422
17159
  }
16423
17160
  if (schema.maximum !== void 0 && value > schema.maximum) {
16424
- problems.push(`"${path21}" must be <= ${schema.maximum}`);
17161
+ problems.push(`"${path22}" must be <= ${schema.maximum}`);
16425
17162
  }
16426
17163
  }
16427
17164
  if (declared.includes("array") && Array.isArray(value) && schema.items) {
16428
17165
  value.forEach((item, index) => {
16429
- problems.push(...checkValue(`${path21}[${index}]`, schema.items, item));
17166
+ problems.push(...checkValue(`${path22}[${index}]`, schema.items, item));
16430
17167
  });
16431
17168
  }
16432
17169
  return problems;
@@ -16506,10 +17243,10 @@ function createMcpServer(options) {
16506
17243
  if (method === "notifications/cancelled") {
16507
17244
  const requestId2 = params?.requestId;
16508
17245
  if (typeof requestId2 === "string" || typeof requestId2 === "number") {
16509
- const cancel = cancellations.get(requestId2);
16510
- if (cancel !== void 0) {
17246
+ const pending = cancellations.get(requestId2);
17247
+ if (pending !== void 0) {
16511
17248
  cancellations.delete(requestId2);
16512
- cancel();
17249
+ for (const cancel of pending) cancel();
16513
17250
  }
16514
17251
  }
16515
17252
  }
@@ -16590,7 +17327,13 @@ function createMcpServer(options) {
16590
17327
  ...options.context,
16591
17328
  // Always offered, so a long tool can be stopped whether or not the client asked for progress.
16592
17329
  onCancel: (cancel) => {
16593
- cancellations.set(id, cancel);
17330
+ registeredCancel = cancel;
17331
+ let pending = cancellations.get(id);
17332
+ if (pending === void 0) {
17333
+ pending = /* @__PURE__ */ new Set();
17334
+ cancellations.set(id, pending);
17335
+ }
17336
+ pending.add(cancel);
16594
17337
  },
16595
17338
  ...progressToken === void 0 || options.notify === void 0 ? {} : {
16596
17339
  notify: (event) => {
@@ -16605,6 +17348,7 @@ function createMcpServer(options) {
16605
17348
  }
16606
17349
  };
16607
17350
  let outcome;
17351
+ let registeredCancel;
16608
17352
  try {
16609
17353
  outcome = await tool.handler(args, callContext);
16610
17354
  } catch (error) {
@@ -16616,7 +17360,13 @@ function createMcpServer(options) {
16616
17360
  modern
16617
17361
  );
16618
17362
  } finally {
16619
- cancellations.delete(id);
17363
+ if (registeredCancel !== void 0) {
17364
+ const pending = cancellations.get(id);
17365
+ if (pending !== void 0) {
17366
+ pending.delete(registeredCancel);
17367
+ if (pending.size === 0) cancellations.delete(id);
17368
+ }
17369
+ }
16620
17370
  }
16621
17371
  return ok(
16622
17372
  id,